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

1.17      albertel    1: # The LearningOnline Network with CAPA
1.13      albertel    2: # The LON-CAPA Grading handler
1.17      albertel    3: #
1.596.2.3! raeburn     4: # $Id: grades.pm,v 1.596.2.2 2010/12/20 04:23:43 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.582     raeburn   100:     my ($symb,$errorref) = @_;
1.439     albertel  101: 
                    102:     my $navmap   = Apache::lonnavmaps::navmap->new();
1.582     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.582     raeburn   153:     my ($symb,$response_error) = @_;
1.377     albertel  154: 
                    155:     my $navmap = Apache::lonnavmaps::navmap->new();
1.582     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);
1.593     raeburn   163:     unless (ref($res)) {
                    164:         $$response_error = 1;
                    165:         return;
                    166:     }
1.377     albertel  167:     my $partlist = $res->parts();
1.392     albertel  168:     my %vPart = 
                    169: 	map { $_ => 1 } (&Apache::loncommon::get_env_multiple('form.vPart'));
1.377     albertel  170:     my (%response_types,%handgrade);
                    171:     foreach my $part (@{ $partlist }) {
1.392     albertel  172: 	next if (%vPart && !exists($vPart{$part}));
                    173: 
1.377     albertel  174: 	my @types = $res->responseType($part);
                    175: 	my @ids = $res->responseIds($part);
                    176: 	for (my $i=0; $i < scalar(@ids); $i++) {
                    177: 	    $response_types{$part}{$ids[$i]} = $types[$i];
                    178: 	    $handgrade{$part.'_'.$ids[$i]} = 
                    179: 		&Apache::lonnet::EXT('resource.'.$part.'_'.$ids[$i].
                    180: 				     '.handgrade',$symb);
1.41      ng        181: 	}
                    182:     }
1.377     albertel  183:     return ($partlist,\%handgrade,\%response_types);
1.39      ng        184: }
                    185: 
1.375     albertel  186: sub flatten_responseType {
                    187:     my ($responseType) = @_;
                    188:     my @part_response_id =
                    189: 	map { 
                    190: 	    my $part = $_;
                    191: 	    map {
                    192: 		[$part,$_]
                    193: 		} sort(keys(%{ $responseType->{$part} }));
                    194: 	} sort(keys(%$responseType));
                    195:     return @part_response_id;
                    196: }
                    197: 
1.207     albertel  198: sub get_display_part {
1.324     albertel  199:     my ($partID,$symb)=@_;
1.207     albertel  200:     my $display=&Apache::lonnet::EXT('resource.'.$partID.'.display',$symb);
                    201:     if (defined($display) and $display ne '') {
1.577     bisitz    202:         $display.= ' (<span class="LC_internal_info">'
                    203:                   .&mt('Part ID: [_1]',$partID).'</span>)';
1.207     albertel  204:     } else {
                    205: 	$display=$partID;
                    206:     }
                    207:     return $display;
                    208: }
1.269     raeburn   209: 
1.118     ng        210: #--- Show resource title
                    211: #--- and parts and response type
                    212: sub showResourceInfo {
1.582     raeburn   213:     my ($symb,$probTitle,$checkboxes,$res_error) = @_;
1.398     albertel  214:     my $result = '<h3>'.&mt('Current Resource').': '.$probTitle.'</h3>'."\n";
1.582     raeburn   215:     my ($partlist,$handgrade,$responseType) = &response_type($symb,$res_error);
                    216:     if (ref($res_error)) {
                    217:         if ($$res_error) {
                    218:             return;
                    219:         }
                    220:     }
1.584     bisitz    221:     $result.=&Apache::loncommon::start_data_table()
                    222:             .&Apache::loncommon::start_data_table_header_row();
                    223:     if ($checkboxes) {
                    224:         $result.='<th>&nbsp;</th>';
                    225:     }
                    226:     $result.='<th>'.&mt('Problem Part').'</th>'
                    227:             .'<th>'.&mt('Res. ID').'</th>'
                    228:             .'<th>'.&mt('Type').'</th>'
                    229:             .&Apache::loncommon::end_data_table_header_row();
1.126     ng        230:     my %resptype = ();
1.122     ng        231:     my $hdgrade='no';
1.154     albertel  232:     my %partsseen;
1.524     raeburn   233:     foreach my $partID (sort(keys(%$responseType))) {
1.584     bisitz    234:         foreach my $resID (sort(keys(%{ $responseType->{$partID} }))) {
                    235:             my $handgrade=$$handgrade{$partID.'_'.$resID};
                    236:             my $responsetype = $responseType->{$partID}->{$resID};
                    237:             $hdgrade = $handgrade if ($handgrade eq 'yes');
                    238:             $result.=&Apache::loncommon::start_data_table_row();
                    239:             if ($checkboxes) {
                    240:                 if (exists($partsseen{$partID})) {
                    241:                     $result.="<td>&nbsp;</td>";
                    242:                 } else {
                    243:                     $result.="<td><input type='checkbox' name='vPart' value='$partID' checked='checked' /></td>";
                    244:                 }
                    245:                 $partsseen{$partID}=1;
                    246:             }
                    247:             my $display_part=&get_display_part($partID,$symb);
                    248:             $result.='<td>'.$display_part.'</td>'
                    249:                     .'<td>'.'<span class="LC_internal_info">'.$resID.'</span></td>'
                    250:                     .'<td>'.&mt($responsetype).'</td>'
                    251: #                   .'<td>'.&mt('<b>Handgrade: </b>[_1]',$handgrade).'</td>'
                    252:                     .&Apache::loncommon::end_data_table_row();
                    253:         }
1.118     ng        254:     }
1.584     bisitz    255:     $result.=&Apache::loncommon::end_data_table();
1.147     albertel  256:     return $result,$responseType,$hdgrade,$partlist,$handgrade;
1.118     ng        257: }
                    258: 
1.434     albertel  259: sub reset_caches {
                    260:     &reset_analyze_cache();
                    261:     &reset_perm();
                    262: }
                    263: 
                    264: {
                    265:     my %analyze_cache;
1.557     raeburn   266:     my %analyze_cache_formkeys;
1.148     albertel  267: 
1.434     albertel  268:     sub reset_analyze_cache {
                    269: 	undef(%analyze_cache);
1.557     raeburn   270:         undef(%analyze_cache_formkeys);
1.434     albertel  271:     }
                    272: 
                    273:     sub get_analyze {
1.596.2.2  raeburn   274: 	my ($symb,$uname,$udom,$no_increment,$add_to_hash,$type,$trial,$rndseed)=@_;
1.434     albertel  275: 	my $key = "$symb\0$uname\0$udom";
1.596.2.2  raeburn   276:         if ($type eq 'randomizetry') {
                    277:             if ($trial ne '') {
                    278:                 $key .= "\0".$trial;
                    279:             }
                    280:         }
1.557     raeburn   281: 	if (exists($analyze_cache{$key})) {
                    282:             my $getupdate = 0;
                    283:             if (ref($add_to_hash) eq 'HASH') {
                    284:                 foreach my $item (keys(%{$add_to_hash})) {
                    285:                     if (ref($analyze_cache_formkeys{$key}) eq 'HASH') {
                    286:                         if (!exists($analyze_cache_formkeys{$key}{$item})) {
                    287:                             $getupdate = 1;
                    288:                             last;
                    289:                         }
                    290:                     } else {
                    291:                         $getupdate = 1;
                    292:                     }
                    293:                 }
                    294:             }
                    295:             if (!$getupdate) {
                    296:                 return $analyze_cache{$key};
                    297:             }
                    298:         }
1.434     albertel  299: 
                    300: 	my (undef,undef,$url)=&Apache::lonnet::decode_symb($symb);
                    301: 	$url=&Apache::lonnet::clutter($url);
1.557     raeburn   302:         my %form = ('grade_target'      => 'analyze',
                    303:                     'grade_domain'      => $udom,
                    304:                     'grade_symb'        => $symb,
                    305:                     'grade_courseid'    =>  $env{'request.course.id'},
                    306:                     'grade_username'    => $uname,
                    307:                     'grade_noincrement' => $no_increment);
1.596.2.2  raeburn   308:         if ($type eq 'randomizetry') {
                    309:             $form{'grade_questiontype'} = $type;
                    310:             if ($rndseed ne '') {
                    311:                 $form{'grade_rndseed'} = $rndseed;
                    312:             }
                    313:         }
1.557     raeburn   314:         if (ref($add_to_hash)) {
                    315:             %form = (%form,%{$add_to_hash});
1.596.2.2  raeburn   316:         }
1.557     raeburn   317: 	my $subresult=&ssi_with_retries($url, $ssi_retries,%form);
1.434     albertel  318: 	(undef,$subresult)=split(/_HASH_REF__/,$subresult,2);
                    319: 	my %analyze=&Apache::lonnet::str2hash($subresult);
1.557     raeburn   320:         if (ref($add_to_hash) eq 'HASH') {
                    321:             $analyze_cache_formkeys{$key} = $add_to_hash;
                    322:         } else {
                    323:             $analyze_cache_formkeys{$key} = {};
                    324:         }
1.434     albertel  325: 	return $analyze_cache{$key} = \%analyze;
                    326:     }
                    327: 
                    328:     sub get_order {
1.596.2.2  raeburn   329: 	my ($partid,$respid,$symb,$uname,$udom,$no_increment,$type,$trial,$rndseed)=@_;
                    330: 	my $analyze = &get_analyze($symb,$uname,$udom,$no_increment,undef,$type,$trial,$rndseed);
1.434     albertel  331: 	return $analyze->{"$partid.$respid.shown"};
                    332:     }
                    333: 
                    334:     sub get_radiobutton_correct_foil {
1.596.2.2  raeburn   335: 	my ($partid,$respid,$symb,$uname,$udom,$type,$trial,$rndseed)=@_;
                    336: 	my $analyze = &get_analyze($symb,$uname,$udom,undef,undef,$type,$trial,$rndseed);
                    337:         my $foils = &get_order($partid,$respid,$symb,$uname,$udom,undef,$type,$trial,$rndseed);
1.555     raeburn   338:         if (ref($foils) eq 'ARRAY') {
                    339: 	    foreach my $foil (@{$foils}) {
                    340: 	        if ($analyze->{"$partid.$respid.foil.value.$foil"} eq 'true') {
                    341: 		    return $foil;
                    342: 	        }
1.434     albertel  343: 	    }
                    344: 	}
                    345:     }
1.554     raeburn   346: 
                    347:     sub scantron_partids_tograde {
1.557     raeburn   348:         my ($resource,$cid,$uname,$udom,$check_for_randomlist) = @_;
1.554     raeburn   349:         my (%analysis,@parts);
                    350:         if (ref($resource)) {
                    351:             my $symb = $resource->symb();
1.557     raeburn   352:             my $add_to_form;
                    353:             if ($check_for_randomlist) {
                    354:                 $add_to_form = { 'check_parts_withrandomlist' => 1,};
                    355:             }
                    356:             my $analyze = &get_analyze($symb,$uname,$udom,undef,$add_to_form);
1.554     raeburn   357:             if (ref($analyze) eq 'HASH') {
                    358:                 %analysis = %{$analyze};
                    359:             }
                    360:             if (ref($analysis{'parts'}) eq 'ARRAY') {
                    361:                 foreach my $part (@{$analysis{'parts'}}) {
                    362:                     my ($id,$respid) = split(/\./,$part);
                    363:                     if (!&Apache::loncommon::check_if_partid_hidden($id,$symb,$udom,$uname)) {
                    364:                         push(@parts,$part);
                    365:                     }
                    366:                 }
                    367:             }
                    368:         }
                    369:         return (\%analysis,\@parts);
                    370:     }
                    371: 
1.148     albertel  372: }
1.434     albertel  373: 
1.118     ng        374: #--- Clean response type for display
1.335     albertel  375: #--- Currently filters option/rank/radiobutton/match/essay/Task
                    376: #        response types only.
1.118     ng        377: sub cleanRecord {
1.336     albertel  378:     my ($answer,$response,$symb,$partid,$respid,$record,$order,$version,
1.596.2.2  raeburn   379: 	$uname,$udom,$type,$trial,$rndseed) = @_;
1.398     albertel  380:     my $grayFont = '<span class="LC_internal_info">';
1.148     albertel  381:     if ($response =~ /^(option|rank)$/) {
                    382: 	my %answer=&Apache::lonnet::str2hash($answer);
                    383: 	my %grading=&Apache::lonnet::str2hash($record->{$version."resource.$partid.$respid.submissiongrading"});
                    384: 	my ($toprow,$bottomrow);
                    385: 	foreach my $foil (@$order) {
                    386: 	    if ($grading{$foil} == 1) {
                    387: 		$toprow.='<td><b>'.$answer{$foil}.'&nbsp;</b></td>';
                    388: 	    } else {
                    389: 		$toprow.='<td><i>'.$answer{$foil}.'&nbsp;</i></td>';
                    390: 	    }
1.398     albertel  391: 	    $bottomrow.='<td>'.$grayFont.$foil.'</span>&nbsp;</td>';
1.148     albertel  392: 	}
                    393: 	return '<blockquote><table border="1">'.
1.466     albertel  394: 	    '<tr valign="top"><td>'.&mt('Answer').'</td>'.$toprow.'</tr>'.
                    395: 	    '<tr valign="top"><td>'.$grayFont.&mt('Option ID').'</span></td>'.
1.596.2.1  raeburn   396: 	    $bottomrow.'</tr></table></blockquote>';
1.148     albertel  397:     } elsif ($response eq 'match') {
                    398: 	my %answer=&Apache::lonnet::str2hash($answer);
                    399: 	my %grading=&Apache::lonnet::str2hash($record->{$version."resource.$partid.$respid.submissiongrading"});
                    400: 	my @items=&Apache::lonnet::str2array($record->{$version."resource.$partid.$respid.submissionitems"});
                    401: 	my ($toprow,$middlerow,$bottomrow);
                    402: 	foreach my $foil (@$order) {
                    403: 	    my $item=shift(@items);
                    404: 	    if ($grading{$foil} == 1) {
                    405: 		$toprow.='<td><b>'.$item.'&nbsp;</b></td>';
1.398     albertel  406: 		$middlerow.='<td><b>'.$grayFont.$answer{$foil}.'&nbsp;</span></b></td>';
1.148     albertel  407: 	    } else {
                    408: 		$toprow.='<td><i>'.$item.'&nbsp;</i></td>';
1.398     albertel  409: 		$middlerow.='<td><i>'.$grayFont.$answer{$foil}.'&nbsp;</span></i></td>';
1.148     albertel  410: 	    }
1.398     albertel  411: 	    $bottomrow.='<td>'.$grayFont.$foil.'</span>&nbsp;</td>';
1.118     ng        412: 	}
1.126     ng        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('Item ID').'</span></td>'.
1.148     albertel  416: 	    $middlerow.'</tr>'.
1.466     albertel  417: 	    '<tr valign="top"><td>'.$grayFont.&mt('Option ID').'</span></td>'.
1.148     albertel  418: 	    $bottomrow.'</tr>'.'</table></blockquote>';
                    419:     } elsif ($response eq 'radiobutton') {
                    420: 	my %answer=&Apache::lonnet::str2hash($answer);
                    421: 	my ($toprow,$bottomrow);
1.434     albertel  422: 	my $correct = 
1.596.2.2  raeburn   423: 	    &get_radiobutton_correct_foil($partid,$respid,$symb,$uname,$udom,$type,$trial,$rndseed);
1.434     albertel  424: 	foreach my $foil (@$order) {
1.148     albertel  425: 	    if (exists($answer{$foil})) {
1.434     albertel  426: 		if ($foil eq $correct) {
1.466     albertel  427: 		    $toprow.='<td><b>'.&mt('true').'</b></td>';
1.148     albertel  428: 		} else {
1.466     albertel  429: 		    $toprow.='<td><i>'.&mt('true').'</i></td>';
1.148     albertel  430: 		}
                    431: 	    } else {
1.466     albertel  432: 		$toprow.='<td>'.&mt('false').'</td>';
1.148     albertel  433: 	    }
1.398     albertel  434: 	    $bottomrow.='<td>'.$grayFont.$foil.'</span>&nbsp;</td>';
1.148     albertel  435: 	}
                    436: 	return '<blockquote><table border="1">'.
1.466     albertel  437: 	    '<tr valign="top"><td>'.&mt('Answer').'</td>'.$toprow.'</tr>'.
                    438: 	    '<tr valign="top"><td>'.$grayFont.&mt('Option ID').'</span></td>'.
1.148     albertel  439: 	    $grayFont.$bottomrow.'</tr>'.'</table></blockquote>';
                    440:     } elsif ($response eq 'essay') {
1.257     albertel  441: 	if (! exists ($env{'form.'.$symb})) {
1.122     ng        442: 	    my (%keyhash) = &Apache::lonnet::dump('nohist_handgrade',
1.257     albertel  443: 						  $env{'course.'.$env{'request.course.id'}.'.domain'},
                    444: 						  $env{'course.'.$env{'request.course.id'}.'.num'});
1.122     ng        445: 
1.257     albertel  446: 	    my $loginuser = $env{'user.name'}.':'.$env{'user.domain'};
                    447: 	    $env{'form.keywords'} = $keyhash{$symb.'_keywords'} ne '' ? $keyhash{$symb.'_keywords'} : '';
                    448: 	    $env{'form.kwclr'}    = $keyhash{$loginuser.'_kwclr'} ne '' ? $keyhash{$loginuser.'_kwclr'} : 'red';
                    449: 	    $env{'form.kwsize'}   = $keyhash{$loginuser.'_kwsize'} ne '' ? $keyhash{$loginuser.'_kwsize'} : '0';
                    450: 	    $env{'form.kwstyle'}  = $keyhash{$loginuser.'_kwstyle'} ne '' ? $keyhash{$loginuser.'_kwstyle'} : '';
                    451: 	    $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        452: 	}
1.166     albertel  453: 	$answer =~ s-\n-<br />-g;
                    454: 	return '<br /><br /><blockquote><tt>'.&keywords_highlight($answer).'</tt></blockquote>';
1.268     albertel  455:     } elsif ( $response eq 'organic') {
                    456: 	my $result='Smile representation: "<tt>'.$answer.'</tt>"';
                    457: 	my $jme=$record->{$version."resource.$partid.$respid.molecule"};
                    458: 	$result.=&Apache::chemresponse::jme_img($jme,$answer,400);
                    459: 	return $result;
1.335     albertel  460:     } elsif ( $response eq 'Task') {
                    461: 	if ( $answer eq 'SUBMITTED') {
                    462: 	    my $files = $record->{$version."resource.$respid.$partid.bridgetask.portfiles"};
1.336     albertel  463: 	    my $result = &Apache::bridgetask::file_list($files,$uname,$udom);
1.335     albertel  464: 	    return $result;
                    465: 	} elsif ( grep(/^\Q$version\E.*?\.instance$/, keys(%{$record})) ) {
                    466: 	    my @matches = grep(/^\Q$version\E.*?\.instance$/,
                    467: 			       keys(%{$record}));
                    468: 	    return join('<br />',($version,@matches));
                    469: 			       
                    470: 			       
                    471: 	} else {
                    472: 	    my $result =
                    473: 		'<p>'
                    474: 		.&mt('Overall result: [_1]',
                    475: 		     $record->{$version."resource.$respid.$partid.status"})
                    476: 		.'</p>';
                    477: 	    
                    478: 	    $result .= '<ul>';
                    479: 	    my @grade = grep(/^\Q${version}resource.$respid.$partid.\E[^.]*[.]status$/,
                    480: 			     keys(%{$record}));
                    481: 	    foreach my $grade (sort(@grade)) {
                    482: 		my ($dim) = ($grade =~/[.]([^.]+)[.]status$/);
                    483: 		$result.= '<li>'.&mt("Dimension: [_1], status [_2] ",
                    484: 				     $dim, $record->{$grade}).
                    485: 			  '</li>';
                    486: 	    }
                    487: 	    $result.='</ul>';
                    488: 	    return $result;
                    489: 	}
1.440     albertel  490:     } elsif ( $response =~ m/(?:numerical|formula)/) {
                    491: 	$answer = 
                    492: 	    &Apache::loncommon::format_previous_attempt_value('submission',
                    493: 							      $answer);
1.122     ng        494:     }
1.118     ng        495:     return $answer;
                    496: }
                    497: 
                    498: #-- A couple of common js functions
                    499: sub commonJSfunctions {
                    500:     my $request = shift;
                    501:     $request->print(<<COMMONJSFUNCTIONS);
                    502: <script type="text/javascript" language="javascript">
                    503:     function radioSelection(radioButton) {
                    504: 	var selection=null;
                    505: 	if (radioButton.length > 1) {
                    506: 	    for (var i=0; i<radioButton.length; i++) {
                    507: 		if (radioButton[i].checked) {
                    508: 		    return radioButton[i].value;
                    509: 		}
                    510: 	    }
                    511: 	} else {
                    512: 	    if (radioButton.checked) return radioButton.value;
                    513: 	}
                    514: 	return selection;
                    515:     }
                    516: 
                    517:     function pullDownSelection(selectOne) {
                    518: 	var selection="";
                    519: 	if (selectOne.length > 1) {
                    520: 	    for (var i=0; i<selectOne.length; i++) {
                    521: 		if (selectOne[i].selected) {
                    522: 		    return selectOne[i].value;
                    523: 		}
                    524: 	    }
                    525: 	} else {
1.138     albertel  526:             // only one value it must be the selected one
                    527: 	    return selectOne.value;
1.118     ng        528: 	}
                    529:     }
                    530: </script>
                    531: COMMONJSFUNCTIONS
                    532: }
                    533: 
1.44      ng        534: #--- Dumps the class list with usernames,list of sections,
                    535: #--- section, ids and fullnames for each user.
                    536: sub getclasslist {
1.449     banghart  537:     my ($getsec,$filterlist,$getgroup) = @_;
1.291     albertel  538:     my @getsec;
1.450     banghart  539:     my @getgroup;
1.442     banghart  540:     my $stu_status = join(':',&Apache::loncommon::get_env_multiple('form.Status'));
1.291     albertel  541:     if (!ref($getsec)) {
                    542: 	if ($getsec ne '' && $getsec ne 'all') {
                    543: 	    @getsec=($getsec);
                    544: 	}
                    545:     } else {
                    546: 	@getsec=@{$getsec};
                    547:     }
                    548:     if (grep(/^all$/,@getsec)) { undef(@getsec); }
1.450     banghart  549:     if (!ref($getgroup)) {
                    550: 	if ($getgroup ne '' && $getgroup ne 'all') {
                    551: 	    @getgroup=($getgroup);
                    552: 	}
                    553:     } else {
                    554: 	@getgroup=@{$getgroup};
                    555:     }
                    556:     if (grep(/^all$/,@getgroup)) { undef(@getgroup); }
1.291     albertel  557: 
1.449     banghart  558:     my ($classlist,$keylist)=&Apache::loncoursedata::get_classlist();
1.49      albertel  559:     # Bail out if we were unable to get the classlist
1.56      matthew   560:     return if (! defined($classlist));
1.449     banghart  561:     &Apache::loncoursedata::get_group_memberships($classlist,$keylist);
1.56      matthew   562:     #
                    563:     my %sections;
                    564:     my %fullnames;
1.205     matthew   565:     foreach my $student (keys(%$classlist)) {
                    566:         my $end      = 
                    567:             $classlist->{$student}->[&Apache::loncoursedata::CL_END()];
                    568:         my $start    = 
                    569:             $classlist->{$student}->[&Apache::loncoursedata::CL_START()];
                    570:         my $id       = 
                    571:             $classlist->{$student}->[&Apache::loncoursedata::CL_ID()];
                    572:         my $section  = 
                    573:             $classlist->{$student}->[&Apache::loncoursedata::CL_SECTION()];
                    574:         my $fullname = 
                    575:             $classlist->{$student}->[&Apache::loncoursedata::CL_FULLNAME()];
                    576:         my $status   = 
                    577:             $classlist->{$student}->[&Apache::loncoursedata::CL_STATUS()];
1.449     banghart  578:         my $group   = 
                    579:             $classlist->{$student}->[&Apache::loncoursedata::CL_GROUP()];
1.76      ng        580: 	# filter students according to status selected
1.442     banghart  581: 	if ($filterlist && (!($stu_status =~ /Any/))) {
                    582: 	    if (!($stu_status =~ $status)) {
1.450     banghart  583: 		delete($classlist->{$student});
1.76      ng        584: 		next;
                    585: 	    }
                    586: 	}
1.450     banghart  587: 	# filter students according to groups selected
1.453     banghart  588: 	my @stu_groups = split(/,/,$group);
1.450     banghart  589: 	if (@getgroup) {
                    590: 	    my $exclude = 1;
1.454     banghart  591: 	    foreach my $grp (@getgroup) {
                    592: 	        foreach my $stu_group (@stu_groups) {
1.453     banghart  593: 	            if ($stu_group eq $grp) {
                    594: 	                $exclude = 0;
                    595:     	            } 
1.450     banghart  596: 	        }
1.453     banghart  597:     	        if (($grp eq 'none') && !$group) {
                    598:         	        $exclude = 0;
                    599:         	}
1.450     banghart  600: 	    }
                    601: 	    if ($exclude) {
                    602: 	        delete($classlist->{$student});
                    603: 	    }
                    604: 	}
1.205     matthew   605: 	$section = ($section ne '' ? $section : 'none');
1.106     albertel  606: 	if (&canview($section)) {
1.291     albertel  607: 	    if (!@getsec || grep(/^\Q$section\E$/,@getsec)) {
1.103     albertel  608: 		$sections{$section}++;
1.450     banghart  609: 		if ($classlist->{$student}) {
                    610: 		    $fullnames{$student}=$fullname;
                    611: 		}
1.103     albertel  612: 	    } else {
1.205     matthew   613: 		delete($classlist->{$student});
1.103     albertel  614: 	    }
                    615: 	} else {
1.205     matthew   616: 	    delete($classlist->{$student});
1.103     albertel  617: 	}
1.44      ng        618:     }
                    619:     my %seen = ();
1.56      matthew   620:     my @sections = sort(keys(%sections));
                    621:     return ($classlist,\@sections,\%fullnames);
1.44      ng        622: }
                    623: 
1.103     albertel  624: sub canmodify {
                    625:     my ($sec)=@_;
                    626:     if ($perm{'mgr'}) {
                    627: 	if (!defined($perm{'mgr_section'})) {
                    628: 	    # can modify whole class
                    629: 	    return 1;
                    630: 	} else {
                    631: 	    if ($sec eq $perm{'mgr_section'}) {
                    632: 		#can modify the requested section
                    633: 		return 1;
                    634: 	    } else {
                    635: 		# can't modify the request section
                    636: 		return 0;
                    637: 	    }
                    638: 	}
                    639:     }
                    640:     #can't modify
                    641:     return 0;
                    642: }
                    643: 
                    644: sub canview {
                    645:     my ($sec)=@_;
                    646:     if ($perm{'vgr'}) {
                    647: 	if (!defined($perm{'vgr_section'})) {
                    648: 	    # can modify whole class
                    649: 	    return 1;
                    650: 	} else {
                    651: 	    if ($sec eq $perm{'vgr_section'}) {
                    652: 		#can modify the requested section
                    653: 		return 1;
                    654: 	    } else {
                    655: 		# can't modify the request section
                    656: 		return 0;
                    657: 	    }
                    658: 	}
                    659:     }
                    660:     #can't modify
                    661:     return 0;
                    662: }
                    663: 
1.44      ng        664: #--- Retrieve the grade status of a student for all the parts
                    665: sub student_gradeStatus {
1.324     albertel  666:     my ($symb,$udom,$uname,$partlist) = @_;
1.257     albertel  667:     my %record     = &Apache::lonnet::restore($symb,$env{'request.course.id'},$udom,$uname);
1.44      ng        668:     my %partstatus = ();
                    669:     foreach (@$partlist) {
1.128     ng        670: 	my ($status,undef)   = split(/_/,$record{"resource.$_.solved"},2);
1.44      ng        671: 	$status              = 'nothing' if ($status eq '');
                    672: 	$partstatus{$_}      = $status;
                    673: 	my $subkey           = "resource.$_.submitted_by";
                    674: 	$partstatus{$subkey} = $record{$subkey} if ($record{$subkey} ne '');
                    675:     }
                    676:     return %partstatus;
                    677: }
                    678: 
1.45      ng        679: # hidden form and javascript that calls the form
                    680: # Use by verifyscript and viewgrades
                    681: # Shows a student's view of problem and submission
                    682: sub jscriptNform {
1.324     albertel  683:     my ($symb) = @_;
1.442     banghart  684:     my $stu_status = join(':',&Apache::loncommon::get_env_multiple('form.Status'));
1.45      ng        685:     my $jscript='<script type="text/javascript" language="javascript">'."\n".
                    686: 	'    function viewOneStudent(user,domain) {'."\n".
                    687: 	'	document.onestudent.student.value = user;'."\n".
                    688: 	'	document.onestudent.userdom.value = domain;'."\n".
                    689: 	'	document.onestudent.submit();'."\n".
                    690: 	'    }'."\n".
                    691: 	'</script>'."\n";
                    692:     $jscript.= '<form action="/adm/grades" method="post" name="onestudent">'."\n".
1.418     albertel  693: 	'<input type="hidden" name="symb"    value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
1.257     albertel  694: 	'<input type="hidden" name="saveState" value="'.$env{'form.saveState'}.'" />'."\n".
                    695: 	'<input type="hidden" name="probTitle" value="'.$env{'form.probTitle'}.'" />'."\n".
1.442     banghart  696: 	'<input type="hidden" name="Status"  value="'.$stu_status.'" />'."\n".
1.45      ng        697: 	'<input type="hidden" name="command" value="submission" />'."\n".
                    698: 	'<input type="hidden" name="student" value="" />'."\n".
                    699: 	'<input type="hidden" name="userdom" value="" />'."\n".
                    700: 	'</form>'."\n";
                    701:     return $jscript;
                    702: }
1.39      ng        703: 
1.447     foxr      704: 
                    705: 
1.315     bowersj2  706: # Given the score (as a number [0-1] and the weight) what is the final
                    707: # point value? This function will round to the nearest tenth, third,
                    708: # or quarter if one of those is within the tolerance of .00001.
1.316     albertel  709: sub compute_points {
1.315     bowersj2  710:     my ($score, $weight) = @_;
                    711:     
                    712:     my $tolerance = .00001;
                    713:     my $points = $score * $weight;
                    714: 
                    715:     # Check for nearness to 1/x.
                    716:     my $check_for_nearness = sub {
                    717:         my ($factor) = @_;
                    718:         my $num = ($points * $factor) + $tolerance;
                    719:         my $floored_num = floor($num);
1.316     albertel  720:         if ($num - $floored_num < 2 * $tolerance * $factor) {
1.315     bowersj2  721:             return $floored_num / $factor;
                    722:         }
                    723:         return $points;
                    724:     };
                    725: 
                    726:     $points = $check_for_nearness->(10);
                    727:     $points = $check_for_nearness->(3);
                    728:     $points = $check_for_nearness->(4);
                    729:     
                    730:     return $points;
                    731: }
                    732: 
1.44      ng        733: #------------------ End of general use routines --------------------
1.87      www       734: 
                    735: #
                    736: # Find most similar essay
                    737: #
                    738: 
                    739: sub most_similar {
1.426     albertel  740:     my ($uname,$udom,$uessay,$old_essays)=@_;
1.87      www       741: 
                    742: # ignore spaces and punctuation
                    743: 
                    744:     $uessay=~s/\W+/ /gs;
                    745: 
1.282     www       746: # ignore empty submissions (occuring when only files are sent)
                    747: 
                    748:     unless ($uessay=~/\w+/) { return ''; }
                    749: 
1.87      www       750: # these will be returned. Do not care if not at least 50 percent similar
1.88      www       751:     my $limit=0.6;
1.87      www       752:     my $sname='';
                    753:     my $sdom='';
                    754:     my $scrsid='';
                    755:     my $sessay='';
                    756: # go through all essays ...
1.426     albertel  757:     foreach my $tkey (keys(%$old_essays)) {
                    758: 	my ($tname,$tdom,$tcrsid)=map {&unescape($_)} (split(/\./,$tkey));
1.87      www       759: # ... except the same student
1.426     albertel  760:         next if (($tname eq $uname) && ($tdom eq $udom));
                    761: 	my $tessay=$old_essays->{$tkey};
                    762: 	$tessay=~s/\W+/ /gs;
1.87      www       763: # String similarity gives up if not even limit
1.426     albertel  764: 	my $tsimilar=&String::Similarity::similarity($uessay,$tessay,$limit);
1.87      www       765: # Found one
1.426     albertel  766: 	if ($tsimilar>$limit) {
                    767: 	    $limit=$tsimilar;
                    768: 	    $sname=$tname;
                    769: 	    $sdom=$tdom;
                    770: 	    $scrsid=$tcrsid;
                    771: 	    $sessay=$old_essays->{$tkey};
                    772: 	}
1.87      www       773:     }
1.88      www       774:     if ($limit>0.6) {
1.87      www       775:        return ($sname,$sdom,$scrsid,$sessay,$limit);
                    776:     } else {
                    777:        return ('','','','',0);
                    778:     }
                    779: }
                    780: 
1.44      ng        781: #-------------------------------------------------------------------
                    782: 
                    783: #------------------------------------ Receipt Verification Routines
1.45      ng        784: #
1.44      ng        785: #--- Check whether a receipt number is valid.---
                    786: sub verifyreceipt {
                    787:     my $request  = shift;
                    788: 
1.257     albertel  789:     my $courseid = $env{'request.course.id'};
1.184     www       790:     my $receipt  = &Apache::lonnet::recprefix($courseid).'-'.
1.257     albertel  791: 	$env{'form.receipt'};
1.44      ng        792:     $receipt     =~ s/[^\-\d]//g;
1.378     albertel  793:     my ($symb)   = &get_symb($request);
1.44      ng        794: 
1.487     albertel  795:     my $title.=
                    796: 	'<h3><span class="LC_info">'.
1.584     bisitz    797: 	&mt('Verifying Receipt No. [_1]',$receipt).
1.487     albertel  798: 	'</span></h3>'."\n".
                    799: 	'<h4>'.&mt('<b>Resource: </b>[_1]',$env{'form.probTitle'}).
                    800: 	'</h4>'."\n";
1.44      ng        801: 
                    802:     my ($string,$contents,$matches) = ('','',0);
1.56      matthew   803:     my (undef,undef,$fullname) = &getclasslist('all','0');
1.177     albertel  804:     
                    805:     my $receiptparts=0;
1.390     albertel  806:     if ($env{"course.$courseid.receiptalg"} eq 'receipt2' ||
                    807: 	$env{"course.$courseid.receiptalg"} eq 'receipt3') { $receiptparts=1; }
1.177     albertel  808:     my $parts=['0'];
1.582     raeburn   809:     if ($receiptparts) {
                    810:         my $res_error; 
                    811:         ($parts)=&response_type($symb,\$res_error);
                    812:         if ($res_error) {
                    813:             return &navmap_errormsg();
                    814:         } 
                    815:     }
1.486     albertel  816:     
                    817:     my $header = 
                    818: 	&Apache::loncommon::start_data_table().
                    819: 	&Apache::loncommon::start_data_table_header_row().
1.487     albertel  820: 	'<th>&nbsp;'.&mt('Fullname').'&nbsp;</th>'."\n".
                    821: 	'<th>&nbsp;'.&mt('Username').'&nbsp;</th>'."\n".
                    822: 	'<th>&nbsp;'.&mt('Domain').'&nbsp;</th>';
1.486     albertel  823:     if ($receiptparts) {
1.487     albertel  824: 	$header.='<th>&nbsp;'.&mt('Problem Part').'&nbsp;</th>';
1.486     albertel  825:     }
                    826:     $header.=
                    827: 	&Apache::loncommon::end_data_table_header_row();
                    828: 
1.294     albertel  829:     foreach (sort 
                    830: 	     {
                    831: 		 if (lc($$fullname{$a}) ne lc($$fullname{$b})) {
                    832: 		     return (lc($$fullname{$a}) cmp lc($$fullname{$b}));
                    833: 		 }
                    834: 		 return $a cmp $b;
                    835: 	     } (keys(%$fullname))) {
1.44      ng        836: 	my ($uname,$udom)=split(/\:/);
1.177     albertel  837: 	foreach my $part (@$parts) {
                    838: 	    if ($receipt eq &Apache::lonnet::ireceipt($uname,$udom,$courseid,$symb,$part)) {
1.486     albertel  839: 		$contents.=
                    840: 		    &Apache::loncommon::start_data_table_row().
                    841: 		    '<td>&nbsp;'."\n".
1.177     albertel  842: 		    '<a href="javascript:viewOneStudent(\''.$uname.'\',\''.$udom.
1.417     albertel  843: 		    '\');" target="_self">'.$$fullname{$_}.'</a>&nbsp;</td>'."\n".
1.177     albertel  844: 		    '<td>&nbsp;'.$uname.'&nbsp;</td>'.
                    845: 		    '<td>&nbsp;'.$udom.'&nbsp;</td>';
                    846: 		if ($receiptparts) {
                    847: 		    $contents.='<td>&nbsp;'.$part.'&nbsp;</td>';
                    848: 		}
1.486     albertel  849: 		$contents.= 
                    850: 		    &Apache::loncommon::end_data_table_row()."\n";
1.177     albertel  851: 		
                    852: 		$matches++;
                    853: 	    }
1.44      ng        854: 	}
                    855:     }
                    856:     if ($matches == 0) {
1.584     bisitz    857:         $string = $title
                    858:                  .'<p class="LC_warning">'
                    859:                  .&mt('No match found for the above receipt number.')
                    860:                  .'</p>';
1.44      ng        861:     } else {
1.324     albertel  862: 	$string = &jscriptNform($symb).$title.
1.487     albertel  863: 	    '<p>'.
1.584     bisitz    864: 	    &mt('The above receipt number matches the following [quant,_1,student].',$matches).
1.487     albertel  865: 	    '</p>'.
1.486     albertel  866: 	    $header.
                    867: 	    $contents.
                    868: 	    &Apache::loncommon::end_data_table()."\n";
1.44      ng        869:     }
1.324     albertel  870:     return $string.&show_grading_menu_form($symb);
1.44      ng        871: }
                    872: 
                    873: #--- This is called by a number of programs.
                    874: #--- Called from the Grading Menu - View/Grade an individual student
                    875: #--- Also called directly when one clicks on the subm button 
                    876: #    on the problem page.
1.30      ng        877: sub listStudents {
1.41      ng        878:     my ($request) = shift;
1.49      albertel  879: 
1.324     albertel  880:     my ($symb) = &get_symb($request);
1.257     albertel  881:     my $cdom      = $env{"course.$env{'request.course.id'}.domain"};
                    882:     my $cnum      = $env{"course.$env{'request.course.id'}.num"};
                    883:     my $getsec    = $env{'form.section'} eq '' ? 'all' : $env{'form.section'};
1.449     banghart  884:     my $getgroup  = $env{'form.group'} eq '' ? 'all' : $env{'form.group'};
1.257     albertel  885:     my $submitonly= $env{'form.submitonly'} eq '' ? 'all' : $env{'form.submitonly'};
1.548     bisitz    886:     my $viewgrade = $env{'form.showgrading'} eq 'yes' ? 'View/Grade/Regrade' : 'View';
1.257     albertel  887:     $env{'form.probTitle'} = $env{'form.probTitle'} eq '' ? 
                    888: 	&Apache::lonnet::gettitle($symb) : $env{'form.probTitle'};
1.49      albertel  889: 
1.548     bisitz    890:     my $result='<h3><span class="LC_info">&nbsp;'
                    891: 	.&mt("$viewgrade Submissions for a Student or a Group of Students")
1.485     albertel  892: 	.'</span></h3>';
1.118     ng        893: 
1.324     albertel  894:     my ($table,undef,$hdgrade,$partlist,$handgrade) = &showResourceInfo($symb,$env{'form.probTitle'},($env{'form.showgrading'} eq 'yes'));
1.49      albertel  895: 
1.559     raeburn   896:     my %lt = &Apache::lonlocal::texthash (
                    897: 		'multiple' => 'Please select a student or group of students before clicking on the Next button.',
                    898: 		'single'   => 'Please select the student before clicking on the Next button.',
                    899: 	     );
1.45      ng        900:     $request->print(<<LISTJAVASCRIPT);
                    901: <script type="text/javascript" language="javascript">
1.110     ng        902:     function checkSelect(checkBox) {
                    903: 	var ctr=0;
                    904: 	var sense="";
                    905: 	if (checkBox.length > 1) {
                    906: 	    for (var i=0; i<checkBox.length; i++) {
                    907: 		if (checkBox[i].checked) {
                    908: 		    ctr++;
                    909: 		}
                    910: 	    }
1.485     albertel  911: 	    sense = '$lt{'multiple'}';
1.110     ng        912: 	} else {
                    913: 	    if (checkBox.checked) {
                    914: 		ctr = 1;
                    915: 	    }
1.485     albertel  916: 	    sense = '$lt{'single'}';
1.110     ng        917: 	}
                    918: 	if (ctr == 0) {
1.485     albertel  919: 	    alert(sense);
1.110     ng        920: 	    return false;
                    921: 	}
                    922: 	document.gradesub.submit();
                    923:     }
                    924: 
                    925:     function reLoadList(formname) {
1.112     ng        926: 	if (formname.saveStatusOld.value == pullDownSelection(formname.Status)) {return;}
1.110     ng        927: 	formname.command.value = 'submission';
                    928: 	formname.submit();
                    929:     }
1.45      ng        930: </script>
                    931: LISTJAVASCRIPT
                    932: 
1.118     ng        933:     &commonJSfunctions($request);
1.41      ng        934:     $request->print($result);
1.39      ng        935: 
1.401     albertel  936:     my $checkhdgrade = ($env{'form.handgrade'} eq 'yes' && scalar(@$partlist) > 1 ) ? 'checked="checked"' : '';
                    937:     my $checklastsub = $checkhdgrade eq '' ? 'checked="checked"' : '';
1.154     albertel  938:     my $gradeTable='<form action="/adm/grades" method="post" name="gradesub">'.
1.485     albertel  939: 	"\n".$table;
                    940: 	
1.561     bisitz    941:     $gradeTable .= &Apache::lonhtmlcommon::start_pick_box();
                    942:     $gradeTable .= &Apache::lonhtmlcommon::row_title(&mt('View Problem Text'))
                    943:                   .'<label><input type="radio" name="vProb" value="no" checked="checked" /> '.&mt('no').' </label>'."\n"
                    944:                   .'<label><input type="radio" name="vProb" value="yes" /> '.&mt('one student').' </label>'."\n"
                    945:                   .'<label><input type="radio" name="vProb" value="all" /> '.&mt('all students').' </label><br />'."\n"
                    946:                   .&Apache::lonhtmlcommon::row_closure();
                    947:     $gradeTable .= &Apache::lonhtmlcommon::row_title(&mt('View Answer'))
                    948:                   .'<label><input type="radio" name="vAns" value="no"  /> '.&mt('no').' </label>'."\n"
                    949:                   .'<label><input type="radio" name="vAns" value="yes" /> '.&mt('one student').' </label>'."\n"
                    950:                   .'<label><input type="radio" name="vAns" value="all" checked="checked" /> '.&mt('all students').' </label><br />'."\n"
                    951:                   .&Apache::lonhtmlcommon::row_closure();
1.485     albertel  952: 
                    953:     my $submission_options;
1.257     albertel  954:     if ($env{'form.handgrade'} eq 'yes' && scalar(@$partlist) > 1) {
1.485     albertel  955: 	$submission_options.=
                    956: 	    '<label><input type="radio" name="lastSub" value="hdgrade" '.$checkhdgrade.' /> '.&mt('essay part only').' </label>'."\n";
1.49      albertel  957:     }
1.442     banghart  958:     my $stu_status = join(':',&Apache::loncommon::get_env_multiple('form.Status'));
                    959:     my $saveStatus = $stu_status eq '' ? 'Active' : $stu_status;
1.257     albertel  960:     $env{'form.Status'} = $saveStatus;
1.485     albertel  961:     $submission_options.=
1.592     bisitz    962:         '<span class="LC_nobreak">'.
                    963:         '<label><input type="radio" name="lastSub" value="lastonly" '.$checklastsub.' /> '.
                    964:         &mt('last submission only').' </label></span>'."\n".
                    965:         '<span class="LC_nobreak">'.
                    966:         '<label><input type="radio" name="lastSub" value="last" /> '.
                    967:         &mt('last submission &amp; parts info').' </label></span>'."\n".
                    968:         '<span class="LC_nobreak">'.
                    969:         '<label><input type="radio" name="lastSub" value="datesub" /> '.
                    970:         &mt('by dates and submissions').'</label></span>'."\n".
                    971:         '<span class="LC_nobreak">'.
                    972:         '<label><input type="radio" name="lastSub" value="all" /> '.
                    973:         &mt('all details').'</label></span>';
1.561     bisitz    974:     $gradeTable .= &Apache::lonhtmlcommon::row_title(&mt('Submissions'))
                    975:                   .$submission_options
                    976:                   .&Apache::lonhtmlcommon::row_closure();
                    977: 
                    978:     $gradeTable .= &Apache::lonhtmlcommon::row_title(&mt('Grading Increments'))
                    979:                   .'<select name="increment">'
                    980:                   .'<option value="1">'.&mt('Whole Points').'</option>'
                    981:                   .'<option value=".5">'.&mt('Half Points').'</option>'
                    982:                   .'<option value=".25">'.&mt('Quarter Points').'</option>'
                    983:                   .'<option value=".1">'.&mt('Tenths of a Point').'</option>'
                    984:                   .'</select>'
                    985:                   .&Apache::lonhtmlcommon::row_closure();
1.485     albertel  986: 
                    987:     $gradeTable .= 
1.432     banghart  988:         &build_section_inputs().
1.45      ng        989: 	'<input type="hidden" name="submitonly"  value="'.$submitonly.'" />'."\n".
1.257     albertel  990: 	'<input type="hidden" name="handgrade"   value="'.$env{'form.handgrade'}.'" /><br />'."\n".
                    991: 	'<input type="hidden" name="showgrading" value="'.$env{'form.showgrading'}.'" /><br />'."\n".
                    992: 	'<input type="hidden" name="saveState"   value="'.$env{'form.saveState'}.'" />'."\n".
                    993: 	'<input type="hidden" name="probTitle"   value="'.$env{'form.probTitle'}.'" />'."\n".
1.418     albertel  994: 	'<input type="hidden" name="symb" value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
1.110     ng        995: 	'<input type="hidden" name="saveStatusOld" value="'.$saveStatus.'" />'."\n";
                    996: 
1.257     albertel  997:     if (exists($env{'form.gradingMenu'}) && exists($env{'form.Status'})) {
1.561     bisitz    998: 	$gradeTable .= '<input type="hidden" name="Status" value="'.$stu_status.'" />'."\n";
1.124     ng        999:     } else {
1.561     bisitz   1000:         $gradeTable .= &Apache::lonhtmlcommon::row_title(&mt('Student Status'))
                   1001:                       .&Apache::lonhtmlcommon::StatusOptions(
                   1002:                            $saveStatus,undef,1,'javascript:reLoadList(this.form);')
                   1003:                       .&Apache::lonhtmlcommon::row_closure();
1.124     ng       1004:     }
1.112     ng       1005: 
1.561     bisitz   1006:     $gradeTable .= &Apache::lonhtmlcommon::row_title(&mt('Check For Plagiarism'))
                   1007:                   .'<input type="checkbox" name="checkPlag" checked="checked" />'
                   1008:                   .&Apache::lonhtmlcommon::row_closure(1)
                   1009:                   .&Apache::lonhtmlcommon::end_pick_box();
                   1010: 
                   1011:     $gradeTable .= '<p>'
                   1012:                   .&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"
                   1013:                   .'<input type="hidden" name="command" value="processGroup" />'
                   1014:                   .'</p>';
1.249     albertel 1015: 
                   1016: # checkall buttons
                   1017:     $gradeTable.=&check_script('gradesub', 'stuinfo');
1.110     ng       1018:     $gradeTable.='<input type="button" '."\n".
1.589     bisitz   1019:         'onclick="javascript:checkSelect(this.form.stuinfo);" '."\n".
                   1020:         'value="'.&mt('Next').' &rarr;" /> <br />'."\n";
1.249     albertel 1021:     $gradeTable.=&check_buttons();
1.450     banghart 1022:     my ($classlist, undef, $fullname) = &getclasslist($getsec,'1',$getgroup);
1.474     albertel 1023:     $gradeTable.= &Apache::loncommon::start_data_table().
                   1024: 	&Apache::loncommon::start_data_table_header_row();
1.110     ng       1025:     my $loop = 0;
                   1026:     while ($loop < 2) {
1.485     albertel 1027: 	$gradeTable.='<th>'.&mt('No.').'</th><th>'.&mt('Select').'</th>'.
                   1028: 	    '<th>'.&nameUserString('header').'&nbsp;'.&mt('Section/Group').'</th>';
1.301     albertel 1029: 	if ($env{'form.showgrading'} eq 'yes' 
                   1030: 	    && $submitonly ne 'queued'
                   1031: 	    && $submitonly ne 'all') {
1.485     albertel 1032: 	    foreach my $part (sort(@$partlist)) {
                   1033: 		my $display_part=
                   1034: 		    &get_display_part((split(/_/,$part))[0],$symb);
                   1035: 		$gradeTable.=
                   1036: 		    '<th>'.&mt('Part: [_1] Status',$display_part).'</th>';
1.110     ng       1037: 	    }
1.301     albertel 1038: 	} elsif ($submitonly eq 'queued') {
1.474     albertel 1039: 	    $gradeTable.='<th>'.&mt('Queue Status').'&nbsp;</th>';
1.110     ng       1040: 	}
                   1041: 	$loop++;
1.126     ng       1042: #	$gradeTable.='<td></td>' if ($loop%2 ==1);
1.41      ng       1043:     }
1.474     albertel 1044:     $gradeTable.=&Apache::loncommon::end_data_table_header_row()."\n";
1.41      ng       1045: 
1.45      ng       1046:     my $ctr = 0;
1.294     albertel 1047:     foreach my $student (sort 
                   1048: 			 {
                   1049: 			     if (lc($$fullname{$a}) ne lc($$fullname{$b})) {
                   1050: 				 return (lc($$fullname{$a}) cmp lc($$fullname{$b}));
                   1051: 			     }
                   1052: 			     return $a cmp $b;
                   1053: 			 }
                   1054: 			 (keys(%$fullname))) {
1.41      ng       1055: 	my ($uname,$udom) = split(/:/,$student);
1.301     albertel 1056: 
1.110     ng       1057: 	my %status = ();
1.301     albertel 1058: 
                   1059: 	if ($submitonly eq 'queued') {
                   1060: 	    my %queue_status = 
                   1061: 		&Apache::bridgetask::get_student_status($symb,$cdom,$cnum,
                   1062: 							$udom,$uname);
                   1063: 	    next if (!defined($queue_status{'gradingqueue'}));
                   1064: 	    $status{'gradingqueue'} = $queue_status{'gradingqueue'};
                   1065: 	}
                   1066: 
                   1067: 	if ($env{'form.showgrading'} eq 'yes' 
                   1068: 	    && $submitonly ne 'queued'
                   1069: 	    && $submitonly ne 'all') {
1.324     albertel 1070: 	    (%status) =&student_gradeStatus($symb,$udom,$uname,$partlist);
1.145     albertel 1071: 	    my $submitted = 0;
1.164     albertel 1072: 	    my $graded = 0;
1.248     albertel 1073: 	    my $incorrect = 0;
1.110     ng       1074: 	    foreach (keys(%status)) {
1.145     albertel 1075: 		$submitted = 1 if ($status{$_} ne 'nothing');
1.248     albertel 1076: 		$graded = 1 if ($status{$_} =~ /^ungraded/);
                   1077: 		$incorrect = 1 if ($status{$_} =~ /^incorrect/);
                   1078: 		
1.110     ng       1079: 		my ($foo,$partid,$foo1) = split(/\./,$_);
                   1080: 		if ($status{'resource.'.$partid.'.submitted_by'} ne '') {
1.145     albertel 1081: 		    $submitted = 0;
1.150     albertel 1082: 		    my ($part)=split(/\./,$partid);
1.110     ng       1083: 		    $gradeTable.='<input type="hidden" name="'.
1.150     albertel 1084: 			$student.':'.$part.':submitted_by" value="'.
1.110     ng       1085: 			$status{'resource.'.$partid.'.submitted_by'}.'" />';
                   1086: 		}
1.41      ng       1087: 	    }
1.248     albertel 1088: 	    
1.156     albertel 1089: 	    next if (!$submitted && ($submitonly eq 'yes' ||
                   1090: 				     $submitonly eq 'incorrect' ||
                   1091: 				     $submitonly eq 'graded'));
1.248     albertel 1092: 	    next if (!$graded && ($submitonly eq 'graded'));
                   1093: 	    next if (!$incorrect && $submitonly eq 'incorrect');
1.41      ng       1094: 	}
1.34      ng       1095: 
1.45      ng       1096: 	$ctr++;
1.249     albertel 1097: 	my $section = $classlist->{$student}->[&Apache::loncoursedata::CL_SECTION()];
1.452     banghart 1098:         my $group = $classlist->{$student}->[&Apache::loncoursedata::CL_GROUP()];
1.104     albertel 1099: 	if ( $perm{'vgr'} eq 'F' ) {
1.474     albertel 1100: 	    if ($ctr%2 ==1) {
                   1101: 		$gradeTable.= &Apache::loncommon::start_data_table_row();
                   1102: 	    }
1.126     ng       1103: 	    $gradeTable.='<td align="right">'.$ctr.'&nbsp;</td>'.
1.563     bisitz   1104:                '<td align="center"><label><input type="checkbox" name="stuinfo" value="'.
1.249     albertel 1105:                $student.':'.$$fullname{$student}.':::SECTION'.$section.
                   1106: 	       ')&nbsp;" />&nbsp;&nbsp;</label></td>'."\n".'<td>'.
                   1107: 	       &nameUserString(undef,$$fullname{$student},$uname,$udom).
1.474     albertel 1108: 	       '&nbsp;'.$section.($group ne '' ?'/'.$group:'').'</td>'."\n";
1.110     ng       1109: 
1.257     albertel 1110: 	    if ($env{'form.showgrading'} eq 'yes' && $submitonly ne 'all') {
1.524     raeburn  1111: 		foreach (sort(keys(%status))) {
1.485     albertel 1112: 		    next if ($_ =~ /^resource.*?submitted_by$/);
                   1113: 		    $gradeTable.='<td align="center">&nbsp;'.&mt($status{$_}).'&nbsp;</td>'."\n";
1.110     ng       1114: 		}
1.41      ng       1115: 	    }
1.126     ng       1116: #	    $gradeTable.='<td></td>' if ($ctr%2 ==1);
1.474     albertel 1117: 	    if ($ctr%2 ==0) {
                   1118: 		$gradeTable.=&Apache::loncommon::end_data_table_row()."\n";
                   1119: 	    }
1.41      ng       1120: 	}
                   1121:     }
1.110     ng       1122:     if ($ctr%2 ==1) {
1.126     ng       1123: 	$gradeTable.='<td>&nbsp;</td><td>&nbsp;</td><td>&nbsp;</td>';
1.301     albertel 1124: 	    if ($env{'form.showgrading'} eq 'yes' 
                   1125: 		&& $submitonly ne 'queued'
                   1126: 		&& $submitonly ne 'all') {
1.110     ng       1127: 		foreach (@$partlist) {
                   1128: 		    $gradeTable.='<td>&nbsp;</td>';
                   1129: 		}
1.301     albertel 1130: 	    } elsif ($submitonly eq 'queued') {
                   1131: 		$gradeTable.='<td>&nbsp;</td>';
1.110     ng       1132: 	    }
1.474     albertel 1133: 	$gradeTable.=&Apache::loncommon::end_data_table_row();
1.110     ng       1134:     }
                   1135: 
1.474     albertel 1136:     $gradeTable.=&Apache::loncommon::end_data_table()."\n".
1.589     bisitz   1137:         '<input type="button" '.
                   1138:         'onclick="javascript:checkSelect(this.form.stuinfo);" '.
                   1139:         'value="'.&mt('Next').' &rarr;" /></form>'."\n";
1.45      ng       1140:     if ($ctr == 0) {
1.96      albertel 1141: 	my $num_students=(scalar(keys(%$fullname)));
                   1142: 	if ($num_students eq 0) {
1.485     albertel 1143: 	    $gradeTable='<br />&nbsp;<span class="LC_warning">'.&mt('There are no students currently enrolled.').'</span>';
1.96      albertel 1144: 	} else {
1.171     albertel 1145: 	    my $submissions='submissions';
                   1146: 	    if ($submitonly eq 'incorrect') { $submissions = 'incorrect submissions'; }
                   1147: 	    if ($submitonly eq 'graded'   ) { $submissions = 'ungraded submissions'; }
1.301     albertel 1148: 	    if ($submitonly eq 'queued'   ) { $submissions = 'queued submissions'; }
1.398     albertel 1149: 	    $gradeTable='<br />&nbsp;<span class="LC_warning">'.
1.485     albertel 1150: 		&mt('No '.$submissions.' found for this resource for any students. ([_1] students checked for '.$submissions.')',
                   1151: 		    $num_students).
                   1152: 		'</span><br />';
1.96      albertel 1153: 	}
1.46      ng       1154:     } elsif ($ctr == 1) {
1.474     albertel 1155: 	$gradeTable =~ s/type="checkbox"/type="checkbox" checked="checked"/;
1.45      ng       1156:     }
1.324     albertel 1157:     $gradeTable.=&show_grading_menu_form($symb);
1.45      ng       1158:     $request->print($gradeTable);
1.44      ng       1159:     return '';
1.10      ng       1160: }
                   1161: 
1.44      ng       1162: #---- Called from the listStudents routine
1.249     albertel 1163: 
                   1164: sub check_script {
                   1165:     my ($form, $type)=@_;
                   1166:     my $chkallscript='<script type="text/javascript">
                   1167:     function checkall() {
                   1168:         for (i=0; i<document.forms.'.$form.'.elements.length; i++) {
                   1169:             ele = document.forms.'.$form.'.elements[i];
                   1170:             if (ele.name == "'.$type.'") {
                   1171:             document.forms.'.$form.'.elements[i].checked=true;
                   1172:                                        }
                   1173:         }
                   1174:     }
                   1175: 
                   1176:     function checksec() {
                   1177:         for (i=0; i<document.forms.'.$form.'.elements.length; i++) {
                   1178:             ele = document.forms.'.$form.'.elements[i];
                   1179:            string = document.forms.'.$form.'.chksec.value;
                   1180:            if
                   1181:           (ele.value.indexOf(":::SECTION"+string)>0) {
                   1182:               document.forms.'.$form.'.elements[i].checked=true;
                   1183:             }
                   1184:         }
                   1185:     }
                   1186: 
                   1187: 
                   1188:     function uncheckall() {
                   1189:         for (i=0; i<document.forms.'.$form.'.elements.length; i++) {
                   1190:             ele = document.forms.'.$form.'.elements[i];
                   1191:             if (ele.name == "'.$type.'") {
                   1192:             document.forms.'.$form.'.elements[i].checked=false;
                   1193:                                        }
                   1194:         }
                   1195:     }
                   1196: 
                   1197: </script>'."\n";
                   1198:     return $chkallscript;
                   1199: }
                   1200: 
                   1201: sub check_buttons {
1.485     albertel 1202:     my $buttons.='<input type="button" onclick="checkall()" value="'.&mt('Check All').'" />';
                   1203:     $buttons.='<input type="button" onclick="uncheckall()" value="'.&mt('Uncheck All').'" />&nbsp;';
                   1204:     $buttons.='<input type="button" onclick="checksec()" value="'.&mt('Check Section/Group').'" />';
1.249     albertel 1205:     $buttons.='<input type="text" size="5" name="chksec" />&nbsp;';
                   1206:     return $buttons;
                   1207: }
                   1208: 
1.44      ng       1209: #     Displays the submissions for one student or a group of students
1.34      ng       1210: sub processGroup {
1.41      ng       1211:     my ($request)  = shift;
                   1212:     my $ctr        = 0;
1.155     albertel 1213:     my @stuchecked = &Apache::loncommon::get_env_multiple('form.stuinfo');
1.41      ng       1214:     my $total      = scalar(@stuchecked)-1;
1.45      ng       1215: 
1.396     banghart 1216:     foreach my $student (@stuchecked) {
                   1217: 	my ($uname,$udom,$fullname) = split(/:/,$student);
1.257     albertel 1218: 	$env{'form.student'}        = $uname;
                   1219: 	$env{'form.userdom'}        = $udom;
                   1220: 	$env{'form.fullname'}       = $fullname;
1.41      ng       1221: 	&submission($request,$ctr,$total);
                   1222: 	$ctr++;
                   1223:     }
                   1224:     return '';
1.35      ng       1225: }
1.34      ng       1226: 
1.44      ng       1227: #------------------------------------------------------------------------------------
                   1228: #
                   1229: #-------------------------- Next few routines handles grading by student, essentially
                   1230: #                           handles essay response type problem/part
                   1231: #
                   1232: #--- Javascript to handle the submission page functionality ---
                   1233: sub sub_page_js {
                   1234:     my $request = shift;
1.539     riegler  1235: 	    my $alertmsg = &mt('A number equal or greater than 0 is expected. Entered value = ');
1.44      ng       1236:     $request->print(<<SUBJAVASCRIPT);
                   1237: <script type="text/javascript" language="javascript">
1.71      ng       1238:     function updateRadio(formname,id,weight) {
1.125     ng       1239: 	var gradeBox = formname["GD_BOX"+id];
                   1240: 	var radioButton = formname["RADVAL"+id];
                   1241: 	var oldpts = formname["oldpts"+id].value;
1.72      ng       1242: 	var pts = checkSolved(formname,id) == 'update' ? gradeBox.value : oldpts;
1.71      ng       1243: 	gradeBox.value = pts;
                   1244: 	var resetbox = false;
                   1245: 	if (isNaN(pts) || pts < 0) {
1.539     riegler  1246: 	    alert("$alertmsg"+pts);
1.71      ng       1247: 	    for (var i=0; i<radioButton.length; i++) {
                   1248: 		if (radioButton[i].checked) {
                   1249: 		    gradeBox.value = i;
                   1250: 		    resetbox = true;
                   1251: 		}
                   1252: 	    }
                   1253: 	    if (!resetbox) {
                   1254: 		formtextbox.value = "";
                   1255: 	    }
                   1256: 	    return;
1.44      ng       1257: 	}
1.71      ng       1258: 
                   1259: 	if (pts > weight) {
                   1260: 	    var resp = confirm("You entered a value ("+pts+
                   1261: 			       ") greater than the weight for the part. Accept?");
                   1262: 	    if (resp == false) {
1.125     ng       1263: 		gradeBox.value = oldpts;
1.71      ng       1264: 		return;
                   1265: 	    }
1.44      ng       1266: 	}
1.13      albertel 1267: 
1.71      ng       1268: 	for (var i=0; i<radioButton.length; i++) {
                   1269: 	    radioButton[i].checked=false;
                   1270: 	    if (pts == i && pts != "") {
                   1271: 		radioButton[i].checked=true;
                   1272: 	    }
                   1273: 	}
                   1274: 	updateSelect(formname,id);
1.125     ng       1275: 	formname["stores"+id].value = "0";
1.41      ng       1276:     }
1.5       albertel 1277: 
1.72      ng       1278:     function writeBox(formname,id,pts) {
1.125     ng       1279: 	var gradeBox = formname["GD_BOX"+id];
1.71      ng       1280: 	if (checkSolved(formname,id) == 'update') {
                   1281: 	    gradeBox.value = pts;
                   1282: 	} else {
1.125     ng       1283: 	    var oldpts = formname["oldpts"+id].value;
1.72      ng       1284: 	    gradeBox.value = oldpts;
1.125     ng       1285: 	    var radioButton = formname["RADVAL"+id];
1.71      ng       1286: 	    for (var i=0; i<radioButton.length; i++) {
                   1287: 		radioButton[i].checked=false;
1.72      ng       1288: 		if (i == oldpts) {
1.71      ng       1289: 		    radioButton[i].checked=true;
                   1290: 		}
                   1291: 	    }
1.41      ng       1292: 	}
1.125     ng       1293: 	formname["stores"+id].value = "0";
1.71      ng       1294: 	updateSelect(formname,id);
                   1295: 	return;
1.41      ng       1296:     }
1.44      ng       1297: 
1.71      ng       1298:     function clearRadBox(formname,id) {
                   1299: 	if (checkSolved(formname,id) == 'noupdate') {
                   1300: 	    updateSelect(formname,id);
                   1301: 	    return;
                   1302: 	}
1.125     ng       1303: 	gradeSelect = formname["GD_SEL"+id];
1.71      ng       1304: 	for (var i=0; i<gradeSelect.length; i++) {
                   1305: 	    if (gradeSelect[i].selected) {
                   1306: 		var selectx=i;
                   1307: 	    }
                   1308: 	}
1.125     ng       1309: 	var stores = formname["stores"+id];
1.71      ng       1310: 	if (selectx == stores.value) { return };
1.125     ng       1311: 	var gradeBox = formname["GD_BOX"+id];
1.71      ng       1312: 	gradeBox.value = "";
1.125     ng       1313: 	var radioButton = formname["RADVAL"+id];
1.71      ng       1314: 	for (var i=0; i<radioButton.length; i++) {
                   1315: 	    radioButton[i].checked=false;
                   1316: 	}
                   1317: 	stores.value = selectx;
                   1318:     }
1.5       albertel 1319: 
1.71      ng       1320:     function checkSolved(formname,id) {
1.125     ng       1321: 	if (formname["solved"+id].value == "correct_by_student" && formname.overRideScore.value == 'no') {
1.118     ng       1322: 	    var reply = confirm("This problem has been graded correct by the computer. Do you want to change the score?");
                   1323: 	    if (!reply) {return "noupdate";}
1.120     ng       1324: 	    formname.overRideScore.value = 'yes';
1.41      ng       1325: 	}
1.71      ng       1326: 	return "update";
1.13      albertel 1327:     }
1.71      ng       1328: 
                   1329:     function updateSelect(formname,id) {
1.125     ng       1330: 	formname["GD_SEL"+id][0].selected = true;
1.71      ng       1331: 	return;
1.41      ng       1332:     }
1.33      ng       1333: 
1.121     ng       1334: //=========== Check that a point is assigned for all the parts  ============
1.71      ng       1335:     function checksubmit(formname,val,total,parttot) {
1.121     ng       1336: 	formname.gradeOpt.value = val;
1.71      ng       1337: 	if (val == "Save & Next") {
                   1338: 	    for (i=0;i<=total;i++) {
                   1339: 		for (j=0;j<parttot;j++) {
1.125     ng       1340: 		    var partid = formname["partid"+i+"_"+j].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;
1.71      ng       1343: 			if (points == "") {
1.125     ng       1344: 			    var name = formname["name"+i].value;
1.129     ng       1345: 			    var studentID = (name != '' ? name : formname["unamedom"+i].value);
                   1346: 			    var resp = confirm("You did not assign a score for "+studentID+
                   1347: 					       ", part "+partid+". Continue?");
1.71      ng       1348: 			    if (resp == false) {
1.125     ng       1349: 				formname["GD_BOX"+i+"_"+partid].focus();
1.71      ng       1350: 				return false;
                   1351: 			    }
                   1352: 			}
                   1353: 		    }
                   1354: 		    
                   1355: 		}
                   1356: 	    }
                   1357: 	    
                   1358: 	}
1.121     ng       1359: 	if (val == "Grade Student") {
                   1360: 	    formname.showgrading.value = "yes";
                   1361: 	    if (formname.Status.value == "") {
                   1362: 		formname.Status.value = "Active";
                   1363: 	    }
                   1364: 	    formname.studentNo.value = total;
                   1365: 	}
1.120     ng       1366: 	formname.submit();
                   1367:     }
                   1368: 
1.71      ng       1369: //======= Check that a score is assigned for all the problems (page/sequence grading only) =========
                   1370:     function checkSubmitPage(formname,total) {
                   1371: 	noscore = new Array(100);
                   1372: 	var ptr = 0;
                   1373: 	for (i=1;i<total;i++) {
1.125     ng       1374: 	    var partid = formname["q_"+i].value;
1.127     ng       1375: 	    if (formname["GD_SEL"+i+"_"+partid][0].selected) {
1.125     ng       1376: 		var points = formname["GD_BOX"+i+"_"+partid].value;
                   1377: 		var status = formname["solved"+i+"_"+partid].value;
1.71      ng       1378: 		if (points == "" && status != "correct_by_student") {
                   1379: 		    noscore[ptr] = i;
                   1380: 		    ptr++;
                   1381: 		}
                   1382: 	    }
                   1383: 	}
                   1384: 	if (ptr != 0) {
                   1385: 	    var sense = ptr == 1 ? ": " : "s: ";
                   1386: 	    var prolist = "";
                   1387: 	    if (ptr == 1) {
                   1388: 		prolist = noscore[0];
                   1389: 	    } else {
                   1390: 		var i = 0;
                   1391: 		while (i < ptr-1) {
                   1392: 		    prolist += noscore[i]+", ";
                   1393: 		    i++;
                   1394: 		}
                   1395: 		prolist += "and "+noscore[i];
                   1396: 	    }
                   1397: 	    var resp = confirm("You did not assign any score for the following problem"+sense+prolist+". Continue?");
                   1398: 	    if (resp == false) {
                   1399: 		return false;
                   1400: 	    }
                   1401: 	}
1.45      ng       1402: 
1.71      ng       1403: 	formname.submit();
                   1404:     }
                   1405: </script>
                   1406: SUBJAVASCRIPT
                   1407: }
1.45      ng       1408: 
1.71      ng       1409: #--- javascript for essay type problem --
                   1410: sub sub_page_kw_js {
                   1411:     my $request = shift;
1.80      ng       1412:     my $iconpath = $request->dir_config('lonIconsURL');
1.118     ng       1413:     &commonJSfunctions($request);
1.350     albertel 1414: 
1.351     albertel 1415:     my $inner_js_msg_central=<<INNERJS;
1.350     albertel 1416:     <script text="text/javascript">
                   1417:     function checkInput() {
                   1418:       opener.document.SCORE.msgsub.value = opener.checkEntities(document.msgcenter.msgsub.value);
                   1419:       var nmsg   = opener.document.SCORE.savemsgN.value;
                   1420:       var usrctr = document.msgcenter.usrctr.value;
                   1421:       var newval = opener.document.SCORE["newmsg"+usrctr];
                   1422:       newval.value = opener.checkEntities(document.msgcenter.newmsg.value);
                   1423: 
                   1424:       var msgchk = "";
                   1425:       if (document.msgcenter.subchk.checked) {
                   1426:          msgchk = "msgsub,";
                   1427:       }
                   1428:       var includemsg = 0;
                   1429:       for (var i=1; i<=nmsg; i++) {
                   1430:           var opnmsg = opener.document.SCORE["savemsg"+i];
                   1431:           var frmmsg = document.msgcenter["msg"+i];
                   1432:           opnmsg.value = opener.checkEntities(frmmsg.value);
                   1433:           var showflg = opener.document.SCORE["shownOnce"+i];
                   1434:           showflg.value = "1";
                   1435:           var chkbox = document.msgcenter["msgn"+i];
                   1436:           if (chkbox.checked) {
                   1437:              msgchk += "savemsg"+i+",";
                   1438:              includemsg = 1;
                   1439:           }
                   1440:       }
                   1441:       if (document.msgcenter.newmsgchk.checked) {
                   1442:          msgchk += "newmsg"+usrctr;
                   1443:          includemsg = 1;
                   1444:       }
                   1445:       imgformname = opener.document.SCORE["mailicon"+usrctr];
                   1446:       imgformname.src = "$iconpath/"+((includemsg) ? "mailto.gif" : "mailbkgrd.gif");
                   1447:       var includemsg = opener.document.SCORE["includemsg"+usrctr];
                   1448:       includemsg.value = msgchk;
                   1449: 
                   1450:       self.close()
                   1451: 
                   1452:     }
                   1453:     </script>
                   1454: INNERJS
                   1455: 
1.351     albertel 1456:     my $inner_js_highlight_central=<<INNERJS;
                   1457:  <script type="text/javascript">
                   1458:     function updateChoice(flag) {
                   1459:       opener.document.SCORE.kwclr.value = opener.radioSelection(document.hlCenter.kwdclr);
                   1460:       opener.document.SCORE.kwsize.value = opener.radioSelection(document.hlCenter.kwdsize);
                   1461:       opener.document.SCORE.kwstyle.value = opener.radioSelection(document.hlCenter.kwdstyle);
                   1462:       opener.document.SCORE.refresh.value = "on";
                   1463:       if (opener.document.SCORE.keywords.value!=""){
                   1464:          opener.document.SCORE.submit();
                   1465:       }
                   1466:       self.close()
                   1467:     }
                   1468: </script>
                   1469: INNERJS
                   1470: 
                   1471:     my $start_page_msg_central = 
                   1472:         &Apache::loncommon::start_page('Message Central',$inner_js_msg_central,
                   1473: 				       {'js_ready'  => 1,
                   1474: 					'only_body' => 1,
                   1475: 					'bgcolor'   =>'#FFFFFF',});
                   1476:     my $end_page_msg_central = 
                   1477: 	&Apache::loncommon::end_page({'js_ready' => 1});
                   1478: 
                   1479: 
                   1480:     my $start_page_highlight_central = 
                   1481:         &Apache::loncommon::start_page('Highlight Central',
                   1482: 				       $inner_js_highlight_central,
1.350     albertel 1483: 				       {'js_ready'  => 1,
                   1484: 					'only_body' => 1,
                   1485: 					'bgcolor'   =>'#FFFFFF',});
1.351     albertel 1486:     my $end_page_highlight_central = 
1.350     albertel 1487: 	&Apache::loncommon::end_page({'js_ready' => 1});
                   1488: 
1.219     www      1489:     my $docopen=&Apache::lonhtmlcommon::javascript_docopen();
1.236     albertel 1490:     $docopen=~s/^document\.//;
1.539     riegler  1491:     my $alertmsg = &mt('Please select a word or group of words from document and then click this link.');
1.71      ng       1492:     $request->print(<<SUBJAVASCRIPT);
                   1493: <script type="text/javascript" language="javascript">
1.45      ng       1494: 
1.44      ng       1495: //===================== Show list of keywords ====================
1.122     ng       1496:   function keywords(formname) {
                   1497:     var nret = prompt("Keywords list, separated by a space. Add/delete to list if desired.",formname.keywords.value);
1.44      ng       1498:     if (nret==null) return;
1.122     ng       1499:     formname.keywords.value = nret;
1.44      ng       1500: 
1.122     ng       1501:     if (formname.keywords.value != "") {
1.128     ng       1502: 	formname.refresh.value = "on";
1.122     ng       1503: 	formname.submit();
1.44      ng       1504:     }
                   1505:     return;
                   1506:   }
                   1507: 
                   1508: //===================== Script to view submitted by ==================
                   1509:   function viewSubmitter(submitter) {
                   1510:     document.SCORE.refresh.value = "on";
                   1511:     document.SCORE.NCT.value = "1";
                   1512:     document.SCORE.unamedom0.value = submitter;
                   1513:     document.SCORE.submit();
                   1514:     return;
                   1515:   }
                   1516: 
                   1517: //===================== Script to add keyword(s) ==================
                   1518:   function getSel() {
                   1519:     if (document.getSelection) txt = document.getSelection();
                   1520:     else if (document.selection) txt = document.selection.createRange().text;
                   1521:     else return;
                   1522:     var cleantxt = txt.replace(new RegExp('([\\f\\n\\r\\t\\v ])+', 'g')," ");
                   1523:     if (cleantxt=="") {
1.539     riegler  1524: 	alert("$alertmsg");
1.44      ng       1525: 	return;
                   1526:     }
                   1527:     var nret = prompt("Add selection to keyword list? Edit if desired.",cleantxt);
                   1528:     if (nret==null) return;
1.127     ng       1529:     document.SCORE.keywords.value = document.SCORE.keywords.value+" "+nret;
1.44      ng       1530:     if (document.SCORE.keywords.value != "") {
1.127     ng       1531: 	document.SCORE.refresh.value = "on";
1.44      ng       1532: 	document.SCORE.submit();
                   1533:     }
                   1534:     return;
                   1535:   }
                   1536: 
                   1537: //====================== Script for composing message ==============
1.80      ng       1538:    // preload images
                   1539:    img1 = new Image();
                   1540:    img1.src = "$iconpath/mailbkgrd.gif";
                   1541:    img2 = new Image();
                   1542:    img2.src = "$iconpath/mailto.gif";
                   1543: 
1.44      ng       1544:   function msgCenter(msgform,usrctr,fullname) {
                   1545:     var Nmsg  = msgform.savemsgN.value;
                   1546:     savedMsgHeader(Nmsg,usrctr,fullname);
                   1547:     var subject = msgform.msgsub.value;
1.127     ng       1548:     var msgchk = document.SCORE["includemsg"+usrctr].value;
1.44      ng       1549:     re = /msgsub/;
                   1550:     var shwsel = "";
                   1551:     if (re.test(msgchk)) { shwsel = "checked" }
1.123     ng       1552:     subject = (document.SCORE.shownSub.value == 0 ? checkEntities(subject) : subject);
                   1553:     displaySubject(checkEntities(subject),shwsel);
1.44      ng       1554:     for (var i=1; i<=Nmsg; i++) {
1.123     ng       1555: 	var testmsg = "savemsg"+i+",";
                   1556: 	re = new RegExp(testmsg,"g");
1.44      ng       1557: 	shwsel = "";
                   1558: 	if (re.test(msgchk)) { shwsel = "checked" }
1.125     ng       1559: 	var message = document.SCORE["savemsg"+i].value;
1.126     ng       1560: 	message = (document.SCORE["shownOnce"+i].value == 0 ? checkEntities(message) : message);
1.123     ng       1561: 	displaySavedMsg(i,message,shwsel); //I do not get it. w/o checkEntities on saved messages,
                   1562: 	                                   //any &lt; is already converted to <, etc. However, only once!!
1.44      ng       1563:     }
1.125     ng       1564:     newmsg = document.SCORE["newmsg"+usrctr].value;
1.44      ng       1565:     shwsel = "";
                   1566:     re = /newmsg/;
                   1567:     if (re.test(msgchk)) { shwsel = "checked" }
                   1568:     newMsg(newmsg,shwsel);
                   1569:     msgTail(); 
                   1570:     return;
                   1571:   }
                   1572: 
1.123     ng       1573:   function checkEntities(strx) {
                   1574:     if (strx.length == 0) return strx;
                   1575:     var orgStr = ["&", "<", ">", '"']; 
                   1576:     var newStr = ["&amp;", "&lt;", "&gt;", "&quot;"];
                   1577:     var counter = 0;
                   1578:     while (counter < 4) {
                   1579: 	strx = strReplace(strx,orgStr[counter],newStr[counter]);
                   1580: 	counter++;
                   1581:     }
                   1582:     return strx;
                   1583:   }
                   1584: 
                   1585:   function strReplace(strx, orgStr, newStr) {
                   1586:     return strx.split(orgStr).join(newStr);
                   1587:   }
                   1588: 
1.44      ng       1589:   function savedMsgHeader(Nmsg,usrctr,fullname) {
1.76      ng       1590:     var height = 70*Nmsg+250;
1.44      ng       1591:     var scrollbar = "no";
                   1592:     if (height > 600) {
                   1593: 	height = 600;
                   1594: 	scrollbar = "yes";
                   1595:     }
1.118     ng       1596:     var xpos = (screen.width-600)/2;
                   1597:     xpos = (xpos < 0) ? '0' : xpos;
                   1598:     var ypos = (screen.height-height)/2-30;
                   1599:     ypos = (ypos < 0) ? '0' : ypos;
                   1600: 
1.206     albertel 1601:     pWin = window.open('', 'MessageCenter', 'resizable=yes,toolbar=no,location=no,scrollbars='+scrollbar+',screenx='+xpos+',screeny='+ypos+',width=600,height='+height);
1.76      ng       1602:     pWin.focus();
                   1603:     pDoc = pWin.document;
1.219     www      1604:     pDoc.$docopen;
1.351     albertel 1605:     pDoc.write('$start_page_msg_central');
1.76      ng       1606: 
                   1607:     pDoc.write("<form action=\\"inactive\\" name=\\"msgcenter\\">");
                   1608:     pDoc.write("<input value=\\""+usrctr+"\\" name=\\"usrctr\\" type=\\"hidden\\">");
1.465     albertel 1609:     pDoc.write("<h3><span class=\\"LC_info\\">&nbsp;Compose Message for \"+fullname+\"<\\/span><\\/h3><br /><br />");
1.76      ng       1610: 
1.564     bisitz   1611:     pDoc.write('<table border="0" width="100%"><tr><td bgcolor="#777777">');
                   1612:     pDoc.write('<table border="0" width="100%"><tr bgcolor="#DDFFFF">');
1.465     albertel 1613:     pDoc.write("<td><b>Type<\\/b><\\/td><td><b>Include<\\/b><\\/td><td><b>Message<\\/td><\\/tr>");
1.44      ng       1614: }
                   1615:     function displaySubject(msg,shwsel) {
1.76      ng       1616:     pDoc = pWin.document;
                   1617:     pDoc.write("<tr bgcolor=\\"#ffffdd\\">");
1.465     albertel 1618:     pDoc.write("<td>Subject<\\/td>");
                   1619:     pDoc.write("<td align=\\"center\\"><input name=\\"subchk\\" type=\\"checkbox\\"" +shwsel+"><\\/td>");
                   1620:     pDoc.write("<td><input name=\\"msgsub\\" type=\\"text\\" value=\\""+msg+"\\"size=\\"60\\" maxlength=\\"80\\"><\\/td><\\/tr>");
1.44      ng       1621: }
                   1622: 
1.72      ng       1623:   function displaySavedMsg(ctr,msg,shwsel) {
1.76      ng       1624:     pDoc = pWin.document;
                   1625:     pDoc.write("<tr bgcolor=\\"#ffffdd\\">");
1.465     albertel 1626:     pDoc.write("<td align=\\"center\\">"+ctr+"<\\/td>");
                   1627:     pDoc.write("<td align=\\"center\\"><input name=\\"msgn"+ctr+"\\" type=\\"checkbox\\"" +shwsel+"><\\/td>");
                   1628:     pDoc.write("<td><textarea name=\\"msg"+ctr+"\\" cols=\\"60\\" rows=\\"3\\">"+msg+"<\\/textarea><\\/td><\\/tr>");
1.44      ng       1629: }
                   1630: 
                   1631:   function newMsg(newmsg,shwsel) {
1.76      ng       1632:     pDoc = pWin.document;
                   1633:     pDoc.write("<tr bgcolor=\\"#ffffdd\\">");
1.465     albertel 1634:     pDoc.write("<td align=\\"center\\">New<\\/td>");
                   1635:     pDoc.write("<td align=\\"center\\"><input name=\\"newmsgchk\\" type=\\"checkbox\\"" +shwsel+"><\\/td>");
                   1636:     pDoc.write("<td><textarea name=\\"newmsg\\" cols=\\"60\\" rows=\\"3\\" onchange=\\"javascript:this.form.newmsgchk.checked=true\\" >"+newmsg+"<\\/textarea><\\/td><\\/tr>");
1.44      ng       1637: }
                   1638: 
                   1639:   function msgTail() {
1.76      ng       1640:     pDoc = pWin.document;
1.465     albertel 1641:     pDoc.write("<\\/table>");
                   1642:     pDoc.write("<\\/td><\\/tr><\\/table>&nbsp;");
1.589     bisitz   1643:     pDoc.write("<input type=\\"button\\" value=\\"Save\\" onclick=\\"javascript:checkInput()\\">&nbsp;&nbsp;");
                   1644:     pDoc.write("<input type=\\"button\\" value=\\"Cancel\\" onclick=\\"self.close()\\"><br /><br />");
1.465     albertel 1645:     pDoc.write("<\\/form>");
1.351     albertel 1646:     pDoc.write('$end_page_msg_central');
1.128     ng       1647:     pDoc.close();
1.44      ng       1648: }
                   1649: 
                   1650: //====================== Script for keyword highlight options ==============
                   1651:   function kwhighlight() {
                   1652:     var kwclr    = document.SCORE.kwclr.value;
                   1653:     var kwsize   = document.SCORE.kwsize.value;
                   1654:     var kwstyle  = document.SCORE.kwstyle.value;
                   1655:     var redsel = "";
                   1656:     var grnsel = "";
                   1657:     var blusel = "";
                   1658:     if (kwclr=="red")   {var redsel="checked"};
                   1659:     if (kwclr=="green") {var grnsel="checked"};
                   1660:     if (kwclr=="blue")  {var blusel="checked"};
                   1661:     var sznsel = "";
                   1662:     var sz1sel = "";
                   1663:     var sz2sel = "";
                   1664:     if (kwsize=="0")  {var sznsel="checked"};
                   1665:     if (kwsize=="+1") {var sz1sel="checked"};
                   1666:     if (kwsize=="+2") {var sz2sel="checked"};
                   1667:     var synsel = "";
                   1668:     var syisel = "";
                   1669:     var sybsel = "";
                   1670:     if (kwstyle=="")    {var synsel="checked"};
                   1671:     if (kwstyle=="<i>") {var syisel="checked"};
                   1672:     if (kwstyle=="<b>") {var sybsel="checked"};
                   1673:     highlightCentral();
                   1674:     highlightbody('red','red',redsel,'0','normal',sznsel,'','normal',synsel);
                   1675:     highlightbody('green','green',grnsel,'+1','+1',sz1sel,'<i>','italic',syisel);
                   1676:     highlightbody('blue','blue',blusel,'+2','+2',sz2sel,'<b>','bold',sybsel);
                   1677:     highlightend();
                   1678:     return;
                   1679:   }
                   1680: 
                   1681:   function highlightCentral() {
1.76      ng       1682: //    if (window.hwdWin) window.hwdWin.close();
1.118     ng       1683:     var xpos = (screen.width-400)/2;
                   1684:     xpos = (xpos < 0) ? '0' : xpos;
                   1685:     var ypos = (screen.height-330)/2-30;
                   1686:     ypos = (ypos < 0) ? '0' : ypos;
                   1687: 
1.206     albertel 1688:     hwdWin = window.open('', 'KeywordHighlightCentral', 'resizeable=yes,toolbar=no,location=no,scrollbars=no,width=400,height=300,screenx='+xpos+',screeny='+ypos);
1.76      ng       1689:     hwdWin.focus();
                   1690:     var hDoc = hwdWin.document;
1.219     www      1691:     hDoc.$docopen;
1.351     albertel 1692:     hDoc.write('$start_page_highlight_central');
1.76      ng       1693:     hDoc.write("<form action=\\"inactive\\" name=\\"hlCenter\\">");
1.465     albertel 1694:     hDoc.write("<h3><span class=\\"LC_info\\">&nbsp;Keyword Highlight Options<\\/span><\\/h3><br /><br />");
1.76      ng       1695: 
1.564     bisitz   1696:     hDoc.write('<table border="0" width="100%"><tr><td bgcolor="#777777">');
                   1697:     hDoc.write('<table border="0" width="100%"><tr bgcolor="#DDFFFF">');
1.465     albertel 1698:     hDoc.write("<td><b>Text Color<\\/b><\\/td><td><b>Font Size<\\/b><\\/td><td><b>Font Style<\\/td><\\/tr>");
1.44      ng       1699:   }
                   1700: 
                   1701:   function highlightbody(clrval,clrtxt,clrsel,szval,sztxt,szsel,syval,sytxt,sysel) { 
1.76      ng       1702:     var hDoc = hwdWin.document;
                   1703:     hDoc.write("<tr bgcolor=\\"#ffffdd\\">");
                   1704:     hDoc.write("<td align=\\"left\\">");
1.465     albertel 1705:     hDoc.write("<input name=\\"kwdclr\\" type=\\"radio\\" value=\\""+clrval+"\\" "+clrsel+">&nbsp;"+clrtxt+"<\\/td>");
1.76      ng       1706:     hDoc.write("<td align=\\"left\\">");
1.465     albertel 1707:     hDoc.write("<input name=\\"kwdsize\\" type=\\"radio\\" value=\\""+szval+"\\" "+szsel+">&nbsp;"+sztxt+"<\\/td>");
1.76      ng       1708:     hDoc.write("<td align=\\"left\\">");
1.465     albertel 1709:     hDoc.write("<input name=\\"kwdstyle\\" type=\\"radio\\" value=\\""+syval+"\\" "+sysel+">&nbsp;"+sytxt+"<\\/td>");
                   1710:     hDoc.write("<\\/tr>");
1.44      ng       1711:   }
                   1712: 
                   1713:   function highlightend() { 
1.76      ng       1714:     var hDoc = hwdWin.document;
1.465     albertel 1715:     hDoc.write("<\\/table>");
                   1716:     hDoc.write("<\\/td><\\/tr><\\/table>&nbsp;");
1.589     bisitz   1717:     hDoc.write("<input type=\\"button\\" value=\\"Save\\" onclick=\\"javascript:updateChoice(1)\\">&nbsp;&nbsp;");
                   1718:     hDoc.write("<input type=\\"button\\" value=\\"Cancel\\" onclick=\\"self.close()\\"><br /><br />");
1.465     albertel 1719:     hDoc.write("<\\/form>");
1.351     albertel 1720:     hDoc.write('$end_page_highlight_central');
1.128     ng       1721:     hDoc.close();
1.44      ng       1722:   }
                   1723: 
                   1724: </script>
                   1725: SUBJAVASCRIPT
                   1726: }
                   1727: 
1.349     albertel 1728: sub get_increment {
1.348     bowersj2 1729:     my $increment = $env{'form.increment'};
                   1730:     if ($increment != 1 && $increment != .5 && $increment != .25 &&
                   1731:         $increment != .1) {
                   1732:         $increment = 1;
                   1733:     }
                   1734:     return $increment;
                   1735: }
                   1736: 
1.585     bisitz   1737: sub gradeBox_start {
                   1738:     return (
                   1739:         &Apache::loncommon::start_data_table()
                   1740:        .&Apache::loncommon::start_data_table_header_row()
                   1741:        .'<th>'.&mt('Part').'</th>'
                   1742:        .'<th>'.&mt('Points').'</th>'
                   1743:        .'<th>&nbsp;</th>'
                   1744:        .'<th>'.&mt('Assign Grade').'</th>'
                   1745:        .'<th>'.&mt('Weight').'</th>'
                   1746:        .'<th>'.&mt('Grade Status').'</th>'
                   1747:        .&Apache::loncommon::end_data_table_header_row()
                   1748:     );
                   1749: }
                   1750: 
                   1751: sub gradeBox_end {
                   1752:     return (
                   1753:         &Apache::loncommon::end_data_table()
                   1754:     );
                   1755: }
1.71      ng       1756: #--- displays the grading box, used in essay type problem and grading by page/sequence
                   1757: sub gradeBox {
1.322     albertel 1758:     my ($request,$symb,$uname,$udom,$counter,$partid,$record) = @_;
1.381     albertel 1759:     my $checkIcon = '<img alt="'.&mt('Check Mark').
1.485     albertel 1760: 	'" src="'.&Apache::loncommon::lonhttpdurl($request->dir_config('lonIconsURL').'/check.gif').'" height="16" border="0" />';
1.71      ng       1761:     my $wgt    = &Apache::lonnet::EXT('resource.'.$partid.'.weight',$symb,$udom,$uname);
1.466     albertel 1762:     my $wgtmsg = ($wgt > 0) ? &mt('(problem weight)') 
                   1763:                            : '<span class="LC_info">'.&mt('problem weight assigned by computer').'</span>';
1.71      ng       1764:     $wgt       = ($wgt > 0 ? $wgt : '1');
                   1765:     my $score  = ($$record{'resource.'.$partid.'.awarded'} eq '' ?
1.320     albertel 1766: 		  '' : &compute_points($$record{'resource.'.$partid.'.awarded'},$wgt));
1.71      ng       1767:     my $result='<input type="hidden" name="WGT'.$counter.'_'.$partid.'" value="'.$wgt.'" />'."\n";
1.466     albertel 1768:     my $display_part= &get_display_part($partid,$symb);
1.270     albertel 1769:     my %last_resets = &get_last_resets($symb,$env{'request.course.id'},
                   1770: 				       [$partid]);
                   1771:     my $aggtries = $$record{'resource.'.$partid.'.tries'};
1.269     raeburn  1772:     if ($last_resets{$partid}) {
                   1773:         $aggtries = &get_num_tries($record,$last_resets{$partid},$partid);
                   1774:     }
1.585     bisitz   1775:     $result.=&Apache::loncommon::start_data_table_row();
1.71      ng       1776:     my $ctr = 0;
1.348     bowersj2 1777:     my $thisweight = 0;
1.349     albertel 1778:     my $increment = &get_increment();
1.485     albertel 1779: 
                   1780:     my $radio.='<table border="0"><tr>'."\n";  # display radio buttons in a nice table 10 across
1.348     bowersj2 1781:     while ($thisweight<=$wgt) {
1.532     bisitz   1782: 	$radio.= '<td><span class="LC_nobreak"><label><input type="radio" name="RADVAL'.$counter.'_'.$partid.'" '.
1.589     bisitz   1783:         'onclick="javascript:writeBox(this.form,\''.$counter.'_'.$partid.'\','.
1.348     bowersj2 1784: 	    $thisweight.')" value="'.$thisweight.'" '.
1.401     albertel 1785: 	    ($score eq $thisweight ? 'checked="checked"':'').' /> '.$thisweight."</label></span></td>\n";
1.485     albertel 1786: 	$radio.=(($ctr+1)%10 == 0 ? '</tr><tr>' : '');
1.348     bowersj2 1787:         $thisweight += $increment;
1.71      ng       1788: 	$ctr++;
                   1789:     }
1.485     albertel 1790:     $radio.='</tr></table>';
                   1791: 
                   1792:     my $line.='<input type="text" name="GD_BOX'.$counter.'_'.$partid.'"'.
1.71      ng       1793: 	($score ne ''? ' value = "'.$score.'"':'').' size="4" '.
1.589     bisitz   1794: 	'onchange="javascript:updateRadio(this.form,\''.$counter.'_'.$partid.'\','.
1.71      ng       1795: 	$wgt.')" /></td>'."\n";
1.485     albertel 1796:     $line.='<td>/'.$wgt.' '.$wgtmsg.
1.71      ng       1797: 	($$record{'resource.'.$partid.'.solved'} eq 'correct_by_student' ? '&nbsp;'.$checkIcon : '').
1.585     bisitz   1798: 	' </td>'."\n";
                   1799:     $line.='<td><select name="GD_SEL'.$counter.'_'.$partid.'" '.
1.589     bisitz   1800: 	'onchange="javascript:clearRadBox(this.form,\''.$counter.'_'.$partid.'\')" >'."\n";
1.71      ng       1801:     if ($$record{'resource.'.$partid.'.solved'} eq 'excused') {
1.485     albertel 1802: 	$line.='<option></option>'.
                   1803: 	    '<option value="excused" selected="selected">'.&mt('excused').'</option>';
1.71      ng       1804:     } else {
1.485     albertel 1805: 	$line.='<option selected="selected"></option>'.
                   1806: 	    '<option value="excused" >'.&mt('excused').'</option>';
1.71      ng       1807:     }
1.485     albertel 1808:     $line.='<option value="reset status">'.&mt('reset status').'</option></select>'."\n";
                   1809: 
                   1810: 
1.540     riegler  1811: 	#&mt('<td><b>Part:</b></td><td>[_1]</td><td><b>Points:</b></td><td>[_2]</td><td>or</td><td>[_3]</td>',$display_part,$radio,$line);
1.485     albertel 1812:     $result .= 
1.585     bisitz   1813: 	    '<td>'.$display_part.'</td><td>'.$radio.'</td><td>'.&mt('or').'</td><td>'.$line.'</td>';
                   1814:     $result.=&Apache::loncommon::end_data_table_row();
1.71      ng       1815:     $result.='<input type="hidden" name="stores'.$counter.'_'.$partid.'" value="" />'."\n".
                   1816: 	'<input type="hidden" name="oldpts'.$counter.'_'.$partid.'" value="'.$score.'" />'."\n".
                   1817: 	'<input type="hidden" name="solved'.$counter.'_'.$partid.'" value="'.
1.269     raeburn  1818: 	$$record{'resource.'.$partid.'.solved'}.'" />'."\n".
                   1819:         '<input type="hidden" name="totaltries'.$counter.'_'.$partid.'" value="'.
                   1820:         $$record{'resource.'.$partid.'.tries'}.'" />'."\n".
                   1821:         '<input type="hidden" name="aggtries'.$counter.'_'.$partid.'" value="'.
                   1822:         $aggtries.'" />'."\n";
1.582     raeburn  1823:     my $res_error;
                   1824:     $result.=&handback_box($symb,$uname,$udom,$counter,$partid,$record,\$res_error);
                   1825:     if ($res_error) {
                   1826:         return &navmap_errormsg();
                   1827:     }
1.318     banghart 1828:     return $result;
                   1829: }
1.322     albertel 1830: 
                   1831: sub handback_box {
1.582     raeburn  1832:     my ($symb,$uname,$udom,$counter,$partid,$record,$res_error) = @_;
                   1833:     my ($partlist,$handgrade,$responseType) = &response_type($symb,$res_error);
1.323     banghart 1834:     my (@respids);
1.375     albertel 1835:      my @part_response_id = &flatten_responseType($responseType);
                   1836:     foreach my $part_response_id (@part_response_id) {
                   1837:     	my ($part,$resp) = @{ $part_response_id };
1.323     banghart 1838:         if ($part eq $partid) {
1.375     albertel 1839:             push(@respids,$resp);
1.323     banghart 1840:         }
                   1841:     }
1.318     banghart 1842:     my $result;
1.323     banghart 1843:     foreach my $respid (@respids) {
1.322     albertel 1844: 	my $prefix = $counter.'_'.$partid.'_'.$respid.'_';
                   1845: 	my $files=&get_submitted_files($udom,$uname,$partid,$respid,$record);
                   1846: 	next if (!@$files);
                   1847: 	my $file_counter = 1;
1.313     banghart 1848: 	foreach my $file (@$files) {
1.368     banghart 1849: 	    if ($file =~ /\/portfolio\//) {
                   1850:     	        my ($file_path, $file_disp) = ($file =~ m|(.+/)(.+)$|);
                   1851:     	        my ($name,$version,$ext) = &file_name_version_ext($file_disp);
                   1852:     	        $file_disp = "$name.$ext";
                   1853:     	        $file = $file_path.$file_disp;
                   1854:     	        $result.=&mt('Return commented version of [_1] to student.',
                   1855:     			 '<span class="LC_filename">'.$file_disp.'</span>');
                   1856:     	        $result.='<input type="file"   name="'.$prefix.'returndoc'.$file_counter.'" />'."\n";
                   1857:     	        $result.='<input type="hidden" name="'.$prefix.'origdoc'.$file_counter.'" value="'.$file.'" /><br />';
1.485     albertel 1858:     	        $result.='('.&mt('File will be uploaded when you click on Save &amp; Next below.').')<br />';
1.368     banghart 1859:     	        $file_counter++;
                   1860: 	    }
1.322     albertel 1861: 	}
1.313     banghart 1862:     }
1.318     banghart 1863:     return $result;    
1.71      ng       1864: }
1.44      ng       1865: 
1.58      albertel 1866: sub show_problem {
1.382     albertel 1867:     my ($request,$symb,$uname,$udom,$removeform,$viewon,$mode,$form) = @_;
1.144     albertel 1868:     my $rendered;
1.382     albertel 1869:     my %form = ((ref($form) eq 'HASH')? %{$form} : ());
1.329     albertel 1870:     &Apache::lonxml::remember_problem_counter();
1.144     albertel 1871:     if ($mode eq 'both' or $mode eq 'text') {
                   1872: 	$rendered=&Apache::loncommon::get_student_view($symb,$uname,$udom,
1.382     albertel 1873: 						       $env{'request.course.id'},
                   1874: 						       undef,\%form);
1.144     albertel 1875:     }
1.58      albertel 1876:     if ($removeform) {
                   1877: 	$rendered=~s|<form(.*?)>||g;
                   1878: 	$rendered=~s|</form>||g;
1.374     albertel 1879: 	$rendered=~s|(<input[^>]*name\s*=\s*"?)(\w+)("?)|$1would_have_been_$2$3|g;
1.58      albertel 1880:     }
1.144     albertel 1881:     my $companswer;
                   1882:     if ($mode eq 'both' or $mode eq 'answer') {
1.329     albertel 1883: 	&Apache::lonxml::restore_problem_counter();
1.382     albertel 1884: 	$companswer=
                   1885: 	    &Apache::loncommon::get_student_answers($symb,$uname,$udom,
                   1886: 						    $env{'request.course.id'},
                   1887: 						    %form);
1.144     albertel 1888:     }
1.58      albertel 1889:     if ($removeform) {
                   1890: 	$companswer=~s|<form(.*?)>||g;
                   1891: 	$companswer=~s|</form>||g;
1.144     albertel 1892: 	$companswer=~s|name="submit"|name="would_have_been_submit"|g;
1.58      albertel 1893:     }
1.468     albertel 1894:     $rendered=
1.588     bisitz   1895:         '<div class="LC_Box">'
                   1896:        .'<h3 class="LC_hcell">'.&mt('View of the problem').'</h3>'
                   1897:        .$rendered
                   1898:        .'</div>';
1.468     albertel 1899:     $companswer=
1.588     bisitz   1900:         '<div class="LC_Box">'
                   1901:        .'<h3 class="LC_hcell">'.&mt('Correct answer').'</h3>'
                   1902:        .$companswer
                   1903:        .'</div>';
1.468     albertel 1904:     my $result;
1.144     albertel 1905:     if ($mode eq 'both') {
1.588     bisitz   1906:         $result=$rendered.$companswer;
1.144     albertel 1907:     } elsif ($mode eq 'text') {
1.588     bisitz   1908:         $result=$rendered;
1.144     albertel 1909:     } elsif ($mode eq 'answer') {
1.588     bisitz   1910:         $result=$companswer;
1.144     albertel 1911:     }
1.71      ng       1912:     return $result;
1.58      albertel 1913: }
1.397     albertel 1914: 
1.396     banghart 1915: sub files_exist {
                   1916:     my ($r, $symb) = @_;
                   1917:     my @students = &Apache::loncommon::get_env_multiple('form.stuinfo');
1.397     albertel 1918: 
1.396     banghart 1919:     foreach my $student (@students) {
                   1920:         my ($uname,$udom,$fullname) = split(/:/,$student);
1.397     albertel 1921:         my %record = &Apache::lonnet::restore($symb,$env{'request.course.id'},
                   1922: 					      $udom,$uname);
1.396     banghart 1923:         my ($string,$timestamp)= &get_last_submission(\%record);
1.397     albertel 1924:         foreach my $submission (@$string) {
                   1925:             my ($partid,$respid) =
                   1926: 		($submission =~ /^resource\.([^\.]*)\.([^\.]*)\.submission/);
                   1927:             my $files=&get_submitted_files($udom,$uname,$partid,$respid,
                   1928: 					   \%record);
                   1929:             return 1 if (@$files);
1.396     banghart 1930:         }
                   1931:     }
1.397     albertel 1932:     return 0;
1.396     banghart 1933: }
1.397     albertel 1934: 
1.394     banghart 1935: sub download_all_link {
                   1936:     my ($r,$symb) = @_;
1.395     albertel 1937:     my $all_students = 
                   1938: 	join("\n", &Apache::loncommon::get_env_multiple('form.stuinfo'));
                   1939: 
                   1940:     my $parts =
                   1941: 	join("\n",&Apache::loncommon::get_env_multiple('form.vPart'));
                   1942: 
1.394     banghart 1943:     my $identifier = &Apache::loncommon::get_cgi_id();
1.514     raeburn  1944:     &Apache::lonnet::appenv({'cgi.'.$identifier.'.students' => $all_students,
                   1945:                              'cgi.'.$identifier.'.symb' => $symb,
                   1946:                              'cgi.'.$identifier.'.parts' => $parts,});
1.395     albertel 1947:     $r->print('<a href="/cgi-bin/multidownload.pl?'.$identifier.'">'.
                   1948: 	      &mt('Download All Submitted Documents').'</a>');
1.394     banghart 1949:     return
                   1950: }
1.395     albertel 1951: 
1.432     banghart 1952: sub build_section_inputs {
                   1953:     my $section_inputs;
                   1954:     if ($env{'form.section'} eq '') {
                   1955:         $section_inputs .= '<input type="hidden" name="section" value="all" />'."\n";
                   1956:     } else {
                   1957:         my @sections = &Apache::loncommon::get_env_multiple('form.section');
1.434     albertel 1958:         foreach my $section (@sections) {
1.432     banghart 1959:             $section_inputs .= '<input type="hidden" name="section" value="'.$section.'" />'."\n";
                   1960:         }
                   1961:     }
                   1962:     return $section_inputs;
                   1963: }
                   1964: 
1.44      ng       1965: # --------------------------- show submissions of a student, option to grade 
                   1966: sub submission {
                   1967:     my ($request,$counter,$total) = @_;
1.257     albertel 1968:     my ($uname,$udom)     = ($env{'form.student'},$env{'form.userdom'});
                   1969:     $udom = ($udom eq '' ? $env{'user.domain'} : $udom); #has form.userdom changed for a student?
                   1970:     my $usec = &Apache::lonnet::getsection($udom,$uname,$env{'request.course.id'});
                   1971:     $env{'form.fullname'} = &Apache::loncommon::plainname($uname,$udom,'lastname') if $env{'form.fullname'} eq '';
1.324     albertel 1972:     my $symb = &get_symb($request); 
                   1973:     if ($symb eq '') { $request->print("Unable to handle ambiguous references:."); return ''; }
1.104     albertel 1974: 
                   1975:     if (!&canview($usec)) {
1.398     albertel 1976: 	$request->print('<span class="LC_warning">Unable to view requested student.('.
                   1977: 			$uname.':'.$udom.' in section '.$usec.' in course id '.
                   1978: 			$env{'request.course.id'}.')</span>');
1.324     albertel 1979: 	$request->print(&show_grading_menu_form($symb));
1.104     albertel 1980: 	return;
                   1981:     }
                   1982: 
1.257     albertel 1983:     if (!$env{'form.lastSub'}) { $env{'form.lastSub'} = 'datesub'; }
                   1984:     if (!$env{'form.vProb'}) { $env{'form.vProb'} = 'yes'; }
                   1985:     if (!$env{'form.vAns'}) { $env{'form.vAns'} = 'yes'; }
                   1986:     my $last = ($env{'form.lastSub'} eq 'last' ? 'last' : '');
1.381     albertel 1987:     my $checkIcon = '<img alt="'.&mt('Check Mark').
                   1988: 	'" src="'.$request->dir_config('lonIconsURL').
1.122     ng       1989: 	'/check.gif" height="16" border="0" />';
1.41      ng       1990: 
1.426     albertel 1991:     my %old_essays;
1.41      ng       1992:     # header info
                   1993:     if ($counter == 0) {
                   1994: 	&sub_page_js($request);
1.257     albertel 1995: 	&sub_page_kw_js($request) if ($env{'form.handgrade'} eq 'yes');
                   1996: 	$env{'form.probTitle'} = $env{'form.probTitle'} eq '' ? 
                   1997: 	    &Apache::lonnet::gettitle($symb) : $env{'form.probTitle'};
1.397     albertel 1998: 	if ($env{'form.handgrade'} eq 'yes' && &files_exist($request, $symb)) {
1.396     banghart 1999: 	    &download_all_link($request, $symb);
                   2000: 	}
1.485     albertel 2001: 	$request->print('<h3>&nbsp;<span class="LC_info">'.&mt('Submission Record').'</span></h3>'."\n".
                   2002: 			'<h4>&nbsp;'.&mt('<b>Resource: </b> [_1]',$env{'form.probTitle'}).'</h4>'."\n");
1.118     ng       2003: 
1.44      ng       2004: 	# option to display problem, only once else it cause problems 
                   2005:         # with the form later since the problem has a form.
1.257     albertel 2006: 	if ($env{'form.vProb'} eq 'yes' or $env{'form.vAns'} eq 'yes') {
1.144     albertel 2007: 	    my $mode;
1.257     albertel 2008: 	    if ($env{'form.vProb'} eq 'yes' && $env{'form.vAns'} eq 'yes') {
1.144     albertel 2009: 		$mode='both';
1.257     albertel 2010: 	    } elsif ($env{'form.vProb'} eq 'yes') {
1.144     albertel 2011: 		$mode='text';
1.257     albertel 2012: 	    } elsif ($env{'form.vAns'} eq 'yes') {
1.144     albertel 2013: 		$mode='answer';
                   2014: 	    }
1.329     albertel 2015: 	    &Apache::lonxml::clear_problem_counter();
1.144     albertel 2016: 	    $request->print(&show_problem($request,$symb,$uname,$udom,0,1,$mode));
1.41      ng       2017: 	}
1.441     www      2018: 
1.44      ng       2019: 	# kwclr is the only variable that is guaranteed to be non blank 
                   2020:         # if this subroutine has been called once.
1.41      ng       2021: 	my %keyhash = ();
1.257     albertel 2022: 	if ($env{'form.kwclr'} eq '' && $env{'form.handgrade'} eq 'yes') {
1.41      ng       2023: 	    %keyhash = &Apache::lonnet::dump('nohist_handgrade',
1.257     albertel 2024: 					     $env{'course.'.$env{'request.course.id'}.'.domain'},
                   2025: 					     $env{'course.'.$env{'request.course.id'}.'.num'});
1.41      ng       2026: 
1.257     albertel 2027: 	    my $loginuser = $env{'user.name'}.':'.$env{'user.domain'};
                   2028: 	    $env{'form.keywords'} = $keyhash{$symb.'_keywords'} ne '' ? $keyhash{$symb.'_keywords'} : '';
                   2029: 	    $env{'form.kwclr'}    = $keyhash{$loginuser.'_kwclr'} ne '' ? $keyhash{$loginuser.'_kwclr'} : 'red';
                   2030: 	    $env{'form.kwsize'}   = $keyhash{$loginuser.'_kwsize'} ne '' ? $keyhash{$loginuser.'_kwsize'} : '0';
                   2031: 	    $env{'form.kwstyle'}  = $keyhash{$loginuser.'_kwstyle'} ne '' ? $keyhash{$loginuser.'_kwstyle'} : '';
                   2032: 	    $env{'form.msgsub'}   = $keyhash{$symb.'_subject'} ne '' ? 
                   2033: 		$keyhash{$symb.'_subject'} : $env{'form.probTitle'};
                   2034: 	    $env{'form.savemsgN'} = $keyhash{$symb.'_savemsgN'} ne '' ? $keyhash{$symb.'_savemsgN'} : '0';
1.41      ng       2035: 	}
1.257     albertel 2036: 	my $overRideScore = $env{'form.overRideScore'} eq '' ? 'no' : $env{'form.overRideScore'};
1.442     banghart 2037: 	my $stu_status = join(':',&Apache::loncommon::get_env_multiple('form.Status'));
1.303     banghart 2038: 	$request->print('<form action="/adm/grades" method="post" name="SCORE" enctype="multipart/form-data">'."\n".
1.41      ng       2039: 			'<input type="hidden" name="command"    value="handgrade" />'."\n".
1.257     albertel 2040: 			'<input type="hidden" name="saveState"  value="'.$env{'form.saveState'}.'" />'."\n".
1.442     banghart 2041: 			'<input type="hidden" name="Status"     value="'.$stu_status.'" />'."\n".
1.120     ng       2042: 			'<input type="hidden" name="overRideScore" value="'.$overRideScore.'" />'."\n".
1.257     albertel 2043: 			'<input type="hidden" name="probTitle"  value="'.$env{'form.probTitle'}.'" />'."\n".
1.41      ng       2044: 			'<input type="hidden" name="refresh"    value="off" />'."\n".
1.120     ng       2045: 			'<input type="hidden" name="studentNo"  value="" />'."\n".
                   2046: 			'<input type="hidden" name="gradeOpt"   value="" />'."\n".
1.418     albertel 2047: 			'<input type="hidden" name="symb"       value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
1.257     albertel 2048: 			'<input type="hidden" name="showgrading" value="'.$env{'form.showgrading'}.'" />'."\n".
                   2049: 			'<input type="hidden" name="vProb"      value="'.$env{'form.vProb'}.'" />'."\n".
                   2050: 			'<input type="hidden" name="vAns"       value="'.$env{'form.vAns'}.'" />'."\n".
                   2051: 			'<input type="hidden" name="lastSub"    value="'.$env{'form.lastSub'}.'" />'."\n".
1.432     banghart 2052: 			&build_section_inputs().
1.326     albertel 2053: 			'<input type="hidden" name="submitonly" value="'.$env{'form.submitonly'}.'" />'."\n".
                   2054: 			'<input type="hidden" name="handgrade"  value="'.$env{'form.handgrade'}.'" />'."\n".
1.41      ng       2055: 			'<input type="hidden" name="NCT"'.
1.257     albertel 2056: 			' value="'.($env{'form.NTSTU'} ne '' ? $env{'form.NTSTU'} : $total+1).'" />'."\n");
                   2057: 	if ($env{'form.handgrade'} eq 'yes') {
                   2058: 	    $request->print('<input type="hidden" name="keywords" value="'.$env{'form.keywords'}.'" />'."\n".
                   2059: 			    '<input type="hidden" name="kwclr"    value="'.$env{'form.kwclr'}.'" />'."\n".
                   2060: 			    '<input type="hidden" name="kwsize"   value="'.$env{'form.kwsize'}.'" />'."\n".
                   2061: 			    '<input type="hidden" name="kwstyle"  value="'.$env{'form.kwstyle'}.'" />'."\n".
                   2062: 			    '<input type="hidden" name="msgsub"   value="'.$env{'form.msgsub'}.'" />'."\n".
1.123     ng       2063: 			    '<input type="hidden" name="shownSub" value="0" />'."\n".
1.257     albertel 2064: 			    '<input type="hidden" name="savemsgN" value="'.$env{'form.savemsgN'}.'" />'."\n");
1.154     albertel 2065: 	    foreach my $partid (&Apache::loncommon::get_env_multiple('form.vPart')) {
                   2066: 		$request->print('<input type="hidden" name="vPart" value="'.$partid.'" />'."\n");
                   2067: 	    }
1.123     ng       2068: 	}
1.41      ng       2069: 	
                   2070: 	my ($cts,$prnmsg) = (1,'');
1.257     albertel 2071: 	while ($cts <= $env{'form.savemsgN'}) {
1.41      ng       2072: 	    $prnmsg.='<input type="hidden" name="savemsg'.$cts.'" value="'.
1.123     ng       2073: 		(!exists($keyhash{$symb.'_savemsg'.$cts}) ? 
1.257     albertel 2074: 		 &Apache::lonfeedback::clear_out_html($env{'form.savemsg'.$cts}) :
1.80      ng       2075: 		 &Apache::lonfeedback::clear_out_html($keyhash{$symb.'_savemsg'.$cts})).
1.123     ng       2076: 		'" />'."\n".
                   2077: 		'<input type="hidden" name="shownOnce'.$cts.'" value="0" />'."\n";
1.41      ng       2078: 	    $cts++;
                   2079: 	}
                   2080: 	$request->print($prnmsg);
1.32      ng       2081: 
1.257     albertel 2082: 	if ($env{'form.handgrade'} eq 'yes' && $env{'form.showgrading'} eq 'yes') {
1.88      www      2083: #
                   2084: # Print out the keyword options line
                   2085: #
1.41      ng       2086: 	    $request->print(<<KEYWORDS);
1.38      ng       2087: &nbsp;<b>Keyword Options:</b>&nbsp;
1.417     albertel 2088: <a href="javascript:keywords(document.SCORE);" target="_self">List</a>&nbsp; &nbsp;
1.589     bisitz   2089: <a href="#" onmousedown="javascript:getSel(); return false"
1.38      ng       2090:  CLASS="page">Paste Selection to List</a>&nbsp; &nbsp;
1.417     albertel 2091: <a href="javascript:kwhighlight();" target="_self">Highlight Attribute</a><br /><br />
1.38      ng       2092: KEYWORDS
1.88      www      2093: #
                   2094: # Load the other essays for similarity check
                   2095: #
1.324     albertel 2096:             my (undef,undef,$essayurl) = &Apache::lonnet::decode_symb($symb);
1.384     albertel 2097: 	    my ($adom,$aname,$apath)=($essayurl=~/^($LONCAPA::domain_re)\/($LONCAPA::username_re)\/(.*)$/);
1.359     www      2098: 	    $apath=&escape($apath);
1.88      www      2099: 	    $apath=~s/\W/\_/gs;
1.426     albertel 2100: 	    %old_essays=&Apache::lonnet::dump('nohist_essay_'.$apath,$adom,$aname);
1.41      ng       2101:         }
                   2102:     }
1.44      ng       2103: 
1.441     www      2104: # This is where output for one specific student would start
1.592     bisitz   2105:     my $add_class = ($counter%2) ? ' LC_grade_show_user_odd_row' : '';
                   2106:     $request->print(
                   2107:         "\n\n"
                   2108:        .'<div class="LC_grade_show_user'.$add_class.'">'
                   2109:        .'<h2>'.&nameUserString(undef,$env{'form.fullname'},$uname,$udom).'</h2>'
                   2110:        ."\n"
                   2111:     );
1.441     www      2112: 
1.592     bisitz   2113:     # Show additional functions if allowed
                   2114:     if ($perm{'vgr'}) {
                   2115:         $request->print(
                   2116:             &Apache::loncommon::track_student_link(
                   2117:                 &mt('View recent activity'),
                   2118:                 $uname,$udom,'check')
                   2119:            .' '
                   2120:         );
                   2121:     }
                   2122:     if ($perm{'opa'}) {
                   2123:         $request->print(
                   2124:             &Apache::loncommon::pprmlink(
                   2125:                 &mt('Set/Change parameters'),
                   2126:                 $uname,$udom,$symb,'check'));
                   2127:     }
                   2128: 
                   2129:     # Show Problem
1.257     albertel 2130:     if ($env{'form.vProb'} eq 'all' or $env{'form.vAns'} eq 'all') {
1.144     albertel 2131: 	my $mode;
1.257     albertel 2132: 	if ($env{'form.vProb'} eq 'all' && $env{'form.vAns'} eq 'all') {
1.144     albertel 2133: 	    $mode='both';
1.257     albertel 2134: 	} elsif ($env{'form.vProb'} eq 'all' ) {
1.144     albertel 2135: 	    $mode='text';
1.257     albertel 2136: 	} elsif ($env{'form.vAns'} eq 'all') {
1.144     albertel 2137: 	    $mode='answer';
                   2138: 	}
1.329     albertel 2139: 	&Apache::lonxml::clear_problem_counter();
1.475     albertel 2140: 	$request->print(&show_problem($request,$symb,$uname,$udom,1,1,$mode,{'request.prefix' => 'ctr'.$counter}));
1.58      albertel 2141:     }
1.144     albertel 2142: 
1.257     albertel 2143:     my %record = &Apache::lonnet::restore($symb,$env{'request.course.id'},$udom,$uname);
1.582     raeburn  2144:     my $res_error;
                   2145:     my ($partlist,$handgrade,$responseType) = &response_type($symb,\$res_error);
                   2146:     if ($res_error) {
                   2147:         $request->print(&navmap_errormsg());
                   2148:         return;
                   2149:     }
1.41      ng       2150: 
1.44      ng       2151:     # Display student info
1.41      ng       2152:     $request->print(($counter == 0 ? '' : '<br />'));
1.590     bisitz   2153: 
                   2154:     my $result='<div class="LC_Box">'
                   2155:               .'<h3 class="LC_hcell">'.&mt('Submissions').'</h3>';
1.45      ng       2156:     $result.='<input type="hidden" name="name'.$counter.
1.588     bisitz   2157:              '" value="'.$env{'form.fullname'}.'" />'."\n";
1.469     albertel 2158:     if ($env{'form.handgrade'} eq 'no') {
1.588     bisitz   2159:         $result.='<p class="LC_info">'
                   2160:                 .&mt('Part(s) graded correct by the computer is marked with a [_1] symbol.',$checkIcon)
                   2161:                 ."</p>\n";
1.469     albertel 2162:     }
                   2163: 
1.118     ng       2164:     # If any part of the problem is an essay-response (handgraded), then check for collaborators
1.464     albertel 2165:     my $fullname;
                   2166:     my $col_fullnames = [];
1.257     albertel 2167:     if ($env{'form.handgrade'} eq 'yes') {
1.464     albertel 2168: 	(my $sub_result,$fullname,$col_fullnames)=
                   2169: 	    &check_collaborators($symb,$uname,$udom,\%record,$handgrade,
                   2170: 				 $counter);
                   2171: 	$result.=$sub_result;
1.41      ng       2172:     }
1.44      ng       2173:     $request->print($result."\n");
1.588     bisitz   2174: 
1.44      ng       2175:     # print student answer/submission
1.588     bisitz   2176:     # Options are (1) Handgraded submission only
1.44      ng       2177:     #             (2) Last submission, includes submission that is not handgraded 
                   2178:     #                  (for multi-response type part)
                   2179:     #             (3) Last submission plus the parts info
                   2180:     #             (4) The whole record for this student
1.257     albertel 2181:     if ($env{'form.lastSub'} =~ /^(lastonly|hdgrade)$/) {
1.151     albertel 2182: 	my ($string,$timestamp)= &get_last_submission(\%record);
1.468     albertel 2183: 	
                   2184: 	my $lastsubonly;
                   2185: 
1.588     bisitz   2186:         if ($$timestamp eq '') {
                   2187:             $lastsubonly.='<div class="LC_grade_submissions_body">'.$$string[0].'</div>'; 
                   2188:         } else {
1.592     bisitz   2189:             $lastsubonly =
                   2190:                 '<div class="LC_grade_submissions_body">'
                   2191:                .'<b>'.&mt('Date Submitted:').'</b> '.$$timestamp."\n";
1.468     albertel 2192: 
1.151     albertel 2193: 	    my %seenparts;
1.375     albertel 2194: 	    my @part_response_id = &flatten_responseType($responseType);
                   2195: 	    foreach my $part (@part_response_id) {
1.393     albertel 2196: 		next if ($env{'form.lastSub'} eq 'hdgrade' 
                   2197: 			 && $$handgrade{$$part[0].'_'.$$part[1]} ne 'yes');
                   2198: 
1.375     albertel 2199: 		my ($partid,$respid) = @{ $part };
1.324     albertel 2200: 		my $display_part=&get_display_part($partid,$symb);
1.257     albertel 2201: 		if ($env{"form.$uname:$udom:$partid:submitted_by"}) {
1.151     albertel 2202: 		    if (exists($seenparts{$partid})) { next; }
                   2203: 		    $seenparts{$partid}=1;
1.207     albertel 2204: 		    my $submitby='<b>Part:</b> '.$display_part.
                   2205: 			' <b>Collaborative submission by:</b> '.
1.151     albertel 2206: 			'<a href="javascript:viewSubmitter(\''.
1.257     albertel 2207: 			$env{"form.$uname:$udom:$partid:submitted_by"}.
1.417     albertel 2208: 			'\');" target="_self">'.
1.257     albertel 2209: 			$$fullname{$env{"form.$uname:$udom:$partid:submitted_by"}}.'</a><br />';
1.151     albertel 2210: 		    $request->print($submitby);
                   2211: 		    next;
                   2212: 		}
                   2213: 		my $responsetype = $responseType->{$partid}->{$respid};
                   2214: 		if (!exists($record{"resource.$partid.$respid.submission"})) {
1.577     bisitz   2215:                     $lastsubonly.="\n".'<div class="LC_grade_submission_part">'.
                   2216:                         '<b>'.&mt('Part: [_1]',$display_part).'</b>'.
                   2217:                         ' <span class="LC_internal_info">'.
                   2218:                         '('.&mt('Part ID: [_1]',$respid).')</b>'.
                   2219:                         '</span>&nbsp; &nbsp;'.
1.539     riegler  2220: 			'<span class="LC_warning">'.&mt('Nothing submitted - no attempts.').'</span><br /><br /></div>';
1.151     albertel 2221: 		    next;
                   2222: 		}
1.468     albertel 2223: 		foreach my $submission (@$string) {
                   2224: 		    my ($partid,$respid) = ($submission =~ /^resource\.([^\.]*)\.([^\.]*)\.submission/);
1.375     albertel 2225: 		    if (join('_',@{$part}) ne ($partid.'_'.$respid)) { next; }
1.596     raeburn  2226: 		    my ($ressub,$hide,$subval) = split(/:/,$submission,3);
1.151     albertel 2227: 		    # Similarity check
                   2228: 		    my $similar='';
1.596.2.2  raeburn  2229:                     my ($type,$trial,$rndseed);
                   2230:                     if ($hide eq 'rand') {
                   2231:                         $type = 'randomizetry';
                   2232:                         $trial = $record{"resource.$partid.tries"};
                   2233:                         $rndseed = $record{"resource.$partid.rndseed"};
                   2234:                     }
1.257     albertel 2235: 		    if($env{'form.checkPlag'}){
1.151     albertel 2236: 			my ($oname,$odom,$ocrsid,$oessay,$osim)=
1.426     albertel 2237: 			    &most_similar($uname,$udom,$subval,\%old_essays);
1.151     albertel 2238: 			if ($osim) {
                   2239: 			    $osim=int($osim*100.0);
1.426     albertel 2240: 			    my %old_course_desc = 
                   2241: 				&Apache::lonnet::coursedescription($ocrsid,
                   2242: 								   {'one_time' => 1});
                   2243: 
1.596.2.2  raeburn  2244:                             if ($hide eq 'anon') {
1.596     raeburn  2245:                                 $similar='<hr /><span class="LC_warning">'.&mt("Essay was found to be similar to another essay submitted for this assignment.").'<br />'.
                   2246:                                          &mt('As the current submission is for an anonymous survey, no other details are available.').'</span><hr />';
                   2247:                             } else {
                   2248: 			        $similar="<hr /><h3><span class=\"LC_warning\">".
                   2249: 				    &mt('Essay is [_1]% similar to an essay by [_2] in course [_3] (course id [_4]:[_5])',
                   2250: 				        $osim,
                   2251: 				        &Apache::loncommon::plainname($oname,$odom).' ('.$oname.':'.$odom.')',
                   2252: 				        $old_course_desc{'description'},
                   2253: 				        $old_course_desc{'num'},
                   2254: 				        $old_course_desc{'domain'}).
                   2255: 				    '</span></h3><blockquote><i>'.
                   2256: 				    &keywords_highlight($oessay).
                   2257: 				    '</i></blockquote><hr />';
                   2258:                             }
1.151     albertel 2259: 			}
1.150     albertel 2260: 		    }
1.596.2.2  raeburn  2261: 		    my $order=&get_order($partid,$respid,$symb,$uname,$udom,
                   2262:                                          undef,$type,$trial,$rndseed);
1.257     albertel 2263: 		    if ($env{'form.lastSub'} eq 'lastonly' || 
                   2264: 			($env{'form.lastSub'} eq 'hdgrade' && 
1.377     albertel 2265: 			 $$handgrade{$$part[0].'_'.$$part[1]} eq 'yes')) {
1.324     albertel 2266: 			my $display_part=&get_display_part($partid,$symb);
1.577     bisitz   2267:                         $lastsubonly.='<div class="LC_grade_submission_part">'.
                   2268:                             '<b>'.&mt('Part: [_1]',$display_part).'</b>'.
                   2269:                             ' <span class="LC_internal_info">'.
                   2270:                             '('.&mt('Part ID: [_1]',$respid).')'.
                   2271:                             '</b></span>&nbsp; &nbsp;';
1.313     banghart 2272: 			my $files=&get_submitted_files($udom,$uname,$partid,$respid,\%record);
                   2273: 			if (@$files) {
1.596.2.2  raeburn  2274:                             if ($hide eq 'anon') {
1.596     raeburn  2275:                                 $lastsubonly.='<br />'.&mt('[quant,_1,file] uploaded to this anonymous survey',scalar(@{$files}));
                   2276:                             } else {
                   2277:                                 $lastsubonly.='<br /><span class="LC_warning">'.&mt('Like all files provided by users, this file may contain viruses').'</span><br />';
                   2278:                                 foreach my $file (@$files) {
                   2279:                                     &Apache::lonnet::allowuploaded('/adm/grades',$file);
                   2280:                                     $lastsubonly.='<br /><a href="'.$file.'?rawmode=1" target="lonGRDs"><img src="'.&Apache::loncommon::icon($file).'" border="0" /> '.$file.'</a>';
                   2281:                                 }
                   2282:                             }
1.236     albertel 2283: 			    $lastsubonly.='<br />';
1.41      ng       2284: 			}
1.596.2.2  raeburn  2285:                         if ($hide eq 'anon') {
1.596     raeburn  2286:                             $lastsubonly.='<b>'.&mt('Anonymous Survey').'</b>'; 
                   2287:                         } else {
                   2288: 			    $lastsubonly.='<b>'.&mt('Submitted Answer:').' </b>'.
                   2289: 			        &cleanRecord($subval,$responsetype,$symb,$partid,
1.596.2.2  raeburn  2290: 					     $respid,\%record,$order,undef,$uname,$udom,$type,$trial,$rndseed);
1.596     raeburn  2291:                         }
1.151     albertel 2292: 			if ($similar) {$lastsubonly.="<br /><br />$similar\n";}
1.468     albertel 2293: 			$lastsubonly.='</div>';
1.41      ng       2294: 		    }
                   2295: 		}
                   2296: 	    }
1.588     bisitz   2297: 	    $lastsubonly.='</div>'."\n"; # End: LC_grade_submissions_body
1.151     albertel 2298: 	}
                   2299: 	$request->print($lastsubonly);
1.468     albertel 2300:    } elsif ($env{'form.lastSub'} eq 'datesub') {
1.324     albertel 2301: 	my (undef,$responseType,undef,$parts) = &showResourceInfo($symb);
1.148     albertel 2302: 	$request->print(&displaySubByDates($symb,\%record,$parts,$responseType,$checkIcon,$uname,$udom));
1.257     albertel 2303:     } elsif ($env{'form.lastSub'} =~ /^(last|all)$/) {
1.41      ng       2304: 	$request->print(&Apache::loncommon::get_previous_attempt($symb,$uname,$udom,
1.257     albertel 2305: 								 $env{'request.course.id'},
1.44      ng       2306: 								 $last,'.submission',
                   2307: 								 'Apache::grades::keywords_highlight'));
1.41      ng       2308:     }
1.120     ng       2309: 
1.121     ng       2310:     $request->print('<input type="hidden" name="unamedom'.$counter.'" value="'.$uname.':'
                   2311: 	.$udom.'" />'."\n");
1.44      ng       2312:     # return if view submission with no grading option
1.257     albertel 2313:     if ($env{'form.showgrading'} eq '' || (!&canmodify($usec))) {
1.120     ng       2314: 	my $toGrade.='<input type="button" value="Grade Student" '.
1.589     bisitz   2315: 	    'onclick="javascript:checksubmit(this.form,\'Grade Student\',\''
1.417     albertel 2316: 	    .$counter.'\');" target="_self" /> &nbsp;'."\n" if (&canmodify($usec));
1.468     albertel 2317: 	$toGrade.='</div>'."\n";
1.257     albertel 2318: 	if (($env{'form.command'} eq 'submission') || 
                   2319: 	    ($env{'form.command'} eq 'processGroup' && $counter == $total)) {
1.324     albertel 2320: 	    $toGrade.='</form>'.&show_grading_menu_form($symb); 
1.169     albertel 2321: 	}
1.180     albertel 2322: 	$request->print($toGrade);
1.41      ng       2323: 	return;
1.180     albertel 2324:     } else {
1.468     albertel 2325: 	$request->print('</div>'."\n");
1.41      ng       2326:     }
1.33      ng       2327: 
1.121     ng       2328:     # essay grading message center
1.257     albertel 2329:     if ($env{'form.handgrade'} eq 'yes') {
1.468     albertel 2330: 	my $result='<div class="LC_grade_message_center">';
                   2331:     
                   2332: 	$result.='<div class="LC_grade_message_center_header">'.
                   2333: 	    &mt('Send Message').'</div><div class="LC_grade_message_center_body">';
1.257     albertel 2334: 	my ($lastname,$givenn) = split(/,/,$env{'form.fullname'});
1.118     ng       2335: 	my $msgfor = $givenn.' '.$lastname;
1.464     albertel 2336: 	if (scalar(@$col_fullnames) > 0) {
                   2337: 	    my $lastone = pop(@$col_fullnames);
                   2338: 	    $msgfor .= ', '.(join ', ',@$col_fullnames).' and '.$lastone.'.';
1.118     ng       2339: 	}
                   2340: 	$msgfor =~ s/\'/\\'/g; #' stupid emacs - no! javascript
1.468     albertel 2341: 	$result.='<input type="hidden" name="includemsg'.$counter.'" value="" />'."\n".
1.121     ng       2342: 	    '<input type="hidden" name="newmsg'.$counter.'" value="" />'."\n";
                   2343: 	$result.='&nbsp;<a href="javascript:msgCenter(document.SCORE,'.$counter.
1.417     albertel 2344: 	    ',\''.$msgfor.'\');" target="_self">'.
1.464     albertel 2345: 	    &mt('Compose message to student').(scalar(@$col_fullnames) >= 1 ? 's' : '').'</a><label> ('.
1.350     albertel 2346: 	    &mt('incl. grades').' <input type="checkbox" name="withgrades'.$counter.'" /></label>)'.
1.118     ng       2347: 	    '<img src="'.$request->dir_config('lonIconsURL').
                   2348: 	    '/mailbkgrd.gif" width="14" height="10" name="mailicon'.$counter.'" />'."\n".
1.298     www      2349: 	    '<br />&nbsp;('.
1.468     albertel 2350: 	    &mt('Message will be sent when you click on Save &amp; Next below.').")\n";
                   2351: 	$result.='</div></div>';
1.121     ng       2352: 	$request->print($result);
1.118     ng       2353:     }
1.41      ng       2354: 
                   2355:     my %seen = ();
                   2356:     my @partlist;
1.129     ng       2357:     my @gradePartRespid;
1.375     albertel 2358:     my @part_response_id = &flatten_responseType($responseType);
1.585     bisitz   2359:     $request->print(
1.588     bisitz   2360:         '<div class="LC_Box">'
                   2361:        .'<h3 class="LC_hcell">'.&mt('Assign Grades').'</h3>'
1.585     bisitz   2362:     );
1.592     bisitz   2363:     $request->print(&gradeBox_start());
1.375     albertel 2364:     foreach my $part_response_id (@part_response_id) {
                   2365:     	my ($partid,$respid) = @{ $part_response_id };
                   2366: 	my $part_resp = join('_',@{ $part_response_id });
1.322     albertel 2367: 	next if ($seen{$partid} > 0);
1.41      ng       2368: 	$seen{$partid}++;
1.393     albertel 2369: 	next if ($$handgrade{$part_resp} ne 'yes' 
                   2370: 		 && $env{'form.lastSub'} eq 'hdgrade');
1.524     raeburn  2371: 	push(@partlist,$partid);
                   2372: 	push(@gradePartRespid,$partid.'.'.$respid);
1.322     albertel 2373: 	$request->print(&gradeBox($request,$symb,$uname,$udom,$counter,$partid,\%record));
1.41      ng       2374:     }
1.585     bisitz   2375:     $request->print(&gradeBox_end()); # </div>
                   2376:     $request->print('</div>');
1.468     albertel 2377: 
                   2378:     $request->print('<div class="LC_grade_info_links">');
                   2379:     $request->print('</div>');
                   2380: 
1.45      ng       2381:     $result='<input type="hidden" name="partlist'.$counter.
                   2382: 	'" value="'.(join ":",@partlist).'" />'."\n";
1.129     ng       2383:     $result.='<input type="hidden" name="gradePartRespid'.
                   2384: 	'" value="'.(join ":",@gradePartRespid).'" />'."\n" if ($counter == 0);
1.45      ng       2385:     my $ctr = 0;
                   2386:     while ($ctr < scalar(@partlist)) {
                   2387: 	$result.='<input type="hidden" name="partid'.$counter.'_'.$ctr.'" value="'.
                   2388: 	    $partlist[$ctr].'" />'."\n";
                   2389: 	$ctr++;
                   2390:     }
1.468     albertel 2391:     $request->print($result.''."\n");
1.41      ng       2392: 
1.441     www      2393: # Done with printing info for one student
                   2394: 
1.468     albertel 2395:     $request->print('</div>');#LC_grade_show_user
1.441     www      2396: 
                   2397: 
1.41      ng       2398:     # print end of form
                   2399:     if ($counter == $total) {
1.592     bisitz   2400:         my $endform='<br /><hr /><table border="0"><tr><td>'."\n";
1.485     albertel 2401: 	$endform.='<input type="button" value="'.&mt('Save &amp; Next').'" '.
1.589     bisitz   2402: 	    'onclick="javascript:checksubmit(this.form,\'Save & Next\','.
1.417     albertel 2403: 	    $total.','.scalar(@partlist).');" target="_self" /> &nbsp;'."\n";
1.119     ng       2404: 	my $ntstu ='<select name="NTSTU">'.
                   2405: 	    '<option>1</option><option>2</option>'.
                   2406: 	    '<option>3</option><option>5</option>'.
                   2407: 	    '<option>7</option><option>10</option></select>'."\n";
1.257     albertel 2408: 	my $nsel = ($env{'form.NTSTU'} ne '' ? $env{'form.NTSTU'} : '1');
1.401     albertel 2409: 	$ntstu =~ s/<option>$nsel</<option selected="selected">$nsel</;
1.578     raeburn  2410:         $endform.=&mt('[_1]student(s)',$ntstu);
1.485     albertel 2411: 	$endform.='&nbsp;&nbsp;<input type="button" value="'.&mt('Previous').'" '.
1.589     bisitz   2412: 	    'onclick="javascript:checksubmit(this.form,\'Previous\');" target="_self" /> &nbsp;'."\n".
1.485     albertel 2413: 	    '<input type="button" value="'.&mt('Next').'" '.
1.589     bisitz   2414: 	    'onclick="javascript:checksubmit(this.form,\'Next\');" target="_self" /> &nbsp;';
1.592     bisitz   2415:         $endform.='<span class="LC_warning">'.
                   2416:                   &mt('(Next and Previous (student) do not save the scores.)').
                   2417:                   '</span>'."\n" ;
1.349     albertel 2418:         $endform.="<input type='hidden' value='".&get_increment().
1.348     bowersj2 2419:             "' name='increment' />";
1.485     albertel 2420: 	$endform.='</td></tr></table></form>';
1.324     albertel 2421: 	$endform.=&show_grading_menu_form($symb);
1.41      ng       2422: 	$request->print($endform);
                   2423:     }
                   2424:     return '';
1.38      ng       2425: }
                   2426: 
1.464     albertel 2427: sub check_collaborators {
                   2428:     my ($symb,$uname,$udom,$record,$handgrade,$counter) = @_;
                   2429:     my ($result,@col_fullnames);
                   2430:     my ($classlist,undef,$fullname) = &getclasslist('all','0');
                   2431:     foreach my $part (keys(%$handgrade)) {
                   2432: 	my $ncol = &Apache::lonnet::EXT('resource.'.$part.
                   2433: 					'.maxcollaborators',
                   2434: 					$symb,$udom,$uname);
                   2435: 	next if ($ncol <= 0);
                   2436: 	$part =~ s/\_/\./g;
                   2437: 	next if ($record->{'resource.'.$part.'.collaborators'} eq '');
                   2438: 	my (@good_collaborators, @bad_collaborators);
                   2439: 	foreach my $possible_collaborator
                   2440: 	    (split(/,?\s+/,$record->{'resource.'.$part.'.collaborators'})) { 
                   2441: 	    $possible_collaborator =~ s/[\$\^\(\)]//g;
                   2442: 	    next if ($possible_collaborator eq '');
                   2443: 	    my ($co_name,$co_dom) = split(/\@|:/,$possible_collaborator);
                   2444: 	    $co_dom = $udom if (! defined($co_dom) || $co_dom =~ /^domain$/i);
                   2445: 	    next if ($co_name eq $uname && $co_dom eq $udom);
                   2446: 	    # Doing this grep allows 'fuzzy' specification
                   2447: 	    my @matches = grep(/^\Q$co_name\E:\Q$co_dom\E$/i, 
                   2448: 			       keys(%$classlist));
                   2449: 	    if (! scalar(@matches)) {
                   2450: 		push(@bad_collaborators, $possible_collaborator);
                   2451: 	    } else {
                   2452: 		push(@good_collaborators, @matches);
                   2453: 	    }
                   2454: 	}
                   2455: 	if (scalar(@good_collaborators) != 0) {
1.466     albertel 2456: 	    $result.='<br />'.&mt('Collaborators: ');
1.464     albertel 2457: 	    foreach my $name (@good_collaborators) {
                   2458: 		my ($lastname,$givenn) = split(/,/,$$fullname{$name});
                   2459: 		push(@col_fullnames, $givenn.' '.$lastname);
                   2460: 		$result.=$fullname->{$name}.'&nbsp; &nbsp; &nbsp;';
                   2461: 	    }
                   2462: 	    $result.='<br />'."\n";
1.466     albertel 2463: 	    my ($part)=split(/\./,$part);
1.464     albertel 2464: 	    $result.='<input type="hidden" name="collaborator'.$counter.
                   2465: 		'" value="'.$part.':'.(join ':',@good_collaborators).'" />'.
                   2466: 		"\n";
                   2467: 	}
                   2468: 	if (scalar(@bad_collaborators) > 0) {
1.466     albertel 2469: 	    $result.='<div class="LC_warning">';
1.464     albertel 2470: 	    $result.=&mt('This student has submitted [quant,_1,invalid collaborator]: [_2]',scalar(@bad_collaborators),join(', ',@bad_collaborators));
                   2471: 	    $result .= '</div>';
                   2472: 	}         
                   2473: 	if (scalar(@bad_collaborators > $ncol)) {
1.466     albertel 2474: 	    $result .= '<div class="LC_warning">';
1.464     albertel 2475: 	    $result .= &mt('This student has submitted too many '.
                   2476: 		'collaborators.  Maximum is [_1].',$ncol);
                   2477: 	    $result .= '</div>';
                   2478: 	}
                   2479:     }
                   2480:     return ($result,$fullname,\@col_fullnames);
                   2481: }
                   2482: 
1.44      ng       2483: #--- Retrieve the last submission for all the parts
1.38      ng       2484: sub get_last_submission {
1.119     ng       2485:     my ($returnhash)=@_;
1.596     raeburn  2486:     my (@string,$timestamp,%lasthidden);
1.119     ng       2487:     if ($$returnhash{'version'}) {
1.46      ng       2488: 	my %lasthash=();
                   2489: 	my ($version);
1.119     ng       2490: 	for ($version=1;$version<=$$returnhash{'version'};$version++) {
1.397     albertel 2491: 	    foreach my $key (sort(split(/\:/,
                   2492: 					$$returnhash{$version.':keys'}))) {
                   2493: 		$lasthash{$key}=$$returnhash{$version.':'.$key};
                   2494: 		$timestamp = 
1.545     raeburn  2495: 		    &Apache::lonlocal::locallocaltime($$returnhash{$version.':timestamp'});
1.46      ng       2496: 	    }
                   2497: 	}
1.596.2.2  raeburn  2498:         my (%typeparts,%randombytry);
1.596     raeburn  2499:         my $showsurv = 
                   2500:             &Apache::lonnet::allowed('vas',$env{'request.course.id'});
                   2501:         foreach my $key (sort(keys(%lasthash))) {
                   2502:             if ($key =~ /\.type$/) {
                   2503:                 if (($lasthash{$key} eq 'anonsurvey') || 
1.596.2.2  raeburn  2504:                     ($lasthash{$key} eq 'anonsurveycred') ||
                   2505:                     ($lasthash{$key} eq 'randomizetry')) {
1.596     raeburn  2506:                     my ($ign,@parts) = split(/\./,$key);
                   2507:                     pop(@parts);
1.596.2.3! raeburn  2508:                     my $id = join('.',@parts);
1.596.2.2  raeburn  2509:                     if ($lasthash{$key} eq 'randomizetry') {
                   2510:                         $randombytry{$ign.'.'.$id} = $lasthash{$key};
                   2511:                     } else {
                   2512:                         unless ($showsurv) {
                   2513:                             $typeparts{$ign.'.'.$id} = $lasthash{$key};
                   2514:                         }
1.596     raeburn  2515:                     }
                   2516:                     delete($lasthash{$key});
                   2517:                 }
                   2518:             }
                   2519:         }
                   2520:         my @hidden = keys(%typeparts);
1.596.2.2  raeburn  2521:         my @randomize = keys(%randombytry);
1.397     albertel 2522: 	foreach my $key (keys(%lasthash)) {
                   2523: 	    next if ($key !~ /\.submission$/);
1.596     raeburn  2524:             my $hide;
                   2525:             if (@hidden) {
                   2526:                 foreach my $id (@hidden) {
                   2527:                     if ($key =~ /^\Q$id\E/) {
1.596.2.2  raeburn  2528:                         $hide = 'anon';
1.596     raeburn  2529:                         last;
                   2530:                     }
                   2531:                 }
                   2532:             }
1.596.2.2  raeburn  2533:             unless ($hide) {
                   2534:                 if (@randomize) {
                   2535:                     foreach my $id (@hidden) {
                   2536:                         if ($key =~ /^\Q$id\E/) {
                   2537:                             $hide = 'rand';
                   2538:                             last;
                   2539:                         }
                   2540:                     }
                   2541:                 }
                   2542:             }
1.397     albertel 2543: 	    my ($partid,$foo) = split(/submission$/,$key);
                   2544: 	    my $draft  = $lasthash{$partid.'awarddetail'} eq 'DRAFT' ?
1.398     albertel 2545: 		'<span class="LC_warning">Draft Copy</span> ' : '';
1.596     raeburn  2546: 	    push(@string, join(':', $key, $hide, $draft.$lasthash{$key}));
1.41      ng       2547: 	}
                   2548:     }
1.397     albertel 2549:     if (!@string) {
                   2550: 	$string[0] =
1.539     riegler  2551: 	    '<span class="LC_warning">'.&mt('Nothing submitted - no attempts.').'</span>';
1.397     albertel 2552:     }
                   2553:     return (\@string,\$timestamp);
1.38      ng       2554: }
1.35      ng       2555: 
1.44      ng       2556: #--- High light keywords, with style choosen by user.
1.38      ng       2557: sub keywords_highlight {
1.44      ng       2558:     my $string    = shift;
1.257     albertel 2559:     my $size      = $env{'form.kwsize'} eq '0' ? '' : 'size='.$env{'form.kwsize'};
                   2560:     my $styleon   = $env{'form.kwstyle'} eq ''  ? '' : $env{'form.kwstyle'};
1.41      ng       2561:     (my $styleoff = $styleon) =~ s/\</\<\//;
1.257     albertel 2562:     my @keylist   = split(/[,\s+]/,$env{'form.keywords'});
1.398     albertel 2563:     foreach my $keyword (@keylist) {
                   2564: 	$string =~ s/\b\Q$keyword\E(\b|\.)/<font color\=$env{'form.kwclr'} $size\>$styleon$keyword$styleoff<\/font>/gi;
1.41      ng       2565:     }
                   2566:     return $string;
1.38      ng       2567: }
1.36      ng       2568: 
1.44      ng       2569: #--- Called from submission routine
1.38      ng       2570: sub processHandGrade {
1.41      ng       2571:     my ($request) = shift;
1.324     albertel 2572:     my $symb   = &get_symb($request);
                   2573:     my (undef,undef,$url) = &Apache::lonnet::decode_symb($symb);
1.257     albertel 2574:     my $button = $env{'form.gradeOpt'};
                   2575:     my $ngrade = $env{'form.NCT'};
                   2576:     my $ntstu  = $env{'form.NTSTU'};
1.301     albertel 2577:     my $cdom   = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   2578:     my $cnum   = $env{'course.'.$env{'request.course.id'}.'.num'};
                   2579: 
1.44      ng       2580:     if ($button eq 'Save & Next') {
                   2581: 	my $ctr = 0;
                   2582: 	while ($ctr < $ngrade) {
1.257     albertel 2583: 	    my ($uname,$udom) = split(/:/,$env{'form.unamedom'.$ctr});
1.324     albertel 2584: 	    my ($errorflag,$pts,$wgt) = &saveHandGrade($request,$symb,$uname,$udom,$ctr);
1.71      ng       2585: 	    if ($errorflag eq 'no_score') {
                   2586: 		$ctr++;
                   2587: 		next;
                   2588: 	    }
1.104     albertel 2589: 	    if ($errorflag eq 'not_allowed') {
1.398     albertel 2590: 		$request->print("<span class=\"LC_warning\">Not allowed to modify grades for $uname:$udom</span>");
1.104     albertel 2591: 		$ctr++;
                   2592: 		next;
                   2593: 	    }
1.257     albertel 2594: 	    my $includemsg = $env{'form.includemsg'.$ctr};
1.44      ng       2595: 	    my ($subject,$message,$msgstatus) = ('','','');
1.418     albertel 2596: 	    my $restitle = &Apache::lonnet::gettitle($symb);
                   2597:             my ($feedurl,$showsymb) =
                   2598: 		&get_feedurl_and_symb($symb,$uname,$udom);
                   2599: 	    my $messagetail;
1.62      albertel 2600: 	    if ($includemsg =~ /savemsg|newmsg\Q$ctr\E/) {
1.298     www      2601: 		$subject = $env{'form.msgsub'} if ($includemsg =~ /msgsub/);
1.295     www      2602: 		unless ($subject=~/\w/) { $subject=&mt('Grading Feedback'); }
1.386     raeburn  2603: 		$subject.=' ['.$restitle.']';
1.44      ng       2604: 		my (@msgnum) = split(/,/,$includemsg);
                   2605: 		foreach (@msgnum) {
1.257     albertel 2606: 		    $message.=$env{'form.'.$_} if ($_ =~ /savemsg|newmsg/ && $_ ne '');
1.44      ng       2607: 		}
1.80      ng       2608: 		$message =&Apache::lonfeedback::clear_out_html($message);
1.298     www      2609: 		if ($env{'form.withgrades'.$ctr}) {
                   2610: 		    $message.="\n\nPoint".($pts > 1 ? 's':'').' awarded = '.$pts.' out of '.$wgt;
1.386     raeburn  2611: 		    $messagetail = " for <a href=\"".
1.418     albertel 2612: 		                   $feedurl."?symb=$showsymb\">$env{'form.probTitle'}</a>";
1.386     raeburn  2613: 		}
                   2614: 		$msgstatus = 
                   2615:                     &Apache::lonmsg::user_normal_msg($uname,$udom,$subject,
                   2616: 						     $message.$messagetail,
1.418     albertel 2617:                                                      undef,$feedurl,undef,
1.386     raeburn  2618:                                                      undef,undef,$showsymb,
                   2619:                                                      $restitle);
1.574     bisitz   2620: 		$request->print('<br />'.&mt('Sending message to [_1]',$uname.':'.$udom).': '.
1.296     www      2621: 				$msgstatus);
1.44      ng       2622: 	    }
1.257     albertel 2623: 	    if ($env{'form.collaborator'.$ctr}) {
1.155     albertel 2624: 		my @collabstrs=&Apache::loncommon::get_env_multiple("form.collaborator$ctr");
1.150     albertel 2625: 		foreach my $collabstr (@collabstrs) {
                   2626: 		    my ($part,@collaborators) = split(/:/,$collabstr);
1.310     banghart 2627: 		    foreach my $collaborator (@collaborators) {
1.150     albertel 2628: 			my ($errorflag,$pts,$wgt) = 
1.324     albertel 2629: 			    &saveHandGrade($request,$symb,$collaborator,$udom,$ctr,
1.257     albertel 2630: 					   $env{'form.unamedom'.$ctr},$part);
1.150     albertel 2631: 			if ($errorflag eq 'not_allowed') {
1.362     albertel 2632: 			    $request->print("<span class=\"LC_error\">".&mt('Not allowed to modify grades for [_1]',"$collaborator:$udom")."</span>");
1.150     albertel 2633: 			    next;
1.418     albertel 2634: 			} elsif ($message ne '') {
                   2635: 			    my ($baseurl,$showsymb) = 
                   2636: 				&get_feedurl_and_symb($symb,$collaborator,
                   2637: 						      $udom);
                   2638: 			    if ($env{'form.withgrades'.$ctr}) {
                   2639: 				$messagetail = " for <a href=\"".
1.386     raeburn  2640:                                     $baseurl."?symb=$showsymb\">$env{'form.probTitle'}</a>";
1.150     albertel 2641: 			    }
1.418     albertel 2642: 			    $msgstatus = 
                   2643: 				&Apache::lonmsg::user_normal_msg($collaborator,$udom,$subject,$message.$messagetail,undef,$baseurl,undef,undef,undef,$showsymb,$restitle);
1.104     albertel 2644: 			}
1.44      ng       2645: 		    }
                   2646: 		}
                   2647: 	    }
                   2648: 	    $ctr++;
                   2649: 	}
                   2650:     }
                   2651: 
1.257     albertel 2652:     if ($env{'form.handgrade'} eq 'yes') {
1.119     ng       2653: 	# Keywords sorted in alphabatical order
1.257     albertel 2654: 	my $loginuser = $env{'user.name'}.':'.$env{'user.domain'};
1.119     ng       2655: 	my %keyhash = ();
1.257     albertel 2656: 	$env{'form.keywords'}           =~ s/,\s{0,}|\s+/ /g;
                   2657: 	$env{'form.keywords'}           =~ s/^\s+|\s+$//;
                   2658: 	my (@keywords) = sort(split(/\s+/,$env{'form.keywords'}));
                   2659: 	$env{'form.keywords'} = join(' ',@keywords);
                   2660: 	$keyhash{$symb.'_keywords'}     = $env{'form.keywords'};
                   2661: 	$keyhash{$symb.'_subject'}      = $env{'form.msgsub'};
                   2662: 	$keyhash{$loginuser.'_kwclr'}   = $env{'form.kwclr'};
                   2663: 	$keyhash{$loginuser.'_kwsize'}  = $env{'form.kwsize'};
                   2664: 	$keyhash{$loginuser.'_kwstyle'} = $env{'form.kwstyle'};
1.119     ng       2665: 
                   2666: 	# message center - Order of message gets changed. Blank line is eliminated.
1.257     albertel 2667: 	# New messages are saved in env for the next student.
1.119     ng       2668: 	# All messages are saved in nohist_handgrade.db
                   2669: 	my ($ctr,$idx) = (1,1);
1.257     albertel 2670: 	while ($ctr <= $env{'form.savemsgN'}) {
                   2671: 	    if ($env{'form.savemsg'.$ctr} ne '') {
                   2672: 		$keyhash{$symb.'_savemsg'.$idx} = $env{'form.savemsg'.$ctr};
1.119     ng       2673: 		$idx++;
                   2674: 	    }
                   2675: 	    $ctr++;
1.41      ng       2676: 	}
1.119     ng       2677: 	$ctr = 0;
                   2678: 	while ($ctr < $ngrade) {
1.257     albertel 2679: 	    if ($env{'form.newmsg'.$ctr} ne '') {
                   2680: 		$keyhash{$symb.'_savemsg'.$idx} = $env{'form.newmsg'.$ctr};
                   2681: 		$env{'form.savemsg'.$idx} = $env{'form.newmsg'.$ctr};
1.119     ng       2682: 		$idx++;
                   2683: 	    }
                   2684: 	    $ctr++;
1.41      ng       2685: 	}
1.257     albertel 2686: 	$env{'form.savemsgN'} = --$idx;
                   2687: 	$keyhash{$symb.'_savemsgN'} = $env{'form.savemsgN'};
1.119     ng       2688: 	my $putresult = &Apache::lonnet::put
1.301     albertel 2689: 	    ('nohist_handgrade',\%keyhash,$cdom,$cnum);
1.41      ng       2690:     }
1.44      ng       2691:     # Called by Save & Refresh from Highlight Attribute Window
1.257     albertel 2692:     my (undef,undef,$fullname) = &getclasslist($env{'form.section'},'1');
                   2693:     if ($env{'form.refresh'} eq 'on') {
1.86      ng       2694: 	my ($ctr,$total) = (0,0);
                   2695: 	while ($ctr < $ngrade) {
1.257     albertel 2696: 	    $total++ if  $env{'form.unamedom'.$ctr} ne '';
1.86      ng       2697: 	    $ctr++;
                   2698: 	}
1.257     albertel 2699: 	$env{'form.NTSTU'}=$ngrade;
1.86      ng       2700: 	$ctr = 0;
                   2701: 	while ($ctr < $total) {
1.257     albertel 2702: 	    my $processUser = $env{'form.unamedom'.$ctr};
                   2703: 	    ($env{'form.student'},$env{'form.userdom'}) = split(/:/,$processUser);
                   2704: 	    $env{'form.fullname'} = $$fullname{$processUser};
1.86      ng       2705: 	    &submission($request,$ctr,$total-1);
1.41      ng       2706: 	    $ctr++;
                   2707: 	}
                   2708: 	return '';
                   2709:     }
1.36      ng       2710: 
1.121     ng       2711: # Go directly to grade student - from submission or link from chart page
1.120     ng       2712:     if ($button eq 'Grade Student') {
1.324     albertel 2713: 	(undef,undef,$env{'form.handgrade'},undef,undef) = &showResourceInfo($symb);
1.257     albertel 2714: 	my $processUser = $env{'form.unamedom'.$env{'form.studentNo'}};
                   2715: 	($env{'form.student'},$env{'form.userdom'}) = split(/:/,$processUser);
                   2716: 	$env{'form.fullname'} = $$fullname{$processUser};
1.120     ng       2717: 	&submission($request,0,0);
                   2718: 	return '';
                   2719:     }
                   2720: 
1.44      ng       2721:     # Get the next/previous one or group of students
1.257     albertel 2722:     my $firststu = $env{'form.unamedom0'};
                   2723:     my $laststu = $env{'form.unamedom'.($ngrade-1)};
1.119     ng       2724:     my $ctr = 2;
1.41      ng       2725:     while ($laststu eq '') {
1.257     albertel 2726: 	$laststu  = $env{'form.unamedom'.($ngrade-$ctr)};
1.41      ng       2727: 	$ctr++;
                   2728: 	$laststu = $firststu if ($ctr > $ngrade);
                   2729:     }
1.44      ng       2730: 
1.41      ng       2731:     my (@parsedlist,@nextlist);
                   2732:     my ($nextflg) = 0;
1.524     raeburn  2733:     foreach my $item (sort 
1.294     albertel 2734: 	     {
                   2735: 		 if (lc($$fullname{$a}) ne lc($$fullname{$b})) {
                   2736: 		     return (lc($$fullname{$a}) cmp lc($$fullname{$b}));
                   2737: 		 }
                   2738: 		 return $a cmp $b;
                   2739: 	     } (keys(%$fullname))) {
1.41      ng       2740: 	if ($nextflg == 1 && $button =~ /Next$/) {
1.524     raeburn  2741: 	    push(@parsedlist,$item);
1.41      ng       2742: 	}
1.524     raeburn  2743: 	$nextflg = 1 if ($item eq $laststu);
1.41      ng       2744: 	if ($button eq 'Previous') {
1.524     raeburn  2745: 	    last if ($item eq $firststu);
                   2746: 	    push(@parsedlist,$item);
1.41      ng       2747: 	}
                   2748:     }
                   2749:     $ctr = 0;
                   2750:     @parsedlist = reverse @parsedlist if ($button eq 'Previous');
1.582     raeburn  2751:     my $res_error;
                   2752:     my ($partlist) = &response_type($symb,\$res_error);
                   2753:     if ($res_error) {
                   2754:         $request->print(&navmap_errormsg());
                   2755:         return;
                   2756:     }
1.41      ng       2757:     foreach my $student (@parsedlist) {
1.257     albertel 2758: 	my $submitonly=$env{'form.submitonly'};
1.41      ng       2759: 	my ($uname,$udom) = split(/:/,$student);
1.301     albertel 2760: 	
                   2761: 	if ($submitonly eq 'queued') {
                   2762: 	    my %queue_status = 
                   2763: 		&Apache::bridgetask::get_student_status($symb,$cdom,$cnum,
                   2764: 							$udom,$uname);
                   2765: 	    next if (!defined($queue_status{'gradingqueue'}));
                   2766: 	}
                   2767: 
1.156     albertel 2768: 	if ($submitonly =~ /^(yes|graded|incorrect)$/) {
1.257     albertel 2769: #	    my %record = &Apache::lonnet::restore($symb,$env{'request.course.id'},$udom,$uname);
1.324     albertel 2770: 	    my %status=&student_gradeStatus($symb,$udom,$uname,$partlist);
1.145     albertel 2771: 	    my $submitted = 0;
1.248     albertel 2772: 	    my $ungraded = 0;
                   2773: 	    my $incorrect = 0;
1.524     raeburn  2774: 	    foreach my $item (keys(%status)) {
                   2775: 		$submitted = 1 if ($status{$item} ne 'nothing');
                   2776: 		$ungraded = 1 if ($status{$item} =~ /^ungraded/);
                   2777: 		$incorrect = 1 if ($status{$item} =~ /^incorrect/);
                   2778: 		my ($foo,$partid,$foo1) = split(/\./,$item);
1.145     albertel 2779: 		if ($status{'resource.'.$partid.'.submitted_by'} ne '') {
                   2780: 		    $submitted = 0;
                   2781: 		}
1.41      ng       2782: 	    }
1.156     albertel 2783: 	    next if (!$submitted && ($submitonly eq 'yes' ||
                   2784: 				     $submitonly eq 'incorrect' ||
                   2785: 				     $submitonly eq 'graded'));
1.248     albertel 2786: 	    next if (!$ungraded && ($submitonly eq 'graded'));
                   2787: 	    next if (!$incorrect && $submitonly eq 'incorrect');
1.41      ng       2788: 	}
1.524     raeburn  2789: 	push(@nextlist,$student) if ($ctr < $ntstu);
1.129     ng       2790: 	last if ($ctr == $ntstu);
1.41      ng       2791: 	$ctr++;
                   2792:     }
1.36      ng       2793: 
1.41      ng       2794:     $ctr = 0;
                   2795:     my $total = scalar(@nextlist)-1;
1.39      ng       2796: 
1.524     raeburn  2797:     foreach (sort(@nextlist)) {
1.41      ng       2798: 	my ($uname,$udom,$submitter) = split(/:/);
1.257     albertel 2799: 	$env{'form.student'}  = $uname;
                   2800: 	$env{'form.userdom'}  = $udom;
                   2801: 	$env{'form.fullname'} = $$fullname{$_};
1.41      ng       2802: 	&submission($request,$ctr,$total);
                   2803: 	$ctr++;
                   2804:     }
                   2805:     if ($total < 0) {
1.485     albertel 2806: 	my $the_end = '<h3><span class="LC_info">'.&mt('LON-CAPA User Message').'</span></h3><br />'."\n";
                   2807: 	$the_end.=&mt('<b>Message: </b> No more students for this section or class.').'<br /><br />'."\n";
                   2808: 	$the_end.=&mt('Click on the button below to return to the grading menu.').'<br /><br />'."\n";
1.324     albertel 2809: 	$the_end.=&show_grading_menu_form($symb);
1.41      ng       2810: 	$request->print($the_end);
                   2811:     }
                   2812:     return '';
1.38      ng       2813: }
1.36      ng       2814: 
1.44      ng       2815: #---- Save the score and award for each student, if changed
1.38      ng       2816: sub saveHandGrade {
1.324     albertel 2817:     my ($request,$symb,$stuname,$domain,$newflg,$submitter,$part) = @_;
1.342     banghart 2818:     my @version_parts;
1.104     albertel 2819:     my $usec = &Apache::lonnet::getsection($domain,$stuname,
1.257     albertel 2820: 					   $env{'request.course.id'});
1.104     albertel 2821:     if (!&canmodify($usec)) { return('not_allowed'); }
1.337     banghart 2822:     my %record = &Apache::lonnet::restore($symb,$env{'request.course.id'},$domain,$stuname);
1.251     banghart 2823:     my @parts_graded;
1.77      ng       2824:     my %newrecord  = ();
                   2825:     my ($pts,$wgt) = ('','');
1.269     raeburn  2826:     my %aggregate = ();
                   2827:     my $aggregateflag = 0;
1.301     albertel 2828:     my @parts = split(/:/,$env{'form.partlist'.$newflg});
                   2829:     foreach my $new_part (@parts) {
1.337     banghart 2830: 	#collaborator ($submi may vary for different parts
1.259     banghart 2831: 	if ($submitter && $new_part ne $part) { next; }
                   2832: 	my $dropMenu = $env{'form.GD_SEL'.$newflg.'_'.$new_part};
1.125     ng       2833: 	if ($dropMenu eq 'excused') {
1.259     banghart 2834: 	    if ($record{'resource.'.$new_part.'.solved'} ne 'excused') {
                   2835: 		$newrecord{'resource.'.$new_part.'.solved'} = 'excused';
                   2836: 		if (exists($record{'resource.'.$new_part.'.awarded'})) {
                   2837: 		    $newrecord{'resource.'.$new_part.'.awarded'} = '';
1.58      albertel 2838: 		}
1.364     banghart 2839: 	        $newrecord{'resource.'.$new_part.'.regrader'}="$env{'user.name'}:$env{'user.domain'}";
1.58      albertel 2840: 	    }
1.125     ng       2841: 	} elsif ($dropMenu eq 'reset status'
1.259     banghart 2842: 		 && exists($record{'resource.'.$new_part.'.solved'})) { #don't bother if no old records -> no attempts
1.524     raeburn  2843: 	    foreach my $key (keys(%record)) {
1.259     banghart 2844: 		if ($key=~/^resource\.\Q$new_part\E\./) { $newrecord{$key} = ''; }
1.197     albertel 2845: 	    }
1.259     banghart 2846: 	    $newrecord{'resource.'.$new_part.'.regrader'}=
1.257     albertel 2847: 		"$env{'user.name'}:$env{'user.domain'}";
1.270     albertel 2848:             my $totaltries = $record{'resource.'.$part.'.tries'};
                   2849: 
                   2850:             my %last_resets = &get_last_resets($symb,$env{'request.course.id'},
                   2851: 					       [$new_part]);
                   2852:             my $aggtries =$totaltries;
1.269     raeburn  2853:             if ($last_resets{$new_part}) {
1.270     albertel 2854:                 $aggtries = &get_num_tries(\%record,$last_resets{$new_part},
                   2855: 					   $new_part);
1.269     raeburn  2856:             }
1.270     albertel 2857: 
                   2858:             my $solvedstatus = $record{'resource.'.$new_part.'.solved'};
1.269     raeburn  2859:             if ($aggtries > 0) {
1.327     albertel 2860:                 &decrement_aggs($symb,$new_part,\%aggregate,$aggtries,$totaltries,$solvedstatus);
1.269     raeburn  2861:                 $aggregateflag = 1;
                   2862:             }
1.125     ng       2863: 	} elsif ($dropMenu eq '') {
1.259     banghart 2864: 	    $pts = ($env{'form.GD_BOX'.$newflg.'_'.$new_part} ne '' ? 
                   2865: 		    $env{'form.GD_BOX'.$newflg.'_'.$new_part} : 
                   2866: 		    $env{'form.RADVAL'.$newflg.'_'.$new_part});
                   2867: 	    if ($pts eq '' && $env{'form.GD_SEL'.$newflg.'_'.$new_part} eq '') {
1.153     albertel 2868: 		next;
                   2869: 	    }
1.259     banghart 2870: 	    $wgt = $env{'form.WGT'.$newflg.'_'.$new_part} eq '' ? 1 : 
                   2871: 		$env{'form.WGT'.$newflg.'_'.$new_part};
1.41      ng       2872: 	    my $partial= $pts/$wgt;
1.259     banghart 2873: 	    if ($partial eq $record{'resource.'.$new_part.'.awarded'}) {
1.153     albertel 2874: 		#do not update score for part if not changed.
1.346     banghart 2875:                 &handback_files($request,$symb,$stuname,$domain,$newflg,$new_part,\%newrecord);
1.153     albertel 2876: 		next;
1.251     banghart 2877: 	    } else {
1.524     raeburn  2878: 	        push(@parts_graded,$new_part);
1.153     albertel 2879: 	    }
1.259     banghart 2880: 	    if ($record{'resource.'.$new_part.'.awarded'} ne $partial) {
                   2881: 		$newrecord{'resource.'.$new_part.'.awarded'}  = $partial;
1.153     albertel 2882: 	    }
1.259     banghart 2883: 	    my $reckey = 'resource.'.$new_part.'.solved';
1.41      ng       2884: 	    if ($partial == 0) {
1.153     albertel 2885: 		if ($record{$reckey} ne 'incorrect_by_override') {
                   2886: 		    $newrecord{$reckey} = 'incorrect_by_override';
                   2887: 		}
1.41      ng       2888: 	    } else {
1.153     albertel 2889: 		if ($record{$reckey} ne 'correct_by_override') {
                   2890: 		    $newrecord{$reckey} = 'correct_by_override';
                   2891: 		}
                   2892: 	    }	    
                   2893: 	    if ($submitter && 
1.259     banghart 2894: 		($record{'resource.'.$new_part.'.submitted_by'} ne $submitter)) {
                   2895: 		$newrecord{'resource.'.$new_part.'.submitted_by'} = $submitter;
1.41      ng       2896: 	    }
1.259     banghart 2897: 	    $newrecord{'resource.'.$new_part.'.regrader'}=
1.257     albertel 2898: 		"$env{'user.name'}:$env{'user.domain'}";
1.41      ng       2899: 	}
1.259     banghart 2900: 	# unless problem has been graded, set flag to version the submitted files
1.305     banghart 2901: 	unless ($record{'resource.'.$new_part.'.solved'} =~ /^correct_/  || 
                   2902: 	        $record{'resource.'.$new_part.'.solved'} eq 'incorrect_by_override' ||
                   2903: 	        $dropMenu eq 'reset status')
                   2904: 	   {
1.524     raeburn  2905: 	    push(@version_parts,$new_part);
1.259     banghart 2906: 	}
1.41      ng       2907:     }
1.301     albertel 2908:     my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   2909:     my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   2910: 
1.344     albertel 2911:     if (%newrecord) {
                   2912:         if (@version_parts) {
1.364     banghart 2913:             my @changed_keys = &version_portfiles(\%record, \@parts_graded, 
                   2914:                                 $env{'request.course.id'}, $symb, $domain, $stuname, \@version_parts);
1.344     albertel 2915: 	    @newrecord{@changed_keys} = @record{@changed_keys};
1.367     albertel 2916: 	    foreach my $new_part (@version_parts) {
                   2917: 		&handback_files($request,$symb,$stuname,$domain,$newflg,
                   2918: 				$new_part,\%newrecord);
                   2919: 	    }
1.259     banghart 2920:         }
1.44      ng       2921: 	&Apache::lonnet::cstore(\%newrecord,$symb,
1.257     albertel 2922: 				$env{'request.course.id'},$domain,$stuname);
1.380     albertel 2923: 	&check_and_remove_from_queue(\@parts,\%record,\%newrecord,$symb,
                   2924: 				     $cdom,$cnum,$domain,$stuname);
1.41      ng       2925:     }
1.269     raeburn  2926:     if ($aggregateflag) {
                   2927:         &Apache::lonnet::cinc('nohist_resourcetracker',\%aggregate,
1.301     albertel 2928: 			      $cdom,$cnum);
1.269     raeburn  2929:     }
1.301     albertel 2930:     return ('',$pts,$wgt);
1.36      ng       2931: }
1.322     albertel 2932: 
1.380     albertel 2933: sub check_and_remove_from_queue {
                   2934:     my ($parts,$record,$newrecord,$symb,$cdom,$cnum,$domain,$stuname) = @_;
                   2935:     my @ungraded_parts;
                   2936:     foreach my $part (@{$parts}) {
                   2937: 	if (    $record->{   'resource.'.$part.'.awarded'} eq ''
                   2938: 	     && $record->{   'resource.'.$part.'.solved' } ne 'excused'
                   2939: 	     && $newrecord->{'resource.'.$part.'.awarded'} eq ''
                   2940: 	     && $newrecord->{'resource.'.$part.'.solved' } ne 'excused'
                   2941: 		) {
                   2942: 	    push(@ungraded_parts, $part);
                   2943: 	}
                   2944:     }
                   2945:     if ( !@ungraded_parts ) {
                   2946: 	&Apache::bridgetask::remove_from_queue('gradingqueue',$symb,$cdom,
                   2947: 					       $cnum,$domain,$stuname);
                   2948:     }
                   2949: }
                   2950: 
1.337     banghart 2951: sub handback_files {
                   2952:     my ($request,$symb,$stuname,$domain,$newflg,$new_part,$newrecord) = @_;
1.517     raeburn  2953:     my $portfolio_root = '/userfiles/portfolio';
1.582     raeburn  2954:     my $res_error;
                   2955:     my ($partlist,$handgrade,$responseType) = &response_type($symb,\$res_error);
                   2956:     if ($res_error) {
                   2957:         $request->print('<br />'.&navmap_errormsg().'<br />');
                   2958:         return;
                   2959:     }
1.375     albertel 2960:     my @part_response_id = &flatten_responseType($responseType);
                   2961:     foreach my $part_response_id (@part_response_id) {
                   2962:     	my ($part_id,$resp_id) = @{ $part_response_id };
                   2963: 	my $part_resp = join('_',@{ $part_response_id });
1.337     banghart 2964:             if (($env{'form.'.$newflg.'_'.$part_resp.'_returndoc1'}) && ($new_part == $part_id)) {
                   2965:                 # if multiple files are uploaded names will be 'returndoc2','returndoc3'
                   2966:                 my $file_counter = 1;
1.367     albertel 2967: 		my $file_msg;
1.337     banghart 2968:                 while ($env{'form.'.$newflg.'_'.$part_resp.'_returndoc'.$file_counter}) {
                   2969:                     my $fname=$env{'form.'.$newflg.'_'.$part_resp.'_returndoc'.$file_counter.'.filename'};
1.338     banghart 2970:                     my ($directory,$answer_file) = 
                   2971:                         ($env{'form.'.$newflg.'_'.$part_resp.'_origdoc'.$file_counter} =~ /^(.*?)([^\/]*)$/);
                   2972:                     my ($answer_name,$answer_ver,$answer_ext) =
                   2973: 		        &file_name_version_ext($answer_file);
1.355     banghart 2974: 		    my ($portfolio_path) = ($directory =~ /^.+$stuname\/portfolio(.*)/);
1.517     raeburn  2975:                     my $getpropath = 1;
                   2976: 		    my @dir_list = &Apache::lonnet::dirlist($portfolio_root.$portfolio_path,$domain,$stuname,$getpropath);
1.338     banghart 2977: 		    my $version = &get_next_version($answer_name, $answer_ext, \@dir_list);
1.355     banghart 2978:                     # fix file name
                   2979:                     my ($save_file_name) = (($directory.$answer_name.".$version.".$answer_ext) =~ /^.+\/${stuname}\/(.*)/);
                   2980:                     my $result=&Apache::lonnet::finishuserfileupload($stuname,$domain,
                   2981:             	                                $newflg.'_'.$part_resp.'_returndoc'.$file_counter,
                   2982:             	                                $save_file_name);
1.337     banghart 2983:                     if ($result !~ m|^/uploaded/|) {
1.536     raeburn  2984:                         $request->print('<br /><span class="LC_error">'.
                   2985:                             &mt('An error occurred ([_1]) while trying to upload [_2].',
                   2986:                                 $result,$newflg.'_'.$part_resp.'_returndoc'.$file_counter).
                   2987:                                         '</span>');
1.356     banghart 2988:                     } else {
1.360     banghart 2989:                         # mark the file as read only
                   2990:                         my @files = ($save_file_name);
1.372     albertel 2991:                         my @what = ($symb,$env{'request.course.id'},'handback');
1.360     banghart 2992:                         &Apache::lonnet::mark_as_readonly($domain,$stuname,\@files,\@what);
1.367     albertel 2993: 			if (exists($$newrecord{"resource.$new_part.$resp_id.handback"})) {
                   2994: 			    $$newrecord{"resource.$new_part.$resp_id.handback"}.=',';
                   2995: 			}
                   2996:                         $$newrecord{"resource.$new_part.$resp_id.handback"} .= $save_file_name;
                   2997: 			$file_msg.= "\n".'<br /><span class="LC_filename"><a href="/uploaded/'."$domain/$stuname/".$save_file_name.'">'.$save_file_name."</a></span><br />";
                   2998: 
1.337     banghart 2999:                     }
                   3000:                     $request->print("<br />".$fname." will be the uploaded file name");
1.354     albertel 3001:                     $request->print(" ".$env{'form.'.$newflg.'_'.$part_resp.'_origdoc'.$file_counter});
1.337     banghart 3002:                     $file_counter++;
                   3003:                 }
1.367     albertel 3004: 		my $subject = "File Handed Back by Instructor ";
                   3005: 		my $message = "A file has been returned that was originally submitted in reponse to: <br />";
                   3006: 		$message .= "<strong>".&Apache::lonnet::gettitle($symb)."</strong><br />";
                   3007: 		$message .= ' The returned file(s) are named: '. $file_msg;
                   3008: 		$message .= " and can be found in your portfolio space.";
1.418     albertel 3009: 		my ($feedurl,$showsymb) = 
                   3010: 		    &get_feedurl_and_symb($symb,$domain,$stuname);
1.386     raeburn  3011:                 my $restitle = &Apache::lonnet::gettitle($symb);
                   3012: 		my $msgstatus = 
                   3013:                    &Apache::lonmsg::user_normal_msg($stuname,$domain,$subject.
                   3014: 			 ' (File Returned) ['.$restitle.']',$message,undef,
1.418     albertel 3015:                          $feedurl,undef,undef,undef,$showsymb,$restitle);
1.337     banghart 3016:             }
                   3017:         }
1.338     banghart 3018:     return;
1.337     banghart 3019: }
                   3020: 
1.418     albertel 3021: sub get_feedurl_and_symb {
                   3022:     my ($symb,$uname,$udom) = @_;
                   3023:     my (undef,undef,$url) = &Apache::lonnet::decode_symb($symb);
                   3024:     $url = &Apache::lonnet::clutter($url);
                   3025:     my $encrypturl=&Apache::lonnet::EXT('resource.0.encrypturl',
                   3026: 					$symb,$udom,$uname);
                   3027:     if ($encrypturl =~ /^yes$/i) {
                   3028: 	&Apache::lonenc::encrypted(\$url,1);
                   3029: 	&Apache::lonenc::encrypted(\$symb,1);
                   3030:     }
                   3031:     return ($url,$symb);
                   3032: }
                   3033: 
1.313     banghart 3034: sub get_submitted_files {
                   3035:     my ($udom,$uname,$partid,$respid,$record) = @_;
                   3036:     my @files;
                   3037:     if ($$record{"resource.$partid.$respid.portfiles"}) {
                   3038:         my $file_url = '/uploaded/'.$udom.'/'.$uname.'/portfolio';
                   3039:         foreach my $file (split(',',$$record{"resource.$partid.$respid.portfiles"})) {
                   3040:     	    push(@files,$file_url.$file);
                   3041:         }
                   3042:     }
                   3043:     if ($$record{"resource.$partid.$respid.uploadedurl"}) {
                   3044:         push(@files,$$record{"resource.$partid.$respid.uploadedurl"});
                   3045:     }
                   3046:     return (\@files);
                   3047: }
1.322     albertel 3048: 
1.269     raeburn  3049: # ----------- Provides number of tries since last reset.
                   3050: sub get_num_tries {
                   3051:     my ($record,$last_reset,$part) = @_;
                   3052:     my $timestamp = '';
                   3053:     my $num_tries = 0;
                   3054:     if ($$record{'version'}) {
                   3055:         for (my $version=$$record{'version'};$version>=1;$version--) {
                   3056:             if (exists($$record{$version.':resource.'.$part.'.solved'})) {
                   3057:                 $timestamp = $$record{$version.':timestamp'};
                   3058:                 if ($timestamp > $last_reset) {
                   3059:                     $num_tries ++;
                   3060:                 } else {
                   3061:                     last;
                   3062:                 }
                   3063:             }
                   3064:         }
                   3065:     }
                   3066:     return $num_tries;
                   3067: }
                   3068: 
                   3069: # ----------- Determine decrements required in aggregate totals 
                   3070: sub decrement_aggs {
                   3071:     my ($symb,$part,$aggregate,$aggtries,$totaltries,$solvedstatus) = @_;
                   3072:     my %decrement = (
                   3073:                         attempts => 0,
                   3074:                         users => 0,
                   3075:                         correct => 0
                   3076:                     );
                   3077:     $decrement{'attempts'} = $aggtries;
                   3078:     if ($solvedstatus =~ /^correct/) {
                   3079:         $decrement{'correct'} = 1;
                   3080:     }
                   3081:     if ($aggtries == $totaltries) {
                   3082:         $decrement{'users'} = 1;
                   3083:     }
1.524     raeburn  3084:     foreach my $type (keys(%decrement)) {
1.269     raeburn  3085:         $$aggregate{$symb."\0".$part."\0".$type} = -$decrement{$type};
                   3086:     }
                   3087:     return;
                   3088: }
                   3089: 
                   3090: # ----------- Determine timestamps for last reset of aggregate totals for parts  
                   3091: sub get_last_resets {
1.270     albertel 3092:     my ($symb,$courseid,$partids) =@_;
                   3093:     my %last_resets;
1.269     raeburn  3094:     my $cdom = $env{'course.'.$courseid.'.domain'};
                   3095:     my $cname = $env{'course.'.$courseid.'.num'};
1.271     albertel 3096:     my @keys;
                   3097:     foreach my $part (@{$partids}) {
                   3098: 	push(@keys,"$symb\0$part\0resettime");
                   3099:     }
                   3100:     my %results=&Apache::lonnet::get('nohist_resourcetracker',\@keys,
                   3101: 				     $cdom,$cname);
                   3102:     foreach my $part (@{$partids}) {
                   3103: 	$last_resets{$part}=$results{"$symb\0$part\0resettime"};
1.269     raeburn  3104:     }
1.270     albertel 3105:     return %last_resets;
1.269     raeburn  3106: }
                   3107: 
1.251     banghart 3108: # ----------- Handles creating versions for portfolio files as answers
                   3109: sub version_portfiles {
1.343     banghart 3110:     my ($record, $parts_graded, $courseid, $symb, $domain, $stu_name, $v_flag) = @_;
1.263     banghart 3111:     my $version_parts = join('|',@$v_flag);
1.343     banghart 3112:     my @returned_keys;
1.255     banghart 3113:     my $parts = join('|', @$parts_graded);
1.517     raeburn  3114:     my $portfolio_root = '/userfiles/portfolio';
1.277     albertel 3115:     foreach my $key (keys(%$record)) {
1.259     banghart 3116:         my $new_portfiles;
1.263     banghart 3117:         if ($key =~ /^resource\.($version_parts)\./ && $key =~ /\.portfiles$/ ) {
1.342     banghart 3118:             my @versioned_portfiles;
1.367     albertel 3119:             my @portfiles = split(/\s*,\s*/,$$record{$key});
1.252     banghart 3120:             foreach my $file (@portfiles) {
1.306     banghart 3121:                 &Apache::lonnet::unmark_as_readonly($domain,$stu_name,[$symb,$env{'request.course.id'}],$file);
1.304     albertel 3122:                 my ($directory,$answer_file) =($file =~ /^(.*?)([^\/]*)$/);
                   3123: 		my ($answer_name,$answer_ver,$answer_ext) =
                   3124: 		    &file_name_version_ext($answer_file);
1.517     raeburn  3125:                 my $getpropath = 1;    
                   3126:                 my @dir_list = &Apache::lonnet::dirlist($portfolio_root.$directory,$domain,$stu_name,$getpropath);
1.342     banghart 3127:                 my $version = &get_next_version($answer_name, $answer_ext, \@dir_list);
1.306     banghart 3128:                 my $new_answer = &version_selected_portfile($domain, $stu_name, $directory, $answer_file, $version);
                   3129:                 if ($new_answer ne 'problem getting file') {
1.342     banghart 3130:                     push(@versioned_portfiles, $directory.$new_answer);
1.306     banghart 3131:                     &Apache::lonnet::mark_as_readonly($domain,$stu_name,
1.367     albertel 3132:                         [$directory.$new_answer],
1.306     banghart 3133:                         [$symb,$env{'request.course.id'},'graded']);
1.259     banghart 3134:                 }
1.252     banghart 3135:             }
1.343     banghart 3136:             $$record{$key} = join(',',@versioned_portfiles);
                   3137:             push(@returned_keys,$key);
1.251     banghart 3138:         }
                   3139:     } 
1.343     banghart 3140:     return (@returned_keys);   
1.305     banghart 3141: }
                   3142: 
1.307     banghart 3143: sub get_next_version {
1.341     banghart 3144:     my ($answer_name, $answer_ext, $dir_list) = @_;
1.307     banghart 3145:     my $version;
                   3146:     foreach my $row (@$dir_list) {
                   3147:         my ($file) = split(/\&/,$row,2);
                   3148:         my ($file_name,$file_version,$file_ext) =
                   3149: 	    &file_name_version_ext($file);
                   3150:         if (($file_name eq $answer_name) && 
                   3151: 	    ($file_ext eq $answer_ext)) {
                   3152:                 # gets here if filename and extension match, regardless of version
                   3153:                 if ($file_version ne '') {
                   3154:                 # a versioned file is found  so save it for later
                   3155:                 if ($file_version > $version) {
                   3156: 		    $version = $file_version;
                   3157: 	        }
                   3158:             }
                   3159:         }
                   3160:     } 
                   3161:     $version ++;
                   3162:     return($version);
                   3163: }
                   3164: 
1.305     banghart 3165: sub version_selected_portfile {
1.306     banghart 3166:     my ($domain,$stu_name,$directory,$file_name,$version) = @_;
                   3167:     my ($answer_name,$answer_ver,$answer_ext) =
                   3168:         &file_name_version_ext($file_name);
                   3169:     my $new_answer;
                   3170:     $env{'form.copy'} = &Apache::lonnet::getfile("/uploaded/$domain/$stu_name/portfolio$directory$file_name");
                   3171:     if($env{'form.copy'} eq '-1') {
                   3172:         $new_answer = 'problem getting file';
                   3173:     } else {
                   3174:         $new_answer = $answer_name.'.'.$version.'.'.$answer_ext;
                   3175:         my $copy_result = &Apache::lonnet::finishuserfileupload(
                   3176:                             $stu_name,$domain,'copy',
                   3177: 		        '/portfolio'.$directory.$new_answer);
                   3178:     }    
                   3179:     return ($new_answer);
1.251     banghart 3180: }
                   3181: 
1.304     albertel 3182: sub file_name_version_ext {
                   3183:     my ($file)=@_;
                   3184:     my @file_parts = split(/\./, $file);
                   3185:     my ($name,$version,$ext);
                   3186:     if (@file_parts > 1) {
                   3187: 	$ext=pop(@file_parts);
                   3188: 	if (@file_parts > 1 && $file_parts[-1] =~ /^\d+$/) {
                   3189: 	    $version=pop(@file_parts);
                   3190: 	}
                   3191: 	$name=join('.',@file_parts);
                   3192:     } else {
                   3193: 	$name=join('.',@file_parts);
                   3194:     }
                   3195:     return($name,$version,$ext);
                   3196: }
                   3197: 
1.44      ng       3198: #--------------------------------------------------------------------------------------
                   3199: #
                   3200: #-------------------------- Next few routines handles grading by section or whole class
                   3201: #
                   3202: #--- Javascript to handle grading by section or whole class
1.42      ng       3203: sub viewgrades_js {
                   3204:     my ($request) = shift;
                   3205: 
1.539     riegler  3206:     my $alertmsg = &mt('A number equal or greater than 0 is expected. Entered value = ');
1.41      ng       3207:     $request->print(<<VIEWJAVASCRIPT);
                   3208: <script type="text/javascript" language="javascript">
1.45      ng       3209:    function writePoint(partid,weight,point) {
1.125     ng       3210: 	var radioButton = document.classgrade["RADVAL_"+partid];
                   3211: 	var textbox = document.classgrade["TEXTVAL_"+partid];
1.42      ng       3212: 	if (point == "textval") {
1.125     ng       3213: 	    point = document.classgrade["TEXTVAL_"+partid].value;
1.109     matthew  3214: 	    if (isNaN(point) || parseFloat(point) < 0) {
1.539     riegler  3215: 		alert("$alertmsg"+parseFloat(point));
1.42      ng       3216: 		var resetbox = false;
                   3217: 		for (var i=0; i<radioButton.length; i++) {
                   3218: 		    if (radioButton[i].checked) {
                   3219: 			textbox.value = i;
                   3220: 			resetbox = true;
                   3221: 		    }
                   3222: 		}
                   3223: 		if (!resetbox) {
                   3224: 		    textbox.value = "";
                   3225: 		}
                   3226: 		return;
                   3227: 	    }
1.109     matthew  3228: 	    if (parseFloat(point) > parseFloat(weight)) {
                   3229: 		var resp = confirm("You entered a value ("+parseFloat(point)+
1.44      ng       3230: 				   ") greater than the weight for the part. Accept?");
                   3231: 		if (resp == false) {
                   3232: 		    textbox.value = "";
                   3233: 		    return;
                   3234: 		}
                   3235: 	    }
1.42      ng       3236: 	    for (var i=0; i<radioButton.length; i++) {
                   3237: 		radioButton[i].checked=false;
1.109     matthew  3238: 		if (parseFloat(point) == i) {
1.42      ng       3239: 		    radioButton[i].checked=true;
                   3240: 		}
                   3241: 	    }
1.41      ng       3242: 
1.42      ng       3243: 	} else {
1.125     ng       3244: 	    textbox.value = parseFloat(point);
1.42      ng       3245: 	}
1.41      ng       3246: 	for (i=0;i<document.classgrade.total.value;i++) {
1.125     ng       3247: 	    var user = document.classgrade["ctr"+i].value;
1.289     albertel 3248: 	    user = user.replace(new RegExp(':', 'g'),"_");
1.125     ng       3249: 	    var scorename = document.classgrade["GD_"+user+"_"+partid+"_awarded"];
                   3250: 	    var saveval   = document.classgrade["GD_"+user+"_"+partid+"_solved_s"].value;
                   3251: 	    var selname   = document.classgrade["GD_"+user+"_"+partid+"_solved"];
1.42      ng       3252: 	    if (saveval != "correct") {
                   3253: 		scorename.value = point;
1.43      ng       3254: 		if (selname[0].selected != true) {
                   3255: 		    selname[0].selected = true;
                   3256: 		}
1.42      ng       3257: 	    }
                   3258: 	}
1.125     ng       3259: 	document.classgrade["SELVAL_"+partid][0].selected = true;
1.42      ng       3260:     }
                   3261: 
                   3262:     function writeRadText(partid,weight) {
1.125     ng       3263: 	var selval   = document.classgrade["SELVAL_"+partid];
                   3264: 	var radioButton = document.classgrade["RADVAL_"+partid];
1.265     www      3265:         var override = document.classgrade["FORCE_"+partid].checked;
1.125     ng       3266: 	var textbox = document.classgrade["TEXTVAL_"+partid];
                   3267: 	if (selval[1].selected || selval[2].selected) {
1.42      ng       3268: 	    for (var i=0; i<radioButton.length; i++) {
                   3269: 		radioButton[i].checked=false;
                   3270: 
                   3271: 	    }
                   3272: 	    textbox.value = "";
                   3273: 
                   3274: 	    for (i=0;i<document.classgrade.total.value;i++) {
1.125     ng       3275: 		var user = document.classgrade["ctr"+i].value;
1.289     albertel 3276: 		user = user.replace(new RegExp(':', 'g'),"_");
1.125     ng       3277: 		var scorename = document.classgrade["GD_"+user+"_"+partid+"_awarded"];
                   3278: 		var saveval   = document.classgrade["GD_"+user+"_"+partid+"_solved_s"].value;
                   3279: 		var selname   = document.classgrade["GD_"+user+"_"+partid+"_solved"];
1.265     www      3280: 		if ((saveval != "correct") || override) {
1.42      ng       3281: 		    scorename.value = "";
1.125     ng       3282: 		    if (selval[1].selected) {
                   3283: 			selname[1].selected = true;
                   3284: 		    } else {
                   3285: 			selname[2].selected = true;
                   3286: 			if (Number(document.classgrade["GD_"+user+"_"+partid+"_tries"].value)) 
                   3287: 			{document.classgrade["GD_"+user+"_"+partid+"_tries"].value = '0';}
                   3288: 		    }
1.42      ng       3289: 		}
                   3290: 	    }
1.43      ng       3291: 	} else {
                   3292: 	    for (i=0;i<document.classgrade.total.value;i++) {
1.125     ng       3293: 		var user = document.classgrade["ctr"+i].value;
1.289     albertel 3294: 		user = user.replace(new RegExp(':', 'g'),"_");
1.125     ng       3295: 		var scorename = document.classgrade["GD_"+user+"_"+partid+"_awarded"];
                   3296: 		var saveval   = document.classgrade["GD_"+user+"_"+partid+"_solved_s"].value;
                   3297: 		var selname   = document.classgrade["GD_"+user+"_"+partid+"_solved"];
1.265     www      3298: 		if ((saveval != "correct") || override) {
1.125     ng       3299: 		    scorename.value = document.classgrade["GD_"+user+"_"+partid+"_awarded_s"].value;
1.43      ng       3300: 		    selname[0].selected = true;
                   3301: 		}
                   3302: 	    }
                   3303: 	}	    
1.42      ng       3304:     }
                   3305: 
                   3306:     function changeSelect(partid,user) {
1.125     ng       3307: 	var selval = document.classgrade["GD_"+user+'_'+partid+"_solved"];
                   3308: 	var textbox = document.classgrade["GD_"+user+'_'+partid+"_awarded"];
1.44      ng       3309: 	var point  = textbox.value;
1.125     ng       3310: 	var weight = document.classgrade["weight_"+partid].value;
1.44      ng       3311: 
1.109     matthew  3312: 	if (isNaN(point) || parseFloat(point) < 0) {
1.539     riegler  3313: 	    alert("$alertmsg"+parseFloat(point));
1.44      ng       3314: 	    textbox.value = "";
                   3315: 	    return;
                   3316: 	}
1.109     matthew  3317: 	if (parseFloat(point) > parseFloat(weight)) {
                   3318: 	    var resp = confirm("You entered a value ("+parseFloat(point)+
1.44      ng       3319: 			       ") greater than the weight of the part. Accept?");
                   3320: 	    if (resp == false) {
                   3321: 		textbox.value = "";
                   3322: 		return;
                   3323: 	    }
                   3324: 	}
1.42      ng       3325: 	selval[0].selected = true;
                   3326:     }
                   3327: 
                   3328:     function changeOneScore(partid,user) {
1.125     ng       3329: 	var selval = document.classgrade["GD_"+user+'_'+partid+"_solved"];
                   3330: 	if (selval[1].selected || selval[2].selected) {
                   3331: 	    document.classgrade["GD_"+user+'_'+partid+"_awarded"].value = "";
                   3332: 	    if (selval[2].selected) {
                   3333: 		document.classgrade["GD_"+user+'_'+partid+"_tries"].value = "0";
                   3334: 	    }
1.269     raeburn  3335:         }
1.42      ng       3336:     }
                   3337: 
                   3338:     function resetEntry(numpart) {
                   3339: 	for (ctpart=0;ctpart<numpart;ctpart++) {
1.125     ng       3340: 	    var partid = document.classgrade["partid_"+ctpart].value;
                   3341: 	    var radioButton = document.classgrade["RADVAL_"+partid];
                   3342: 	    var textbox = document.classgrade["TEXTVAL_"+partid];
                   3343: 	    var selval  = document.classgrade["SELVAL_"+partid];
1.42      ng       3344: 	    for (var i=0; i<radioButton.length; i++) {
                   3345: 		radioButton[i].checked=false;
                   3346: 
                   3347: 	    }
                   3348: 	    textbox.value = "";
                   3349: 	    selval[0].selected = true;
                   3350: 
                   3351: 	    for (i=0;i<document.classgrade.total.value;i++) {
1.125     ng       3352: 		var user = document.classgrade["ctr"+i].value;
1.289     albertel 3353: 		user = user.replace(new RegExp(':', 'g'),"_");
1.125     ng       3354: 		var resetscore = document.classgrade["GD_"+user+"_"+partid+"_awarded"];
                   3355: 		resetscore.value = document.classgrade["GD_"+user+"_"+partid+"_awarded_s"].value;
                   3356: 		var resettries = document.classgrade["GD_"+user+"_"+partid+"_tries"];
                   3357: 		resettries.value = document.classgrade["GD_"+user+"_"+partid+"_tries_s"].value;
                   3358: 		var saveselval   = document.classgrade["GD_"+user+"_"+partid+"_solved_s"].value;
                   3359: 		var selname   = document.classgrade["GD_"+user+"_"+partid+"_solved"];
1.42      ng       3360: 		if (saveselval == "excused") {
1.43      ng       3361: 		    if (selname[1].selected == false) { selname[1].selected = true;}
1.42      ng       3362: 		} else {
1.43      ng       3363: 		    if (selname[0].selected == false) {selname[0].selected = true};
1.42      ng       3364: 		}
                   3365: 	    }
1.41      ng       3366: 	}
1.42      ng       3367:     }
                   3368: 
1.41      ng       3369: </script>
                   3370: VIEWJAVASCRIPT
1.42      ng       3371: }
                   3372: 
1.44      ng       3373: #--- show scores for a section or whole class w/ option to change/update a score
1.42      ng       3374: sub viewgrades {
                   3375:     my ($request) = shift;
                   3376:     &viewgrades_js($request);
1.41      ng       3377: 
1.324     albertel 3378:     my ($symb) = &get_symb($request);
1.168     albertel 3379:     #need to make sure we have the correct data for later EXT calls, 
                   3380:     #thus invalidate the cache
                   3381:     &Apache::lonnet::devalidatecourseresdata(
1.257     albertel 3382:                  $env{'course.'.$env{'request.course.id'}.'.num'},
                   3383:                  $env{'course.'.$env{'request.course.id'}.'.domain'});
1.168     albertel 3384:     &Apache::lonnet::clear_EXT_cache_status();
                   3385: 
1.398     albertel 3386:     my $result='<h3><span class="LC_info">'.&mt('Manual Grading').'</span></h3>';
1.485     albertel 3387:     $result.='<h4>'.&mt('<b>Current Resource: </b>[_1]',$env{'form.probTitle'}).'</h4>'."\n";
1.41      ng       3388: 
                   3389:     #view individual student submission form - called using Javascript viewOneStudent
1.324     albertel 3390:     $result.=&jscriptNform($symb);
1.41      ng       3391: 
1.44      ng       3392:     #beginning of class grading form
1.442     banghart 3393:     my $stu_status = join(':',&Apache::loncommon::get_env_multiple('form.Status'));
1.41      ng       3394:     $result.= '<form action="/adm/grades" method="post" name="classgrade">'."\n".
1.418     albertel 3395: 	'<input type="hidden" name="symb"    value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
1.38      ng       3396: 	'<input type="hidden" name="command" value="editgrades" />'."\n".
1.432     banghart 3397: 	&build_section_inputs().
1.257     albertel 3398: 	'<input type="hidden" name="saveState" value="'.$env{'form.saveState'}.'" />'."\n".
1.442     banghart 3399: 	'<input type="hidden" name="Status" value="'.$env{'stu_status'}.'" />'."\n".
1.257     albertel 3400: 	'<input type="hidden" name="probTitle" value="'.$env{'form.probTitle'}.'" />'."\n";
1.72      ng       3401: 
1.560     raeburn  3402:     my ($common_header,$specific_header);
1.257     albertel 3403:     if ($env{'form.section'} eq 'all') {
1.560     raeburn  3404: 	$common_header = &mt('Assign Common Grade to Class');
                   3405:         $specific_header = &mt('Assign Grade to Specific Students in Class');
1.257     albertel 3406:     } elsif ($env{'form.section'} eq 'none') {
1.560     raeburn  3407:         $common_header = &mt('Assign Common Grade to Students in no Section');
                   3408: 	$specific_header = &mt('Assign Grade to Specific Students in no Section');
1.52      albertel 3409:     } else {
1.560     raeburn  3410:         my $section_display = join (", ",&Apache::loncommon::get_env_multiple('form.section'));
                   3411:         $common_header = &mt('Assign Common Grade to Students in Section(s) [_1]',$section_display);
                   3412: 	$specific_header = &mt('Assign Grade to Specific Students in Section(s) [_1]',$section_display);
1.52      albertel 3413:     }
1.560     raeburn  3414:     $result.= '<h3>'.$common_header.'</h3>'.&Apache::loncommon::start_data_table();
1.44      ng       3415:     #radio buttons/text box for assigning points for a section or class.
                   3416:     #handles different parts of a problem
1.582     raeburn  3417:     my $res_error;
                   3418:     my ($partlist,$handgrade,$responseType) = &response_type($symb,\$res_error);
                   3419:     if ($res_error) {
                   3420:         return &navmap_errormsg();
                   3421:     }
1.42      ng       3422:     my %weight = ();
                   3423:     my $ctsparts = 0;
1.45      ng       3424:     my %seen = ();
1.375     albertel 3425:     my @part_response_id = &flatten_responseType($responseType);
                   3426:     foreach my $part_response_id (@part_response_id) {
                   3427:     	my ($partid,$respid) = @{ $part_response_id };
                   3428: 	my $part_resp = join('_',@{ $part_response_id });
1.45      ng       3429: 	next if $seen{$partid};
                   3430: 	$seen{$partid}++;
1.375     albertel 3431: 	my $handgrade=$$handgrade{$part_resp};
1.42      ng       3432: 	my $wgt = &Apache::lonnet::EXT('resource.'.$partid.'.weight',$symb);
                   3433: 	$weight{$partid} = $wgt eq '' ? '1' : $wgt;
                   3434: 
1.324     albertel 3435: 	my $display_part=&get_display_part($partid,$symb);
1.485     albertel 3436: 	my $radio.='<table border="0"><tr>';  
1.41      ng       3437: 	my $ctr = 0;
1.42      ng       3438: 	while ($ctr<=$weight{$partid}) { # display radio buttons in a nice table 10 across
1.485     albertel 3439: 	    $radio.= '<td><label><input type="radio" name="RADVAL_'.$partid.'" '.
1.54      albertel 3440: 		'onclick="javascript:writePoint(\''.$partid.'\','.$weight{$partid}.
1.288     albertel 3441: 		','.$ctr.')" />'.$ctr."</label></td>\n";
1.41      ng       3442: 	    $result.=(($ctr+1)%10 == 0 ? '</tr><tr>' : '');
                   3443: 	    $ctr++;
                   3444: 	}
1.485     albertel 3445: 	$radio.='</tr></table>';
                   3446: 	my $line = '<input type="text" name="TEXTVAL_'.
1.589     bisitz   3447: 	    $partid.'" size="4" '.'onchange="javascript:writePoint(\''.
1.54      albertel 3448: 		$partid.'\','.$weight{$partid}.',\'textval\')" /> /'.
1.539     riegler  3449: 	    $weight{$partid}.' '.&mt('(problem weight)').'</td>'."\n";
                   3450: 	$line.= '<td><b>'.&mt('Grade Status').':</b><select name="SELVAL_'.$partid.'"'.
1.589     bisitz   3451: 	    'onchange="javascript:writeRadText(\''.$partid.'\','.
1.59      albertel 3452: 		$weight{$partid}.')"> '.
1.401     albertel 3453: 	    '<option selected="selected"> </option>'.
1.485     albertel 3454: 	    '<option value="excused">'.&mt('excused').'</option>'.
                   3455: 	    '<option value="reset status">'.&mt('reset status').'</option>'.
                   3456: 	    '</select></td>'.
                   3457:             '<td><label><input type="checkbox" name="FORCE_'.$partid.'" />'.&mt('Override "Correct"').'</label>';
                   3458: 	$line.='<input type="hidden" name="partid_'.
                   3459: 	    $ctsparts.'" value="'.$partid.'" />'."\n";
                   3460: 	$line.='<input type="hidden" name="weight_'.
                   3461: 	    $partid.'" value="'.$weight{$partid}.'" />'."\n";
                   3462: 
                   3463: 	$result.=
                   3464: 	    &Apache::loncommon::start_data_table_row()."\n".
1.577     bisitz   3465: 	    '<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 3466: 	    &Apache::loncommon::end_data_table_row()."\n";
1.42      ng       3467: 	$ctsparts++;
1.41      ng       3468:     }
1.474     albertel 3469:     $result.=&Apache::loncommon::end_data_table()."\n".
1.52      albertel 3470: 	'<input type="hidden" name="totalparts" value="'.$ctsparts.'" />';
1.485     albertel 3471:     $result.='<input type="button" value="'.&mt('Revert to Default').'" '.
1.589     bisitz   3472: 	'onclick="javascript:resetEntry('.$ctsparts.');" />';
1.41      ng       3473: 
1.44      ng       3474:     #table listing all the students in a section/class
                   3475:     #header of table
1.560     raeburn  3476:     $result.= '<h3>'.$specific_header.'</h3>'.
                   3477:               &Apache::loncommon::start_data_table().
                   3478: 	      &Apache::loncommon::start_data_table_header_row().
                   3479: 	      '<th>'.&mt('No.').'</th>'.
                   3480: 	      '<th>'.&nameUserString('header')."</th>\n";
1.582     raeburn  3481:     my $partserror;
                   3482:     my (@parts) = sort(&getpartlist($symb,\$partserror));
                   3483:     if ($partserror) {
                   3484:         return &navmap_errormsg();
                   3485:     }
1.324     albertel 3486:     my (undef,undef,$url)=&Apache::lonnet::decode_symb($symb);
1.269     raeburn  3487:     my @partids = ();
1.41      ng       3488:     foreach my $part (@parts) {
                   3489: 	my $display=&Apache::lonnet::metadata($url,$part.'.display');
1.539     riegler  3490:         my $narrowtext = &mt('Tries');
                   3491: 	$display =~ s|^Number of Attempts|$narrowtext <br />|; # makes the column narrower
1.41      ng       3492: 	if  (!$display) { $display = &Apache::lonnet::metadata($url,$part.'.name'); }
1.207     albertel 3493: 	my ($partid) = &split_part_type($part);
1.524     raeburn  3494:         push(@partids,$partid);
1.324     albertel 3495: 	my $display_part=&get_display_part($partid,$symb);
1.41      ng       3496: 	if ($display =~ /^Partial Credit Factor/) {
1.485     albertel 3497: 	    $result.='<th>'.
                   3498: 		&mt('Score Part: [_1]<br /> (weight = [_2])',
                   3499: 		    $display_part,$weight{$partid}).'</th>'."\n";
1.41      ng       3500: 	    next;
1.485     albertel 3501: 	    
1.207     albertel 3502: 	} else {
1.485     albertel 3503: 	    if ($display =~ /Problem Status/) {
                   3504: 		my $grade_status_mt = &mt('Grade Status');
                   3505: 		$display =~ s{Problem Status}{$grade_status_mt<br />};
                   3506: 	    }
                   3507: 	    my $part_mt = &mt('Part:');
                   3508: 	    $display =~s{\[Part: \Q$partid\E\]}{$part_mt $display_part};
1.41      ng       3509: 	}
1.485     albertel 3510: 
1.474     albertel 3511: 	$result.='<th>'.$display.'</th>'."\n";
1.41      ng       3512:     }
1.474     albertel 3513:     $result.=&Apache::loncommon::end_data_table_header_row();
1.44      ng       3514: 
1.270     albertel 3515:     my %last_resets = 
                   3516: 	&get_last_resets($symb,$env{'request.course.id'},\@partids);
1.269     raeburn  3517: 
1.41      ng       3518:     #get info for each student
1.44      ng       3519:     #list all the students - with points and grade status
1.257     albertel 3520:     my (undef,undef,$fullname) = &getclasslist($env{'form.section'},'1');
1.41      ng       3521:     my $ctr = 0;
1.294     albertel 3522:     foreach (sort 
                   3523: 	     {
                   3524: 		 if (lc($$fullname{$a}) ne lc($$fullname{$b})) {
                   3525: 		     return (lc($$fullname{$a}) cmp lc($$fullname{$b}));
                   3526: 		 }
                   3527: 		 return $a cmp $b;
                   3528: 	     } (keys(%$fullname))) {
1.126     ng       3529: 	$ctr++;
1.324     albertel 3530: 	$result.=&viewstudentgrade($symb,$env{'request.course.id'},
1.269     raeburn  3531: 				   $_,$$fullname{$_},\@parts,\%weight,$ctr,\%last_resets);
1.41      ng       3532:     }
1.474     albertel 3533:     $result.=&Apache::loncommon::end_data_table();
1.41      ng       3534:     $result.='<input type="hidden" name="total" value="'.$ctr.'" />'."\n";
1.485     albertel 3535:     $result.='<input type="button" value="'.&mt('Save').'" '.
1.589     bisitz   3536: 	'onclick="javascript:submit();" target="_self" /></form>'."\n";
1.96      albertel 3537:     if (scalar(%$fullname) eq 0) {
                   3538: 	my $colspan=3+scalar(@parts);
1.433     banghart 3539: 	my $section_display = join (", ",&Apache::loncommon::get_env_multiple('form.section'));
1.442     banghart 3540:         my $stu_status = join(' or ',&Apache::loncommon::get_env_multiple('form.Status'));
1.433     banghart 3541: 	$result='<span class="LC_warning">'.
1.485     albertel 3542: 	    &mt('There are no students in section(s) [_1] with enrollment status [_2] to modify or grade.',
1.442     banghart 3543: 	        $section_display, $stu_status).
1.433     banghart 3544: 	    '</span>';
1.96      albertel 3545:     }
1.324     albertel 3546:     $result.=&show_grading_menu_form($symb);
1.41      ng       3547:     return $result;
                   3548: }
                   3549: 
1.44      ng       3550: #--- call by previous routine to display each student
1.41      ng       3551: sub viewstudentgrade {
1.324     albertel 3552:     my ($symb,$courseid,$student,$fullname,$parts,$weight,$ctr,$last_resets) = @_;
1.44      ng       3553:     my ($uname,$udom) = split(/:/,$student);
                   3554:     my %record=&Apache::lonnet::restore($symb,$courseid,$udom,$uname);
1.269     raeburn  3555:     my %aggregates = (); 
1.474     albertel 3556:     my $result=&Apache::loncommon::start_data_table_row().'<td align="right">'.
1.233     albertel 3557: 	'<input type="hidden" name="ctr'.($ctr-1).'" value="'.$student.'" />'.
                   3558: 	"\n".$ctr.'&nbsp;</td><td>&nbsp;'.
1.44      ng       3559: 	'<a href="javascript:viewOneStudent(\''.$uname.'\',\''.$udom.
1.417     albertel 3560: 	'\');" target="_self">'.$fullname.'</a> '.
1.398     albertel 3561: 	'<span class="LC_internal_info">('.$uname.($env{'user.domain'} eq $udom ? '' : ':'.$udom).')</span></td>'."\n";
1.281     albertel 3562:     $student=~s/:/_/; # colon doen't work in javascript for names
1.63      albertel 3563:     foreach my $apart (@$parts) {
                   3564: 	my ($part,$type) = &split_part_type($apart);
1.41      ng       3565: 	my $score=$record{"resource.$part.$type"};
1.276     albertel 3566:         $result.='<td align="center">';
1.269     raeburn  3567:         my ($aggtries,$totaltries);
                   3568:         unless (exists($aggregates{$part})) {
1.270     albertel 3569: 	    $totaltries = $record{'resource.'.$part.'.tries'};
                   3570: 
                   3571: 	    $aggtries = $totaltries;
1.269     raeburn  3572:             if ($$last_resets{$part}) {  
1.270     albertel 3573:                 $aggtries = &get_num_tries(\%record,$$last_resets{$part},
                   3574: 					   $part);
                   3575:             }
1.269     raeburn  3576:             $result.='<input type="hidden" name="'.
                   3577:                 'GD_'.$student.'_'.$part.'_aggtries" value="'.$aggtries.'" />'."\n";
                   3578:             $result.='<input type="hidden" name="'.
                   3579:                 'GD_'.$student.'_'.$part.'_totaltries" value="'.$totaltries.'" />'."\n";
                   3580:             $aggregates{$part} = 1;
                   3581:         }
1.41      ng       3582: 	if ($type eq 'awarded') {
1.320     albertel 3583: 	    my $pts = $score eq '' ? '' : &compute_points($score,$$weight{$part});
1.42      ng       3584: 	    $result.='<input type="hidden" name="'.
1.89      albertel 3585: 		'GD_'.$student.'_'.$part.'_awarded_s" value="'.$pts.'" />'."\n";
1.233     albertel 3586: 	    $result.='<input type="text" name="'.
1.89      albertel 3587: 		'GD_'.$student.'_'.$part.'_awarded" '.
1.589     bisitz   3588:                 'onchange="javascript:changeSelect(\''.$part.'\',\''.$student.
1.44      ng       3589: 		'\')" value="'.$pts.'" size="4" /></td>'."\n";
1.41      ng       3590: 	} elsif ($type eq 'solved') {
                   3591: 	    my ($status,$foo)=split(/_/,$score,2);
                   3592: 	    $status = 'nothing' if ($status eq '');
1.89      albertel 3593: 	    $result.='<input type="hidden" name="'.'GD_'.$student.'_'.
1.54      albertel 3594: 		$part.'_solved_s" value="'.$status.'" />'."\n";
1.233     albertel 3595: 	    $result.='&nbsp;<select name="'.
1.89      albertel 3596: 		'GD_'.$student.'_'.$part.'_solved" '.
1.589     bisitz   3597:                 'onchange="javascript:changeOneScore(\''.$part.'\',\''.$student.'\')" >'."\n";
1.485     albertel 3598: 	    $result.= (($status eq 'excused') ? '<option> </option><option selected="selected" value="excused">'.&mt('excused').'</option>' 
                   3599: 		: '<option selected="selected"> </option><option value="excused">'.&mt('excused').'</option>')."\n";
                   3600: 	    $result.='<option value="reset status">'.&mt('reset status').'</option>';
1.126     ng       3601: 	    $result.="</select>&nbsp;</td>\n";
1.122     ng       3602: 	} else {
                   3603: 	    $result.='<input type="hidden" name="'.
                   3604: 		'GD_'.$student.'_'.$part.'_'.$type.'_s" value="'.$score.'" />'.
                   3605: 		    "\n";
1.233     albertel 3606: 	    $result.='<input type="text" name="'.
1.122     ng       3607: 		'GD_'.$student.'_'.$part.'_'.$type.'" '.
                   3608: 		'value="'.$score.'" size="4" /></td>'."\n";
1.41      ng       3609: 	}
                   3610:     }
1.474     albertel 3611:     $result.=&Apache::loncommon::end_data_table_row();
1.41      ng       3612:     return $result;
1.38      ng       3613: }
                   3614: 
1.44      ng       3615: #--- change scores for all the students in a section/class
                   3616: #    record does not get update if unchanged
1.38      ng       3617: sub editgrades {
1.41      ng       3618:     my ($request) = @_;
                   3619: 
1.324     albertel 3620:     my $symb=&get_symb($request);
1.433     banghart 3621:     my $section_display = join (", ",&Apache::loncommon::get_env_multiple('form.section'));
1.477     albertel 3622:     my $title='<h2>'.&mt('Current Grade Status').'</h2>';
                   3623:     $title.='<h4>'.&mt('<b>Current Resource: </b>[_1]',$env{'form.probTitle'}).'</h4>'."\n";
1.433     banghart 3624:     $title.='<h4>'.&mt('<b>Section: </b>[_1]',$section_display).'</h4>'."\n";
1.126     ng       3625: 
1.477     albertel 3626:     my $result= &Apache::loncommon::start_data_table().
                   3627: 	&Apache::loncommon::start_data_table_header_row().
                   3628: 	'<th rowspan="2" valign="middle">'.&mt('No.').'</th>'.
                   3629: 	'<th rowspan="2" valign="middle">'.&nameUserString('header')."</th>\n";
1.43      ng       3630:     my %scoreptr = (
                   3631: 		    'correct'  =>'correct_by_override',
                   3632: 		    'incorrect'=>'incorrect_by_override',
                   3633: 		    'excused'  =>'excused',
                   3634: 		    'ungraded' =>'ungraded_attempted',
1.596     raeburn  3635:                     'credited' =>'credit_attempted',
1.43      ng       3636: 		    'nothing'  => '',
                   3637: 		    );
1.257     albertel 3638:     my ($classlist,undef,$fullname) = &getclasslist($env{'form.section'},'0');
1.34      ng       3639: 
1.44      ng       3640:     my (@partid);
                   3641:     my %weight = ();
1.54      albertel 3642:     my %columns = ();
1.44      ng       3643:     my ($i,$ctr,$count,$rec_update) = (0,0,0,0);
1.54      albertel 3644: 
1.582     raeburn  3645:     my $partserror;
                   3646:     my (@parts) = sort(&getpartlist($symb,\$partserror));
                   3647:     if ($partserror) {
                   3648:         return &navmap_errormsg();
                   3649:     }
1.54      albertel 3650:     my $header;
1.257     albertel 3651:     while ($ctr < $env{'form.totalparts'}) {
                   3652: 	my $partid = $env{'form.partid_'.$ctr};
1.524     raeburn  3653: 	push(@partid,$partid);
1.257     albertel 3654: 	$weight{$partid} = $env{'form.weight_'.$partid};
1.44      ng       3655: 	$ctr++;
1.54      albertel 3656:     }
1.324     albertel 3657:     my (undef,undef,$url) = &Apache::lonnet::decode_symb($symb);
1.54      albertel 3658:     foreach my $partid (@partid) {
1.478     albertel 3659: 	$header .= '<th align="center">'.&mt('Old Score').'</th>'.
                   3660: 	    '<th align="center">'.&mt('New Score').'</th>';
1.54      albertel 3661: 	$columns{$partid}=2;
                   3662: 	foreach my $stores (@parts) {
                   3663: 	    my ($part,$type) = &split_part_type($stores);
                   3664: 	    if ($part !~ m/^\Q$partid\E/) { next;}
                   3665: 	    if ($type eq 'awarded' || $type eq 'solved') { next; }
                   3666: 	    my $display=&Apache::lonnet::metadata($url,$stores.'.display');
1.551     raeburn  3667: 	    $display =~ s/\[Part: \Q$part\E\]//;
1.539     riegler  3668:             my $narrowtext = &mt('Tries');
                   3669: 	    $display =~ s/Number of Attempts/$narrowtext/;
                   3670: 	    $header .= '<th align="center">'.&mt('Old').' '.$display.'</th>'.
                   3671: 		'<th align="center">'.&mt('New').' '.$display.'</th>';
1.54      albertel 3672: 	    $columns{$partid}+=2;
                   3673: 	}
                   3674:     }
                   3675:     foreach my $partid (@partid) {
1.324     albertel 3676: 	my $display_part=&get_display_part($partid,$symb);
1.478     albertel 3677: 	$result .= '<th colspan="'.$columns{$partid}.'" align="center">'.
                   3678: 	    &mt('Part: [_1] (Weight = [_2])',$display_part,$weight{$partid}).
                   3679: 	    '</th>';
1.54      albertel 3680: 
1.44      ng       3681:     }
1.477     albertel 3682:     $result .= &Apache::loncommon::end_data_table_header_row().
                   3683: 	&Apache::loncommon::start_data_table_header_row().
                   3684: 	$header.
                   3685: 	&Apache::loncommon::end_data_table_header_row();
                   3686:     my @noupdate;
1.126     ng       3687:     my ($updateCtr,$noupdateCtr) = (1,1);
1.257     albertel 3688:     for ($i=0; $i<$env{'form.total'}; $i++) {
1.93      albertel 3689: 	my $line;
1.257     albertel 3690: 	my $user = $env{'form.ctr'.$i};
1.281     albertel 3691: 	my ($uname,$udom)=split(/:/,$user);
1.44      ng       3692: 	my %newrecord;
                   3693: 	my $updateflag = 0;
1.281     albertel 3694: 	$line .= '<td>'.&nameUserString(undef,$$fullname{$user},$uname,$udom).'</td>';
1.108     albertel 3695: 	my $usec=$classlist->{"$uname:$udom"}[5];
1.105     albertel 3696: 	if (!&canmodify($usec)) {
1.126     ng       3697: 	    my $numcols=scalar(@partid)*4+2;
1.477     albertel 3698: 	    push(@noupdate,
1.478     albertel 3699: 		 $line."<td colspan=\"$numcols\"><span class=\"LC_warning\">".
                   3700: 		 &mt('Not allowed to modify student')."</span></td></tr>");
1.105     albertel 3701: 	    next;
                   3702: 	}
1.269     raeburn  3703:         my %aggregate = ();
                   3704:         my $aggregateflag = 0;
1.281     albertel 3705: 	$user=~s/:/_/; # colon doen't work in javascript for names
1.44      ng       3706: 	foreach (@partid) {
1.257     albertel 3707: 	    my $old_aw    = $env{'form.GD_'.$user.'_'.$_.'_awarded_s'};
1.54      albertel 3708: 	    my $old_part_pcr = $old_aw/($weight{$_} ne '0' ? $weight{$_}:1);
                   3709: 	    my $old_part  = $old_aw eq '' ? '' : $old_part_pcr;
1.257     albertel 3710: 	    my $old_score = $scoreptr{$env{'form.GD_'.$user.'_'.$_.'_solved_s'}};
                   3711: 	    my $awarded   = $env{'form.GD_'.$user.'_'.$_.'_awarded'};
1.54      albertel 3712: 	    my $pcr       = $awarded/($weight{$_} ne '0' ? $weight{$_} : 1);
                   3713: 	    my $partial   = $awarded eq '' ? '' : $pcr;
1.44      ng       3714: 	    my $score;
                   3715: 	    if ($partial eq '') {
1.257     albertel 3716: 		$score = $scoreptr{$env{'form.GD_'.$user.'_'.$_.'_solved_s'}};
1.44      ng       3717: 	    } elsif ($partial > 0) {
                   3718: 		$score = 'correct_by_override';
                   3719: 	    } elsif ($partial == 0) {
                   3720: 		$score = 'incorrect_by_override';
                   3721: 	    }
1.257     albertel 3722: 	    my $dropMenu = $env{'form.GD_'.$user.'_'.$_.'_solved'};
1.125     ng       3723: 	    $score = 'excused' if (($dropMenu eq 'excused') && ($score ne 'excused'));
                   3724: 
1.292     albertel 3725: 	    $newrecord{'resource.'.$_.'.regrader'}=
                   3726: 		"$env{'user.name'}:$env{'user.domain'}";
1.125     ng       3727: 	    if ($dropMenu eq 'reset status' &&
                   3728: 		$old_score ne '') { # ignore if no previous attempts => nothing to reset
1.299     albertel 3729: 		$newrecord{'resource.'.$_.'.tries'} = '';
1.125     ng       3730: 		$newrecord{'resource.'.$_.'.solved'} = '';
                   3731: 		$newrecord{'resource.'.$_.'.award'} = '';
1.299     albertel 3732: 		$newrecord{'resource.'.$_.'.awarded'} = '';
1.125     ng       3733: 		$updateflag = 1;
1.269     raeburn  3734:                 if ($env{'form.GD_'.$user.'_'.$_.'_aggtries'} > 0) {
                   3735:                     my $aggtries = $env{'form.GD_'.$user.'_'.$_.'_aggtries'};
                   3736:                     my $totaltries = $env{'form.GD_'.$user.'_'.$_.'_totaltries'};
                   3737:                     my $solvedstatus = $env{'form.GD_'.$user.'_'.$_.'_solved_s'};
                   3738:                     &decrement_aggs($symb,$_,\%aggregate,$aggtries,$totaltries,$solvedstatus);
                   3739:                     $aggregateflag = 1;
                   3740:                 }
1.139     albertel 3741: 	    } elsif (!($old_part eq $partial && $old_score eq $score)) {
                   3742: 		$updateflag = 1;
                   3743: 		$newrecord{'resource.'.$_.'.awarded'}  = $partial if $partial ne '';
                   3744: 		$newrecord{'resource.'.$_.'.solved'}   = $score;
                   3745: 		$rec_update++;
1.125     ng       3746: 	    }
                   3747: 
1.93      albertel 3748: 	    $line .= '<td align="center">'.$old_aw.'&nbsp;</td>'.
1.44      ng       3749: 		'<td align="center">'.$awarded.
                   3750: 		($score eq 'excused' ? $score : '').'&nbsp;</td>';
1.5       albertel 3751: 
1.54      albertel 3752: 
                   3753: 	    my $partid=$_;
                   3754: 	    foreach my $stores (@parts) {
                   3755: 		my ($part,$type) = &split_part_type($stores);
                   3756: 		if ($part !~ m/^\Q$partid\E/) { next;}
                   3757: 		if ($type eq 'awarded' || $type eq 'solved') { next; }
1.257     albertel 3758: 		my $old_aw    = $env{'form.GD_'.$user.'_'.$part.'_'.$type.'_s'};
                   3759: 		my $awarded   = $env{'form.GD_'.$user.'_'.$part.'_'.$type};
1.54      albertel 3760: 		if ($awarded ne '' && $awarded ne $old_aw) {
                   3761: 		    $newrecord{'resource.'.$part.'.'.$type}= $awarded;
1.257     albertel 3762: 		    $newrecord{'resource.'.$part.'.regrader'}="$env{'user.name'}:$env{'user.domain'}";
1.54      albertel 3763: 		    $updateflag=1;
                   3764: 		}
1.93      albertel 3765: 		$line .= '<td align="center">'.$old_aw.'&nbsp;</td>'.
1.54      albertel 3766: 		    '<td align="center">'.$awarded.'&nbsp;</td>';
                   3767: 	    }
1.44      ng       3768: 	}
1.477     albertel 3769: 	$line.="\n";
1.301     albertel 3770: 
                   3771: 	my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   3772: 	my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   3773: 
1.44      ng       3774: 	if ($updateflag) {
                   3775: 	    $count++;
1.257     albertel 3776: 	    &Apache::lonnet::cstore(\%newrecord,$symb,$env{'request.course.id'},
1.89      albertel 3777: 				    $udom,$uname);
1.301     albertel 3778: 
                   3779: 	    if (&Apache::bridgetask::in_queue('gradingqueue',$symb,$cdom,
                   3780: 					      $cnum,$udom,$uname)) {
                   3781: 		# need to figure out if should be in queue.
                   3782: 		my %record =  
                   3783: 		    &Apache::lonnet::restore($symb,$env{'request.course.id'},
                   3784: 					     $udom,$uname);
                   3785: 		my $all_graded = 1;
                   3786: 		my $none_graded = 1;
                   3787: 		foreach my $part (@parts) {
                   3788: 		    if ( $record{'resource.'.$part.'.awarded'} eq '' ) {
                   3789: 			$all_graded = 0;
                   3790: 		    } else {
                   3791: 			$none_graded = 0;
                   3792: 		    }
                   3793: 		}
                   3794: 
                   3795: 		if ($all_graded || $none_graded) {
                   3796: 		    &Apache::bridgetask::remove_from_queue('gradingqueue',
                   3797: 							   $symb,$cdom,$cnum,
                   3798: 							   $udom,$uname);
                   3799: 		}
                   3800: 	    }
                   3801: 
1.477     albertel 3802: 	    $result.=&Apache::loncommon::start_data_table_row().
                   3803: 		'<td align="right">&nbsp;'.$updateCtr.'&nbsp;</td>'.$line.
                   3804: 		&Apache::loncommon::end_data_table_row();
1.126     ng       3805: 	    $updateCtr++;
1.93      albertel 3806: 	} else {
1.477     albertel 3807: 	    push(@noupdate,
                   3808: 		 '<td align="right">&nbsp;'.$noupdateCtr.'&nbsp;</td>'.$line);
1.126     ng       3809: 	    $noupdateCtr++;
1.44      ng       3810: 	}
1.269     raeburn  3811:         if ($aggregateflag) {
                   3812:             &Apache::lonnet::cinc('nohist_resourcetracker',\%aggregate,
1.301     albertel 3813: 				  $cdom,$cnum);
1.269     raeburn  3814:         }
1.93      albertel 3815:     }
1.477     albertel 3816:     if (@noupdate) {
1.126     ng       3817: #	my $numcols=(scalar(@partid)*(scalar(@parts)-1)*2)+3;
                   3818: 	my $numcols=scalar(@partid)*4+2;
1.477     albertel 3819: 	$result .= &Apache::loncommon::start_data_table_row('LC_empty_row').
1.478     albertel 3820: 	    '<td align="center" colspan="'.$numcols.'">'.
                   3821: 	    &mt('No Changes Occurred For the Students Below').
                   3822: 	    '</td>'.
1.477     albertel 3823: 	    &Apache::loncommon::end_data_table_row();
                   3824: 	foreach my $line (@noupdate) {
                   3825: 	    $result.=
                   3826: 		&Apache::loncommon::start_data_table_row().
                   3827: 		$line.
                   3828: 		&Apache::loncommon::end_data_table_row();
                   3829: 	}
1.44      ng       3830:     }
1.477     albertel 3831:     $result .= &Apache::loncommon::end_data_table().
                   3832: 	&show_grading_menu_form($symb);
1.478     albertel 3833:     my $msg = '<p><b>'.
                   3834: 	&mt('Number of records updated = [_1] for [quant,_2,student].',
                   3835: 	    $rec_update,$count).'</b><br />'.
                   3836: 	'<b>'.&mt('Total number of students = [_1]',$env{'form.total'}).
                   3837: 	'</b></p>';
1.44      ng       3838:     return $title.$msg.$result;
1.5       albertel 3839: }
1.54      albertel 3840: 
                   3841: sub split_part_type {
                   3842:     my ($partstr) = @_;
                   3843:     my ($temp,@allparts)=split(/_/,$partstr);
                   3844:     my $type=pop(@allparts);
1.439     albertel 3845:     my $part=join('_',@allparts);
1.54      albertel 3846:     return ($part,$type);
                   3847: }
                   3848: 
1.44      ng       3849: #------------- end of section for handling grading by section/class ---------
                   3850: #
                   3851: #----------------------------------------------------------------------------
                   3852: 
1.5       albertel 3853: 
1.44      ng       3854: #----------------------------------------------------------------------------
                   3855: #
                   3856: #-------------------------- Next few routines handles grading by csv upload
                   3857: #
                   3858: #--- Javascript to handle csv upload
1.27      albertel 3859: sub csvupload_javascript_reverse_associate {
1.573     bisitz   3860:     my $error1=&mt('You need to specify the username or the student/employee ID');
1.246     albertel 3861:     my $error2=&mt('You need to specify at least one grading field');
1.27      albertel 3862:   return(<<ENDPICK);
                   3863:   function verify(vf) {
                   3864:     var foundsomething=0;
                   3865:     var founduname=0;
1.243     albertel 3866:     var foundID=0;
1.27      albertel 3867:     for (i=0;i<=vf.nfields.value;i++) {
                   3868:       tw=eval('vf.f'+i+'.selectedIndex');
1.243     albertel 3869:       if (i==0 && tw!=0) { foundID=1; }
                   3870:       if (i==1 && tw!=0) { founduname=1; }
                   3871:       if (i!=0 && i!=1 && i!=2 && tw!=0) { foundsomething=1; }
1.27      albertel 3872:     }
1.246     albertel 3873:     if (founduname==0 && foundID==0) {
                   3874: 	alert('$error1');
                   3875: 	return;
1.27      albertel 3876:     }
                   3877:     if (foundsomething==0) {
1.246     albertel 3878: 	alert('$error2');
                   3879: 	return;
1.27      albertel 3880:     }
                   3881:     vf.submit();
                   3882:   }
                   3883:   function flip(vf,tf) {
                   3884:     var nw=eval('vf.f'+tf+'.selectedIndex');
                   3885:     var i;
                   3886:     for (i=0;i<=vf.nfields.value;i++) {
                   3887:       //can not pick the same destination field for both name and domain
                   3888:       if (((i ==0)||(i ==1)) && 
                   3889:           ((tf==0)||(tf==1)) && 
                   3890:           (i!=tf) &&
                   3891:           (eval('vf.f'+i+'.selectedIndex')==nw)) {
                   3892:         eval('vf.f'+i+'.selectedIndex=0;')
                   3893:       }
                   3894:     }
                   3895:   }
                   3896: ENDPICK
                   3897: }
                   3898: 
                   3899: sub csvupload_javascript_forward_associate {
1.573     bisitz   3900:     my $error1=&mt('You need to specify the username or the student/employee ID');
1.246     albertel 3901:     my $error2=&mt('You need to specify at least one grading field');
1.27      albertel 3902:   return(<<ENDPICK);
                   3903:   function verify(vf) {
                   3904:     var foundsomething=0;
                   3905:     var founduname=0;
1.243     albertel 3906:     var foundID=0;
1.27      albertel 3907:     for (i=0;i<=vf.nfields.value;i++) {
                   3908:       tw=eval('vf.f'+i+'.selectedIndex');
1.243     albertel 3909:       if (tw==1) { foundID=1; }
                   3910:       if (tw==2) { founduname=1; }
                   3911:       if (tw>3) { foundsomething=1; }
1.27      albertel 3912:     }
1.246     albertel 3913:     if (founduname==0 && foundID==0) {
                   3914: 	alert('$error1');
                   3915: 	return;
1.27      albertel 3916:     }
                   3917:     if (foundsomething==0) {
1.246     albertel 3918: 	alert('$error2');
                   3919: 	return;
1.27      albertel 3920:     }
                   3921:     vf.submit();
                   3922:   }
                   3923:   function flip(vf,tf) {
                   3924:     var nw=eval('vf.f'+tf+'.selectedIndex');
                   3925:     var i;
                   3926:     //can not pick the same destination field twice
                   3927:     for (i=0;i<=vf.nfields.value;i++) {
                   3928:       if ((i!=tf) && (eval('vf.f'+i+'.selectedIndex')==nw)) {
                   3929:         eval('vf.f'+i+'.selectedIndex=0;')
                   3930:       }
                   3931:     }
                   3932:   }
                   3933: ENDPICK
                   3934: }
                   3935: 
1.26      albertel 3936: sub csvuploadmap_header {
1.324     albertel 3937:     my ($request,$symb,$datatoken,$distotal)= @_;
1.41      ng       3938:     my $javascript;
1.257     albertel 3939:     if ($env{'form.upfile_associate'} eq 'reverse') {
1.41      ng       3940: 	$javascript=&csvupload_javascript_reverse_associate();
                   3941:     } else {
                   3942: 	$javascript=&csvupload_javascript_forward_associate();
                   3943:     }
1.45      ng       3944: 
1.324     albertel 3945:     my ($result) = &showResourceInfo($symb,$env{'form.probTitle'});
1.257     albertel 3946:     my $checked=(($env{'form.noFirstLine'})?' checked="checked"':'');
1.245     albertel 3947:     my $ignore=&mt('Ignore First Line');
1.418     albertel 3948:     $symb = &Apache::lonenc::check_encrypt($symb);
1.41      ng       3949:     $request->print(<<ENDPICK);
1.26      albertel 3950: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="gradesupload">
1.398     albertel 3951: <h3><span class="LC_info">Uploading Class Grades</span></h3>
1.45      ng       3952: $result
1.326     albertel 3953: <hr />
1.26      albertel 3954: <h3>Identify fields</h3>
                   3955: Total number of records found in file: $distotal <hr />
                   3956: Enter as many fields as you can. The system will inform you and bring you back
                   3957: to this page if the data selected is insufficient to run your class.<hr />
1.589     bisitz   3958: <input type="button" value="Reverse Association" onclick="javascript:this.form.associate.value='Reverse Association';submit(this.form);" />
1.245     albertel 3959: <label><input type="checkbox" name="noFirstLine" $checked />$ignore</label>
1.26      albertel 3960: <input type="hidden" name="associate"  value="" />
                   3961: <input type="hidden" name="phase"      value="three" />
                   3962: <input type="hidden" name="datatoken"  value="$datatoken" />
1.257     albertel 3963: <input type="hidden" name="fileupload" value="$env{'form.fileupload'}" />
                   3964: <input type="hidden" name="upfiletype" value="$env{'form.upfiletype'}" />
1.26      albertel 3965: <input type="hidden" name="upfile_associate" 
1.257     albertel 3966:                                        value="$env{'form.upfile_associate'}" />
1.26      albertel 3967: <input type="hidden" name="symb"       value="$symb" />
1.257     albertel 3968: <input type="hidden" name="saveState"  value="$env{'form.saveState'}" />
                   3969: <input type="hidden" name="probTitle"  value="$env{'form.probTitle'}" />
1.246     albertel 3970: <input type="hidden" name="command"    value="csvuploadoptions" />
1.26      albertel 3971: <hr />
                   3972: <script type="text/javascript" language="Javascript">
                   3973: $javascript
                   3974: </script>
                   3975: ENDPICK
1.118     ng       3976:     return '';
1.26      albertel 3977: 
                   3978: }
                   3979: 
                   3980: sub csvupload_fields {
1.582     raeburn  3981:     my ($symb,$errorref) = @_;
                   3982:     my (@parts) = &getpartlist($symb,$errorref);
                   3983:     if (ref($errorref)) {
                   3984:         if ($$errorref) {
                   3985:             return;
                   3986:         }
                   3987:     }
                   3988: 
1.556     weissno  3989:     my @fields=(['ID','Student/Employee ID'],
1.243     albertel 3990: 		['username','Student Username'],
                   3991: 		['domain','Student Domain']);
1.324     albertel 3992:     my (undef,undef,$url) = &Apache::lonnet::decode_symb($symb);
1.41      ng       3993:     foreach my $part (sort(@parts)) {
                   3994: 	my @datum;
                   3995: 	my $display=&Apache::lonnet::metadata($url,$part.'.display');
                   3996: 	my $name=$part;
                   3997: 	if  (!$display) { $display = $name; }
                   3998: 	@datum=($name,$display);
1.244     albertel 3999: 	if ($name=~/^stores_(.*)_awarded/) {
                   4000: 	    push(@fields,['stores_'.$1.'_points',"Points [Part: $1]"]);
                   4001: 	}
1.41      ng       4002: 	push(@fields,\@datum);
                   4003:     }
                   4004:     return (@fields);
1.26      albertel 4005: }
                   4006: 
                   4007: sub csvuploadmap_footer {
1.41      ng       4008:     my ($request,$i,$keyfields) =@_;
                   4009:     $request->print(<<ENDPICK);
1.26      albertel 4010: </table>
                   4011: <input type="hidden" name="nfields" value="$i" />
                   4012: <input type="hidden" name="keyfields" value="$keyfields" />
1.589     bisitz   4013: <input type="button" onclick="javascript:verify(this.form)" value="Assign Grades" /><br />
1.26      albertel 4014: </form>
                   4015: ENDPICK
                   4016: }
                   4017: 
1.283     albertel 4018: sub checkforfile_js {
1.539     riegler  4019:     my $alertmsg = &mt('Please use the browse button to select a file from your local directory.');
1.86      ng       4020:     my $result =<<CSVFORMJS;
                   4021: <script type="text/javascript" language="javascript">
                   4022:     function checkUpload(formname) {
                   4023: 	if (formname.upfile.value == "") {
1.539     riegler  4024: 	    alert("$alertmsg");
1.86      ng       4025: 	    return false;
                   4026: 	}
                   4027: 	formname.submit();
                   4028:     }
                   4029:     </script>
                   4030: CSVFORMJS
1.283     albertel 4031:     return $result;
                   4032: }
                   4033: 
                   4034: sub upcsvScores_form {
                   4035:     my ($request) = shift;
1.324     albertel 4036:     my ($symb)=&get_symb($request);
1.283     albertel 4037:     if (!$symb) {return '';}
                   4038:     my $result=&checkforfile_js();
1.257     albertel 4039:     $env{'form.probTitle'} = &Apache::lonnet::gettitle($symb);
1.324     albertel 4040:     my ($table) = &showResourceInfo($symb,$env{'form.probTitle'});
1.118     ng       4041:     $result.=$table;
1.326     albertel 4042:     $result.='<br /><table width="100%" border="0"><tr><td bgcolor="#777777">'."\n";
                   4043:     $result.='<table width="100%" border="0"><tr bgcolor="#e6ffff"><td>'."\n";
1.538     schulted 4044:     $result.='&nbsp;<b>'.&mt('Specify a file containing the class scores for current resource.').
                   4045: 	'</b></td></tr>'."\n";
1.86      ng       4046:     $result.='<tr bgcolor=#ffffe6><td>'."\n";
1.370     www      4047:     my $upload=&mt("Upload Scores");
1.86      ng       4048:     my $upfile_select=&Apache::loncommon::upfile_select_html();
1.245     albertel 4049:     my $ignore=&mt('Ignore First Line');
1.418     albertel 4050:     $symb = &Apache::lonenc::check_encrypt($symb);
1.86      ng       4051:     $result.=<<ENDUPFORM;
1.106     albertel 4052: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="gradesupload">
1.86      ng       4053: <input type="hidden" name="symb" value="$symb" />
                   4054: <input type="hidden" name="command" value="csvuploadmap" />
1.257     albertel 4055: <input type="hidden" name="probTitle" value="$env{'form.probTitle'}" />
                   4056: <input type="hidden" name="saveState"  value="$env{'form.saveState'}" />
1.86      ng       4057: $upfile_select
1.589     bisitz   4058: <br /><input type="button" onclick="javascript:checkUpload(this.form);" value="$upload" />
1.283     albertel 4059: <label><input type="checkbox" name="noFirstLine" />$ignore</label>
1.86      ng       4060: </form>
                   4061: ENDUPFORM
1.370     www      4062:     $result.=&Apache::loncommon::help_open_topic("Course_Convert_To_CSV",
                   4063:                            &mt("How do I create a CSV file from a spreadsheet"))
                   4064:     .'</td></tr></table>'."\n";
1.86      ng       4065:     $result.='</td></tr></table><br /><br />'."\n";
1.324     albertel 4066:     $result.=&show_grading_menu_form($symb);
1.86      ng       4067:     return $result;
                   4068: }
                   4069: 
                   4070: 
1.26      albertel 4071: sub csvuploadmap {
1.41      ng       4072:     my ($request)= @_;
1.324     albertel 4073:     my ($symb)=&get_symb($request);
1.41      ng       4074:     if (!$symb) {return '';}
1.72      ng       4075: 
1.41      ng       4076:     my $datatoken;
1.257     albertel 4077:     if (!$env{'form.datatoken'}) {
1.41      ng       4078: 	$datatoken=&Apache::loncommon::upfile_store($request);
1.26      albertel 4079:     } else {
1.257     albertel 4080: 	$datatoken=$env{'form.datatoken'};
1.41      ng       4081: 	&Apache::loncommon::load_tmp_file($request);
1.26      albertel 4082:     }
1.41      ng       4083:     my @records=&Apache::loncommon::upfile_record_sep();
1.257     albertel 4084:     if ($env{'form.noFirstLine'}) { shift(@records); }
1.324     albertel 4085:     &csvuploadmap_header($request,$symb,$datatoken,$#records+1);
1.41      ng       4086:     my ($i,$keyfields);
                   4087:     if (@records) {
1.582     raeburn  4088:         my $fieldserror;
                   4089: 	my @fields=&csvupload_fields($symb,\$fieldserror);
                   4090:         if ($fieldserror) {
                   4091:             $request->print(&navmap_errormsg());
                   4092:             return;
                   4093:         }
1.257     albertel 4094: 	if ($env{'form.upfile_associate'} eq 'reverse') {	
1.41      ng       4095: 	    &Apache::loncommon::csv_print_samples($request,\@records);
                   4096: 	    $i=&Apache::loncommon::csv_print_select_table($request,\@records,
                   4097: 							  \@fields);
                   4098: 	    foreach (@fields) { $keyfields.=$_->[0].','; }
                   4099: 	    chop($keyfields);
                   4100: 	} else {
                   4101: 	    unshift(@fields,['none','']);
                   4102: 	    $i=&Apache::loncommon::csv_samples_select_table($request,\@records,
                   4103: 							    \@fields);
1.311     banghart 4104:             foreach my $rec (@records) {
                   4105:                 my %temp = &Apache::loncommon::record_sep($rec);
                   4106:                 if (%temp) {
                   4107:                     $keyfields=join(',',sort(keys(%temp)));
                   4108:                     last;
                   4109:                 }
                   4110:             }
1.41      ng       4111: 	}
                   4112:     }
                   4113:     &csvuploadmap_footer($request,$i,$keyfields);
1.324     albertel 4114:     $request->print(&show_grading_menu_form($symb));
1.72      ng       4115: 
1.41      ng       4116:     return '';
1.27      albertel 4117: }
                   4118: 
1.246     albertel 4119: sub csvuploadoptions {
1.41      ng       4120:     my ($request)= @_;
1.324     albertel 4121:     my ($symb)=&get_symb($request);
1.257     albertel 4122:     my $checked=(($env{'form.noFirstLine'})?'1':'0');
1.246     albertel 4123:     my $ignore=&mt('Ignore First Line');
                   4124:     $request->print(<<ENDPICK);
                   4125: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="gradesupload">
1.398     albertel 4126: <h3><span class="LC_info">Uploading Class Grade Options</span></h3>
1.246     albertel 4127: <input type="hidden" name="command"    value="csvuploadassign" />
1.302     albertel 4128: <!--
1.246     albertel 4129: <p>
                   4130: <label>
                   4131:    <input type="checkbox" name="show_full_results" />
                   4132:    Show a table of all changes
                   4133: </label>
                   4134: </p>
1.302     albertel 4135: -->
1.246     albertel 4136: <p>
                   4137: <label>
                   4138:    <input type="checkbox" name="overwite_scores" checked="checked" />
                   4139:    Overwrite any existing score
                   4140: </label>
                   4141: </p>
                   4142: ENDPICK
                   4143:     my %fields=&get_fields();
                   4144:     if (!defined($fields{'domain'})) {
1.257     albertel 4145: 	my $domform = &Apache::loncommon::select_dom_form($env{'request.role.domain'},'default_domain');
1.246     albertel 4146: 	$request->print("\n<p> Users are in domain: ".$domform."</p>\n");
                   4147:     }
1.257     albertel 4148:     foreach my $key (sort(keys(%env))) {
1.246     albertel 4149: 	if ($key !~ /^form\.(.*)$/) { next; }
                   4150: 	my $cleankey=$1;
                   4151: 	if ($cleankey eq 'command') { next; }
                   4152: 	$request->print('<input type="hidden" name="'.$cleankey.
1.257     albertel 4153: 			'"  value="'.$env{$key}.'" />'."\n");
1.246     albertel 4154:     }
                   4155:     # FIXME do a check for any duplicated user ids...
                   4156:     # FIXME do a check for any invalid user ids?...
1.290     albertel 4157:     $request->print('<input type="submit" value="Assign Grades" /><br />
                   4158: <hr /></form>'."\n");
1.324     albertel 4159:     $request->print(&show_grading_menu_form($symb));
1.246     albertel 4160:     return '';
                   4161: }
                   4162: 
                   4163: sub get_fields {
                   4164:     my %fields;
1.257     albertel 4165:     my @keyfields = split(/\,/,$env{'form.keyfields'});
                   4166:     for (my $i=0; $i<=$env{'form.nfields'}; $i++) {
                   4167: 	if ($env{'form.upfile_associate'} eq 'reverse') {
                   4168: 	    if ($env{'form.f'.$i} ne 'none') {
                   4169: 		$fields{$keyfields[$i]}=$env{'form.f'.$i};
1.41      ng       4170: 	    }
                   4171: 	} else {
1.257     albertel 4172: 	    if ($env{'form.f'.$i} ne 'none') {
                   4173: 		$fields{$env{'form.f'.$i}}=$keyfields[$i];
1.41      ng       4174: 	    }
                   4175: 	}
1.27      albertel 4176:     }
1.246     albertel 4177:     return %fields;
                   4178: }
                   4179: 
                   4180: sub csvuploadassign {
                   4181:     my ($request)= @_;
1.324     albertel 4182:     my ($symb)=&get_symb($request);
1.246     albertel 4183:     if (!$symb) {return '';}
1.345     bowersj2 4184:     my $error_msg = '';
1.246     albertel 4185:     &Apache::loncommon::load_tmp_file($request);
                   4186:     my @gradedata = &Apache::loncommon::upfile_record_sep();
1.257     albertel 4187:     if ($env{'form.noFirstLine'}) { shift(@gradedata); }
1.246     albertel 4188:     my %fields=&get_fields();
1.41      ng       4189:     $request->print('<h3>Assigning Grades</h3>');
1.257     albertel 4190:     my $courseid=$env{'request.course.id'};
1.97      albertel 4191:     my ($classlist) = &getclasslist('all',0);
1.106     albertel 4192:     my @notallowed;
1.41      ng       4193:     my @skipped;
                   4194:     my $countdone=0;
                   4195:     foreach my $grade (@gradedata) {
                   4196: 	my %entries=&Apache::loncommon::record_sep($grade);
1.246     albertel 4197: 	my $domain;
                   4198: 	if ($entries{$fields{'domain'}}) {
                   4199: 	    $domain=$entries{$fields{'domain'}};
                   4200: 	} else {
1.257     albertel 4201: 	    $domain=$env{'form.default_domain'};
1.246     albertel 4202: 	}
1.243     albertel 4203: 	$domain=~s/\s//g;
1.41      ng       4204: 	my $username=$entries{$fields{'username'}};
1.160     albertel 4205: 	$username=~s/\s//g;
1.243     albertel 4206: 	if (!$username) {
                   4207: 	    my $id=$entries{$fields{'ID'}};
1.247     albertel 4208: 	    $id=~s/\s//g;
1.243     albertel 4209: 	    my %ids=&Apache::lonnet::idget($domain,$id);
                   4210: 	    $username=$ids{$id};
                   4211: 	}
1.41      ng       4212: 	if (!exists($$classlist{"$username:$domain"})) {
1.247     albertel 4213: 	    my $id=$entries{$fields{'ID'}};
                   4214: 	    $id=~s/\s//g;
                   4215: 	    if ($id) {
                   4216: 		push(@skipped,"$id:$domain");
                   4217: 	    } else {
                   4218: 		push(@skipped,"$username:$domain");
                   4219: 	    }
1.41      ng       4220: 	    next;
                   4221: 	}
1.108     albertel 4222: 	my $usec=$classlist->{"$username:$domain"}[5];
1.106     albertel 4223: 	if (!&canmodify($usec)) {
                   4224: 	    push(@notallowed,"$username:$domain");
                   4225: 	    next;
                   4226: 	}
1.244     albertel 4227: 	my %points;
1.41      ng       4228: 	my %grades;
                   4229: 	foreach my $dest (keys(%fields)) {
1.244     albertel 4230: 	    if ($dest eq 'ID' || $dest eq 'username' ||
                   4231: 		$dest eq 'domain') { next; }
                   4232: 	    if ($entries{$fields{$dest}} =~ /^\s*$/) { next; }
                   4233: 	    if ($dest=~/stores_(.*)_points/) {
                   4234: 		my $part=$1;
                   4235: 		my $wgt =&Apache::lonnet::EXT('resource.'.$part.'.weight',
                   4236: 					      $symb,$domain,$username);
1.345     bowersj2 4237:                 if ($wgt) {
                   4238:                     $entries{$fields{$dest}}=~s/\s//g;
                   4239:                     my $pcr=$entries{$fields{$dest}} / $wgt;
1.463     albertel 4240:                     my $award=($pcr == 0) ? 'incorrect_by_override'
                   4241:                                           : 'correct_by_override';
1.345     bowersj2 4242:                     $grades{"resource.$part.awarded"}=$pcr;
                   4243:                     $grades{"resource.$part.solved"}=$award;
                   4244:                     $points{$part}=1;
                   4245:                 } else {
                   4246:                     $error_msg = "<br />" .
                   4247:                         &mt("Some point values were assigned"
                   4248:                             ." for problems with a weight "
                   4249:                             ."of zero. These values were "
                   4250:                             ."ignored.");
                   4251:                 }
1.244     albertel 4252: 	    } else {
                   4253: 		if ($dest=~/stores_(.*)_awarded/) { if ($points{$1}) {next;} }
                   4254: 		if ($dest=~/stores_(.*)_solved/)  { if ($points{$1}) {next;} }
                   4255: 		my $store_key=$dest;
                   4256: 		$store_key=~s/^stores/resource/;
                   4257: 		$store_key=~s/_/\./g;
                   4258: 		$grades{$store_key}=$entries{$fields{$dest}};
                   4259: 	    }
1.41      ng       4260: 	}
1.508     www      4261: 	if (! %grades) { 
                   4262:            push(@skipped,&mt("[_1]: no data to save","$username:$domain")); 
                   4263:         } else {
                   4264: 	   $grades{"resource.regrader"}="$env{'user.name'}:$env{'user.domain'}";
                   4265: 	   my $result=&Apache::lonnet::cstore(\%grades,$symb,
1.302     albertel 4266: 					   $env{'request.course.id'},
                   4267: 					   $domain,$username);
1.508     www      4268: 	   if ($result eq 'ok') {
                   4269: 	      $request->print('.');
                   4270: 	   } else {
                   4271: 	      $request->print("<p><span class=\"LC_error\">".
                   4272:                               &mt("Failed to save data for student [_1]. Message when trying to save was: [_2]",
                   4273:                                   "$username:$domain",$result)."</span></p>");
                   4274: 	   }
                   4275: 	   $request->rflush();
                   4276: 	   $countdone++;
                   4277:         }
1.41      ng       4278:     }
1.570     www      4279:     $request->print('<br />'.&Apache::lonhtmlcommon::confirm_success(&mt("Saved scores for [quant,_1,student]",$countdone),$countdone==0));
1.41      ng       4280:     if (@skipped) {
1.571     www      4281: 	$request->print('<br />'.&Apache::lonhtmlcommon::confirm_success(&mt('No scores stored for the following username(s):'),1).'<br />');
                   4282:         $request->print(join(', ',@skipped));
1.106     albertel 4283:     }
                   4284:     if (@notallowed) {
1.571     www      4285: 	$request->print('<br />'.&Apache::lonhtmlcommon::confirm_success(&mt('Modification of scores not allowed for the following username(s):'),1).'<br />');
                   4286: 	$request->print(join(', ',@notallowed));
1.41      ng       4287:     }
1.106     albertel 4288:     $request->print("<br />\n");
1.324     albertel 4289:     $request->print(&show_grading_menu_form($symb));
1.345     bowersj2 4290:     return $error_msg;
1.26      albertel 4291: }
1.44      ng       4292: #------------- end of section for handling csv file upload ---------
                   4293: #
                   4294: #-------------------------------------------------------------------
                   4295: #
1.122     ng       4296: #-------------- Next few routines handle grading by page/sequence
1.72      ng       4297: #
                   4298: #--- Select a page/sequence and a student to grade
1.68      ng       4299: sub pickStudentPage {
                   4300:     my ($request) = shift;
                   4301: 
1.539     riegler  4302:     my $alertmsg = &mt('Please select the student you wish to grade.');
1.68      ng       4303:     $request->print(<<LISTJAVASCRIPT);
                   4304: <script type="text/javascript" language="javascript">
                   4305: 
                   4306: function checkPickOne(formname) {
1.76      ng       4307:     if (radioSelection(formname.student) == null) {
1.539     riegler  4308: 	alert("$alertmsg");
1.68      ng       4309: 	return;
                   4310:     }
1.125     ng       4311:     ptr = pullDownSelection(formname.selectpage);
                   4312:     formname.page.value = formname["page"+ptr].value;
                   4313:     formname.title.value = formname["title"+ptr].value;
1.68      ng       4314:     formname.submit();
                   4315: }
                   4316: 
                   4317: </script>
                   4318: LISTJAVASCRIPT
1.118     ng       4319:     &commonJSfunctions($request);
1.324     albertel 4320:     my ($symb) = &get_symb($request);
1.257     albertel 4321:     my $cdom      = $env{"course.$env{'request.course.id'}.domain"};
                   4322:     my $cnum      = $env{"course.$env{'request.course.id'}.num"};
                   4323:     my $getsec    = $env{'form.section'} eq '' ? 'all' : $env{'form.section'};
1.68      ng       4324: 
1.398     albertel 4325:     my $result='<h3><span class="LC_info">&nbsp;'.
1.485     albertel 4326: 	&mt('Manual Grading by Page or Sequence').'</span></h3>';
1.68      ng       4327: 
1.80      ng       4328:     $result.='<form action="/adm/grades" method="post" name="displayPage">'."\n";
1.582     raeburn  4329:     my $map_error;
                   4330:     my ($titles,$symbx) = &getSymbMap($map_error);
                   4331:     if ($map_error) {
                   4332:         $request->print(&navmap_errormsg());
                   4333:         return; 
                   4334:     }
1.137     albertel 4335:     my ($curpage) =&Apache::lonnet::decode_symb($symb); 
                   4336: #    my ($curpage,$mapId) =&Apache::lonnet::decode_symb($symb); 
                   4337: #    my $type=($curpage =~ /\.(page|sequence)/);
1.485     albertel 4338:     my $select = '<select name="selectpage">'."\n";
1.70      ng       4339:     my $ctr=0;
1.68      ng       4340:     foreach (@$titles) {
                   4341: 	my ($minder,$showtitle) = ($_ =~ /(\d+)\.(.*)/);
1.485     albertel 4342: 	$select.='<option value="'.$ctr.'" '.
1.401     albertel 4343: 	    ($$symbx{$_} =~ /$curpage$/ ? 'selected="selected"' : '').
1.71      ng       4344: 	    '>'.$showtitle.'</option>'."\n";
1.70      ng       4345: 	$ctr++;
1.68      ng       4346:     }
1.485     albertel 4347:     $select.= '</select>';
1.539     riegler  4348:     $result.='&nbsp;<b>'.&mt('Problems from').':</b> '.$select."<br />\n";
1.485     albertel 4349: 
1.70      ng       4350:     $ctr=0;
                   4351:     foreach (@$titles) {
                   4352: 	my ($minder,$showtitle) = ($_ =~ /(\d+)\.(.*)/);
                   4353: 	$result.='<input type="hidden" name="page'.$ctr.'" value="'.$$symbx{$_}.'" />'."\n";
                   4354: 	$result.='<input type="hidden" name="title'.$ctr.'" value="'.$showtitle.'" />'."\n";
                   4355: 	$ctr++;
                   4356:     }
1.72      ng       4357:     $result.='<input type="hidden" name="page" />'."\n".
                   4358: 	'<input type="hidden" name="title" />'."\n";
1.68      ng       4359: 
1.485     albertel 4360:     my $options =
                   4361: 	'<label><input type="radio" name="vProb" value="no" checked="checked" /> '.&mt('no').' </label>'."\n".
                   4362: 	'<label><input type="radio" name="vProb" value="yes" /> '.&mt('yes').' </label>'."<br />\n";
1.539     riegler  4363:     $result.='&nbsp;<b>'.&mt('View Problem Text').': </b>'.$options;
1.485     albertel 4364: 
                   4365:     $options =
                   4366: 	'<label><input type="radio" name="lastSub" value="none" /> '.&mt('none').' </label>'."\n".
                   4367: 	'<label><input type="radio" name="lastSub" value="datesub" checked="checked" /> '.&mt('by dates and submissions').'</label>'."\n".
                   4368: 	'<label><input type="radio" name="lastSub" value="all" /> '.&mt('all details').' </label>'."\n";
1.539     riegler  4369:     $result.='&nbsp;<b>'.&mt('Submissions').': </b>'.$options;
1.432     banghart 4370:     
                   4371:     $result.=&build_section_inputs();
1.442     banghart 4372:     my $stu_status = join(':',&Apache::loncommon::get_env_multiple('form.Status'));
                   4373:     $result.='<input type="hidden" name="Status"  value="'.$stu_status.'" />'."\n".
1.72      ng       4374: 	'<input type="hidden" name="command" value="displayPage" />'."\n".
1.418     albertel 4375: 	'<input type="hidden" name="symb"    value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
1.257     albertel 4376: 	'<input type="hidden" name="saveState" value="'.$env{'form.saveState'}.'" />'."<br />\n";
1.72      ng       4377: 
1.539     riegler  4378:     $result.='&nbsp;<b>'.&mt('Use CODE').': </b> <input type="text" name="CODE" value="" /> <br />'."\n";
1.382     albertel 4379: 
1.80      ng       4380:     $result.='&nbsp;<input type="button" '.
1.589     bisitz   4381:              'onclick="javascript:checkPickOne(this.form);" value="'.&mt('Next').' &rarr;" /><br />'."\n";
1.72      ng       4382: 
1.68      ng       4383:     $request->print($result);
                   4384: 
1.485     albertel 4385:     my $studentTable.='&nbsp;<b>'.&mt('Select a student you wish to grade and then click on the Next button.').'</b><br />'.
1.484     albertel 4386: 	&Apache::loncommon::start_data_table().
                   4387: 	&Apache::loncommon::start_data_table_header_row().
1.485     albertel 4388: 	'<th align="right">&nbsp;'.&mt('No.').'</th>'.
1.484     albertel 4389: 	'<th>'.&nameUserString('header').'</th>'.
1.485     albertel 4390: 	'<th align="right">&nbsp;'.&mt('No.').'</th>'.
1.484     albertel 4391: 	'<th>'.&nameUserString('header').'</th>'.
                   4392: 	&Apache::loncommon::end_data_table_header_row();
1.68      ng       4393:  
1.76      ng       4394:     my (undef,undef,$fullname) = &getclasslist($getsec,'1');
1.68      ng       4395:     my $ptr = 1;
1.294     albertel 4396:     foreach my $student (sort 
                   4397: 			 {
                   4398: 			     if (lc($$fullname{$a}) ne lc($$fullname{$b})) {
                   4399: 				 return (lc($$fullname{$a}) cmp lc($$fullname{$b}));
                   4400: 			     }
                   4401: 			     return $a cmp $b;
                   4402: 			 } (keys(%$fullname))) {
1.68      ng       4403: 	my ($uname,$udom) = split(/:/,$student);
1.484     albertel 4404: 	$studentTable.=($ptr%2==1 ? &Apache::loncommon::start_data_table_row()
                   4405:                                   : '</td>');
1.126     ng       4406: 	$studentTable.='<td align="right">'.$ptr.'&nbsp;</td>';
1.288     albertel 4407: 	$studentTable.='<td>&nbsp;<label><input type="radio" name="student" value="'.$student.'" /> '
                   4408: 	    .&nameUserString(undef,$$fullname{$student},$uname,$udom)."</label>\n";
1.484     albertel 4409: 	$studentTable.=
                   4410: 	    ($ptr%2 == 0 ? '</td>'.&Apache::loncommon::end_data_table_row() 
                   4411:                          : '');
1.68      ng       4412: 	$ptr++;
                   4413:     }
1.484     albertel 4414:     if ($ptr%2 == 0) {
                   4415: 	$studentTable.='</td><td>&nbsp;</td><td>&nbsp;</td>'.
                   4416: 	    &Apache::loncommon::end_data_table_row();
                   4417:     }
                   4418:     $studentTable.=&Apache::loncommon::end_data_table()."\n";
1.126     ng       4419:     $studentTable.='<input type="button" '.
1.589     bisitz   4420:                    'onclick="javascript:checkPickOne(this.form);" value="'.&mt('Next').' &rarr;" /></form>'."\n";
1.68      ng       4421: 
1.324     albertel 4422:     $studentTable.=&show_grading_menu_form($symb);
1.68      ng       4423:     $request->print($studentTable);
                   4424: 
                   4425:     return '';
                   4426: }
                   4427: 
                   4428: sub getSymbMap {
1.582     raeburn  4429:     my ($map_error) = @_;
1.132     bowersj2 4430:     my $navmap = Apache::lonnavmaps::navmap->new();
1.582     raeburn  4431:     unless (ref($navmap)) {
                   4432:         if (ref($map_error)) {
                   4433:             $$map_error = 'navmap';
                   4434:         }
                   4435:         return;
                   4436:     }
1.68      ng       4437:     my %symbx = ();
                   4438:     my @titles = ();
1.117     bowersj2 4439:     my $minder = 0;
                   4440: 
                   4441:     # Gather every sequence that has problems.
1.240     albertel 4442:     my @sequences = $navmap->retrieveResources(undef, sub { shift->is_map(); },
                   4443: 					       1,0,1);
1.117     bowersj2 4444:     for my $sequence ($navmap->getById('0.0'), @sequences) {
1.241     albertel 4445: 	if ($navmap->hasResource($sequence, sub { shift->is_problem(); }, 0) ) {
1.381     albertel 4446: 	    my $title = $minder.'.'.
                   4447: 		&HTML::Entities::encode($sequence->compTitle(),'"\'&');
                   4448: 	    push(@titles, $title); # minder in case two titles are identical
                   4449: 	    $symbx{$title} = &HTML::Entities::encode($sequence->symb(),'"\'&');
1.117     bowersj2 4450: 	    $minder++;
1.241     albertel 4451: 	}
1.68      ng       4452:     }
                   4453:     return \@titles,\%symbx;
                   4454: }
                   4455: 
1.72      ng       4456: #
                   4457: #--- Displays a page/sequence w/wo problems, w/wo submissions
1.68      ng       4458: sub displayPage {
                   4459:     my ($request) = shift;
                   4460: 
1.324     albertel 4461:     my ($symb) = &get_symb($request);
1.257     albertel 4462:     my $cdom      = $env{"course.$env{'request.course.id'}.domain"};
                   4463:     my $cnum      = $env{"course.$env{'request.course.id'}.num"};
                   4464:     my $getsec    = $env{'form.section'} eq '' ? 'all' : $env{'form.section'};
                   4465:     my $pageTitle = $env{'form.page'};
1.103     albertel 4466:     my ($classlist,undef,$fullname) = &getclasslist($getsec,'1');
1.257     albertel 4467:     my ($uname,$udom) = split(/:/,$env{'form.student'});
                   4468:     my $usec=$classlist->{$env{'form.student'}}[5];
1.168     albertel 4469: 
                   4470:     #need to make sure we have the correct data for later EXT calls, 
                   4471:     #thus invalidate the cache
                   4472:     &Apache::lonnet::devalidatecourseresdata(
1.257     albertel 4473:                  $env{'course.'.$env{'request.course.id'}.'.num'},
                   4474:                  $env{'course.'.$env{'request.course.id'}.'.domain'});
1.168     albertel 4475:     &Apache::lonnet::clear_EXT_cache_status();
                   4476: 
1.103     albertel 4477:     if (!&canview($usec)) {
1.485     albertel 4478: 	$request->print('<span class="LC_warning">'.&mt('Unable to view requested student. ([_1])',$env{'form.student'}).'</span>');
1.324     albertel 4479: 	$request->print(&show_grading_menu_form($symb));
1.103     albertel 4480: 	return;
                   4481:     }
1.398     albertel 4482:     my $result='<h3><span class="LC_info">&nbsp;'.$env{'form.title'}.'</span></h3>';
1.485     albertel 4483:     $result.='<h3>&nbsp;'.&mt('Student: [_1]',&nameUserString(undef,$$fullname{$env{'form.student'}},$uname,$udom)).
1.129     ng       4484: 	'</h3>'."\n";
1.500     albertel 4485:     $env{'form.CODE'} = uc($env{'form.CODE'});
1.501     foxr     4486:     if (&Apache::lonnet::validCODE(uc($env{'form.CODE'}))) {
1.485     albertel 4487: 	$result.='<h3>&nbsp;'.&mt('CODE: [_1]',$env{'form.CODE'}).'</h3>'."\n";
1.382     albertel 4488:     } else {
                   4489: 	delete($env{'form.CODE'});
                   4490:     }
1.71      ng       4491:     &sub_page_js($request);
                   4492:     $request->print($result);
                   4493: 
1.132     bowersj2 4494:     my $navmap = Apache::lonnavmaps::navmap->new();
1.582     raeburn  4495:     unless (ref($navmap)) {
                   4496:         $request->print(&navmap_errormsg());
                   4497:         $request->print(&show_grading_menu_form($symb));
                   4498:         return;
                   4499:     }
1.257     albertel 4500:     my ($mapUrl, $id, $resUrl)=&Apache::lonnet::decode_symb($env{'form.page'});
1.68      ng       4501:     my $map = $navmap->getResourceByUrl($resUrl); # add to navmaps
1.288     albertel 4502:     if (!$map) {
1.485     albertel 4503: 	$request->print('<span class="LC_warning">'.&mt('Unable to view requested sequence. ([_1])',$resUrl).'</span>');
1.324     albertel 4504: 	$request->print(&show_grading_menu_form($symb));
1.288     albertel 4505: 	return; 
                   4506:     }
1.68      ng       4507:     my $iterator = $navmap->getIterator($map->map_start(),
                   4508: 					$map->map_finish());
                   4509: 
1.71      ng       4510:     my $studentTable='<form action="/adm/grades" method="post" name="gradePage">'."\n".
1.72      ng       4511: 	'<input type="hidden" name="command" value="gradeByPage" />'."\n".
1.257     albertel 4512: 	'<input type="hidden" name="fullname" value="'.$$fullname{$env{'form.student'}}.'" />'."\n".
                   4513: 	'<input type="hidden" name="student" value="'.$env{'form.student'}.'" />'."\n".
1.72      ng       4514: 	'<input type="hidden" name="page"    value="'.$pageTitle.'" />'."\n".
1.257     albertel 4515: 	'<input type="hidden" name="title"   value="'.$env{'form.title'}.'" />'."\n".
1.418     albertel 4516: 	'<input type="hidden" name="symb"    value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
1.125     ng       4517: 	'<input type="hidden" name="overRideScore" value="no" />'."\n".
1.257     albertel 4518: 	'<input type="hidden" name="saveState" value="'.$env{'form.saveState'}.'" />'."\n";
1.71      ng       4519: 
1.382     albertel 4520:     if (defined($env{'form.CODE'})) {
                   4521: 	$studentTable.=
                   4522: 	    '<input type="hidden" name="CODE" value="'.$env{'form.CODE'}.'" />'."\n";
                   4523:     }
1.381     albertel 4524:     my $checkIcon = '<img alt="'.&mt('Check Mark').
1.485     albertel 4525: 	'" src="'.&Apache::loncommon::lonhttpdurl($request->dir_config('lonIconsURL').'/check.gif').'" height="16" border="0" />';
1.71      ng       4526: 
1.594     bisitz   4527:     $studentTable.='&nbsp;<span class="LC_info">'.
                   4528:         &mt('Problems graded correct by the computer are marked with a [_1] symbol.',$checkIcon).
                   4529:         '</span>'."\n".
1.484     albertel 4530: 	&Apache::loncommon::start_data_table().
                   4531: 	&Apache::loncommon::start_data_table_header_row().
                   4532: 	'<th align="center">&nbsp;Prob.&nbsp;</th>'.
1.485     albertel 4533: 	'<th>&nbsp;'.($env{'form.vProb'} eq 'no' ? &mt('Title') : &mt('Problem Text')).'/'.&mt('Grade').'</th>'.
1.484     albertel 4534: 	&Apache::loncommon::end_data_table_header_row();
1.71      ng       4535: 
1.329     albertel 4536:     &Apache::lonxml::clear_problem_counter();
1.196     albertel 4537:     my ($depth,$question,$prob) = (1,1,1);
1.68      ng       4538:     $iterator->next(); # skip the first BEGIN_MAP
                   4539:     my $curRes = $iterator->next(); # for "current resource"
1.101     albertel 4540:     while ($depth > 0) {
1.68      ng       4541:         if($curRes == $iterator->BEGIN_MAP) { $depth++; }
1.100     bowersj2 4542:         if($curRes == $iterator->END_MAP) { $depth--; }
1.68      ng       4543: 
1.385     albertel 4544:         if (ref($curRes) && $curRes->is_problem()) {
1.91      albertel 4545: 	    my $parts = $curRes->parts();
1.68      ng       4546:             my $title = $curRes->compTitle();
1.71      ng       4547: 	    my $symbx = $curRes->symb();
1.484     albertel 4548: 	    $studentTable.=
                   4549: 		&Apache::loncommon::start_data_table_row().
                   4550: 		'<td align="center" valign="top" >'.$prob.
1.485     albertel 4551: 		(scalar(@{$parts}) == 1 ? '' 
1.596.2.2  raeburn  4552: 		                        : '<br />('.&mt('[_1]parts)',
                   4553: 							scalar(@{$parts}).'&nbsp;')
1.485     albertel 4554: 		 ).
                   4555: 		 '</td>';
1.71      ng       4556: 	    $studentTable.='<td valign="top">';
1.382     albertel 4557: 	    my %form = ('CODE' => $env{'form.CODE'},);
1.257     albertel 4558: 	    if ($env{'form.vProb'} eq 'yes' ) {
1.144     albertel 4559: 		$studentTable.=&show_problem($request,$symbx,$uname,$udom,1,
1.383     albertel 4560: 					     undef,'both',\%form);
1.71      ng       4561: 	    } else {
1.382     albertel 4562: 		my $companswer = &Apache::loncommon::get_student_answers($symbx,$uname,$udom,$env{'request.course.id'},%form);
1.80      ng       4563: 		$companswer =~ s|<form(.*?)>||g;
                   4564: 		$companswer =~ s|</form>||g;
1.71      ng       4565: #		while ($companswer =~ /(<a href\=\"javascript:newWindow.*?Script Vars<\/a>)/s) { #<a href="javascript:newWindow</a>
1.116     ng       4566: #		    $companswer =~ s/$1/ /ms;
1.326     albertel 4567: #		    $request->print('match='.$1."<br />\n");
1.71      ng       4568: #		}
1.116     ng       4569: #		$companswer =~ s|<table border=\"1\">|<table border=\"0\">|g;
1.539     riegler  4570: 		$studentTable.='&nbsp;<b>'.$title.'</b>&nbsp;<br />&nbsp;<b>'.&mt('Correct answer').':</b><br />'.$companswer;
1.71      ng       4571: 	    }
                   4572: 
1.257     albertel 4573: 	    my %record = &Apache::lonnet::restore($symbx,$env{'request.course.id'},$udom,$uname);
1.125     ng       4574: 
1.257     albertel 4575: 	    if ($env{'form.lastSub'} eq 'datesub') {
1.71      ng       4576: 		if ($record{'version'} eq '') {
1.485     albertel 4577: 		    $studentTable.='<br />&nbsp;<span class="LC_warning">'.&mt('No recorded submission for this problem.').'</span><br />';
1.71      ng       4578: 		} else {
1.116     ng       4579: 		    my %responseType = ();
                   4580: 		    foreach my $partid (@{$parts}) {
1.147     albertel 4581: 			my @responseIds =$curRes->responseIds($partid);
                   4582: 			my @responseType =$curRes->responseType($partid);
                   4583: 			my %responseIds;
                   4584: 			for (my $i=0;$i<=$#responseIds;$i++) {
                   4585: 			    $responseIds{$responseIds[$i]}=$responseType[$i];
                   4586: 			}
                   4587: 			$responseType{$partid} = \%responseIds;
1.116     ng       4588: 		    }
1.148     albertel 4589: 		    $studentTable.= &displaySubByDates($symbx,\%record,$parts,\%responseType,$checkIcon,$uname,$udom);
1.147     albertel 4590: 
1.71      ng       4591: 		}
1.257     albertel 4592: 	    } elsif ($env{'form.lastSub'} eq 'all') {
                   4593: 		my $last = ($env{'form.lastSub'} eq 'last' ? 'last' : '');
1.71      ng       4594: 		$studentTable.=&Apache::loncommon::get_previous_attempt($symbx,$uname,$udom,
1.257     albertel 4595: 									$env{'request.course.id'},
1.71      ng       4596: 									'','.submission');
                   4597:  
                   4598: 	    }
1.103     albertel 4599: 	    if (&canmodify($usec)) {
1.585     bisitz   4600:             $studentTable.=&gradeBox_start();
1.103     albertel 4601: 		foreach my $partid (@{$parts}) {
                   4602: 		    $studentTable.=&gradeBox($request,$symbx,$uname,$udom,$question,$partid,\%record);
                   4603: 		    $studentTable.='<input type="hidden" name="q_'.$question.'" value="'.$partid.'" />'."\n";
                   4604: 		    $question++;
                   4605: 		}
1.585     bisitz   4606:             $studentTable.=&gradeBox_end();
1.196     albertel 4607: 		$prob++;
1.71      ng       4608: 	    }
                   4609: 	    $studentTable.='</td></tr>';
1.68      ng       4610: 
1.103     albertel 4611: 	}
1.68      ng       4612:         $curRes = $iterator->next();
                   4613:     }
                   4614: 
1.589     bisitz   4615:     $studentTable.=
                   4616:         '</table>'."\n".
                   4617:         '<input type="button" value="'.&mt('Save').'" '.
                   4618:         'onclick="javascript:checkSubmitPage(this.form,'.$question.');" />'.
                   4619:         '</form>'."\n";
1.324     albertel 4620:     $studentTable.=&show_grading_menu_form($symb);
1.71      ng       4621:     $request->print($studentTable);
                   4622: 
                   4623:     return '';
1.119     ng       4624: }
                   4625: 
                   4626: sub displaySubByDates {
1.148     albertel 4627:     my ($symb,$record,$parts,$responseType,$checkIcon,$uname,$udom) = @_;
1.224     albertel 4628:     my $isCODE=0;
1.335     albertel 4629:     my $isTask = ($symb =~/\.task$/);
1.224     albertel 4630:     if (exists($record->{'resource.CODE'})) { $isCODE=1; }
1.467     albertel 4631:     my $studentTable=&Apache::loncommon::start_data_table().
                   4632: 	&Apache::loncommon::start_data_table_header_row().
                   4633: 	'<th>'.&mt('Date/Time').'</th>'.
                   4634: 	($isCODE?'<th>'.&mt('CODE').'</th>':'').
                   4635: 	'<th>'.&mt('Submission').'</th>'.
                   4636: 	'<th>'.&mt('Status').'</th>'.
                   4637: 	&Apache::loncommon::end_data_table_header_row();
1.119     ng       4638:     my ($version);
                   4639:     my %mark;
1.148     albertel 4640:     my %orders;
1.119     ng       4641:     $mark{'correct_by_student'} = $checkIcon;
1.147     albertel 4642:     if (!exists($$record{'1:timestamp'})) {
1.539     riegler  4643: 	return '<br />&nbsp;<span class="LC_warning">'.&mt('Nothing submitted - no attempts.').'</span><br />';
1.147     albertel 4644:     }
1.335     albertel 4645: 
                   4646:     my $interaction;
1.525     raeburn  4647:     my $no_increment = 1;
1.596.2.2  raeburn  4648:     my %lastrndseed;
1.119     ng       4649:     for ($version=1;$version<=$$record{'version'};$version++) {
1.467     albertel 4650: 	my $timestamp = 
                   4651: 	    &Apache::lonlocal::locallocaltime($$record{$version.':timestamp'});
1.335     albertel 4652: 	if (exists($$record{$version.':resource.0.version'})) {
                   4653: 	    $interaction = $$record{$version.':resource.0.version'};
                   4654: 	}
                   4655: 
                   4656: 	my $where = ($isTask ? "$version:resource.$interaction"
                   4657: 		             : "$version:resource");
1.467     albertel 4658: 	$studentTable.=&Apache::loncommon::start_data_table_row().
                   4659: 	    '<td>'.$timestamp.'</td>';
1.224     albertel 4660: 	if ($isCODE) {
                   4661: 	    $studentTable.='<td>'.$record->{$version.':resource.CODE'}.'</td>';
                   4662: 	}
1.119     ng       4663: 	my @versionKeys = split(/\:/,$$record{$version.':keys'});
                   4664: 	my @displaySub = ();
                   4665: 	foreach my $partid (@{$parts}) {
1.596.2.2  raeburn  4666:             my ($hidden,$type);
                   4667:             $type = $$record{$version.':resource.'.$partid.'.type'};
                   4668:             if (($type eq 'anonsurvey') || ($type eq 'anonsurveycred')) {
1.596     raeburn  4669:                 $hidden = 1;
                   4670:             }
1.335     albertel 4671: 	    my @matchKey = ($isTask ? sort(grep /^resource\.\d+\.\Q$partid\E\.award$/,@versionKeys)
                   4672: 			            : sort(grep /^resource\.\Q$partid\E\..*?\.submission$/,@versionKeys));
                   4673: 	    
1.122     ng       4674: #	    next if ($$record{"$version:resource.$partid.solved"} eq '');
1.324     albertel 4675: 	    my $display_part=&get_display_part($partid,$symb);
1.147     albertel 4676: 	    foreach my $matchKey (@matchKey) {
1.198     albertel 4677: 		if (exists($$record{$version.':'.$matchKey}) &&
                   4678: 		    $$record{$version.':'.$matchKey} ne '') {
1.596     raeburn  4679:                     
1.335     albertel 4680: 		    my ($responseId)= ($isTask ? ($matchKey=~ /^resource\.(.*?)\.\Q$partid\E\.award$/)
                   4681: 				               : ($matchKey=~ /^resource\.\Q$partid\E\.(.*?)\.submission$/));
1.577     bisitz   4682:                     $displaySub[0].='<span class="LC_nobreak"';
                   4683:                     $displaySub[0].='<b>'.&mt('Part: [_1]',$display_part).'</b>'
                   4684:                                    .' <span class="LC_internal_info">'
                   4685:                                    .'('.&mt('Part ID: [_1]',$responseId).')'
                   4686:                                    .'</span>'
                   4687:                                    .' <b>';
1.596     raeburn  4688:                     if ($hidden) {
                   4689:                         $displaySub[0].= &mt('Anonymous Survey').'</b>';
                   4690:                     } else {
1.596.2.2  raeburn  4691:                         my ($trial,$rndseed,$newvariation);
                   4692:                         if ($type eq 'randomizetry') {
                   4693:                             $trial = $$record{"$where.$partid.tries"};
                   4694:                             $rndseed = $$record{"$where.$partid.rndseed"};
                   4695:                         }
1.596     raeburn  4696: 		        if ($$record{"$where.$partid.tries"} eq '') {
                   4697: 			    $displaySub[0].=&mt('Trial not counted');
                   4698: 		        } else {
                   4699: 			    $displaySub[0].=&mt('Trial: [_1]',
1.467     albertel 4700: 					    $$record{"$where.$partid.tries"});
1.596.2.2  raeburn  4701:                             if ($rndseed || $lastrndseed{$partid}) {
                   4702:                                 if ($rndseed ne $lastrndseed{$partid}) {
                   4703:                                     $newvariation = '&nbsp;('.&mt('New variation this try').')';
                   4704:                                 }
                   4705:                             }
1.596     raeburn  4706: 		        }
                   4707: 		        my $responseType=($isTask ? 'Task'
1.335     albertel 4708:                                               : $responseType->{$partid}->{$responseId});
1.596     raeburn  4709: 		        if (!exists($orders{$partid})) { $orders{$partid}={}; }
1.596.2.2  raeburn  4710: 		        if ((!exists($orders{$partid}->{$responseId})) || ($trial)) {
1.596     raeburn  4711: 			    $orders{$partid}->{$responseId}=
                   4712: 			        &get_order($partid,$responseId,$symb,$uname,$udom,
1.596.2.2  raeburn  4713:                                            $no_increment,$type,$trial,$rndseed);
1.596     raeburn  4714: 		        }
1.596.2.2  raeburn  4715: 		        $displaySub[0].='</b>'.$newvariation.'</span>'; # /nobreak
1.596     raeburn  4716: 		        $displaySub[0].='&nbsp; '.
1.596.2.2  raeburn  4717: 			    &cleanRecord($$record{$version.':'.$matchKey},$responseType,$symb,$partid,$responseId,$record,$orders{$partid}->{$responseId},"$version:",$uname,$udom,$type,$trial,$rndseed).'<br />';
1.596     raeburn  4718:                     }
1.147     albertel 4719: 		}
                   4720: 	    }
1.335     albertel 4721: 	    if (exists($$record{"$where.$partid.checkedin"})) {
1.485     albertel 4722: 		$displaySub[1].=&mt('Checked in by [_1] into slot [_2]',
                   4723: 				    $$record{"$where.$partid.checkedin"},
                   4724: 				    $$record{"$where.$partid.checkedin.slot"}).
                   4725: 					'<br />';
1.335     albertel 4726: 	    }
                   4727: 	    if (exists $$record{"$where.$partid.award"}) {
1.485     albertel 4728: 		$displaySub[1].='<b>'.&mt('Part:').'</b>&nbsp;'.$display_part.' &nbsp;'.
1.335     albertel 4729: 		    lc($$record{"$where.$partid.award"}).' '.
                   4730: 		    $mark{$$record{"$where.$partid.solved"}}.
1.147     albertel 4731: 		    '<br />';
                   4732: 	    }
1.335     albertel 4733: 	    if (exists $$record{"$where.$partid.regrader"}) {
                   4734: 		$displaySub[2].=$$record{"$where.$partid.regrader"}.
                   4735: 		    ' (<b>'.&mt('Part').':</b> '.$display_part.')';
                   4736: 	    } elsif ($$record{"$version:resource.$partid.regrader"} =~ /\S/) {
                   4737: 		$displaySub[2].=
                   4738: 		    $$record{"$version:resource.$partid.regrader"}.
1.207     albertel 4739: 		    ' (<b>'.&mt('Part').':</b> '.$display_part.')';
1.147     albertel 4740: 	    }
                   4741: 	}
                   4742: 	# needed because old essay regrader has not parts info
                   4743: 	if (exists $$record{"$version:resource.regrader"}) {
                   4744: 	    $displaySub[2].=$$record{"$version:resource.regrader"};
                   4745: 	}
                   4746: 	$studentTable.='<td>'.$displaySub[0].'&nbsp;</td><td>'.$displaySub[1];
                   4747: 	if ($displaySub[2]) {
1.467     albertel 4748: 	    $studentTable.=&mt('Manually graded by [_1]',$displaySub[2]);
1.147     albertel 4749: 	}
1.467     albertel 4750: 	$studentTable.='&nbsp;</td>'.
                   4751: 	    &Apache::loncommon::end_data_table_row();
1.119     ng       4752:     }
1.467     albertel 4753:     $studentTable.=&Apache::loncommon::end_data_table();
1.119     ng       4754:     return $studentTable;
1.71      ng       4755: }
                   4756: 
                   4757: sub updateGradeByPage {
                   4758:     my ($request) = shift;
                   4759: 
1.257     albertel 4760:     my $cdom      = $env{"course.$env{'request.course.id'}.domain"};
                   4761:     my $cnum      = $env{"course.$env{'request.course.id'}.num"};
                   4762:     my $getsec    = $env{'form.section'} eq '' ? 'all' : $env{'form.section'};
                   4763:     my $pageTitle = $env{'form.page'};
1.103     albertel 4764:     my ($classlist,undef,$fullname) = &getclasslist($getsec,'1');
1.257     albertel 4765:     my ($uname,$udom) = split(/:/,$env{'form.student'});
                   4766:     my $usec=$classlist->{$env{'form.student'}}[5];
1.103     albertel 4767:     if (!&canmodify($usec)) {
1.526     raeburn  4768: 	$request->print('<span class="LC_warning">'.&mt('Unable to modify requested student ([_1])',$env{'form.student'}).'</span>');
1.324     albertel 4769: 	$request->print(&show_grading_menu_form($env{'form.symb'}));
1.103     albertel 4770: 	return;
                   4771:     }
1.398     albertel 4772:     my $result='<h3><span class="LC_info">&nbsp;'.$env{'form.title'}.'</span></h3>';
1.526     raeburn  4773:     $result.='<h3>&nbsp;'.&mt('Student: ').&nameUserString(undef,$env{'form.fullname'},$uname,$udom).
1.129     ng       4774: 	'</h3>'."\n";
1.70      ng       4775: 
1.68      ng       4776:     $request->print($result);
                   4777: 
1.582     raeburn  4778: 
1.132     bowersj2 4779:     my $navmap = Apache::lonnavmaps::navmap->new();
1.582     raeburn  4780:     unless (ref($navmap)) {
                   4781:         $request->print(&navmap_errormsg());
                   4782:         return;
                   4783:     }
1.257     albertel 4784:     my ($mapUrl, $id, $resUrl) = &Apache::lonnet::decode_symb( $env{'form.page'});
1.71      ng       4785:     my $map = $navmap->getResourceByUrl($resUrl); # add to navmaps
1.288     albertel 4786:     if (!$map) {
1.527     raeburn  4787: 	$request->print('<span class="LC_warning">'.&mt('Unable to grade requested sequence ([_1]).',$resUrl).'</span>');
1.324     albertel 4788: 	my ($symb)=&get_symb($request);
                   4789: 	$request->print(&show_grading_menu_form($symb));
1.288     albertel 4790: 	return; 
                   4791:     }
1.71      ng       4792:     my $iterator = $navmap->getIterator($map->map_start(),
                   4793: 					$map->map_finish());
1.70      ng       4794: 
1.484     albertel 4795:     my $studentTable=
                   4796: 	&Apache::loncommon::start_data_table().
                   4797: 	&Apache::loncommon::start_data_table_header_row().
1.485     albertel 4798: 	'<th align="center">&nbsp;'.&mt('Prob.').'&nbsp;</th>'.
                   4799: 	'<th>&nbsp;'.&mt('Title').'&nbsp;</th>'.
                   4800: 	'<th>&nbsp;'.&mt('Previous Score').'&nbsp;</th>'.
                   4801: 	'<th>&nbsp;'.&mt('New Score').'&nbsp;</th>'.
1.484     albertel 4802: 	&Apache::loncommon::end_data_table_header_row();
1.71      ng       4803: 
                   4804:     $iterator->next(); # skip the first BEGIN_MAP
                   4805:     my $curRes = $iterator->next(); # for "current resource"
1.196     albertel 4806:     my ($depth,$question,$prob,$changeflag)= (1,1,1,0);
1.101     albertel 4807:     while ($depth > 0) {
1.71      ng       4808:         if($curRes == $iterator->BEGIN_MAP) { $depth++; }
1.100     bowersj2 4809:         if($curRes == $iterator->END_MAP) { $depth--; }
1.71      ng       4810: 
1.385     albertel 4811:         if (ref($curRes) && $curRes->is_problem()) {
1.91      albertel 4812: 	    my $parts = $curRes->parts();
1.71      ng       4813:             my $title = $curRes->compTitle();
                   4814: 	    my $symbx = $curRes->symb();
1.484     albertel 4815: 	    $studentTable.=
                   4816: 		&Apache::loncommon::start_data_table_row().
                   4817: 		'<td align="center" valign="top" >'.$prob.
1.485     albertel 4818: 		(scalar(@{$parts}) == 1 ? '' 
1.596.2.2  raeburn  4819:                                         : '<br />('.&mt('[quant,_1,part]',scalar(@{$parts}))
1.526     raeburn  4820: 		.')').'</td>';
1.71      ng       4821: 	    $studentTable.='<td valign="top">&nbsp;<b>'.$title.'</b>&nbsp;</td>';
                   4822: 
                   4823: 	    my %newrecord=();
                   4824: 	    my @displayPts=();
1.269     raeburn  4825:             my %aggregate = ();
                   4826:             my $aggregateflag = 0;
1.71      ng       4827: 	    foreach my $partid (@{$parts}) {
1.257     albertel 4828: 		my $newpts = $env{'form.GD_BOX'.$question.'_'.$partid};
                   4829: 		my $oldpts = $env{'form.oldpts'.$question.'_'.$partid};
1.71      ng       4830: 
1.257     albertel 4831: 		my $wgt = $env{'form.WGT'.$question.'_'.$partid} != 0 ? 
                   4832: 		    $env{'form.WGT'.$question.'_'.$partid} : 1;
1.71      ng       4833: 		my $partial = $newpts/$wgt;
                   4834: 		my $score;
                   4835: 		if ($partial > 0) {
                   4836: 		    $score = 'correct_by_override';
1.125     ng       4837: 		} elsif ($newpts ne '') { #empty is taken as 0
1.71      ng       4838: 		    $score = 'incorrect_by_override';
                   4839: 		}
1.257     albertel 4840: 		my $dropMenu = $env{'form.GD_SEL'.$question.'_'.$partid};
1.125     ng       4841: 		if ($dropMenu eq 'excused') {
1.71      ng       4842: 		    $partial = '';
                   4843: 		    $score = 'excused';
1.125     ng       4844: 		} elsif ($dropMenu eq 'reset status'
1.257     albertel 4845: 			 && $env{'form.solved'.$question.'_'.$partid} ne '') { #update only if previous record exists
1.125     ng       4846: 		    $newrecord{'resource.'.$partid.'.tries'} = 0;
                   4847: 		    $newrecord{'resource.'.$partid.'.solved'} = '';
                   4848: 		    $newrecord{'resource.'.$partid.'.award'} = '';
                   4849: 		    $newrecord{'resource.'.$partid.'.awarded'} = 0;
1.257     albertel 4850: 		    $newrecord{'resource.'.$partid.'.regrader'} = "$env{'user.name'}:$env{'user.domain'}";
1.125     ng       4851: 		    $changeflag++;
                   4852: 		    $newpts = '';
1.269     raeburn  4853:                     
                   4854:                     my $aggtries =  $env{'form.aggtries'.$question.'_'.$partid};
                   4855:                     my $totaltries = $env{'form.totaltries'.$question.'_'.$partid};
                   4856:                     my $solvedstatus = $env{'form.solved'.$question.'_'.$partid};
                   4857:                     if ($aggtries > 0) {
                   4858:                         &decrement_aggs($symbx,$partid,\%aggregate,$aggtries,$totaltries,$solvedstatus);
                   4859:                         $aggregateflag = 1;
                   4860:                     }
1.71      ng       4861: 		}
1.324     albertel 4862: 		my $display_part=&get_display_part($partid,$curRes->symb());
1.257     albertel 4863: 		my $oldstatus = $env{'form.solved'.$question.'_'.$partid};
1.526     raeburn  4864: 		$displayPts[0].='&nbsp;<b>'.&mt('Part').':</b> '.$display_part.' = '.
1.71      ng       4865: 		    (($oldstatus eq 'excused') ? 'excused' : $oldpts).
1.326     albertel 4866: 		    '&nbsp;<br />';
1.526     raeburn  4867: 		$displayPts[1].='&nbsp;<b>'.&mt('Part').':</b> '.$display_part.' = '.
1.125     ng       4868: 		     (($score eq 'excused') ? 'excused' : $newpts).
1.326     albertel 4869: 		    '&nbsp;<br />';
1.71      ng       4870: 		$question++;
1.380     albertel 4871: 		next if ($dropMenu eq 'reset status' || ($newpts eq $oldpts && $score ne 'excused'));
1.125     ng       4872: 
1.71      ng       4873: 		$newrecord{'resource.'.$partid.'.awarded'}  = $partial if $partial ne '';
1.125     ng       4874: 		$newrecord{'resource.'.$partid.'.solved'}   = $score if $score ne '';
1.257     albertel 4875: 		$newrecord{'resource.'.$partid.'.regrader'} = "$env{'user.name'}:$env{'user.domain'}"
1.125     ng       4876: 		    if (scalar(keys(%newrecord)) > 0);
1.71      ng       4877: 
                   4878: 		$changeflag++;
                   4879: 	    }
                   4880: 	    if (scalar(keys(%newrecord)) > 0) {
1.382     albertel 4881: 		my %record = 
                   4882: 		    &Apache::lonnet::restore($symbx,$env{'request.course.id'},
                   4883: 					     $udom,$uname);
                   4884: 
                   4885: 		if (&Apache::lonnet::validCODE($env{'form.CODE'})) {
                   4886: 		    $newrecord{'resource.CODE'} = $env{'form.CODE'};
                   4887: 		} elsif (&Apache::lonnet::validCODE($record{'resource.CODE'})) {
                   4888: 		    $newrecord{'resource.CODE'} = '';
                   4889: 		}
1.257     albertel 4890: 		&Apache::lonnet::cstore(\%newrecord,$symbx,$env{'request.course.id'},
1.71      ng       4891: 					$udom,$uname);
1.382     albertel 4892: 		%record = &Apache::lonnet::restore($symbx,
                   4893: 						   $env{'request.course.id'},
                   4894: 						   $udom,$uname);
1.380     albertel 4895: 		&check_and_remove_from_queue($parts,\%record,undef,$symbx,
                   4896: 					     $cdom,$cnum,$udom,$uname);
1.71      ng       4897: 	    }
1.380     albertel 4898: 	    
1.269     raeburn  4899:             if ($aggregateflag) {
                   4900:                 &Apache::lonnet::cinc('nohist_resourcetracker',\%aggregate,
                   4901:                       $env{'course.'.$env{'request.course.id'}.'.domain'},
                   4902:                       $env{'course.'.$env{'request.course.id'}.'.num'});
                   4903:             }
1.125     ng       4904: 
1.71      ng       4905: 	    $studentTable.='<td valign="top">'.$displayPts[0].'</td>'.
                   4906: 		'<td valign="top">'.$displayPts[1].'</td>'.
1.484     albertel 4907: 		&Apache::loncommon::end_data_table_row();
1.68      ng       4908: 
1.196     albertel 4909: 	    $prob++;
1.68      ng       4910: 	}
1.71      ng       4911:         $curRes = $iterator->next();
1.68      ng       4912:     }
1.98      albertel 4913: 
1.484     albertel 4914:     $studentTable.=&Apache::loncommon::end_data_table();
1.324     albertel 4915:     $studentTable.=&show_grading_menu_form($env{'form.symb'});
1.526     raeburn  4916:     my $grademsg=($changeflag == 0 ? &mt('No score was changed or updated.') :
                   4917: 		  &mt('The scores were changed for [quant,_1,problem].',
                   4918: 		  $changeflag));
1.76      ng       4919:     $request->print($grademsg.$studentTable);
1.68      ng       4920: 
1.70      ng       4921:     return '';
                   4922: }
                   4923: 
1.72      ng       4924: #-------- end of section for handling grading by page/sequence ---------
                   4925: #
                   4926: #-------------------------------------------------------------------
                   4927: 
1.581     www      4928: #-------------------- Bubblesheet (Scantron) Grading -------------------
1.75      albertel 4929: #
                   4930: #------ start of section for handling grading by page/sequence ---------
                   4931: 
1.423     albertel 4932: =pod
                   4933: 
                   4934: =head1 Bubble sheet grading routines
                   4935: 
1.424     albertel 4936:   For this documentation:
                   4937: 
                   4938:    'scanline' refers to the full line of characters
                   4939:    from the file that we are parsing that represents one entire sheet
                   4940: 
                   4941:    'bubble line' refers to the data
                   4942:    representing the line of bubbles that are on the physical bubble sheet
                   4943: 
                   4944: 
                   4945: The overall process is that a scanned in bubble sheet data is uploaded
                   4946: into a course. When a user wants to grade, they select a
                   4947: sequence/folder of resources, a file of bubble sheet info, and pick
                   4948: one of the predefined configurations for what each scanline looks
                   4949: like.
                   4950: 
                   4951: Next each scanline is checked for any errors of either 'missing
1.435     foxr     4952: bubbles' (it's an error because it may have been mis-scanned
1.424     albertel 4953: because too light bubbling), 'double bubble' (each bubble line should
                   4954: have no more that one letter picked), invalid or duplicated CODE,
1.556     weissno  4955: invalid student/employee ID
1.424     albertel 4956: 
                   4957: If the CODE option is used that determines the randomization of the
1.556     weissno  4958: homework problems, either way the student/employee ID is looked up into a
1.424     albertel 4959: username:domain.
                   4960: 
                   4961: During the validation phase the instructor can choose to skip scanlines. 
                   4962: 
1.435     foxr     4963: After the validation phase, there are now 3 bubble sheet files
1.424     albertel 4964: 
                   4965:   scantron_original_filename (unmodified original file)
                   4966:   scantron_corrected_filename (file where the corrected information has replaced the original information)
                   4967:   scantron_skipped_filename (contains the exact text of scanlines that where skipped)
                   4968: 
                   4969: Also there is a separate hash nohist_scantrondata that contains extra
                   4970: correction information that isn't representable in the bubble sheet
                   4971: file (see &scantron_getfile() for more information)
                   4972: 
                   4973: After all scanlines are either valid, marked as valid or skipped, then
                   4974: foreach line foreach problem in the picked sequence, an ssi request is
                   4975: made that simulates a user submitting their selected letter(s) against
                   4976: the homework problem.
1.423     albertel 4977: 
                   4978: =over 4
                   4979: 
                   4980: 
                   4981: 
                   4982: =item defaultFormData
                   4983: 
                   4984:   Returns html hidden inputs used to hold context/default values.
                   4985: 
                   4986:  Arguments:
                   4987:   $symb - $symb of the current resource 
                   4988: 
                   4989: =cut
1.422     foxr     4990: 
1.81      albertel 4991: sub defaultFormData {
1.324     albertel 4992:     my ($symb)=@_;
1.447     foxr     4993:     return '<input type="hidden" name="symb"    value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
1.257     albertel 4994:      '<input type="hidden" name="saveState" value="'.$env{'form.saveState'}.'" />'."\n".
                   4995:      '<input type="hidden" name="probTitle" value="'.$env{'form.probTitle'}.'" />'."\n";
1.81      albertel 4996: }
                   4997: 
1.447     foxr     4998: 
1.423     albertel 4999: =pod 
                   5000: 
                   5001: =item getSequenceDropDown
                   5002: 
                   5003:    Return html dropdown of possible sequences to grade
                   5004:  
                   5005:  Arguments:
1.582     raeburn  5006:    $symb - $symb of the current resource
                   5007:    $map_error - ref to scalar which will container error if
                   5008:                 $navmap object is unavailable in &getSymbMap().
1.423     albertel 5009: 
                   5010: =cut
1.422     foxr     5011: 
1.75      albertel 5012: sub getSequenceDropDown {
1.582     raeburn  5013:     my ($symb,$map_error)=@_;
1.75      albertel 5014:     my $result='<select name="selectpage">'."\n";
1.582     raeburn  5015:     my ($titles,$symbx) = &getSymbMap($map_error);
                   5016:     if (ref($map_error)) {
                   5017:         return if ($$map_error);
                   5018:     }
1.137     albertel 5019:     my ($curpage)=&Apache::lonnet::decode_symb($symb); 
1.75      albertel 5020:     my $ctr=0;
                   5021:     foreach (@$titles) {
                   5022: 	my ($minder,$showtitle) = ($_ =~ /(\d+)\.(.*)/);
                   5023: 	$result.='<option value="'.$$symbx{$_}.'" '.
1.401     albertel 5024: 	    ($$symbx{$_} =~ /$curpage$/ ? 'selected="selected"' : '').
1.75      albertel 5025: 	    '>'.$showtitle.'</option>'."\n";
                   5026: 	$ctr++;
                   5027:     }
                   5028:     $result.= '</select>';
                   5029:     return $result;
                   5030: }
                   5031: 
1.495     albertel 5032: my %bubble_lines_per_response;     # no. bubble lines for each response.
1.554     raeburn  5033:                                    # key is zero-based index - 0, 1, 2 ...
1.495     albertel 5034: 
                   5035: my %first_bubble_line;             # First bubble line no. for each bubble.
                   5036: 
1.509     raeburn  5037: my %subdivided_bubble_lines;       # no. bubble lines for optionresponse, 
                   5038:                                    # matchresponse or rankresponse, where 
                   5039:                                    # an individual response can have multiple 
                   5040:                                    # lines
1.503     raeburn  5041: 
                   5042: my %responsetype_per_response;     # responsetype for each response
                   5043: 
1.495     albertel 5044: # Save and restore the bubble lines array to the form env.
                   5045: 
                   5046: 
                   5047: sub save_bubble_lines {
                   5048:     foreach my $line (keys(%bubble_lines_per_response)) {
                   5049: 	$env{"form.scantron.bubblelines.$line"}  = $bubble_lines_per_response{$line};
                   5050: 	$env{"form.scantron.first_bubble_line.$line"} =
                   5051: 	    $first_bubble_line{$line};
1.503     raeburn  5052:         $env{"form.scantron.sub_bubblelines.$line"} = 
                   5053:             $subdivided_bubble_lines{$line};
                   5054:         $env{"form.scantron.responsetype.$line"} =
                   5055:             $responsetype_per_response{$line};
1.495     albertel 5056:     }
                   5057: }
                   5058: 
                   5059: 
                   5060: sub restore_bubble_lines {
                   5061:     my $line = 0;
                   5062:     %bubble_lines_per_response = ();
                   5063:     while ($env{"form.scantron.bubblelines.$line"}) {
                   5064: 	my $value = $env{"form.scantron.bubblelines.$line"};
                   5065: 	$bubble_lines_per_response{$line} = $value;
                   5066: 	$first_bubble_line{$line}  =
                   5067: 	    $env{"form.scantron.first_bubble_line.$line"};
1.503     raeburn  5068:         $subdivided_bubble_lines{$line} =
                   5069:             $env{"form.scantron.sub_bubblelines.$line"};
                   5070:         $responsetype_per_response{$line} =
                   5071:             $env{"form.scantron.responsetype.$line"};
1.495     albertel 5072: 	$line++;
                   5073:     }
                   5074: }
                   5075: 
                   5076: #  Given the parsed scanline, get the response for 
                   5077: #  'answer' number n:
                   5078: 
                   5079: sub get_response_bubbles {
                   5080:     my ($parsed_line, $response)  = @_;
                   5081: 
                   5082:     my $bubble_line = $first_bubble_line{$response-1} +1;
                   5083:     my $bubble_lines= $bubble_lines_per_response{$response-1};
                   5084:     
                   5085:     my $selected = "";
                   5086: 
                   5087:     for (my $bline = 0; $bline < $bubble_lines; $bline++) {
                   5088: 	$selected .= $$parsed_line{"scantron.$bubble_line.answer"}.":";
                   5089: 	$bubble_line++;
                   5090:     }
                   5091:     return $selected;
                   5092: }
1.423     albertel 5093: 
                   5094: =pod 
                   5095: 
                   5096: =item scantron_filenames
                   5097: 
                   5098:    Returns a list of the scantron files in the current course 
                   5099: 
                   5100: =cut
1.422     foxr     5101: 
1.202     albertel 5102: sub scantron_filenames {
1.257     albertel 5103:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
                   5104:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
1.517     raeburn  5105:     my $getpropath = 1;
1.157     albertel 5106:     my @files=&Apache::lonnet::dirlist('userfiles',$cdom,$cname,
1.517     raeburn  5107:                                        $getpropath);
1.202     albertel 5108:     my @possiblenames;
1.201     albertel 5109:     foreach my $filename (sort(@files)) {
1.157     albertel 5110: 	($filename)=split(/&/,$filename);
                   5111: 	if ($filename!~/^scantron_orig_/) { next ; }
                   5112: 	$filename=~s/^scantron_orig_//;
1.202     albertel 5113: 	push(@possiblenames,$filename);
                   5114:     }
                   5115:     return @possiblenames;
                   5116: }
                   5117: 
1.423     albertel 5118: =pod 
                   5119: 
                   5120: =item scantron_uploads
                   5121: 
                   5122:    Returns  html drop-down list of scantron files in current course.
                   5123: 
                   5124:  Arguments:
                   5125:    $file2grade - filename to set as selected in the dropdown
                   5126: 
                   5127: =cut
1.422     foxr     5128: 
1.202     albertel 5129: sub scantron_uploads {
1.209     ng       5130:     my ($file2grade) = @_;
1.202     albertel 5131:     my $result=	'<select name="scantron_selectfile">';
                   5132:     $result.="<option></option>";
                   5133:     foreach my $filename (sort(&scantron_filenames())) {
1.401     albertel 5134: 	$result.="<option".($filename eq $file2grade ? ' selected="selected"':'').">$filename</option>\n";
1.81      albertel 5135:     }
                   5136:     $result.="</select>";
                   5137:     return $result;
                   5138: }
                   5139: 
1.423     albertel 5140: =pod 
                   5141: 
                   5142: =item scantron_scantab
                   5143: 
                   5144:   Returns html drop down of the scantron formats in the scantronformat.tab
                   5145:   file.
                   5146: 
                   5147: =cut
1.422     foxr     5148: 
1.82      albertel 5149: sub scantron_scantab {
                   5150:     my $result='<select name="scantron_format">'."\n";
1.191     albertel 5151:     $result.='<option></option>'."\n";
1.518     raeburn  5152:     my @lines = &get_scantronformat_file();
                   5153:     if (@lines > 0) {
                   5154:         foreach my $line (@lines) {
                   5155:             next if (($line =~ /^\#/) || ($line eq ''));
                   5156: 	    my ($name,$descrip)=split(/:/,$line);
                   5157: 	    $result.='<option value="'.$name.'">'.$descrip.'</option>'."\n";
                   5158:         }
1.82      albertel 5159:     }
                   5160:     $result.='</select>'."\n";
1.518     raeburn  5161:     return $result;
                   5162: }
                   5163: 
                   5164: =pod
                   5165: 
                   5166: =item get_scantronformat_file
                   5167: 
                   5168:   Returns an array containing lines from the scantron format file for
                   5169:   the domain of the course.
                   5170: 
                   5171:   If a url for a custom.tab file is listed in domain's configuration.db, 
                   5172:   lines are from this file.
                   5173: 
                   5174:   Otherwise, if a default.tab has been published in RES space by the 
                   5175:   domainconfig user, lines are from this file.
                   5176: 
                   5177:   Otherwise, fall back to getting lines from the legacy file on the
1.519     raeburn  5178:   local server:  /home/httpd/lonTabs/default_scantronformat.tab    
1.82      albertel 5179: 
1.518     raeburn  5180: =cut
                   5181: 
                   5182: sub get_scantronformat_file {
                   5183:     my $cdom= $env{'course.'.$env{'request.course.id'}.'.domain'};
                   5184:     my %domconfig = &Apache::lonnet::get_dom('configuration',['scantron'],$cdom);
                   5185:     my $gottab = 0;
                   5186:     my @lines;
                   5187:     if (ref($domconfig{'scantron'}) eq 'HASH') {
                   5188:         if ($domconfig{'scantron'}{'scantronformat'} ne '') {
                   5189:             my $formatfile = &Apache::lonnet::getfile($Apache::lonnet::perlvar{'lonDocRoot'}.$domconfig{'scantron'}{'scantronformat'});
                   5190:             if ($formatfile ne '-1') {
                   5191:                 @lines = split("\n",$formatfile,-1);
                   5192:                 $gottab = 1;
                   5193:             }
                   5194:         }
                   5195:     }
                   5196:     if (!$gottab) {
                   5197:         my $confname = $cdom.'-domainconfig';
                   5198:         my $default = $Apache::lonnet::perlvar{'lonDocRoot'}.'/res/'.$cdom.'/'.$confname.'/default.tab';
                   5199:         my $formatfile =  &Apache::lonnet::getfile($default);
                   5200:         if ($formatfile ne '-1') {
                   5201:             @lines = split("\n",$formatfile,-1);
                   5202:             $gottab = 1;
                   5203:         }
                   5204:     }
                   5205:     if (!$gottab) {
1.519     raeburn  5206:         my @domains = &Apache::lonnet::current_machine_domains();
                   5207:         if (grep(/^\Q$cdom\E$/,@domains)) {
                   5208:             my $fh=Apache::File->new($Apache::lonnet::perlvar{'lonTabDir'}.'/scantronformat.tab');
                   5209:             @lines = <$fh>;
                   5210:             close($fh);
                   5211:         } else {
                   5212:             my $fh=Apache::File->new($Apache::lonnet::perlvar{'lonTabDir'}.'/default_scantronformat.tab');
                   5213:             @lines = <$fh>;
                   5214:             close($fh);
                   5215:         }
1.518     raeburn  5216:     }
                   5217:     return @lines;
1.82      albertel 5218: }
                   5219: 
1.423     albertel 5220: =pod 
                   5221: 
                   5222: =item scantron_CODElist
                   5223: 
                   5224:   Returns html drop down of the saved CODE lists from current course,
                   5225:   generated from earlier printings.
                   5226: 
                   5227: =cut
1.422     foxr     5228: 
1.186     albertel 5229: sub scantron_CODElist {
1.257     albertel 5230:     my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   5231:     my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
1.186     albertel 5232:     my @names=&Apache::lonnet::getkeys('CODEs',$cdom,$cnum);
                   5233:     my $namechoice='<option></option>';
1.225     albertel 5234:     foreach my $name (sort {uc($a) cmp uc($b)} @names) {
1.191     albertel 5235: 	if ($name =~ /^error: 2 /) { next; }
1.278     albertel 5236: 	if ($name =~ /^type\0/) { next; }
1.186     albertel 5237: 	$namechoice.='<option value="'.$name.'">'.$name.'</option>';
                   5238:     }
                   5239:     $namechoice='<select name="scantron_CODElist">'.$namechoice.'</select>';
                   5240:     return $namechoice;
                   5241: }
                   5242: 
1.423     albertel 5243: =pod 
                   5244: 
                   5245: =item scantron_CODEunique
                   5246: 
                   5247:   Returns the html for "Each CODE to be used once" radio.
                   5248: 
                   5249: =cut
1.422     foxr     5250: 
1.186     albertel 5251: sub scantron_CODEunique {
1.532     bisitz   5252:     my $result='<span class="LC_nobreak">
1.272     albertel 5253:                  <label><input type="radio" name="scantron_CODEunique"
1.423     albertel 5254:                         value="yes" checked="checked" />'.&mt('Yes').' </label>
1.381     albertel 5255:                 </span>
1.532     bisitz   5256:                 <span class="LC_nobreak">
1.272     albertel 5257:                  <label><input type="radio" name="scantron_CODEunique"
1.423     albertel 5258:                         value="no" />'.&mt('No').' </label>
1.381     albertel 5259:                 </span>';
1.186     albertel 5260:     return $result;
                   5261: }
1.423     albertel 5262: 
                   5263: =pod 
                   5264: 
                   5265: =item scantron_selectphase
                   5266: 
                   5267:   Generates the initial screen to start the bubble sheet process.
                   5268:   Allows for - starting a grading run.
1.424     albertel 5269:              - downloading existing scan data (original, corrected
1.423     albertel 5270:                                                 or skipped info)
                   5271: 
                   5272:              - uploading new scan data
                   5273: 
                   5274:  Arguments:
                   5275:   $r          - The Apache request object
                   5276:   $file2grade - name of the file that contain the scanned data to score
                   5277: 
                   5278: =cut
1.186     albertel 5279: 
1.75      albertel 5280: sub scantron_selectphase {
1.209     ng       5281:     my ($r,$file2grade) = @_;
1.324     albertel 5282:     my ($symb)=&get_symb($r);
1.75      albertel 5283:     if (!$symb) {return '';}
1.582     raeburn  5284:     my $map_error;
                   5285:     my $sequence_selector=&getSequenceDropDown($symb,\$map_error);
                   5286:     if ($map_error) {
                   5287:         $r->print('<br />'.&navmap_errormsg().'<br />');
                   5288:         return;
                   5289:     }
1.324     albertel 5290:     my $default_form_data=&defaultFormData($symb);
                   5291:     my $grading_menu_button=&show_grading_menu_form($symb);
1.209     ng       5292:     my $file_selector=&scantron_uploads($file2grade);
1.82      albertel 5293:     my $format_selector=&scantron_scantab();
1.186     albertel 5294:     my $CODE_selector=&scantron_CODElist();
                   5295:     my $CODE_unique=&scantron_CODEunique();
1.75      albertel 5296:     my $result;
1.422     foxr     5297: 
1.513     foxr     5298:     $ssi_error = 0;
                   5299: 
1.422     foxr     5300:     # Chunk of form to prompt for a file to grade and how:
                   5301: 
1.489     albertel 5302:     $result.= '
                   5303:     <br />
                   5304:     <form method="post" enctype="multipart/form-data" action="/adm/grades" name="scantron_process">
                   5305:     <input type="hidden" name="command" value="scantron_warning" />
                   5306:     '.$default_form_data.'
                   5307:     '.&Apache::loncommon::start_data_table('LC_scantron_action').'
                   5308:        '.&Apache::loncommon::start_data_table_header_row().'
                   5309:             <th colspan="2">
1.492     albertel 5310:               &nbsp;'.&mt('Specify file and which Folder/Sequence to grade').'
1.489     albertel 5311:             </th>
                   5312:        '.&Apache::loncommon::end_data_table_header_row().'
                   5313:        '.&Apache::loncommon::start_data_table_row().'
1.492     albertel 5314:             <td> '.&mt('Sequence to grade:').' </td><td> '.$sequence_selector.' </td>
1.489     albertel 5315:        '.&Apache::loncommon::end_data_table_row().'
                   5316:        '.&Apache::loncommon::start_data_table_row().'
1.572     www      5317:             <td> '.&mt('Filename of bubblesheet data file:').' </td><td> '.$file_selector.' </td>
1.489     albertel 5318:        '.&Apache::loncommon::end_data_table_row().'
                   5319:        '.&Apache::loncommon::start_data_table_row().'
1.572     www      5320:             <td> '.&mt('Format of bubblesheet data file:').' </td><td> '.$format_selector.' </td>
1.489     albertel 5321:        '.&Apache::loncommon::end_data_table_row().'
                   5322:        '.&Apache::loncommon::start_data_table_row().'
1.492     albertel 5323:             <td> '.&mt('Saved CODEs to validate against:').' </td><td> '.$CODE_selector.' </td>
1.489     albertel 5324:        '.&Apache::loncommon::end_data_table_row().'
                   5325:        '.&Apache::loncommon::start_data_table_row().'
1.492     albertel 5326:             <td> '.&mt('Each CODE is only to be used once:').'</td><td> '.$CODE_unique.' </td>
1.489     albertel 5327:        '.&Apache::loncommon::end_data_table_row().'
                   5328:        '.&Apache::loncommon::start_data_table_row().'
1.492     albertel 5329: 	    <td> '.&mt('Options:').' </td>
1.187     albertel 5330:             <td>
1.492     albertel 5331: 	       <label><input type="checkbox" name="scantron_options_redo" value="redo_skipped"/> '.&mt('Do only previously skipped records').'</label> <br />
                   5332:                <label><input type="checkbox" name="scantron_options_ignore" value="ignore_corrections"/> '.&mt('Remove all existing corrections').'</label> <br />
                   5333:                <label><input type="checkbox" name="scantron_options_hidden" value="ignore_hidden"/> '.&mt('Skip hidden resources when grading').'</label>
1.187     albertel 5334: 	    </td>
1.489     albertel 5335:        '.&Apache::loncommon::end_data_table_row().'
                   5336:        '.&Apache::loncommon::start_data_table_row().'
1.174     albertel 5337:             <td colspan="2">
1.572     www      5338:               <input type="submit" value="'.&mt('Grading: Validate Bubblesheet Records').'" />
1.162     albertel 5339:             </td>
1.489     albertel 5340:        '.&Apache::loncommon::end_data_table_row().'
                   5341:     '.&Apache::loncommon::end_data_table().'
                   5342:     </form>
                   5343: ';
1.162     albertel 5344:    
                   5345:     $r->print($result);
                   5346: 
1.257     albertel 5347:     if (&Apache::lonnet::allowed('usc',$env{'request.role.domain'}) ||
                   5348:         &Apache::lonnet::allowed('usc',$env{'request.course.id'})) {
1.162     albertel 5349: 
1.422     foxr     5350: 	# Chunk of form to prompt for a scantron file upload.
                   5351: 
1.489     albertel 5352:         $r->print('
                   5353:     <br />
                   5354:     '.&Apache::loncommon::start_data_table('LC_scantron_action').'
                   5355:        '.&Apache::loncommon::start_data_table_header_row().'
                   5356:             <th>
1.572     www      5357:               &nbsp;'.&mt('Specify a bubblesheet data file to upload.').'
1.489     albertel 5358:             </th>
                   5359:        '.&Apache::loncommon::end_data_table_header_row().'
                   5360:        '.&Apache::loncommon::start_data_table_row().'
1.162     albertel 5361:             <td>
1.489     albertel 5362: ');
1.324     albertel 5363:     my $default_form_data=&defaultFormData(&get_symb($r,1));
1.257     albertel 5364:     my $cdom= $env{'course.'.$env{'request.course.id'}.'.domain'};
                   5365:     my $cnum= $env{'course.'.$env{'request.course.id'}.'.num'};
1.492     albertel 5366:     $r->print('
1.174     albertel 5367:               <script type="text/javascript" language="javascript">
                   5368:     function checkUpload(formname) {
                   5369: 	if (formname.upfile.value == "") {
1.492     albertel 5370: 	    alert("'.&mt('Please use the browse button to select a file from your local directory.').'");
1.174     albertel 5371: 	    return false;
                   5372: 	}
                   5373: 	formname.submit();
                   5374:     }
                   5375:               </script>
                   5376: 
1.492     albertel 5377:               <form enctype="multipart/form-data" action="/adm/grades" name="rules" method="post">
                   5378:                 '.$default_form_data.'
                   5379:                 <input name="courseid" type="hidden" value="'.$cnum.'" />
                   5380:                 <input name="domainid" type="hidden" value="'.$cdom.'" />
                   5381:                 <input name="command" value="scantronupload_save" type="hidden" />
                   5382:                 '.&mt('File to upload: [_1]','<input type="file" name="upfile" size="50" />').'
1.174     albertel 5383:                 <br />
1.589     bisitz   5384:                 <input type="button" onclick="javascript:checkUpload(this.form);" value="'.&mt('Upload Bubblesheet Data').'" />
1.174     albertel 5385:               </form>
1.492     albertel 5386: ');
1.162     albertel 5387: 
1.489     albertel 5388:         $r->print('
1.162     albertel 5389:             </td>
1.489     albertel 5390:        '.&Apache::loncommon::end_data_table_row().'
                   5391:        '.&Apache::loncommon::end_data_table().'
                   5392: ');
1.162     albertel 5393:     }
1.422     foxr     5394: 
                   5395:     # Chunk of the form that prompts to view a scoring office file,
                   5396:     # corrected file, skipped records in a file.
                   5397: 
1.489     albertel 5398:     $r->print('
                   5399:    <br />
                   5400:    <form action="/adm/grades" name="scantron_download">
                   5401:      '.$default_form_data.'
                   5402:      <input type="hidden" name="command" value="scantron_download" />
                   5403:      '.&Apache::loncommon::start_data_table('LC_scantron_action').'
                   5404:        '.&Apache::loncommon::start_data_table_header_row().'
                   5405:               <th>
1.492     albertel 5406:                 &nbsp;'.&mt('Download a scoring office file').'
1.489     albertel 5407:               </th>
                   5408:        '.&Apache::loncommon::end_data_table_header_row().'
                   5409:        '.&Apache::loncommon::start_data_table_row().'
1.492     albertel 5410:               <td> '.&mt('Filename of scoring office file: [_1]',$file_selector).' 
1.489     albertel 5411:                 <br />
1.492     albertel 5412:                 <input type="submit" value="'.&mt('Download: Show List of Associated Files').'" />
1.489     albertel 5413:        '.&Apache::loncommon::end_data_table_row().'
                   5414:      '.&Apache::loncommon::end_data_table().'
                   5415:    </form>
                   5416:    <br />
                   5417: ');
1.162     albertel 5418: 
1.457     banghart 5419:     &Apache::lonpickcode::code_list($r,2);
1.523     raeburn  5420: 
1.528     raeburn  5421:     $r->print('<br /><form method="post" name="checkscantron">'.
1.523     raeburn  5422:              $default_form_data."\n".
                   5423:              &Apache::loncommon::start_data_table('LC_scantron_action')."\n".
                   5424:              &Apache::loncommon::start_data_table_header_row()."\n".
                   5425:              '<th colspan="2">
1.572     www      5426:               &nbsp;'.&mt('Review bubblesheet data and submissions for a previously graded folder/sequence')."\n".
1.523     raeburn  5427:              '</th>'."\n".
                   5428:               &Apache::loncommon::end_data_table_header_row()."\n".
                   5429:               &Apache::loncommon::start_data_table_row()."\n".
                   5430:               '<td> '.&mt('Graded folder/sequence:').' </td>'."\n".
                   5431:               '<td> '.$sequence_selector.' </td>'.
                   5432:               &Apache::loncommon::end_data_table_row()."\n".
                   5433:               &Apache::loncommon::start_data_table_row()."\n".
                   5434:               '<td> '.&mt('Filename of scoring office file:').' </td>'."\n".
                   5435:               '<td> '.$file_selector.' </td>'."\n".
                   5436:               &Apache::loncommon::end_data_table_row()."\n".
                   5437:               &Apache::loncommon::start_data_table_row()."\n".
                   5438:               '<td> '.&mt('Format of data file:').' </td>'."\n".
                   5439:               '<td> '.$format_selector.' </td>'."\n".
                   5440:               &Apache::loncommon::end_data_table_row()."\n".
                   5441:               &Apache::loncommon::start_data_table_row()."\n".
1.557     raeburn  5442:               '<td> '.&mt('Options').' </td>'."\n".
                   5443:               '<td> <label><input type="checkbox" name="scantron_options_hidden" value="ignore_hidden"/> '.&mt('Skip hidden resources').'</label></td>'.
                   5444:               &Apache::loncommon::end_data_table_row()."\n".
                   5445:               &Apache::loncommon::start_data_table_row()."\n".
1.523     raeburn  5446:               '<td colspan="2">'."\n".
                   5447:               '<input type="hidden" name="command" value="checksubmissions" />'."\n".
1.575     www      5448:               '<input type="submit" value="'.&mt('Review Bubblesheet Data and Submission Records').'" />'."\n".
1.523     raeburn  5449:               '</td>'."\n".
                   5450:               &Apache::loncommon::end_data_table_row()."\n".
                   5451:               &Apache::loncommon::end_data_table()."\n".
                   5452:               '</form><br />');
1.457     banghart 5453:     $r->print($grading_menu_button);
1.523     raeburn  5454:     return;
1.75      albertel 5455: }
                   5456: 
1.423     albertel 5457: =pod
                   5458: 
                   5459: =item get_scantron_config
                   5460: 
                   5461:    Parse and return the scantron configuration line selected as a
                   5462:    hash of configuration file fields.
                   5463: 
                   5464:  Arguments:
                   5465:     which - the name of the configuration to parse from the file.
                   5466: 
                   5467: 
                   5468:  Returns:
                   5469:             If the named configuration is not in the file, an empty
                   5470:             hash is returned.
                   5471:     a hash with the fields
                   5472:       name         - internal name for the this configuration setup
                   5473:       description  - text to display to operator that describes this config
                   5474:       CODElocation - if 0 or the string 'none'
                   5475:                           - no CODE exists for this config
                   5476:                      if -1 || the string 'letter'
                   5477:                           - a CODE exists for this config and is
                   5478:                             a string of letters
                   5479:                      Unsupported value (but planned for future support)
                   5480:                           if a positive integer
                   5481:                                - The CODE exists as the first n items from
                   5482:                                  the question section of the form
                   5483:                           if the string 'number'
                   5484:                                - The CODE exists for this config and is
                   5485:                                  a string of numbers
                   5486:       CODEstart   - (only matter if a CODE exists) column in the line where
                   5487:                      the CODE starts
                   5488:       CODElength  - length of the CODE
1.573     bisitz   5489:       IDstart     - column where the student/employee ID starts
1.556     weissno  5490:       IDlength    - length of the student/employee ID info
1.423     albertel 5491:       Qstart      - column where the information from the bubbled
                   5492:                     'questions' start
                   5493:       Qlength     - number of columns comprising a single bubble line from
                   5494:                     the sheet. (usually either 1 or 10)
1.424     albertel 5495:       Qon         - either a single character representing the character used
1.423     albertel 5496:                     to signal a bubble was chosen in the positional setup, or
                   5497:                     the string 'letter' if the letter of the chosen bubble is
                   5498:                     in the final, or 'number' if a number representing the
                   5499:                     chosen bubble is in the file (1->A 0->J)
1.424     albertel 5500:       Qoff        - the character used to represent that a bubble was
                   5501:                     left blank
1.423     albertel 5502:       PaperID     - if the scanning process generates a unique number for each
                   5503:                     sheet scanned the column that this ID number starts in
                   5504:       PaperIDlength - number of columns that comprise the unique ID number
                   5505:                       for the sheet of paper
1.424     albertel 5506:       FirstName   - column that the first name starts in
1.423     albertel 5507:       FirstNameLength - number of columns that the first name spans
                   5508:  
                   5509:       LastName    - column that the last name starts in
                   5510:       LastNameLength - number of columns that the last name spans
                   5511: 
                   5512: =cut
1.422     foxr     5513: 
1.82      albertel 5514: sub get_scantron_config {
                   5515:     my ($which) = @_;
1.518     raeburn  5516:     my @lines = &get_scantronformat_file();
1.82      albertel 5517:     my %config;
1.157     albertel 5518:     #FIXME probably should move to XML it has already gotten a bit much now
1.518     raeburn  5519:     foreach my $line (@lines) {
1.82      albertel 5520: 	my ($name,$descrip)=split(/:/,$line);
                   5521: 	if ($name ne $which ) { next; }
                   5522: 	chomp($line);
                   5523: 	my @config=split(/:/,$line);
                   5524: 	$config{'name'}=$config[0];
                   5525: 	$config{'description'}=$config[1];
                   5526: 	$config{'CODElocation'}=$config[2];
                   5527: 	$config{'CODEstart'}=$config[3];
                   5528: 	$config{'CODElength'}=$config[4];
                   5529: 	$config{'IDstart'}=$config[5];
                   5530: 	$config{'IDlength'}=$config[6];
                   5531: 	$config{'Qstart'}=$config[7];
1.497     foxr     5532:  	$config{'Qlength'}=$config[8];
1.82      albertel 5533: 	$config{'Qoff'}=$config[9];
                   5534: 	$config{'Qon'}=$config[10];
1.157     albertel 5535: 	$config{'PaperID'}=$config[11];
                   5536: 	$config{'PaperIDlength'}=$config[12];
                   5537: 	$config{'FirstName'}=$config[13];
                   5538: 	$config{'FirstNamelength'}=$config[14];
                   5539: 	$config{'LastName'}=$config[15];
                   5540: 	$config{'LastNamelength'}=$config[16];
1.82      albertel 5541: 	last;
                   5542:     }
                   5543:     return %config;
                   5544: }
                   5545: 
1.423     albertel 5546: =pod 
                   5547: 
                   5548: =item username_to_idmap
                   5549: 
1.556     weissno  5550:     creates a hash keyed by student/employee ID with values of the corresponding
1.423     albertel 5551:     student username:domain.
                   5552: 
                   5553:   Arguments:
                   5554: 
                   5555:     $classlist - reference to the class list hash. This is a hash
                   5556:                  keyed by student name:domain  whose elements are references
1.424     albertel 5557:                  to arrays containing various chunks of information
1.423     albertel 5558:                  about the student. (See loncoursedata for more info).
                   5559: 
                   5560:   Returns
                   5561:     %idmap - the constructed hash
                   5562: 
                   5563: =cut
                   5564: 
1.82      albertel 5565: sub username_to_idmap {
                   5566:     my ($classlist)= @_;
                   5567:     my %idmap;
                   5568:     foreach my $student (keys(%$classlist)) {
                   5569: 	$idmap{$classlist->{$student}->[&Apache::loncoursedata::CL_ID]}=
                   5570: 	    $student;
                   5571:     }
                   5572:     return %idmap;
                   5573: }
1.423     albertel 5574: 
                   5575: =pod
                   5576: 
1.424     albertel 5577: =item scantron_fixup_scanline
1.423     albertel 5578: 
                   5579:    Process a requested correction to a scanline.
                   5580: 
                   5581:   Arguments:
                   5582:     $scantron_config   - hash from &get_scantron_config()
                   5583:     $scan_data         - hash of correction information 
                   5584:                           (see &scantron_getfile())
                   5585:     $line              - existing scanline
                   5586:     $whichline         - line number of the passed in scanline
                   5587:     $field             - type of change to process 
                   5588:                          (either 
1.573     bisitz   5589:                           'ID'     -> correct the student/employee ID
1.423     albertel 5590:                           'CODE'   -> correct the CODE
                   5591:                           'answer' -> fixup the submitted answers)
                   5592:     
                   5593:    $args               - hash of additional info,
                   5594:                           - 'ID' 
                   5595:                                'newid' -> studentID to use in replacement
1.424     albertel 5596:                                           of existing one
1.423     albertel 5597:                           - 'CODE' 
                   5598:                                'CODE_ignore_dup' - set to true if duplicates
                   5599:                                                    should be ignored.
                   5600: 	                       'CODE' - is new code or 'use_unfound'
1.424     albertel 5601:                                         if the existing unfound code should
1.423     albertel 5602:                                         be used as is
                   5603:                           - 'answer'
                   5604:                                'response' - new answer or 'none' if blank
                   5605:                                'question' - the bubble line to change
1.503     raeburn  5606:                                'questionnum' - the question identifier,
                   5607:                                                may include subquestion. 
1.423     albertel 5608: 
                   5609:   Returns:
                   5610:     $line - the modified scanline
                   5611: 
                   5612:   Side effects: 
                   5613:     $scan_data - may be updated
                   5614: 
                   5615: =cut
                   5616: 
1.82      albertel 5617: 
1.157     albertel 5618: sub scantron_fixup_scanline {
                   5619:     my ($scantron_config,$scan_data,$line,$whichline,$field,$args)=@_;
                   5620:     if ($field eq 'ID') {
                   5621: 	if (length($args->{'newid'}) > $$scantron_config{'IDlength'}) {
1.186     albertel 5622: 	    return ($line,1,'New value too large');
1.157     albertel 5623: 	}
                   5624: 	if (length($args->{'newid'}) < $$scantron_config{'IDlength'}) {
                   5625: 	    $args->{'newid'}=sprintf('%-'.$$scantron_config{'IDlength'}.'s',
                   5626: 				     $args->{'newid'});
                   5627: 	}
                   5628: 	substr($line,$$scantron_config{'IDstart'}-1,
                   5629: 	       $$scantron_config{'IDlength'})=$args->{'newid'};
                   5630: 	if ($args->{'newid'}=~/^\s*$/) {
                   5631: 	    &scan_data($scan_data,"$whichline.user",
                   5632: 		       $args->{'username'}.':'.$args->{'domain'});
                   5633: 	}
1.186     albertel 5634:     } elsif ($field eq 'CODE') {
1.192     albertel 5635: 	if ($args->{'CODE_ignore_dup'}) {
                   5636: 	    &scan_data($scan_data,"$whichline.CODE_ignore_dup",'1');
                   5637: 	}
                   5638: 	&scan_data($scan_data,"$whichline.useCODE",'1');
                   5639: 	if ($args->{'CODE'} ne 'use_unfound') {
1.191     albertel 5640: 	    if (length($args->{'CODE'}) > $$scantron_config{'CODElength'}) {
                   5641: 		return ($line,1,'New CODE value too large');
                   5642: 	    }
                   5643: 	    if (length($args->{'CODE'}) < $$scantron_config{'CODElength'}) {
                   5644: 		$args->{'CODE'}=sprintf('%-'.$$scantron_config{'CODElength'}.'s',$args->{'CODE'});
                   5645: 	    }
                   5646: 	    substr($line,$$scantron_config{'CODEstart'}-1,
                   5647: 		   $$scantron_config{'CODElength'})=$args->{'CODE'};
1.186     albertel 5648: 	}
1.157     albertel 5649:     } elsif ($field eq 'answer') {
1.497     foxr     5650: 	my $length=$scantron_config->{'Qlength'};
1.157     albertel 5651: 	my $off=$scantron_config->{'Qoff'};
                   5652: 	my $on=$scantron_config->{'Qon'};
1.497     foxr     5653: 	my $answer=${off}x$length;
                   5654: 	if ($args->{'response'} eq 'none') {
                   5655: 	    &scan_data($scan_data,
1.503     raeburn  5656: 		       "$whichline.no_bubble.".$args->{'questionnum'},'1');
1.497     foxr     5657: 	} else {
                   5658: 	    if ($on eq 'letter') {
                   5659: 		my @alphabet=('A'..'Z');
                   5660: 		$answer=$alphabet[$args->{'response'}];
                   5661: 	    } elsif ($on eq 'number') {
                   5662: 		$answer=$args->{'response'}+1;
                   5663: 		if ($answer == 10) { $answer = '0'; }
1.274     albertel 5664: 	    } else {
1.497     foxr     5665: 		substr($answer,$args->{'response'},1)=$on;
1.274     albertel 5666: 	    }
1.497     foxr     5667: 	    &scan_data($scan_data,
1.503     raeburn  5668: 		       "$whichline.no_bubble.".$args->{'questionnum'},undef,'1');
1.157     albertel 5669: 	}
1.497     foxr     5670: 	my $where=$length*($args->{'question'}-1)+$scantron_config->{'Qstart'};
                   5671: 	substr($line,$where-1,$length)=$answer;
1.157     albertel 5672:     }
                   5673:     return $line;
                   5674: }
1.423     albertel 5675: 
                   5676: =pod
                   5677: 
                   5678: =item scan_data
                   5679: 
                   5680:     Edit or look up  an item in the scan_data hash.
                   5681: 
                   5682:   Arguments:
                   5683:     $scan_data  - The hash (see scantron_getfile)
                   5684:     $key        - shorthand of the key to edit (actual key is
1.424     albertel 5685:                   scantronfilename_key).
1.423     albertel 5686:     $data        - New value of the hash entry.
                   5687:     $delete      - If true, the entry is removed from the hash.
                   5688: 
                   5689:   Returns:
                   5690:     The new value of the hash table field (undefined if deleted).
                   5691: 
                   5692: =cut
                   5693: 
                   5694: 
1.157     albertel 5695: sub scan_data {
                   5696:     my ($scan_data,$key,$value,$delete)=@_;
1.257     albertel 5697:     my $filename=$env{'form.scantron_selectfile'};
1.157     albertel 5698:     if (defined($value)) {
                   5699: 	$scan_data->{$filename.'_'.$key} = $value;
                   5700:     }
                   5701:     if ($delete) { delete($scan_data->{$filename.'_'.$key}); }
                   5702:     return $scan_data->{$filename.'_'.$key};
                   5703: }
1.423     albertel 5704: 
1.495     albertel 5705: # ----- These first few routines are general use routines.----
                   5706: 
                   5707: # Return the number of occurences of a pattern in a string.
                   5708: 
                   5709: sub occurence_count {
                   5710:     my ($string, $pattern) = @_;
                   5711: 
                   5712:     my @matches = ($string =~ /$pattern/g);
                   5713: 
                   5714:     return scalar(@matches);
                   5715: }
                   5716: 
                   5717: 
                   5718: # Take a string known to have digits and convert all the
                   5719: # digits into letters in the range J,A..I.
                   5720: 
                   5721: sub digits_to_letters {
                   5722:     my ($input) = @_;
                   5723: 
                   5724:     my @alphabet = ('J', 'A'..'I');
                   5725: 
                   5726:     my @input    = split(//, $input);
                   5727:     my $output ='';
                   5728:     for (my $i = 0; $i < scalar(@input); $i++) {
                   5729: 	if ($input[$i] =~ /\d/) {
                   5730: 	    $output .= $alphabet[$input[$i]];
                   5731: 	} else {
                   5732: 	    $output .= $input[$i];
                   5733: 	}
                   5734:     }
                   5735:     return $output;
                   5736: }
                   5737: 
1.423     albertel 5738: =pod 
                   5739: 
                   5740: =item scantron_parse_scanline
                   5741: 
                   5742:   Decodes a scanline from the selected scantron file
                   5743: 
                   5744:  Arguments:
                   5745:     line             - The text of the scantron file line to process
                   5746:     whichline        - Line number
                   5747:     scantron_config  - Hash describing the format of the scantron lines.
                   5748:     scan_data        - Hash of extra information about the scanline
                   5749:                        (see scantron_getfile for more information)
                   5750:     just_header      - True if should not process question answers but only
                   5751:                        the stuff to the left of the answers.
                   5752:  Returns:
                   5753:    Hash containing the result of parsing the scanline
                   5754: 
                   5755:    Keys are all proceeded by the string 'scantron.'
                   5756: 
                   5757:        CODE    - the CODE in use for this scanline
                   5758:        useCODE - 1 if the CODE is invalid but it usage has been forced
                   5759:                  by the operator
                   5760:        CODE_ignore_dup - 1 if the CODE is a duplicated use when unique
                   5761:                             CODEs were selected, but the usage has been
                   5762:                             forced by the operator
1.556     weissno  5763:        ID  - student/employee ID
1.423     albertel 5764:        PaperID - if used, the ID number printed on the sheet when the 
                   5765:                  paper was scanned
                   5766:        FirstName - first name from the sheet
                   5767:        LastName  - last name from the sheet
                   5768: 
                   5769:      if just_header was not true these key may also exist
                   5770: 
1.447     foxr     5771:        missingerror - a list of bubble ranges that are considered to be answers
                   5772:                       to a single question that don't have any bubbles filled in.
                   5773:                       Of the form questionnumber:firstbubblenumber:count.
                   5774:        doubleerror  - a list of bubble ranges that are considered to be answers
                   5775:                       to a single question that have more than one bubble filled in.
                   5776:                       Of the form questionnumber::firstbubblenumber:count
                   5777:    
                   5778:                 In the above, count is the number of bubble responses in the
                   5779:                 input line needed to represent the possible answers to the question.
                   5780:                 e.g. a radioresponse with 15 choices in an answer sheet with 10 choices
                   5781:                 per line would have count = 2.
                   5782: 
1.423     albertel 5783:        maxquest     - the number of the last bubble line that was parsed
                   5784: 
                   5785:        (<number> starts at 1)
                   5786:        <number>.answer - zero or more letters representing the selected
                   5787:                          letters from the scanline for the bubble line 
                   5788:                          <number>.
                   5789:                          if blank there was either no bubble or there where
                   5790:                          multiple bubbles, (consult the keys missingerror and
                   5791:                          doubleerror if this is an error condition)
                   5792: 
                   5793: =cut
                   5794: 
1.82      albertel 5795: sub scantron_parse_scanline {
1.423     albertel 5796:     my ($line,$whichline,$scantron_config,$scan_data,$just_header)=@_;
1.470     foxr     5797: 
1.82      albertel 5798:     my %record;
1.550     raeburn  5799:     my $lastpos = $env{'form.scantron_maxbubble'}*$$scantron_config{'Qlength'};
                   5800:     my $questions=substr($line,$$scantron_config{'Qstart'}-1,$lastpos);  # Answers
1.422     foxr     5801:     my $data=substr($line,0,$$scantron_config{'Qstart'}-1);     # earlier stuff
1.278     albertel 5802:     if (!($$scantron_config{'CODElocation'} eq 0 ||
                   5803: 	  $$scantron_config{'CODElocation'} eq 'none')) {
                   5804: 	if ($$scantron_config{'CODElocation'} < 0 ||
                   5805: 	    $$scantron_config{'CODElocation'} eq 'letter' ||
                   5806: 	    $$scantron_config{'CODElocation'} eq 'number') {
1.191     albertel 5807: 	    $record{'scantron.CODE'}=substr($data,
                   5808: 					    $$scantron_config{'CODEstart'}-1,
1.83      albertel 5809: 					    $$scantron_config{'CODElength'});
1.191     albertel 5810: 	    if (&scan_data($scan_data,"$whichline.useCODE")) {
                   5811: 		$record{'scantron.useCODE'}=1;
                   5812: 	    }
1.192     albertel 5813: 	    if (&scan_data($scan_data,"$whichline.CODE_ignore_dup")) {
                   5814: 		$record{'scantron.CODE_ignore_dup'}=1;
                   5815: 	    }
1.82      albertel 5816: 	} else {
                   5817: 	    #FIXME interpret first N questions
                   5818: 	}
                   5819:     }
1.83      albertel 5820:     $record{'scantron.ID'}=substr($data,$$scantron_config{'IDstart'}-1,
                   5821: 				  $$scantron_config{'IDlength'});
1.157     albertel 5822:     $record{'scantron.PaperID'}=
                   5823: 	substr($data,$$scantron_config{'PaperID'}-1,
                   5824: 	       $$scantron_config{'PaperIDlength'});
                   5825:     $record{'scantron.FirstName'}=
                   5826: 	substr($data,$$scantron_config{'FirstName'}-1,
                   5827: 	       $$scantron_config{'FirstNamelength'});
                   5828:     $record{'scantron.LastName'}=
                   5829: 	substr($data,$$scantron_config{'LastName'}-1,
                   5830: 	       $$scantron_config{'LastNamelength'});
1.423     albertel 5831:     if ($just_header) { return \%record; }
1.194     albertel 5832: 
1.82      albertel 5833:     my @alphabet=('A'..'Z');
                   5834:     my $questnum=0;
1.447     foxr     5835:     my $ansnum  =1;		# Multiple 'answer lines'/question.
                   5836: 
1.470     foxr     5837:     chomp($questions);		# Get rid of any trailing \n.
                   5838:     $questions =~ s/\r$//;      # Get rid of trailing \r too (MAC or Win uploads).
                   5839:     while (length($questions)) {
1.447     foxr     5840: 	my $answers_needed = $bubble_lines_per_response{$questnum};
1.503     raeburn  5841:         my $answer_length  = ($$scantron_config{'Qlength'} * $answers_needed)
                   5842:                              || 1;
                   5843:         $questnum++;
                   5844:         my $quest_id = $questnum;
                   5845:         my $currentquest = substr($questions,0,$answer_length);
                   5846:         $questions       = substr($questions,$answer_length);
                   5847:         if (length($currentquest) < $answer_length) { next; }
                   5848: 
                   5849:         if ($subdivided_bubble_lines{$questnum-1} =~ /,/) {
                   5850:             my $subquestnum = 1;
                   5851:             my $subquestions = $currentquest;
                   5852:             my @subanswers_needed = 
                   5853:                 split(/,/,$subdivided_bubble_lines{$questnum-1});  
                   5854:             foreach my $subans (@subanswers_needed) {
                   5855:                 my $subans_length =
                   5856:                     ($$scantron_config{'Qlength'} * $subans)  || 1;
                   5857:                 my $currsubquest = substr($subquestions,0,$subans_length);
                   5858:                 $subquestions   = substr($subquestions,$subans_length);
                   5859:                 $quest_id = "$questnum.$subquestnum";
                   5860:                 if (($$scantron_config{'Qon'} eq 'letter') ||
                   5861:                     ($$scantron_config{'Qon'} eq 'number')) {
                   5862:                     $ansnum = &scantron_validator_lettnum($ansnum, 
                   5863:                         $questnum,$quest_id,$subans,$currsubquest,$whichline,
                   5864:                         \@alphabet,\%record,$scantron_config,$scan_data);
                   5865:                 } else {
                   5866:                     $ansnum = &scantron_validator_positional($ansnum,
                   5867:                         $questnum,$quest_id,$subans,$currsubquest,$whichline,                        \@alphabet,\%record,$scantron_config,$scan_data);
                   5868:                 }
                   5869:                 $subquestnum ++;
                   5870:             }
                   5871:         } else {
                   5872:             if (($$scantron_config{'Qon'} eq 'letter') ||
                   5873:                 ($$scantron_config{'Qon'} eq 'number')) {
                   5874:                 $ansnum = &scantron_validator_lettnum($ansnum,$questnum,
                   5875:                     $quest_id,$answers_needed,$currentquest,$whichline,
                   5876:                     \@alphabet,\%record,$scantron_config,$scan_data);
                   5877:             } else {
                   5878:                 $ansnum = &scantron_validator_positional($ansnum,$questnum,
                   5879:                     $quest_id,$answers_needed,$currentquest,$whichline,
                   5880:                     \@alphabet,\%record,$scantron_config,$scan_data);
                   5881:             }
                   5882:         }
                   5883:     }
                   5884:     $record{'scantron.maxquest'}=$questnum;
                   5885:     return \%record;
                   5886: }
1.447     foxr     5887: 
1.503     raeburn  5888: sub scantron_validator_lettnum {
                   5889:     my ($ansnum,$questnum,$quest_id,$answers_needed,$currquest,$whichline,
                   5890:         $alphabet,$record,$scantron_config,$scan_data) = @_;
                   5891: 
                   5892:     # Qon 'letter' implies for each slot in currquest we have:
                   5893:     #    ? or * for doubles, a letter in A-Z for a bubble, and
                   5894:     #    about anything else (esp. a value of Qoff) for missing
                   5895:     #    bubbles.
                   5896:     #
                   5897:     # Qon 'number' implies each slot gives a digit that indexes the
                   5898:     #    bubbles filled, or Qoff, or a non-number for unbubbled lines,
                   5899:     #    and * or ? for double bubbles on a single line.
                   5900:     #
1.447     foxr     5901: 
1.503     raeburn  5902:     my $matchon;
                   5903:     if ($$scantron_config{'Qon'} eq 'letter') {
                   5904:         $matchon = '[A-Z]';
                   5905:     } elsif ($$scantron_config{'Qon'} eq 'number') {
                   5906:         $matchon = '\d';
                   5907:     }
                   5908:     my $occurrences = 0;
                   5909:     if (($responsetype_per_response{$questnum-1} eq 'essayresponse') ||
                   5910:         ($responsetype_per_response{$questnum-1} eq 'formularesponse') ||
1.510     raeburn  5911:         ($responsetype_per_response{$questnum-1} eq 'stringresponse') ||
                   5912:         ($responsetype_per_response{$questnum-1} eq 'imageresponse') ||
                   5913:         ($responsetype_per_response{$questnum-1} eq 'reactionresponse') ||
                   5914:         ($responsetype_per_response{$questnum-1} eq 'organicresponse')) {
1.503     raeburn  5915:         my @singlelines = split('',$currquest);
                   5916:         foreach my $entry (@singlelines) {
                   5917:             $occurrences = &occurence_count($entry,$matchon);
                   5918:             if ($occurrences > 1) {
                   5919:                 last;
                   5920:             }
                   5921:         } 
                   5922:     } else {
                   5923:         $occurrences = &occurence_count($currquest,$matchon); 
                   5924:     }
                   5925:     if (($currquest =~ /\?/ || $currquest =~ /\*/) || ($occurrences > 1)) {
                   5926:         push(@{$record->{'scantron.doubleerror'}},$quest_id);
                   5927:         for (my $ans=0; $ans<$answers_needed; $ans++) {
                   5928:             my $bubble = substr($currquest,$ans,1);
                   5929:             if ($bubble =~ /$matchon/ ) {
                   5930:                 if ($$scantron_config{'Qon'} eq 'number') {
                   5931:                     if ($bubble == 0) {
                   5932:                         $bubble = 10; 
                   5933:                     }
                   5934:                     $record->{"scantron.$ansnum.answer"} = 
                   5935:                         $alphabet->[$bubble-1];
                   5936:                 } else {
                   5937:                     $record->{"scantron.$ansnum.answer"} = $bubble;
                   5938:                 }
                   5939:             } else {
                   5940:                 $record->{"scantron.$ansnum.answer"}='';
                   5941:             }
                   5942:             $ansnum++;
                   5943:         }
                   5944:     } elsif (!defined($currquest)
                   5945:             || (&occurence_count($currquest, $$scantron_config{'Qoff'}) == length($currquest))
                   5946:             || (&occurence_count($currquest,$matchon) == 0)) {
                   5947:         for (my $ans=0; $ans<$answers_needed; $ans++ ) {
                   5948:             $record->{"scantron.$ansnum.answer"}='';
                   5949:             $ansnum++;
                   5950:         }
                   5951:         if (!&scan_data($scan_data,"$whichline.no_bubble.$quest_id")) {
                   5952:             push(@{$record->{'scantron.missingerror'}},$quest_id);
                   5953:         }
                   5954:     } else {
                   5955:         if ($$scantron_config{'Qon'} eq 'number') {
                   5956:             $currquest = &digits_to_letters($currquest);            
                   5957:         }
                   5958:         for (my $ans=0; $ans<$answers_needed; $ans++) {
                   5959:             my $bubble = substr($currquest,$ans,1);
                   5960:             $record->{"scantron.$ansnum.answer"} = $bubble;
                   5961:             $ansnum++;
                   5962:         }
                   5963:     }
                   5964:     return $ansnum;
                   5965: }
1.447     foxr     5966: 
1.503     raeburn  5967: sub scantron_validator_positional {
                   5968:     my ($ansnum,$questnum,$quest_id,$answers_needed,$currquest,
                   5969:         $whichline,$alphabet,$record,$scantron_config,$scan_data) = @_;
1.447     foxr     5970: 
1.503     raeburn  5971:     # Otherwise there's a positional notation;
                   5972:     # each bubble line requires Qlength items, and there are filled in
                   5973:     # bubbles for each case where there 'Qon' characters.
                   5974:     #
1.447     foxr     5975: 
1.503     raeburn  5976:     my @array=split($$scantron_config{'Qon'},$currquest,-1);
1.447     foxr     5977: 
1.503     raeburn  5978:     # If the split only gives us one element.. the full length of the
                   5979:     # answer string, no bubbles are filled in:
1.447     foxr     5980: 
1.507     raeburn  5981:     if ($answers_needed eq '') {
                   5982:         return;
                   5983:     }
                   5984: 
1.503     raeburn  5985:     if (length($array[0]) eq $$scantron_config{'Qlength'}*$answers_needed) {
                   5986:         for (my $ans=0; $ans<$answers_needed; $ans++ ) {
                   5987:             $record->{"scantron.$ansnum.answer"}='';
                   5988:             $ansnum++;
                   5989:         }
                   5990:         if (!&scan_data($scan_data,"$whichline.no_bubble.$quest_id")) {
                   5991:             push(@{$record->{"scantron.missingerror"}},$quest_id);
                   5992:         }
                   5993:     } elsif (scalar(@array) == 2) {
                   5994:         my $location = length($array[0]);
                   5995:         my $line_num = int($location / $$scantron_config{'Qlength'});
                   5996:         my $bubble   = $alphabet->[$location % $$scantron_config{'Qlength'}];
                   5997:         for (my $ans=0; $ans<$answers_needed; $ans++) {
                   5998:             if ($ans eq $line_num) {
                   5999:                 $record->{"scantron.$ansnum.answer"} = $bubble;
                   6000:             } else {
                   6001:                 $record->{"scantron.$ansnum.answer"} = ' ';
                   6002:             }
                   6003:             $ansnum++;
                   6004:          }
                   6005:     } else {
                   6006:         #  If there's more than one instance of a bubble character
                   6007:         #  That's a double bubble; with positional notation we can
                   6008:         #  record all the bubbles filled in as well as the
                   6009:         #  fact this response consists of multiple bubbles.
                   6010:         #
                   6011:         if (($responsetype_per_response{$questnum-1} eq 'essayresponse') ||
                   6012:             ($responsetype_per_response{$questnum-1} eq 'formularesponse') ||
1.510     raeburn  6013:             ($responsetype_per_response{$questnum-1} eq 'stringresponse') ||
                   6014:             ($responsetype_per_response{$questnum-1} eq 'imageresponse') ||
                   6015:             ($responsetype_per_response{$questnum-1} eq 'reactionresponse') ||
                   6016:             ($responsetype_per_response{$questnum-1} eq 'organicresponse')) {
1.503     raeburn  6017:             my $doubleerror = 0;
                   6018:             while (($currquest >= $$scantron_config{'Qlength'}) && 
                   6019:                    (!$doubleerror)) {
                   6020:                my $currline = substr($currquest,0,$$scantron_config{'Qlength'});
                   6021:                $currquest = substr($currquest,$$scantron_config{'Qlength'});
                   6022:                my @currarray = split($$scantron_config{'Qon'},$currline,-1);
                   6023:                if (length(@currarray) > 2) {
                   6024:                    $doubleerror = 1;
                   6025:                } 
                   6026:             }
                   6027:             if ($doubleerror) {
                   6028:                 push(@{$record->{'scantron.doubleerror'}},$quest_id);
                   6029:             }
                   6030:         } else {
                   6031:             push(@{$record->{'scantron.doubleerror'}},$quest_id);
                   6032:         }
                   6033:         my $item = $ansnum;
                   6034:         for (my $ans=0; $ans<$answers_needed; $ans++) {
                   6035:             $record->{"scantron.$item.answer"} = '';
                   6036:             $item ++;
                   6037:         }
1.447     foxr     6038: 
1.503     raeburn  6039:         my @ans=@array;
                   6040:         my $i=0;
                   6041:         my $increment = 0;
                   6042:         while ($#ans) {
                   6043:             $i+=length($ans[0]) + $increment;
                   6044:             my $line   = int($i/$$scantron_config{'Qlength'} + $ansnum);
                   6045:             my $bubble = $i%$$scantron_config{'Qlength'};
                   6046:             $record->{"scantron.$line.answer"}.=$alphabet->[$bubble];
                   6047:             shift(@ans);
                   6048:             $increment = 1;
                   6049:         }
                   6050:         $ansnum += $answers_needed;
1.82      albertel 6051:     }
1.503     raeburn  6052:     return $ansnum;
1.82      albertel 6053: }
                   6054: 
1.423     albertel 6055: =pod
                   6056: 
                   6057: =item scantron_add_delay
                   6058: 
                   6059:    Adds an error message that occurred during the grading phase to a
                   6060:    queue of messages to be shown after grading pass is complete
                   6061: 
                   6062:  Arguments:
1.424     albertel 6063:    $delayqueue  - arrary ref of hash ref of error messages
1.423     albertel 6064:    $scanline    - the scanline that caused the error
                   6065:    $errormesage - the error message
                   6066:    $errorcode   - a numeric code for the error
                   6067: 
                   6068:  Side Effects:
1.424     albertel 6069:    updates the $delayqueue to have a new hash ref of the error
1.423     albertel 6070: 
                   6071: =cut
                   6072: 
1.82      albertel 6073: sub scantron_add_delay {
1.140     albertel 6074:     my ($delayqueue,$scanline,$errormessage,$errorcode)=@_;
                   6075:     push(@$delayqueue,
                   6076: 	 {'line' => $scanline, 'emsg' => $errormessage,
                   6077: 	  'ecode' => $errorcode }
                   6078: 	 );
1.82      albertel 6079: }
                   6080: 
1.423     albertel 6081: =pod
                   6082: 
                   6083: =item scantron_find_student
                   6084: 
1.424     albertel 6085:    Finds the username for the current scanline
                   6086: 
                   6087:   Arguments:
                   6088:    $scantron_record - hash result from scantron_parse_scanline
                   6089:    $scan_data       - hash of correction information 
                   6090:                       (see &scantron_getfile() form more information)
                   6091:    $idmap           - hash from &username_to_idmap()
                   6092:    $line            - number of current scanline
                   6093:  
                   6094:   Returns:
                   6095:    Either 'username:domain' or undef if unknown
                   6096: 
1.423     albertel 6097: =cut
                   6098: 
1.82      albertel 6099: sub scantron_find_student {
1.157     albertel 6100:     my ($scantron_record,$scan_data,$idmap,$line)=@_;
1.83      albertel 6101:     my $scanID=$$scantron_record{'scantron.ID'};
1.157     albertel 6102:     if ($scanID =~ /^\s*$/) {
                   6103:  	return &scan_data($scan_data,"$line.user");
                   6104:     }
1.83      albertel 6105:     foreach my $id (keys(%$idmap)) {
1.157     albertel 6106:  	if (lc($id) eq lc($scanID)) {
                   6107:  	    return $$idmap{$id};
                   6108:  	}
1.83      albertel 6109:     }
                   6110:     return undef;
                   6111: }
                   6112: 
1.423     albertel 6113: =pod
                   6114: 
                   6115: =item scantron_filter
                   6116: 
1.424     albertel 6117:    Filter sub for lonnavmaps, filters out hidden resources if ignore
                   6118:    hidden resources was selected
                   6119: 
1.423     albertel 6120: =cut
                   6121: 
1.83      albertel 6122: sub scantron_filter {
                   6123:     my ($curres)=@_;
1.331     albertel 6124: 
                   6125:     if (ref($curres) && $curres->is_problem()) {
                   6126: 	# if the user has asked to not have either hidden
                   6127: 	# or 'randomout' controlled resources to be graded
                   6128: 	# don't include them
                   6129: 	if ($env{'form.scantron_options_hidden'} eq 'ignore_hidden'
                   6130: 	    && $curres->randomout) {
                   6131: 	    return 0;
                   6132: 	}
1.83      albertel 6133: 	return 1;
                   6134:     }
                   6135:     return 0;
1.82      albertel 6136: }
                   6137: 
1.423     albertel 6138: =pod
                   6139: 
                   6140: =item scantron_process_corrections
                   6141: 
1.424     albertel 6142:    Gets correction information out of submitted form data and corrects
                   6143:    the scanline
                   6144: 
1.423     albertel 6145: =cut
                   6146: 
1.157     albertel 6147: sub scantron_process_corrections {
                   6148:     my ($r) = @_;
1.257     albertel 6149:     my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
1.157     albertel 6150:     my ($scanlines,$scan_data)=&scantron_getfile();
                   6151:     my $classlist=&Apache::loncoursedata::get_classlist();
1.257     albertel 6152:     my $which=$env{'form.scantron_line'};
1.200     albertel 6153:     my $line=&scantron_get_line($scanlines,$scan_data,$which);
1.157     albertel 6154:     my ($skip,$err,$errmsg);
1.257     albertel 6155:     if ($env{'form.scantron_skip_record'}) {
1.157     albertel 6156: 	$skip=1;
1.257     albertel 6157:     } elsif ($env{'form.scantron_corrections'} =~ /^(duplicate|incorrect)ID$/) {
                   6158: 	my $newstudent=$env{'form.scantron_username'}.':'.
                   6159: 	    $env{'form.scantron_domain'};
1.157     albertel 6160: 	my $newid=$classlist->{$newstudent}->[&Apache::loncoursedata::CL_ID];
                   6161: 	($line,$err,$errmsg)=
                   6162: 	    &scantron_fixup_scanline(\%scantron_config,$scan_data,$line,$which,
                   6163: 				     'ID',{'newid'=>$newid,
1.257     albertel 6164: 				    'username'=>$env{'form.scantron_username'},
                   6165: 				    'domain'=>$env{'form.scantron_domain'}});
                   6166:     } elsif ($env{'form.scantron_corrections'} =~ /^(duplicate|incorrect)CODE$/) {
                   6167: 	my $resolution=$env{'form.scantron_CODE_resolution'};
1.190     albertel 6168: 	my $newCODE;
1.192     albertel 6169: 	my %args;
1.190     albertel 6170: 	if      ($resolution eq 'use_unfound') {
1.191     albertel 6171: 	    $newCODE='use_unfound';
1.190     albertel 6172: 	} elsif ($resolution eq 'use_found') {
1.257     albertel 6173: 	    $newCODE=$env{'form.scantron_CODE_selectedvalue'};
1.190     albertel 6174: 	} elsif ($resolution eq 'use_typed') {
1.257     albertel 6175: 	    $newCODE=$env{'form.scantron_CODE_newvalue'};
1.194     albertel 6176: 	} elsif ($resolution =~ /^use_closest_(\d+)/) {
1.257     albertel 6177: 	    $newCODE=$env{"form.scantron_CODE_closest_$1"};
1.190     albertel 6178: 	}
1.257     albertel 6179: 	if ($env{'form.scantron_corrections'} eq 'duplicateCODE') {
1.192     albertel 6180: 	    $args{'CODE_ignore_dup'}=1;
                   6181: 	}
                   6182: 	$args{'CODE'}=$newCODE;
1.186     albertel 6183: 	($line,$err,$errmsg)=
                   6184: 	    &scantron_fixup_scanline(\%scantron_config,$scan_data,$line,$which,
1.192     albertel 6185: 				     'CODE',\%args);
1.257     albertel 6186:     } elsif ($env{'form.scantron_corrections'} =~ /^(missing|double)bubble$/) {
                   6187: 	foreach my $question (split(',',$env{'form.scantron_questions'})) {
1.157     albertel 6188: 	    ($line,$err,$errmsg)=
                   6189: 		&scantron_fixup_scanline(\%scantron_config,$scan_data,$line,
                   6190: 					 $which,'answer',
                   6191: 					 { 'question'=>$question,
1.503     raeburn  6192: 		      		   'response'=>$env{"form.scantron_correct_Q_$question"},
                   6193:                                    'questionnum'=>$env{"form.scantron_questionnum_Q_$question"}});
1.157     albertel 6194: 	    if ($err) { last; }
                   6195: 	}
                   6196:     }
                   6197:     if ($err) {
1.398     albertel 6198: 	$r->print("<span class=\"LC_warning\">Unable to accept last correction, an error occurred :$errmsg:</span>");
1.157     albertel 6199:     } else {
1.200     albertel 6200: 	&scantron_put_line($scanlines,$scan_data,$which,$line,$skip);
1.157     albertel 6201: 	&scantron_putfile($scanlines,$scan_data);
                   6202:     }
                   6203: }
                   6204: 
1.423     albertel 6205: =pod
                   6206: 
                   6207: =item reset_skipping_status
                   6208: 
1.424     albertel 6209:    Forgets the current set of remember skipped scanlines (and thus
                   6210:    reverts back to considering all lines in the
                   6211:    scantron_skipped_<filename> file)
                   6212: 
1.423     albertel 6213: =cut
                   6214: 
1.200     albertel 6215: sub reset_skipping_status {
                   6216:     my ($scanlines,$scan_data)=&scantron_getfile();
                   6217:     &scan_data($scan_data,'remember_skipping',undef,1);
                   6218:     &scantron_putfile(undef,$scan_data);
                   6219: }
                   6220: 
1.423     albertel 6221: =pod
                   6222: 
                   6223: =item start_skipping
                   6224: 
1.424     albertel 6225:    Marks a scanline to be skipped. 
                   6226: 
1.423     albertel 6227: =cut
                   6228: 
1.376     albertel 6229: sub start_skipping {
1.200     albertel 6230:     my ($scan_data,$i)=@_;
                   6231:     my %remembered=split(':',&scan_data($scan_data,'remember_skipping'));
1.376     albertel 6232:     if ($env{'form.scantron_options_redo'} =~ /^redo_/) {
                   6233: 	$remembered{$i}=2;
                   6234:     } else {
                   6235: 	$remembered{$i}=1;
                   6236:     }
1.200     albertel 6237:     &scan_data($scan_data,'remember_skipping',join(':',%remembered));
                   6238: }
                   6239: 
1.423     albertel 6240: =pod
                   6241: 
                   6242: =item should_be_skipped
                   6243: 
1.424     albertel 6244:    Checks whether a scanline should be skipped.
                   6245: 
1.423     albertel 6246: =cut
                   6247: 
1.200     albertel 6248: sub should_be_skipped {
1.376     albertel 6249:     my ($scanlines,$scan_data,$i)=@_;
1.257     albertel 6250:     if ($env{'form.scantron_options_redo'} !~ /^redo_/) {
1.200     albertel 6251: 	# not redoing old skips
1.376     albertel 6252: 	if ($scanlines->{'skipped'}[$i]) { return 1; }
1.200     albertel 6253: 	return 0;
                   6254:     }
                   6255:     my %remembered=split(':',&scan_data($scan_data,'remember_skipping'));
1.376     albertel 6256: 
                   6257:     if (exists($remembered{$i}) && $remembered{$i} != 2 ) {
                   6258: 	return 0;
                   6259:     }
1.200     albertel 6260:     return 1;
                   6261: }
                   6262: 
1.423     albertel 6263: =pod
                   6264: 
                   6265: =item remember_current_skipped
                   6266: 
1.424     albertel 6267:    Discovers what scanlines are in the scantron_skipped_<filename>
                   6268:    file and remembers them into scan_data for later use.
                   6269: 
1.423     albertel 6270: =cut
                   6271: 
1.200     albertel 6272: sub remember_current_skipped {
                   6273:     my ($scanlines,$scan_data)=&scantron_getfile();
                   6274:     my %to_remember;
                   6275:     for (my $i=0;$i<=$scanlines->{'count'};$i++) {
                   6276: 	if ($scanlines->{'skipped'}[$i]) {
                   6277: 	    $to_remember{$i}=1;
                   6278: 	}
                   6279:     }
1.376     albertel 6280: 
1.200     albertel 6281:     &scan_data($scan_data,'remember_skipping',join(':',%to_remember));
                   6282:     &scantron_putfile(undef,$scan_data);
                   6283: }
                   6284: 
1.423     albertel 6285: =pod
                   6286: 
                   6287: =item check_for_error
                   6288: 
1.424     albertel 6289:     Checks if there was an error when attempting to remove a specific
                   6290:     scantron_.. bubble sheet data file. Prints out an error if
                   6291:     something went wrong.
                   6292: 
1.423     albertel 6293: =cut
                   6294: 
1.200     albertel 6295: sub check_for_error {
                   6296:     my ($r,$result)=@_;
                   6297:     if ($result ne 'ok' && $result ne 'not_found' ) {
1.492     albertel 6298: 	$r->print(&mt("An error occurred ([_1]) when trying to remove the existing corrections.",$result));
1.200     albertel 6299:     }
                   6300: }
1.157     albertel 6301: 
1.423     albertel 6302: =pod
                   6303: 
                   6304: =item scantron_warning_screen
                   6305: 
1.424     albertel 6306:    Interstitial screen to make sure the operator has selected the
                   6307:    correct options before we start the validation phase.
                   6308: 
1.423     albertel 6309: =cut
                   6310: 
1.203     albertel 6311: sub scantron_warning_screen {
                   6312:     my ($button_text)=@_;
1.257     albertel 6313:     my $title=&Apache::lonnet::gettitle($env{'form.selectpage'});
1.284     albertel 6314:     my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
1.373     albertel 6315:     my $CODElist;
1.284     albertel 6316:     if ($scantron_config{'CODElocation'} &&
                   6317: 	$scantron_config{'CODEstart'} &&
                   6318: 	$scantron_config{'CODElength'}) {
                   6319: 	$CODElist=$env{'form.scantron_CODElist'};
1.398     albertel 6320: 	if ($env{'form.scantron_CODElist'} eq '') { $CODElist='<span class="LC_warning">None</span>'; }
1.284     albertel 6321: 	$CODElist=
1.492     albertel 6322: 	    '<tr><td><b>'.&mt('List of CODES to validate against:').'</b></td><td><tt>'.
1.373     albertel 6323: 	    $env{'form.scantron_CODElist'}.'</tt></td></tr>';
1.284     albertel 6324:     }
1.492     albertel 6325:     return ('
1.203     albertel 6326: <p>
1.492     albertel 6327: <span class="LC_warning">
                   6328: '.&mt('Please double check the information below before clicking on \'[_1]\'',&mt($button_text)).'</span>
1.203     albertel 6329: </p>
                   6330: <table>
1.492     albertel 6331: <tr><td><b>'.&mt('Sequence to be Graded:').'</b></td><td>'.$title.'</td></tr>
                   6332: <tr><td><b>'.&mt('Data File that will be used:').'</b></td><td><tt>'.$env{'form.scantron_selectfile'}.'</tt></td></tr>
                   6333: '.$CODElist.'
1.203     albertel 6334: </table>
                   6335: <br />
1.492     albertel 6336: <p> '.&mt('If this information is correct, please click on \'[_1]\'.',&mt($button_text)).'</p>
                   6337: <p> '.&mt('If something is incorrect, please click the \'Grading Menu\' button to start over.').'</p>
1.203     albertel 6338: 
                   6339: <br />
1.492     albertel 6340: ');
1.203     albertel 6341: }
                   6342: 
1.423     albertel 6343: =pod
                   6344: 
                   6345: =item scantron_do_warning
                   6346: 
1.424     albertel 6347:    Check if the operator has picked something for all required
                   6348:    fields. Error out if something is missing.
                   6349: 
1.423     albertel 6350: =cut
                   6351: 
1.203     albertel 6352: sub scantron_do_warning {
                   6353:     my ($r)=@_;
1.324     albertel 6354:     my ($symb)=&get_symb($r);
1.203     albertel 6355:     if (!$symb) {return '';}
1.324     albertel 6356:     my $default_form_data=&defaultFormData($symb);
1.203     albertel 6357:     $r->print(&scantron_form_start().$default_form_data);
1.257     albertel 6358:     if ( $env{'form.selectpage'} eq '' ||
                   6359: 	 $env{'form.scantron_selectfile'} eq '' ||
                   6360: 	 $env{'form.scantron_format'} eq '' ) {
1.492     albertel 6361: 	$r->print("<p>".&mt('You have forgetten to specify some information. Please go Back and try again.')."</p>");
1.257     albertel 6362: 	if ( $env{'form.selectpage'} eq '') {
1.492     albertel 6363: 	    $r->print('<p><span class="LC_error">'.&mt('You have not selected a Sequence to grade').'</span></p>');
1.237     albertel 6364: 	} 
1.257     albertel 6365: 	if ( $env{'form.scantron_selectfile'} eq '') {
1.492     albertel 6366: 	    $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 6367: 	} 
1.257     albertel 6368: 	if ( $env{'form.scantron_format'} eq '') {
1.492     albertel 6369: 	    $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 6370: 	} 
                   6371:     } else {
1.265     www      6372: 	my $warning=&scantron_warning_screen('Grading: Validate Records');
1.492     albertel 6373: 	$r->print('
                   6374: '.$warning.'
                   6375: <input type="submit" name="submit" value="'.&mt('Grading: Validate Records').'" />
1.203     albertel 6376: <input type="hidden" name="command" value="scantron_validate" />
1.492     albertel 6377: ');
1.237     albertel 6378:     }
1.352     albertel 6379:     $r->print("</form><br />".&show_grading_menu_form($symb));
1.203     albertel 6380:     return '';
                   6381: }
                   6382: 
1.423     albertel 6383: =pod
                   6384: 
                   6385: =item scantron_form_start
                   6386: 
1.424     albertel 6387:     html hidden input for remembering all selected grading options
                   6388: 
1.423     albertel 6389: =cut
                   6390: 
1.203     albertel 6391: sub scantron_form_start {
                   6392:     my ($max_bubble)=@_;
                   6393:     my $result= <<SCANTRONFORM;
                   6394: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="scantronupload">
1.257     albertel 6395:   <input type="hidden" name="selectpage" value="$env{'form.selectpage'}" />
                   6396:   <input type="hidden" name="scantron_format" value="$env{'form.scantron_format'}" />
                   6397:   <input type="hidden" name="scantron_selectfile" value="$env{'form.scantron_selectfile'}" />
1.218     albertel 6398:   <input type="hidden" name="scantron_maxbubble" value="$max_bubble" />
1.257     albertel 6399:   <input type="hidden" name="scantron_CODElist" value="$env{'form.scantron_CODElist'}" />
                   6400:   <input type="hidden" name="scantron_CODEunique" value="$env{'form.scantron_CODEunique'}" />
                   6401:   <input type="hidden" name="scantron_options_redo" value="$env{'form.scantron_options_redo'}" />
                   6402:   <input type="hidden" name="scantron_options_ignore" value="$env{'form.scantron_options_ignore'}" />
1.331     albertel 6403:   <input type="hidden" name="scantron_options_hidden" value="$env{'form.scantron_options_hidden'}" />
1.203     albertel 6404: SCANTRONFORM
1.447     foxr     6405: 
                   6406:   my $line = 0;
                   6407:     while (defined($env{"form.scantron.bubblelines.$line"})) {
                   6408:        my $chunk =
                   6409: 	   '<input type="hidden" name="scantron.bubblelines.'.$line.'" value="'.$env{"form.scantron.bubblelines.$line"}.'" />'."\n";
1.448     foxr     6410:        $chunk .=
                   6411: 	   '<input type="hidden" name="scantron.first_bubble_line.'.$line.'" value="'.$env{"form.scantron.first_bubble_line.$line"}.'" />'."\n";
1.503     raeburn  6412:        $chunk .= 
                   6413:            '<input type="hidden" name="scantron.sub_bubblelines.'.$line.'" value="'.$env{"form.scantron.sub_bubblelines.$line"}.'" />'."\n";
1.504     raeburn  6414:        $chunk .=
                   6415:            '<input type="hidden" name="scantron.responsetype.'.$line.'" value="'.$env{"form.scantron.responsetype.$line"}.'" />'."\n";
1.447     foxr     6416:        $result .= $chunk;
                   6417:        $line++;
                   6418:    }
1.203     albertel 6419:     return $result;
                   6420: }
                   6421: 
1.423     albertel 6422: =pod
                   6423: 
                   6424: =item scantron_validate_file
                   6425: 
1.424     albertel 6426:     Dispatch routine for doing validation of a bubble sheet data file.
                   6427: 
                   6428:     Also processes any necessary information resets that need to
                   6429:     occur before validation begins (ignore previous corrections,
                   6430:     restarting the skipped records processing)
                   6431: 
1.423     albertel 6432: =cut
                   6433: 
1.157     albertel 6434: sub scantron_validate_file {
                   6435:     my ($r) = @_;
1.324     albertel 6436:     my ($symb)=&get_symb($r);
1.157     albertel 6437:     if (!$symb) {return '';}
1.324     albertel 6438:     my $default_form_data=&defaultFormData($symb);
1.200     albertel 6439:     
                   6440:     # do the detection of only doing skipped records first befroe we delete
1.424     albertel 6441:     # them when doing the corrections reset
1.257     albertel 6442:     if ($env{'form.scantron_options_redo'} ne 'redo_skipped_ready') {
1.200     albertel 6443: 	&reset_skipping_status();
                   6444:     }
1.257     albertel 6445:     if ($env{'form.scantron_options_redo'} eq 'redo_skipped') {
1.200     albertel 6446: 	&remember_current_skipped();
1.257     albertel 6447: 	$env{'form.scantron_options_redo'}='redo_skipped_ready';
1.200     albertel 6448:     }
                   6449: 
1.257     albertel 6450:     if ($env{'form.scantron_options_ignore'} eq 'ignore_corrections') {
1.200     albertel 6451: 	&check_for_error($r,&scantron_remove_file('corrected'));
                   6452: 	&check_for_error($r,&scantron_remove_file('skipped'));
                   6453: 	&check_for_error($r,&scantron_remove_scan_data());
1.257     albertel 6454: 	$env{'form.scantron_options_ignore'}='done';
1.192     albertel 6455:     }
1.200     albertel 6456: 
1.257     albertel 6457:     if ($env{'form.scantron_corrections'}) {
1.157     albertel 6458: 	&scantron_process_corrections($r);
                   6459:     }
1.503     raeburn  6460:     $r->print('<p>'.&mt('Gathering necessary information.').'</p>');$r->rflush();
1.157     albertel 6461:     #get the student pick code ready
                   6462:     $r->print(&Apache::loncommon::studentbrowser_javascript());
1.582     raeburn  6463:     my $nav_error;
                   6464:     my $max_bubble=&scantron_get_maxbubble(\$nav_error);
                   6465:     if ($nav_error) {
                   6466:         $r->print(&navmap_errormsg());
                   6467:         return '';
                   6468:     }
1.203     albertel 6469:     my $result=&scantron_form_start($max_bubble).$default_form_data;
1.157     albertel 6470:     $r->print($result);
                   6471:     
1.334     albertel 6472:     my @validate_phases=( 'sequence',
                   6473: 			  'ID',
1.157     albertel 6474: 			  'CODE',
                   6475: 			  'doublebubble',
                   6476: 			  'missingbubbles');
1.257     albertel 6477:     if (!$env{'form.validatepass'}) {
                   6478: 	$env{'form.validatepass'} = 0;
1.157     albertel 6479:     }
1.257     albertel 6480:     my $currentphase=$env{'form.validatepass'};
1.157     albertel 6481: 
1.448     foxr     6482: 
1.157     albertel 6483:     my $stop=0;
                   6484:     while (!$stop && $currentphase < scalar(@validate_phases)) {
1.503     raeburn  6485: 	$r->print(&mt('Validating '.$validate_phases[$currentphase]).'<br />');
1.157     albertel 6486: 	$r->rflush();
                   6487: 	my $which="scantron_validate_".$validate_phases[$currentphase];
                   6488: 	{
                   6489: 	    no strict 'refs';
                   6490: 	    ($stop,$currentphase)=&$which($r,$currentphase);
                   6491: 	}
                   6492:     }
                   6493:     if (!$stop) {
1.203     albertel 6494: 	my $warning=&scantron_warning_screen('Start Grading');
1.542     raeburn  6495: 	$r->print(&mt('Validation process complete.').'<br />'.
                   6496:                   $warning.
                   6497:                   &mt('Perform verification for each student after storage of submissions?').
                   6498:                   '&nbsp;<span class="LC_nobreak"><label>'.
                   6499:                   '<input type="radio" name="verifyrecord" value="1" />'.&mt('Yes').'</label>'.
                   6500:                   ('&nbsp;'x3).'<label>'.
                   6501:                   '<input type="radio" name="verifyrecord" value="0" checked="checked" />'.&mt('No').
                   6502:                   '</label></span><br />'.
                   6503:                   &mt('Grading will take longer if you use verification.').'<br />'.
1.572     www      6504:                   &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  6505:                   '<input type="submit" name="submit" value="'.&mt('Start Grading').'" />'.
                   6506:                   '<input type="hidden" name="command" value="scantron_process" />'."\n");
1.157     albertel 6507:     } else {
                   6508: 	$r->print('<input type="hidden" name="command" value="scantron_validate" />');
                   6509: 	$r->print("<input type='hidden' name='validatepass' value='".$currentphase."' />");
                   6510:     }
                   6511:     if ($stop) {
1.334     albertel 6512: 	if ($validate_phases[$currentphase] eq 'sequence') {
1.539     riegler  6513: 	    $r->print('<input type="submit" name="submit" value="'.&mt('Ignore').' &rarr; " />');
1.492     albertel 6514: 	    $r->print(' '.&mt('this error').' <br />');
1.334     albertel 6515: 
1.492     albertel 6516: 	    $r->print(" <p>".&mt("Or click the 'Grading Menu' button to start over.")."</p>");
1.334     albertel 6517: 	} else {
1.503     raeburn  6518:             if ($validate_phases[$currentphase] eq 'doublebubble' || $validate_phases[$currentphase] eq 'missingbubbles') {
1.539     riegler  6519: 	        $r->print('<input type="button" name="submitbutton" value="'.&mt('Continue').' &rarr;" onclick="javascript:verify_bubble_radio(this.form)" />');
1.503     raeburn  6520:             } else {
1.539     riegler  6521:                 $r->print('<input type="submit" name="submit" value="'.&mt('Continue').' &rarr;" />');
1.503     raeburn  6522:             }
1.492     albertel 6523: 	    $r->print(' '.&mt('using corrected info').' <br />');
                   6524: 	    $r->print("<input type='submit' value='".&mt("Skip")."' name='scantron_skip_record' />");
                   6525: 	    $r->print(" ".&mt("this scanline saving it for later."));
1.334     albertel 6526: 	}
1.157     albertel 6527:     }
1.352     albertel 6528:     $r->print(" </form><br />".&show_grading_menu_form($symb));
1.157     albertel 6529:     return '';
                   6530: }
                   6531: 
1.423     albertel 6532: 
                   6533: =pod
                   6534: 
                   6535: =item scantron_remove_file
                   6536: 
1.424     albertel 6537:    Removes the requested bubble sheet data file, makes sure that
                   6538:    scantron_original_<filename> is never removed
                   6539: 
                   6540: 
1.423     albertel 6541: =cut
                   6542: 
1.200     albertel 6543: sub scantron_remove_file {
1.192     albertel 6544:     my ($which)=@_;
1.257     albertel 6545:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   6546:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1.192     albertel 6547:     my $file='scantron_';
1.200     albertel 6548:     if ($which eq 'corrected' || $which eq 'skipped') {
                   6549: 	$file.=$which.'_';
1.192     albertel 6550:     } else {
                   6551: 	return 'refused';
                   6552:     }
1.257     albertel 6553:     $file.=$env{'form.scantron_selectfile'};
1.200     albertel 6554:     return &Apache::lonnet::removeuserfile($cname,$cdom,$file);
                   6555: }
                   6556: 
1.423     albertel 6557: 
                   6558: =pod
                   6559: 
                   6560: =item scantron_remove_scan_data
                   6561: 
1.424     albertel 6562:    Removes all scan_data correction for the requested bubble sheet
                   6563:    data file.  (In the case that both the are doing skipped records we need
                   6564:    to remember the old skipped lines for the time being so that element
                   6565:    persists for a while.)
                   6566: 
1.423     albertel 6567: =cut
                   6568: 
1.200     albertel 6569: sub scantron_remove_scan_data {
1.257     albertel 6570:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   6571:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1.192     albertel 6572:     my @keys=&Apache::lonnet::getkeys('nohist_scantrondata',$cdom,$cname);
                   6573:     my @todelete;
1.257     albertel 6574:     my $filename=$env{'form.scantron_selectfile'};
1.192     albertel 6575:     foreach my $key (@keys) {
                   6576: 	if ($key=~/^\Q$filename\E_/) {
1.257     albertel 6577: 	    if ($env{'form.scantron_options_redo'} eq 'redo_skipped_ready' &&
1.200     albertel 6578: 		$key=~/remember_skipping/) {
                   6579: 		next;
                   6580: 	    }
1.192     albertel 6581: 	    push(@todelete,$key);
                   6582: 	}
                   6583:     }
1.200     albertel 6584:     my $result;
1.192     albertel 6585:     if (@todelete) {
1.491     albertel 6586: 	$result = &Apache::lonnet::del('nohist_scantrondata',
                   6587: 				       \@todelete,$cdom,$cname);
                   6588:     } else {
                   6589: 	$result = 'ok';
1.192     albertel 6590:     }
                   6591:     return $result;
                   6592: }
                   6593: 
1.423     albertel 6594: 
                   6595: =pod
                   6596: 
                   6597: =item scantron_getfile
                   6598: 
1.424     albertel 6599:     Fetches the requested bubble sheet data file (all 3 versions), and
                   6600:     the scan_data hash
                   6601:   
                   6602:   Arguments:
                   6603:     None
                   6604: 
                   6605:   Returns:
                   6606:     2 hash references
                   6607: 
                   6608:      - first one has 
                   6609:          orig      -
                   6610:          corrected -
                   6611:          skipped   -  each of which points to an array ref of the specified
                   6612:                       file broken up into individual lines
                   6613:          count     - number of scanlines
                   6614:  
                   6615:      - second is the scan_data hash possible keys are
1.425     albertel 6616:        ($number refers to scanline numbered $number and thus the key affects
                   6617:         only that scanline
                   6618:         $bubline refers to the specific bubble line element and the aspects
                   6619:         refers to that specific bubble line element)
                   6620: 
                   6621:        $number.user - username:domain to use
                   6622:        $number.CODE_ignore_dup 
                   6623:                     - ignore the duplicate CODE error 
                   6624:        $number.useCODE
                   6625:                     - use the CODE in the scanline as is
                   6626:        $number.no_bubble.$bubline
                   6627:                     - it is valid that there is no bubbled in bubble
                   6628:                       at $number $bubline
                   6629:        remember_skipping
                   6630:                     - a frozen hash containing keys of $number and values
                   6631:                       of either 
                   6632:                         1 - we are on a 'do skipped records pass' and plan
                   6633:                             on processing this line
                   6634:                         2 - we are on a 'do skipped records pass' and this
                   6635:                             scanline has been marked to skip yet again
1.424     albertel 6636: 
1.423     albertel 6637: =cut
                   6638: 
1.157     albertel 6639: sub scantron_getfile {
1.200     albertel 6640:     #FIXME really would prefer a scantron directory
1.257     albertel 6641:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   6642:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1.157     albertel 6643:     my $lines;
                   6644:     $lines=&Apache::lonnet::getfile('/uploaded/'.$cdom.'/'.$cname.'/'.
1.257     albertel 6645: 		       'scantron_orig_'.$env{'form.scantron_selectfile'});
1.157     albertel 6646:     my %scanlines;
                   6647:     $scanlines{'orig'}=[(split("\n",$lines,-1))];
                   6648:     my $temp=$scanlines{'orig'};
                   6649:     $scanlines{'count'}=$#$temp;
                   6650: 
                   6651:     $lines=&Apache::lonnet::getfile('/uploaded/'.$cdom.'/'.$cname.'/'.
1.257     albertel 6652: 		       'scantron_corrected_'.$env{'form.scantron_selectfile'});
1.157     albertel 6653:     if ($lines eq '-1') {
                   6654: 	$scanlines{'corrected'}=[];
                   6655:     } else {
                   6656: 	$scanlines{'corrected'}=[(split("\n",$lines,-1))];
                   6657:     }
                   6658:     $lines=&Apache::lonnet::getfile('/uploaded/'.$cdom.'/'.$cname.'/'.
1.257     albertel 6659: 		       'scantron_skipped_'.$env{'form.scantron_selectfile'});
1.157     albertel 6660:     if ($lines eq '-1') {
                   6661: 	$scanlines{'skipped'}=[];
                   6662:     } else {
                   6663: 	$scanlines{'skipped'}=[(split("\n",$lines,-1))];
                   6664:     }
1.175     albertel 6665:     my @tmp=&Apache::lonnet::dump('nohist_scantrondata',$cdom,$cname);
1.157     albertel 6666:     if ($tmp[0] =~ /^(error:|no_such_host)/) { @tmp=(); }
                   6667:     my %scan_data = @tmp;
                   6668:     return (\%scanlines,\%scan_data);
                   6669: }
                   6670: 
1.423     albertel 6671: =pod
                   6672: 
                   6673: =item lonnet_putfile
                   6674: 
1.424     albertel 6675:    Wrapper routine to call &Apache::lonnet::finishuserfileupload
                   6676: 
                   6677:  Arguments:
                   6678:    $contents - data to store
                   6679:    $filename - filename to store $contents into
                   6680: 
                   6681:  Returns:
                   6682:    result value from &Apache::lonnet::finishuserfileupload
                   6683: 
1.423     albertel 6684: =cut
                   6685: 
1.157     albertel 6686: sub lonnet_putfile {
                   6687:     my ($contents,$filename)=@_;
1.257     albertel 6688:     my $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   6689:     my $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
                   6690:     $env{'form.sillywaytopassafilearound'}=$contents;
1.275     albertel 6691:     &Apache::lonnet::finishuserfileupload($docuname,$docudom,'sillywaytopassafilearound',$filename);
1.157     albertel 6692: 
                   6693: }
                   6694: 
1.423     albertel 6695: =pod
                   6696: 
                   6697: =item scantron_putfile
                   6698: 
1.424     albertel 6699:     Stores the current version of the bubble sheet data files, and the
                   6700:     scan_data hash. (Does not modify the original version only the
                   6701:     corrected and skipped versions.
                   6702: 
                   6703:  Arguments:
                   6704:     $scanlines - hash ref that looks like the first return value from
                   6705:                  &scantron_getfile()
                   6706:     $scan_data - hash ref that looks like the second return value from
                   6707:                  &scantron_getfile()
                   6708: 
1.423     albertel 6709: =cut
                   6710: 
1.157     albertel 6711: sub scantron_putfile {
                   6712:     my ($scanlines,$scan_data) = @_;
1.200     albertel 6713:     #FIXME really would prefer a scantron directory
1.257     albertel 6714:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   6715:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1.200     albertel 6716:     if ($scanlines) {
                   6717: 	my $prefix='scantron_';
1.157     albertel 6718: # no need to update orig, shouldn't change
                   6719: #   &lonnet_putfile(join("\n",@{$scanlines->{'orig'}}),$prefix.'orig_'.
1.257     albertel 6720: #		    $env{'form.scantron_selectfile'});
1.200     albertel 6721: 	&lonnet_putfile(join("\n",@{$scanlines->{'corrected'}}),
                   6722: 			$prefix.'corrected_'.
1.257     albertel 6723: 			$env{'form.scantron_selectfile'});
1.200     albertel 6724: 	&lonnet_putfile(join("\n",@{$scanlines->{'skipped'}}),
                   6725: 			$prefix.'skipped_'.
1.257     albertel 6726: 			$env{'form.scantron_selectfile'});
1.200     albertel 6727:     }
1.175     albertel 6728:     &Apache::lonnet::put('nohist_scantrondata',$scan_data,$cdom,$cname);
1.157     albertel 6729: }
                   6730: 
1.423     albertel 6731: =pod
                   6732: 
                   6733: =item scantron_get_line
                   6734: 
1.424     albertel 6735:    Returns the correct version of the scanline
                   6736: 
                   6737:  Arguments:
                   6738:     $scanlines - hash ref that looks like the first return value from
                   6739:                  &scantron_getfile()
                   6740:     $scan_data - hash ref that looks like the second return value from
                   6741:                  &scantron_getfile()
                   6742:     $i         - number of the requested line (starts at 0)
                   6743: 
                   6744:  Returns:
                   6745:    A scanline, (either the original or the corrected one if it
                   6746:    exists), or undef if the requested scanline should be
                   6747:    skipped. (Either because it's an skipped scanline, or it's an
                   6748:    unskipped scanline and we are not doing a 'do skipped scanlines'
                   6749:    pass.
                   6750: 
1.423     albertel 6751: =cut
                   6752: 
1.157     albertel 6753: sub scantron_get_line {
1.200     albertel 6754:     my ($scanlines,$scan_data,$i)=@_;
1.376     albertel 6755:     if (&should_be_skipped($scanlines,$scan_data,$i)) { return undef; }
                   6756:     #if ($scanlines->{'skipped'}[$i]) { return undef; }
1.157     albertel 6757:     if ($scanlines->{'corrected'}[$i]) {return $scanlines->{'corrected'}[$i];}
                   6758:     return $scanlines->{'orig'}[$i]; 
                   6759: }
                   6760: 
1.423     albertel 6761: =pod
                   6762: 
                   6763: =item scantron_todo_count
                   6764: 
1.424     albertel 6765:     Counts the number of scanlines that need processing.
                   6766: 
                   6767:  Arguments:
                   6768:     $scanlines - hash ref that looks like the first return value from
                   6769:                  &scantron_getfile()
                   6770:     $scan_data - hash ref that looks like the second return value from
                   6771:                  &scantron_getfile()
                   6772: 
                   6773:  Returns:
                   6774:     $count - number of scanlines to process
                   6775: 
1.423     albertel 6776: =cut
                   6777: 
1.200     albertel 6778: sub get_todo_count {
                   6779:     my ($scanlines,$scan_data)=@_;
                   6780:     my $count=0;
                   6781:     for (my $i=0;$i<=$scanlines->{'count'};$i++) {
                   6782: 	my $line=&scantron_get_line($scanlines,$scan_data,$i);
                   6783: 	if ($line=~/^[\s\cz]*$/) { next; }
                   6784: 	$count++;
                   6785:     }
                   6786:     return $count;
                   6787: }
                   6788: 
1.423     albertel 6789: =pod
                   6790: 
                   6791: =item scantron_put_line
                   6792: 
1.424     albertel 6793:     Updates the 'corrected' or 'skipped' versions of the bubble sheet
                   6794:     data file.
                   6795: 
                   6796:  Arguments:
                   6797:     $scanlines - hash ref that looks like the first return value from
                   6798:                  &scantron_getfile()
                   6799:     $scan_data - hash ref that looks like the second return value from
                   6800:                  &scantron_getfile()
                   6801:     $i         - line number to update
                   6802:     $newline   - contents of the updated scanline
                   6803:     $skip      - if true make the line for skipping and update the
                   6804:                  'skipped' file
                   6805: 
1.423     albertel 6806: =cut
                   6807: 
1.157     albertel 6808: sub scantron_put_line {
1.200     albertel 6809:     my ($scanlines,$scan_data,$i,$newline,$skip)=@_;
1.157     albertel 6810:     if ($skip) {
                   6811: 	$scanlines->{'skipped'}[$i]=$newline;
1.376     albertel 6812: 	&start_skipping($scan_data,$i);
1.157     albertel 6813: 	return;
                   6814:     }
                   6815:     $scanlines->{'corrected'}[$i]=$newline;
                   6816: }
                   6817: 
1.423     albertel 6818: =pod
                   6819: 
                   6820: =item scantron_clear_skip
                   6821: 
1.424     albertel 6822:    Remove a line from the 'skipped' file
                   6823: 
                   6824:  Arguments:
                   6825:     $scanlines - hash ref that looks like the first return value from
                   6826:                  &scantron_getfile()
                   6827:     $scan_data - hash ref that looks like the second return value from
                   6828:                  &scantron_getfile()
                   6829:     $i         - line number to update
                   6830: 
1.423     albertel 6831: =cut
                   6832: 
1.376     albertel 6833: sub scantron_clear_skip {
                   6834:     my ($scanlines,$scan_data,$i)=@_;
                   6835:     if (exists($scanlines->{'skipped'}[$i])) {
                   6836: 	undef($scanlines->{'skipped'}[$i]);
                   6837: 	return 1;
                   6838:     }
                   6839:     return 0;
                   6840: }
                   6841: 
1.423     albertel 6842: =pod
                   6843: 
                   6844: =item scantron_filter_not_exam
                   6845: 
1.424     albertel 6846:    Filter routine used by &Apache::lonnavmaps::retrieveResources(), to
                   6847:    filter out resources that are not marked as 'exam' mode
                   6848: 
1.423     albertel 6849: =cut
                   6850: 
1.334     albertel 6851: sub scantron_filter_not_exam {
                   6852:     my ($curres)=@_;
                   6853:     
                   6854:     if (ref($curres) && $curres->is_problem() && !$curres->is_exam()) {
                   6855: 	# if the user has asked to not have either hidden
                   6856: 	# or 'randomout' controlled resources to be graded
                   6857: 	# don't include them
                   6858: 	if ($env{'form.scantron_options_hidden'} eq 'ignore_hidden'
                   6859: 	    && $curres->randomout) {
                   6860: 	    return 0;
                   6861: 	}
                   6862: 	return 1;
                   6863:     }
                   6864:     return 0;
                   6865: }
                   6866: 
1.423     albertel 6867: =pod
                   6868: 
                   6869: =item scantron_validate_sequence
                   6870: 
1.424     albertel 6871:     Validates the selected sequence, checking for resource that are
                   6872:     not set to exam mode.
                   6873: 
1.423     albertel 6874: =cut
                   6875: 
1.334     albertel 6876: sub scantron_validate_sequence {
                   6877:     my ($r,$currentphase) = @_;
                   6878: 
                   6879:     my $navmap=Apache::lonnavmaps::navmap->new();
1.582     raeburn  6880:     unless (ref($navmap)) {
                   6881:         $r->print(&navmap_errormsg());
                   6882:         return (1,$currentphase);
                   6883:     }
1.334     albertel 6884:     my (undef,undef,$sequence)=
                   6885: 	&Apache::lonnet::decode_symb($env{'form.selectpage'});
                   6886: 
                   6887:     my $map=$navmap->getResourceByUrl($sequence);
                   6888: 
                   6889:     $r->print('<input type="hidden" name="validate_sequence_exam"
                   6890:                                     value="ignore" />');
                   6891:     if ($env{'form.validate_sequence_exam'} ne 'ignore') {
                   6892: 	my @resources=
                   6893: 	    $navmap->retrieveResources($map,\&scantron_filter_not_exam,1,0);
                   6894: 	if (@resources) {
1.357     banghart 6895: 	    $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 6896: 	    return (1,$currentphase);
                   6897: 	}
                   6898:     }
                   6899: 
                   6900:     return (0,$currentphase+1);
                   6901: }
                   6902: 
1.423     albertel 6903: 
                   6904: 
1.157     albertel 6905: sub scantron_validate_ID {
                   6906:     my ($r,$currentphase) = @_;
                   6907:     
                   6908:     #get student info
                   6909:     my $classlist=&Apache::loncoursedata::get_classlist();
                   6910:     my %idmap=&username_to_idmap($classlist);
                   6911: 
                   6912:     #get scantron line setup
1.257     albertel 6913:     my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
1.157     albertel 6914:     my ($scanlines,$scan_data)=&scantron_getfile();
1.582     raeburn  6915: 
                   6916:     my $nav_error;
                   6917:     &scantron_get_maxbubble(\$nav_error); # parse needs the bubble_lines.. array.
                   6918:     if ($nav_error) {
                   6919:         $r->print(&navmap_errormsg());
                   6920:         return(1,$currentphase);
                   6921:     }
1.157     albertel 6922: 
                   6923:     my %found=('ids'=>{},'usernames'=>{});
                   6924:     for (my $i=0;$i<=$scanlines->{'count'};$i++) {
1.200     albertel 6925: 	my $line=&scantron_get_line($scanlines,$scan_data,$i);
1.157     albertel 6926: 	if ($line=~/^[\s\cz]*$/) { next; }
                   6927: 	my $scan_record=&scantron_parse_scanline($line,$i,\%scantron_config,
                   6928: 						 $scan_data);
                   6929: 	my $id=$$scan_record{'scantron.ID'};
                   6930: 	my $found;
                   6931: 	foreach my $checkid (keys(%idmap)) {
                   6932: 	    if (lc($checkid) eq lc($id)) { $found=$checkid;last; }
                   6933: 	}
                   6934: 	if ($found) {
                   6935: 	    my $username=$idmap{$found};
                   6936: 	    if ($found{'ids'}{$found}) {
                   6937: 		&scantron_get_correction($r,$i,$scan_record,\%scantron_config,
                   6938: 					 $line,'duplicateID',$found);
1.194     albertel 6939: 		return(1,$currentphase);
1.157     albertel 6940: 	    } elsif ($found{'usernames'}{$username}) {
                   6941: 		&scantron_get_correction($r,$i,$scan_record,\%scantron_config,
                   6942: 					 $line,'duplicateID',$username);
1.194     albertel 6943: 		return(1,$currentphase);
1.157     albertel 6944: 	    }
1.186     albertel 6945: 	    #FIXME store away line we previously saw the ID on to use above
1.157     albertel 6946: 	    $found{'ids'}{$found}++;
                   6947: 	    $found{'usernames'}{$username}++;
                   6948: 	} else {
                   6949: 	    if ($id =~ /^\s*$/) {
1.158     albertel 6950: 		my $username=&scan_data($scan_data,"$i.user");
1.157     albertel 6951: 		if (defined($username) && $found{'usernames'}{$username}) {
                   6952: 		    &scantron_get_correction($r,$i,$scan_record,
                   6953: 					     \%scantron_config,
                   6954: 					     $line,'duplicateID',$username);
1.194     albertel 6955: 		    return(1,$currentphase);
1.157     albertel 6956: 		} elsif (!defined($username)) {
                   6957: 		    &scantron_get_correction($r,$i,$scan_record,
                   6958: 					     \%scantron_config,
                   6959: 					     $line,'incorrectID');
1.194     albertel 6960: 		    return(1,$currentphase);
1.157     albertel 6961: 		}
                   6962: 		$found{'usernames'}{$username}++;
                   6963: 	    } else {
                   6964: 		&scantron_get_correction($r,$i,$scan_record,\%scantron_config,
                   6965: 					 $line,'incorrectID');
1.194     albertel 6966: 		return(1,$currentphase);
1.157     albertel 6967: 	    }
                   6968: 	}
                   6969:     }
                   6970: 
                   6971:     return (0,$currentphase+1);
                   6972: }
                   6973: 
1.423     albertel 6974: 
1.157     albertel 6975: sub scantron_get_correction {
                   6976:     my ($r,$i,$scan_record,$scan_config,$line,$error,$arg)=@_;
1.454     banghart 6977: #FIXME in the case of a duplicated ID the previous line, probably need
1.157     albertel 6978: #to show both the current line and the previous one and allow skipping
                   6979: #the previous one or the current one
                   6980: 
1.333     albertel 6981:     if ( $$scan_record{'scantron.PaperID'} =~ /\S/) {
1.492     albertel 6982: 	$r->print("<p>".&mt("<b>An error was detected ($error)</b>".
                   6983: 			    " for PaperID <tt>[_1]</tt>",
                   6984: 			    $$scan_record{'scantron.PaperID'})."</p> \n");
1.157     albertel 6985:     } else {
1.492     albertel 6986: 	$r->print("<p>".&mt("<b>An error was detected ($error)</b>".
                   6987: 			    " in scanline [_1] <pre>[_2]</pre>",
                   6988: 			    $i,$line)."</p> \n");
                   6989:     }
                   6990:     my $message="<p>".&mt("The ID on the form is  <tt>[_1]</tt><br />".
                   6991: 			  "The name on the paper is [_2],[_3]",
                   6992: 			  $$scan_record{'scantron.ID'},
                   6993: 			  $$scan_record{'scantron.LastName'},
                   6994: 			  $$scan_record{'scantron.FirstName'})."</p>";
1.242     albertel 6995: 
1.157     albertel 6996:     $r->print('<input type="hidden" name="scantron_corrections" value="'.$error.'" />'."\n");
                   6997:     $r->print('<input type="hidden" name="scantron_line" value="'.$i.'" />'."\n");
1.503     raeburn  6998:                            # Array populated for doublebubble or
                   6999:     my @lines_to_correct;  # missingbubble errors to build javascript
                   7000:                            # to validate radio button checking   
                   7001: 
1.157     albertel 7002:     if ($error =~ /ID$/) {
1.186     albertel 7003: 	if ($error eq 'incorrectID') {
1.492     albertel 7004: 	    $r->print("<p>".&mt("The encoded ID is not in the classlist").
                   7005: 		      "</p>\n");
1.157     albertel 7006: 	} elsif ($error eq 'duplicateID') {
1.492     albertel 7007: 	    $r->print("<p>".&mt("The encoded ID has also been used by a previous paper [_1]",$arg)."</p>\n");
1.157     albertel 7008: 	}
1.242     albertel 7009: 	$r->print($message);
1.492     albertel 7010: 	$r->print("<p>".&mt("How should I handle this?")." <br /> \n");
1.157     albertel 7011: 	$r->print("\n<ul><li> ");
                   7012: 	#FIXME it would be nice if this sent back the user ID and
                   7013: 	#could do partial userID matches
                   7014: 	$r->print(&Apache::loncommon::selectstudent_link('scantronupload',
                   7015: 				       'scantron_username','scantron_domain'));
                   7016: 	$r->print(": <input type='text' name='scantron_username' value='' />");
                   7017: 	$r->print("\n@".
1.257     albertel 7018: 		 &Apache::loncommon::select_dom_form($env{'request.role.domain'},'scantron_domain'));
1.157     albertel 7019: 
                   7020: 	$r->print('</li>');
1.186     albertel 7021:     } elsif ($error =~ /CODE$/) {
                   7022: 	if ($error eq 'incorrectCODE') {
1.492     albertel 7023: 	    $r->print("<p>".&mt("The encoded CODE is not in the list of possible CODEs.")."</p>\n");
1.186     albertel 7024: 	} elsif ($error eq 'duplicateCODE') {
1.492     albertel 7025: 	    $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 7026: 	}
1.492     albertel 7027: 	$r->print("<p>".&mt("The CODE on the form is  <tt>'[_1]'</tt>",
                   7028: 			    $$scan_record{'scantron.CODE'})."<br />\n");
1.242     albertel 7029: 	$r->print($message);
1.492     albertel 7030: 	$r->print("<p>".&mt("How should I handle this?")." <br /> \n");
1.187     albertel 7031: 	$r->print("\n<br /> ");
1.194     albertel 7032: 	my $i=0;
1.273     albertel 7033: 	if ($error eq 'incorrectCODE' 
                   7034: 	    && $$scan_record{'scantron.CODE'}=~/\S/ ) {
1.194     albertel 7035: 	    my ($max,$closest)=&scantron_get_closely_matching_CODEs($arg,$$scan_record{'scantron.CODE'});
1.278     albertel 7036: 	    if ($closest > 0) {
                   7037: 		foreach my $testcode (@{$closest}) {
                   7038: 		    my $checked='';
1.569     bisitz   7039: 		    if (!$i) { $checked=' checked="checked"'; }
1.492     albertel 7040: 		    $r->print("
                   7041:    <label>
1.569     bisitz   7042:        <input type='radio' name='scantron_CODE_resolution' value='use_closest_$i'$checked />
1.492     albertel 7043:        ".&mt("Use the similar CODE [_1] instead.",
                   7044: 	    "<b><tt>".$testcode."</tt></b>")."
                   7045:     </label>
                   7046:     <input type='hidden' name='scantron_CODE_closest_$i' value='$testcode' />");
1.278     albertel 7047: 		    $r->print("\n<br />");
                   7048: 		    $i++;
                   7049: 		}
1.194     albertel 7050: 	    }
                   7051: 	}
1.273     albertel 7052: 	if ($$scan_record{'scantron.CODE'}=~/\S/ ) {
1.569     bisitz   7053: 	    my $checked; if (!$i) { $checked=' checked="checked"'; }
1.492     albertel 7054: 	    $r->print("
                   7055:     <label>
1.569     bisitz   7056:         <input type='radio' name='scantron_CODE_resolution' value='use_unfound'$checked />
1.492     albertel 7057:        ".&mt("Use the CODE [_1] that is was on the paper, ignoring the error.",
                   7058: 	     "<b><tt>".$$scan_record{'scantron.CODE'}."</tt></b>")."
                   7059:     </label>");
1.273     albertel 7060: 	    $r->print("\n<br />");
                   7061: 	}
1.194     albertel 7062: 
1.188     albertel 7063: 	$r->print(<<ENDSCRIPT);
                   7064: <script type="text/javascript">
                   7065: function change_radio(field) {
1.190     albertel 7066:     var slct=document.scantronupload.scantron_CODE_resolution;
1.188     albertel 7067:     var i;
                   7068:     for (i=0;i<slct.length;i++) {
                   7069:         if (slct[i].value==field) { slct[i].checked=true; }
                   7070:     }
                   7071: }
                   7072: </script>
                   7073: ENDSCRIPT
1.187     albertel 7074: 	my $href="/adm/pickcode?".
1.359     www      7075: 	   "form=".&escape("scantronupload").
                   7076: 	   "&scantron_format=".&escape($env{'form.scantron_format'}).
                   7077: 	   "&scantron_CODElist=".&escape($env{'form.scantron_CODElist'}).
                   7078: 	   "&curCODE=".&escape($$scan_record{'scantron.CODE'}).
                   7079: 	   "&scantron_selectfile=".&escape($env{'form.scantron_selectfile'});
1.332     albertel 7080: 	if ($env{'form.scantron_CODElist'} =~ /\S/) { 
1.492     albertel 7081: 	    $r->print("
                   7082:     <label>
                   7083:        <input type='radio' name='scantron_CODE_resolution' value='use_found' />
                   7084:        ".&mt("[_1]Select[_2] a CODE from the list of all CODEs and use it.",
                   7085: 	     "<a target='_blank' href='$href'>","</a>")."
                   7086:     </label> 
1.558     bisitz   7087:     ".&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 7088: 	    $r->print("\n<br />");
                   7089: 	}
1.492     albertel 7090: 	$r->print("
                   7091:     <label>
                   7092:        <input type='radio' name='scantron_CODE_resolution' value='use_typed' />
                   7093:        ".&mt("Use [_1] as the CODE.",
                   7094: 	     "</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 7095: 	$r->print("\n<br /><br />");
1.157     albertel 7096:     } elsif ($error eq 'doublebubble') {
1.503     raeburn  7097: 	$r->print("<p>".&mt("There have been multiple bubbles scanned for some question(s)")."</p>\n");
1.497     foxr     7098: 
                   7099: 	# The form field scantron_questions is acutally a list of line numbers.
                   7100: 	# represented by this form so:
                   7101: 
                   7102: 	my $line_list = &questions_to_line_list($arg);
                   7103: 
1.157     albertel 7104: 	$r->print('<input type="hidden" name="scantron_questions" value="'.
1.497     foxr     7105: 		  $line_list.'" />');
1.242     albertel 7106: 	$r->print($message);
1.492     albertel 7107: 	$r->print("<p>".&mt("Please indicate which bubble should be used for grading")."</p>");
1.157     albertel 7108: 	foreach my $question (@{$arg}) {
1.503     raeburn  7109: 	    my @linenums = &prompt_for_corrections($r,$question,$scan_config,
                   7110:                                                    $scan_record, $error);
1.524     raeburn  7111:             push(@lines_to_correct,@linenums);
1.157     albertel 7112: 	}
1.503     raeburn  7113:         $r->print(&verify_bubbles_checked(@lines_to_correct));
1.157     albertel 7114:     } elsif ($error eq 'missingbubble') {
1.492     albertel 7115: 	$r->print("<p>".&mt("There have been <b>no</b> bubbles scanned for some question(s)")."</p>\n");
1.242     albertel 7116: 	$r->print($message);
1.492     albertel 7117: 	$r->print("<p>".&mt("Please indicate which bubble should be used for grading.")."</p>");
1.503     raeburn  7118: 	$r->print(&mt("Some questions have no scanned bubbles.")."\n");
1.497     foxr     7119: 
1.503     raeburn  7120: 	# The form field scantron_questions is actually a list of line numbers not
1.497     foxr     7121: 	# a list of question numbers. Therefore:
                   7122: 	#
                   7123: 	
                   7124: 	my $line_list = &questions_to_line_list($arg);
                   7125: 
1.157     albertel 7126: 	$r->print('<input type="hidden" name="scantron_questions" value="'.
1.497     foxr     7127: 		  $line_list.'" />');
1.157     albertel 7128: 	foreach my $question (@{$arg}) {
1.503     raeburn  7129: 	    my @linenums = &prompt_for_corrections($r,$question,$scan_config,
                   7130:                                                    $scan_record, $error);
1.524     raeburn  7131:             push(@lines_to_correct,@linenums);
1.157     albertel 7132: 	}
1.503     raeburn  7133:         $r->print(&verify_bubbles_checked(@lines_to_correct));
1.157     albertel 7134:     } else {
                   7135: 	$r->print("\n<ul>");
                   7136:     }
                   7137:     $r->print("\n</li></ul>");
1.497     foxr     7138: }
                   7139: 
1.503     raeburn  7140: sub verify_bubbles_checked {
                   7141:     my (@ansnums) = @_;
                   7142:     my $ansnumstr = join('","',@ansnums);
                   7143:     my $warning = &mt("A bubble or 'No bubble' selection has not been made for one or more lines.");
                   7144:     my $output = (<<ENDSCRIPT);
                   7145: <script type="text/javascript">
                   7146: function verify_bubble_radio(form) {
                   7147:     var ansnumArray = new Array ("$ansnumstr");
                   7148:     var need_bubble_count = 0;
                   7149:     for (var i=0; i<ansnumArray.length; i++) {
                   7150:         if (form.elements["scantron_correct_Q_"+ansnumArray[i]].length > 1) {
                   7151:             var bubble_picked = 0; 
                   7152:             for (var j=0; j<form.elements["scantron_correct_Q_"+ansnumArray[i]].length; j++) {
                   7153:                 if (form.elements["scantron_correct_Q_"+ansnumArray[i]][j].checked == true) {
                   7154:                     bubble_picked = 1;
                   7155:                 }
                   7156:             }
                   7157:             if (bubble_picked == 0) {
                   7158:                 need_bubble_count ++;
                   7159:             }
                   7160:         }
                   7161:     }
                   7162:     if (need_bubble_count) {
                   7163:         alert("$warning");
                   7164:         return;
                   7165:     }
                   7166:     form.submit(); 
                   7167: }
                   7168: </script>
                   7169: ENDSCRIPT
                   7170:     return $output;
                   7171: }
                   7172: 
1.497     foxr     7173: =pod
                   7174: 
                   7175: =item  questions_to_line_list
1.157     albertel 7176: 
1.497     foxr     7177: Converts a list of questions into a string of comma separated
                   7178: line numbers in the answer sheet used by the questions.  This is
                   7179: used to fill in the scantron_questions form field.
                   7180: 
                   7181:   Arguments:
                   7182:      questions    - Reference to an array of questions.
                   7183: 
                   7184: =cut
                   7185: 
                   7186: 
                   7187: sub questions_to_line_list {
                   7188:     my ($questions) = @_;
                   7189:     my @lines;
                   7190: 
1.503     raeburn  7191:     foreach my $item (@{$questions}) {
                   7192:         my $question = $item;
                   7193:         my ($first,$count,$last);
                   7194:         if ($item =~ /^(\d+)\.(\d+)$/) {
                   7195:             $question = $1;
                   7196:             my $subquestion = $2;
                   7197:             $first = $first_bubble_line{$question-1} + 1;
                   7198:             my @subans = split(/,/,$subdivided_bubble_lines{$question-1});
                   7199:             my $subcount = 1;
                   7200:             while ($subcount<$subquestion) {
                   7201:                 $first += $subans[$subcount-1];
                   7202:                 $subcount ++;
                   7203:             }
                   7204:             $count = $subans[$subquestion-1];
                   7205:         } else {
                   7206: 	    $first   = $first_bubble_line{$question-1} + 1;
                   7207: 	    $count   = $bubble_lines_per_response{$question-1};
                   7208:         }
1.506     raeburn  7209:         $last = $first+$count-1;
1.503     raeburn  7210:         push(@lines, ($first..$last));
1.497     foxr     7211:     }
                   7212:     return join(',', @lines);
                   7213: }
                   7214: 
                   7215: =pod 
                   7216: 
                   7217: =item prompt_for_corrections
                   7218: 
                   7219: Prompts for a potentially multiline correction to the
                   7220: user's bubbling (factors out common code from scantron_get_correction
                   7221: for multi and missing bubble cases).
                   7222: 
                   7223:  Arguments:
                   7224:    $r           - Apache request object.
                   7225:    $question    - The question number to prompt for.
                   7226:    $scan_config - The scantron file configuration hash.
                   7227:    $scan_record - Reference to the hash that has the the parsed scanlines.
1.503     raeburn  7228:    $error       - Type of error
1.497     foxr     7229: 
                   7230:  Implicit inputs:
                   7231:    %bubble_lines_per_response   - Starting line numbers for each question.
                   7232:                                   Numbered from 0 (but question numbers are from
                   7233:                                   1.
                   7234:    %first_bubble_line           - Starting bubble line for each question.
1.509     raeburn  7235:    %subdivided_bubble_lines     - optionresponse, matchresponse and rankresponse 
                   7236:                                   type problems render as separate sub-questions, 
1.503     raeburn  7237:                                   in exam mode. This hash contains a 
                   7238:                                   comma-separated list of the lines per 
                   7239:                                   sub-question.
1.510     raeburn  7240:    %responsetype_per_response   - essayresponse, formularesponse,
                   7241:                                   stringresponse, imageresponse, reactionresponse,
                   7242:                                   and organicresponse type problem parts can have
1.503     raeburn  7243:                                   multiple lines per response if the weight
                   7244:                                   assigned exceeds 10.  In this case, only
                   7245:                                   one bubble per line is permitted, but more 
                   7246:                                   than one line might contain bubbles, e.g.
                   7247:                                   bubbling of: line 1 - J, line 2 - J, 
                   7248:                                   line 3 - B would assign 22 points.  
1.497     foxr     7249: 
                   7250: =cut
                   7251: 
                   7252: sub prompt_for_corrections {
1.503     raeburn  7253:     my ($r, $question, $scan_config, $scan_record, $error) = @_;
                   7254:     my ($current_line,$lines);
                   7255:     my @linenums;
                   7256:     my $questionnum = $question;
                   7257:     if ($question =~ /^(\d+)\.(\d+)$/) {
                   7258:         $question = $1;
                   7259:         $current_line = $first_bubble_line{$question-1} + 1 ;
                   7260:         my $subquestion = $2;
                   7261:         my @subans = split(/,/,$subdivided_bubble_lines{$question-1});
                   7262:         my $subcount = 1;
                   7263:         while ($subcount<$subquestion) {
                   7264:             $current_line += $subans[$subcount-1];
                   7265:             $subcount ++;
                   7266:         }
                   7267:         $lines = $subans[$subquestion-1];
                   7268:     } else {
                   7269:         $current_line = $first_bubble_line{$question-1} + 1 ;
                   7270:         $lines        = $bubble_lines_per_response{$question-1};
                   7271:     }
1.497     foxr     7272:     if ($lines > 1) {
1.503     raeburn  7273:         $r->print(&mt('The group of bubble lines below responds to a single question.').'<br />');
                   7274:         if (($responsetype_per_response{$question-1} eq 'essayresponse') ||
                   7275:             ($responsetype_per_response{$question-1} eq 'formularesponse') ||
1.510     raeburn  7276:             ($responsetype_per_response{$question-1} eq 'stringresponse') ||
                   7277:             ($responsetype_per_response{$question-1} eq 'imageresponse') ||
                   7278:             ($responsetype_per_response{$question-1} eq 'reactionresponse') ||
                   7279:             ($responsetype_per_response{$question-1} eq 'organicresponse')) {
1.572     www      7280:             $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  7281:         } else {
                   7282:             $r->print(&mt("Select at most one bubble in a single line and select 'No Bubble' in all the other lines. ")."<br />");
                   7283:         }
1.497     foxr     7284:     }
                   7285:     for (my $i =0; $i < $lines; $i++) {
1.503     raeburn  7286:         my $selected = $$scan_record{"scantron.$current_line.answer"};
                   7287: 	&scantron_bubble_selector($r,$scan_config,$current_line, 
                   7288: 	        		  $questionnum,$error,split('', $selected));
1.524     raeburn  7289:         push(@linenums,$current_line);
1.497     foxr     7290: 	$current_line++;
                   7291:     }
                   7292:     if ($lines > 1) {
                   7293: 	$r->print("<hr /><br />");
                   7294:     }
1.503     raeburn  7295:     return @linenums;
1.157     albertel 7296: }
1.423     albertel 7297: 
                   7298: =pod
                   7299: 
                   7300: =item scantron_bubble_selector
                   7301:   
                   7302:    Generates the html radiobuttons to correct a single bubble line
1.424     albertel 7303:    possibly showing the existing the selected bubbles if known
1.423     albertel 7304: 
                   7305:  Arguments:
                   7306:     $r           - Apache request object
                   7307:     $scan_config - hash from &get_scantron_config()
1.497     foxr     7308:     $line        - Number of the line being displayed.
1.503     raeburn  7309:     $questionnum - Question number (may include subquestion)
                   7310:     $error       - Type of error.
1.497     foxr     7311:     @selected    - Array of bubbles picked on this line.
1.423     albertel 7312: 
                   7313: =cut
                   7314: 
1.157     albertel 7315: sub scantron_bubble_selector {
1.503     raeburn  7316:     my ($r,$scan_config,$line,$questionnum,$error,@selected)=@_;
1.157     albertel 7317:     my $max=$$scan_config{'Qlength'};
1.274     albertel 7318: 
                   7319:     my $scmode=$$scan_config{'Qon'};
                   7320:     if ($scmode eq 'number' || $scmode eq 'letter') { $max=10; }	     
                   7321: 
1.157     albertel 7322:     my @alphabet=('A'..'Z');
1.503     raeburn  7323:     $r->print(&Apache::loncommon::start_data_table().
                   7324:               &Apache::loncommon::start_data_table_row());
                   7325:     $r->print('<td rowspan="2" class="LC_leftcol_header">'.$line.'</td>');
1.497     foxr     7326:     for (my $i=0;$i<$max+1;$i++) {
                   7327: 	$r->print("\n".'<td align="center">');
                   7328: 	if ($selected[0] eq $alphabet[$i]) { $r->print('X'); shift(@selected) }
                   7329: 	else { $r->print('&nbsp;'); }
                   7330: 	$r->print('</td>');
                   7331:     }
1.503     raeburn  7332:     $r->print(&Apache::loncommon::end_data_table_row().
                   7333:               &Apache::loncommon::start_data_table_row());
1.497     foxr     7334:     for (my $i=0;$i<$max;$i++) {
                   7335: 	$r->print("\n".
                   7336: 		  '<td><label><input type="radio" name="scantron_correct_Q_'.
                   7337: 		  $line.'" value="'.$i.'" />'.$alphabet[$i]."</label></td>");
                   7338:     }
1.503     raeburn  7339:     my $nobub_checked = ' ';
                   7340:     if ($error eq 'missingbubble') {
                   7341:         $nobub_checked = ' checked = "checked" ';
                   7342:     }
                   7343:     $r->print("\n".'<td><label><input type="radio" name="scantron_correct_Q_'.
                   7344: 	      $line.'" value="none"'.$nobub_checked.'/>'.&mt('No bubble').
                   7345:               '</label>'."\n".'<input type="hidden" name="scantron_questionnum_Q_'.
                   7346:               $line.'" value="'.$questionnum.'" /></td>');
                   7347:     $r->print(&Apache::loncommon::end_data_table_row().
                   7348:               &Apache::loncommon::end_data_table());
1.157     albertel 7349: }
                   7350: 
1.423     albertel 7351: =pod
                   7352: 
                   7353: =item num_matches
                   7354: 
1.424     albertel 7355:    Counts the number of characters that are the same between the two arguments.
                   7356: 
                   7357:  Arguments:
                   7358:    $orig - CODE from the scanline
                   7359:    $code - CODE to match against
                   7360: 
                   7361:  Returns:
                   7362:    $count - integer count of the number of same characters between the
                   7363:             two arguments
                   7364: 
1.423     albertel 7365: =cut
                   7366: 
1.194     albertel 7367: sub num_matches {
                   7368:     my ($orig,$code) = @_;
                   7369:     my @code=split(//,$code);
                   7370:     my @orig=split(//,$orig);
                   7371:     my $same=0;
                   7372:     for (my $i=0;$i<scalar(@code);$i++) {
                   7373: 	if ($code[$i] eq $orig[$i]) { $same++; }
                   7374:     }
                   7375:     return $same;
                   7376: }
                   7377: 
1.423     albertel 7378: =pod
                   7379: 
                   7380: =item scantron_get_closely_matching_CODEs
                   7381: 
1.424     albertel 7382:    Cycles through all CODEs and finds the set that has the greatest
                   7383:    number of same characters as the provided CODE
                   7384: 
                   7385:  Arguments:
                   7386:    $allcodes - hash ref returned by &get_codes()
                   7387:    $CODE     - CODE from the current scanline
                   7388: 
                   7389:  Returns:
                   7390:    2 element list
                   7391:     - first elements is number of how closely matching the best fit is 
                   7392:       (5 means best set has 5 matching characters)
                   7393:     - second element is an arrary ref containing the set of valid CODEs
                   7394:       that best fit the passed in CODE
                   7395: 
1.423     albertel 7396: =cut
                   7397: 
1.194     albertel 7398: sub scantron_get_closely_matching_CODEs {
                   7399:     my ($allcodes,$CODE)=@_;
                   7400:     my @CODEs;
                   7401:     foreach my $testcode (sort(keys(%{$allcodes}))) {
                   7402: 	push(@{$CODEs[&num_matches($CODE,$testcode)]},$testcode);
                   7403:     }
                   7404: 
                   7405:     return ($#CODEs,$CODEs[-1]);
                   7406: }
                   7407: 
1.423     albertel 7408: =pod
                   7409: 
                   7410: =item get_codes
                   7411: 
1.424     albertel 7412:    Builds a hash which has keys of all of the valid CODEs from the selected
                   7413:    set of remembered CODEs.
                   7414: 
                   7415:  Arguments:
                   7416:   $old_name - name of the set of remembered CODEs
                   7417:   $cdom     - domain of the course
                   7418:   $cnum     - internal course name
                   7419: 
                   7420:  Returns:
                   7421:   %allcodes - keys are the valid CODEs, values are all 1
                   7422: 
1.423     albertel 7423: =cut
                   7424: 
1.194     albertel 7425: sub get_codes {
1.280     foxr     7426:     my ($old_name, $cdom, $cnum) = @_;
                   7427:     if (!$old_name) {
                   7428: 	$old_name=$env{'form.scantron_CODElist'};
                   7429:     }
                   7430:     if (!$cdom) {
                   7431: 	$cdom =$env{'course.'.$env{'request.course.id'}.'.domain'};
                   7432:     }
                   7433:     if (!$cnum) {
                   7434: 	$cnum =$env{'course.'.$env{'request.course.id'}.'.num'};
                   7435:     }
1.278     albertel 7436:     my %result=&Apache::lonnet::get('CODEs',[$old_name,"type\0$old_name"],
                   7437: 				    $cdom,$cnum);
                   7438:     my %allcodes;
                   7439:     if ($result{"type\0$old_name"} eq 'number') {
                   7440: 	%allcodes=map {($_,1)} split(',',$result{$old_name});
                   7441:     } else {
                   7442: 	%allcodes=map {(&Apache::lonprintout::num_to_letters($_),1)} split(',',$result{$old_name});
                   7443:     }
1.194     albertel 7444:     return %allcodes;
                   7445: }
                   7446: 
1.423     albertel 7447: =pod
                   7448: 
                   7449: =item scantron_validate_CODE
                   7450: 
1.424     albertel 7451:    Validates all scanlines in the selected file to not have any
                   7452:    invalid or underspecified CODEs and that none of the codes are
                   7453:    duplicated if this was requested.
                   7454: 
1.423     albertel 7455: =cut
                   7456: 
1.157     albertel 7457: sub scantron_validate_CODE {
                   7458:     my ($r,$currentphase) = @_;
1.257     albertel 7459:     my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
1.186     albertel 7460:     if ($scantron_config{'CODElocation'} &&
                   7461: 	$scantron_config{'CODEstart'} &&
                   7462: 	$scantron_config{'CODElength'}) {
1.257     albertel 7463: 	if (!defined($env{'form.scantron_CODElist'})) {
1.186     albertel 7464: 	    &FIXME_blow_up()
                   7465: 	}
                   7466:     } else {
                   7467: 	return (0,$currentphase+1);
                   7468:     }
                   7469:     
                   7470:     my %usedCODEs;
                   7471: 
1.194     albertel 7472:     my %allcodes=&get_codes();
1.186     albertel 7473: 
1.582     raeburn  7474:     my $nav_error;
                   7475:     &scantron_get_maxbubble(\$nav_error); # parse needs the lines per response array.
                   7476:     if ($nav_error) {
                   7477:         $r->print(&navmap_errormsg());
                   7478:         return(1,$currentphase);
                   7479:     }
1.447     foxr     7480: 
1.186     albertel 7481:     my ($scanlines,$scan_data)=&scantron_getfile();
                   7482:     for (my $i=0;$i<=$scanlines->{'count'};$i++) {
1.200     albertel 7483: 	my $line=&scantron_get_line($scanlines,$scan_data,$i);
1.186     albertel 7484: 	if ($line=~/^[\s\cz]*$/) { next; }
                   7485: 	my $scan_record=&scantron_parse_scanline($line,$i,\%scantron_config,
                   7486: 						 $scan_data);
                   7487: 	my $CODE=$$scan_record{'scantron.CODE'};
                   7488: 	my $error=0;
1.224     albertel 7489: 	if (!&Apache::lonnet::validCODE($CODE)) {
                   7490: 	    &scantron_get_correction($r,$i,$scan_record,
                   7491: 				     \%scantron_config,
                   7492: 				     $line,'incorrectCODE',\%allcodes);
                   7493: 	    return(1,$currentphase);
                   7494: 	}
1.221     albertel 7495: 	if (%allcodes && !exists($allcodes{$CODE}) 
                   7496: 	    && !$$scan_record{'scantron.useCODE'}) {
1.186     albertel 7497: 	    &scantron_get_correction($r,$i,$scan_record,
                   7498: 				     \%scantron_config,
1.194     albertel 7499: 				     $line,'incorrectCODE',\%allcodes);
                   7500: 	    return(1,$currentphase);
1.186     albertel 7501: 	}
1.214     albertel 7502: 	if (exists($usedCODEs{$CODE}) 
1.257     albertel 7503: 	    && $env{'form.scantron_CODEunique'} eq 'yes'
1.192     albertel 7504: 	    && !$$scan_record{'scantron.CODE_ignore_dup'}) {
1.186     albertel 7505: 	    &scantron_get_correction($r,$i,$scan_record,
                   7506: 				     \%scantron_config,
1.194     albertel 7507: 				     $line,'duplicateCODE',$usedCODEs{$CODE});
                   7508: 	    return(1,$currentphase);
1.186     albertel 7509: 	}
1.524     raeburn  7510: 	push(@{$usedCODEs{$CODE}},$$scan_record{'scantron.PaperID'});
1.186     albertel 7511:     }
1.157     albertel 7512:     return (0,$currentphase+1);
                   7513: }
                   7514: 
1.423     albertel 7515: =pod
                   7516: 
                   7517: =item scantron_validate_doublebubble
                   7518: 
1.424     albertel 7519:    Validates all scanlines in the selected file to not have any
                   7520:    bubble lines with multiple bubbles marked.
                   7521: 
1.423     albertel 7522: =cut
                   7523: 
1.157     albertel 7524: sub scantron_validate_doublebubble {
                   7525:     my ($r,$currentphase) = @_;
                   7526:     #get student info
                   7527:     my $classlist=&Apache::loncoursedata::get_classlist();
                   7528:     my %idmap=&username_to_idmap($classlist);
                   7529: 
                   7530:     #get scantron line setup
1.257     albertel 7531:     my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
1.157     albertel 7532:     my ($scanlines,$scan_data)=&scantron_getfile();
1.583     raeburn  7533:     my $nav_error;
                   7534:     &scantron_get_maxbubble(\$nav_error); # parse needs the bubble line array.
                   7535:     if ($nav_error) {
                   7536:         $r->print(&navmap_errormsg());
                   7537:         return(1,$currentphase);
                   7538:     }
1.447     foxr     7539: 
1.157     albertel 7540:     for (my $i=0;$i<=$scanlines->{'count'};$i++) {
1.200     albertel 7541: 	my $line=&scantron_get_line($scanlines,$scan_data,$i);
1.157     albertel 7542: 	if ($line=~/^[\s\cz]*$/) { next; }
                   7543: 	my $scan_record=&scantron_parse_scanline($line,$i,\%scantron_config,
                   7544: 						 $scan_data);
                   7545: 	if (!defined($$scan_record{'scantron.doubleerror'})) { next; }
                   7546: 	&scantron_get_correction($r,$i,$scan_record,\%scantron_config,$line,
                   7547: 				 'doublebubble',
                   7548: 				 $$scan_record{'scantron.doubleerror'});
                   7549:     	return (1,$currentphase);
                   7550:     }
                   7551:     return (0,$currentphase+1);
                   7552: }
                   7553: 
1.423     albertel 7554: 
1.503     raeburn  7555: sub scantron_get_maxbubble {
1.582     raeburn  7556:     my ($nav_error) = @_;
1.257     albertel 7557:     if (defined($env{'form.scantron_maxbubble'}) &&
                   7558: 	$env{'form.scantron_maxbubble'}) {
1.447     foxr     7559: 	&restore_bubble_lines();
1.257     albertel 7560: 	return $env{'form.scantron_maxbubble'};
1.191     albertel 7561:     }
1.330     albertel 7562: 
1.447     foxr     7563:     my (undef, undef, $sequence) =
1.257     albertel 7564: 	&Apache::lonnet::decode_symb($env{'form.selectpage'});
1.330     albertel 7565: 
1.447     foxr     7566:     my $navmap=Apache::lonnavmaps::navmap->new();
1.582     raeburn  7567:     unless (ref($navmap)) {
                   7568:         if (ref($nav_error)) {
                   7569:             $$nav_error = 1;
                   7570:         }
1.591     raeburn  7571:         return;
1.582     raeburn  7572:     }
1.191     albertel 7573:     my $map=$navmap->getResourceByUrl($sequence);
                   7574:     my @resources=$navmap->retrieveResources($map,\&scantron_filter,1,0);
1.330     albertel 7575: 
                   7576:     &Apache::lonxml::clear_problem_counter();
                   7577: 
1.557     raeburn  7578:     my $uname       = $env{'user.name'};
                   7579:     my $udom        = $env{'user.domain'};
1.435     foxr     7580:     my $cid         = $env{'request.course.id'};
                   7581:     my $total_lines = 0;
                   7582:     %bubble_lines_per_response = ();
1.447     foxr     7583:     %first_bubble_line         = ();
1.503     raeburn  7584:     %subdivided_bubble_lines   = ();
                   7585:     %responsetype_per_response = ();
1.554     raeburn  7586: 
1.447     foxr     7587:     my $response_number = 0;
                   7588:     my $bubble_line     = 0;
1.191     albertel 7589:     foreach my $resource (@resources) {
1.542     raeburn  7590:         my ($analysis,$parts) = &scantron_partids_tograde($resource,$cid,$uname,$udom);
                   7591:         if ((ref($analysis) eq 'HASH') && (ref($parts) eq 'ARRAY')) {
                   7592: 	    foreach my $part_id (@{$parts}) {
                   7593:                 my $lines;
                   7594: 
                   7595: 	        # TODO - make this a persistent hash not an array.
                   7596: 
                   7597:                 # optionresponse, matchresponse and rankresponse type items 
                   7598:                 # render as separate sub-questions in exam mode.
                   7599:                 if (($analysis->{$part_id.'.type'} eq 'optionresponse') ||
                   7600:                     ($analysis->{$part_id.'.type'} eq 'matchresponse') ||
                   7601:                     ($analysis->{$part_id.'.type'} eq 'rankresponse')) {
                   7602:                     my ($numbub,$numshown);
                   7603:                     if ($analysis->{$part_id.'.type'} eq 'optionresponse') {
                   7604:                         if (ref($analysis->{$part_id.'.options'}) eq 'ARRAY') {
                   7605:                             $numbub = scalar(@{$analysis->{$part_id.'.options'}});
                   7606:                         }
                   7607:                     } elsif ($analysis->{$part_id.'.type'} eq 'matchresponse') {
                   7608:                         if (ref($analysis->{$part_id.'.items'}) eq 'ARRAY') {
                   7609:                             $numbub = scalar(@{$analysis->{$part_id.'.items'}});
                   7610:                         }
                   7611:                     } elsif ($analysis->{$part_id.'.type'} eq 'rankresponse') {
                   7612:                         if (ref($analysis->{$part_id.'.foils'}) eq 'ARRAY') {
                   7613:                             $numbub = scalar(@{$analysis->{$part_id.'.foils'}});
                   7614:                         }
                   7615:                     }
                   7616:                     if (ref($analysis->{$part_id.'.shown'}) eq 'ARRAY') {
                   7617:                         $numshown = scalar(@{$analysis->{$part_id.'.shown'}});
                   7618:                     }
                   7619:                     my $bubbles_per_line = 10;
                   7620:                     my $inner_bubble_lines = int($numbub/$bubbles_per_line);
                   7621:                     if (($numbub % $bubbles_per_line) != 0) {
                   7622:                         $inner_bubble_lines++;
                   7623:                     }
                   7624:                     for (my $i=0; $i<$numshown; $i++) {
                   7625:                         $subdivided_bubble_lines{$response_number} .= 
                   7626:                             $inner_bubble_lines.',';
                   7627:                     }
                   7628:                     $subdivided_bubble_lines{$response_number} =~ s/,$//;
                   7629:                     $lines = $numshown * $inner_bubble_lines;
                   7630:                 } else {
                   7631:                     $lines = $analysis->{"$part_id.bubble_lines"};
                   7632:                 } 
                   7633: 
                   7634:                 $first_bubble_line{$response_number} = $bubble_line;
                   7635: 	        $bubble_lines_per_response{$response_number} = $lines;
                   7636:                 $responsetype_per_response{$response_number} = 
                   7637:                     $analysis->{$part_id.'.type'};
                   7638: 	        $response_number++;
                   7639: 
                   7640: 	        $bubble_line +=  $lines;
                   7641: 	        $total_lines +=  $lines;
                   7642: 	    }
                   7643:         }
                   7644:     }
1.552     raeburn  7645:     &Apache::lonnet::delenv('scantron.');
1.542     raeburn  7646: 
                   7647:     &save_bubble_lines();
                   7648:     $env{'form.scantron_maxbubble'} =
                   7649: 	$total_lines;
                   7650:     return $env{'form.scantron_maxbubble'};
                   7651: }
1.523     raeburn  7652: 
1.157     albertel 7653: sub scantron_validate_missingbubbles {
                   7654:     my ($r,$currentphase) = @_;
                   7655:     #get student info
                   7656:     my $classlist=&Apache::loncoursedata::get_classlist();
                   7657:     my %idmap=&username_to_idmap($classlist);
                   7658: 
                   7659:     #get scantron line setup
1.257     albertel 7660:     my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
1.157     albertel 7661:     my ($scanlines,$scan_data)=&scantron_getfile();
1.582     raeburn  7662:     my $nav_error;
                   7663:     my $max_bubble=&scantron_get_maxbubble(\$nav_error);
                   7664:     if ($nav_error) {
                   7665:         return(1,$currentphase);
                   7666:     }
1.157     albertel 7667:     if (!$max_bubble) { $max_bubble=2**31; }
                   7668:     for (my $i=0;$i<=$scanlines->{'count'};$i++) {
1.200     albertel 7669: 	my $line=&scantron_get_line($scanlines,$scan_data,$i);
1.157     albertel 7670: 	if ($line=~/^[\s\cz]*$/) { next; }
                   7671: 	my $scan_record=&scantron_parse_scanline($line,$i,\%scantron_config,
                   7672: 						 $scan_data);
                   7673: 	if (!defined($$scan_record{'scantron.missingerror'})) { next; }
                   7674: 	my @to_correct;
1.470     foxr     7675: 	
                   7676: 	# Probably here's where the error is...
                   7677: 
1.157     albertel 7678: 	foreach my $missing (@{$$scan_record{'scantron.missingerror'}}) {
1.505     raeburn  7679:             my $lastbubble;
                   7680:             if ($missing =~ /^(\d+)\.(\d+)$/) {
                   7681:                my $question = $1;
                   7682:                my $subquestion = $2;
                   7683:                if (!defined($first_bubble_line{$question -1})) { next; }
                   7684:                my $first = $first_bubble_line{$question-1};
                   7685:                my @subans = split(/,/,$subdivided_bubble_lines{$question-1});
                   7686:                my $subcount = 1;
                   7687:                while ($subcount<$subquestion) {
                   7688:                    $first += $subans[$subcount-1];
                   7689:                    $subcount ++;
                   7690:                }
                   7691:                my $count = $subans[$subquestion-1];
                   7692:                $lastbubble = $first + $count;
                   7693:             } else {
                   7694:                 if (!defined($first_bubble_line{$missing - 1})) { next; }
                   7695:                 $lastbubble = $first_bubble_line{$missing - 1} + $bubble_lines_per_response{$missing - 1};
                   7696:             }
                   7697:             if ($lastbubble > $max_bubble) { next; }
1.157     albertel 7698: 	    push(@to_correct,$missing);
                   7699: 	}
                   7700: 	if (@to_correct) {
                   7701: 	    &scantron_get_correction($r,$i,$scan_record,\%scantron_config,
                   7702: 				     $line,'missingbubble',\@to_correct);
                   7703: 	    return (1,$currentphase);
                   7704: 	}
                   7705: 
                   7706:     }
                   7707:     return (0,$currentphase+1);
                   7708: }
                   7709: 
1.423     albertel 7710: 
1.82      albertel 7711: sub scantron_process_students {
1.75      albertel 7712:     my ($r) = @_;
1.513     foxr     7713: 
1.257     albertel 7714:     my (undef,undef,$sequence)=&Apache::lonnet::decode_symb($env{'form.selectpage'});
1.324     albertel 7715:     my ($symb)=&get_symb($r);
1.513     foxr     7716:     if (!$symb) {
                   7717: 	return '';
                   7718:     }
1.324     albertel 7719:     my $default_form_data=&defaultFormData($symb);
1.82      albertel 7720: 
1.257     albertel 7721:     my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
1.157     albertel 7722:     my ($scanlines,$scan_data)=&scantron_getfile();
1.82      albertel 7723:     my $classlist=&Apache::loncoursedata::get_classlist();
                   7724:     my %idmap=&username_to_idmap($classlist);
1.132     bowersj2 7725:     my $navmap=Apache::lonnavmaps::navmap->new();
1.582     raeburn  7726:     unless (ref($navmap)) {
                   7727:         $r->print(&navmap_errormsg());
                   7728:         return '';
                   7729:     }  
1.83      albertel 7730:     my $map=$navmap->getResourceByUrl($sequence);
                   7731:     my @resources=$navmap->retrieveResources($map,\&scantron_filter,1,0);
1.557     raeburn  7732:     my (%grader_partids_by_symb,%grader_randomlists_by_symb);
                   7733:     &graders_resources_pass(\@resources,\%grader_partids_by_symb,
                   7734:                             \%grader_randomlists_by_symb);
1.586     raeburn  7735:     my $resource_error;
1.557     raeburn  7736:     foreach my $resource (@resources) {
1.586     raeburn  7737:         my $ressymb;
                   7738:         if (ref($resource)) {
                   7739:             $ressymb = $resource->symb();
                   7740:         } else {
                   7741:             $resource_error = 1;
                   7742:             last;
                   7743:         }
1.557     raeburn  7744:         my ($analysis,$parts) =
                   7745:             &scantron_partids_tograde($resource,$env{'request.course.id'},
                   7746:                                       $env{'user.name'},$env{'user.domain'},1);
                   7747:         $grader_partids_by_symb{$ressymb} = $parts;
                   7748:         if (ref($analysis) eq 'HASH') {
                   7749:             if (ref($analysis->{'parts_withrandomlist'}) eq 'ARRAY') {
                   7750:                 $grader_randomlists_by_symb{$ressymb} = 
                   7751:                     $analysis->{'parts_withrandomlist'};
                   7752:             }
                   7753:         }
                   7754:     }
1.586     raeburn  7755:     if ($resource_error) {
                   7756:         $r->print(&navmap_errormsg());
                   7757:         return '';
                   7758:     }
1.557     raeburn  7759: 
1.554     raeburn  7760:     my ($uname,$udom);
1.82      albertel 7761:     my $result= <<SCANTRONFORM;
1.81      albertel 7762: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="scantronupload">
                   7763:   <input type="hidden" name="command" value="scantron_configphase" />
                   7764:   $default_form_data
                   7765: SCANTRONFORM
1.82      albertel 7766:     $r->print($result);
                   7767: 
                   7768:     my @delayqueue;
1.542     raeburn  7769:     my (%completedstudents,%scandata);
1.140     albertel 7770:     
1.520     www      7771:     my $lock=&Apache::lonnet::set_lock(&mt('Grading bubblesheet exam'));
1.200     albertel 7772:     my $count=&get_todo_count($scanlines,$scan_data);
1.575     www      7773:     my %prog_state=&Apache::lonhtmlcommon::Create_PrgWin($r,'Bubblesheet Status',
                   7774:  				    'Bubblesheet Progress',$count,
1.195     albertel 7775: 				    'inline',undef,'scantronupload');
1.140     albertel 7776:     &Apache::lonhtmlcommon::Update_PrgWin($r,\%prog_state,
                   7777: 					  'Processing first student');
1.542     raeburn  7778:     $r->print('<br />');
1.140     albertel 7779:     my $start=&Time::HiRes::time();
1.158     albertel 7780:     my $i=-1;
1.542     raeburn  7781:     my $started;
1.447     foxr     7782: 
1.582     raeburn  7783:     my $nav_error;
                   7784:     &scantron_get_maxbubble(\$nav_error); # Need the bubble lines array to parse.
                   7785:     if ($nav_error) {
                   7786:         $r->print(&navmap_errormsg());
                   7787:         return '';
                   7788:     }
                   7789: 
1.513     foxr     7790:     # If an ssi failed in scantron_get_maxbubble, put an error message out to
                   7791:     # the user and return.
                   7792: 
                   7793:     if ($ssi_error) {
                   7794: 	$r->print("</form>");
                   7795: 	&ssi_print_error($r);
                   7796: 	$r->print(&show_grading_menu_form($symb));
1.520     www      7797:         &Apache::lonnet::remove_lock($lock);
1.513     foxr     7798: 	return '';		# Dunno why the other returns return '' rather than just returning.
                   7799:     }
1.447     foxr     7800: 
1.542     raeburn  7801:     my %lettdig = &letter_to_digits();
                   7802:     my $numletts = scalar(keys(%lettdig));
                   7803: 
1.157     albertel 7804:     while ($i<$scanlines->{'count'}) {
                   7805:  	($uname,$udom)=('','');
                   7806:  	$i++;
1.200     albertel 7807:  	my $line=&scantron_get_line($scanlines,$scan_data,$i);
1.157     albertel 7808:  	if ($line=~/^[\s\cz]*$/) { next; }
1.200     albertel 7809: 	if ($started) {
                   7810: 	    &Apache::lonhtmlcommon::Increment_PrgWin($r,\%prog_state,
                   7811: 						     'last student');
                   7812: 	}
                   7813: 	$started=1;
1.157     albertel 7814:  	my $scan_record=&scantron_parse_scanline($line,$i,\%scantron_config,
                   7815:  						 $scan_data);
                   7816:  	unless ($uname=&scantron_find_student($scan_record,$scan_data,
                   7817:  					      \%idmap,$i)) {
                   7818:   	    &scantron_add_delay(\@delayqueue,$line,
                   7819:  				'Unable to find a student that matches',1);
                   7820:  	    next;
                   7821:   	}
                   7822:  	if (exists $completedstudents{$uname}) {
                   7823:  	    &scantron_add_delay(\@delayqueue,$line,
                   7824:  				'Student '.$uname.' has multiple sheets',2);
                   7825:  	    next;
                   7826:  	}
                   7827:   	($uname,$udom)=split(/:/,$uname);
1.330     albertel 7828: 
1.586     raeburn  7829:         my (%partids_by_symb,$res_error);
1.554     raeburn  7830:         foreach my $resource (@resources) {
1.586     raeburn  7831:             my $ressymb;
                   7832:             if (ref($resource)) {
                   7833:                 $ressymb = $resource->symb();
                   7834:             } else {
                   7835:                 $res_error = 1;
                   7836:                 last;
                   7837:             }
1.557     raeburn  7838:             if ((exists($grader_randomlists_by_symb{$ressymb})) ||
                   7839:                 (ref($grader_partids_by_symb{$ressymb}) ne 'ARRAY')) {
                   7840:                 my ($analysis,$parts) =
                   7841:                     &scantron_partids_tograde($resource,$env{'request.course.id'},$uname,$udom);
                   7842:                 $partids_by_symb{$ressymb} = $parts;
                   7843:             } else {
                   7844:                 $partids_by_symb{$ressymb} = $grader_partids_by_symb{$ressymb};
                   7845:             }
1.554     raeburn  7846:         }
                   7847: 
1.586     raeburn  7848:         if ($res_error) {
                   7849:             &scantron_add_delay(\@delayqueue,$line,
                   7850:                                 'An error occurred while grading student '.$uname,2);
                   7851:             next;
                   7852:         }
                   7853: 
1.330     albertel 7854: 	&Apache::lonxml::clear_problem_counter();
1.514     raeburn  7855:   	&Apache::lonnet::appenv($scan_record);
1.376     albertel 7856: 
                   7857: 	if (&scantron_clear_skip($scanlines,$scan_data,$i)) {
                   7858: 	    &scantron_putfile($scanlines,$scan_data);
                   7859: 	}
1.161     albertel 7860: 	
1.542     raeburn  7861:         my $scancode;
                   7862:         if ((exists($scan_record->{'scantron.CODE'})) &&
                   7863:             (&Apache::lonnet::validCODE($scan_record->{'scantron.CODE'}))) {
                   7864:             $scancode = $scan_record->{'scantron.CODE'};
                   7865:         } else {
                   7866:             $scancode = '';
                   7867:         }
                   7868: 
                   7869:         if (&grade_student_bubbles($r,$uname,$udom,$scan_record,$scancode,
1.554     raeburn  7870:                                    \@resources,\%partids_by_symb) eq 'ssi_error') {
1.542     raeburn  7871:             $ssi_error = 0; # So end of handler error message does not trigger.
                   7872:             $r->print("</form>");
                   7873:             &ssi_print_error($r);
                   7874:             $r->print(&show_grading_menu_form($symb));
                   7875:             &Apache::lonnet::remove_lock($lock);
                   7876:             return '';      # Why return ''?  Beats me.
                   7877:         }
1.513     foxr     7878: 
1.140     albertel 7879: 	$completedstudents{$uname}={'line'=>$line};
1.542     raeburn  7880:         if ($env{'form.verifyrecord'}) {
                   7881:             my $lastpos = $env{'form.scantron_maxbubble'}*$scantron_config{'Qlength'};
                   7882:             my $studentdata = substr($line,$scantron_config{'Qstart'}-1,$lastpos);
                   7883:             chomp($studentdata);
                   7884:             $studentdata =~ s/\r$//;
                   7885:             my $studentrecord = '';
                   7886:             my $counter = -1;
                   7887:             foreach my $resource (@resources) {
1.554     raeburn  7888:                 my $ressymb = $resource->symb();
1.542     raeburn  7889:                 ($counter,my $recording) =
                   7890:                     &verify_scantron_grading($resource,$udom,$uname,$env{'request.course.id'},
1.554     raeburn  7891:                                              $counter,$studentdata,$partids_by_symb{$ressymb},
1.542     raeburn  7892:                                              \%scantron_config,\%lettdig,$numletts);
                   7893:                 $studentrecord .= $recording;
                   7894:             }
                   7895:             if ($studentrecord ne $studentdata) {
1.554     raeburn  7896:                 &Apache::lonxml::clear_problem_counter();
                   7897:                 if (&grade_student_bubbles($r,$uname,$udom,$scan_record,$scancode,
                   7898:                                            \@resources,\%partids_by_symb) eq 'ssi_error') {
                   7899:                     $ssi_error = 0; # So end of handler error message does not trigger.
                   7900:                     $r->print("</form>");
                   7901:                     &ssi_print_error($r);
                   7902:                     $r->print(&show_grading_menu_form($symb));
                   7903:                     &Apache::lonnet::remove_lock($lock);
                   7904:                     delete($completedstudents{$uname});
                   7905:                     return '';
                   7906:                 }
1.542     raeburn  7907:                 $counter = -1;
                   7908:                 $studentrecord = '';
                   7909:                 foreach my $resource (@resources) {
1.554     raeburn  7910:                     my $ressymb = $resource->symb();
1.542     raeburn  7911:                     ($counter,my $recording) =
                   7912:                         &verify_scantron_grading($resource,$udom,$uname,$env{'request.course.id'},
1.554     raeburn  7913:                                                  $counter,$studentdata,$partids_by_symb{$ressymb},
1.542     raeburn  7914:                                                  \%scantron_config,\%lettdig,$numletts);
                   7915:                     $studentrecord .= $recording;
                   7916:                 }
                   7917:                 if ($studentrecord ne $studentdata) {
                   7918:                     $r->print('<p><span class="LC_error">');
                   7919:                     if ($scancode eq '') {
                   7920:                         $r->print(&mt('Mismatch grading bubble sheet for user: [_1] with ID: [_2].',
                   7921:                                   $uname.':'.$udom,$scan_record->{'scantron.ID'}));
                   7922:                     } else {
                   7923:                         $r->print(&mt('Mismatch grading bubble sheet for user: [_1] with ID: [_2] and CODE: [_3].',
                   7924:                                   $uname.':'.$udom,$scan_record->{'scantron.ID'},$scancode));
                   7925:                     }
                   7926:                     $r->print('</span><br />'.&Apache::loncommon::start_data_table()."\n".
                   7927:                               &Apache::loncommon::start_data_table_header_row()."\n".
                   7928:                               '<th>'.&mt('Source').'</th><th>'.&mt('Bubbled responses').'</th>'.
                   7929:                               &Apache::loncommon::end_data_table_header_row()."\n".
                   7930:                               &Apache::loncommon::start_data_table_row().
                   7931:                               '<td>'.&mt('Bubble Sheet').'</td>'.
                   7932:                               '<td><span class="LC_nobreak">'.$studentdata.'</span></td>'.
                   7933:                               &Apache::loncommon::end_data_table_row().
                   7934:                               &Apache::loncommon::start_data_table_row().
                   7935:                               '<td>Stored submissions</td>'.
                   7936:                               '<td><span class="LC_nobreak">'.$studentrecord.'</span></td>'."\n".
                   7937:                               &Apache::loncommon::end_data_table_row().
                   7938:                               &Apache::loncommon::end_data_table().'</p>');
                   7939:                 } else {
                   7940:                     $r->print('<br /><span class="LC_warning">'.
                   7941:                              &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 />'.
                   7942:                              &mt("As a consequence, this user's submission history records two tries.").
                   7943:                                  '</span><br />');
                   7944:                 }
                   7945:             }
                   7946:         }
1.543     raeburn  7947:         if (&Apache::loncommon::connection_aborted($r)) { last; }
1.140     albertel 7948:     } continue {
1.330     albertel 7949: 	&Apache::lonxml::clear_problem_counter();
1.552     raeburn  7950: 	&Apache::lonnet::delenv('scantron.');
1.82      albertel 7951:     }
1.140     albertel 7952:     &Apache::lonhtmlcommon::Close_PrgWin($r,\%prog_state);
1.520     www      7953:     &Apache::lonnet::remove_lock($lock);
1.172     albertel 7954: #    my $lasttime = &Time::HiRes::time()-$start;
                   7955: #    $r->print("<p>took $lasttime</p>");
1.140     albertel 7956: 
1.200     albertel 7957:     $r->print("</form>");
1.324     albertel 7958:     $r->print(&show_grading_menu_form($symb));
1.157     albertel 7959:     return '';
1.75      albertel 7960: }
1.157     albertel 7961: 
1.557     raeburn  7962: sub graders_resources_pass {
                   7963:     my ($resources,$grader_partids_by_symb,$grader_randomlists_by_symb) = @_;
                   7964:     if ((ref($resources) eq 'ARRAY') && (ref($grader_partids_by_symb)) && 
                   7965:         (ref($grader_randomlists_by_symb) eq 'HASH')) {
                   7966:         foreach my $resource (@{$resources}) {
                   7967:             my $ressymb = $resource->symb();
                   7968:             my ($analysis,$parts) =
                   7969:                 &scantron_partids_tograde($resource,$env{'request.course.id'},
                   7970:                                           $env{'user.name'},$env{'user.domain'},1);
                   7971:             $grader_partids_by_symb->{$ressymb} = $parts;
                   7972:             if (ref($analysis) eq 'HASH') {
                   7973:                 if (ref($analysis->{'parts_withrandomlist'}) eq 'ARRAY') {
                   7974:                     $grader_randomlists_by_symb->{$ressymb} =
                   7975:                         $analysis->{'parts_withrandomlist'};
                   7976:                 }
                   7977:             }
                   7978:         }
                   7979:     }
                   7980:     return;
                   7981: }
                   7982: 
1.542     raeburn  7983: sub grade_student_bubbles {
1.554     raeburn  7984:     my ($r,$uname,$udom,$scan_record,$scancode,$resources,$parts) = @_;
                   7985:     if (ref($resources) eq 'ARRAY') {
                   7986:         my $count = 0;
                   7987:         foreach my $resource (@{$resources}) {
                   7988:             my $ressymb = $resource->symb();
                   7989:             my %form = ('submitted'      => 'scantron',
                   7990:                         'grade_target'   => 'grade',
                   7991:                         'grade_username' => $uname,
                   7992:                         'grade_domain'   => $udom,
                   7993:                         'grade_courseid' => $env{'request.course.id'},
                   7994:                         'grade_symb'     => $ressymb,
                   7995:                         'CODE'           => $scancode
                   7996:                        );
                   7997:             if (ref($parts) eq 'HASH') {
                   7998:                 if (ref($parts->{$ressymb}) eq 'ARRAY') {
                   7999:                     foreach my $part (@{$parts->{$ressymb}}) {
                   8000:                         $form{'scantron_questnum_start.'.$part} =
                   8001:                             1+$env{'form.scantron.first_bubble_line.'.$count};
                   8002:                         $count++;
                   8003:                     }
                   8004:                 }
                   8005:             }
                   8006:             my $result=&ssi_with_retries($resource->src(),$ssi_retries,%form);
                   8007:             return 'ssi_error' if ($ssi_error);
                   8008:             last if (&Apache::loncommon::connection_aborted($r));
                   8009:         }
1.542     raeburn  8010:     }
                   8011:     return;
                   8012: }
                   8013: 
1.157     albertel 8014: sub scantron_upload_scantron_data {
                   8015:     my ($r)=@_;
1.565     raeburn  8016:     my $dom = $env{'request.role.domain'};
                   8017:     my $domdesc = &Apache::lonnet::domain($dom,'description');
                   8018:     $r->print(&Apache::loncommon::coursebrowser_javascript($dom));
1.157     albertel 8019:     my $select_link=&Apache::loncommon::selectcourse_link('rules','courseid',
1.181     albertel 8020: 							  'domainid',
1.565     raeburn  8021: 							  'coursename',$dom);
                   8022:     my $syllabuslink = '<a href="javascript:ToSyllabus();">'.&mt('Syllabus').'</a>'.
                   8023:                        ('&nbsp'x2).&mt('(shows course personnel)'); 
1.324     albertel 8024:     my $default_form_data=&defaultFormData(&get_symb($r,1));
1.579     raeburn  8025:     my $nofile_alert = &mt('Please use the browse button to select a file from your local directory.');
                   8026:     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 8027:     $r->print('
1.157     albertel 8028: <script type="text/javascript" language="javascript">
                   8029:     function checkUpload(formname) {
                   8030: 	if (formname.upfile.value == "") {
1.579     raeburn  8031: 	    alert("'.$nofile_alert.'");
1.157     albertel 8032: 	    return false;
                   8033: 	}
1.565     raeburn  8034:         if (formname.courseid.value == "") {
1.579     raeburn  8035:             alert("'.$nocourseid_alert.'");
1.565     raeburn  8036:             return false;
                   8037:         }
1.157     albertel 8038: 	formname.submit();
                   8039:     }
1.565     raeburn  8040: 
                   8041:     function ToSyllabus() {
                   8042:         var cdom = '."'$dom'".';
                   8043:         var cnum = document.rules.courseid.value;
                   8044:         if (cdom == "" || cdom == null) {
                   8045:             return;
                   8046:         }
                   8047:         if (cnum == "" || cnum == null) {
                   8048:            return;
                   8049:         }
                   8050:         syllwin=window.open("/public/"+cdom+"/"+cnum+"/syllabus","LONCAPASyllabus",
                   8051:                             "height=350,width=350,scrollbars=yes,menubar=no");
                   8052:         return;
                   8053:     }
                   8054: 
1.157     albertel 8055: </script>
                   8056: 
1.566     raeburn  8057: <h3>'.&mt('Send scanned bubblesheet data to a course').'</h3>
                   8058: 
1.492     albertel 8059: <form enctype="multipart/form-data" action="/adm/grades" name="rules" method="post">
1.565     raeburn  8060: '.$default_form_data.
                   8061:   &Apache::lonhtmlcommon::start_pick_box().
                   8062:   &Apache::lonhtmlcommon::row_title(&mt('Course ID')).
                   8063:   '<input name="courseid" type="text" size="30" />'.$select_link.
                   8064:   &Apache::lonhtmlcommon::row_closure().
                   8065:   &Apache::lonhtmlcommon::row_title(&mt('Course Name')).
                   8066:   '<input name="coursename" type="text" size="30" />'.$syllabuslink.
                   8067:   &Apache::lonhtmlcommon::row_closure().
                   8068:   &Apache::lonhtmlcommon::row_title(&mt('Domain')).
                   8069:   '<input name="domainid" type="hidden" />'.$domdesc.
                   8070:   &Apache::lonhtmlcommon::row_closure().
                   8071:   &Apache::lonhtmlcommon::row_title(&mt('File to upload')).
                   8072:   '<input type="file" name="upfile" size="50" />'.
                   8073:   &Apache::lonhtmlcommon::row_closure(1).
                   8074:   &Apache::lonhtmlcommon::end_pick_box().'<br />
                   8075: 
1.492     albertel 8076: <input name="command" value="scantronupload_save" type="hidden" />
1.589     bisitz   8077: <input type="button" onclick="javascript:checkUpload(this.form);" value="'.&mt('Upload Bubblesheet Data').'" />
1.157     albertel 8078: </form>
1.492     albertel 8079: ');
1.157     albertel 8080:     return '';
                   8081: }
                   8082: 
1.423     albertel 8083: 
1.157     albertel 8084: sub scantron_upload_scantron_data_save {
                   8085:     my($r)=@_;
1.324     albertel 8086:     my ($symb)=&get_symb($r,1);
1.182     albertel 8087:     my $doanotherupload=
                   8088: 	'<br /><form action="/adm/grades" method="post">'."\n".
                   8089: 	'<input type="hidden" name="command" value="scantronupload" />'."\n".
1.492     albertel 8090: 	'<input type="submit" name="submit" value="'.&mt('Do Another Upload').'" />'."\n".
1.182     albertel 8091: 	'</form>'."\n";
1.257     albertel 8092:     if (!&Apache::lonnet::allowed('usc',$env{'form.domainid'}) &&
1.162     albertel 8093: 	!&Apache::lonnet::allowed('usc',
1.257     albertel 8094: 			    $env{'form.domainid'}.'_'.$env{'form.courseid'})) {
1.575     www      8095: 	$r->print(&mt("You are not allowed to upload bubblesheet data to the requested course.")."<br />");
1.182     albertel 8096: 	if ($symb) {
1.324     albertel 8097: 	    $r->print(&show_grading_menu_form($symb));
1.182     albertel 8098: 	} else {
                   8099: 	    $r->print($doanotherupload);
                   8100: 	}
1.162     albertel 8101: 	return '';
                   8102:     }
1.257     albertel 8103:     my %coursedata=&Apache::lonnet::coursedescription($env{'form.domainid'}.'_'.$env{'form.courseid'});
1.568     raeburn  8104:     my $uploadedfile;
1.567     raeburn  8105:     $r->print('<h3>'.&mt("Uploading file to [_1]",$coursedata{'description'}).'</h3>');
1.257     albertel 8106:     if (length($env{'form.upfile'}) < 2) {
1.568     raeburn  8107:         $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 8108:     } else {
1.568     raeburn  8109:         my $result = 
                   8110:             &Apache::lonnet::userfileupload('upfile','','scantron','','','',
                   8111:                                             $env{'form.courseid'},$env{'form.domainid'});
                   8112: 	if ($result =~ m{^/uploaded/}) {
1.567     raeburn  8113: 	    $r->print(&mt('[_1]Success:[_2] Successfully uploaded [_3] bytes of data into location: [_4]',
                   8114:                           '<span class="LC_success">','</span>',(length($env{'form.upfile'})-1),
                   8115: 			  '<span class="LC_filename">'.$result.'</span>'));
1.568     raeburn  8116:             ($uploadedfile) = ($result =~ m{/([^/]+)$});
1.567     raeburn  8117:             $r->print(&validate_uploaded_scantron_file($env{'form.domainid'},
1.568     raeburn  8118:                                                        $env{'form.courseid'},$uploadedfile));
1.210     albertel 8119: 	} else {
1.567     raeburn  8120: 	    $r->print(&mt('[_1]Error:[_2] An error ([_3]) occurred when attempting to upload the file, [_4]',
                   8121:                           '<span class="LC_error">','</span>',$result,
1.568     raeburn  8122: 			  '<span class="LC_filename">'.&HTML::Entities::encode($env{'form.upfile.filename'},'<>&"').'</span>'));
1.183     albertel 8123: 	}
                   8124:     }
1.174     albertel 8125:     if ($symb) {
1.209     ng       8126: 	$r->print(&scantron_selectphase($r,$uploadedfile));
1.174     albertel 8127:     } else {
1.182     albertel 8128: 	$r->print($doanotherupload);
1.174     albertel 8129:     }
1.157     albertel 8130:     return '';
                   8131: }
                   8132: 
1.567     raeburn  8133: sub validate_uploaded_scantron_file {
                   8134:     my ($cdom,$cname,$fname) = @_;
                   8135:     my $scanlines=&Apache::lonnet::getfile('/uploaded/'.$cdom.'/'.$cname.'/'.$fname);
                   8136:     my @lines;
                   8137:     if ($scanlines ne '-1') {
                   8138:         @lines=split("\n",$scanlines,-1);
                   8139:     }
                   8140:     my $output;
                   8141:     if (@lines) {
                   8142:         my (%counts,$max_match_format);
                   8143:         my ($max_match_count,$max_match_pct) = (0,0);
                   8144:         my $classlist = &Apache::loncoursedata::get_classlist($cdom,$cname);
                   8145:         my %idmap = &username_to_idmap($classlist);
                   8146:         foreach my $key (keys(%idmap)) {
                   8147:             my $lckey = lc($key);
                   8148:             $idmap{$lckey} = $idmap{$key};
                   8149:         }
                   8150:         my %unique_formats;
                   8151:         my @formatlines = &get_scantronformat_file();
                   8152:         foreach my $line (@formatlines) {
                   8153:             chomp($line);
                   8154:             my @config = split(/:/,$line);
                   8155:             my $idstart = $config[5];
                   8156:             my $idlength = $config[6];
                   8157:             if (($idstart ne '') && ($idlength > 0)) {
                   8158:                 if (ref($unique_formats{$idstart.':'.$idlength}) eq 'ARRAY') {
                   8159:                     push(@{$unique_formats{$idstart.':'.$idlength}},$config[0].':'.$config[1]); 
                   8160:                 } else {
                   8161:                     $unique_formats{$idstart.':'.$idlength} = [$config[0].':'.$config[1]];
                   8162:                 }
                   8163:             }
                   8164:         }
                   8165:         foreach my $key (keys(%unique_formats)) {
                   8166:             my ($idstart,$idlength) = split(':',$key);
                   8167:             %{$counts{$key}} = (
                   8168:                                'found'   => 0,
                   8169:                                'total'   => 0,
                   8170:                               );
                   8171:             foreach my $line (@lines) {
                   8172:                 next if ($line =~ /^#/);
                   8173:                 next if ($line =~ /^[\s\cz]*$/);
                   8174:                 my $id = substr($line,$idstart-1,$idlength);
                   8175:                 $id = lc($id);
                   8176:                 if (exists($idmap{$id})) {
                   8177:                     $counts{$key}{'found'} ++;
                   8178:                 }
                   8179:                 $counts{$key}{'total'} ++;
                   8180:             }
                   8181:             if ($counts{$key}{'total'}) {
                   8182:                 my $percent_match = (100*$counts{$key}{'found'})/($counts{$key}{'total'});
                   8183:                 if (($max_match_format eq '') || ($percent_match > $max_match_pct)) {
                   8184:                     $max_match_pct = $percent_match;
                   8185:                     $max_match_format = $key;
                   8186:                     $max_match_count = $counts{$key}{'total'};
                   8187:                 }
                   8188:             }
                   8189:         }
                   8190:         if (ref($unique_formats{$max_match_format}) eq 'ARRAY') {
                   8191:             my $format_descs;
                   8192:             my $numwithformat = @{$unique_formats{$max_match_format}};
                   8193:             for (my $i=0; $i<$numwithformat; $i++) {
                   8194:                 my ($name,$desc) = split(':',$unique_formats{$max_match_format}[$i]);
                   8195:                 if ($i<$numwithformat-2) {
                   8196:                     $format_descs .= '"<i>'.$desc.'</i>", ';
                   8197:                 } elsif ($i==$numwithformat-2) {
                   8198:                     $format_descs .= '"<i>'.$desc.'</i>" '.&mt('and').' ';
                   8199:                 } elsif ($i==$numwithformat-1) {
                   8200:                     $format_descs .= '"<i>'.$desc.'</i>"';
                   8201:                 }
                   8202:             }
                   8203:             my $showpct = sprintf("%.0f",$max_match_pct).'%';
                   8204:             $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).
                   8205:                        '<br />'.&mt('A low percentage of matches results from one of the following:').'<ul>'.
                   8206:                        '<li>'.&mt('The file was uploaded to the wrong course').'</li>'.
                   8207:                        '<li>'.&mt('The data are not in the format expected for the domain: [_1]',
                   8208:                                   '<i>'.$cdom.'</i>').'</li>'.
                   8209:                        '<li>'.&mt('Students did not bubble their IDs, or mis-bubbled them').'</li>'.
                   8210:                        '<li>'.&mt('The course roster is not up to date').'</li>'.
                   8211:                        '</ul>';
                   8212:         }
                   8213:     } else {
                   8214:         $output = '<span class="LC_warning">'.&mt('Uploaded file contained no data').'</span>';
                   8215:     }
                   8216:     return $output;
                   8217: }
                   8218: 
1.202     albertel 8219: sub valid_file {
                   8220:     my ($requested_file)=@_;
                   8221:     foreach my $filename (sort(&scantron_filenames())) {
                   8222: 	if ($requested_file eq $filename) { return 1; }
                   8223:     }
                   8224:     return 0;
                   8225: }
                   8226: 
                   8227: sub scantron_download_scantron_data {
                   8228:     my ($r)=@_;
1.324     albertel 8229:     my $default_form_data=&defaultFormData(&get_symb($r,1));
1.257     albertel 8230:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   8231:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
                   8232:     my $file=$env{'form.scantron_selectfile'};
1.202     albertel 8233:     if (! &valid_file($file)) {
1.492     albertel 8234: 	$r->print('
1.202     albertel 8235: 	<p>
1.492     albertel 8236: 	    '.&mt('The requested file name was invalid.').'
1.202     albertel 8237:         </p>
1.492     albertel 8238: ');
1.324     albertel 8239: 	$r->print(&show_grading_menu_form(&get_symb($r,1)));
1.202     albertel 8240: 	return;
                   8241:     }
                   8242:     my $orig='/uploaded/'.$cdom.'/'.$cname.'/scantron_orig_'.$file;
                   8243:     my $corrected='/uploaded/'.$cdom.'/'.$cname.'/scantron_corrected_'.$file;
                   8244:     my $skipped='/uploaded/'.$cdom.'/'.$cname.'/scantron_skipped_'.$file;
                   8245:     &Apache::lonnet::allowuploaded('/adm/grades',$orig);
                   8246:     &Apache::lonnet::allowuploaded('/adm/grades',$corrected);
                   8247:     &Apache::lonnet::allowuploaded('/adm/grades',$skipped);
1.492     albertel 8248:     $r->print('
1.202     albertel 8249:     <p>
1.492     albertel 8250: 	'.&mt('[_1]Original[_2] file as uploaded by the scantron office.',
                   8251: 	      '<a href="'.$orig.'">','</a>').'
1.202     albertel 8252:     </p>
                   8253:     <p>
1.492     albertel 8254: 	'.&mt('[_1]Corrections[_2], a file of corrected records that were used in grading.',
                   8255: 	      '<a href="'.$corrected.'">','</a>').'
1.202     albertel 8256:     </p>
                   8257:     <p>
1.492     albertel 8258: 	'.&mt('[_1]Skipped[_2], a file of records that were skipped.',
                   8259: 	      '<a href="'.$skipped.'">','</a>').'
1.202     albertel 8260:     </p>
1.492     albertel 8261: ');
1.324     albertel 8262:     $r->print(&show_grading_menu_form(&get_symb($r,1)));
1.202     albertel 8263:     return '';
                   8264: }
1.157     albertel 8265: 
1.523     raeburn  8266: sub checkscantron_results {
                   8267:     my ($r) = @_;
                   8268:     my ($symb)=&get_symb($r);
                   8269:     if (!$symb) {return '';}
                   8270:     my $grading_menu_button=&show_grading_menu_form($symb);
                   8271:     my $cid = $env{'request.course.id'};
1.542     raeburn  8272:     my %lettdig = &letter_to_digits();
1.523     raeburn  8273:     my $numletts = scalar(keys(%lettdig));
                   8274:     my $cnum = $env{'course.'.$cid.'.num'};
                   8275:     my $cdom = $env{'course.'.$cid.'.domain'};
                   8276:     my (undef, undef, $sequence) = &Apache::lonnet::decode_symb($env{'form.selectpage'});
                   8277:     my %record;
                   8278:     my %scantron_config =
                   8279:         &Apache::grades::get_scantron_config($env{'form.scantron_format'});
                   8280:     my ($scanlines,$scan_data)=&Apache::grades::scantron_getfile();
                   8281:     my $classlist=&Apache::loncoursedata::get_classlist();
                   8282:     my %idmap=&Apache::grades::username_to_idmap($classlist);
                   8283:     my $navmap=Apache::lonnavmaps::navmap->new();
1.582     raeburn  8284:     unless (ref($navmap)) {
                   8285:         $r->print(&navmap_errormsg());
                   8286:         return '';
                   8287:     }
1.523     raeburn  8288:     my $map=$navmap->getResourceByUrl($sequence);
1.557     raeburn  8289:     my @resources=$navmap->retrieveResources($map,\&scantron_filter,1,0);
                   8290:     my (%grader_partids_by_symb,%grader_randomlists_by_symb);
                   8291:     &graders_resources_pass(\@resources,\%grader_partids_by_symb,                             \%grader_randomlists_by_symb);
                   8292: 
1.554     raeburn  8293:     my ($uname,$udom);
1.523     raeburn  8294:     my (%scandata,%lastname,%bylast);
                   8295:     $r->print('
                   8296: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="checkscantron">'."\n");
                   8297: 
                   8298:     my @delayqueue;
                   8299:     my %completedstudents;
                   8300: 
                   8301:     my $count=&Apache::grades::get_todo_count($scanlines,$scan_data);
1.581     www      8302:     my %prog_state=&Apache::lonhtmlcommon::Create_PrgWin($r,'Bubblesheet/Submissions Comparison Status',
                   8303:                                     'Progress of Bubblesheet Data/Submission Records Comparison',$count,
1.523     raeburn  8304:                                     'inline',undef,'checkscantron');
1.546     raeburn  8305:     my ($username,$domain,$started);
1.582     raeburn  8306:     my $nav_error;
                   8307:     &scantron_get_maxbubble(\$nav_error); # Need the bubble lines array to parse.
                   8308:     if ($nav_error) {
                   8309:         $r->print(&navmap_errormsg());
                   8310:         return '';
                   8311:     }
1.523     raeburn  8312: 
                   8313:     &Apache::lonhtmlcommon::Update_PrgWin($r,\%prog_state,
                   8314:                                           'Processing first student');
                   8315:     my $start=&Time::HiRes::time();
                   8316:     my $i=-1;
                   8317: 
                   8318:     while ($i<$scanlines->{'count'}) {
                   8319:         ($username,$domain,$uname)=('','','');
                   8320:         $i++;
                   8321:         my $line=&Apache::grades::scantron_get_line($scanlines,$scan_data,$i);
                   8322:         if ($line=~/^[\s\cz]*$/) { next; }
                   8323:         if ($started) {
                   8324:             &Apache::lonhtmlcommon::Increment_PrgWin($r,\%prog_state,
                   8325:                                                      'last student');
                   8326:         }
                   8327:         $started=1;
                   8328:         my $scan_record=
                   8329:             &Apache::grades::scantron_parse_scanline($line,$i,\%scantron_config,
                   8330:                                                      $scan_data);
                   8331:         unless ($uname=&Apache::grades::scantron_find_student($scan_record,$scan_data,
                   8332:                                                               \%idmap,$i)) {
                   8333:             &Apache::grades::scantron_add_delay(\@delayqueue,$line,
                   8334:                                 'Unable to find a student that matches',1);
                   8335:             next;
                   8336:         }
                   8337:         if (exists $completedstudents{$uname}) {
                   8338:             &Apache::grades::scantron_add_delay(\@delayqueue,$line,
                   8339:                                 'Student '.$uname.' has multiple sheets',2);
                   8340:             next;
                   8341:         }
                   8342:         my $pid = $scan_record->{'scantron.ID'};
                   8343:         $lastname{$pid} = $scan_record->{'scantron.LastName'};
                   8344:         push(@{$bylast{$lastname{$pid}}},$pid);
                   8345:         my $lastpos = $env{'form.scantron_maxbubble'}*$scantron_config{'Qlength'};
                   8346:         $scandata{$pid} = substr($line,$scantron_config{'Qstart'}-1,$lastpos);
                   8347:         chomp($scandata{$pid});
                   8348:         $scandata{$pid} =~ s/\r$//;
                   8349:         ($username,$domain)=split(/:/,$uname);
                   8350:         my $counter = -1;
                   8351:         foreach my $resource (@resources) {
1.557     raeburn  8352:             my $parts;
1.554     raeburn  8353:             my $ressymb = $resource->symb();
1.557     raeburn  8354:             if ((exists($grader_randomlists_by_symb{$ressymb})) ||
                   8355:                 (ref($grader_partids_by_symb{$ressymb}) ne 'ARRAY')) {
                   8356:                 (my $analysis,$parts) =
                   8357:                     &scantron_partids_tograde($resource,$env{'request.course.id'},$username,$domain);
                   8358:             } else {
                   8359:                 $parts = $grader_partids_by_symb{$ressymb};
                   8360:             }
1.542     raeburn  8361:             ($counter,my $recording) =
                   8362:                 &verify_scantron_grading($resource,$domain,$username,$cid,$counter,
1.554     raeburn  8363:                                          $scandata{$pid},$parts,
1.542     raeburn  8364:                                          \%scantron_config,\%lettdig,$numletts);
                   8365:             $record{$pid} .= $recording;
1.523     raeburn  8366:         }
                   8367:     }
                   8368:     &Apache::lonhtmlcommon::Close_PrgWin($r,\%prog_state);
                   8369:     $r->print('<br />');
                   8370:     my ($okstudents,$badstudents,$numstudents,$passed,$failed);
                   8371:     $passed = 0;
                   8372:     $failed = 0;
                   8373:     $numstudents = 0;
                   8374:     foreach my $last (sort(keys(%bylast))) {
                   8375:         if (ref($bylast{$last}) eq 'ARRAY') {
                   8376:             foreach my $pid (sort(@{$bylast{$last}})) {
                   8377:                 my $showscandata = $scandata{$pid};
                   8378:                 my $showrecord = $record{$pid};
                   8379:                 $showscandata =~ s/\s/&nbsp;/g;
                   8380:                 $showrecord =~ s/\s/&nbsp;/g;
                   8381:                 if ($scandata{$pid} eq $record{$pid}) {
                   8382:                     my $css_class = ($passed % 2)?'LC_odd_row':'LC_even_row';
                   8383:                     $okstudents .= '<tr class="'.$css_class.'">'.
1.581     www      8384: '<td>'.&mt('Bubblesheet').'</td><td>'.$showscandata.'</td><td rowspan="2">'.$last.'</td><td rowspan="2">'.$pid.'</td>'."\n".
1.523     raeburn  8385: '</tr>'."\n".
                   8386: '<tr class="'.$css_class.'">'."\n".
                   8387: '<td>Submissions</td><td>'.$showrecord.'</td></tr>'."\n";
                   8388:                     $passed ++;
                   8389:                 } else {
                   8390:                     my $css_class = ($failed % 2)?'LC_odd_row':'LC_even_row';
1.581     www      8391:                     $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  8392: '</tr>'."\n".
                   8393: '<tr class="'.$css_class.'">'."\n".
                   8394: '<td>Submissions</td><td><span class="LC_nobreak">'.$record{$pid}.'</span></td>'."\n".
                   8395: '</tr>'."\n";
                   8396:                     $failed ++;
                   8397:                 }
                   8398:                 $numstudents ++;
                   8399:             }
                   8400:         }
                   8401:     }
1.572     www      8402:     $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  8403:     $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>');
                   8404:     if ($passed) {
1.572     www      8405:         $r->print(&mt('Students with exact correspondence between bubblesheet data and submissions are as follows:').'<br /><br />');
1.523     raeburn  8406:         $r->print(&Apache::loncommon::start_data_table()."\n".
                   8407:                  &Apache::loncommon::start_data_table_header_row()."\n".
                   8408:                  '<th>'.&mt('Source').'</th><th>'.&mt('Bubble records').'</th><th>'.&mt('Name').'</th><th>'.&mt('ID').'</th>'.
                   8409:                  &Apache::loncommon::end_data_table_header_row()."\n".
                   8410:                  $okstudents."\n".
                   8411:                  &Apache::loncommon::end_data_table().'<br />');
                   8412:     }
                   8413:     if ($failed) {
1.572     www      8414:         $r->print(&mt('Students with differences between bubblesheet data and submissions are as follows:').'<br /><br />');
1.523     raeburn  8415:         $r->print(&Apache::loncommon::start_data_table()."\n".
                   8416:                  &Apache::loncommon::start_data_table_header_row()."\n".
                   8417:                  '<th>'.&mt('Source').'</th><th>'.&mt('Bubble records').'</th><th>'.&mt('Name').'</th><th>'.&mt('ID').'</th>'.
                   8418:                  &Apache::loncommon::end_data_table_header_row()."\n".
                   8419:                  $badstudents."\n".
                   8420:                  &Apache::loncommon::end_data_table()).'<br />'.
1.572     www      8421:                  &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  8422:     }
                   8423:     $r->print('</form><br />'.$grading_menu_button);
                   8424:     return;
                   8425: }
                   8426: 
1.542     raeburn  8427: sub verify_scantron_grading {
1.554     raeburn  8428:     my ($resource,$domain,$username,$cid,$counter,$scandata,$partids,
1.542     raeburn  8429:         $scantron_config,$lettdig,$numletts) = @_;
                   8430:     my ($record,%expected,%startpos);
                   8431:     return ($counter,$record) if (!ref($resource));
                   8432:     return ($counter,$record) if (!$resource->is_problem());
                   8433:     my $symb = $resource->symb();
1.554     raeburn  8434:     return ($counter,$record) if (ref($partids) ne 'ARRAY');
                   8435:     foreach my $part_id (@{$partids}) {
1.542     raeburn  8436:         $counter ++;
                   8437:         $expected{$part_id} = 0;
                   8438:         if ($env{"form.scantron.sub_bubblelines.$counter"}) {
                   8439:             my @sub_lines = split(/,/,$env{"form.scantron.sub_bubblelines.$counter"});
                   8440:             foreach my $item (@sub_lines) {
                   8441:                 $expected{$part_id} += $item;
                   8442:             }
                   8443:         } else {
                   8444:             $expected{$part_id} = $env{"form.scantron.bubblelines.$counter"};
                   8445:         }
                   8446:         $startpos{$part_id} = $env{"form.scantron.first_bubble_line.$counter"};
                   8447:     }
                   8448:     if ($symb) {
                   8449:         my %recorded;
                   8450:         my (%returnhash) = &Apache::lonnet::restore($symb,$cid,$domain,$username);
                   8451:         if ($returnhash{'version'}) {
                   8452:             my %lasthash=();
                   8453:             my $version;
                   8454:             for ($version=1;$version<=$returnhash{'version'};$version++) {
                   8455:                 foreach my $key (sort(split(/\:/,$returnhash{$version.':keys'}))) {
                   8456:                     $lasthash{$key}=$returnhash{$version.':'.$key};
                   8457:                 }
                   8458:             }
                   8459:             foreach my $key (keys(%lasthash)) {
                   8460:                 if ($key =~ /\.scantron$/) {
                   8461:                     my $value = &unescape($lasthash{$key});
                   8462:                     my ($part_id) = ($key =~ /^resource\.(.+)\.scantron$/);
                   8463:                     if ($value eq '') {
                   8464:                         for (my $i=0; $i<$expected{$part_id}; $i++) {
                   8465:                             for (my $j=0; $j<$scantron_config->{'length'}; $j++) {
                   8466:                                 $recorded{$part_id} .= $scantron_config->{'Qoff'};
                   8467:                             }
                   8468:                         }
                   8469:                     } else {
                   8470:                         my @tocheck;
                   8471:                         my @items = split(//,$value);
                   8472:                         if (($scantron_config->{'Qon'} eq 'letter') ||
                   8473:                             ($scantron_config->{'Qon'} eq 'number')) {
                   8474:                             if (@items < $expected{$part_id}) {
                   8475:                                 my $fragment = substr($scandata,$startpos{$part_id},$expected{$part_id});
                   8476:                                 my @singles = split(//,$fragment);
                   8477:                                 foreach my $pos (@singles) {
                   8478:                                     if ($pos eq ' ') {
                   8479:                                         push(@tocheck,$pos);
                   8480:                                     } else {
                   8481:                                         my $next = shift(@items);
                   8482:                                         push(@tocheck,$next);
                   8483:                                     }
                   8484:                                 }
                   8485:                             } else {
                   8486:                                 @tocheck = @items;
                   8487:                             }
                   8488:                             foreach my $letter (@tocheck) {
                   8489:                                 if ($scantron_config->{'Qon'} eq 'letter') {
                   8490:                                     if ($letter !~ /^[A-J]$/) {
                   8491:                                         $letter = $scantron_config->{'Qoff'};
                   8492:                                     }
                   8493:                                     $recorded{$part_id} .= $letter;
                   8494:                                 } elsif ($scantron_config->{'Qon'} eq 'number') {
                   8495:                                     my $digit;
                   8496:                                     if ($letter !~ /^[A-J]$/) {
                   8497:                                         $digit = $scantron_config->{'Qoff'};
                   8498:                                     } else {
                   8499:                                         $digit = $lettdig->{$letter};
                   8500:                                     }
                   8501:                                     $recorded{$part_id} .= $digit;
                   8502:                                 }
                   8503:                             }
                   8504:                         } else {
                   8505:                             @tocheck = @items;
                   8506:                             for (my $i=0; $i<$expected{$part_id}; $i++) {
                   8507:                                 my $curr_sub = shift(@tocheck);
                   8508:                                 my $digit;
                   8509:                                 if ($curr_sub =~ /^[A-J]$/) {
                   8510:                                     $digit = $lettdig->{$curr_sub}-1;
                   8511:                                 }
                   8512:                                 if ($curr_sub eq 'J') {
                   8513:                                     $digit += scalar($numletts);
                   8514:                                 }
                   8515:                                 for (my $j=0; $j<$scantron_config->{'Qlength'}; $j++) {
                   8516:                                     if ($j == $digit) {
                   8517:                                         $recorded{$part_id} .= $scantron_config->{'Qon'};
                   8518:                                     } else {
                   8519:                                         $recorded{$part_id} .= $scantron_config->{'Qoff'};
                   8520:                                     }
                   8521:                                 }
                   8522:                             }
                   8523:                         }
                   8524:                     }
                   8525:                 }
                   8526:             }
                   8527:         }
1.554     raeburn  8528:         foreach my $part_id (@{$partids}) {
1.542     raeburn  8529:             if ($recorded{$part_id} eq '') {
                   8530:                 for (my $i=0; $i<$expected{$part_id}; $i++) {
                   8531:                     for (my $j=0; $j<$scantron_config->{'Qlength'}; $j++) {
                   8532:                         $recorded{$part_id} .= $scantron_config->{'Qoff'};
                   8533:                     }
                   8534:                 }
                   8535:             }
                   8536:             $record .= $recorded{$part_id};
                   8537:         }
                   8538:     }
                   8539:     return ($counter,$record);
                   8540: }
                   8541: 
                   8542: sub letter_to_digits { 
                   8543:     my %lettdig = (
                   8544:                     A => 1,
                   8545:                     B => 2,
                   8546:                     C => 3,
                   8547:                     D => 4,
                   8548:                     E => 5,
                   8549:                     F => 6,
                   8550:                     G => 7,
                   8551:                     H => 8,
                   8552:                     I => 9,
                   8553:                     J => 0,
                   8554:                   );
                   8555:     return %lettdig;
                   8556: }
                   8557: 
1.423     albertel 8558: 
1.75      albertel 8559: #-------- end of section for handling grading scantron forms -------
                   8560: #
                   8561: #-------------------------------------------------------------------
                   8562: 
1.72      ng       8563: #-------------------------- Menu interface -------------------------
                   8564: #
                   8565: #--- Show a Grading Menu button - Calls the next routine ---
                   8566: sub show_grading_menu_form {
1.324     albertel 8567:     my ($symb)=@_;
1.125     ng       8568:     my $result.='<br /><form action="/adm/grades" method="post">'."\n".
1.418     albertel 8569: 	'<input type="hidden" name="symb" value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
1.257     albertel 8570: 	'<input type="hidden" name="saveState"  value="'.$env{'form.saveState'}.'" />'."\n".
1.72      ng       8571: 	'<input type="hidden" name="command" value="gradingmenu" />'."\n".
1.478     albertel 8572: 	'<input type="submit" name="submit" value="'.&mt('Grading Menu').'" />'."\n".
1.72      ng       8573: 	'</form>'."\n";
                   8574:     return $result;
                   8575: }
                   8576: 
1.77      ng       8577: # -- Retrieve choices for grading form
                   8578: sub savedState {
                   8579:     my %savedState = ();
1.257     albertel 8580:     if ($env{'form.saveState'}) {
                   8581: 	foreach (split(/:/,$env{'form.saveState'})) {
1.77      ng       8582: 	    my ($key,$value) = split(/=/,$_,2);
                   8583: 	    $savedState{$key} = $value;
                   8584: 	}
                   8585:     }
                   8586:     return \%savedState;
                   8587: }
1.76      ng       8588: 
1.443     banghart 8589: sub grading_menu {
                   8590:     my ($request) = @_;
                   8591:     my ($symb)=&get_symb($request);
                   8592:     if (!$symb) {return '';}
                   8593:     my $probTitle = &Apache::lonnet::gettitle($symb);
                   8594:     my ($table,undef,$hdgrade) = &showResourceInfo($symb,$probTitle);
                   8595: 
1.444     banghart 8596:     $request->print($table);
1.443     banghart 8597:     my %fields = ('symb'=>&Apache::lonenc::check_encrypt($symb),
                   8598:                   'handgrade'=>$hdgrade,
                   8599:                   'probTitle'=>$probTitle,
                   8600:                   'command'=>'submit_options',
                   8601:                   'saveState'=>"",
                   8602:                   'gradingMenu'=>1,
                   8603:                   'showgrading'=>"yes");
1.538     schulted 8604:     
                   8605:     my $url1 = &Apache::lonhtmlcommon::build_url('grades/',\%fields);
                   8606:     
1.443     banghart 8607:     $fields{'command'} = 'csvform';
1.538     schulted 8608:     my $url2 = &Apache::lonhtmlcommon::build_url('grades/',\%fields);
                   8609:     
1.443     banghart 8610:     $fields{'command'} = 'processclicker';
1.538     schulted 8611:     my $url3 = &Apache::lonhtmlcommon::build_url('grades/',\%fields);
                   8612:     
1.443     banghart 8613:     $fields{'command'} = 'scantron_selectphase';
1.538     schulted 8614:     my $url4 = &Apache::lonhtmlcommon::build_url('grades/',\%fields);
                   8615:     
                   8616:     my @menu = ({	categorytitle=>'Course Grading',
                   8617:             items =>[
                   8618:                         {	linktext => 'Manual Grading/View Submissions',
                   8619:                     		url => $url1,
                   8620:                     		permission => 'F',
                   8621:                     		icon => 'edit-find-replace.png',
                   8622:                     		linktitle => 'Start the process of hand grading submissions.'
                   8623:                         },
                   8624:                 	    {	linktext => 'Upload Scores',
                   8625:                     		url => $url2,
                   8626:                     		permission => 'F',
                   8627:                     		icon => 'uploadscores.png',
                   8628:                     		linktitle => 'Specify a file containing the class scores for current resource.'
                   8629:                 	    },
                   8630:                 	    {	linktext => 'Process Clicker',
                   8631:                     		url => $url3,
                   8632:                     		permission => 'F',
                   8633:                     		icon => 'addClickerInfoFile.png',
                   8634:                     		linktitle => 'Specify a file containing the clicker information for this resource.'
                   8635:                 	    },
1.587     raeburn  8636:                 	    {	linktext => 'Grade/Manage/Review Bubblesheets',
1.538     schulted 8637:                     		url => $url4,
                   8638:                     		permission => 'F',
                   8639:                     		icon => 'stat.png',
                   8640:                     		linktitle => 'Grade scantron exams, upload/download scantron data files, and review previously graded scantron exams.'
                   8641:                 	    }
                   8642:                     ]
                   8643:             });
                   8644: 
                   8645:     #$fields{'command'} = 'verify';
                   8646:     #$url = &Apache::lonhtmlcommon::build_url('grades/',\%fields);
1.443     banghart 8647:     #
                   8648:     # Create the menu
                   8649:     my $Str;
1.444     banghart 8650:     # $Str .= '<h2>'.&mt('Please select a grading task').'</h2>';
1.445     banghart 8651:     $Str .= '<form method="post" action="" name="gradingMenu">';
                   8652:     $Str .= '<input type="hidden" name="command" value="" />'.
                   8653:     	'<input type="hidden" name="symb"        value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
                   8654: 	'<input type="hidden" name="handgrade"   value="'.$hdgrade.'" />'."\n".
1.476     albertel 8655: 	'<input type="hidden" name="probTitle"   value="'.$probTitle.'" />'."\n".
1.445     banghart 8656: 	'<input type="hidden" name="saveState"   value="" />'."\n".
                   8657: 	'<input type="hidden" name="gradingMenu" value="1" />'."\n".
                   8658: 	'<input type="hidden" name="showgrading" value="yes" />'."\n";
                   8659: 
1.538     schulted 8660:     $Str .= Apache::lonhtmlcommon::generate_menu(@menu);
                   8661:     #$menudata->{'jscript'}
1.584     bisitz   8662:     $Str .='<hr /><input type="button" value="'.&mt('Verify Receipt No.').'" '.
1.589     bisitz   8663:         ' onclick="javascript:checkChoice(document.forms.gradingMenu,\'5\',\'verify\')" '.
1.538     schulted 8664:         ' /> '.
                   8665:         &Apache::lonnet::recprefix($env{'request.course.id'}).
1.589     bisitz   8666:         '-<input type="text" name="receipt" size="4" onchange="javascript:checkReceiptNo(this.form,\'OK\')" />';
1.538     schulted 8667: 
1.444     banghart 8668:     $Str .="</form>\n";
1.539     riegler  8669:     my $receiptalert = &mt("Please enter a receipt number given by a student in the receipt box.");
1.443     banghart 8670:     $request->print(<<GRADINGMENUJS);
                   8671: <script type="text/javascript" language="javascript">
                   8672:     function checkChoice(formname,val,cmdx) {
                   8673: 	if (val <= 2) {
                   8674: 	    var cmd = radioSelection(formname.radioChoice);
                   8675: 	    var cmdsave = cmd;
                   8676: 	} else {
                   8677: 	    cmd = cmdx;
                   8678: 	    cmdsave = 'submission';
                   8679: 	}
                   8680: 	formname.command.value = cmd;
                   8681: 	if (val < 5) formname.submit();
                   8682: 	if (val == 5) {
1.458     banghart 8683: 	    if (!checkReceiptNo(formname,'notOK')) { 
                   8684: 	        return false;
                   8685: 	    } else {
                   8686: 	        formname.submit();
                   8687: 	    }
1.445     banghart 8688: 	}
                   8689:     }
1.443     banghart 8690: 
                   8691:     function checkReceiptNo(formname,nospace) {
                   8692: 	var receiptNo = formname.receipt.value;
                   8693: 	var checkOpt = false;
                   8694: 	if (nospace == "OK" && isNaN(receiptNo)) {checkOpt = true;}
                   8695: 	if (nospace == "notOK" && (isNaN(receiptNo) || receiptNo == "")) {checkOpt = true;}
                   8696: 	if (checkOpt) {
1.539     riegler  8697: 	    alert("$receiptalert");
1.443     banghart 8698: 	    formname.receipt.value = "";
                   8699: 	    formname.receipt.focus();
                   8700: 	    return false;
                   8701: 	}
                   8702: 	return true;
                   8703:     }
                   8704: </script>
                   8705: GRADINGMENUJS
                   8706:     &commonJSfunctions($request);
                   8707:     return $Str;    
                   8708: }
                   8709: 
                   8710: 
                   8711: #--- Displays the submissions first page -------
                   8712: sub submit_options {
1.72      ng       8713:     my ($request) = @_;
1.324     albertel 8714:     my ($symb)=&get_symb($request);
1.72      ng       8715:     if (!$symb) {return '';}
1.76      ng       8716:     my $probTitle = &Apache::lonnet::gettitle($symb);
1.72      ng       8717: 
1.539     riegler  8718:     my $receiptalert = &mt("Please enter a receipt number given by a student in the receipt box."); 
1.72      ng       8719:     $request->print(<<GRADINGMENUJS);
                   8720: <script type="text/javascript" language="javascript">
1.116     ng       8721:     function checkChoice(formname,val,cmdx) {
                   8722: 	if (val <= 2) {
                   8723: 	    var cmd = radioSelection(formname.radioChoice);
1.118     ng       8724: 	    var cmdsave = cmd;
1.116     ng       8725: 	} else {
                   8726: 	    cmd = cmdx;
1.118     ng       8727: 	    cmdsave = 'submission';
1.116     ng       8728: 	}
                   8729: 	formname.command.value = cmd;
1.118     ng       8730: 	formname.saveState.value = "saveCmd="+cmdsave+":saveSec="+pullDownSelection(formname.section)+
1.145     albertel 8731: 	    ":saveSub="+pullDownSelection(formname.submitonly)+":saveStatus="+pullDownSelection(formname.Status);
1.116     ng       8732: 	if (val < 5) formname.submit();
                   8733: 	if (val == 5) {
1.72      ng       8734: 	    if (!checkReceiptNo(formname,'notOK')) { return false;}
                   8735: 	    formname.submit();
                   8736: 	}
1.238     albertel 8737: 	if (val < 7) formname.submit();
1.72      ng       8738:     }
                   8739: 
                   8740:     function checkReceiptNo(formname,nospace) {
                   8741: 	var receiptNo = formname.receipt.value;
                   8742: 	var checkOpt = false;
                   8743: 	if (nospace == "OK" && isNaN(receiptNo)) {checkOpt = true;}
                   8744: 	if (nospace == "notOK" && (isNaN(receiptNo) || receiptNo == "")) {checkOpt = true;}
                   8745: 	if (checkOpt) {
1.539     riegler  8746: 	    alert("$receiptalert");
1.72      ng       8747: 	    formname.receipt.value = "";
                   8748: 	    formname.receipt.focus();
                   8749: 	    return false;
                   8750: 	}
                   8751: 	return true;
                   8752:     }
                   8753: </script>
                   8754: GRADINGMENUJS
1.118     ng       8755:     &commonJSfunctions($request);
1.324     albertel 8756:     my ($table,undef,$hdgrade) = &showResourceInfo($symb,$probTitle);
1.473     albertel 8757:     my $result;
1.76      ng       8758:     my (undef,$sections) = &getclasslist('all','0');
1.77      ng       8759:     my $savedState = &savedState();
1.118     ng       8760:     my $saveCmd = ($$savedState{'saveCmd'} eq '' ? 'submission' : $$savedState{'saveCmd'});
1.77      ng       8761:     my $saveSec = ($$savedState{'saveSec'} eq '' ? 'all' : $$savedState{'saveSec'});
1.118     ng       8762:     my $saveSub = ($$savedState{'saveSub'} eq '' ? 'all' : $$savedState{'saveSub'});
1.77      ng       8763:     my $saveStatus = ($$savedState{'saveStatus'} eq '' ? 'Active' : $$savedState{'saveStatus'});
1.72      ng       8764: 
1.533     bisitz   8765:     # Preselect sections
                   8766:     my $selsec="";
                   8767:     if (ref($sections)) {
                   8768:         foreach my $section (sort(@$sections)) {
                   8769:             $selsec.='<option value="'.$section.'" '.
                   8770:                 ($saveSec eq $section ? 'selected="selected"':'').'>'.$section.'</option>'."\n";
                   8771:         }
                   8772:     }
                   8773: 
1.72      ng       8774:     $result.='<form action="/adm/grades" method="post" name="gradingMenu">'."\n".
1.418     albertel 8775: 	'<input type="hidden" name="symb"        value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
1.72      ng       8776: 	'<input type="hidden" name="handgrade"   value="'.$hdgrade.'" />'."\n".
                   8777: 	'<input type="hidden" name="probTitle"   value="'.$probTitle.'" />'."\n".
1.116     ng       8778: 	'<input type="hidden" name="command"     value="" />'."\n".
1.77      ng       8779: 	'<input type="hidden" name="saveState"   value="" />'."\n".
1.124     ng       8780: 	'<input type="hidden" name="gradingMenu" value="1" />'."\n".
1.72      ng       8781: 	'<input type="hidden" name="showgrading" value="yes" />'."\n";
                   8782: 
1.472     albertel 8783:     $result.='
1.533     bisitz   8784: <h2>
                   8785:   '.&mt('Grade Current Resource').'
                   8786: </h2>
                   8787: <div>
                   8788:   '.$table.'
                   8789: </div>
                   8790: 
1.537     harmsja  8791: <div class="LC_columnSection">
                   8792:   
1.533     bisitz   8793:     <fieldset>
                   8794:       <legend>
                   8795:        '.&mt('Sections').'
                   8796:       </legend>
                   8797:       <select name="section" multiple="multiple" size="5">'."\n";
                   8798:     $result.= $selsec;
1.401     albertel 8799:     $result.= '<option value="all" '.($saveSec eq 'all' ? 'selected="selected"' : ''). '>all</option></select> &nbsp; ';
1.472     albertel 8800:     $result.='
1.533     bisitz   8801:     </fieldset>
1.537     harmsja  8802:   
1.533     bisitz   8803:     <fieldset>
                   8804:       <legend>
                   8805:         '.&mt('Groups').'
                   8806:       </legend>
                   8807:       '.&Apache::lonstatistics::GroupSelect('group','multiple',5).'
                   8808:     </fieldset>
1.537     harmsja  8809:   
1.533     bisitz   8810:     <fieldset>
                   8811:       <legend>
                   8812:         '.&mt('Access Status').'
                   8813:       </legend>
                   8814:       '.&Apache::lonhtmlcommon::StatusOptions($saveStatus,undef,5,undef,'mult').'
                   8815:     </fieldset>
1.537     harmsja  8816:   
1.533     bisitz   8817:     <fieldset>
                   8818:       <legend>
                   8819:         '.&mt('Submission Status').'
                   8820:       </legend>
                   8821:       <select name="submitonly" size="5">
1.473     albertel 8822: 	         <option value="yes" '.      ($saveSub eq 'yes'       ? 'selected="selected"' : '').'>'.&mt('with submissions').'</option>
                   8823: 	         <option value="queued" '.   ($saveSub eq 'queued'    ? 'selected="selected"' : '').'>'.&mt('in grading queue').'</option>
                   8824: 	         <option value="graded" '.   ($saveSub eq 'graded'    ? 'selected="selected"' : '').'>'.&mt('with ungraded submissions').'</option>
                   8825: 	         <option value="incorrect" '.($saveSub eq 'incorrect' ? 'selected="selected"' : '').'>'.&mt('with incorrect submissions').'</option>
                   8826:                  <option value="all" '.      ($saveSub eq 'all'       ? 'selected="selected"' : '').'>'.&mt('with any status').'</option>
1.533     bisitz   8827:       </select>
                   8828:     </fieldset>
1.537     harmsja  8829:   
1.533     bisitz   8830: </div>
                   8831: 
                   8832: <br />
                   8833:           <div>
                   8834:             <div>
1.473     albertel 8835:               <label>
                   8836:                 <input type="radio" name="radioChoice" value="submission" '.
                   8837:                   ($saveCmd eq 'submission' ? 'checked="checked"' : '').' /> '.
                   8838:              &mt('Select individual students to grade and view submissions.').'
                   8839: 	      </label> 
                   8840:             </div>
1.533     bisitz   8841:             <div>
1.473     albertel 8842: 	      <label>
                   8843:                 <input type="radio" name="radioChoice" value="viewgrades" '.
                   8844:                   ($saveCmd eq 'viewgrades' ? 'checked="checked"' : '').' /> '.
                   8845:                     &mt('Grade all selected students in a grading table.').'
                   8846:               </label>
                   8847:             </div>
1.533     bisitz   8848:             <div>
1.589     bisitz   8849: 	      <input type="button" onclick="javascript:checkChoice(this.form,\'2\');" value="'.&mt('Next').' &rarr;" />
1.473     albertel 8850:             </div>
1.472     albertel 8851:           </div>
1.533     bisitz   8852: 
                   8853: 
1.473     albertel 8854:         <h2>
                   8855:          '.&mt('Grade Complete Folder for One Student').'
                   8856:         </h2>
1.533     bisitz   8857:         <div>
                   8858:             <div>
1.473     albertel 8859:               <label>
                   8860:                 <input type="radio" name="radioChoice" value="pickStudentPage" '.
                   8861: 	  ($saveCmd eq 'pickStudentPage' ? 'checked="checked"' : '').' /> '.
                   8862:   &mt('The <b>complete</b> page/sequence/folder: For one student').'
                   8863:               </label>
                   8864:             </div>
1.533     bisitz   8865:             <div>
1.589     bisitz   8866: 	      <input type="button" onclick="javascript:checkChoice(this.form,\'2\');" value="'.&mt('Next').' &rarr;" />
1.473     albertel 8867:             </div>
1.472     albertel 8868:         </div>
                   8869:   </form>';
1.499     albertel 8870:     $result .= &show_grading_menu_form($symb);
1.44      ng       8871:     return $result;
1.2       albertel 8872: }
                   8873: 
1.285     albertel 8874: sub reset_perm {
                   8875:     undef(%perm);
                   8876: }
                   8877: 
                   8878: sub init_perm {
                   8879:     &reset_perm();
1.300     albertel 8880:     foreach my $test_perm ('vgr','mgr','opa') {
                   8881: 
                   8882: 	my $scope = $env{'request.course.id'};
                   8883: 	if (!($perm{$test_perm}=&Apache::lonnet::allowed($test_perm,$scope))) {
                   8884: 
                   8885: 	    $scope .= '/'.$env{'request.course.sec'};
                   8886: 	    if ( $perm{$test_perm}=
                   8887: 		 &Apache::lonnet::allowed($test_perm,$scope)) {
                   8888: 		$perm{$test_perm.'_section'}=$env{'request.course.sec'};
                   8889: 	    } else {
                   8890: 		delete($perm{$test_perm});
                   8891: 	    }
1.285     albertel 8892: 	}
                   8893:     }
                   8894: }
                   8895: 
1.400     www      8896: sub gather_clicker_ids {
1.408     albertel 8897:     my %clicker_ids;
1.400     www      8898: 
                   8899:     my $classlist = &Apache::loncoursedata::get_classlist();
                   8900: 
                   8901:     # Set up a couple variables.
1.407     albertel 8902:     my $username_idx = &Apache::loncoursedata::CL_SNAME();
                   8903:     my $domain_idx   = &Apache::loncoursedata::CL_SDOM();
1.438     www      8904:     my $status_idx   = &Apache::loncoursedata::CL_STATUS();
1.400     www      8905: 
1.407     albertel 8906:     foreach my $student (keys(%$classlist)) {
1.438     www      8907:         if ($classlist->{$student}->[$status_idx] ne 'Active') { next; }
1.407     albertel 8908:         my $username = $classlist->{$student}->[$username_idx];
                   8909:         my $domain   = $classlist->{$student}->[$domain_idx];
1.400     www      8910:         my $clickers =
1.408     albertel 8911: 	    (&Apache::lonnet::userenvironment($domain,$username,'clickers'))[1];
1.400     www      8912:         foreach my $id (split(/\,/,$clickers)) {
1.414     www      8913:             $id=~s/^[\#0]+//;
1.421     www      8914:             $id=~s/[\-\:]//g;
1.407     albertel 8915:             if (exists($clicker_ids{$id})) {
1.408     albertel 8916: 		$clicker_ids{$id}.=','.$username.':'.$domain;
1.400     www      8917:             } else {
1.408     albertel 8918: 		$clicker_ids{$id}=$username.':'.$domain;
1.400     www      8919:             }
                   8920:         }
                   8921:     }
1.407     albertel 8922:     return %clicker_ids;
1.400     www      8923: }
                   8924: 
1.402     www      8925: sub gather_adv_clicker_ids {
1.408     albertel 8926:     my %clicker_ids;
1.402     www      8927:     my $cnum=$env{'course.'.$env{'request.course.id'}.'.num'};
                   8928:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
                   8929:     my %coursepersonnel=&Apache::lonnet::get_course_adv_roles($cdom.'/'.$cnum);
1.409     albertel 8930:     foreach my $element (sort(keys(%coursepersonnel))) {
1.402     www      8931:         foreach my $person (split(/\,/,$coursepersonnel{$element})) {
                   8932:             my ($puname,$pudom)=split(/\:/,$person);
                   8933:             my $clickers =
1.408     albertel 8934: 		(&Apache::lonnet::userenvironment($pudom,$puname,'clickers'))[1];
1.405     www      8935:             foreach my $id (split(/\,/,$clickers)) {
1.414     www      8936: 		$id=~s/^[\#0]+//;
1.421     www      8937:                 $id=~s/[\-\:]//g;
1.408     albertel 8938: 		if (exists($clicker_ids{$id})) {
                   8939: 		    $clicker_ids{$id}.=','.$puname.':'.$pudom;
                   8940: 		} else {
                   8941: 		    $clicker_ids{$id}=$puname.':'.$pudom;
                   8942: 		}
1.405     www      8943:             }
1.402     www      8944:         }
                   8945:     }
1.407     albertel 8946:     return %clicker_ids;
1.402     www      8947: }
                   8948: 
1.413     www      8949: sub clicker_grading_parameters {
                   8950:     return ('gradingmechanism' => 'scalar',
                   8951:             'upfiletype' => 'scalar',
                   8952:             'specificid' => 'scalar',
                   8953:             'pcorrect' => 'scalar',
                   8954:             'pincorrect' => 'scalar');
                   8955: }
                   8956: 
1.400     www      8957: sub process_clicker {
                   8958:     my ($r)=@_;
                   8959:     my ($symb)=&get_symb($r);
                   8960:     if (!$symb) {return '';}
                   8961:     my $result=&checkforfile_js();
                   8962:     $env{'form.probTitle'} = &Apache::lonnet::gettitle($symb);
                   8963:     my ($table) = &showResourceInfo($symb,$env{'form.probTitle'});
                   8964:     $result.=$table;
                   8965:     $result.='<br /><table width="100%" border="0"><tr><td bgcolor="#777777">'."\n";
                   8966:     $result.='<table width="100%" border="0"><tr bgcolor="#e6ffff"><td>'."\n";
1.538     schulted 8967:     $result.='&nbsp;<b>'.&mt('Specify a file containing the clicker information for this resource.').
                   8968:         '</b></td></tr>'."\n";
1.400     www      8969:     $result.='<tr bgcolor=#ffffe6><td>'."\n";
1.413     www      8970: # Attempt to restore parameters from last session, set defaults if not present
                   8971:     my %Saveable_Parameters=&clicker_grading_parameters();
                   8972:     &Apache::loncommon::restore_course_settings('grades_clicker',
                   8973:                                                  \%Saveable_Parameters);
                   8974:     if (!$env{'form.pcorrect'}) { $env{'form.pcorrect'}=100; }
                   8975:     if (!$env{'form.pincorrect'}) { $env{'form.pincorrect'}=100; }
                   8976:     if (!$env{'form.gradingmechanism'}) { $env{'form.gradingmechanism'}='attendance'; }
                   8977:     if (!$env{'form.upfiletype'}) { $env{'form.upfiletype'}='iclicker'; }
                   8978: 
                   8979:     my %checked;
1.521     www      8980:     foreach my $gradingmechanism ('attendance','personnel','specific','given') {
1.413     www      8981:        if ($env{'form.gradingmechanism'} eq $gradingmechanism) {
1.569     bisitz   8982:           $checked{$gradingmechanism}=' checked="checked"';
1.413     www      8983:        }
                   8984:     }
                   8985: 
1.400     www      8986:     my $upload=&mt("Upload File");
                   8987:     my $type=&mt("Type");
1.402     www      8988:     my $attendance=&mt("Award points just for participation");
                   8989:     my $personnel=&mt("Correctness determined from response by course personnel");
1.414     www      8990:     my $specific=&mt("Correctness determined from response with clicker ID(s)"); 
1.521     www      8991:     my $given=&mt("Correctness determined from given list of answers").' '.
                   8992:               '<font size="-2"><tt>('.&mt("Provide comma-separated list. Use '*' for any answer correct, '-' for skip").')</tt></font>';
1.402     www      8993:     my $pcorrect=&mt("Percentage points for correct solution");
                   8994:     my $pincorrect=&mt("Percentage points for incorrect solution");
1.413     www      8995:     my $selectform=&Apache::loncommon::select_form($env{'form.upfiletype'},'upfiletype',
1.596.2.1  raeburn  8996:                                                    {'iclicker' => 'i>clicker',
                   8997:                                                     'interwrite' => 'interwrite PRS'});
1.418     albertel 8998:     $symb = &Apache::lonenc::check_encrypt($symb);
1.400     www      8999:     $result.=<<ENDUPFORM;
1.402     www      9000: <script type="text/javascript">
                   9001: function sanitycheck() {
                   9002: // Accept only integer percentages
                   9003:    document.forms.gradesupload.pcorrect.value=Math.round(document.forms.gradesupload.pcorrect.value);
                   9004:    document.forms.gradesupload.pincorrect.value=Math.round(document.forms.gradesupload.pincorrect.value);
                   9005: // Find out grading choice
                   9006:    for (i=0; i<document.forms.gradesupload.gradingmechanism.length; i++) {
                   9007:       if (document.forms.gradesupload.gradingmechanism[i].checked) {
                   9008:          gradingchoice=document.forms.gradesupload.gradingmechanism[i].value;
                   9009:       }
                   9010:    }
                   9011: // By default, new choice equals user selection
                   9012:    newgradingchoice=gradingchoice;
                   9013: // Not good to give more points for false answers than correct ones
                   9014:    if (Math.round(document.forms.gradesupload.pcorrect.value)<Math.round(document.forms.gradesupload.pincorrect.value)) {
                   9015:       document.forms.gradesupload.pcorrect.value=document.forms.gradesupload.pincorrect.value;
                   9016:    }
                   9017: // If new choice is attendance only, and old choice was correctness-based, restore defaults
                   9018:    if ((gradingchoice=='attendance') && (document.forms.gradesupload.waschecked.value!='attendance')) {
                   9019:       document.forms.gradesupload.pcorrect.value=100;
                   9020:       document.forms.gradesupload.pincorrect.value=100;
                   9021:    }
                   9022: // If the values are different, cannot be attendance only
                   9023:    if ((Math.round(document.forms.gradesupload.pcorrect.value)!=Math.round(document.forms.gradesupload.pincorrect.value)) &&
                   9024:        (gradingchoice=='attendance')) {
                   9025:        newgradingchoice='personnel';
                   9026:    }
                   9027: // Change grading choice to new one
                   9028:    for (i=0; i<document.forms.gradesupload.gradingmechanism.length; i++) {
                   9029:       if (document.forms.gradesupload.gradingmechanism[i].value==newgradingchoice) {
                   9030:          document.forms.gradesupload.gradingmechanism[i].checked=true;
                   9031:       } else {
                   9032:          document.forms.gradesupload.gradingmechanism[i].checked=false;
                   9033:       }
                   9034:    }
                   9035: // Remember the old state
                   9036:    document.forms.gradesupload.waschecked.value=newgradingchoice;
                   9037: }
                   9038: </script>
1.400     www      9039: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="gradesupload">
                   9040: <input type="hidden" name="symb" value="$symb" />
                   9041: <input type="hidden" name="command" value="processclickerfile" />
                   9042: <input type="hidden" name="probTitle" value="$env{'form.probTitle'}" />
                   9043: <input type="hidden" name="saveState"  value="$env{'form.saveState'}" />
                   9044: <input type="file" name="upfile" size="50" />
                   9045: <br /><label>$type: $selectform</label>
1.589     bisitz   9046: <br /><label><input type="radio" name="gradingmechanism" value="attendance"$checked{'attendance'} onclick="sanitycheck()" />$attendance </label>
                   9047: <br /><label><input type="radio" name="gradingmechanism" value="personnel"$checked{'personnel'} onclick="sanitycheck()" />$personnel</label>
                   9048: <br /><label><input type="radio" name="gradingmechanism" value="specific"$checked{'specific'} onclick="sanitycheck()" />$specific </label>
1.414     www      9049: <input type="text" name="specificid" value="$env{'form.specificid'}" size="20" />
1.589     bisitz   9050: <br /><label><input type="radio" name="gradingmechanism" value="given"$checked{'given'} onclick="sanitycheck()" />$given </label>
1.521     www      9051: <br />&nbsp;&nbsp;&nbsp;
                   9052: <input type="text" name="givenanswer" size="50" />
1.413     www      9053: <input type="hidden" name="waschecked" value="$env{'form.gradingmechanism'}" />
1.589     bisitz   9054: <br /><label>$pcorrect: <input type="text" name="pcorrect" size="4" value="$env{'form.pcorrect'}" onchange="sanitycheck()" /></label>
                   9055: <br /><label>$pincorrect: <input type="text" name="pincorrect" size="4" value="$env{'form.pincorrect'}" onchange="sanitycheck()" /></label>
                   9056: <br /><input type="button" onclick="javascript:checkUpload(this.form);" value="$upload" />
1.400     www      9057: </form>
                   9058: ENDUPFORM
                   9059:     $result.='</td></tr></table>'."\n".
                   9060:              '</td></tr></table><br /><br />'."\n";
                   9061:     $result.=&show_grading_menu_form($symb);
                   9062:     return $result;
                   9063: }
                   9064: 
                   9065: sub process_clicker_file {
                   9066:     my ($r)=@_;
                   9067:     my ($symb)=&get_symb($r);
                   9068:     if (!$symb) {return '';}
1.413     www      9069: 
                   9070:     my %Saveable_Parameters=&clicker_grading_parameters();
                   9071:     &Apache::loncommon::store_course_settings('grades_clicker',
                   9072:                                               \%Saveable_Parameters);
                   9073: 
1.400     www      9074:     my ($result) = &showResourceInfo($symb,$env{'form.probTitle'});
1.404     www      9075:     if (($env{'form.gradingmechanism'} eq 'specific') && ($env{'form.specificid'}!~/\w/)) {
1.408     albertel 9076: 	$result.='<span class="LC_error">'.&mt('You need to specify a clicker ID for the correct answer').'</span>';
                   9077: 	return $result.&show_grading_menu_form($symb);
1.404     www      9078:     }
1.522     www      9079:     if (($env{'form.gradingmechanism'} eq 'given') && ($env{'form.givenanswer'}!~/\S/)) {
1.521     www      9080:         $result.='<span class="LC_error">'.&mt('You need to specify the correct answer').'</span>';
                   9081:         return $result.&show_grading_menu_form($symb);
                   9082:     }
1.522     www      9083:     my $foundgiven=0;
1.521     www      9084:     if ($env{'form.gradingmechanism'} eq 'given') {
                   9085:         $env{'form.givenanswer'}=~s/^\s*//gs;
                   9086:         $env{'form.givenanswer'}=~s/\s*$//gs;
                   9087:         $env{'form.givenanswer'}=~s/[^a-zA-Z0-9\.\*\-]+/\,/g;
                   9088:         $env{'form.givenanswer'}=uc($env{'form.givenanswer'});
1.522     www      9089:         my @answers=split(/\,/,$env{'form.givenanswer'});
                   9090:         $foundgiven=$#answers+1;
1.521     www      9091:     }
1.407     albertel 9092:     my %clicker_ids=&gather_clicker_ids();
1.408     albertel 9093:     my %correct_ids;
1.404     www      9094:     if ($env{'form.gradingmechanism'} eq 'personnel') {
1.408     albertel 9095: 	%correct_ids=&gather_adv_clicker_ids();
1.404     www      9096:     }
                   9097:     if ($env{'form.gradingmechanism'} eq 'specific') {
1.414     www      9098: 	foreach my $correct_id (split(/[\s\,]/,$env{'form.specificid'})) {;
                   9099: 	   $correct_id=~tr/a-z/A-Z/;
                   9100: 	   $correct_id=~s/\s//gs;
                   9101: 	   $correct_id=~s/^[\#0]+//;
1.421     www      9102:            $correct_id=~s/[\-\:]//g;
1.414     www      9103:            if ($correct_id) {
                   9104: 	      $correct_ids{$correct_id}='specified';
                   9105:            }
                   9106:         }
1.400     www      9107:     }
1.404     www      9108:     if ($env{'form.gradingmechanism'} eq 'attendance') {
1.408     albertel 9109: 	$result.=&mt('Score based on attendance only');
1.521     www      9110:     } elsif ($env{'form.gradingmechanism'} eq 'given') {
1.522     www      9111:         $result.=&mt('Score based on [_1] ([_2] answers)','<tt>'.$env{'form.givenanswer'}.'</tt>',$foundgiven);
1.404     www      9112:     } else {
1.408     albertel 9113: 	my $number=0;
1.411     www      9114: 	$result.='<p><b>'.&mt('Correctness determined by the following IDs').'</b>';
1.408     albertel 9115: 	foreach my $id (sort(keys(%correct_ids))) {
1.411     www      9116: 	    $result.='<br /><tt>'.$id.'</tt> - ';
1.408     albertel 9117: 	    if ($correct_ids{$id} eq 'specified') {
                   9118: 		$result.=&mt('specified');
                   9119: 	    } else {
                   9120: 		my ($uname,$udom)=split(/\:/,$correct_ids{$id});
                   9121: 		$result.=&Apache::loncommon::plainname($uname,$udom);
                   9122: 	    }
                   9123: 	    $number++;
                   9124: 	}
1.411     www      9125:         $result.="</p>\n";
1.408     albertel 9126: 	if ($number==0) {
                   9127: 	    $result.='<span class="LC_error">'.&mt('No IDs found to determine correct answer').'</span>';
                   9128: 	    return $result.&show_grading_menu_form($symb);
                   9129: 	}
1.404     www      9130:     }
1.405     www      9131:     if (length($env{'form.upfile'}) < 2) {
1.407     albertel 9132:         $result.=&mt('[_1] Error: [_2] The file you attempted to upload, [_3] contained no information. Please check that you entered the correct filename.',
                   9133: 		     '<span class="LC_error">',
                   9134: 		     '</span>',
                   9135: 		     '<span class="LC_filename">'.&HTML::Entities::encode($env{'form.upfile.filename'},'<>&"').'</span>');
1.405     www      9136:         return $result.&show_grading_menu_form($symb);
                   9137:     }
1.410     www      9138: 
                   9139: # Were able to get all the info needed, now analyze the file
                   9140: 
1.411     www      9141:     $result.=&Apache::loncommon::studentbrowser_javascript();
1.418     albertel 9142:     $symb = &Apache::lonenc::check_encrypt($symb);
1.410     www      9143:     my $heading=&mt('Scanning clicker file');
                   9144:     $result.=(<<ENDHEADER);
                   9145: <br /><table width="100%" border="0"><tr><td bgcolor="#777777">
                   9146: <table width="100%" border="0"><tr bgcolor="#e6ffff"><td>
                   9147: <b>$heading</b></td></tr><tr bgcolor=#ffffe6><td>
                   9148: <form method="post" action="/adm/grades" name="clickeranalysis">
                   9149: <input type="hidden" name="symb" value="$symb" />
                   9150: <input type="hidden" name="command" value="assignclickergrades" />
                   9151: <input type="hidden" name="probTitle" value="$env{'form.probTitle'}" />
                   9152: <input type="hidden" name="saveState"  value="$env{'form.saveState'}" />
1.411     www      9153: <input type="hidden" name="gradingmechanism" value="$env{'form.gradingmechanism'}" />
                   9154: <input type="hidden" name="pcorrect" value="$env{'form.pcorrect'}" />
                   9155: <input type="hidden" name="pincorrect" value="$env{'form.pincorrect'}" />
1.410     www      9156: ENDHEADER
1.522     www      9157:     if ($env{'form.gradingmechanism'} eq 'given') {
                   9158:        $result.='<input type="hidden" name="correct:given" value="'.$env{'form.givenanswer'}.'" />';
                   9159:     } 
1.408     albertel 9160:     my %responses;
                   9161:     my @questiontitles;
1.405     www      9162:     my $errormsg='';
                   9163:     my $number=0;
                   9164:     if ($env{'form.upfiletype'} eq 'iclicker') {
1.408     albertel 9165: 	($errormsg,$number)=&iclicker_eval(\@questiontitles,\%responses);
1.406     www      9166:     }
1.419     www      9167:     if ($env{'form.upfiletype'} eq 'interwrite') {
                   9168:         ($errormsg,$number)=&interwrite_eval(\@questiontitles,\%responses);
                   9169:     }
1.411     www      9170:     $result.='<br />'.&mt('Found [_1] question(s)',$number).'<br />'.
                   9171:              '<input type="hidden" name="number" value="'.$number.'" />'.
                   9172:              &mt('Awarding [_1] percent for correct and [_2] percent for incorrect responses',
                   9173:                  $env{'form.pcorrect'},$env{'form.pincorrect'}).
                   9174:              '<br />';
1.522     www      9175:     if (($env{'form.gradingmechanism'} eq 'given') && ($number!=$foundgiven)) {
                   9176:        $result.='<span class="LC_error">'.&mt('Number of given answers does not agree with number of questions in file.').'</span>';
                   9177:        return $result.&show_grading_menu_form($symb);
                   9178:     } 
1.414     www      9179: # Remember Question Titles
                   9180: # FIXME: Possibly need delimiter other than ":"
                   9181:     for (my $i=0;$i<$number;$i++) {
                   9182:         $result.='<input type="hidden" name="question:'.$i.'" value="'.
                   9183:                  &HTML::Entities::encode($questiontitles[$i],'"&<>').'" />';
                   9184:     }
1.411     www      9185:     my $correct_count=0;
                   9186:     my $student_count=0;
                   9187:     my $unknown_count=0;
1.414     www      9188: # Match answers with usernames
                   9189: # FIXME: Possibly need delimiter other than ":"
1.409     albertel 9190:     foreach my $id (keys(%responses)) {
1.410     www      9191:        if ($correct_ids{$id}) {
1.414     www      9192:           $result.="\n".'<input type="hidden" name="correct:'.$correct_count.':'.$correct_ids{$id}.'" value="'.$responses{$id}.'" />';
1.411     www      9193:           $correct_count++;
1.410     www      9194:        } elsif ($clicker_ids{$id}) {
1.437     www      9195:           if ($clicker_ids{$id}=~/\,/) {
                   9196: # More than one user with the same clicker!
                   9197:              $result.="\n<hr />".&mt('Clicker registered more than once').": <tt>".$id."</tt><br />";
                   9198:              $result.="\n".'<input type="hidden" name="unknown:'.$id.'" value="'.$responses{$id}.'" />'.
                   9199:                            "<select name='multi".$id."'>";
                   9200:              foreach my $reguser (sort(split(/\,/,$clicker_ids{$id}))) {
                   9201:                  $result.="<option value='".$reguser."'>".&Apache::loncommon::plainname(split(/\:/,$reguser)).' ('.$reguser.')</option>';
                   9202:              }
                   9203:              $result.='</select>';
                   9204:              $unknown_count++;
                   9205:           } else {
                   9206: # Good: found one and only one user with the right clicker
                   9207:              $result.="\n".'<input type="hidden" name="student:'.$clicker_ids{$id}.'" value="'.$responses{$id}.'" />';
                   9208:              $student_count++;
                   9209:           }
1.410     www      9210:        } else {
1.411     www      9211:           $result.="\n<hr />".&mt('Unregistered Clicker')." <tt>".$id."</tt><br />";
                   9212:           $result.="\n".'<input type="hidden" name="unknown:'.$id.'" value="'.$responses{$id}.'" />'.
                   9213:                    "\n".&mt("Username").": <input type='text' name='uname".$id."' />&nbsp;".
                   9214:                    "\n".&mt("Domain").": ".
                   9215:                    &Apache::loncommon::select_dom_form($env{'course.'.$env{'request.course.id'}.'.domain'},'udom'.$id).'&nbsp;'.
                   9216:                    &Apache::loncommon::selectstudent_link('clickeranalysis','uname'.$id,'udom'.$id);
                   9217:           $unknown_count++;
1.410     www      9218:        }
1.405     www      9219:     }
1.412     www      9220:     $result.='<hr />'.
                   9221:              &mt('Found [_1] registered and [_2] unregistered clickers.',$student_count,$unknown_count);
1.521     www      9222:     if (($env{'form.gradingmechanism'} ne 'attendance') && ($env{'form.gradingmechanism'} ne 'given')) {
1.412     www      9223:        if ($correct_count==0) {
                   9224:           $errormsg.="Found no correct answers answers for grading!";
                   9225:        } elsif ($correct_count>1) {
1.414     www      9226:           $result.='<br /><span class="LC_warning">'.&mt("Found [_1] entries for grading!",$correct_count).'</span>';
1.412     www      9227:        }
                   9228:     }
1.428     www      9229:     if ($number<1) {
                   9230:        $errormsg.="Found no questions.";
                   9231:     }
1.412     www      9232:     if ($errormsg) {
                   9233:        $result.='<br /><span class="LC_error">'.&mt($errormsg).'</span>';
                   9234:     } else {
                   9235:        $result.='<br /><input type="submit" name="finalize" value="'.&mt('Finalize Grading').'" />';
                   9236:     }
                   9237:     $result.='</form></td></tr></table>'."\n".
1.410     www      9238:              '</td></tr></table><br /><br />'."\n";
1.404     www      9239:     return $result.&show_grading_menu_form($symb);
1.400     www      9240: }
                   9241: 
1.405     www      9242: sub iclicker_eval {
1.406     www      9243:     my ($questiontitles,$responses)=@_;
1.405     www      9244:     my $number=0;
                   9245:     my $errormsg='';
                   9246:     foreach my $line (split(/[\n\r]/,$env{'form.upfile'})) {
1.410     www      9247:         my %components=&Apache::loncommon::record_sep($line);
                   9248:         my @entries=map {$components{$_}} (sort(keys(%components)));
1.408     albertel 9249: 	if ($entries[0] eq 'Question') {
                   9250: 	    for (my $i=3;$i<$#entries;$i+=6) {
                   9251: 		$$questiontitles[$number]=$entries[$i];
                   9252: 		$number++;
                   9253: 	    }
                   9254: 	}
                   9255: 	if ($entries[0]=~/^\#/) {
                   9256: 	    my $id=$entries[0];
                   9257: 	    my @idresponses;
                   9258: 	    $id=~s/^[\#0]+//;
                   9259: 	    for (my $i=0;$i<$number;$i++) {
                   9260: 		my $idx=3+$i*6;
                   9261: 		push(@idresponses,$entries[$idx]);
                   9262: 	    }
                   9263: 	    $$responses{$id}=join(',',@idresponses);
                   9264: 	}
1.405     www      9265:     }
                   9266:     return ($errormsg,$number);
                   9267: }
                   9268: 
1.419     www      9269: sub interwrite_eval {
                   9270:     my ($questiontitles,$responses)=@_;
                   9271:     my $number=0;
                   9272:     my $errormsg='';
1.420     www      9273:     my $skipline=1;
                   9274:     my $questionnumber=0;
                   9275:     my %idresponses=();
1.419     www      9276:     foreach my $line (split(/[\n\r]/,$env{'form.upfile'})) {
                   9277:         my %components=&Apache::loncommon::record_sep($line);
                   9278:         my @entries=map {$components{$_}} (sort(keys(%components)));
1.420     www      9279:         if ($entries[1] eq 'Time') { $skipline=0; next; }
                   9280:         if ($entries[1] eq 'Response') { $skipline=1; }
                   9281:         next if $skipline;
                   9282:         if ($entries[0]!=$questionnumber) {
                   9283:            $questionnumber=$entries[0];
                   9284:            $$questiontitles[$number]=&mt('Question [_1]',$questionnumber);
                   9285:            $number++;
1.419     www      9286:         }
1.420     www      9287:         my $id=$entries[4];
                   9288:         $id=~s/^[\#0]+//;
1.421     www      9289:         $id=~s/^v\d*\://i;
                   9290:         $id=~s/[\-\:]//g;
1.420     www      9291:         $idresponses{$id}[$number]=$entries[6];
                   9292:     }
1.524     raeburn  9293:     foreach my $id (keys(%idresponses)) {
1.420     www      9294:        $$responses{$id}=join(',',@{$idresponses{$id}});
                   9295:        $$responses{$id}=~s/^\s*\,//;
1.419     www      9296:     }
                   9297:     return ($errormsg,$number);
                   9298: }
                   9299: 
1.414     www      9300: sub assign_clicker_grades {
                   9301:     my ($r)=@_;
                   9302:     my ($symb)=&get_symb($r);
                   9303:     if (!$symb) {return '';}
1.416     www      9304: # See which part we are saving to
1.582     raeburn  9305:     my $res_error;
                   9306:     my ($partlist,$handgrade,$responseType) = &response_type($symb,\$res_error);
                   9307:     if ($res_error) {
                   9308:         return &navmap_errormsg();
                   9309:     }
1.416     www      9310: # FIXME: This should probably look for the first handgradeable part
                   9311:     my $part=$$partlist[0];
                   9312: # Start screen output
1.414     www      9313:     my ($result) = &showResourceInfo($symb,$env{'form.probTitle'});
1.416     www      9314: 
1.414     www      9315:     my $heading=&mt('Assigning grades based on clicker file');
                   9316:     $result.=(<<ENDHEADER);
                   9317: <br /><table width="100%" border="0"><tr><td bgcolor="#777777">
                   9318: <table width="100%" border="0"><tr bgcolor="#e6ffff"><td>
                   9319: <b>$heading</b></td></tr><tr bgcolor=#ffffe6><td>
                   9320: ENDHEADER
                   9321: # Get correct result
                   9322: # FIXME: Possibly need delimiter other than ":"
                   9323:     my @correct=();
1.415     www      9324:     my $gradingmechanism=$env{'form.gradingmechanism'};
                   9325:     my $number=$env{'form.number'};
                   9326:     if ($gradingmechanism ne 'attendance') {
1.414     www      9327:        foreach my $key (keys(%env)) {
                   9328:           if ($key=~/^form\.correct\:/) {
                   9329:              my @input=split(/\,/,$env{$key});
                   9330:              for (my $i=0;$i<=$#input;$i++) {
                   9331:                  if (($correct[$i]) && ($input[$i]) &&
                   9332:                      ($correct[$i] ne $input[$i])) {
                   9333:                     $result.='<br /><span class="LC_warning">'.
                   9334:                              &mt('More than one correct result given for question "[_1]": [_2] versus [_3].',
                   9335:                                  $env{'form.question:'.$i},$correct[$i],$input[$i]).'</span>';
                   9336:                  } elsif ($input[$i]) {
                   9337:                     $correct[$i]=$input[$i];
                   9338:                  }
                   9339:              }
                   9340:           }
                   9341:        }
1.415     www      9342:        for (my $i=0;$i<$number;$i++) {
1.414     www      9343:           if (!$correct[$i]) {
                   9344:              $result.='<br /><span class="LC_error">'.
                   9345:                       &mt('No correct result given for question "[_1]"!',
                   9346:                           $env{'form.question:'.$i}).'</span>';
                   9347:           }
                   9348:        }
                   9349:        $result.='<br />'.&mt("Correct answer: [_1]",join(', ',map { ($_?$_:'-') } @correct));
                   9350:     }
                   9351: # Start grading
1.415     www      9352:     my $pcorrect=$env{'form.pcorrect'};
                   9353:     my $pincorrect=$env{'form.pincorrect'};
1.416     www      9354:     my $storecount=0;
1.415     www      9355:     foreach my $key (keys(%env)) {
1.420     www      9356:        my $user='';
1.415     www      9357:        if ($key=~/^form\.student\:(.*)$/) {
1.420     www      9358:           $user=$1;
                   9359:        }
                   9360:        if ($key=~/^form\.unknown\:(.*)$/) {
                   9361:           my $id=$1;
                   9362:           if (($env{'form.uname'.$id}) && ($env{'form.udom'.$id})) {
                   9363:              $user=$env{'form.uname'.$id}.':'.$env{'form.udom'.$id};
1.437     www      9364:           } elsif ($env{'form.multi'.$id}) {
                   9365:              $user=$env{'form.multi'.$id};
1.420     www      9366:           }
                   9367:        }
                   9368:        if ($user) { 
1.415     www      9369:           my @answer=split(/\,/,$env{$key});
                   9370:           my $sum=0;
1.522     www      9371:           my $realnumber=$number;
1.415     www      9372:           for (my $i=0;$i<$number;$i++) {
1.576     www      9373:              if  ($correct[$i] eq '-') {
                   9374:                 $realnumber--;
                   9375:              } elsif ($answer[$i]) {
1.415     www      9376:                 if ($gradingmechanism eq 'attendance') {
                   9377:                    $sum+=$pcorrect;
1.576     www      9378:                 } elsif ($correct[$i] eq '*') {
1.522     www      9379:                    $sum+=$pcorrect;
1.415     www      9380:                 } else {
                   9381:                    if ($answer[$i] eq $correct[$i]) {
                   9382:                       $sum+=$pcorrect;
                   9383:                    } else {
                   9384:                       $sum+=$pincorrect;
                   9385:                    }
                   9386:                 }
                   9387:              }
                   9388:           }
1.522     www      9389:           my $ave=$sum/(100*$realnumber);
1.416     www      9390: # Store
                   9391:           my ($username,$domain)=split(/\:/,$user);
                   9392:           my %grades=();
                   9393:           $grades{"resource.$part.solved"}='correct_by_override';
                   9394:           $grades{"resource.$part.awarded"}=$ave;
                   9395:           $grades{"resource.regrader"}="$env{'user.name'}:$env{'user.domain'}";
                   9396:           my $returncode=&Apache::lonnet::cstore(\%grades,$symb,
                   9397:                                                  $env{'request.course.id'},
                   9398:                                                  $domain,$username);
                   9399:           if ($returncode ne 'ok') {
                   9400:              $result.="<br /><span class=\"LC_error\">Failed to save student $username:$domain. Message when trying to save was ($returncode)</span>";
                   9401:           } else {
                   9402:              $storecount++;
                   9403:           }
1.415     www      9404:        }
                   9405:     }
                   9406: # We are done
1.549     hauer    9407:     $result.='<br />'.&mt('Successfully stored grades for [quant,_1,student].',$storecount).
1.416     www      9408:              '</td></tr></table>'."\n".
1.414     www      9409:              '</td></tr></table><br /><br />'."\n";
                   9410:     return $result.&show_grading_menu_form($symb);
                   9411: }
                   9412: 
1.582     raeburn  9413: sub navmap_errormsg {
                   9414:     return '<div class="LC_error">'.
                   9415:            &mt('An error occurred retrieving information about resources in the course.').'<br />'.
1.595     raeburn  9416:            &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>').
1.582     raeburn  9417:            '</div>';
                   9418: }
                   9419: 
1.1       albertel 9420: sub handler {
1.41      ng       9421:     my $request=$_[0];
1.434     albertel 9422:     &reset_caches();
1.257     albertel 9423:     if ($env{'browser.mathml'}) {
1.141     www      9424: 	&Apache::loncommon::content_type($request,'text/xml');
1.41      ng       9425:     } else {
1.141     www      9426: 	&Apache::loncommon::content_type($request,'text/html');
1.41      ng       9427:     }
                   9428:     $request->send_http_header;
1.44      ng       9429:     return '' if $request->header_only;
1.41      ng       9430:     &Apache::loncommon::get_unprocessed_cgi($ENV{'QUERY_STRING'});
1.324     albertel 9431:     my $symb=&get_symb($request,1);
1.160     albertel 9432:     my @commands=&Apache::loncommon::get_env_multiple('form.command');
                   9433:     my $command=$commands[0];
1.447     foxr     9434: 
1.160     albertel 9435:     if ($#commands > 0) {
                   9436: 	&Apache::lonnet::logthis("grades got multiple commands ".join(':',@commands));
                   9437:     }
1.447     foxr     9438: 
1.513     foxr     9439:     $ssi_error = 0;
1.535     raeburn  9440:     my $brcrum = [{href=>"/adm/grades",text=>"Grading"}];
                   9441:     $request->print(&Apache::loncommon::start_page('Grading',undef,
                   9442:                                           {'bread_crumbs' => $brcrum}));
1.324     albertel 9443:     if ($symb eq '' && $command eq '') {
1.257     albertel 9444: 	if ($env{'user.adv'}) {
                   9445: 	    if (($env{'form.codeone'}) && ($env{'form.codetwo'}) &&
                   9446: 		($env{'form.codethree'})) {
                   9447: 		my $token=$env{'form.codeone'}.'*'.$env{'form.codetwo'}.'*'.
                   9448: 		    $env{'form.codethree'};
1.41      ng       9449: 		my ($tsymb,$tuname,$tudom,$tcrsid)=
                   9450: 		    &Apache::lonnet::checkin($token);
                   9451: 		if ($tsymb) {
1.137     albertel 9452: 		    my ($map,$id,$url)=&Apache::lonnet::decode_symb($tsymb);
1.41      ng       9453: 		    if (&Apache::lonnet::allowed('mgr',$tcrsid)) {
1.513     foxr     9454: 			$request->print(&ssi_with_retries('/res/'.$url, $ssi_retries,
1.99      albertel 9455: 					  ('grade_username' => $tuname,
                   9456: 					   'grade_domain' => $tudom,
                   9457: 					   'grade_courseid' => $tcrsid,
                   9458: 					   'grade_symb' => $tsymb)));
1.41      ng       9459: 		    } else {
1.45      ng       9460: 			$request->print('<h3>Not authorized: '.$token.'</h3>');
1.99      albertel 9461: 		    }
1.41      ng       9462: 		} else {
1.45      ng       9463: 		    $request->print('<h3>Not a valid DocID: '.$token.'</h3>');
1.41      ng       9464: 		}
1.14      www      9465: 	    } else {
1.41      ng       9466: 		$request->print(&Apache::lonxml::tokeninputfield());
                   9467: 	    }
                   9468: 	}
                   9469:     } else {
1.285     albertel 9470: 	&init_perm();
1.104     albertel 9471: 	if ($command eq 'submission' && $perm{'vgr'}) {
1.257     albertel 9472: 	    ($env{'form.student'} eq '' ? &listStudents($request) : &submission($request,0,0));
1.103     albertel 9473: 	} elsif ($command eq 'pickStudentPage' && $perm{'vgr'}) {
1.68      ng       9474: 	    &pickStudentPage($request);
1.103     albertel 9475: 	} elsif ($command eq 'displayPage' && $perm{'vgr'}) {
1.68      ng       9476: 	    &displayPage($request);
1.104     albertel 9477: 	} elsif ($command eq 'gradeByPage' && $perm{'mgr'}) {
1.71      ng       9478: 	    &updateGradeByPage($request);
1.104     albertel 9479: 	} elsif ($command eq 'processGroup' && $perm{'vgr'}) {
1.41      ng       9480: 	    &processGroup($request);
1.104     albertel 9481: 	} elsif ($command eq 'gradingmenu' && $perm{'vgr'}) {
1.443     banghart 9482: 	    $request->print(&grading_menu($request));
                   9483: 	} elsif ($command eq 'submit_options' && $perm{'vgr'}) {
                   9484: 	    $request->print(&submit_options($request));
1.104     albertel 9485: 	} elsif ($command eq 'viewgrades' && $perm{'vgr'}) {
1.41      ng       9486: 	    $request->print(&viewgrades($request));
1.104     albertel 9487: 	} elsif ($command eq 'handgrade' && $perm{'mgr'}) {
1.41      ng       9488: 	    $request->print(&processHandGrade($request));
1.106     albertel 9489: 	} elsif ($command eq 'editgrades' && $perm{'mgr'}) {
1.41      ng       9490: 	    $request->print(&editgrades($request));
1.106     albertel 9491: 	} elsif ($command eq 'verify' && $perm{'vgr'}) {
1.41      ng       9492: 	    $request->print(&verifyreceipt($request));
1.400     www      9493:         } elsif ($command eq 'processclicker' && $perm{'mgr'}) {
                   9494:             $request->print(&process_clicker($request));
                   9495:         } elsif ($command eq 'processclickerfile' && $perm{'mgr'}) {
                   9496:             $request->print(&process_clicker_file($request));
1.414     www      9497:         } elsif ($command eq 'assignclickergrades' && $perm{'mgr'}) {
                   9498:             $request->print(&assign_clicker_grades($request));
1.106     albertel 9499: 	} elsif ($command eq 'csvform' && $perm{'mgr'}) {
1.72      ng       9500: 	    $request->print(&upcsvScores_form($request));
1.106     albertel 9501: 	} elsif ($command eq 'csvupload' && $perm{'mgr'}) {
1.41      ng       9502: 	    $request->print(&csvupload($request));
1.106     albertel 9503: 	} elsif ($command eq 'csvuploadmap' && $perm{'mgr'} ) {
1.41      ng       9504: 	    $request->print(&csvuploadmap($request));
1.246     albertel 9505: 	} elsif ($command eq 'csvuploadoptions' && $perm{'mgr'}) {
1.257     albertel 9506: 	    if ($env{'form.associate'} ne 'Reverse Association') {
1.246     albertel 9507: 		$request->print(&csvuploadoptions($request));
1.41      ng       9508: 	    } else {
1.257     albertel 9509: 		if ( $env{'form.upfile_associate'} ne 'reverse' ) {
                   9510: 		    $env{'form.upfile_associate'} = 'reverse';
1.41      ng       9511: 		} else {
1.257     albertel 9512: 		    $env{'form.upfile_associate'} = 'forward';
1.41      ng       9513: 		}
                   9514: 		$request->print(&csvuploadmap($request));
                   9515: 	    }
1.246     albertel 9516: 	} elsif ($command eq 'csvuploadassign' && $perm{'mgr'} ) {
                   9517: 	    $request->print(&csvuploadassign($request));
1.106     albertel 9518: 	} elsif ($command eq 'scantron_selectphase' && $perm{'mgr'}) {
1.75      albertel 9519: 	    $request->print(&scantron_selectphase($request));
1.203     albertel 9520:  	} elsif ($command eq 'scantron_warning' && $perm{'mgr'}) {
                   9521:  	    $request->print(&scantron_do_warning($request));
1.142     albertel 9522: 	} elsif ($command eq 'scantron_validate' && $perm{'mgr'}) {
                   9523: 	    $request->print(&scantron_validate_file($request));
1.106     albertel 9524: 	} elsif ($command eq 'scantron_process' && $perm{'mgr'}) {
1.82      albertel 9525: 	    $request->print(&scantron_process_students($request));
1.157     albertel 9526:  	} elsif ($command eq 'scantronupload' && 
1.257     albertel 9527:  		 (&Apache::lonnet::allowed('usc',$env{'request.role.domain'})||
                   9528: 		  &Apache::lonnet::allowed('usc',$env{'request.course.id'}))) {
1.162     albertel 9529:  	    $request->print(&scantron_upload_scantron_data($request)); 
1.157     albertel 9530:  	} elsif ($command eq 'scantronupload_save' &&
1.257     albertel 9531:  		 (&Apache::lonnet::allowed('usc',$env{'request.role.domain'})||
                   9532: 		  &Apache::lonnet::allowed('usc',$env{'request.course.id'}))) {
1.157     albertel 9533:  	    $request->print(&scantron_upload_scantron_data_save($request));
1.202     albertel 9534:  	} elsif ($command eq 'scantron_download' &&
1.257     albertel 9535: 		 &Apache::lonnet::allowed('usc',$env{'request.course.id'})) {
1.162     albertel 9536:  	    $request->print(&scantron_download_scantron_data($request));
1.523     raeburn  9537:         } elsif ($command eq 'checksubmissions' && $perm{'vgr'}) {
                   9538:             $request->print(&checkscantron_results($request));     
1.106     albertel 9539: 	} elsif ($command) {
1.562     bisitz   9540: 	    $request->print('<p class="LC_error">'.&mt('Access Denied ([_1])',$command).'</p>');
1.26      albertel 9541: 	}
1.2       albertel 9542:     }
1.513     foxr     9543:     if ($ssi_error) {
                   9544: 	&ssi_print_error($request);
                   9545:     }
1.353     albertel 9546:     $request->print(&Apache::loncommon::end_page());
1.434     albertel 9547:     &reset_caches();
1.44      ng       9548:     return '';
                   9549: }
                   9550: 
1.1       albertel 9551: 1;
                   9552: 
1.13      albertel 9553: __END__;
1.531     jms      9554: 
                   9555: 
                   9556: =head1 NAME
                   9557: 
                   9558: Apache::grades
                   9559: 
                   9560: =head1 SYNOPSIS
                   9561: 
                   9562: Handles the viewing of grades.
                   9563: 
                   9564: This is part of the LearningOnline Network with CAPA project
                   9565: described at http://www.lon-capa.org.
                   9566: 
                   9567: =head1 OVERVIEW
                   9568: 
                   9569: Do an ssi with retries:
                   9570: While I'd love to factor out this with the vesrion in lonprintout,
                   9571: 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
                   9572: I'm not quite ready to invent (e.g. an ssi_with_retry object).
                   9573: 
                   9574: At least the logic that drives this has been pulled out into loncommon.
                   9575: 
                   9576: 
                   9577: 
                   9578: ssi_with_retries - Does the server side include of a resource.
                   9579:                      if the ssi call returns an error we'll retry it up to
                   9580:                      the number of times requested by the caller.
                   9581:                      If we still have a proble, no text is appended to the
                   9582:                      output and we set some global variables.
                   9583:                      to indicate to the caller an SSI error occurred.  
                   9584:                      All of this is supposed to deal with the issues described
                   9585:                      in LonCAPA BZ 5631 see:
                   9586:                      http://bugs.lon-capa.org/show_bug.cgi?id=5631
                   9587:                      by informing the user that this happened.
                   9588: 
                   9589: Parameters:
                   9590:   resource   - The resource to include.  This is passed directly, without
                   9591:                interpretation to lonnet::ssi.
                   9592:   form       - The form hash parameters that guide the interpretation of the resource
                   9593:                
                   9594:   retries    - Number of retries allowed before giving up completely.
                   9595: Returns:
                   9596:   On success, returns the rendered resource identified by the resource parameter.
                   9597: Side Effects:
                   9598:   The following global variables can be set:
                   9599:    ssi_error                - If an unrecoverable error occurred this becomes true.
                   9600:                               It is up to the caller to initialize this to false
                   9601:                               if desired.
                   9602:    ssi_error_resource  - If an unrecoverable error occurred, this is the value
                   9603:                               of the resource that could not be rendered by the ssi
                   9604:                               call.
                   9605:    ssi_error_message   - The error string fetched from the ssi response
                   9606:                               in the event of an error.
                   9607: 
                   9608: 
                   9609: =head1 HANDLER SUBROUTINE
                   9610: 
                   9611: ssi_with_retries()
                   9612: 
                   9613: =head1 SUBROUTINES
                   9614: 
                   9615: =over
                   9616: 
                   9617: =item scantron_get_correction() : 
                   9618: 
                   9619:    Builds the interface screen to interact with the operator to fix a
                   9620:    specific error condition in a specific scanline
                   9621: 
                   9622:  Arguments:
                   9623:     $r           - Apache request object
                   9624:     $i           - number of the current scanline
                   9625:     $scan_record - hash ref as returned from &scantron_parse_scanline()
                   9626:     $scan_config - hash ref as returned from &get_scantron_config()
                   9627:     $line        - full contents of the current scanline
                   9628:     $error       - error condition, valid values are
                   9629:                    'incorrectCODE', 'duplicateCODE',
                   9630:                    'doublebubble', 'missingbubble',
                   9631:                    'duplicateID', 'incorrectID'
                   9632:     $arg         - extra information needed
                   9633:        For errors:
                   9634:          - duplicateID   - paper number that this studentID was seen before on
                   9635:          - duplicateCODE - array ref of the paper numbers this CODE was
                   9636:                            seen on before
                   9637:          - incorrectCODE - current incorrect CODE 
                   9638:          - doublebubble  - array ref of the bubble lines that have double
                   9639:                            bubble errors
                   9640:          - missingbubble - array ref of the bubble lines that have missing
                   9641:                            bubble errors
                   9642: 
                   9643: =item  scantron_get_maxbubble() : 
                   9644: 
1.582     raeburn  9645:    Arguments:
                   9646:        $nav_error  - Reference to scalar which is a flag to indicate a
                   9647:                       failure to retrieve a navmap object.
                   9648:        if $nav_error is set to 1 by scantron_get_maxbubble(), the 
                   9649:        calling routine should trap the error condition and display the warning
                   9650:        found in &navmap_errormsg().
                   9651: 
1.531     jms      9652:    Returns the maximum number of bubble lines that are expected to
                   9653:    occur. Does this by walking the selected sequence rendering the
                   9654:    resource and then checking &Apache::lonxml::get_problem_counter()
                   9655:    for what the current value of the problem counter is.
                   9656: 
                   9657:    Caches the results to $env{'form.scantron_maxbubble'},
                   9658:    $env{'form.scantron.bubble_lines.n'}, 
                   9659:    $env{'form.scantron.first_bubble_line.n'} and
                   9660:    $env{"form.scantron.sub_bubblelines.n"}
                   9661:    which are the total number of bubble, lines, the number of bubble
                   9662:    lines for response n and number of the first bubble line for response n,
                   9663:    and a comma separated list of numbers of bubble lines for sub-questions
                   9664:    (for optionresponse, matchresponse, and rankresponse items), for response n.  
                   9665: 
                   9666: 
                   9667: =item  scantron_validate_missingbubbles() : 
                   9668: 
                   9669:    Validates all scanlines in the selected file to not have any
                   9670:     answers that don't have bubbles that have not been verified
                   9671:     to be bubble free.
                   9672: 
                   9673: =item  scantron_process_students() : 
                   9674: 
                   9675:    Routine that does the actual grading of the bubble sheet information.
                   9676: 
                   9677:    The parsed scanline hash is added to %env 
                   9678: 
                   9679:    Then foreach unskipped scanline it does an &Apache::lonnet::ssi()
                   9680:    foreach resource , with the form data of
                   9681: 
                   9682: 	'submitted'     =>'scantron' 
                   9683: 	'grade_target'  =>'grade',
                   9684: 	'grade_username'=> username of student
                   9685: 	'grade_domain'  => domain of student
                   9686: 	'grade_courseid'=> of course
                   9687: 	'grade_symb'    => symb of resource to grade
                   9688: 
                   9689:     This triggers a grading pass. The problem grading code takes care
                   9690:     of converting the bubbled letter information (now in %env) into a
                   9691:     valid submission.
                   9692: 
                   9693: =item  scantron_upload_scantron_data() :
                   9694: 
                   9695:     Creates the screen for adding a new bubble sheet data file to a course.
                   9696: 
                   9697: =item  scantron_upload_scantron_data_save() : 
                   9698: 
                   9699:    Adds a provided bubble information data file to the course if user
                   9700:    has the correct privileges to do so. 
                   9701: 
                   9702: =item  valid_file() :
                   9703: 
                   9704:    Validates that the requested bubble data file exists in the course.
                   9705: 
                   9706: =item  scantron_download_scantron_data() : 
                   9707: 
                   9708:    Shows a list of the three internal files (original, corrected,
                   9709:    skipped) for a specific bubble sheet data file that exists in the
                   9710:    course.
                   9711: 
                   9712: =item  scantron_validate_ID() : 
                   9713: 
                   9714:    Validates all scanlines in the selected file to not have any
1.556     weissno  9715:    invalid or underspecified student/employee IDs
1.531     jms      9716: 
1.582     raeburn  9717: =item navmap_errormsg() :
                   9718: 
                   9719:    Returns HTML mark-up inside a <div></div> with a link to re-initialize the course.
                   9720:    Should be called whenever the request to instantiate a navmap object fails.  
                   9721: 
1.531     jms      9722: =back
                   9723: 
                   9724: =cut

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