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

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.2! raeburn     4: # $Id: grades.pm,v 1.596.2.1 2010/08/13 01:23:59 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.2! raeburn  2508:                     if ($lasthash{$key} eq 'randomizetry') {
1.596     raeburn  2509:                         my $id = join(',',@parts);
1.596.2.2! raeburn  2510:                         $randombytry{$ign.'.'.$id} = $lasthash{$key};
        !          2511:                     } else {
        !          2512:                         unless ($showsurv) {
        !          2513:                             my $id = join(',',@parts);
        !          2514:                             $typeparts{$ign.'.'.$id} = $lasthash{$key};
        !          2515:                         }
1.596     raeburn  2516:                     }
                   2517:                     delete($lasthash{$key});
                   2518:                 }
                   2519:             }
                   2520:         }
                   2521:         my @hidden = keys(%typeparts);
1.596.2.2! raeburn  2522:         my @randomize = keys(%randombytry);
1.397     albertel 2523: 	foreach my $key (keys(%lasthash)) {
                   2524: 	    next if ($key !~ /\.submission$/);
1.596     raeburn  2525:             my $hide;
                   2526:             if (@hidden) {
                   2527:                 foreach my $id (@hidden) {
                   2528:                     if ($key =~ /^\Q$id\E/) {
1.596.2.2! raeburn  2529:                         $hide = 'anon';
1.596     raeburn  2530:                         last;
                   2531:                     }
                   2532:                 }
                   2533:             }
1.596.2.2! raeburn  2534:             unless ($hide) {
        !          2535:                 if (@randomize) {
        !          2536:                     foreach my $id (@hidden) {
        !          2537:                         if ($key =~ /^\Q$id\E/) {
        !          2538:                             $hide = 'rand';
        !          2539:                             last;
        !          2540:                         }
        !          2541:                     }
        !          2542:                 }
        !          2543:             }
1.397     albertel 2544: 	    my ($partid,$foo) = split(/submission$/,$key);
                   2545: 	    my $draft  = $lasthash{$partid.'awarddetail'} eq 'DRAFT' ?
1.398     albertel 2546: 		'<span class="LC_warning">Draft Copy</span> ' : '';
1.596     raeburn  2547: 	    push(@string, join(':', $key, $hide, $draft.$lasthash{$key}));
1.41      ng       2548: 	}
                   2549:     }
1.397     albertel 2550:     if (!@string) {
                   2551: 	$string[0] =
1.539     riegler  2552: 	    '<span class="LC_warning">'.&mt('Nothing submitted - no attempts.').'</span>';
1.397     albertel 2553:     }
                   2554:     return (\@string,\$timestamp);
1.38      ng       2555: }
1.35      ng       2556: 
1.44      ng       2557: #--- High light keywords, with style choosen by user.
1.38      ng       2558: sub keywords_highlight {
1.44      ng       2559:     my $string    = shift;
1.257     albertel 2560:     my $size      = $env{'form.kwsize'} eq '0' ? '' : 'size='.$env{'form.kwsize'};
                   2561:     my $styleon   = $env{'form.kwstyle'} eq ''  ? '' : $env{'form.kwstyle'};
1.41      ng       2562:     (my $styleoff = $styleon) =~ s/\</\<\//;
1.257     albertel 2563:     my @keylist   = split(/[,\s+]/,$env{'form.keywords'});
1.398     albertel 2564:     foreach my $keyword (@keylist) {
                   2565: 	$string =~ s/\b\Q$keyword\E(\b|\.)/<font color\=$env{'form.kwclr'} $size\>$styleon$keyword$styleoff<\/font>/gi;
1.41      ng       2566:     }
                   2567:     return $string;
1.38      ng       2568: }
1.36      ng       2569: 
1.44      ng       2570: #--- Called from submission routine
1.38      ng       2571: sub processHandGrade {
1.41      ng       2572:     my ($request) = shift;
1.324     albertel 2573:     my $symb   = &get_symb($request);
                   2574:     my (undef,undef,$url) = &Apache::lonnet::decode_symb($symb);
1.257     albertel 2575:     my $button = $env{'form.gradeOpt'};
                   2576:     my $ngrade = $env{'form.NCT'};
                   2577:     my $ntstu  = $env{'form.NTSTU'};
1.301     albertel 2578:     my $cdom   = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   2579:     my $cnum   = $env{'course.'.$env{'request.course.id'}.'.num'};
                   2580: 
1.44      ng       2581:     if ($button eq 'Save & Next') {
                   2582: 	my $ctr = 0;
                   2583: 	while ($ctr < $ngrade) {
1.257     albertel 2584: 	    my ($uname,$udom) = split(/:/,$env{'form.unamedom'.$ctr});
1.324     albertel 2585: 	    my ($errorflag,$pts,$wgt) = &saveHandGrade($request,$symb,$uname,$udom,$ctr);
1.71      ng       2586: 	    if ($errorflag eq 'no_score') {
                   2587: 		$ctr++;
                   2588: 		next;
                   2589: 	    }
1.104     albertel 2590: 	    if ($errorflag eq 'not_allowed') {
1.398     albertel 2591: 		$request->print("<span class=\"LC_warning\">Not allowed to modify grades for $uname:$udom</span>");
1.104     albertel 2592: 		$ctr++;
                   2593: 		next;
                   2594: 	    }
1.257     albertel 2595: 	    my $includemsg = $env{'form.includemsg'.$ctr};
1.44      ng       2596: 	    my ($subject,$message,$msgstatus) = ('','','');
1.418     albertel 2597: 	    my $restitle = &Apache::lonnet::gettitle($symb);
                   2598:             my ($feedurl,$showsymb) =
                   2599: 		&get_feedurl_and_symb($symb,$uname,$udom);
                   2600: 	    my $messagetail;
1.62      albertel 2601: 	    if ($includemsg =~ /savemsg|newmsg\Q$ctr\E/) {
1.298     www      2602: 		$subject = $env{'form.msgsub'} if ($includemsg =~ /msgsub/);
1.295     www      2603: 		unless ($subject=~/\w/) { $subject=&mt('Grading Feedback'); }
1.386     raeburn  2604: 		$subject.=' ['.$restitle.']';
1.44      ng       2605: 		my (@msgnum) = split(/,/,$includemsg);
                   2606: 		foreach (@msgnum) {
1.257     albertel 2607: 		    $message.=$env{'form.'.$_} if ($_ =~ /savemsg|newmsg/ && $_ ne '');
1.44      ng       2608: 		}
1.80      ng       2609: 		$message =&Apache::lonfeedback::clear_out_html($message);
1.298     www      2610: 		if ($env{'form.withgrades'.$ctr}) {
                   2611: 		    $message.="\n\nPoint".($pts > 1 ? 's':'').' awarded = '.$pts.' out of '.$wgt;
1.386     raeburn  2612: 		    $messagetail = " for <a href=\"".
1.418     albertel 2613: 		                   $feedurl."?symb=$showsymb\">$env{'form.probTitle'}</a>";
1.386     raeburn  2614: 		}
                   2615: 		$msgstatus = 
                   2616:                     &Apache::lonmsg::user_normal_msg($uname,$udom,$subject,
                   2617: 						     $message.$messagetail,
1.418     albertel 2618:                                                      undef,$feedurl,undef,
1.386     raeburn  2619:                                                      undef,undef,$showsymb,
                   2620:                                                      $restitle);
1.574     bisitz   2621: 		$request->print('<br />'.&mt('Sending message to [_1]',$uname.':'.$udom).': '.
1.296     www      2622: 				$msgstatus);
1.44      ng       2623: 	    }
1.257     albertel 2624: 	    if ($env{'form.collaborator'.$ctr}) {
1.155     albertel 2625: 		my @collabstrs=&Apache::loncommon::get_env_multiple("form.collaborator$ctr");
1.150     albertel 2626: 		foreach my $collabstr (@collabstrs) {
                   2627: 		    my ($part,@collaborators) = split(/:/,$collabstr);
1.310     banghart 2628: 		    foreach my $collaborator (@collaborators) {
1.150     albertel 2629: 			my ($errorflag,$pts,$wgt) = 
1.324     albertel 2630: 			    &saveHandGrade($request,$symb,$collaborator,$udom,$ctr,
1.257     albertel 2631: 					   $env{'form.unamedom'.$ctr},$part);
1.150     albertel 2632: 			if ($errorflag eq 'not_allowed') {
1.362     albertel 2633: 			    $request->print("<span class=\"LC_error\">".&mt('Not allowed to modify grades for [_1]',"$collaborator:$udom")."</span>");
1.150     albertel 2634: 			    next;
1.418     albertel 2635: 			} elsif ($message ne '') {
                   2636: 			    my ($baseurl,$showsymb) = 
                   2637: 				&get_feedurl_and_symb($symb,$collaborator,
                   2638: 						      $udom);
                   2639: 			    if ($env{'form.withgrades'.$ctr}) {
                   2640: 				$messagetail = " for <a href=\"".
1.386     raeburn  2641:                                     $baseurl."?symb=$showsymb\">$env{'form.probTitle'}</a>";
1.150     albertel 2642: 			    }
1.418     albertel 2643: 			    $msgstatus = 
                   2644: 				&Apache::lonmsg::user_normal_msg($collaborator,$udom,$subject,$message.$messagetail,undef,$baseurl,undef,undef,undef,$showsymb,$restitle);
1.104     albertel 2645: 			}
1.44      ng       2646: 		    }
                   2647: 		}
                   2648: 	    }
                   2649: 	    $ctr++;
                   2650: 	}
                   2651:     }
                   2652: 
1.257     albertel 2653:     if ($env{'form.handgrade'} eq 'yes') {
1.119     ng       2654: 	# Keywords sorted in alphabatical order
1.257     albertel 2655: 	my $loginuser = $env{'user.name'}.':'.$env{'user.domain'};
1.119     ng       2656: 	my %keyhash = ();
1.257     albertel 2657: 	$env{'form.keywords'}           =~ s/,\s{0,}|\s+/ /g;
                   2658: 	$env{'form.keywords'}           =~ s/^\s+|\s+$//;
                   2659: 	my (@keywords) = sort(split(/\s+/,$env{'form.keywords'}));
                   2660: 	$env{'form.keywords'} = join(' ',@keywords);
                   2661: 	$keyhash{$symb.'_keywords'}     = $env{'form.keywords'};
                   2662: 	$keyhash{$symb.'_subject'}      = $env{'form.msgsub'};
                   2663: 	$keyhash{$loginuser.'_kwclr'}   = $env{'form.kwclr'};
                   2664: 	$keyhash{$loginuser.'_kwsize'}  = $env{'form.kwsize'};
                   2665: 	$keyhash{$loginuser.'_kwstyle'} = $env{'form.kwstyle'};
1.119     ng       2666: 
                   2667: 	# message center - Order of message gets changed. Blank line is eliminated.
1.257     albertel 2668: 	# New messages are saved in env for the next student.
1.119     ng       2669: 	# All messages are saved in nohist_handgrade.db
                   2670: 	my ($ctr,$idx) = (1,1);
1.257     albertel 2671: 	while ($ctr <= $env{'form.savemsgN'}) {
                   2672: 	    if ($env{'form.savemsg'.$ctr} ne '') {
                   2673: 		$keyhash{$symb.'_savemsg'.$idx} = $env{'form.savemsg'.$ctr};
1.119     ng       2674: 		$idx++;
                   2675: 	    }
                   2676: 	    $ctr++;
1.41      ng       2677: 	}
1.119     ng       2678: 	$ctr = 0;
                   2679: 	while ($ctr < $ngrade) {
1.257     albertel 2680: 	    if ($env{'form.newmsg'.$ctr} ne '') {
                   2681: 		$keyhash{$symb.'_savemsg'.$idx} = $env{'form.newmsg'.$ctr};
                   2682: 		$env{'form.savemsg'.$idx} = $env{'form.newmsg'.$ctr};
1.119     ng       2683: 		$idx++;
                   2684: 	    }
                   2685: 	    $ctr++;
1.41      ng       2686: 	}
1.257     albertel 2687: 	$env{'form.savemsgN'} = --$idx;
                   2688: 	$keyhash{$symb.'_savemsgN'} = $env{'form.savemsgN'};
1.119     ng       2689: 	my $putresult = &Apache::lonnet::put
1.301     albertel 2690: 	    ('nohist_handgrade',\%keyhash,$cdom,$cnum);
1.41      ng       2691:     }
1.44      ng       2692:     # Called by Save & Refresh from Highlight Attribute Window
1.257     albertel 2693:     my (undef,undef,$fullname) = &getclasslist($env{'form.section'},'1');
                   2694:     if ($env{'form.refresh'} eq 'on') {
1.86      ng       2695: 	my ($ctr,$total) = (0,0);
                   2696: 	while ($ctr < $ngrade) {
1.257     albertel 2697: 	    $total++ if  $env{'form.unamedom'.$ctr} ne '';
1.86      ng       2698: 	    $ctr++;
                   2699: 	}
1.257     albertel 2700: 	$env{'form.NTSTU'}=$ngrade;
1.86      ng       2701: 	$ctr = 0;
                   2702: 	while ($ctr < $total) {
1.257     albertel 2703: 	    my $processUser = $env{'form.unamedom'.$ctr};
                   2704: 	    ($env{'form.student'},$env{'form.userdom'}) = split(/:/,$processUser);
                   2705: 	    $env{'form.fullname'} = $$fullname{$processUser};
1.86      ng       2706: 	    &submission($request,$ctr,$total-1);
1.41      ng       2707: 	    $ctr++;
                   2708: 	}
                   2709: 	return '';
                   2710:     }
1.36      ng       2711: 
1.121     ng       2712: # Go directly to grade student - from submission or link from chart page
1.120     ng       2713:     if ($button eq 'Grade Student') {
1.324     albertel 2714: 	(undef,undef,$env{'form.handgrade'},undef,undef) = &showResourceInfo($symb);
1.257     albertel 2715: 	my $processUser = $env{'form.unamedom'.$env{'form.studentNo'}};
                   2716: 	($env{'form.student'},$env{'form.userdom'}) = split(/:/,$processUser);
                   2717: 	$env{'form.fullname'} = $$fullname{$processUser};
1.120     ng       2718: 	&submission($request,0,0);
                   2719: 	return '';
                   2720:     }
                   2721: 
1.44      ng       2722:     # Get the next/previous one or group of students
1.257     albertel 2723:     my $firststu = $env{'form.unamedom0'};
                   2724:     my $laststu = $env{'form.unamedom'.($ngrade-1)};
1.119     ng       2725:     my $ctr = 2;
1.41      ng       2726:     while ($laststu eq '') {
1.257     albertel 2727: 	$laststu  = $env{'form.unamedom'.($ngrade-$ctr)};
1.41      ng       2728: 	$ctr++;
                   2729: 	$laststu = $firststu if ($ctr > $ngrade);
                   2730:     }
1.44      ng       2731: 
1.41      ng       2732:     my (@parsedlist,@nextlist);
                   2733:     my ($nextflg) = 0;
1.524     raeburn  2734:     foreach my $item (sort 
1.294     albertel 2735: 	     {
                   2736: 		 if (lc($$fullname{$a}) ne lc($$fullname{$b})) {
                   2737: 		     return (lc($$fullname{$a}) cmp lc($$fullname{$b}));
                   2738: 		 }
                   2739: 		 return $a cmp $b;
                   2740: 	     } (keys(%$fullname))) {
1.41      ng       2741: 	if ($nextflg == 1 && $button =~ /Next$/) {
1.524     raeburn  2742: 	    push(@parsedlist,$item);
1.41      ng       2743: 	}
1.524     raeburn  2744: 	$nextflg = 1 if ($item eq $laststu);
1.41      ng       2745: 	if ($button eq 'Previous') {
1.524     raeburn  2746: 	    last if ($item eq $firststu);
                   2747: 	    push(@parsedlist,$item);
1.41      ng       2748: 	}
                   2749:     }
                   2750:     $ctr = 0;
                   2751:     @parsedlist = reverse @parsedlist if ($button eq 'Previous');
1.582     raeburn  2752:     my $res_error;
                   2753:     my ($partlist) = &response_type($symb,\$res_error);
                   2754:     if ($res_error) {
                   2755:         $request->print(&navmap_errormsg());
                   2756:         return;
                   2757:     }
1.41      ng       2758:     foreach my $student (@parsedlist) {
1.257     albertel 2759: 	my $submitonly=$env{'form.submitonly'};
1.41      ng       2760: 	my ($uname,$udom) = split(/:/,$student);
1.301     albertel 2761: 	
                   2762: 	if ($submitonly eq 'queued') {
                   2763: 	    my %queue_status = 
                   2764: 		&Apache::bridgetask::get_student_status($symb,$cdom,$cnum,
                   2765: 							$udom,$uname);
                   2766: 	    next if (!defined($queue_status{'gradingqueue'}));
                   2767: 	}
                   2768: 
1.156     albertel 2769: 	if ($submitonly =~ /^(yes|graded|incorrect)$/) {
1.257     albertel 2770: #	    my %record = &Apache::lonnet::restore($symb,$env{'request.course.id'},$udom,$uname);
1.324     albertel 2771: 	    my %status=&student_gradeStatus($symb,$udom,$uname,$partlist);
1.145     albertel 2772: 	    my $submitted = 0;
1.248     albertel 2773: 	    my $ungraded = 0;
                   2774: 	    my $incorrect = 0;
1.524     raeburn  2775: 	    foreach my $item (keys(%status)) {
                   2776: 		$submitted = 1 if ($status{$item} ne 'nothing');
                   2777: 		$ungraded = 1 if ($status{$item} =~ /^ungraded/);
                   2778: 		$incorrect = 1 if ($status{$item} =~ /^incorrect/);
                   2779: 		my ($foo,$partid,$foo1) = split(/\./,$item);
1.145     albertel 2780: 		if ($status{'resource.'.$partid.'.submitted_by'} ne '') {
                   2781: 		    $submitted = 0;
                   2782: 		}
1.41      ng       2783: 	    }
1.156     albertel 2784: 	    next if (!$submitted && ($submitonly eq 'yes' ||
                   2785: 				     $submitonly eq 'incorrect' ||
                   2786: 				     $submitonly eq 'graded'));
1.248     albertel 2787: 	    next if (!$ungraded && ($submitonly eq 'graded'));
                   2788: 	    next if (!$incorrect && $submitonly eq 'incorrect');
1.41      ng       2789: 	}
1.524     raeburn  2790: 	push(@nextlist,$student) if ($ctr < $ntstu);
1.129     ng       2791: 	last if ($ctr == $ntstu);
1.41      ng       2792: 	$ctr++;
                   2793:     }
1.36      ng       2794: 
1.41      ng       2795:     $ctr = 0;
                   2796:     my $total = scalar(@nextlist)-1;
1.39      ng       2797: 
1.524     raeburn  2798:     foreach (sort(@nextlist)) {
1.41      ng       2799: 	my ($uname,$udom,$submitter) = split(/:/);
1.257     albertel 2800: 	$env{'form.student'}  = $uname;
                   2801: 	$env{'form.userdom'}  = $udom;
                   2802: 	$env{'form.fullname'} = $$fullname{$_};
1.41      ng       2803: 	&submission($request,$ctr,$total);
                   2804: 	$ctr++;
                   2805:     }
                   2806:     if ($total < 0) {
1.485     albertel 2807: 	my $the_end = '<h3><span class="LC_info">'.&mt('LON-CAPA User Message').'</span></h3><br />'."\n";
                   2808: 	$the_end.=&mt('<b>Message: </b> No more students for this section or class.').'<br /><br />'."\n";
                   2809: 	$the_end.=&mt('Click on the button below to return to the grading menu.').'<br /><br />'."\n";
1.324     albertel 2810: 	$the_end.=&show_grading_menu_form($symb);
1.41      ng       2811: 	$request->print($the_end);
                   2812:     }
                   2813:     return '';
1.38      ng       2814: }
1.36      ng       2815: 
1.44      ng       2816: #---- Save the score and award for each student, if changed
1.38      ng       2817: sub saveHandGrade {
1.324     albertel 2818:     my ($request,$symb,$stuname,$domain,$newflg,$submitter,$part) = @_;
1.342     banghart 2819:     my @version_parts;
1.104     albertel 2820:     my $usec = &Apache::lonnet::getsection($domain,$stuname,
1.257     albertel 2821: 					   $env{'request.course.id'});
1.104     albertel 2822:     if (!&canmodify($usec)) { return('not_allowed'); }
1.337     banghart 2823:     my %record = &Apache::lonnet::restore($symb,$env{'request.course.id'},$domain,$stuname);
1.251     banghart 2824:     my @parts_graded;
1.77      ng       2825:     my %newrecord  = ();
                   2826:     my ($pts,$wgt) = ('','');
1.269     raeburn  2827:     my %aggregate = ();
                   2828:     my $aggregateflag = 0;
1.301     albertel 2829:     my @parts = split(/:/,$env{'form.partlist'.$newflg});
                   2830:     foreach my $new_part (@parts) {
1.337     banghart 2831: 	#collaborator ($submi may vary for different parts
1.259     banghart 2832: 	if ($submitter && $new_part ne $part) { next; }
                   2833: 	my $dropMenu = $env{'form.GD_SEL'.$newflg.'_'.$new_part};
1.125     ng       2834: 	if ($dropMenu eq 'excused') {
1.259     banghart 2835: 	    if ($record{'resource.'.$new_part.'.solved'} ne 'excused') {
                   2836: 		$newrecord{'resource.'.$new_part.'.solved'} = 'excused';
                   2837: 		if (exists($record{'resource.'.$new_part.'.awarded'})) {
                   2838: 		    $newrecord{'resource.'.$new_part.'.awarded'} = '';
1.58      albertel 2839: 		}
1.364     banghart 2840: 	        $newrecord{'resource.'.$new_part.'.regrader'}="$env{'user.name'}:$env{'user.domain'}";
1.58      albertel 2841: 	    }
1.125     ng       2842: 	} elsif ($dropMenu eq 'reset status'
1.259     banghart 2843: 		 && exists($record{'resource.'.$new_part.'.solved'})) { #don't bother if no old records -> no attempts
1.524     raeburn  2844: 	    foreach my $key (keys(%record)) {
1.259     banghart 2845: 		if ($key=~/^resource\.\Q$new_part\E\./) { $newrecord{$key} = ''; }
1.197     albertel 2846: 	    }
1.259     banghart 2847: 	    $newrecord{'resource.'.$new_part.'.regrader'}=
1.257     albertel 2848: 		"$env{'user.name'}:$env{'user.domain'}";
1.270     albertel 2849:             my $totaltries = $record{'resource.'.$part.'.tries'};
                   2850: 
                   2851:             my %last_resets = &get_last_resets($symb,$env{'request.course.id'},
                   2852: 					       [$new_part]);
                   2853:             my $aggtries =$totaltries;
1.269     raeburn  2854:             if ($last_resets{$new_part}) {
1.270     albertel 2855:                 $aggtries = &get_num_tries(\%record,$last_resets{$new_part},
                   2856: 					   $new_part);
1.269     raeburn  2857:             }
1.270     albertel 2858: 
                   2859:             my $solvedstatus = $record{'resource.'.$new_part.'.solved'};
1.269     raeburn  2860:             if ($aggtries > 0) {
1.327     albertel 2861:                 &decrement_aggs($symb,$new_part,\%aggregate,$aggtries,$totaltries,$solvedstatus);
1.269     raeburn  2862:                 $aggregateflag = 1;
                   2863:             }
1.125     ng       2864: 	} elsif ($dropMenu eq '') {
1.259     banghart 2865: 	    $pts = ($env{'form.GD_BOX'.$newflg.'_'.$new_part} ne '' ? 
                   2866: 		    $env{'form.GD_BOX'.$newflg.'_'.$new_part} : 
                   2867: 		    $env{'form.RADVAL'.$newflg.'_'.$new_part});
                   2868: 	    if ($pts eq '' && $env{'form.GD_SEL'.$newflg.'_'.$new_part} eq '') {
1.153     albertel 2869: 		next;
                   2870: 	    }
1.259     banghart 2871: 	    $wgt = $env{'form.WGT'.$newflg.'_'.$new_part} eq '' ? 1 : 
                   2872: 		$env{'form.WGT'.$newflg.'_'.$new_part};
1.41      ng       2873: 	    my $partial= $pts/$wgt;
1.259     banghart 2874: 	    if ($partial eq $record{'resource.'.$new_part.'.awarded'}) {
1.153     albertel 2875: 		#do not update score for part if not changed.
1.346     banghart 2876:                 &handback_files($request,$symb,$stuname,$domain,$newflg,$new_part,\%newrecord);
1.153     albertel 2877: 		next;
1.251     banghart 2878: 	    } else {
1.524     raeburn  2879: 	        push(@parts_graded,$new_part);
1.153     albertel 2880: 	    }
1.259     banghart 2881: 	    if ($record{'resource.'.$new_part.'.awarded'} ne $partial) {
                   2882: 		$newrecord{'resource.'.$new_part.'.awarded'}  = $partial;
1.153     albertel 2883: 	    }
1.259     banghart 2884: 	    my $reckey = 'resource.'.$new_part.'.solved';
1.41      ng       2885: 	    if ($partial == 0) {
1.153     albertel 2886: 		if ($record{$reckey} ne 'incorrect_by_override') {
                   2887: 		    $newrecord{$reckey} = 'incorrect_by_override';
                   2888: 		}
1.41      ng       2889: 	    } else {
1.153     albertel 2890: 		if ($record{$reckey} ne 'correct_by_override') {
                   2891: 		    $newrecord{$reckey} = 'correct_by_override';
                   2892: 		}
                   2893: 	    }	    
                   2894: 	    if ($submitter && 
1.259     banghart 2895: 		($record{'resource.'.$new_part.'.submitted_by'} ne $submitter)) {
                   2896: 		$newrecord{'resource.'.$new_part.'.submitted_by'} = $submitter;
1.41      ng       2897: 	    }
1.259     banghart 2898: 	    $newrecord{'resource.'.$new_part.'.regrader'}=
1.257     albertel 2899: 		"$env{'user.name'}:$env{'user.domain'}";
1.41      ng       2900: 	}
1.259     banghart 2901: 	# unless problem has been graded, set flag to version the submitted files
1.305     banghart 2902: 	unless ($record{'resource.'.$new_part.'.solved'} =~ /^correct_/  || 
                   2903: 	        $record{'resource.'.$new_part.'.solved'} eq 'incorrect_by_override' ||
                   2904: 	        $dropMenu eq 'reset status')
                   2905: 	   {
1.524     raeburn  2906: 	    push(@version_parts,$new_part);
1.259     banghart 2907: 	}
1.41      ng       2908:     }
1.301     albertel 2909:     my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   2910:     my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   2911: 
1.344     albertel 2912:     if (%newrecord) {
                   2913:         if (@version_parts) {
1.364     banghart 2914:             my @changed_keys = &version_portfiles(\%record, \@parts_graded, 
                   2915:                                 $env{'request.course.id'}, $symb, $domain, $stuname, \@version_parts);
1.344     albertel 2916: 	    @newrecord{@changed_keys} = @record{@changed_keys};
1.367     albertel 2917: 	    foreach my $new_part (@version_parts) {
                   2918: 		&handback_files($request,$symb,$stuname,$domain,$newflg,
                   2919: 				$new_part,\%newrecord);
                   2920: 	    }
1.259     banghart 2921:         }
1.44      ng       2922: 	&Apache::lonnet::cstore(\%newrecord,$symb,
1.257     albertel 2923: 				$env{'request.course.id'},$domain,$stuname);
1.380     albertel 2924: 	&check_and_remove_from_queue(\@parts,\%record,\%newrecord,$symb,
                   2925: 				     $cdom,$cnum,$domain,$stuname);
1.41      ng       2926:     }
1.269     raeburn  2927:     if ($aggregateflag) {
                   2928:         &Apache::lonnet::cinc('nohist_resourcetracker',\%aggregate,
1.301     albertel 2929: 			      $cdom,$cnum);
1.269     raeburn  2930:     }
1.301     albertel 2931:     return ('',$pts,$wgt);
1.36      ng       2932: }
1.322     albertel 2933: 
1.380     albertel 2934: sub check_and_remove_from_queue {
                   2935:     my ($parts,$record,$newrecord,$symb,$cdom,$cnum,$domain,$stuname) = @_;
                   2936:     my @ungraded_parts;
                   2937:     foreach my $part (@{$parts}) {
                   2938: 	if (    $record->{   'resource.'.$part.'.awarded'} eq ''
                   2939: 	     && $record->{   'resource.'.$part.'.solved' } ne 'excused'
                   2940: 	     && $newrecord->{'resource.'.$part.'.awarded'} eq ''
                   2941: 	     && $newrecord->{'resource.'.$part.'.solved' } ne 'excused'
                   2942: 		) {
                   2943: 	    push(@ungraded_parts, $part);
                   2944: 	}
                   2945:     }
                   2946:     if ( !@ungraded_parts ) {
                   2947: 	&Apache::bridgetask::remove_from_queue('gradingqueue',$symb,$cdom,
                   2948: 					       $cnum,$domain,$stuname);
                   2949:     }
                   2950: }
                   2951: 
1.337     banghart 2952: sub handback_files {
                   2953:     my ($request,$symb,$stuname,$domain,$newflg,$new_part,$newrecord) = @_;
1.517     raeburn  2954:     my $portfolio_root = '/userfiles/portfolio';
1.582     raeburn  2955:     my $res_error;
                   2956:     my ($partlist,$handgrade,$responseType) = &response_type($symb,\$res_error);
                   2957:     if ($res_error) {
                   2958:         $request->print('<br />'.&navmap_errormsg().'<br />');
                   2959:         return;
                   2960:     }
1.375     albertel 2961:     my @part_response_id = &flatten_responseType($responseType);
                   2962:     foreach my $part_response_id (@part_response_id) {
                   2963:     	my ($part_id,$resp_id) = @{ $part_response_id };
                   2964: 	my $part_resp = join('_',@{ $part_response_id });
1.337     banghart 2965:             if (($env{'form.'.$newflg.'_'.$part_resp.'_returndoc1'}) && ($new_part == $part_id)) {
                   2966:                 # if multiple files are uploaded names will be 'returndoc2','returndoc3'
                   2967:                 my $file_counter = 1;
1.367     albertel 2968: 		my $file_msg;
1.337     banghart 2969:                 while ($env{'form.'.$newflg.'_'.$part_resp.'_returndoc'.$file_counter}) {
                   2970:                     my $fname=$env{'form.'.$newflg.'_'.$part_resp.'_returndoc'.$file_counter.'.filename'};
1.338     banghart 2971:                     my ($directory,$answer_file) = 
                   2972:                         ($env{'form.'.$newflg.'_'.$part_resp.'_origdoc'.$file_counter} =~ /^(.*?)([^\/]*)$/);
                   2973:                     my ($answer_name,$answer_ver,$answer_ext) =
                   2974: 		        &file_name_version_ext($answer_file);
1.355     banghart 2975: 		    my ($portfolio_path) = ($directory =~ /^.+$stuname\/portfolio(.*)/);
1.517     raeburn  2976:                     my $getpropath = 1;
                   2977: 		    my @dir_list = &Apache::lonnet::dirlist($portfolio_root.$portfolio_path,$domain,$stuname,$getpropath);
1.338     banghart 2978: 		    my $version = &get_next_version($answer_name, $answer_ext, \@dir_list);
1.355     banghart 2979:                     # fix file name
                   2980:                     my ($save_file_name) = (($directory.$answer_name.".$version.".$answer_ext) =~ /^.+\/${stuname}\/(.*)/);
                   2981:                     my $result=&Apache::lonnet::finishuserfileupload($stuname,$domain,
                   2982:             	                                $newflg.'_'.$part_resp.'_returndoc'.$file_counter,
                   2983:             	                                $save_file_name);
1.337     banghart 2984:                     if ($result !~ m|^/uploaded/|) {
1.536     raeburn  2985:                         $request->print('<br /><span class="LC_error">'.
                   2986:                             &mt('An error occurred ([_1]) while trying to upload [_2].',
                   2987:                                 $result,$newflg.'_'.$part_resp.'_returndoc'.$file_counter).
                   2988:                                         '</span>');
1.356     banghart 2989:                     } else {
1.360     banghart 2990:                         # mark the file as read only
                   2991:                         my @files = ($save_file_name);
1.372     albertel 2992:                         my @what = ($symb,$env{'request.course.id'},'handback');
1.360     banghart 2993:                         &Apache::lonnet::mark_as_readonly($domain,$stuname,\@files,\@what);
1.367     albertel 2994: 			if (exists($$newrecord{"resource.$new_part.$resp_id.handback"})) {
                   2995: 			    $$newrecord{"resource.$new_part.$resp_id.handback"}.=',';
                   2996: 			}
                   2997:                         $$newrecord{"resource.$new_part.$resp_id.handback"} .= $save_file_name;
                   2998: 			$file_msg.= "\n".'<br /><span class="LC_filename"><a href="/uploaded/'."$domain/$stuname/".$save_file_name.'">'.$save_file_name."</a></span><br />";
                   2999: 
1.337     banghart 3000:                     }
                   3001:                     $request->print("<br />".$fname." will be the uploaded file name");
1.354     albertel 3002:                     $request->print(" ".$env{'form.'.$newflg.'_'.$part_resp.'_origdoc'.$file_counter});
1.337     banghart 3003:                     $file_counter++;
                   3004:                 }
1.367     albertel 3005: 		my $subject = "File Handed Back by Instructor ";
                   3006: 		my $message = "A file has been returned that was originally submitted in reponse to: <br />";
                   3007: 		$message .= "<strong>".&Apache::lonnet::gettitle($symb)."</strong><br />";
                   3008: 		$message .= ' The returned file(s) are named: '. $file_msg;
                   3009: 		$message .= " and can be found in your portfolio space.";
1.418     albertel 3010: 		my ($feedurl,$showsymb) = 
                   3011: 		    &get_feedurl_and_symb($symb,$domain,$stuname);
1.386     raeburn  3012:                 my $restitle = &Apache::lonnet::gettitle($symb);
                   3013: 		my $msgstatus = 
                   3014:                    &Apache::lonmsg::user_normal_msg($stuname,$domain,$subject.
                   3015: 			 ' (File Returned) ['.$restitle.']',$message,undef,
1.418     albertel 3016:                          $feedurl,undef,undef,undef,$showsymb,$restitle);
1.337     banghart 3017:             }
                   3018:         }
1.338     banghart 3019:     return;
1.337     banghart 3020: }
                   3021: 
1.418     albertel 3022: sub get_feedurl_and_symb {
                   3023:     my ($symb,$uname,$udom) = @_;
                   3024:     my (undef,undef,$url) = &Apache::lonnet::decode_symb($symb);
                   3025:     $url = &Apache::lonnet::clutter($url);
                   3026:     my $encrypturl=&Apache::lonnet::EXT('resource.0.encrypturl',
                   3027: 					$symb,$udom,$uname);
                   3028:     if ($encrypturl =~ /^yes$/i) {
                   3029: 	&Apache::lonenc::encrypted(\$url,1);
                   3030: 	&Apache::lonenc::encrypted(\$symb,1);
                   3031:     }
                   3032:     return ($url,$symb);
                   3033: }
                   3034: 
1.313     banghart 3035: sub get_submitted_files {
                   3036:     my ($udom,$uname,$partid,$respid,$record) = @_;
                   3037:     my @files;
                   3038:     if ($$record{"resource.$partid.$respid.portfiles"}) {
                   3039:         my $file_url = '/uploaded/'.$udom.'/'.$uname.'/portfolio';
                   3040:         foreach my $file (split(',',$$record{"resource.$partid.$respid.portfiles"})) {
                   3041:     	    push(@files,$file_url.$file);
                   3042:         }
                   3043:     }
                   3044:     if ($$record{"resource.$partid.$respid.uploadedurl"}) {
                   3045:         push(@files,$$record{"resource.$partid.$respid.uploadedurl"});
                   3046:     }
                   3047:     return (\@files);
                   3048: }
1.322     albertel 3049: 
1.269     raeburn  3050: # ----------- Provides number of tries since last reset.
                   3051: sub get_num_tries {
                   3052:     my ($record,$last_reset,$part) = @_;
                   3053:     my $timestamp = '';
                   3054:     my $num_tries = 0;
                   3055:     if ($$record{'version'}) {
                   3056:         for (my $version=$$record{'version'};$version>=1;$version--) {
                   3057:             if (exists($$record{$version.':resource.'.$part.'.solved'})) {
                   3058:                 $timestamp = $$record{$version.':timestamp'};
                   3059:                 if ($timestamp > $last_reset) {
                   3060:                     $num_tries ++;
                   3061:                 } else {
                   3062:                     last;
                   3063:                 }
                   3064:             }
                   3065:         }
                   3066:     }
                   3067:     return $num_tries;
                   3068: }
                   3069: 
                   3070: # ----------- Determine decrements required in aggregate totals 
                   3071: sub decrement_aggs {
                   3072:     my ($symb,$part,$aggregate,$aggtries,$totaltries,$solvedstatus) = @_;
                   3073:     my %decrement = (
                   3074:                         attempts => 0,
                   3075:                         users => 0,
                   3076:                         correct => 0
                   3077:                     );
                   3078:     $decrement{'attempts'} = $aggtries;
                   3079:     if ($solvedstatus =~ /^correct/) {
                   3080:         $decrement{'correct'} = 1;
                   3081:     }
                   3082:     if ($aggtries == $totaltries) {
                   3083:         $decrement{'users'} = 1;
                   3084:     }
1.524     raeburn  3085:     foreach my $type (keys(%decrement)) {
1.269     raeburn  3086:         $$aggregate{$symb."\0".$part."\0".$type} = -$decrement{$type};
                   3087:     }
                   3088:     return;
                   3089: }
                   3090: 
                   3091: # ----------- Determine timestamps for last reset of aggregate totals for parts  
                   3092: sub get_last_resets {
1.270     albertel 3093:     my ($symb,$courseid,$partids) =@_;
                   3094:     my %last_resets;
1.269     raeburn  3095:     my $cdom = $env{'course.'.$courseid.'.domain'};
                   3096:     my $cname = $env{'course.'.$courseid.'.num'};
1.271     albertel 3097:     my @keys;
                   3098:     foreach my $part (@{$partids}) {
                   3099: 	push(@keys,"$symb\0$part\0resettime");
                   3100:     }
                   3101:     my %results=&Apache::lonnet::get('nohist_resourcetracker',\@keys,
                   3102: 				     $cdom,$cname);
                   3103:     foreach my $part (@{$partids}) {
                   3104: 	$last_resets{$part}=$results{"$symb\0$part\0resettime"};
1.269     raeburn  3105:     }
1.270     albertel 3106:     return %last_resets;
1.269     raeburn  3107: }
                   3108: 
1.251     banghart 3109: # ----------- Handles creating versions for portfolio files as answers
                   3110: sub version_portfiles {
1.343     banghart 3111:     my ($record, $parts_graded, $courseid, $symb, $domain, $stu_name, $v_flag) = @_;
1.263     banghart 3112:     my $version_parts = join('|',@$v_flag);
1.343     banghart 3113:     my @returned_keys;
1.255     banghart 3114:     my $parts = join('|', @$parts_graded);
1.517     raeburn  3115:     my $portfolio_root = '/userfiles/portfolio';
1.277     albertel 3116:     foreach my $key (keys(%$record)) {
1.259     banghart 3117:         my $new_portfiles;
1.263     banghart 3118:         if ($key =~ /^resource\.($version_parts)\./ && $key =~ /\.portfiles$/ ) {
1.342     banghart 3119:             my @versioned_portfiles;
1.367     albertel 3120:             my @portfiles = split(/\s*,\s*/,$$record{$key});
1.252     banghart 3121:             foreach my $file (@portfiles) {
1.306     banghart 3122:                 &Apache::lonnet::unmark_as_readonly($domain,$stu_name,[$symb,$env{'request.course.id'}],$file);
1.304     albertel 3123:                 my ($directory,$answer_file) =($file =~ /^(.*?)([^\/]*)$/);
                   3124: 		my ($answer_name,$answer_ver,$answer_ext) =
                   3125: 		    &file_name_version_ext($answer_file);
1.517     raeburn  3126:                 my $getpropath = 1;    
                   3127:                 my @dir_list = &Apache::lonnet::dirlist($portfolio_root.$directory,$domain,$stu_name,$getpropath);
1.342     banghart 3128:                 my $version = &get_next_version($answer_name, $answer_ext, \@dir_list);
1.306     banghart 3129:                 my $new_answer = &version_selected_portfile($domain, $stu_name, $directory, $answer_file, $version);
                   3130:                 if ($new_answer ne 'problem getting file') {
1.342     banghart 3131:                     push(@versioned_portfiles, $directory.$new_answer);
1.306     banghart 3132:                     &Apache::lonnet::mark_as_readonly($domain,$stu_name,
1.367     albertel 3133:                         [$directory.$new_answer],
1.306     banghart 3134:                         [$symb,$env{'request.course.id'},'graded']);
1.259     banghart 3135:                 }
1.252     banghart 3136:             }
1.343     banghart 3137:             $$record{$key} = join(',',@versioned_portfiles);
                   3138:             push(@returned_keys,$key);
1.251     banghart 3139:         }
                   3140:     } 
1.343     banghart 3141:     return (@returned_keys);   
1.305     banghart 3142: }
                   3143: 
1.307     banghart 3144: sub get_next_version {
1.341     banghart 3145:     my ($answer_name, $answer_ext, $dir_list) = @_;
1.307     banghart 3146:     my $version;
                   3147:     foreach my $row (@$dir_list) {
                   3148:         my ($file) = split(/\&/,$row,2);
                   3149:         my ($file_name,$file_version,$file_ext) =
                   3150: 	    &file_name_version_ext($file);
                   3151:         if (($file_name eq $answer_name) && 
                   3152: 	    ($file_ext eq $answer_ext)) {
                   3153:                 # gets here if filename and extension match, regardless of version
                   3154:                 if ($file_version ne '') {
                   3155:                 # a versioned file is found  so save it for later
                   3156:                 if ($file_version > $version) {
                   3157: 		    $version = $file_version;
                   3158: 	        }
                   3159:             }
                   3160:         }
                   3161:     } 
                   3162:     $version ++;
                   3163:     return($version);
                   3164: }
                   3165: 
1.305     banghart 3166: sub version_selected_portfile {
1.306     banghart 3167:     my ($domain,$stu_name,$directory,$file_name,$version) = @_;
                   3168:     my ($answer_name,$answer_ver,$answer_ext) =
                   3169:         &file_name_version_ext($file_name);
                   3170:     my $new_answer;
                   3171:     $env{'form.copy'} = &Apache::lonnet::getfile("/uploaded/$domain/$stu_name/portfolio$directory$file_name");
                   3172:     if($env{'form.copy'} eq '-1') {
                   3173:         $new_answer = 'problem getting file';
                   3174:     } else {
                   3175:         $new_answer = $answer_name.'.'.$version.'.'.$answer_ext;
                   3176:         my $copy_result = &Apache::lonnet::finishuserfileupload(
                   3177:                             $stu_name,$domain,'copy',
                   3178: 		        '/portfolio'.$directory.$new_answer);
                   3179:     }    
                   3180:     return ($new_answer);
1.251     banghart 3181: }
                   3182: 
1.304     albertel 3183: sub file_name_version_ext {
                   3184:     my ($file)=@_;
                   3185:     my @file_parts = split(/\./, $file);
                   3186:     my ($name,$version,$ext);
                   3187:     if (@file_parts > 1) {
                   3188: 	$ext=pop(@file_parts);
                   3189: 	if (@file_parts > 1 && $file_parts[-1] =~ /^\d+$/) {
                   3190: 	    $version=pop(@file_parts);
                   3191: 	}
                   3192: 	$name=join('.',@file_parts);
                   3193:     } else {
                   3194: 	$name=join('.',@file_parts);
                   3195:     }
                   3196:     return($name,$version,$ext);
                   3197: }
                   3198: 
1.44      ng       3199: #--------------------------------------------------------------------------------------
                   3200: #
                   3201: #-------------------------- Next few routines handles grading by section or whole class
                   3202: #
                   3203: #--- Javascript to handle grading by section or whole class
1.42      ng       3204: sub viewgrades_js {
                   3205:     my ($request) = shift;
                   3206: 
1.539     riegler  3207:     my $alertmsg = &mt('A number equal or greater than 0 is expected. Entered value = ');
1.41      ng       3208:     $request->print(<<VIEWJAVASCRIPT);
                   3209: <script type="text/javascript" language="javascript">
1.45      ng       3210:    function writePoint(partid,weight,point) {
1.125     ng       3211: 	var radioButton = document.classgrade["RADVAL_"+partid];
                   3212: 	var textbox = document.classgrade["TEXTVAL_"+partid];
1.42      ng       3213: 	if (point == "textval") {
1.125     ng       3214: 	    point = document.classgrade["TEXTVAL_"+partid].value;
1.109     matthew  3215: 	    if (isNaN(point) || parseFloat(point) < 0) {
1.539     riegler  3216: 		alert("$alertmsg"+parseFloat(point));
1.42      ng       3217: 		var resetbox = false;
                   3218: 		for (var i=0; i<radioButton.length; i++) {
                   3219: 		    if (radioButton[i].checked) {
                   3220: 			textbox.value = i;
                   3221: 			resetbox = true;
                   3222: 		    }
                   3223: 		}
                   3224: 		if (!resetbox) {
                   3225: 		    textbox.value = "";
                   3226: 		}
                   3227: 		return;
                   3228: 	    }
1.109     matthew  3229: 	    if (parseFloat(point) > parseFloat(weight)) {
                   3230: 		var resp = confirm("You entered a value ("+parseFloat(point)+
1.44      ng       3231: 				   ") greater than the weight for the part. Accept?");
                   3232: 		if (resp == false) {
                   3233: 		    textbox.value = "";
                   3234: 		    return;
                   3235: 		}
                   3236: 	    }
1.42      ng       3237: 	    for (var i=0; i<radioButton.length; i++) {
                   3238: 		radioButton[i].checked=false;
1.109     matthew  3239: 		if (parseFloat(point) == i) {
1.42      ng       3240: 		    radioButton[i].checked=true;
                   3241: 		}
                   3242: 	    }
1.41      ng       3243: 
1.42      ng       3244: 	} else {
1.125     ng       3245: 	    textbox.value = parseFloat(point);
1.42      ng       3246: 	}
1.41      ng       3247: 	for (i=0;i<document.classgrade.total.value;i++) {
1.125     ng       3248: 	    var user = document.classgrade["ctr"+i].value;
1.289     albertel 3249: 	    user = user.replace(new RegExp(':', 'g'),"_");
1.125     ng       3250: 	    var scorename = document.classgrade["GD_"+user+"_"+partid+"_awarded"];
                   3251: 	    var saveval   = document.classgrade["GD_"+user+"_"+partid+"_solved_s"].value;
                   3252: 	    var selname   = document.classgrade["GD_"+user+"_"+partid+"_solved"];
1.42      ng       3253: 	    if (saveval != "correct") {
                   3254: 		scorename.value = point;
1.43      ng       3255: 		if (selname[0].selected != true) {
                   3256: 		    selname[0].selected = true;
                   3257: 		}
1.42      ng       3258: 	    }
                   3259: 	}
1.125     ng       3260: 	document.classgrade["SELVAL_"+partid][0].selected = true;
1.42      ng       3261:     }
                   3262: 
                   3263:     function writeRadText(partid,weight) {
1.125     ng       3264: 	var selval   = document.classgrade["SELVAL_"+partid];
                   3265: 	var radioButton = document.classgrade["RADVAL_"+partid];
1.265     www      3266:         var override = document.classgrade["FORCE_"+partid].checked;
1.125     ng       3267: 	var textbox = document.classgrade["TEXTVAL_"+partid];
                   3268: 	if (selval[1].selected || selval[2].selected) {
1.42      ng       3269: 	    for (var i=0; i<radioButton.length; i++) {
                   3270: 		radioButton[i].checked=false;
                   3271: 
                   3272: 	    }
                   3273: 	    textbox.value = "";
                   3274: 
                   3275: 	    for (i=0;i<document.classgrade.total.value;i++) {
1.125     ng       3276: 		var user = document.classgrade["ctr"+i].value;
1.289     albertel 3277: 		user = user.replace(new RegExp(':', 'g'),"_");
1.125     ng       3278: 		var scorename = document.classgrade["GD_"+user+"_"+partid+"_awarded"];
                   3279: 		var saveval   = document.classgrade["GD_"+user+"_"+partid+"_solved_s"].value;
                   3280: 		var selname   = document.classgrade["GD_"+user+"_"+partid+"_solved"];
1.265     www      3281: 		if ((saveval != "correct") || override) {
1.42      ng       3282: 		    scorename.value = "";
1.125     ng       3283: 		    if (selval[1].selected) {
                   3284: 			selname[1].selected = true;
                   3285: 		    } else {
                   3286: 			selname[2].selected = true;
                   3287: 			if (Number(document.classgrade["GD_"+user+"_"+partid+"_tries"].value)) 
                   3288: 			{document.classgrade["GD_"+user+"_"+partid+"_tries"].value = '0';}
                   3289: 		    }
1.42      ng       3290: 		}
                   3291: 	    }
1.43      ng       3292: 	} else {
                   3293: 	    for (i=0;i<document.classgrade.total.value;i++) {
1.125     ng       3294: 		var user = document.classgrade["ctr"+i].value;
1.289     albertel 3295: 		user = user.replace(new RegExp(':', 'g'),"_");
1.125     ng       3296: 		var scorename = document.classgrade["GD_"+user+"_"+partid+"_awarded"];
                   3297: 		var saveval   = document.classgrade["GD_"+user+"_"+partid+"_solved_s"].value;
                   3298: 		var selname   = document.classgrade["GD_"+user+"_"+partid+"_solved"];
1.265     www      3299: 		if ((saveval != "correct") || override) {
1.125     ng       3300: 		    scorename.value = document.classgrade["GD_"+user+"_"+partid+"_awarded_s"].value;
1.43      ng       3301: 		    selname[0].selected = true;
                   3302: 		}
                   3303: 	    }
                   3304: 	}	    
1.42      ng       3305:     }
                   3306: 
                   3307:     function changeSelect(partid,user) {
1.125     ng       3308: 	var selval = document.classgrade["GD_"+user+'_'+partid+"_solved"];
                   3309: 	var textbox = document.classgrade["GD_"+user+'_'+partid+"_awarded"];
1.44      ng       3310: 	var point  = textbox.value;
1.125     ng       3311: 	var weight = document.classgrade["weight_"+partid].value;
1.44      ng       3312: 
1.109     matthew  3313: 	if (isNaN(point) || parseFloat(point) < 0) {
1.539     riegler  3314: 	    alert("$alertmsg"+parseFloat(point));
1.44      ng       3315: 	    textbox.value = "";
                   3316: 	    return;
                   3317: 	}
1.109     matthew  3318: 	if (parseFloat(point) > parseFloat(weight)) {
                   3319: 	    var resp = confirm("You entered a value ("+parseFloat(point)+
1.44      ng       3320: 			       ") greater than the weight of the part. Accept?");
                   3321: 	    if (resp == false) {
                   3322: 		textbox.value = "";
                   3323: 		return;
                   3324: 	    }
                   3325: 	}
1.42      ng       3326: 	selval[0].selected = true;
                   3327:     }
                   3328: 
                   3329:     function changeOneScore(partid,user) {
1.125     ng       3330: 	var selval = document.classgrade["GD_"+user+'_'+partid+"_solved"];
                   3331: 	if (selval[1].selected || selval[2].selected) {
                   3332: 	    document.classgrade["GD_"+user+'_'+partid+"_awarded"].value = "";
                   3333: 	    if (selval[2].selected) {
                   3334: 		document.classgrade["GD_"+user+'_'+partid+"_tries"].value = "0";
                   3335: 	    }
1.269     raeburn  3336:         }
1.42      ng       3337:     }
                   3338: 
                   3339:     function resetEntry(numpart) {
                   3340: 	for (ctpart=0;ctpart<numpart;ctpart++) {
1.125     ng       3341: 	    var partid = document.classgrade["partid_"+ctpart].value;
                   3342: 	    var radioButton = document.classgrade["RADVAL_"+partid];
                   3343: 	    var textbox = document.classgrade["TEXTVAL_"+partid];
                   3344: 	    var selval  = document.classgrade["SELVAL_"+partid];
1.42      ng       3345: 	    for (var i=0; i<radioButton.length; i++) {
                   3346: 		radioButton[i].checked=false;
                   3347: 
                   3348: 	    }
                   3349: 	    textbox.value = "";
                   3350: 	    selval[0].selected = true;
                   3351: 
                   3352: 	    for (i=0;i<document.classgrade.total.value;i++) {
1.125     ng       3353: 		var user = document.classgrade["ctr"+i].value;
1.289     albertel 3354: 		user = user.replace(new RegExp(':', 'g'),"_");
1.125     ng       3355: 		var resetscore = document.classgrade["GD_"+user+"_"+partid+"_awarded"];
                   3356: 		resetscore.value = document.classgrade["GD_"+user+"_"+partid+"_awarded_s"].value;
                   3357: 		var resettries = document.classgrade["GD_"+user+"_"+partid+"_tries"];
                   3358: 		resettries.value = document.classgrade["GD_"+user+"_"+partid+"_tries_s"].value;
                   3359: 		var saveselval   = document.classgrade["GD_"+user+"_"+partid+"_solved_s"].value;
                   3360: 		var selname   = document.classgrade["GD_"+user+"_"+partid+"_solved"];
1.42      ng       3361: 		if (saveselval == "excused") {
1.43      ng       3362: 		    if (selname[1].selected == false) { selname[1].selected = true;}
1.42      ng       3363: 		} else {
1.43      ng       3364: 		    if (selname[0].selected == false) {selname[0].selected = true};
1.42      ng       3365: 		}
                   3366: 	    }
1.41      ng       3367: 	}
1.42      ng       3368:     }
                   3369: 
1.41      ng       3370: </script>
                   3371: VIEWJAVASCRIPT
1.42      ng       3372: }
                   3373: 
1.44      ng       3374: #--- show scores for a section or whole class w/ option to change/update a score
1.42      ng       3375: sub viewgrades {
                   3376:     my ($request) = shift;
                   3377:     &viewgrades_js($request);
1.41      ng       3378: 
1.324     albertel 3379:     my ($symb) = &get_symb($request);
1.168     albertel 3380:     #need to make sure we have the correct data for later EXT calls, 
                   3381:     #thus invalidate the cache
                   3382:     &Apache::lonnet::devalidatecourseresdata(
1.257     albertel 3383:                  $env{'course.'.$env{'request.course.id'}.'.num'},
                   3384:                  $env{'course.'.$env{'request.course.id'}.'.domain'});
1.168     albertel 3385:     &Apache::lonnet::clear_EXT_cache_status();
                   3386: 
1.398     albertel 3387:     my $result='<h3><span class="LC_info">'.&mt('Manual Grading').'</span></h3>';
1.485     albertel 3388:     $result.='<h4>'.&mt('<b>Current Resource: </b>[_1]',$env{'form.probTitle'}).'</h4>'."\n";
1.41      ng       3389: 
                   3390:     #view individual student submission form - called using Javascript viewOneStudent
1.324     albertel 3391:     $result.=&jscriptNform($symb);
1.41      ng       3392: 
1.44      ng       3393:     #beginning of class grading form
1.442     banghart 3394:     my $stu_status = join(':',&Apache::loncommon::get_env_multiple('form.Status'));
1.41      ng       3395:     $result.= '<form action="/adm/grades" method="post" name="classgrade">'."\n".
1.418     albertel 3396: 	'<input type="hidden" name="symb"    value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
1.38      ng       3397: 	'<input type="hidden" name="command" value="editgrades" />'."\n".
1.432     banghart 3398: 	&build_section_inputs().
1.257     albertel 3399: 	'<input type="hidden" name="saveState" value="'.$env{'form.saveState'}.'" />'."\n".
1.442     banghart 3400: 	'<input type="hidden" name="Status" value="'.$env{'stu_status'}.'" />'."\n".
1.257     albertel 3401: 	'<input type="hidden" name="probTitle" value="'.$env{'form.probTitle'}.'" />'."\n";
1.72      ng       3402: 
1.560     raeburn  3403:     my ($common_header,$specific_header);
1.257     albertel 3404:     if ($env{'form.section'} eq 'all') {
1.560     raeburn  3405: 	$common_header = &mt('Assign Common Grade to Class');
                   3406:         $specific_header = &mt('Assign Grade to Specific Students in Class');
1.257     albertel 3407:     } elsif ($env{'form.section'} eq 'none') {
1.560     raeburn  3408:         $common_header = &mt('Assign Common Grade to Students in no Section');
                   3409: 	$specific_header = &mt('Assign Grade to Specific Students in no Section');
1.52      albertel 3410:     } else {
1.560     raeburn  3411:         my $section_display = join (", ",&Apache::loncommon::get_env_multiple('form.section'));
                   3412:         $common_header = &mt('Assign Common Grade to Students in Section(s) [_1]',$section_display);
                   3413: 	$specific_header = &mt('Assign Grade to Specific Students in Section(s) [_1]',$section_display);
1.52      albertel 3414:     }
1.560     raeburn  3415:     $result.= '<h3>'.$common_header.'</h3>'.&Apache::loncommon::start_data_table();
1.44      ng       3416:     #radio buttons/text box for assigning points for a section or class.
                   3417:     #handles different parts of a problem
1.582     raeburn  3418:     my $res_error;
                   3419:     my ($partlist,$handgrade,$responseType) = &response_type($symb,\$res_error);
                   3420:     if ($res_error) {
                   3421:         return &navmap_errormsg();
                   3422:     }
1.42      ng       3423:     my %weight = ();
                   3424:     my $ctsparts = 0;
1.45      ng       3425:     my %seen = ();
1.375     albertel 3426:     my @part_response_id = &flatten_responseType($responseType);
                   3427:     foreach my $part_response_id (@part_response_id) {
                   3428:     	my ($partid,$respid) = @{ $part_response_id };
                   3429: 	my $part_resp = join('_',@{ $part_response_id });
1.45      ng       3430: 	next if $seen{$partid};
                   3431: 	$seen{$partid}++;
1.375     albertel 3432: 	my $handgrade=$$handgrade{$part_resp};
1.42      ng       3433: 	my $wgt = &Apache::lonnet::EXT('resource.'.$partid.'.weight',$symb);
                   3434: 	$weight{$partid} = $wgt eq '' ? '1' : $wgt;
                   3435: 
1.324     albertel 3436: 	my $display_part=&get_display_part($partid,$symb);
1.485     albertel 3437: 	my $radio.='<table border="0"><tr>';  
1.41      ng       3438: 	my $ctr = 0;
1.42      ng       3439: 	while ($ctr<=$weight{$partid}) { # display radio buttons in a nice table 10 across
1.485     albertel 3440: 	    $radio.= '<td><label><input type="radio" name="RADVAL_'.$partid.'" '.
1.54      albertel 3441: 		'onclick="javascript:writePoint(\''.$partid.'\','.$weight{$partid}.
1.288     albertel 3442: 		','.$ctr.')" />'.$ctr."</label></td>\n";
1.41      ng       3443: 	    $result.=(($ctr+1)%10 == 0 ? '</tr><tr>' : '');
                   3444: 	    $ctr++;
                   3445: 	}
1.485     albertel 3446: 	$radio.='</tr></table>';
                   3447: 	my $line = '<input type="text" name="TEXTVAL_'.
1.589     bisitz   3448: 	    $partid.'" size="4" '.'onchange="javascript:writePoint(\''.
1.54      albertel 3449: 		$partid.'\','.$weight{$partid}.',\'textval\')" /> /'.
1.539     riegler  3450: 	    $weight{$partid}.' '.&mt('(problem weight)').'</td>'."\n";
                   3451: 	$line.= '<td><b>'.&mt('Grade Status').':</b><select name="SELVAL_'.$partid.'"'.
1.589     bisitz   3452: 	    'onchange="javascript:writeRadText(\''.$partid.'\','.
1.59      albertel 3453: 		$weight{$partid}.')"> '.
1.401     albertel 3454: 	    '<option selected="selected"> </option>'.
1.485     albertel 3455: 	    '<option value="excused">'.&mt('excused').'</option>'.
                   3456: 	    '<option value="reset status">'.&mt('reset status').'</option>'.
                   3457: 	    '</select></td>'.
                   3458:             '<td><label><input type="checkbox" name="FORCE_'.$partid.'" />'.&mt('Override "Correct"').'</label>';
                   3459: 	$line.='<input type="hidden" name="partid_'.
                   3460: 	    $ctsparts.'" value="'.$partid.'" />'."\n";
                   3461: 	$line.='<input type="hidden" name="weight_'.
                   3462: 	    $partid.'" value="'.$weight{$partid}.'" />'."\n";
                   3463: 
                   3464: 	$result.=
                   3465: 	    &Apache::loncommon::start_data_table_row()."\n".
1.577     bisitz   3466: 	    '<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 3467: 	    &Apache::loncommon::end_data_table_row()."\n";
1.42      ng       3468: 	$ctsparts++;
1.41      ng       3469:     }
1.474     albertel 3470:     $result.=&Apache::loncommon::end_data_table()."\n".
1.52      albertel 3471: 	'<input type="hidden" name="totalparts" value="'.$ctsparts.'" />';
1.485     albertel 3472:     $result.='<input type="button" value="'.&mt('Revert to Default').'" '.
1.589     bisitz   3473: 	'onclick="javascript:resetEntry('.$ctsparts.');" />';
1.41      ng       3474: 
1.44      ng       3475:     #table listing all the students in a section/class
                   3476:     #header of table
1.560     raeburn  3477:     $result.= '<h3>'.$specific_header.'</h3>'.
                   3478:               &Apache::loncommon::start_data_table().
                   3479: 	      &Apache::loncommon::start_data_table_header_row().
                   3480: 	      '<th>'.&mt('No.').'</th>'.
                   3481: 	      '<th>'.&nameUserString('header')."</th>\n";
1.582     raeburn  3482:     my $partserror;
                   3483:     my (@parts) = sort(&getpartlist($symb,\$partserror));
                   3484:     if ($partserror) {
                   3485:         return &navmap_errormsg();
                   3486:     }
1.324     albertel 3487:     my (undef,undef,$url)=&Apache::lonnet::decode_symb($symb);
1.269     raeburn  3488:     my @partids = ();
1.41      ng       3489:     foreach my $part (@parts) {
                   3490: 	my $display=&Apache::lonnet::metadata($url,$part.'.display');
1.539     riegler  3491:         my $narrowtext = &mt('Tries');
                   3492: 	$display =~ s|^Number of Attempts|$narrowtext <br />|; # makes the column narrower
1.41      ng       3493: 	if  (!$display) { $display = &Apache::lonnet::metadata($url,$part.'.name'); }
1.207     albertel 3494: 	my ($partid) = &split_part_type($part);
1.524     raeburn  3495:         push(@partids,$partid);
1.324     albertel 3496: 	my $display_part=&get_display_part($partid,$symb);
1.41      ng       3497: 	if ($display =~ /^Partial Credit Factor/) {
1.485     albertel 3498: 	    $result.='<th>'.
                   3499: 		&mt('Score Part: [_1]<br /> (weight = [_2])',
                   3500: 		    $display_part,$weight{$partid}).'</th>'."\n";
1.41      ng       3501: 	    next;
1.485     albertel 3502: 	    
1.207     albertel 3503: 	} else {
1.485     albertel 3504: 	    if ($display =~ /Problem Status/) {
                   3505: 		my $grade_status_mt = &mt('Grade Status');
                   3506: 		$display =~ s{Problem Status}{$grade_status_mt<br />};
                   3507: 	    }
                   3508: 	    my $part_mt = &mt('Part:');
                   3509: 	    $display =~s{\[Part: \Q$partid\E\]}{$part_mt $display_part};
1.41      ng       3510: 	}
1.485     albertel 3511: 
1.474     albertel 3512: 	$result.='<th>'.$display.'</th>'."\n";
1.41      ng       3513:     }
1.474     albertel 3514:     $result.=&Apache::loncommon::end_data_table_header_row();
1.44      ng       3515: 
1.270     albertel 3516:     my %last_resets = 
                   3517: 	&get_last_resets($symb,$env{'request.course.id'},\@partids);
1.269     raeburn  3518: 
1.41      ng       3519:     #get info for each student
1.44      ng       3520:     #list all the students - with points and grade status
1.257     albertel 3521:     my (undef,undef,$fullname) = &getclasslist($env{'form.section'},'1');
1.41      ng       3522:     my $ctr = 0;
1.294     albertel 3523:     foreach (sort 
                   3524: 	     {
                   3525: 		 if (lc($$fullname{$a}) ne lc($$fullname{$b})) {
                   3526: 		     return (lc($$fullname{$a}) cmp lc($$fullname{$b}));
                   3527: 		 }
                   3528: 		 return $a cmp $b;
                   3529: 	     } (keys(%$fullname))) {
1.126     ng       3530: 	$ctr++;
1.324     albertel 3531: 	$result.=&viewstudentgrade($symb,$env{'request.course.id'},
1.269     raeburn  3532: 				   $_,$$fullname{$_},\@parts,\%weight,$ctr,\%last_resets);
1.41      ng       3533:     }
1.474     albertel 3534:     $result.=&Apache::loncommon::end_data_table();
1.41      ng       3535:     $result.='<input type="hidden" name="total" value="'.$ctr.'" />'."\n";
1.485     albertel 3536:     $result.='<input type="button" value="'.&mt('Save').'" '.
1.589     bisitz   3537: 	'onclick="javascript:submit();" target="_self" /></form>'."\n";
1.96      albertel 3538:     if (scalar(%$fullname) eq 0) {
                   3539: 	my $colspan=3+scalar(@parts);
1.433     banghart 3540: 	my $section_display = join (", ",&Apache::loncommon::get_env_multiple('form.section'));
1.442     banghart 3541:         my $stu_status = join(' or ',&Apache::loncommon::get_env_multiple('form.Status'));
1.433     banghart 3542: 	$result='<span class="LC_warning">'.
1.485     albertel 3543: 	    &mt('There are no students in section(s) [_1] with enrollment status [_2] to modify or grade.',
1.442     banghart 3544: 	        $section_display, $stu_status).
1.433     banghart 3545: 	    '</span>';
1.96      albertel 3546:     }
1.324     albertel 3547:     $result.=&show_grading_menu_form($symb);
1.41      ng       3548:     return $result;
                   3549: }
                   3550: 
1.44      ng       3551: #--- call by previous routine to display each student
1.41      ng       3552: sub viewstudentgrade {
1.324     albertel 3553:     my ($symb,$courseid,$student,$fullname,$parts,$weight,$ctr,$last_resets) = @_;
1.44      ng       3554:     my ($uname,$udom) = split(/:/,$student);
                   3555:     my %record=&Apache::lonnet::restore($symb,$courseid,$udom,$uname);
1.269     raeburn  3556:     my %aggregates = (); 
1.474     albertel 3557:     my $result=&Apache::loncommon::start_data_table_row().'<td align="right">'.
1.233     albertel 3558: 	'<input type="hidden" name="ctr'.($ctr-1).'" value="'.$student.'" />'.
                   3559: 	"\n".$ctr.'&nbsp;</td><td>&nbsp;'.
1.44      ng       3560: 	'<a href="javascript:viewOneStudent(\''.$uname.'\',\''.$udom.
1.417     albertel 3561: 	'\');" target="_self">'.$fullname.'</a> '.
1.398     albertel 3562: 	'<span class="LC_internal_info">('.$uname.($env{'user.domain'} eq $udom ? '' : ':'.$udom).')</span></td>'."\n";
1.281     albertel 3563:     $student=~s/:/_/; # colon doen't work in javascript for names
1.63      albertel 3564:     foreach my $apart (@$parts) {
                   3565: 	my ($part,$type) = &split_part_type($apart);
1.41      ng       3566: 	my $score=$record{"resource.$part.$type"};
1.276     albertel 3567:         $result.='<td align="center">';
1.269     raeburn  3568:         my ($aggtries,$totaltries);
                   3569:         unless (exists($aggregates{$part})) {
1.270     albertel 3570: 	    $totaltries = $record{'resource.'.$part.'.tries'};
                   3571: 
                   3572: 	    $aggtries = $totaltries;
1.269     raeburn  3573:             if ($$last_resets{$part}) {  
1.270     albertel 3574:                 $aggtries = &get_num_tries(\%record,$$last_resets{$part},
                   3575: 					   $part);
                   3576:             }
1.269     raeburn  3577:             $result.='<input type="hidden" name="'.
                   3578:                 'GD_'.$student.'_'.$part.'_aggtries" value="'.$aggtries.'" />'."\n";
                   3579:             $result.='<input type="hidden" name="'.
                   3580:                 'GD_'.$student.'_'.$part.'_totaltries" value="'.$totaltries.'" />'."\n";
                   3581:             $aggregates{$part} = 1;
                   3582:         }
1.41      ng       3583: 	if ($type eq 'awarded') {
1.320     albertel 3584: 	    my $pts = $score eq '' ? '' : &compute_points($score,$$weight{$part});
1.42      ng       3585: 	    $result.='<input type="hidden" name="'.
1.89      albertel 3586: 		'GD_'.$student.'_'.$part.'_awarded_s" value="'.$pts.'" />'."\n";
1.233     albertel 3587: 	    $result.='<input type="text" name="'.
1.89      albertel 3588: 		'GD_'.$student.'_'.$part.'_awarded" '.
1.589     bisitz   3589:                 'onchange="javascript:changeSelect(\''.$part.'\',\''.$student.
1.44      ng       3590: 		'\')" value="'.$pts.'" size="4" /></td>'."\n";
1.41      ng       3591: 	} elsif ($type eq 'solved') {
                   3592: 	    my ($status,$foo)=split(/_/,$score,2);
                   3593: 	    $status = 'nothing' if ($status eq '');
1.89      albertel 3594: 	    $result.='<input type="hidden" name="'.'GD_'.$student.'_'.
1.54      albertel 3595: 		$part.'_solved_s" value="'.$status.'" />'."\n";
1.233     albertel 3596: 	    $result.='&nbsp;<select name="'.
1.89      albertel 3597: 		'GD_'.$student.'_'.$part.'_solved" '.
1.589     bisitz   3598:                 'onchange="javascript:changeOneScore(\''.$part.'\',\''.$student.'\')" >'."\n";
1.485     albertel 3599: 	    $result.= (($status eq 'excused') ? '<option> </option><option selected="selected" value="excused">'.&mt('excused').'</option>' 
                   3600: 		: '<option selected="selected"> </option><option value="excused">'.&mt('excused').'</option>')."\n";
                   3601: 	    $result.='<option value="reset status">'.&mt('reset status').'</option>';
1.126     ng       3602: 	    $result.="</select>&nbsp;</td>\n";
1.122     ng       3603: 	} else {
                   3604: 	    $result.='<input type="hidden" name="'.
                   3605: 		'GD_'.$student.'_'.$part.'_'.$type.'_s" value="'.$score.'" />'.
                   3606: 		    "\n";
1.233     albertel 3607: 	    $result.='<input type="text" name="'.
1.122     ng       3608: 		'GD_'.$student.'_'.$part.'_'.$type.'" '.
                   3609: 		'value="'.$score.'" size="4" /></td>'."\n";
1.41      ng       3610: 	}
                   3611:     }
1.474     albertel 3612:     $result.=&Apache::loncommon::end_data_table_row();
1.41      ng       3613:     return $result;
1.38      ng       3614: }
                   3615: 
1.44      ng       3616: #--- change scores for all the students in a section/class
                   3617: #    record does not get update if unchanged
1.38      ng       3618: sub editgrades {
1.41      ng       3619:     my ($request) = @_;
                   3620: 
1.324     albertel 3621:     my $symb=&get_symb($request);
1.433     banghart 3622:     my $section_display = join (", ",&Apache::loncommon::get_env_multiple('form.section'));
1.477     albertel 3623:     my $title='<h2>'.&mt('Current Grade Status').'</h2>';
                   3624:     $title.='<h4>'.&mt('<b>Current Resource: </b>[_1]',$env{'form.probTitle'}).'</h4>'."\n";
1.433     banghart 3625:     $title.='<h4>'.&mt('<b>Section: </b>[_1]',$section_display).'</h4>'."\n";
1.126     ng       3626: 
1.477     albertel 3627:     my $result= &Apache::loncommon::start_data_table().
                   3628: 	&Apache::loncommon::start_data_table_header_row().
                   3629: 	'<th rowspan="2" valign="middle">'.&mt('No.').'</th>'.
                   3630: 	'<th rowspan="2" valign="middle">'.&nameUserString('header')."</th>\n";
1.43      ng       3631:     my %scoreptr = (
                   3632: 		    'correct'  =>'correct_by_override',
                   3633: 		    'incorrect'=>'incorrect_by_override',
                   3634: 		    'excused'  =>'excused',
                   3635: 		    'ungraded' =>'ungraded_attempted',
1.596     raeburn  3636:                     'credited' =>'credit_attempted',
1.43      ng       3637: 		    'nothing'  => '',
                   3638: 		    );
1.257     albertel 3639:     my ($classlist,undef,$fullname) = &getclasslist($env{'form.section'},'0');
1.34      ng       3640: 
1.44      ng       3641:     my (@partid);
                   3642:     my %weight = ();
1.54      albertel 3643:     my %columns = ();
1.44      ng       3644:     my ($i,$ctr,$count,$rec_update) = (0,0,0,0);
1.54      albertel 3645: 
1.582     raeburn  3646:     my $partserror;
                   3647:     my (@parts) = sort(&getpartlist($symb,\$partserror));
                   3648:     if ($partserror) {
                   3649:         return &navmap_errormsg();
                   3650:     }
1.54      albertel 3651:     my $header;
1.257     albertel 3652:     while ($ctr < $env{'form.totalparts'}) {
                   3653: 	my $partid = $env{'form.partid_'.$ctr};
1.524     raeburn  3654: 	push(@partid,$partid);
1.257     albertel 3655: 	$weight{$partid} = $env{'form.weight_'.$partid};
1.44      ng       3656: 	$ctr++;
1.54      albertel 3657:     }
1.324     albertel 3658:     my (undef,undef,$url) = &Apache::lonnet::decode_symb($symb);
1.54      albertel 3659:     foreach my $partid (@partid) {
1.478     albertel 3660: 	$header .= '<th align="center">'.&mt('Old Score').'</th>'.
                   3661: 	    '<th align="center">'.&mt('New Score').'</th>';
1.54      albertel 3662: 	$columns{$partid}=2;
                   3663: 	foreach my $stores (@parts) {
                   3664: 	    my ($part,$type) = &split_part_type($stores);
                   3665: 	    if ($part !~ m/^\Q$partid\E/) { next;}
                   3666: 	    if ($type eq 'awarded' || $type eq 'solved') { next; }
                   3667: 	    my $display=&Apache::lonnet::metadata($url,$stores.'.display');
1.551     raeburn  3668: 	    $display =~ s/\[Part: \Q$part\E\]//;
1.539     riegler  3669:             my $narrowtext = &mt('Tries');
                   3670: 	    $display =~ s/Number of Attempts/$narrowtext/;
                   3671: 	    $header .= '<th align="center">'.&mt('Old').' '.$display.'</th>'.
                   3672: 		'<th align="center">'.&mt('New').' '.$display.'</th>';
1.54      albertel 3673: 	    $columns{$partid}+=2;
                   3674: 	}
                   3675:     }
                   3676:     foreach my $partid (@partid) {
1.324     albertel 3677: 	my $display_part=&get_display_part($partid,$symb);
1.478     albertel 3678: 	$result .= '<th colspan="'.$columns{$partid}.'" align="center">'.
                   3679: 	    &mt('Part: [_1] (Weight = [_2])',$display_part,$weight{$partid}).
                   3680: 	    '</th>';
1.54      albertel 3681: 
1.44      ng       3682:     }
1.477     albertel 3683:     $result .= &Apache::loncommon::end_data_table_header_row().
                   3684: 	&Apache::loncommon::start_data_table_header_row().
                   3685: 	$header.
                   3686: 	&Apache::loncommon::end_data_table_header_row();
                   3687:     my @noupdate;
1.126     ng       3688:     my ($updateCtr,$noupdateCtr) = (1,1);
1.257     albertel 3689:     for ($i=0; $i<$env{'form.total'}; $i++) {
1.93      albertel 3690: 	my $line;
1.257     albertel 3691: 	my $user = $env{'form.ctr'.$i};
1.281     albertel 3692: 	my ($uname,$udom)=split(/:/,$user);
1.44      ng       3693: 	my %newrecord;
                   3694: 	my $updateflag = 0;
1.281     albertel 3695: 	$line .= '<td>'.&nameUserString(undef,$$fullname{$user},$uname,$udom).'</td>';
1.108     albertel 3696: 	my $usec=$classlist->{"$uname:$udom"}[5];
1.105     albertel 3697: 	if (!&canmodify($usec)) {
1.126     ng       3698: 	    my $numcols=scalar(@partid)*4+2;
1.477     albertel 3699: 	    push(@noupdate,
1.478     albertel 3700: 		 $line."<td colspan=\"$numcols\"><span class=\"LC_warning\">".
                   3701: 		 &mt('Not allowed to modify student')."</span></td></tr>");
1.105     albertel 3702: 	    next;
                   3703: 	}
1.269     raeburn  3704:         my %aggregate = ();
                   3705:         my $aggregateflag = 0;
1.281     albertel 3706: 	$user=~s/:/_/; # colon doen't work in javascript for names
1.44      ng       3707: 	foreach (@partid) {
1.257     albertel 3708: 	    my $old_aw    = $env{'form.GD_'.$user.'_'.$_.'_awarded_s'};
1.54      albertel 3709: 	    my $old_part_pcr = $old_aw/($weight{$_} ne '0' ? $weight{$_}:1);
                   3710: 	    my $old_part  = $old_aw eq '' ? '' : $old_part_pcr;
1.257     albertel 3711: 	    my $old_score = $scoreptr{$env{'form.GD_'.$user.'_'.$_.'_solved_s'}};
                   3712: 	    my $awarded   = $env{'form.GD_'.$user.'_'.$_.'_awarded'};
1.54      albertel 3713: 	    my $pcr       = $awarded/($weight{$_} ne '0' ? $weight{$_} : 1);
                   3714: 	    my $partial   = $awarded eq '' ? '' : $pcr;
1.44      ng       3715: 	    my $score;
                   3716: 	    if ($partial eq '') {
1.257     albertel 3717: 		$score = $scoreptr{$env{'form.GD_'.$user.'_'.$_.'_solved_s'}};
1.44      ng       3718: 	    } elsif ($partial > 0) {
                   3719: 		$score = 'correct_by_override';
                   3720: 	    } elsif ($partial == 0) {
                   3721: 		$score = 'incorrect_by_override';
                   3722: 	    }
1.257     albertel 3723: 	    my $dropMenu = $env{'form.GD_'.$user.'_'.$_.'_solved'};
1.125     ng       3724: 	    $score = 'excused' if (($dropMenu eq 'excused') && ($score ne 'excused'));
                   3725: 
1.292     albertel 3726: 	    $newrecord{'resource.'.$_.'.regrader'}=
                   3727: 		"$env{'user.name'}:$env{'user.domain'}";
1.125     ng       3728: 	    if ($dropMenu eq 'reset status' &&
                   3729: 		$old_score ne '') { # ignore if no previous attempts => nothing to reset
1.299     albertel 3730: 		$newrecord{'resource.'.$_.'.tries'} = '';
1.125     ng       3731: 		$newrecord{'resource.'.$_.'.solved'} = '';
                   3732: 		$newrecord{'resource.'.$_.'.award'} = '';
1.299     albertel 3733: 		$newrecord{'resource.'.$_.'.awarded'} = '';
1.125     ng       3734: 		$updateflag = 1;
1.269     raeburn  3735:                 if ($env{'form.GD_'.$user.'_'.$_.'_aggtries'} > 0) {
                   3736:                     my $aggtries = $env{'form.GD_'.$user.'_'.$_.'_aggtries'};
                   3737:                     my $totaltries = $env{'form.GD_'.$user.'_'.$_.'_totaltries'};
                   3738:                     my $solvedstatus = $env{'form.GD_'.$user.'_'.$_.'_solved_s'};
                   3739:                     &decrement_aggs($symb,$_,\%aggregate,$aggtries,$totaltries,$solvedstatus);
                   3740:                     $aggregateflag = 1;
                   3741:                 }
1.139     albertel 3742: 	    } elsif (!($old_part eq $partial && $old_score eq $score)) {
                   3743: 		$updateflag = 1;
                   3744: 		$newrecord{'resource.'.$_.'.awarded'}  = $partial if $partial ne '';
                   3745: 		$newrecord{'resource.'.$_.'.solved'}   = $score;
                   3746: 		$rec_update++;
1.125     ng       3747: 	    }
                   3748: 
1.93      albertel 3749: 	    $line .= '<td align="center">'.$old_aw.'&nbsp;</td>'.
1.44      ng       3750: 		'<td align="center">'.$awarded.
                   3751: 		($score eq 'excused' ? $score : '').'&nbsp;</td>';
1.5       albertel 3752: 
1.54      albertel 3753: 
                   3754: 	    my $partid=$_;
                   3755: 	    foreach my $stores (@parts) {
                   3756: 		my ($part,$type) = &split_part_type($stores);
                   3757: 		if ($part !~ m/^\Q$partid\E/) { next;}
                   3758: 		if ($type eq 'awarded' || $type eq 'solved') { next; }
1.257     albertel 3759: 		my $old_aw    = $env{'form.GD_'.$user.'_'.$part.'_'.$type.'_s'};
                   3760: 		my $awarded   = $env{'form.GD_'.$user.'_'.$part.'_'.$type};
1.54      albertel 3761: 		if ($awarded ne '' && $awarded ne $old_aw) {
                   3762: 		    $newrecord{'resource.'.$part.'.'.$type}= $awarded;
1.257     albertel 3763: 		    $newrecord{'resource.'.$part.'.regrader'}="$env{'user.name'}:$env{'user.domain'}";
1.54      albertel 3764: 		    $updateflag=1;
                   3765: 		}
1.93      albertel 3766: 		$line .= '<td align="center">'.$old_aw.'&nbsp;</td>'.
1.54      albertel 3767: 		    '<td align="center">'.$awarded.'&nbsp;</td>';
                   3768: 	    }
1.44      ng       3769: 	}
1.477     albertel 3770: 	$line.="\n";
1.301     albertel 3771: 
                   3772: 	my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   3773: 	my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   3774: 
1.44      ng       3775: 	if ($updateflag) {
                   3776: 	    $count++;
1.257     albertel 3777: 	    &Apache::lonnet::cstore(\%newrecord,$symb,$env{'request.course.id'},
1.89      albertel 3778: 				    $udom,$uname);
1.301     albertel 3779: 
                   3780: 	    if (&Apache::bridgetask::in_queue('gradingqueue',$symb,$cdom,
                   3781: 					      $cnum,$udom,$uname)) {
                   3782: 		# need to figure out if should be in queue.
                   3783: 		my %record =  
                   3784: 		    &Apache::lonnet::restore($symb,$env{'request.course.id'},
                   3785: 					     $udom,$uname);
                   3786: 		my $all_graded = 1;
                   3787: 		my $none_graded = 1;
                   3788: 		foreach my $part (@parts) {
                   3789: 		    if ( $record{'resource.'.$part.'.awarded'} eq '' ) {
                   3790: 			$all_graded = 0;
                   3791: 		    } else {
                   3792: 			$none_graded = 0;
                   3793: 		    }
                   3794: 		}
                   3795: 
                   3796: 		if ($all_graded || $none_graded) {
                   3797: 		    &Apache::bridgetask::remove_from_queue('gradingqueue',
                   3798: 							   $symb,$cdom,$cnum,
                   3799: 							   $udom,$uname);
                   3800: 		}
                   3801: 	    }
                   3802: 
1.477     albertel 3803: 	    $result.=&Apache::loncommon::start_data_table_row().
                   3804: 		'<td align="right">&nbsp;'.$updateCtr.'&nbsp;</td>'.$line.
                   3805: 		&Apache::loncommon::end_data_table_row();
1.126     ng       3806: 	    $updateCtr++;
1.93      albertel 3807: 	} else {
1.477     albertel 3808: 	    push(@noupdate,
                   3809: 		 '<td align="right">&nbsp;'.$noupdateCtr.'&nbsp;</td>'.$line);
1.126     ng       3810: 	    $noupdateCtr++;
1.44      ng       3811: 	}
1.269     raeburn  3812:         if ($aggregateflag) {
                   3813:             &Apache::lonnet::cinc('nohist_resourcetracker',\%aggregate,
1.301     albertel 3814: 				  $cdom,$cnum);
1.269     raeburn  3815:         }
1.93      albertel 3816:     }
1.477     albertel 3817:     if (@noupdate) {
1.126     ng       3818: #	my $numcols=(scalar(@partid)*(scalar(@parts)-1)*2)+3;
                   3819: 	my $numcols=scalar(@partid)*4+2;
1.477     albertel 3820: 	$result .= &Apache::loncommon::start_data_table_row('LC_empty_row').
1.478     albertel 3821: 	    '<td align="center" colspan="'.$numcols.'">'.
                   3822: 	    &mt('No Changes Occurred For the Students Below').
                   3823: 	    '</td>'.
1.477     albertel 3824: 	    &Apache::loncommon::end_data_table_row();
                   3825: 	foreach my $line (@noupdate) {
                   3826: 	    $result.=
                   3827: 		&Apache::loncommon::start_data_table_row().
                   3828: 		$line.
                   3829: 		&Apache::loncommon::end_data_table_row();
                   3830: 	}
1.44      ng       3831:     }
1.477     albertel 3832:     $result .= &Apache::loncommon::end_data_table().
                   3833: 	&show_grading_menu_form($symb);
1.478     albertel 3834:     my $msg = '<p><b>'.
                   3835: 	&mt('Number of records updated = [_1] for [quant,_2,student].',
                   3836: 	    $rec_update,$count).'</b><br />'.
                   3837: 	'<b>'.&mt('Total number of students = [_1]',$env{'form.total'}).
                   3838: 	'</b></p>';
1.44      ng       3839:     return $title.$msg.$result;
1.5       albertel 3840: }
1.54      albertel 3841: 
                   3842: sub split_part_type {
                   3843:     my ($partstr) = @_;
                   3844:     my ($temp,@allparts)=split(/_/,$partstr);
                   3845:     my $type=pop(@allparts);
1.439     albertel 3846:     my $part=join('_',@allparts);
1.54      albertel 3847:     return ($part,$type);
                   3848: }
                   3849: 
1.44      ng       3850: #------------- end of section for handling grading by section/class ---------
                   3851: #
                   3852: #----------------------------------------------------------------------------
                   3853: 
1.5       albertel 3854: 
1.44      ng       3855: #----------------------------------------------------------------------------
                   3856: #
                   3857: #-------------------------- Next few routines handles grading by csv upload
                   3858: #
                   3859: #--- Javascript to handle csv upload
1.27      albertel 3860: sub csvupload_javascript_reverse_associate {
1.573     bisitz   3861:     my $error1=&mt('You need to specify the username or the student/employee ID');
1.246     albertel 3862:     my $error2=&mt('You need to specify at least one grading field');
1.27      albertel 3863:   return(<<ENDPICK);
                   3864:   function verify(vf) {
                   3865:     var foundsomething=0;
                   3866:     var founduname=0;
1.243     albertel 3867:     var foundID=0;
1.27      albertel 3868:     for (i=0;i<=vf.nfields.value;i++) {
                   3869:       tw=eval('vf.f'+i+'.selectedIndex');
1.243     albertel 3870:       if (i==0 && tw!=0) { foundID=1; }
                   3871:       if (i==1 && tw!=0) { founduname=1; }
                   3872:       if (i!=0 && i!=1 && i!=2 && tw!=0) { foundsomething=1; }
1.27      albertel 3873:     }
1.246     albertel 3874:     if (founduname==0 && foundID==0) {
                   3875: 	alert('$error1');
                   3876: 	return;
1.27      albertel 3877:     }
                   3878:     if (foundsomething==0) {
1.246     albertel 3879: 	alert('$error2');
                   3880: 	return;
1.27      albertel 3881:     }
                   3882:     vf.submit();
                   3883:   }
                   3884:   function flip(vf,tf) {
                   3885:     var nw=eval('vf.f'+tf+'.selectedIndex');
                   3886:     var i;
                   3887:     for (i=0;i<=vf.nfields.value;i++) {
                   3888:       //can not pick the same destination field for both name and domain
                   3889:       if (((i ==0)||(i ==1)) && 
                   3890:           ((tf==0)||(tf==1)) && 
                   3891:           (i!=tf) &&
                   3892:           (eval('vf.f'+i+'.selectedIndex')==nw)) {
                   3893:         eval('vf.f'+i+'.selectedIndex=0;')
                   3894:       }
                   3895:     }
                   3896:   }
                   3897: ENDPICK
                   3898: }
                   3899: 
                   3900: sub csvupload_javascript_forward_associate {
1.573     bisitz   3901:     my $error1=&mt('You need to specify the username or the student/employee ID');
1.246     albertel 3902:     my $error2=&mt('You need to specify at least one grading field');
1.27      albertel 3903:   return(<<ENDPICK);
                   3904:   function verify(vf) {
                   3905:     var foundsomething=0;
                   3906:     var founduname=0;
1.243     albertel 3907:     var foundID=0;
1.27      albertel 3908:     for (i=0;i<=vf.nfields.value;i++) {
                   3909:       tw=eval('vf.f'+i+'.selectedIndex');
1.243     albertel 3910:       if (tw==1) { foundID=1; }
                   3911:       if (tw==2) { founduname=1; }
                   3912:       if (tw>3) { foundsomething=1; }
1.27      albertel 3913:     }
1.246     albertel 3914:     if (founduname==0 && foundID==0) {
                   3915: 	alert('$error1');
                   3916: 	return;
1.27      albertel 3917:     }
                   3918:     if (foundsomething==0) {
1.246     albertel 3919: 	alert('$error2');
                   3920: 	return;
1.27      albertel 3921:     }
                   3922:     vf.submit();
                   3923:   }
                   3924:   function flip(vf,tf) {
                   3925:     var nw=eval('vf.f'+tf+'.selectedIndex');
                   3926:     var i;
                   3927:     //can not pick the same destination field twice
                   3928:     for (i=0;i<=vf.nfields.value;i++) {
                   3929:       if ((i!=tf) && (eval('vf.f'+i+'.selectedIndex')==nw)) {
                   3930:         eval('vf.f'+i+'.selectedIndex=0;')
                   3931:       }
                   3932:     }
                   3933:   }
                   3934: ENDPICK
                   3935: }
                   3936: 
1.26      albertel 3937: sub csvuploadmap_header {
1.324     albertel 3938:     my ($request,$symb,$datatoken,$distotal)= @_;
1.41      ng       3939:     my $javascript;
1.257     albertel 3940:     if ($env{'form.upfile_associate'} eq 'reverse') {
1.41      ng       3941: 	$javascript=&csvupload_javascript_reverse_associate();
                   3942:     } else {
                   3943: 	$javascript=&csvupload_javascript_forward_associate();
                   3944:     }
1.45      ng       3945: 
1.324     albertel 3946:     my ($result) = &showResourceInfo($symb,$env{'form.probTitle'});
1.257     albertel 3947:     my $checked=(($env{'form.noFirstLine'})?' checked="checked"':'');
1.245     albertel 3948:     my $ignore=&mt('Ignore First Line');
1.418     albertel 3949:     $symb = &Apache::lonenc::check_encrypt($symb);
1.41      ng       3950:     $request->print(<<ENDPICK);
1.26      albertel 3951: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="gradesupload">
1.398     albertel 3952: <h3><span class="LC_info">Uploading Class Grades</span></h3>
1.45      ng       3953: $result
1.326     albertel 3954: <hr />
1.26      albertel 3955: <h3>Identify fields</h3>
                   3956: Total number of records found in file: $distotal <hr />
                   3957: Enter as many fields as you can. The system will inform you and bring you back
                   3958: to this page if the data selected is insufficient to run your class.<hr />
1.589     bisitz   3959: <input type="button" value="Reverse Association" onclick="javascript:this.form.associate.value='Reverse Association';submit(this.form);" />
1.245     albertel 3960: <label><input type="checkbox" name="noFirstLine" $checked />$ignore</label>
1.26      albertel 3961: <input type="hidden" name="associate"  value="" />
                   3962: <input type="hidden" name="phase"      value="three" />
                   3963: <input type="hidden" name="datatoken"  value="$datatoken" />
1.257     albertel 3964: <input type="hidden" name="fileupload" value="$env{'form.fileupload'}" />
                   3965: <input type="hidden" name="upfiletype" value="$env{'form.upfiletype'}" />
1.26      albertel 3966: <input type="hidden" name="upfile_associate" 
1.257     albertel 3967:                                        value="$env{'form.upfile_associate'}" />
1.26      albertel 3968: <input type="hidden" name="symb"       value="$symb" />
1.257     albertel 3969: <input type="hidden" name="saveState"  value="$env{'form.saveState'}" />
                   3970: <input type="hidden" name="probTitle"  value="$env{'form.probTitle'}" />
1.246     albertel 3971: <input type="hidden" name="command"    value="csvuploadoptions" />
1.26      albertel 3972: <hr />
                   3973: <script type="text/javascript" language="Javascript">
                   3974: $javascript
                   3975: </script>
                   3976: ENDPICK
1.118     ng       3977:     return '';
1.26      albertel 3978: 
                   3979: }
                   3980: 
                   3981: sub csvupload_fields {
1.582     raeburn  3982:     my ($symb,$errorref) = @_;
                   3983:     my (@parts) = &getpartlist($symb,$errorref);
                   3984:     if (ref($errorref)) {
                   3985:         if ($$errorref) {
                   3986:             return;
                   3987:         }
                   3988:     }
                   3989: 
1.556     weissno  3990:     my @fields=(['ID','Student/Employee ID'],
1.243     albertel 3991: 		['username','Student Username'],
                   3992: 		['domain','Student Domain']);
1.324     albertel 3993:     my (undef,undef,$url) = &Apache::lonnet::decode_symb($symb);
1.41      ng       3994:     foreach my $part (sort(@parts)) {
                   3995: 	my @datum;
                   3996: 	my $display=&Apache::lonnet::metadata($url,$part.'.display');
                   3997: 	my $name=$part;
                   3998: 	if  (!$display) { $display = $name; }
                   3999: 	@datum=($name,$display);
1.244     albertel 4000: 	if ($name=~/^stores_(.*)_awarded/) {
                   4001: 	    push(@fields,['stores_'.$1.'_points',"Points [Part: $1]"]);
                   4002: 	}
1.41      ng       4003: 	push(@fields,\@datum);
                   4004:     }
                   4005:     return (@fields);
1.26      albertel 4006: }
                   4007: 
                   4008: sub csvuploadmap_footer {
1.41      ng       4009:     my ($request,$i,$keyfields) =@_;
                   4010:     $request->print(<<ENDPICK);
1.26      albertel 4011: </table>
                   4012: <input type="hidden" name="nfields" value="$i" />
                   4013: <input type="hidden" name="keyfields" value="$keyfields" />
1.589     bisitz   4014: <input type="button" onclick="javascript:verify(this.form)" value="Assign Grades" /><br />
1.26      albertel 4015: </form>
                   4016: ENDPICK
                   4017: }
                   4018: 
1.283     albertel 4019: sub checkforfile_js {
1.539     riegler  4020:     my $alertmsg = &mt('Please use the browse button to select a file from your local directory.');
1.86      ng       4021:     my $result =<<CSVFORMJS;
                   4022: <script type="text/javascript" language="javascript">
                   4023:     function checkUpload(formname) {
                   4024: 	if (formname.upfile.value == "") {
1.539     riegler  4025: 	    alert("$alertmsg");
1.86      ng       4026: 	    return false;
                   4027: 	}
                   4028: 	formname.submit();
                   4029:     }
                   4030:     </script>
                   4031: CSVFORMJS
1.283     albertel 4032:     return $result;
                   4033: }
                   4034: 
                   4035: sub upcsvScores_form {
                   4036:     my ($request) = shift;
1.324     albertel 4037:     my ($symb)=&get_symb($request);
1.283     albertel 4038:     if (!$symb) {return '';}
                   4039:     my $result=&checkforfile_js();
1.257     albertel 4040:     $env{'form.probTitle'} = &Apache::lonnet::gettitle($symb);
1.324     albertel 4041:     my ($table) = &showResourceInfo($symb,$env{'form.probTitle'});
1.118     ng       4042:     $result.=$table;
1.326     albertel 4043:     $result.='<br /><table width="100%" border="0"><tr><td bgcolor="#777777">'."\n";
                   4044:     $result.='<table width="100%" border="0"><tr bgcolor="#e6ffff"><td>'."\n";
1.538     schulted 4045:     $result.='&nbsp;<b>'.&mt('Specify a file containing the class scores for current resource.').
                   4046: 	'</b></td></tr>'."\n";
1.86      ng       4047:     $result.='<tr bgcolor=#ffffe6><td>'."\n";
1.370     www      4048:     my $upload=&mt("Upload Scores");
1.86      ng       4049:     my $upfile_select=&Apache::loncommon::upfile_select_html();
1.245     albertel 4050:     my $ignore=&mt('Ignore First Line');
1.418     albertel 4051:     $symb = &Apache::lonenc::check_encrypt($symb);
1.86      ng       4052:     $result.=<<ENDUPFORM;
1.106     albertel 4053: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="gradesupload">
1.86      ng       4054: <input type="hidden" name="symb" value="$symb" />
                   4055: <input type="hidden" name="command" value="csvuploadmap" />
1.257     albertel 4056: <input type="hidden" name="probTitle" value="$env{'form.probTitle'}" />
                   4057: <input type="hidden" name="saveState"  value="$env{'form.saveState'}" />
1.86      ng       4058: $upfile_select
1.589     bisitz   4059: <br /><input type="button" onclick="javascript:checkUpload(this.form);" value="$upload" />
1.283     albertel 4060: <label><input type="checkbox" name="noFirstLine" />$ignore</label>
1.86      ng       4061: </form>
                   4062: ENDUPFORM
1.370     www      4063:     $result.=&Apache::loncommon::help_open_topic("Course_Convert_To_CSV",
                   4064:                            &mt("How do I create a CSV file from a spreadsheet"))
                   4065:     .'</td></tr></table>'."\n";
1.86      ng       4066:     $result.='</td></tr></table><br /><br />'."\n";
1.324     albertel 4067:     $result.=&show_grading_menu_form($symb);
1.86      ng       4068:     return $result;
                   4069: }
                   4070: 
                   4071: 
1.26      albertel 4072: sub csvuploadmap {
1.41      ng       4073:     my ($request)= @_;
1.324     albertel 4074:     my ($symb)=&get_symb($request);
1.41      ng       4075:     if (!$symb) {return '';}
1.72      ng       4076: 
1.41      ng       4077:     my $datatoken;
1.257     albertel 4078:     if (!$env{'form.datatoken'}) {
1.41      ng       4079: 	$datatoken=&Apache::loncommon::upfile_store($request);
1.26      albertel 4080:     } else {
1.257     albertel 4081: 	$datatoken=$env{'form.datatoken'};
1.41      ng       4082: 	&Apache::loncommon::load_tmp_file($request);
1.26      albertel 4083:     }
1.41      ng       4084:     my @records=&Apache::loncommon::upfile_record_sep();
1.257     albertel 4085:     if ($env{'form.noFirstLine'}) { shift(@records); }
1.324     albertel 4086:     &csvuploadmap_header($request,$symb,$datatoken,$#records+1);
1.41      ng       4087:     my ($i,$keyfields);
                   4088:     if (@records) {
1.582     raeburn  4089:         my $fieldserror;
                   4090: 	my @fields=&csvupload_fields($symb,\$fieldserror);
                   4091:         if ($fieldserror) {
                   4092:             $request->print(&navmap_errormsg());
                   4093:             return;
                   4094:         }
1.257     albertel 4095: 	if ($env{'form.upfile_associate'} eq 'reverse') {	
1.41      ng       4096: 	    &Apache::loncommon::csv_print_samples($request,\@records);
                   4097: 	    $i=&Apache::loncommon::csv_print_select_table($request,\@records,
                   4098: 							  \@fields);
                   4099: 	    foreach (@fields) { $keyfields.=$_->[0].','; }
                   4100: 	    chop($keyfields);
                   4101: 	} else {
                   4102: 	    unshift(@fields,['none','']);
                   4103: 	    $i=&Apache::loncommon::csv_samples_select_table($request,\@records,
                   4104: 							    \@fields);
1.311     banghart 4105:             foreach my $rec (@records) {
                   4106:                 my %temp = &Apache::loncommon::record_sep($rec);
                   4107:                 if (%temp) {
                   4108:                     $keyfields=join(',',sort(keys(%temp)));
                   4109:                     last;
                   4110:                 }
                   4111:             }
1.41      ng       4112: 	}
                   4113:     }
                   4114:     &csvuploadmap_footer($request,$i,$keyfields);
1.324     albertel 4115:     $request->print(&show_grading_menu_form($symb));
1.72      ng       4116: 
1.41      ng       4117:     return '';
1.27      albertel 4118: }
                   4119: 
1.246     albertel 4120: sub csvuploadoptions {
1.41      ng       4121:     my ($request)= @_;
1.324     albertel 4122:     my ($symb)=&get_symb($request);
1.257     albertel 4123:     my $checked=(($env{'form.noFirstLine'})?'1':'0');
1.246     albertel 4124:     my $ignore=&mt('Ignore First Line');
                   4125:     $request->print(<<ENDPICK);
                   4126: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="gradesupload">
1.398     albertel 4127: <h3><span class="LC_info">Uploading Class Grade Options</span></h3>
1.246     albertel 4128: <input type="hidden" name="command"    value="csvuploadassign" />
1.302     albertel 4129: <!--
1.246     albertel 4130: <p>
                   4131: <label>
                   4132:    <input type="checkbox" name="show_full_results" />
                   4133:    Show a table of all changes
                   4134: </label>
                   4135: </p>
1.302     albertel 4136: -->
1.246     albertel 4137: <p>
                   4138: <label>
                   4139:    <input type="checkbox" name="overwite_scores" checked="checked" />
                   4140:    Overwrite any existing score
                   4141: </label>
                   4142: </p>
                   4143: ENDPICK
                   4144:     my %fields=&get_fields();
                   4145:     if (!defined($fields{'domain'})) {
1.257     albertel 4146: 	my $domform = &Apache::loncommon::select_dom_form($env{'request.role.domain'},'default_domain');
1.246     albertel 4147: 	$request->print("\n<p> Users are in domain: ".$domform."</p>\n");
                   4148:     }
1.257     albertel 4149:     foreach my $key (sort(keys(%env))) {
1.246     albertel 4150: 	if ($key !~ /^form\.(.*)$/) { next; }
                   4151: 	my $cleankey=$1;
                   4152: 	if ($cleankey eq 'command') { next; }
                   4153: 	$request->print('<input type="hidden" name="'.$cleankey.
1.257     albertel 4154: 			'"  value="'.$env{$key}.'" />'."\n");
1.246     albertel 4155:     }
                   4156:     # FIXME do a check for any duplicated user ids...
                   4157:     # FIXME do a check for any invalid user ids?...
1.290     albertel 4158:     $request->print('<input type="submit" value="Assign Grades" /><br />
                   4159: <hr /></form>'."\n");
1.324     albertel 4160:     $request->print(&show_grading_menu_form($symb));
1.246     albertel 4161:     return '';
                   4162: }
                   4163: 
                   4164: sub get_fields {
                   4165:     my %fields;
1.257     albertel 4166:     my @keyfields = split(/\,/,$env{'form.keyfields'});
                   4167:     for (my $i=0; $i<=$env{'form.nfields'}; $i++) {
                   4168: 	if ($env{'form.upfile_associate'} eq 'reverse') {
                   4169: 	    if ($env{'form.f'.$i} ne 'none') {
                   4170: 		$fields{$keyfields[$i]}=$env{'form.f'.$i};
1.41      ng       4171: 	    }
                   4172: 	} else {
1.257     albertel 4173: 	    if ($env{'form.f'.$i} ne 'none') {
                   4174: 		$fields{$env{'form.f'.$i}}=$keyfields[$i];
1.41      ng       4175: 	    }
                   4176: 	}
1.27      albertel 4177:     }
1.246     albertel 4178:     return %fields;
                   4179: }
                   4180: 
                   4181: sub csvuploadassign {
                   4182:     my ($request)= @_;
1.324     albertel 4183:     my ($symb)=&get_symb($request);
1.246     albertel 4184:     if (!$symb) {return '';}
1.345     bowersj2 4185:     my $error_msg = '';
1.246     albertel 4186:     &Apache::loncommon::load_tmp_file($request);
                   4187:     my @gradedata = &Apache::loncommon::upfile_record_sep();
1.257     albertel 4188:     if ($env{'form.noFirstLine'}) { shift(@gradedata); }
1.246     albertel 4189:     my %fields=&get_fields();
1.41      ng       4190:     $request->print('<h3>Assigning Grades</h3>');
1.257     albertel 4191:     my $courseid=$env{'request.course.id'};
1.97      albertel 4192:     my ($classlist) = &getclasslist('all',0);
1.106     albertel 4193:     my @notallowed;
1.41      ng       4194:     my @skipped;
                   4195:     my $countdone=0;
                   4196:     foreach my $grade (@gradedata) {
                   4197: 	my %entries=&Apache::loncommon::record_sep($grade);
1.246     albertel 4198: 	my $domain;
                   4199: 	if ($entries{$fields{'domain'}}) {
                   4200: 	    $domain=$entries{$fields{'domain'}};
                   4201: 	} else {
1.257     albertel 4202: 	    $domain=$env{'form.default_domain'};
1.246     albertel 4203: 	}
1.243     albertel 4204: 	$domain=~s/\s//g;
1.41      ng       4205: 	my $username=$entries{$fields{'username'}};
1.160     albertel 4206: 	$username=~s/\s//g;
1.243     albertel 4207: 	if (!$username) {
                   4208: 	    my $id=$entries{$fields{'ID'}};
1.247     albertel 4209: 	    $id=~s/\s//g;
1.243     albertel 4210: 	    my %ids=&Apache::lonnet::idget($domain,$id);
                   4211: 	    $username=$ids{$id};
                   4212: 	}
1.41      ng       4213: 	if (!exists($$classlist{"$username:$domain"})) {
1.247     albertel 4214: 	    my $id=$entries{$fields{'ID'}};
                   4215: 	    $id=~s/\s//g;
                   4216: 	    if ($id) {
                   4217: 		push(@skipped,"$id:$domain");
                   4218: 	    } else {
                   4219: 		push(@skipped,"$username:$domain");
                   4220: 	    }
1.41      ng       4221: 	    next;
                   4222: 	}
1.108     albertel 4223: 	my $usec=$classlist->{"$username:$domain"}[5];
1.106     albertel 4224: 	if (!&canmodify($usec)) {
                   4225: 	    push(@notallowed,"$username:$domain");
                   4226: 	    next;
                   4227: 	}
1.244     albertel 4228: 	my %points;
1.41      ng       4229: 	my %grades;
                   4230: 	foreach my $dest (keys(%fields)) {
1.244     albertel 4231: 	    if ($dest eq 'ID' || $dest eq 'username' ||
                   4232: 		$dest eq 'domain') { next; }
                   4233: 	    if ($entries{$fields{$dest}} =~ /^\s*$/) { next; }
                   4234: 	    if ($dest=~/stores_(.*)_points/) {
                   4235: 		my $part=$1;
                   4236: 		my $wgt =&Apache::lonnet::EXT('resource.'.$part.'.weight',
                   4237: 					      $symb,$domain,$username);
1.345     bowersj2 4238:                 if ($wgt) {
                   4239:                     $entries{$fields{$dest}}=~s/\s//g;
                   4240:                     my $pcr=$entries{$fields{$dest}} / $wgt;
1.463     albertel 4241:                     my $award=($pcr == 0) ? 'incorrect_by_override'
                   4242:                                           : 'correct_by_override';
1.345     bowersj2 4243:                     $grades{"resource.$part.awarded"}=$pcr;
                   4244:                     $grades{"resource.$part.solved"}=$award;
                   4245:                     $points{$part}=1;
                   4246:                 } else {
                   4247:                     $error_msg = "<br />" .
                   4248:                         &mt("Some point values were assigned"
                   4249:                             ." for problems with a weight "
                   4250:                             ."of zero. These values were "
                   4251:                             ."ignored.");
                   4252:                 }
1.244     albertel 4253: 	    } else {
                   4254: 		if ($dest=~/stores_(.*)_awarded/) { if ($points{$1}) {next;} }
                   4255: 		if ($dest=~/stores_(.*)_solved/)  { if ($points{$1}) {next;} }
                   4256: 		my $store_key=$dest;
                   4257: 		$store_key=~s/^stores/resource/;
                   4258: 		$store_key=~s/_/\./g;
                   4259: 		$grades{$store_key}=$entries{$fields{$dest}};
                   4260: 	    }
1.41      ng       4261: 	}
1.508     www      4262: 	if (! %grades) { 
                   4263:            push(@skipped,&mt("[_1]: no data to save","$username:$domain")); 
                   4264:         } else {
                   4265: 	   $grades{"resource.regrader"}="$env{'user.name'}:$env{'user.domain'}";
                   4266: 	   my $result=&Apache::lonnet::cstore(\%grades,$symb,
1.302     albertel 4267: 					   $env{'request.course.id'},
                   4268: 					   $domain,$username);
1.508     www      4269: 	   if ($result eq 'ok') {
                   4270: 	      $request->print('.');
                   4271: 	   } else {
                   4272: 	      $request->print("<p><span class=\"LC_error\">".
                   4273:                               &mt("Failed to save data for student [_1]. Message when trying to save was: [_2]",
                   4274:                                   "$username:$domain",$result)."</span></p>");
                   4275: 	   }
                   4276: 	   $request->rflush();
                   4277: 	   $countdone++;
                   4278:         }
1.41      ng       4279:     }
1.570     www      4280:     $request->print('<br />'.&Apache::lonhtmlcommon::confirm_success(&mt("Saved scores for [quant,_1,student]",$countdone),$countdone==0));
1.41      ng       4281:     if (@skipped) {
1.571     www      4282: 	$request->print('<br />'.&Apache::lonhtmlcommon::confirm_success(&mt('No scores stored for the following username(s):'),1).'<br />');
                   4283:         $request->print(join(', ',@skipped));
1.106     albertel 4284:     }
                   4285:     if (@notallowed) {
1.571     www      4286: 	$request->print('<br />'.&Apache::lonhtmlcommon::confirm_success(&mt('Modification of scores not allowed for the following username(s):'),1).'<br />');
                   4287: 	$request->print(join(', ',@notallowed));
1.41      ng       4288:     }
1.106     albertel 4289:     $request->print("<br />\n");
1.324     albertel 4290:     $request->print(&show_grading_menu_form($symb));
1.345     bowersj2 4291:     return $error_msg;
1.26      albertel 4292: }
1.44      ng       4293: #------------- end of section for handling csv file upload ---------
                   4294: #
                   4295: #-------------------------------------------------------------------
                   4296: #
1.122     ng       4297: #-------------- Next few routines handle grading by page/sequence
1.72      ng       4298: #
                   4299: #--- Select a page/sequence and a student to grade
1.68      ng       4300: sub pickStudentPage {
                   4301:     my ($request) = shift;
                   4302: 
1.539     riegler  4303:     my $alertmsg = &mt('Please select the student you wish to grade.');
1.68      ng       4304:     $request->print(<<LISTJAVASCRIPT);
                   4305: <script type="text/javascript" language="javascript">
                   4306: 
                   4307: function checkPickOne(formname) {
1.76      ng       4308:     if (radioSelection(formname.student) == null) {
1.539     riegler  4309: 	alert("$alertmsg");
1.68      ng       4310: 	return;
                   4311:     }
1.125     ng       4312:     ptr = pullDownSelection(formname.selectpage);
                   4313:     formname.page.value = formname["page"+ptr].value;
                   4314:     formname.title.value = formname["title"+ptr].value;
1.68      ng       4315:     formname.submit();
                   4316: }
                   4317: 
                   4318: </script>
                   4319: LISTJAVASCRIPT
1.118     ng       4320:     &commonJSfunctions($request);
1.324     albertel 4321:     my ($symb) = &get_symb($request);
1.257     albertel 4322:     my $cdom      = $env{"course.$env{'request.course.id'}.domain"};
                   4323:     my $cnum      = $env{"course.$env{'request.course.id'}.num"};
                   4324:     my $getsec    = $env{'form.section'} eq '' ? 'all' : $env{'form.section'};
1.68      ng       4325: 
1.398     albertel 4326:     my $result='<h3><span class="LC_info">&nbsp;'.
1.485     albertel 4327: 	&mt('Manual Grading by Page or Sequence').'</span></h3>';
1.68      ng       4328: 
1.80      ng       4329:     $result.='<form action="/adm/grades" method="post" name="displayPage">'."\n";
1.582     raeburn  4330:     my $map_error;
                   4331:     my ($titles,$symbx) = &getSymbMap($map_error);
                   4332:     if ($map_error) {
                   4333:         $request->print(&navmap_errormsg());
                   4334:         return; 
                   4335:     }
1.137     albertel 4336:     my ($curpage) =&Apache::lonnet::decode_symb($symb); 
                   4337: #    my ($curpage,$mapId) =&Apache::lonnet::decode_symb($symb); 
                   4338: #    my $type=($curpage =~ /\.(page|sequence)/);
1.485     albertel 4339:     my $select = '<select name="selectpage">'."\n";
1.70      ng       4340:     my $ctr=0;
1.68      ng       4341:     foreach (@$titles) {
                   4342: 	my ($minder,$showtitle) = ($_ =~ /(\d+)\.(.*)/);
1.485     albertel 4343: 	$select.='<option value="'.$ctr.'" '.
1.401     albertel 4344: 	    ($$symbx{$_} =~ /$curpage$/ ? 'selected="selected"' : '').
1.71      ng       4345: 	    '>'.$showtitle.'</option>'."\n";
1.70      ng       4346: 	$ctr++;
1.68      ng       4347:     }
1.485     albertel 4348:     $select.= '</select>';
1.539     riegler  4349:     $result.='&nbsp;<b>'.&mt('Problems from').':</b> '.$select."<br />\n";
1.485     albertel 4350: 
1.70      ng       4351:     $ctr=0;
                   4352:     foreach (@$titles) {
                   4353: 	my ($minder,$showtitle) = ($_ =~ /(\d+)\.(.*)/);
                   4354: 	$result.='<input type="hidden" name="page'.$ctr.'" value="'.$$symbx{$_}.'" />'."\n";
                   4355: 	$result.='<input type="hidden" name="title'.$ctr.'" value="'.$showtitle.'" />'."\n";
                   4356: 	$ctr++;
                   4357:     }
1.72      ng       4358:     $result.='<input type="hidden" name="page" />'."\n".
                   4359: 	'<input type="hidden" name="title" />'."\n";
1.68      ng       4360: 
1.485     albertel 4361:     my $options =
                   4362: 	'<label><input type="radio" name="vProb" value="no" checked="checked" /> '.&mt('no').' </label>'."\n".
                   4363: 	'<label><input type="radio" name="vProb" value="yes" /> '.&mt('yes').' </label>'."<br />\n";
1.539     riegler  4364:     $result.='&nbsp;<b>'.&mt('View Problem Text').': </b>'.$options;
1.485     albertel 4365: 
                   4366:     $options =
                   4367: 	'<label><input type="radio" name="lastSub" value="none" /> '.&mt('none').' </label>'."\n".
                   4368: 	'<label><input type="radio" name="lastSub" value="datesub" checked="checked" /> '.&mt('by dates and submissions').'</label>'."\n".
                   4369: 	'<label><input type="radio" name="lastSub" value="all" /> '.&mt('all details').' </label>'."\n";
1.539     riegler  4370:     $result.='&nbsp;<b>'.&mt('Submissions').': </b>'.$options;
1.432     banghart 4371:     
                   4372:     $result.=&build_section_inputs();
1.442     banghart 4373:     my $stu_status = join(':',&Apache::loncommon::get_env_multiple('form.Status'));
                   4374:     $result.='<input type="hidden" name="Status"  value="'.$stu_status.'" />'."\n".
1.72      ng       4375: 	'<input type="hidden" name="command" value="displayPage" />'."\n".
1.418     albertel 4376: 	'<input type="hidden" name="symb"    value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
1.257     albertel 4377: 	'<input type="hidden" name="saveState" value="'.$env{'form.saveState'}.'" />'."<br />\n";
1.72      ng       4378: 
1.539     riegler  4379:     $result.='&nbsp;<b>'.&mt('Use CODE').': </b> <input type="text" name="CODE" value="" /> <br />'."\n";
1.382     albertel 4380: 
1.80      ng       4381:     $result.='&nbsp;<input type="button" '.
1.589     bisitz   4382:              'onclick="javascript:checkPickOne(this.form);" value="'.&mt('Next').' &rarr;" /><br />'."\n";
1.72      ng       4383: 
1.68      ng       4384:     $request->print($result);
                   4385: 
1.485     albertel 4386:     my $studentTable.='&nbsp;<b>'.&mt('Select a student you wish to grade and then click on the Next button.').'</b><br />'.
1.484     albertel 4387: 	&Apache::loncommon::start_data_table().
                   4388: 	&Apache::loncommon::start_data_table_header_row().
1.485     albertel 4389: 	'<th align="right">&nbsp;'.&mt('No.').'</th>'.
1.484     albertel 4390: 	'<th>'.&nameUserString('header').'</th>'.
1.485     albertel 4391: 	'<th align="right">&nbsp;'.&mt('No.').'</th>'.
1.484     albertel 4392: 	'<th>'.&nameUserString('header').'</th>'.
                   4393: 	&Apache::loncommon::end_data_table_header_row();
1.68      ng       4394:  
1.76      ng       4395:     my (undef,undef,$fullname) = &getclasslist($getsec,'1');
1.68      ng       4396:     my $ptr = 1;
1.294     albertel 4397:     foreach my $student (sort 
                   4398: 			 {
                   4399: 			     if (lc($$fullname{$a}) ne lc($$fullname{$b})) {
                   4400: 				 return (lc($$fullname{$a}) cmp lc($$fullname{$b}));
                   4401: 			     }
                   4402: 			     return $a cmp $b;
                   4403: 			 } (keys(%$fullname))) {
1.68      ng       4404: 	my ($uname,$udom) = split(/:/,$student);
1.484     albertel 4405: 	$studentTable.=($ptr%2==1 ? &Apache::loncommon::start_data_table_row()
                   4406:                                   : '</td>');
1.126     ng       4407: 	$studentTable.='<td align="right">'.$ptr.'&nbsp;</td>';
1.288     albertel 4408: 	$studentTable.='<td>&nbsp;<label><input type="radio" name="student" value="'.$student.'" /> '
                   4409: 	    .&nameUserString(undef,$$fullname{$student},$uname,$udom)."</label>\n";
1.484     albertel 4410: 	$studentTable.=
                   4411: 	    ($ptr%2 == 0 ? '</td>'.&Apache::loncommon::end_data_table_row() 
                   4412:                          : '');
1.68      ng       4413: 	$ptr++;
                   4414:     }
1.484     albertel 4415:     if ($ptr%2 == 0) {
                   4416: 	$studentTable.='</td><td>&nbsp;</td><td>&nbsp;</td>'.
                   4417: 	    &Apache::loncommon::end_data_table_row();
                   4418:     }
                   4419:     $studentTable.=&Apache::loncommon::end_data_table()."\n";
1.126     ng       4420:     $studentTable.='<input type="button" '.
1.589     bisitz   4421:                    'onclick="javascript:checkPickOne(this.form);" value="'.&mt('Next').' &rarr;" /></form>'."\n";
1.68      ng       4422: 
1.324     albertel 4423:     $studentTable.=&show_grading_menu_form($symb);
1.68      ng       4424:     $request->print($studentTable);
                   4425: 
                   4426:     return '';
                   4427: }
                   4428: 
                   4429: sub getSymbMap {
1.582     raeburn  4430:     my ($map_error) = @_;
1.132     bowersj2 4431:     my $navmap = Apache::lonnavmaps::navmap->new();
1.582     raeburn  4432:     unless (ref($navmap)) {
                   4433:         if (ref($map_error)) {
                   4434:             $$map_error = 'navmap';
                   4435:         }
                   4436:         return;
                   4437:     }
1.68      ng       4438:     my %symbx = ();
                   4439:     my @titles = ();
1.117     bowersj2 4440:     my $minder = 0;
                   4441: 
                   4442:     # Gather every sequence that has problems.
1.240     albertel 4443:     my @sequences = $navmap->retrieveResources(undef, sub { shift->is_map(); },
                   4444: 					       1,0,1);
1.117     bowersj2 4445:     for my $sequence ($navmap->getById('0.0'), @sequences) {
1.241     albertel 4446: 	if ($navmap->hasResource($sequence, sub { shift->is_problem(); }, 0) ) {
1.381     albertel 4447: 	    my $title = $minder.'.'.
                   4448: 		&HTML::Entities::encode($sequence->compTitle(),'"\'&');
                   4449: 	    push(@titles, $title); # minder in case two titles are identical
                   4450: 	    $symbx{$title} = &HTML::Entities::encode($sequence->symb(),'"\'&');
1.117     bowersj2 4451: 	    $minder++;
1.241     albertel 4452: 	}
1.68      ng       4453:     }
                   4454:     return \@titles,\%symbx;
                   4455: }
                   4456: 
1.72      ng       4457: #
                   4458: #--- Displays a page/sequence w/wo problems, w/wo submissions
1.68      ng       4459: sub displayPage {
                   4460:     my ($request) = shift;
                   4461: 
1.324     albertel 4462:     my ($symb) = &get_symb($request);
1.257     albertel 4463:     my $cdom      = $env{"course.$env{'request.course.id'}.domain"};
                   4464:     my $cnum      = $env{"course.$env{'request.course.id'}.num"};
                   4465:     my $getsec    = $env{'form.section'} eq '' ? 'all' : $env{'form.section'};
                   4466:     my $pageTitle = $env{'form.page'};
1.103     albertel 4467:     my ($classlist,undef,$fullname) = &getclasslist($getsec,'1');
1.257     albertel 4468:     my ($uname,$udom) = split(/:/,$env{'form.student'});
                   4469:     my $usec=$classlist->{$env{'form.student'}}[5];
1.168     albertel 4470: 
                   4471:     #need to make sure we have the correct data for later EXT calls, 
                   4472:     #thus invalidate the cache
                   4473:     &Apache::lonnet::devalidatecourseresdata(
1.257     albertel 4474:                  $env{'course.'.$env{'request.course.id'}.'.num'},
                   4475:                  $env{'course.'.$env{'request.course.id'}.'.domain'});
1.168     albertel 4476:     &Apache::lonnet::clear_EXT_cache_status();
                   4477: 
1.103     albertel 4478:     if (!&canview($usec)) {
1.485     albertel 4479: 	$request->print('<span class="LC_warning">'.&mt('Unable to view requested student. ([_1])',$env{'form.student'}).'</span>');
1.324     albertel 4480: 	$request->print(&show_grading_menu_form($symb));
1.103     albertel 4481: 	return;
                   4482:     }
1.398     albertel 4483:     my $result='<h3><span class="LC_info">&nbsp;'.$env{'form.title'}.'</span></h3>';
1.485     albertel 4484:     $result.='<h3>&nbsp;'.&mt('Student: [_1]',&nameUserString(undef,$$fullname{$env{'form.student'}},$uname,$udom)).
1.129     ng       4485: 	'</h3>'."\n";
1.500     albertel 4486:     $env{'form.CODE'} = uc($env{'form.CODE'});
1.501     foxr     4487:     if (&Apache::lonnet::validCODE(uc($env{'form.CODE'}))) {
1.485     albertel 4488: 	$result.='<h3>&nbsp;'.&mt('CODE: [_1]',$env{'form.CODE'}).'</h3>'."\n";
1.382     albertel 4489:     } else {
                   4490: 	delete($env{'form.CODE'});
                   4491:     }
1.71      ng       4492:     &sub_page_js($request);
                   4493:     $request->print($result);
                   4494: 
1.132     bowersj2 4495:     my $navmap = Apache::lonnavmaps::navmap->new();
1.582     raeburn  4496:     unless (ref($navmap)) {
                   4497:         $request->print(&navmap_errormsg());
                   4498:         $request->print(&show_grading_menu_form($symb));
                   4499:         return;
                   4500:     }
1.257     albertel 4501:     my ($mapUrl, $id, $resUrl)=&Apache::lonnet::decode_symb($env{'form.page'});
1.68      ng       4502:     my $map = $navmap->getResourceByUrl($resUrl); # add to navmaps
1.288     albertel 4503:     if (!$map) {
1.485     albertel 4504: 	$request->print('<span class="LC_warning">'.&mt('Unable to view requested sequence. ([_1])',$resUrl).'</span>');
1.324     albertel 4505: 	$request->print(&show_grading_menu_form($symb));
1.288     albertel 4506: 	return; 
                   4507:     }
1.68      ng       4508:     my $iterator = $navmap->getIterator($map->map_start(),
                   4509: 					$map->map_finish());
                   4510: 
1.71      ng       4511:     my $studentTable='<form action="/adm/grades" method="post" name="gradePage">'."\n".
1.72      ng       4512: 	'<input type="hidden" name="command" value="gradeByPage" />'."\n".
1.257     albertel 4513: 	'<input type="hidden" name="fullname" value="'.$$fullname{$env{'form.student'}}.'" />'."\n".
                   4514: 	'<input type="hidden" name="student" value="'.$env{'form.student'}.'" />'."\n".
1.72      ng       4515: 	'<input type="hidden" name="page"    value="'.$pageTitle.'" />'."\n".
1.257     albertel 4516: 	'<input type="hidden" name="title"   value="'.$env{'form.title'}.'" />'."\n".
1.418     albertel 4517: 	'<input type="hidden" name="symb"    value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
1.125     ng       4518: 	'<input type="hidden" name="overRideScore" value="no" />'."\n".
1.257     albertel 4519: 	'<input type="hidden" name="saveState" value="'.$env{'form.saveState'}.'" />'."\n";
1.71      ng       4520: 
1.382     albertel 4521:     if (defined($env{'form.CODE'})) {
                   4522: 	$studentTable.=
                   4523: 	    '<input type="hidden" name="CODE" value="'.$env{'form.CODE'}.'" />'."\n";
                   4524:     }
1.381     albertel 4525:     my $checkIcon = '<img alt="'.&mt('Check Mark').
1.485     albertel 4526: 	'" src="'.&Apache::loncommon::lonhttpdurl($request->dir_config('lonIconsURL').'/check.gif').'" height="16" border="0" />';
1.71      ng       4527: 
1.594     bisitz   4528:     $studentTable.='&nbsp;<span class="LC_info">'.
                   4529:         &mt('Problems graded correct by the computer are marked with a [_1] symbol.',$checkIcon).
                   4530:         '</span>'."\n".
1.484     albertel 4531: 	&Apache::loncommon::start_data_table().
                   4532: 	&Apache::loncommon::start_data_table_header_row().
                   4533: 	'<th align="center">&nbsp;Prob.&nbsp;</th>'.
1.485     albertel 4534: 	'<th>&nbsp;'.($env{'form.vProb'} eq 'no' ? &mt('Title') : &mt('Problem Text')).'/'.&mt('Grade').'</th>'.
1.484     albertel 4535: 	&Apache::loncommon::end_data_table_header_row();
1.71      ng       4536: 
1.329     albertel 4537:     &Apache::lonxml::clear_problem_counter();
1.196     albertel 4538:     my ($depth,$question,$prob) = (1,1,1);
1.68      ng       4539:     $iterator->next(); # skip the first BEGIN_MAP
                   4540:     my $curRes = $iterator->next(); # for "current resource"
1.101     albertel 4541:     while ($depth > 0) {
1.68      ng       4542:         if($curRes == $iterator->BEGIN_MAP) { $depth++; }
1.100     bowersj2 4543:         if($curRes == $iterator->END_MAP) { $depth--; }
1.68      ng       4544: 
1.385     albertel 4545:         if (ref($curRes) && $curRes->is_problem()) {
1.91      albertel 4546: 	    my $parts = $curRes->parts();
1.68      ng       4547:             my $title = $curRes->compTitle();
1.71      ng       4548: 	    my $symbx = $curRes->symb();
1.484     albertel 4549: 	    $studentTable.=
                   4550: 		&Apache::loncommon::start_data_table_row().
                   4551: 		'<td align="center" valign="top" >'.$prob.
1.485     albertel 4552: 		(scalar(@{$parts}) == 1 ? '' 
1.596.2.2! raeburn  4553: 		                        : '<br />('.&mt('[_1]parts)',
        !          4554: 							scalar(@{$parts}).'&nbsp;')
1.485     albertel 4555: 		 ).
                   4556: 		 '</td>';
1.71      ng       4557: 	    $studentTable.='<td valign="top">';
1.382     albertel 4558: 	    my %form = ('CODE' => $env{'form.CODE'},);
1.257     albertel 4559: 	    if ($env{'form.vProb'} eq 'yes' ) {
1.144     albertel 4560: 		$studentTable.=&show_problem($request,$symbx,$uname,$udom,1,
1.383     albertel 4561: 					     undef,'both',\%form);
1.71      ng       4562: 	    } else {
1.382     albertel 4563: 		my $companswer = &Apache::loncommon::get_student_answers($symbx,$uname,$udom,$env{'request.course.id'},%form);
1.80      ng       4564: 		$companswer =~ s|<form(.*?)>||g;
                   4565: 		$companswer =~ s|</form>||g;
1.71      ng       4566: #		while ($companswer =~ /(<a href\=\"javascript:newWindow.*?Script Vars<\/a>)/s) { #<a href="javascript:newWindow</a>
1.116     ng       4567: #		    $companswer =~ s/$1/ /ms;
1.326     albertel 4568: #		    $request->print('match='.$1."<br />\n");
1.71      ng       4569: #		}
1.116     ng       4570: #		$companswer =~ s|<table border=\"1\">|<table border=\"0\">|g;
1.539     riegler  4571: 		$studentTable.='&nbsp;<b>'.$title.'</b>&nbsp;<br />&nbsp;<b>'.&mt('Correct answer').':</b><br />'.$companswer;
1.71      ng       4572: 	    }
                   4573: 
1.257     albertel 4574: 	    my %record = &Apache::lonnet::restore($symbx,$env{'request.course.id'},$udom,$uname);
1.125     ng       4575: 
1.257     albertel 4576: 	    if ($env{'form.lastSub'} eq 'datesub') {
1.71      ng       4577: 		if ($record{'version'} eq '') {
1.485     albertel 4578: 		    $studentTable.='<br />&nbsp;<span class="LC_warning">'.&mt('No recorded submission for this problem.').'</span><br />';
1.71      ng       4579: 		} else {
1.116     ng       4580: 		    my %responseType = ();
                   4581: 		    foreach my $partid (@{$parts}) {
1.147     albertel 4582: 			my @responseIds =$curRes->responseIds($partid);
                   4583: 			my @responseType =$curRes->responseType($partid);
                   4584: 			my %responseIds;
                   4585: 			for (my $i=0;$i<=$#responseIds;$i++) {
                   4586: 			    $responseIds{$responseIds[$i]}=$responseType[$i];
                   4587: 			}
                   4588: 			$responseType{$partid} = \%responseIds;
1.116     ng       4589: 		    }
1.148     albertel 4590: 		    $studentTable.= &displaySubByDates($symbx,\%record,$parts,\%responseType,$checkIcon,$uname,$udom);
1.147     albertel 4591: 
1.71      ng       4592: 		}
1.257     albertel 4593: 	    } elsif ($env{'form.lastSub'} eq 'all') {
                   4594: 		my $last = ($env{'form.lastSub'} eq 'last' ? 'last' : '');
1.71      ng       4595: 		$studentTable.=&Apache::loncommon::get_previous_attempt($symbx,$uname,$udom,
1.257     albertel 4596: 									$env{'request.course.id'},
1.71      ng       4597: 									'','.submission');
                   4598:  
                   4599: 	    }
1.103     albertel 4600: 	    if (&canmodify($usec)) {
1.585     bisitz   4601:             $studentTable.=&gradeBox_start();
1.103     albertel 4602: 		foreach my $partid (@{$parts}) {
                   4603: 		    $studentTable.=&gradeBox($request,$symbx,$uname,$udom,$question,$partid,\%record);
                   4604: 		    $studentTable.='<input type="hidden" name="q_'.$question.'" value="'.$partid.'" />'."\n";
                   4605: 		    $question++;
                   4606: 		}
1.585     bisitz   4607:             $studentTable.=&gradeBox_end();
1.196     albertel 4608: 		$prob++;
1.71      ng       4609: 	    }
                   4610: 	    $studentTable.='</td></tr>';
1.68      ng       4611: 
1.103     albertel 4612: 	}
1.68      ng       4613:         $curRes = $iterator->next();
                   4614:     }
                   4615: 
1.589     bisitz   4616:     $studentTable.=
                   4617:         '</table>'."\n".
                   4618:         '<input type="button" value="'.&mt('Save').'" '.
                   4619:         'onclick="javascript:checkSubmitPage(this.form,'.$question.');" />'.
                   4620:         '</form>'."\n";
1.324     albertel 4621:     $studentTable.=&show_grading_menu_form($symb);
1.71      ng       4622:     $request->print($studentTable);
                   4623: 
                   4624:     return '';
1.119     ng       4625: }
                   4626: 
                   4627: sub displaySubByDates {
1.148     albertel 4628:     my ($symb,$record,$parts,$responseType,$checkIcon,$uname,$udom) = @_;
1.224     albertel 4629:     my $isCODE=0;
1.335     albertel 4630:     my $isTask = ($symb =~/\.task$/);
1.224     albertel 4631:     if (exists($record->{'resource.CODE'})) { $isCODE=1; }
1.467     albertel 4632:     my $studentTable=&Apache::loncommon::start_data_table().
                   4633: 	&Apache::loncommon::start_data_table_header_row().
                   4634: 	'<th>'.&mt('Date/Time').'</th>'.
                   4635: 	($isCODE?'<th>'.&mt('CODE').'</th>':'').
                   4636: 	'<th>'.&mt('Submission').'</th>'.
                   4637: 	'<th>'.&mt('Status').'</th>'.
                   4638: 	&Apache::loncommon::end_data_table_header_row();
1.119     ng       4639:     my ($version);
                   4640:     my %mark;
1.148     albertel 4641:     my %orders;
1.119     ng       4642:     $mark{'correct_by_student'} = $checkIcon;
1.147     albertel 4643:     if (!exists($$record{'1:timestamp'})) {
1.539     riegler  4644: 	return '<br />&nbsp;<span class="LC_warning">'.&mt('Nothing submitted - no attempts.').'</span><br />';
1.147     albertel 4645:     }
1.335     albertel 4646: 
                   4647:     my $interaction;
1.525     raeburn  4648:     my $no_increment = 1;
1.596.2.2! raeburn  4649:     my %lastrndseed;
1.119     ng       4650:     for ($version=1;$version<=$$record{'version'};$version++) {
1.467     albertel 4651: 	my $timestamp = 
                   4652: 	    &Apache::lonlocal::locallocaltime($$record{$version.':timestamp'});
1.335     albertel 4653: 	if (exists($$record{$version.':resource.0.version'})) {
                   4654: 	    $interaction = $$record{$version.':resource.0.version'};
                   4655: 	}
                   4656: 
                   4657: 	my $where = ($isTask ? "$version:resource.$interaction"
                   4658: 		             : "$version:resource");
1.467     albertel 4659: 	$studentTable.=&Apache::loncommon::start_data_table_row().
                   4660: 	    '<td>'.$timestamp.'</td>';
1.224     albertel 4661: 	if ($isCODE) {
                   4662: 	    $studentTable.='<td>'.$record->{$version.':resource.CODE'}.'</td>';
                   4663: 	}
1.119     ng       4664: 	my @versionKeys = split(/\:/,$$record{$version.':keys'});
                   4665: 	my @displaySub = ();
                   4666: 	foreach my $partid (@{$parts}) {
1.596.2.2! raeburn  4667:             my ($hidden,$type);
        !          4668:             $type = $$record{$version.':resource.'.$partid.'.type'};
        !          4669:             if (($type eq 'anonsurvey') || ($type eq 'anonsurveycred')) {
1.596     raeburn  4670:                 $hidden = 1;
                   4671:             }
1.335     albertel 4672: 	    my @matchKey = ($isTask ? sort(grep /^resource\.\d+\.\Q$partid\E\.award$/,@versionKeys)
                   4673: 			            : sort(grep /^resource\.\Q$partid\E\..*?\.submission$/,@versionKeys));
                   4674: 	    
1.122     ng       4675: #	    next if ($$record{"$version:resource.$partid.solved"} eq '');
1.324     albertel 4676: 	    my $display_part=&get_display_part($partid,$symb);
1.147     albertel 4677: 	    foreach my $matchKey (@matchKey) {
1.198     albertel 4678: 		if (exists($$record{$version.':'.$matchKey}) &&
                   4679: 		    $$record{$version.':'.$matchKey} ne '') {
1.596     raeburn  4680:                     
1.335     albertel 4681: 		    my ($responseId)= ($isTask ? ($matchKey=~ /^resource\.(.*?)\.\Q$partid\E\.award$/)
                   4682: 				               : ($matchKey=~ /^resource\.\Q$partid\E\.(.*?)\.submission$/));
1.577     bisitz   4683:                     $displaySub[0].='<span class="LC_nobreak"';
                   4684:                     $displaySub[0].='<b>'.&mt('Part: [_1]',$display_part).'</b>'
                   4685:                                    .' <span class="LC_internal_info">'
                   4686:                                    .'('.&mt('Part ID: [_1]',$responseId).')'
                   4687:                                    .'</span>'
                   4688:                                    .' <b>';
1.596     raeburn  4689:                     if ($hidden) {
                   4690:                         $displaySub[0].= &mt('Anonymous Survey').'</b>';
                   4691:                     } else {
1.596.2.2! raeburn  4692:                         my ($trial,$rndseed,$newvariation);
        !          4693:                         if ($type eq 'randomizetry') {
        !          4694:                             $trial = $$record{"$where.$partid.tries"};
        !          4695:                             $rndseed = $$record{"$where.$partid.rndseed"};
        !          4696:                         }
1.596     raeburn  4697: 		        if ($$record{"$where.$partid.tries"} eq '') {
                   4698: 			    $displaySub[0].=&mt('Trial not counted');
                   4699: 		        } else {
                   4700: 			    $displaySub[0].=&mt('Trial: [_1]',
1.467     albertel 4701: 					    $$record{"$where.$partid.tries"});
1.596.2.2! raeburn  4702:                             if ($rndseed || $lastrndseed{$partid}) {
        !          4703:                                 if ($rndseed ne $lastrndseed{$partid}) {
        !          4704:                                     $newvariation = '&nbsp;('.&mt('New variation this try').')';
        !          4705:                                 }
        !          4706:                             }
1.596     raeburn  4707: 		        }
                   4708: 		        my $responseType=($isTask ? 'Task'
1.335     albertel 4709:                                               : $responseType->{$partid}->{$responseId});
1.596     raeburn  4710: 		        if (!exists($orders{$partid})) { $orders{$partid}={}; }
1.596.2.2! raeburn  4711: 		        if ((!exists($orders{$partid}->{$responseId})) || ($trial)) {
1.596     raeburn  4712: 			    $orders{$partid}->{$responseId}=
                   4713: 			        &get_order($partid,$responseId,$symb,$uname,$udom,
1.596.2.2! raeburn  4714:                                            $no_increment,$type,$trial,$rndseed);
1.596     raeburn  4715: 		        }
1.596.2.2! raeburn  4716: 		        $displaySub[0].='</b>'.$newvariation.'</span>'; # /nobreak
1.596     raeburn  4717: 		        $displaySub[0].='&nbsp; '.
1.596.2.2! raeburn  4718: 			    &cleanRecord($$record{$version.':'.$matchKey},$responseType,$symb,$partid,$responseId,$record,$orders{$partid}->{$responseId},"$version:",$uname,$udom,$type,$trial,$rndseed).'<br />';
1.596     raeburn  4719:                     }
1.147     albertel 4720: 		}
                   4721: 	    }
1.335     albertel 4722: 	    if (exists($$record{"$where.$partid.checkedin"})) {
1.485     albertel 4723: 		$displaySub[1].=&mt('Checked in by [_1] into slot [_2]',
                   4724: 				    $$record{"$where.$partid.checkedin"},
                   4725: 				    $$record{"$where.$partid.checkedin.slot"}).
                   4726: 					'<br />';
1.335     albertel 4727: 	    }
                   4728: 	    if (exists $$record{"$where.$partid.award"}) {
1.485     albertel 4729: 		$displaySub[1].='<b>'.&mt('Part:').'</b>&nbsp;'.$display_part.' &nbsp;'.
1.335     albertel 4730: 		    lc($$record{"$where.$partid.award"}).' '.
                   4731: 		    $mark{$$record{"$where.$partid.solved"}}.
1.147     albertel 4732: 		    '<br />';
                   4733: 	    }
1.335     albertel 4734: 	    if (exists $$record{"$where.$partid.regrader"}) {
                   4735: 		$displaySub[2].=$$record{"$where.$partid.regrader"}.
                   4736: 		    ' (<b>'.&mt('Part').':</b> '.$display_part.')';
                   4737: 	    } elsif ($$record{"$version:resource.$partid.regrader"} =~ /\S/) {
                   4738: 		$displaySub[2].=
                   4739: 		    $$record{"$version:resource.$partid.regrader"}.
1.207     albertel 4740: 		    ' (<b>'.&mt('Part').':</b> '.$display_part.')';
1.147     albertel 4741: 	    }
                   4742: 	}
                   4743: 	# needed because old essay regrader has not parts info
                   4744: 	if (exists $$record{"$version:resource.regrader"}) {
                   4745: 	    $displaySub[2].=$$record{"$version:resource.regrader"};
                   4746: 	}
                   4747: 	$studentTable.='<td>'.$displaySub[0].'&nbsp;</td><td>'.$displaySub[1];
                   4748: 	if ($displaySub[2]) {
1.467     albertel 4749: 	    $studentTable.=&mt('Manually graded by [_1]',$displaySub[2]);
1.147     albertel 4750: 	}
1.467     albertel 4751: 	$studentTable.='&nbsp;</td>'.
                   4752: 	    &Apache::loncommon::end_data_table_row();
1.119     ng       4753:     }
1.467     albertel 4754:     $studentTable.=&Apache::loncommon::end_data_table();
1.119     ng       4755:     return $studentTable;
1.71      ng       4756: }
                   4757: 
                   4758: sub updateGradeByPage {
                   4759:     my ($request) = shift;
                   4760: 
1.257     albertel 4761:     my $cdom      = $env{"course.$env{'request.course.id'}.domain"};
                   4762:     my $cnum      = $env{"course.$env{'request.course.id'}.num"};
                   4763:     my $getsec    = $env{'form.section'} eq '' ? 'all' : $env{'form.section'};
                   4764:     my $pageTitle = $env{'form.page'};
1.103     albertel 4765:     my ($classlist,undef,$fullname) = &getclasslist($getsec,'1');
1.257     albertel 4766:     my ($uname,$udom) = split(/:/,$env{'form.student'});
                   4767:     my $usec=$classlist->{$env{'form.student'}}[5];
1.103     albertel 4768:     if (!&canmodify($usec)) {
1.526     raeburn  4769: 	$request->print('<span class="LC_warning">'.&mt('Unable to modify requested student ([_1])',$env{'form.student'}).'</span>');
1.324     albertel 4770: 	$request->print(&show_grading_menu_form($env{'form.symb'}));
1.103     albertel 4771: 	return;
                   4772:     }
1.398     albertel 4773:     my $result='<h3><span class="LC_info">&nbsp;'.$env{'form.title'}.'</span></h3>';
1.526     raeburn  4774:     $result.='<h3>&nbsp;'.&mt('Student: ').&nameUserString(undef,$env{'form.fullname'},$uname,$udom).
1.129     ng       4775: 	'</h3>'."\n";
1.70      ng       4776: 
1.68      ng       4777:     $request->print($result);
                   4778: 
1.582     raeburn  4779: 
1.132     bowersj2 4780:     my $navmap = Apache::lonnavmaps::navmap->new();
1.582     raeburn  4781:     unless (ref($navmap)) {
                   4782:         $request->print(&navmap_errormsg());
                   4783:         return;
                   4784:     }
1.257     albertel 4785:     my ($mapUrl, $id, $resUrl) = &Apache::lonnet::decode_symb( $env{'form.page'});
1.71      ng       4786:     my $map = $navmap->getResourceByUrl($resUrl); # add to navmaps
1.288     albertel 4787:     if (!$map) {
1.527     raeburn  4788: 	$request->print('<span class="LC_warning">'.&mt('Unable to grade requested sequence ([_1]).',$resUrl).'</span>');
1.324     albertel 4789: 	my ($symb)=&get_symb($request);
                   4790: 	$request->print(&show_grading_menu_form($symb));
1.288     albertel 4791: 	return; 
                   4792:     }
1.71      ng       4793:     my $iterator = $navmap->getIterator($map->map_start(),
                   4794: 					$map->map_finish());
1.70      ng       4795: 
1.484     albertel 4796:     my $studentTable=
                   4797: 	&Apache::loncommon::start_data_table().
                   4798: 	&Apache::loncommon::start_data_table_header_row().
1.485     albertel 4799: 	'<th align="center">&nbsp;'.&mt('Prob.').'&nbsp;</th>'.
                   4800: 	'<th>&nbsp;'.&mt('Title').'&nbsp;</th>'.
                   4801: 	'<th>&nbsp;'.&mt('Previous Score').'&nbsp;</th>'.
                   4802: 	'<th>&nbsp;'.&mt('New Score').'&nbsp;</th>'.
1.484     albertel 4803: 	&Apache::loncommon::end_data_table_header_row();
1.71      ng       4804: 
                   4805:     $iterator->next(); # skip the first BEGIN_MAP
                   4806:     my $curRes = $iterator->next(); # for "current resource"
1.196     albertel 4807:     my ($depth,$question,$prob,$changeflag)= (1,1,1,0);
1.101     albertel 4808:     while ($depth > 0) {
1.71      ng       4809:         if($curRes == $iterator->BEGIN_MAP) { $depth++; }
1.100     bowersj2 4810:         if($curRes == $iterator->END_MAP) { $depth--; }
1.71      ng       4811: 
1.385     albertel 4812:         if (ref($curRes) && $curRes->is_problem()) {
1.91      albertel 4813: 	    my $parts = $curRes->parts();
1.71      ng       4814:             my $title = $curRes->compTitle();
                   4815: 	    my $symbx = $curRes->symb();
1.484     albertel 4816: 	    $studentTable.=
                   4817: 		&Apache::loncommon::start_data_table_row().
                   4818: 		'<td align="center" valign="top" >'.$prob.
1.485     albertel 4819: 		(scalar(@{$parts}) == 1 ? '' 
1.596.2.2! raeburn  4820:                                         : '<br />('.&mt('[quant,_1,part]',scalar(@{$parts}))
1.526     raeburn  4821: 		.')').'</td>';
1.71      ng       4822: 	    $studentTable.='<td valign="top">&nbsp;<b>'.$title.'</b>&nbsp;</td>';
                   4823: 
                   4824: 	    my %newrecord=();
                   4825: 	    my @displayPts=();
1.269     raeburn  4826:             my %aggregate = ();
                   4827:             my $aggregateflag = 0;
1.71      ng       4828: 	    foreach my $partid (@{$parts}) {
1.257     albertel 4829: 		my $newpts = $env{'form.GD_BOX'.$question.'_'.$partid};
                   4830: 		my $oldpts = $env{'form.oldpts'.$question.'_'.$partid};
1.71      ng       4831: 
1.257     albertel 4832: 		my $wgt = $env{'form.WGT'.$question.'_'.$partid} != 0 ? 
                   4833: 		    $env{'form.WGT'.$question.'_'.$partid} : 1;
1.71      ng       4834: 		my $partial = $newpts/$wgt;
                   4835: 		my $score;
                   4836: 		if ($partial > 0) {
                   4837: 		    $score = 'correct_by_override';
1.125     ng       4838: 		} elsif ($newpts ne '') { #empty is taken as 0
1.71      ng       4839: 		    $score = 'incorrect_by_override';
                   4840: 		}
1.257     albertel 4841: 		my $dropMenu = $env{'form.GD_SEL'.$question.'_'.$partid};
1.125     ng       4842: 		if ($dropMenu eq 'excused') {
1.71      ng       4843: 		    $partial = '';
                   4844: 		    $score = 'excused';
1.125     ng       4845: 		} elsif ($dropMenu eq 'reset status'
1.257     albertel 4846: 			 && $env{'form.solved'.$question.'_'.$partid} ne '') { #update only if previous record exists
1.125     ng       4847: 		    $newrecord{'resource.'.$partid.'.tries'} = 0;
                   4848: 		    $newrecord{'resource.'.$partid.'.solved'} = '';
                   4849: 		    $newrecord{'resource.'.$partid.'.award'} = '';
                   4850: 		    $newrecord{'resource.'.$partid.'.awarded'} = 0;
1.257     albertel 4851: 		    $newrecord{'resource.'.$partid.'.regrader'} = "$env{'user.name'}:$env{'user.domain'}";
1.125     ng       4852: 		    $changeflag++;
                   4853: 		    $newpts = '';
1.269     raeburn  4854:                     
                   4855:                     my $aggtries =  $env{'form.aggtries'.$question.'_'.$partid};
                   4856:                     my $totaltries = $env{'form.totaltries'.$question.'_'.$partid};
                   4857:                     my $solvedstatus = $env{'form.solved'.$question.'_'.$partid};
                   4858:                     if ($aggtries > 0) {
                   4859:                         &decrement_aggs($symbx,$partid,\%aggregate,$aggtries,$totaltries,$solvedstatus);
                   4860:                         $aggregateflag = 1;
                   4861:                     }
1.71      ng       4862: 		}
1.324     albertel 4863: 		my $display_part=&get_display_part($partid,$curRes->symb());
1.257     albertel 4864: 		my $oldstatus = $env{'form.solved'.$question.'_'.$partid};
1.526     raeburn  4865: 		$displayPts[0].='&nbsp;<b>'.&mt('Part').':</b> '.$display_part.' = '.
1.71      ng       4866: 		    (($oldstatus eq 'excused') ? 'excused' : $oldpts).
1.326     albertel 4867: 		    '&nbsp;<br />';
1.526     raeburn  4868: 		$displayPts[1].='&nbsp;<b>'.&mt('Part').':</b> '.$display_part.' = '.
1.125     ng       4869: 		     (($score eq 'excused') ? 'excused' : $newpts).
1.326     albertel 4870: 		    '&nbsp;<br />';
1.71      ng       4871: 		$question++;
1.380     albertel 4872: 		next if ($dropMenu eq 'reset status' || ($newpts eq $oldpts && $score ne 'excused'));
1.125     ng       4873: 
1.71      ng       4874: 		$newrecord{'resource.'.$partid.'.awarded'}  = $partial if $partial ne '';
1.125     ng       4875: 		$newrecord{'resource.'.$partid.'.solved'}   = $score if $score ne '';
1.257     albertel 4876: 		$newrecord{'resource.'.$partid.'.regrader'} = "$env{'user.name'}:$env{'user.domain'}"
1.125     ng       4877: 		    if (scalar(keys(%newrecord)) > 0);
1.71      ng       4878: 
                   4879: 		$changeflag++;
                   4880: 	    }
                   4881: 	    if (scalar(keys(%newrecord)) > 0) {
1.382     albertel 4882: 		my %record = 
                   4883: 		    &Apache::lonnet::restore($symbx,$env{'request.course.id'},
                   4884: 					     $udom,$uname);
                   4885: 
                   4886: 		if (&Apache::lonnet::validCODE($env{'form.CODE'})) {
                   4887: 		    $newrecord{'resource.CODE'} = $env{'form.CODE'};
                   4888: 		} elsif (&Apache::lonnet::validCODE($record{'resource.CODE'})) {
                   4889: 		    $newrecord{'resource.CODE'} = '';
                   4890: 		}
1.257     albertel 4891: 		&Apache::lonnet::cstore(\%newrecord,$symbx,$env{'request.course.id'},
1.71      ng       4892: 					$udom,$uname);
1.382     albertel 4893: 		%record = &Apache::lonnet::restore($symbx,
                   4894: 						   $env{'request.course.id'},
                   4895: 						   $udom,$uname);
1.380     albertel 4896: 		&check_and_remove_from_queue($parts,\%record,undef,$symbx,
                   4897: 					     $cdom,$cnum,$udom,$uname);
1.71      ng       4898: 	    }
1.380     albertel 4899: 	    
1.269     raeburn  4900:             if ($aggregateflag) {
                   4901:                 &Apache::lonnet::cinc('nohist_resourcetracker',\%aggregate,
                   4902:                       $env{'course.'.$env{'request.course.id'}.'.domain'},
                   4903:                       $env{'course.'.$env{'request.course.id'}.'.num'});
                   4904:             }
1.125     ng       4905: 
1.71      ng       4906: 	    $studentTable.='<td valign="top">'.$displayPts[0].'</td>'.
                   4907: 		'<td valign="top">'.$displayPts[1].'</td>'.
1.484     albertel 4908: 		&Apache::loncommon::end_data_table_row();
1.68      ng       4909: 
1.196     albertel 4910: 	    $prob++;
1.68      ng       4911: 	}
1.71      ng       4912:         $curRes = $iterator->next();
1.68      ng       4913:     }
1.98      albertel 4914: 
1.484     albertel 4915:     $studentTable.=&Apache::loncommon::end_data_table();
1.324     albertel 4916:     $studentTable.=&show_grading_menu_form($env{'form.symb'});
1.526     raeburn  4917:     my $grademsg=($changeflag == 0 ? &mt('No score was changed or updated.') :
                   4918: 		  &mt('The scores were changed for [quant,_1,problem].',
                   4919: 		  $changeflag));
1.76      ng       4920:     $request->print($grademsg.$studentTable);
1.68      ng       4921: 
1.70      ng       4922:     return '';
                   4923: }
                   4924: 
1.72      ng       4925: #-------- end of section for handling grading by page/sequence ---------
                   4926: #
                   4927: #-------------------------------------------------------------------
                   4928: 
1.581     www      4929: #-------------------- Bubblesheet (Scantron) Grading -------------------
1.75      albertel 4930: #
                   4931: #------ start of section for handling grading by page/sequence ---------
                   4932: 
1.423     albertel 4933: =pod
                   4934: 
                   4935: =head1 Bubble sheet grading routines
                   4936: 
1.424     albertel 4937:   For this documentation:
                   4938: 
                   4939:    'scanline' refers to the full line of characters
                   4940:    from the file that we are parsing that represents one entire sheet
                   4941: 
                   4942:    'bubble line' refers to the data
                   4943:    representing the line of bubbles that are on the physical bubble sheet
                   4944: 
                   4945: 
                   4946: The overall process is that a scanned in bubble sheet data is uploaded
                   4947: into a course. When a user wants to grade, they select a
                   4948: sequence/folder of resources, a file of bubble sheet info, and pick
                   4949: one of the predefined configurations for what each scanline looks
                   4950: like.
                   4951: 
                   4952: Next each scanline is checked for any errors of either 'missing
1.435     foxr     4953: bubbles' (it's an error because it may have been mis-scanned
1.424     albertel 4954: because too light bubbling), 'double bubble' (each bubble line should
                   4955: have no more that one letter picked), invalid or duplicated CODE,
1.556     weissno  4956: invalid student/employee ID
1.424     albertel 4957: 
                   4958: If the CODE option is used that determines the randomization of the
1.556     weissno  4959: homework problems, either way the student/employee ID is looked up into a
1.424     albertel 4960: username:domain.
                   4961: 
                   4962: During the validation phase the instructor can choose to skip scanlines. 
                   4963: 
1.435     foxr     4964: After the validation phase, there are now 3 bubble sheet files
1.424     albertel 4965: 
                   4966:   scantron_original_filename (unmodified original file)
                   4967:   scantron_corrected_filename (file where the corrected information has replaced the original information)
                   4968:   scantron_skipped_filename (contains the exact text of scanlines that where skipped)
                   4969: 
                   4970: Also there is a separate hash nohist_scantrondata that contains extra
                   4971: correction information that isn't representable in the bubble sheet
                   4972: file (see &scantron_getfile() for more information)
                   4973: 
                   4974: After all scanlines are either valid, marked as valid or skipped, then
                   4975: foreach line foreach problem in the picked sequence, an ssi request is
                   4976: made that simulates a user submitting their selected letter(s) against
                   4977: the homework problem.
1.423     albertel 4978: 
                   4979: =over 4
                   4980: 
                   4981: 
                   4982: 
                   4983: =item defaultFormData
                   4984: 
                   4985:   Returns html hidden inputs used to hold context/default values.
                   4986: 
                   4987:  Arguments:
                   4988:   $symb - $symb of the current resource 
                   4989: 
                   4990: =cut
1.422     foxr     4991: 
1.81      albertel 4992: sub defaultFormData {
1.324     albertel 4993:     my ($symb)=@_;
1.447     foxr     4994:     return '<input type="hidden" name="symb"    value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
1.257     albertel 4995:      '<input type="hidden" name="saveState" value="'.$env{'form.saveState'}.'" />'."\n".
                   4996:      '<input type="hidden" name="probTitle" value="'.$env{'form.probTitle'}.'" />'."\n";
1.81      albertel 4997: }
                   4998: 
1.447     foxr     4999: 
1.423     albertel 5000: =pod 
                   5001: 
                   5002: =item getSequenceDropDown
                   5003: 
                   5004:    Return html dropdown of possible sequences to grade
                   5005:  
                   5006:  Arguments:
1.582     raeburn  5007:    $symb - $symb of the current resource
                   5008:    $map_error - ref to scalar which will container error if
                   5009:                 $navmap object is unavailable in &getSymbMap().
1.423     albertel 5010: 
                   5011: =cut
1.422     foxr     5012: 
1.75      albertel 5013: sub getSequenceDropDown {
1.582     raeburn  5014:     my ($symb,$map_error)=@_;
1.75      albertel 5015:     my $result='<select name="selectpage">'."\n";
1.582     raeburn  5016:     my ($titles,$symbx) = &getSymbMap($map_error);
                   5017:     if (ref($map_error)) {
                   5018:         return if ($$map_error);
                   5019:     }
1.137     albertel 5020:     my ($curpage)=&Apache::lonnet::decode_symb($symb); 
1.75      albertel 5021:     my $ctr=0;
                   5022:     foreach (@$titles) {
                   5023: 	my ($minder,$showtitle) = ($_ =~ /(\d+)\.(.*)/);
                   5024: 	$result.='<option value="'.$$symbx{$_}.'" '.
1.401     albertel 5025: 	    ($$symbx{$_} =~ /$curpage$/ ? 'selected="selected"' : '').
1.75      albertel 5026: 	    '>'.$showtitle.'</option>'."\n";
                   5027: 	$ctr++;
                   5028:     }
                   5029:     $result.= '</select>';
                   5030:     return $result;
                   5031: }
                   5032: 
1.495     albertel 5033: my %bubble_lines_per_response;     # no. bubble lines for each response.
1.554     raeburn  5034:                                    # key is zero-based index - 0, 1, 2 ...
1.495     albertel 5035: 
                   5036: my %first_bubble_line;             # First bubble line no. for each bubble.
                   5037: 
1.509     raeburn  5038: my %subdivided_bubble_lines;       # no. bubble lines for optionresponse, 
                   5039:                                    # matchresponse or rankresponse, where 
                   5040:                                    # an individual response can have multiple 
                   5041:                                    # lines
1.503     raeburn  5042: 
                   5043: my %responsetype_per_response;     # responsetype for each response
                   5044: 
1.495     albertel 5045: # Save and restore the bubble lines array to the form env.
                   5046: 
                   5047: 
                   5048: sub save_bubble_lines {
                   5049:     foreach my $line (keys(%bubble_lines_per_response)) {
                   5050: 	$env{"form.scantron.bubblelines.$line"}  = $bubble_lines_per_response{$line};
                   5051: 	$env{"form.scantron.first_bubble_line.$line"} =
                   5052: 	    $first_bubble_line{$line};
1.503     raeburn  5053:         $env{"form.scantron.sub_bubblelines.$line"} = 
                   5054:             $subdivided_bubble_lines{$line};
                   5055:         $env{"form.scantron.responsetype.$line"} =
                   5056:             $responsetype_per_response{$line};
1.495     albertel 5057:     }
                   5058: }
                   5059: 
                   5060: 
                   5061: sub restore_bubble_lines {
                   5062:     my $line = 0;
                   5063:     %bubble_lines_per_response = ();
                   5064:     while ($env{"form.scantron.bubblelines.$line"}) {
                   5065: 	my $value = $env{"form.scantron.bubblelines.$line"};
                   5066: 	$bubble_lines_per_response{$line} = $value;
                   5067: 	$first_bubble_line{$line}  =
                   5068: 	    $env{"form.scantron.first_bubble_line.$line"};
1.503     raeburn  5069:         $subdivided_bubble_lines{$line} =
                   5070:             $env{"form.scantron.sub_bubblelines.$line"};
                   5071:         $responsetype_per_response{$line} =
                   5072:             $env{"form.scantron.responsetype.$line"};
1.495     albertel 5073: 	$line++;
                   5074:     }
                   5075: }
                   5076: 
                   5077: #  Given the parsed scanline, get the response for 
                   5078: #  'answer' number n:
                   5079: 
                   5080: sub get_response_bubbles {
                   5081:     my ($parsed_line, $response)  = @_;
                   5082: 
                   5083:     my $bubble_line = $first_bubble_line{$response-1} +1;
                   5084:     my $bubble_lines= $bubble_lines_per_response{$response-1};
                   5085:     
                   5086:     my $selected = "";
                   5087: 
                   5088:     for (my $bline = 0; $bline < $bubble_lines; $bline++) {
                   5089: 	$selected .= $$parsed_line{"scantron.$bubble_line.answer"}.":";
                   5090: 	$bubble_line++;
                   5091:     }
                   5092:     return $selected;
                   5093: }
1.423     albertel 5094: 
                   5095: =pod 
                   5096: 
                   5097: =item scantron_filenames
                   5098: 
                   5099:    Returns a list of the scantron files in the current course 
                   5100: 
                   5101: =cut
1.422     foxr     5102: 
1.202     albertel 5103: sub scantron_filenames {
1.257     albertel 5104:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
                   5105:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
1.517     raeburn  5106:     my $getpropath = 1;
1.157     albertel 5107:     my @files=&Apache::lonnet::dirlist('userfiles',$cdom,$cname,
1.517     raeburn  5108:                                        $getpropath);
1.202     albertel 5109:     my @possiblenames;
1.201     albertel 5110:     foreach my $filename (sort(@files)) {
1.157     albertel 5111: 	($filename)=split(/&/,$filename);
                   5112: 	if ($filename!~/^scantron_orig_/) { next ; }
                   5113: 	$filename=~s/^scantron_orig_//;
1.202     albertel 5114: 	push(@possiblenames,$filename);
                   5115:     }
                   5116:     return @possiblenames;
                   5117: }
                   5118: 
1.423     albertel 5119: =pod 
                   5120: 
                   5121: =item scantron_uploads
                   5122: 
                   5123:    Returns  html drop-down list of scantron files in current course.
                   5124: 
                   5125:  Arguments:
                   5126:    $file2grade - filename to set as selected in the dropdown
                   5127: 
                   5128: =cut
1.422     foxr     5129: 
1.202     albertel 5130: sub scantron_uploads {
1.209     ng       5131:     my ($file2grade) = @_;
1.202     albertel 5132:     my $result=	'<select name="scantron_selectfile">';
                   5133:     $result.="<option></option>";
                   5134:     foreach my $filename (sort(&scantron_filenames())) {
1.401     albertel 5135: 	$result.="<option".($filename eq $file2grade ? ' selected="selected"':'').">$filename</option>\n";
1.81      albertel 5136:     }
                   5137:     $result.="</select>";
                   5138:     return $result;
                   5139: }
                   5140: 
1.423     albertel 5141: =pod 
                   5142: 
                   5143: =item scantron_scantab
                   5144: 
                   5145:   Returns html drop down of the scantron formats in the scantronformat.tab
                   5146:   file.
                   5147: 
                   5148: =cut
1.422     foxr     5149: 
1.82      albertel 5150: sub scantron_scantab {
                   5151:     my $result='<select name="scantron_format">'."\n";
1.191     albertel 5152:     $result.='<option></option>'."\n";
1.518     raeburn  5153:     my @lines = &get_scantronformat_file();
                   5154:     if (@lines > 0) {
                   5155:         foreach my $line (@lines) {
                   5156:             next if (($line =~ /^\#/) || ($line eq ''));
                   5157: 	    my ($name,$descrip)=split(/:/,$line);
                   5158: 	    $result.='<option value="'.$name.'">'.$descrip.'</option>'."\n";
                   5159:         }
1.82      albertel 5160:     }
                   5161:     $result.='</select>'."\n";
1.518     raeburn  5162:     return $result;
                   5163: }
                   5164: 
                   5165: =pod
                   5166: 
                   5167: =item get_scantronformat_file
                   5168: 
                   5169:   Returns an array containing lines from the scantron format file for
                   5170:   the domain of the course.
                   5171: 
                   5172:   If a url for a custom.tab file is listed in domain's configuration.db, 
                   5173:   lines are from this file.
                   5174: 
                   5175:   Otherwise, if a default.tab has been published in RES space by the 
                   5176:   domainconfig user, lines are from this file.
                   5177: 
                   5178:   Otherwise, fall back to getting lines from the legacy file on the
1.519     raeburn  5179:   local server:  /home/httpd/lonTabs/default_scantronformat.tab    
1.82      albertel 5180: 
1.518     raeburn  5181: =cut
                   5182: 
                   5183: sub get_scantronformat_file {
                   5184:     my $cdom= $env{'course.'.$env{'request.course.id'}.'.domain'};
                   5185:     my %domconfig = &Apache::lonnet::get_dom('configuration',['scantron'],$cdom);
                   5186:     my $gottab = 0;
                   5187:     my @lines;
                   5188:     if (ref($domconfig{'scantron'}) eq 'HASH') {
                   5189:         if ($domconfig{'scantron'}{'scantronformat'} ne '') {
                   5190:             my $formatfile = &Apache::lonnet::getfile($Apache::lonnet::perlvar{'lonDocRoot'}.$domconfig{'scantron'}{'scantronformat'});
                   5191:             if ($formatfile ne '-1') {
                   5192:                 @lines = split("\n",$formatfile,-1);
                   5193:                 $gottab = 1;
                   5194:             }
                   5195:         }
                   5196:     }
                   5197:     if (!$gottab) {
                   5198:         my $confname = $cdom.'-domainconfig';
                   5199:         my $default = $Apache::lonnet::perlvar{'lonDocRoot'}.'/res/'.$cdom.'/'.$confname.'/default.tab';
                   5200:         my $formatfile =  &Apache::lonnet::getfile($default);
                   5201:         if ($formatfile ne '-1') {
                   5202:             @lines = split("\n",$formatfile,-1);
                   5203:             $gottab = 1;
                   5204:         }
                   5205:     }
                   5206:     if (!$gottab) {
1.519     raeburn  5207:         my @domains = &Apache::lonnet::current_machine_domains();
                   5208:         if (grep(/^\Q$cdom\E$/,@domains)) {
                   5209:             my $fh=Apache::File->new($Apache::lonnet::perlvar{'lonTabDir'}.'/scantronformat.tab');
                   5210:             @lines = <$fh>;
                   5211:             close($fh);
                   5212:         } else {
                   5213:             my $fh=Apache::File->new($Apache::lonnet::perlvar{'lonTabDir'}.'/default_scantronformat.tab');
                   5214:             @lines = <$fh>;
                   5215:             close($fh);
                   5216:         }
1.518     raeburn  5217:     }
                   5218:     return @lines;
1.82      albertel 5219: }
                   5220: 
1.423     albertel 5221: =pod 
                   5222: 
                   5223: =item scantron_CODElist
                   5224: 
                   5225:   Returns html drop down of the saved CODE lists from current course,
                   5226:   generated from earlier printings.
                   5227: 
                   5228: =cut
1.422     foxr     5229: 
1.186     albertel 5230: sub scantron_CODElist {
1.257     albertel 5231:     my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   5232:     my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
1.186     albertel 5233:     my @names=&Apache::lonnet::getkeys('CODEs',$cdom,$cnum);
                   5234:     my $namechoice='<option></option>';
1.225     albertel 5235:     foreach my $name (sort {uc($a) cmp uc($b)} @names) {
1.191     albertel 5236: 	if ($name =~ /^error: 2 /) { next; }
1.278     albertel 5237: 	if ($name =~ /^type\0/) { next; }
1.186     albertel 5238: 	$namechoice.='<option value="'.$name.'">'.$name.'</option>';
                   5239:     }
                   5240:     $namechoice='<select name="scantron_CODElist">'.$namechoice.'</select>';
                   5241:     return $namechoice;
                   5242: }
                   5243: 
1.423     albertel 5244: =pod 
                   5245: 
                   5246: =item scantron_CODEunique
                   5247: 
                   5248:   Returns the html for "Each CODE to be used once" radio.
                   5249: 
                   5250: =cut
1.422     foxr     5251: 
1.186     albertel 5252: sub scantron_CODEunique {
1.532     bisitz   5253:     my $result='<span class="LC_nobreak">
1.272     albertel 5254:                  <label><input type="radio" name="scantron_CODEunique"
1.423     albertel 5255:                         value="yes" checked="checked" />'.&mt('Yes').' </label>
1.381     albertel 5256:                 </span>
1.532     bisitz   5257:                 <span class="LC_nobreak">
1.272     albertel 5258:                  <label><input type="radio" name="scantron_CODEunique"
1.423     albertel 5259:                         value="no" />'.&mt('No').' </label>
1.381     albertel 5260:                 </span>';
1.186     albertel 5261:     return $result;
                   5262: }
1.423     albertel 5263: 
                   5264: =pod 
                   5265: 
                   5266: =item scantron_selectphase
                   5267: 
                   5268:   Generates the initial screen to start the bubble sheet process.
                   5269:   Allows for - starting a grading run.
1.424     albertel 5270:              - downloading existing scan data (original, corrected
1.423     albertel 5271:                                                 or skipped info)
                   5272: 
                   5273:              - uploading new scan data
                   5274: 
                   5275:  Arguments:
                   5276:   $r          - The Apache request object
                   5277:   $file2grade - name of the file that contain the scanned data to score
                   5278: 
                   5279: =cut
1.186     albertel 5280: 
1.75      albertel 5281: sub scantron_selectphase {
1.209     ng       5282:     my ($r,$file2grade) = @_;
1.324     albertel 5283:     my ($symb)=&get_symb($r);
1.75      albertel 5284:     if (!$symb) {return '';}
1.582     raeburn  5285:     my $map_error;
                   5286:     my $sequence_selector=&getSequenceDropDown($symb,\$map_error);
                   5287:     if ($map_error) {
                   5288:         $r->print('<br />'.&navmap_errormsg().'<br />');
                   5289:         return;
                   5290:     }
1.324     albertel 5291:     my $default_form_data=&defaultFormData($symb);
                   5292:     my $grading_menu_button=&show_grading_menu_form($symb);
1.209     ng       5293:     my $file_selector=&scantron_uploads($file2grade);
1.82      albertel 5294:     my $format_selector=&scantron_scantab();
1.186     albertel 5295:     my $CODE_selector=&scantron_CODElist();
                   5296:     my $CODE_unique=&scantron_CODEunique();
1.75      albertel 5297:     my $result;
1.422     foxr     5298: 
1.513     foxr     5299:     $ssi_error = 0;
                   5300: 
1.422     foxr     5301:     # Chunk of form to prompt for a file to grade and how:
                   5302: 
1.489     albertel 5303:     $result.= '
                   5304:     <br />
                   5305:     <form method="post" enctype="multipart/form-data" action="/adm/grades" name="scantron_process">
                   5306:     <input type="hidden" name="command" value="scantron_warning" />
                   5307:     '.$default_form_data.'
                   5308:     '.&Apache::loncommon::start_data_table('LC_scantron_action').'
                   5309:        '.&Apache::loncommon::start_data_table_header_row().'
                   5310:             <th colspan="2">
1.492     albertel 5311:               &nbsp;'.&mt('Specify file and which Folder/Sequence to grade').'
1.489     albertel 5312:             </th>
                   5313:        '.&Apache::loncommon::end_data_table_header_row().'
                   5314:        '.&Apache::loncommon::start_data_table_row().'
1.492     albertel 5315:             <td> '.&mt('Sequence to grade:').' </td><td> '.$sequence_selector.' </td>
1.489     albertel 5316:        '.&Apache::loncommon::end_data_table_row().'
                   5317:        '.&Apache::loncommon::start_data_table_row().'
1.572     www      5318:             <td> '.&mt('Filename of bubblesheet data file:').' </td><td> '.$file_selector.' </td>
1.489     albertel 5319:        '.&Apache::loncommon::end_data_table_row().'
                   5320:        '.&Apache::loncommon::start_data_table_row().'
1.572     www      5321:             <td> '.&mt('Format of bubblesheet data file:').' </td><td> '.$format_selector.' </td>
1.489     albertel 5322:        '.&Apache::loncommon::end_data_table_row().'
                   5323:        '.&Apache::loncommon::start_data_table_row().'
1.492     albertel 5324:             <td> '.&mt('Saved CODEs to validate against:').' </td><td> '.$CODE_selector.' </td>
1.489     albertel 5325:        '.&Apache::loncommon::end_data_table_row().'
                   5326:        '.&Apache::loncommon::start_data_table_row().'
1.492     albertel 5327:             <td> '.&mt('Each CODE is only to be used once:').'</td><td> '.$CODE_unique.' </td>
1.489     albertel 5328:        '.&Apache::loncommon::end_data_table_row().'
                   5329:        '.&Apache::loncommon::start_data_table_row().'
1.492     albertel 5330: 	    <td> '.&mt('Options:').' </td>
1.187     albertel 5331:             <td>
1.492     albertel 5332: 	       <label><input type="checkbox" name="scantron_options_redo" value="redo_skipped"/> '.&mt('Do only previously skipped records').'</label> <br />
                   5333:                <label><input type="checkbox" name="scantron_options_ignore" value="ignore_corrections"/> '.&mt('Remove all existing corrections').'</label> <br />
                   5334:                <label><input type="checkbox" name="scantron_options_hidden" value="ignore_hidden"/> '.&mt('Skip hidden resources when grading').'</label>
1.187     albertel 5335: 	    </td>
1.489     albertel 5336:        '.&Apache::loncommon::end_data_table_row().'
                   5337:        '.&Apache::loncommon::start_data_table_row().'
1.174     albertel 5338:             <td colspan="2">
1.572     www      5339:               <input type="submit" value="'.&mt('Grading: Validate Bubblesheet Records').'" />
1.162     albertel 5340:             </td>
1.489     albertel 5341:        '.&Apache::loncommon::end_data_table_row().'
                   5342:     '.&Apache::loncommon::end_data_table().'
                   5343:     </form>
                   5344: ';
1.162     albertel 5345:    
                   5346:     $r->print($result);
                   5347: 
1.257     albertel 5348:     if (&Apache::lonnet::allowed('usc',$env{'request.role.domain'}) ||
                   5349:         &Apache::lonnet::allowed('usc',$env{'request.course.id'})) {
1.162     albertel 5350: 
1.422     foxr     5351: 	# Chunk of form to prompt for a scantron file upload.
                   5352: 
1.489     albertel 5353:         $r->print('
                   5354:     <br />
                   5355:     '.&Apache::loncommon::start_data_table('LC_scantron_action').'
                   5356:        '.&Apache::loncommon::start_data_table_header_row().'
                   5357:             <th>
1.572     www      5358:               &nbsp;'.&mt('Specify a bubblesheet data file to upload.').'
1.489     albertel 5359:             </th>
                   5360:        '.&Apache::loncommon::end_data_table_header_row().'
                   5361:        '.&Apache::loncommon::start_data_table_row().'
1.162     albertel 5362:             <td>
1.489     albertel 5363: ');
1.324     albertel 5364:     my $default_form_data=&defaultFormData(&get_symb($r,1));
1.257     albertel 5365:     my $cdom= $env{'course.'.$env{'request.course.id'}.'.domain'};
                   5366:     my $cnum= $env{'course.'.$env{'request.course.id'}.'.num'};
1.492     albertel 5367:     $r->print('
1.174     albertel 5368:               <script type="text/javascript" language="javascript">
                   5369:     function checkUpload(formname) {
                   5370: 	if (formname.upfile.value == "") {
1.492     albertel 5371: 	    alert("'.&mt('Please use the browse button to select a file from your local directory.').'");
1.174     albertel 5372: 	    return false;
                   5373: 	}
                   5374: 	formname.submit();
                   5375:     }
                   5376:               </script>
                   5377: 
1.492     albertel 5378:               <form enctype="multipart/form-data" action="/adm/grades" name="rules" method="post">
                   5379:                 '.$default_form_data.'
                   5380:                 <input name="courseid" type="hidden" value="'.$cnum.'" />
                   5381:                 <input name="domainid" type="hidden" value="'.$cdom.'" />
                   5382:                 <input name="command" value="scantronupload_save" type="hidden" />
                   5383:                 '.&mt('File to upload: [_1]','<input type="file" name="upfile" size="50" />').'
1.174     albertel 5384:                 <br />
1.589     bisitz   5385:                 <input type="button" onclick="javascript:checkUpload(this.form);" value="'.&mt('Upload Bubblesheet Data').'" />
1.174     albertel 5386:               </form>
1.492     albertel 5387: ');
1.162     albertel 5388: 
1.489     albertel 5389:         $r->print('
1.162     albertel 5390:             </td>
1.489     albertel 5391:        '.&Apache::loncommon::end_data_table_row().'
                   5392:        '.&Apache::loncommon::end_data_table().'
                   5393: ');
1.162     albertel 5394:     }
1.422     foxr     5395: 
                   5396:     # Chunk of the form that prompts to view a scoring office file,
                   5397:     # corrected file, skipped records in a file.
                   5398: 
1.489     albertel 5399:     $r->print('
                   5400:    <br />
                   5401:    <form action="/adm/grades" name="scantron_download">
                   5402:      '.$default_form_data.'
                   5403:      <input type="hidden" name="command" value="scantron_download" />
                   5404:      '.&Apache::loncommon::start_data_table('LC_scantron_action').'
                   5405:        '.&Apache::loncommon::start_data_table_header_row().'
                   5406:               <th>
1.492     albertel 5407:                 &nbsp;'.&mt('Download a scoring office file').'
1.489     albertel 5408:               </th>
                   5409:        '.&Apache::loncommon::end_data_table_header_row().'
                   5410:        '.&Apache::loncommon::start_data_table_row().'
1.492     albertel 5411:               <td> '.&mt('Filename of scoring office file: [_1]',$file_selector).' 
1.489     albertel 5412:                 <br />
1.492     albertel 5413:                 <input type="submit" value="'.&mt('Download: Show List of Associated Files').'" />
1.489     albertel 5414:        '.&Apache::loncommon::end_data_table_row().'
                   5415:      '.&Apache::loncommon::end_data_table().'
                   5416:    </form>
                   5417:    <br />
                   5418: ');
1.162     albertel 5419: 
1.457     banghart 5420:     &Apache::lonpickcode::code_list($r,2);
1.523     raeburn  5421: 
1.528     raeburn  5422:     $r->print('<br /><form method="post" name="checkscantron">'.
1.523     raeburn  5423:              $default_form_data."\n".
                   5424:              &Apache::loncommon::start_data_table('LC_scantron_action')."\n".
                   5425:              &Apache::loncommon::start_data_table_header_row()."\n".
                   5426:              '<th colspan="2">
1.572     www      5427:               &nbsp;'.&mt('Review bubblesheet data and submissions for a previously graded folder/sequence')."\n".
1.523     raeburn  5428:              '</th>'."\n".
                   5429:               &Apache::loncommon::end_data_table_header_row()."\n".
                   5430:               &Apache::loncommon::start_data_table_row()."\n".
                   5431:               '<td> '.&mt('Graded folder/sequence:').' </td>'."\n".
                   5432:               '<td> '.$sequence_selector.' </td>'.
                   5433:               &Apache::loncommon::end_data_table_row()."\n".
                   5434:               &Apache::loncommon::start_data_table_row()."\n".
                   5435:               '<td> '.&mt('Filename of scoring office file:').' </td>'."\n".
                   5436:               '<td> '.$file_selector.' </td>'."\n".
                   5437:               &Apache::loncommon::end_data_table_row()."\n".
                   5438:               &Apache::loncommon::start_data_table_row()."\n".
                   5439:               '<td> '.&mt('Format of data file:').' </td>'."\n".
                   5440:               '<td> '.$format_selector.' </td>'."\n".
                   5441:               &Apache::loncommon::end_data_table_row()."\n".
                   5442:               &Apache::loncommon::start_data_table_row()."\n".
1.557     raeburn  5443:               '<td> '.&mt('Options').' </td>'."\n".
                   5444:               '<td> <label><input type="checkbox" name="scantron_options_hidden" value="ignore_hidden"/> '.&mt('Skip hidden resources').'</label></td>'.
                   5445:               &Apache::loncommon::end_data_table_row()."\n".
                   5446:               &Apache::loncommon::start_data_table_row()."\n".
1.523     raeburn  5447:               '<td colspan="2">'."\n".
                   5448:               '<input type="hidden" name="command" value="checksubmissions" />'."\n".
1.575     www      5449:               '<input type="submit" value="'.&mt('Review Bubblesheet Data and Submission Records').'" />'."\n".
1.523     raeburn  5450:               '</td>'."\n".
                   5451:               &Apache::loncommon::end_data_table_row()."\n".
                   5452:               &Apache::loncommon::end_data_table()."\n".
                   5453:               '</form><br />');
1.457     banghart 5454:     $r->print($grading_menu_button);
1.523     raeburn  5455:     return;
1.75      albertel 5456: }
                   5457: 
1.423     albertel 5458: =pod
                   5459: 
                   5460: =item get_scantron_config
                   5461: 
                   5462:    Parse and return the scantron configuration line selected as a
                   5463:    hash of configuration file fields.
                   5464: 
                   5465:  Arguments:
                   5466:     which - the name of the configuration to parse from the file.
                   5467: 
                   5468: 
                   5469:  Returns:
                   5470:             If the named configuration is not in the file, an empty
                   5471:             hash is returned.
                   5472:     a hash with the fields
                   5473:       name         - internal name for the this configuration setup
                   5474:       description  - text to display to operator that describes this config
                   5475:       CODElocation - if 0 or the string 'none'
                   5476:                           - no CODE exists for this config
                   5477:                      if -1 || the string 'letter'
                   5478:                           - a CODE exists for this config and is
                   5479:                             a string of letters
                   5480:                      Unsupported value (but planned for future support)
                   5481:                           if a positive integer
                   5482:                                - The CODE exists as the first n items from
                   5483:                                  the question section of the form
                   5484:                           if the string 'number'
                   5485:                                - The CODE exists for this config and is
                   5486:                                  a string of numbers
                   5487:       CODEstart   - (only matter if a CODE exists) column in the line where
                   5488:                      the CODE starts
                   5489:       CODElength  - length of the CODE
1.573     bisitz   5490:       IDstart     - column where the student/employee ID starts
1.556     weissno  5491:       IDlength    - length of the student/employee ID info
1.423     albertel 5492:       Qstart      - column where the information from the bubbled
                   5493:                     'questions' start
                   5494:       Qlength     - number of columns comprising a single bubble line from
                   5495:                     the sheet. (usually either 1 or 10)
1.424     albertel 5496:       Qon         - either a single character representing the character used
1.423     albertel 5497:                     to signal a bubble was chosen in the positional setup, or
                   5498:                     the string 'letter' if the letter of the chosen bubble is
                   5499:                     in the final, or 'number' if a number representing the
                   5500:                     chosen bubble is in the file (1->A 0->J)
1.424     albertel 5501:       Qoff        - the character used to represent that a bubble was
                   5502:                     left blank
1.423     albertel 5503:       PaperID     - if the scanning process generates a unique number for each
                   5504:                     sheet scanned the column that this ID number starts in
                   5505:       PaperIDlength - number of columns that comprise the unique ID number
                   5506:                       for the sheet of paper
1.424     albertel 5507:       FirstName   - column that the first name starts in
1.423     albertel 5508:       FirstNameLength - number of columns that the first name spans
                   5509:  
                   5510:       LastName    - column that the last name starts in
                   5511:       LastNameLength - number of columns that the last name spans
                   5512: 
                   5513: =cut
1.422     foxr     5514: 
1.82      albertel 5515: sub get_scantron_config {
                   5516:     my ($which) = @_;
1.518     raeburn  5517:     my @lines = &get_scantronformat_file();
1.82      albertel 5518:     my %config;
1.157     albertel 5519:     #FIXME probably should move to XML it has already gotten a bit much now
1.518     raeburn  5520:     foreach my $line (@lines) {
1.82      albertel 5521: 	my ($name,$descrip)=split(/:/,$line);
                   5522: 	if ($name ne $which ) { next; }
                   5523: 	chomp($line);
                   5524: 	my @config=split(/:/,$line);
                   5525: 	$config{'name'}=$config[0];
                   5526: 	$config{'description'}=$config[1];
                   5527: 	$config{'CODElocation'}=$config[2];
                   5528: 	$config{'CODEstart'}=$config[3];
                   5529: 	$config{'CODElength'}=$config[4];
                   5530: 	$config{'IDstart'}=$config[5];
                   5531: 	$config{'IDlength'}=$config[6];
                   5532: 	$config{'Qstart'}=$config[7];
1.497     foxr     5533:  	$config{'Qlength'}=$config[8];
1.82      albertel 5534: 	$config{'Qoff'}=$config[9];
                   5535: 	$config{'Qon'}=$config[10];
1.157     albertel 5536: 	$config{'PaperID'}=$config[11];
                   5537: 	$config{'PaperIDlength'}=$config[12];
                   5538: 	$config{'FirstName'}=$config[13];
                   5539: 	$config{'FirstNamelength'}=$config[14];
                   5540: 	$config{'LastName'}=$config[15];
                   5541: 	$config{'LastNamelength'}=$config[16];
1.82      albertel 5542: 	last;
                   5543:     }
                   5544:     return %config;
                   5545: }
                   5546: 
1.423     albertel 5547: =pod 
                   5548: 
                   5549: =item username_to_idmap
                   5550: 
1.556     weissno  5551:     creates a hash keyed by student/employee ID with values of the corresponding
1.423     albertel 5552:     student username:domain.
                   5553: 
                   5554:   Arguments:
                   5555: 
                   5556:     $classlist - reference to the class list hash. This is a hash
                   5557:                  keyed by student name:domain  whose elements are references
1.424     albertel 5558:                  to arrays containing various chunks of information
1.423     albertel 5559:                  about the student. (See loncoursedata for more info).
                   5560: 
                   5561:   Returns
                   5562:     %idmap - the constructed hash
                   5563: 
                   5564: =cut
                   5565: 
1.82      albertel 5566: sub username_to_idmap {
                   5567:     my ($classlist)= @_;
                   5568:     my %idmap;
                   5569:     foreach my $student (keys(%$classlist)) {
                   5570: 	$idmap{$classlist->{$student}->[&Apache::loncoursedata::CL_ID]}=
                   5571: 	    $student;
                   5572:     }
                   5573:     return %idmap;
                   5574: }
1.423     albertel 5575: 
                   5576: =pod
                   5577: 
1.424     albertel 5578: =item scantron_fixup_scanline
1.423     albertel 5579: 
                   5580:    Process a requested correction to a scanline.
                   5581: 
                   5582:   Arguments:
                   5583:     $scantron_config   - hash from &get_scantron_config()
                   5584:     $scan_data         - hash of correction information 
                   5585:                           (see &scantron_getfile())
                   5586:     $line              - existing scanline
                   5587:     $whichline         - line number of the passed in scanline
                   5588:     $field             - type of change to process 
                   5589:                          (either 
1.573     bisitz   5590:                           'ID'     -> correct the student/employee ID
1.423     albertel 5591:                           'CODE'   -> correct the CODE
                   5592:                           'answer' -> fixup the submitted answers)
                   5593:     
                   5594:    $args               - hash of additional info,
                   5595:                           - 'ID' 
                   5596:                                'newid' -> studentID to use in replacement
1.424     albertel 5597:                                           of existing one
1.423     albertel 5598:                           - 'CODE' 
                   5599:                                'CODE_ignore_dup' - set to true if duplicates
                   5600:                                                    should be ignored.
                   5601: 	                       'CODE' - is new code or 'use_unfound'
1.424     albertel 5602:                                         if the existing unfound code should
1.423     albertel 5603:                                         be used as is
                   5604:                           - 'answer'
                   5605:                                'response' - new answer or 'none' if blank
                   5606:                                'question' - the bubble line to change
1.503     raeburn  5607:                                'questionnum' - the question identifier,
                   5608:                                                may include subquestion. 
1.423     albertel 5609: 
                   5610:   Returns:
                   5611:     $line - the modified scanline
                   5612: 
                   5613:   Side effects: 
                   5614:     $scan_data - may be updated
                   5615: 
                   5616: =cut
                   5617: 
1.82      albertel 5618: 
1.157     albertel 5619: sub scantron_fixup_scanline {
                   5620:     my ($scantron_config,$scan_data,$line,$whichline,$field,$args)=@_;
                   5621:     if ($field eq 'ID') {
                   5622: 	if (length($args->{'newid'}) > $$scantron_config{'IDlength'}) {
1.186     albertel 5623: 	    return ($line,1,'New value too large');
1.157     albertel 5624: 	}
                   5625: 	if (length($args->{'newid'}) < $$scantron_config{'IDlength'}) {
                   5626: 	    $args->{'newid'}=sprintf('%-'.$$scantron_config{'IDlength'}.'s',
                   5627: 				     $args->{'newid'});
                   5628: 	}
                   5629: 	substr($line,$$scantron_config{'IDstart'}-1,
                   5630: 	       $$scantron_config{'IDlength'})=$args->{'newid'};
                   5631: 	if ($args->{'newid'}=~/^\s*$/) {
                   5632: 	    &scan_data($scan_data,"$whichline.user",
                   5633: 		       $args->{'username'}.':'.$args->{'domain'});
                   5634: 	}
1.186     albertel 5635:     } elsif ($field eq 'CODE') {
1.192     albertel 5636: 	if ($args->{'CODE_ignore_dup'}) {
                   5637: 	    &scan_data($scan_data,"$whichline.CODE_ignore_dup",'1');
                   5638: 	}
                   5639: 	&scan_data($scan_data,"$whichline.useCODE",'1');
                   5640: 	if ($args->{'CODE'} ne 'use_unfound') {
1.191     albertel 5641: 	    if (length($args->{'CODE'}) > $$scantron_config{'CODElength'}) {
                   5642: 		return ($line,1,'New CODE value too large');
                   5643: 	    }
                   5644: 	    if (length($args->{'CODE'}) < $$scantron_config{'CODElength'}) {
                   5645: 		$args->{'CODE'}=sprintf('%-'.$$scantron_config{'CODElength'}.'s',$args->{'CODE'});
                   5646: 	    }
                   5647: 	    substr($line,$$scantron_config{'CODEstart'}-1,
                   5648: 		   $$scantron_config{'CODElength'})=$args->{'CODE'};
1.186     albertel 5649: 	}
1.157     albertel 5650:     } elsif ($field eq 'answer') {
1.497     foxr     5651: 	my $length=$scantron_config->{'Qlength'};
1.157     albertel 5652: 	my $off=$scantron_config->{'Qoff'};
                   5653: 	my $on=$scantron_config->{'Qon'};
1.497     foxr     5654: 	my $answer=${off}x$length;
                   5655: 	if ($args->{'response'} eq 'none') {
                   5656: 	    &scan_data($scan_data,
1.503     raeburn  5657: 		       "$whichline.no_bubble.".$args->{'questionnum'},'1');
1.497     foxr     5658: 	} else {
                   5659: 	    if ($on eq 'letter') {
                   5660: 		my @alphabet=('A'..'Z');
                   5661: 		$answer=$alphabet[$args->{'response'}];
                   5662: 	    } elsif ($on eq 'number') {
                   5663: 		$answer=$args->{'response'}+1;
                   5664: 		if ($answer == 10) { $answer = '0'; }
1.274     albertel 5665: 	    } else {
1.497     foxr     5666: 		substr($answer,$args->{'response'},1)=$on;
1.274     albertel 5667: 	    }
1.497     foxr     5668: 	    &scan_data($scan_data,
1.503     raeburn  5669: 		       "$whichline.no_bubble.".$args->{'questionnum'},undef,'1');
1.157     albertel 5670: 	}
1.497     foxr     5671: 	my $where=$length*($args->{'question'}-1)+$scantron_config->{'Qstart'};
                   5672: 	substr($line,$where-1,$length)=$answer;
1.157     albertel 5673:     }
                   5674:     return $line;
                   5675: }
1.423     albertel 5676: 
                   5677: =pod
                   5678: 
                   5679: =item scan_data
                   5680: 
                   5681:     Edit or look up  an item in the scan_data hash.
                   5682: 
                   5683:   Arguments:
                   5684:     $scan_data  - The hash (see scantron_getfile)
                   5685:     $key        - shorthand of the key to edit (actual key is
1.424     albertel 5686:                   scantronfilename_key).
1.423     albertel 5687:     $data        - New value of the hash entry.
                   5688:     $delete      - If true, the entry is removed from the hash.
                   5689: 
                   5690:   Returns:
                   5691:     The new value of the hash table field (undefined if deleted).
                   5692: 
                   5693: =cut
                   5694: 
                   5695: 
1.157     albertel 5696: sub scan_data {
                   5697:     my ($scan_data,$key,$value,$delete)=@_;
1.257     albertel 5698:     my $filename=$env{'form.scantron_selectfile'};
1.157     albertel 5699:     if (defined($value)) {
                   5700: 	$scan_data->{$filename.'_'.$key} = $value;
                   5701:     }
                   5702:     if ($delete) { delete($scan_data->{$filename.'_'.$key}); }
                   5703:     return $scan_data->{$filename.'_'.$key};
                   5704: }
1.423     albertel 5705: 
1.495     albertel 5706: # ----- These first few routines are general use routines.----
                   5707: 
                   5708: # Return the number of occurences of a pattern in a string.
                   5709: 
                   5710: sub occurence_count {
                   5711:     my ($string, $pattern) = @_;
                   5712: 
                   5713:     my @matches = ($string =~ /$pattern/g);
                   5714: 
                   5715:     return scalar(@matches);
                   5716: }
                   5717: 
                   5718: 
                   5719: # Take a string known to have digits and convert all the
                   5720: # digits into letters in the range J,A..I.
                   5721: 
                   5722: sub digits_to_letters {
                   5723:     my ($input) = @_;
                   5724: 
                   5725:     my @alphabet = ('J', 'A'..'I');
                   5726: 
                   5727:     my @input    = split(//, $input);
                   5728:     my $output ='';
                   5729:     for (my $i = 0; $i < scalar(@input); $i++) {
                   5730: 	if ($input[$i] =~ /\d/) {
                   5731: 	    $output .= $alphabet[$input[$i]];
                   5732: 	} else {
                   5733: 	    $output .= $input[$i];
                   5734: 	}
                   5735:     }
                   5736:     return $output;
                   5737: }
                   5738: 
1.423     albertel 5739: =pod 
                   5740: 
                   5741: =item scantron_parse_scanline
                   5742: 
                   5743:   Decodes a scanline from the selected scantron file
                   5744: 
                   5745:  Arguments:
                   5746:     line             - The text of the scantron file line to process
                   5747:     whichline        - Line number
                   5748:     scantron_config  - Hash describing the format of the scantron lines.
                   5749:     scan_data        - Hash of extra information about the scanline
                   5750:                        (see scantron_getfile for more information)
                   5751:     just_header      - True if should not process question answers but only
                   5752:                        the stuff to the left of the answers.
                   5753:  Returns:
                   5754:    Hash containing the result of parsing the scanline
                   5755: 
                   5756:    Keys are all proceeded by the string 'scantron.'
                   5757: 
                   5758:        CODE    - the CODE in use for this scanline
                   5759:        useCODE - 1 if the CODE is invalid but it usage has been forced
                   5760:                  by the operator
                   5761:        CODE_ignore_dup - 1 if the CODE is a duplicated use when unique
                   5762:                             CODEs were selected, but the usage has been
                   5763:                             forced by the operator
1.556     weissno  5764:        ID  - student/employee ID
1.423     albertel 5765:        PaperID - if used, the ID number printed on the sheet when the 
                   5766:                  paper was scanned
                   5767:        FirstName - first name from the sheet
                   5768:        LastName  - last name from the sheet
                   5769: 
                   5770:      if just_header was not true these key may also exist
                   5771: 
1.447     foxr     5772:        missingerror - a list of bubble ranges that are considered to be answers
                   5773:                       to a single question that don't have any bubbles filled in.
                   5774:                       Of the form questionnumber:firstbubblenumber:count.
                   5775:        doubleerror  - a list of bubble ranges that are considered to be answers
                   5776:                       to a single question that have more than one bubble filled in.
                   5777:                       Of the form questionnumber::firstbubblenumber:count
                   5778:    
                   5779:                 In the above, count is the number of bubble responses in the
                   5780:                 input line needed to represent the possible answers to the question.
                   5781:                 e.g. a radioresponse with 15 choices in an answer sheet with 10 choices
                   5782:                 per line would have count = 2.
                   5783: 
1.423     albertel 5784:        maxquest     - the number of the last bubble line that was parsed
                   5785: 
                   5786:        (<number> starts at 1)
                   5787:        <number>.answer - zero or more letters representing the selected
                   5788:                          letters from the scanline for the bubble line 
                   5789:                          <number>.
                   5790:                          if blank there was either no bubble or there where
                   5791:                          multiple bubbles, (consult the keys missingerror and
                   5792:                          doubleerror if this is an error condition)
                   5793: 
                   5794: =cut
                   5795: 
1.82      albertel 5796: sub scantron_parse_scanline {
1.423     albertel 5797:     my ($line,$whichline,$scantron_config,$scan_data,$just_header)=@_;
1.470     foxr     5798: 
1.82      albertel 5799:     my %record;
1.550     raeburn  5800:     my $lastpos = $env{'form.scantron_maxbubble'}*$$scantron_config{'Qlength'};
                   5801:     my $questions=substr($line,$$scantron_config{'Qstart'}-1,$lastpos);  # Answers
1.422     foxr     5802:     my $data=substr($line,0,$$scantron_config{'Qstart'}-1);     # earlier stuff
1.278     albertel 5803:     if (!($$scantron_config{'CODElocation'} eq 0 ||
                   5804: 	  $$scantron_config{'CODElocation'} eq 'none')) {
                   5805: 	if ($$scantron_config{'CODElocation'} < 0 ||
                   5806: 	    $$scantron_config{'CODElocation'} eq 'letter' ||
                   5807: 	    $$scantron_config{'CODElocation'} eq 'number') {
1.191     albertel 5808: 	    $record{'scantron.CODE'}=substr($data,
                   5809: 					    $$scantron_config{'CODEstart'}-1,
1.83      albertel 5810: 					    $$scantron_config{'CODElength'});
1.191     albertel 5811: 	    if (&scan_data($scan_data,"$whichline.useCODE")) {
                   5812: 		$record{'scantron.useCODE'}=1;
                   5813: 	    }
1.192     albertel 5814: 	    if (&scan_data($scan_data,"$whichline.CODE_ignore_dup")) {
                   5815: 		$record{'scantron.CODE_ignore_dup'}=1;
                   5816: 	    }
1.82      albertel 5817: 	} else {
                   5818: 	    #FIXME interpret first N questions
                   5819: 	}
                   5820:     }
1.83      albertel 5821:     $record{'scantron.ID'}=substr($data,$$scantron_config{'IDstart'}-1,
                   5822: 				  $$scantron_config{'IDlength'});
1.157     albertel 5823:     $record{'scantron.PaperID'}=
                   5824: 	substr($data,$$scantron_config{'PaperID'}-1,
                   5825: 	       $$scantron_config{'PaperIDlength'});
                   5826:     $record{'scantron.FirstName'}=
                   5827: 	substr($data,$$scantron_config{'FirstName'}-1,
                   5828: 	       $$scantron_config{'FirstNamelength'});
                   5829:     $record{'scantron.LastName'}=
                   5830: 	substr($data,$$scantron_config{'LastName'}-1,
                   5831: 	       $$scantron_config{'LastNamelength'});
1.423     albertel 5832:     if ($just_header) { return \%record; }
1.194     albertel 5833: 
1.82      albertel 5834:     my @alphabet=('A'..'Z');
                   5835:     my $questnum=0;
1.447     foxr     5836:     my $ansnum  =1;		# Multiple 'answer lines'/question.
                   5837: 
1.470     foxr     5838:     chomp($questions);		# Get rid of any trailing \n.
                   5839:     $questions =~ s/\r$//;      # Get rid of trailing \r too (MAC or Win uploads).
                   5840:     while (length($questions)) {
1.447     foxr     5841: 	my $answers_needed = $bubble_lines_per_response{$questnum};
1.503     raeburn  5842:         my $answer_length  = ($$scantron_config{'Qlength'} * $answers_needed)
                   5843:                              || 1;
                   5844:         $questnum++;
                   5845:         my $quest_id = $questnum;
                   5846:         my $currentquest = substr($questions,0,$answer_length);
                   5847:         $questions       = substr($questions,$answer_length);
                   5848:         if (length($currentquest) < $answer_length) { next; }
                   5849: 
                   5850:         if ($subdivided_bubble_lines{$questnum-1} =~ /,/) {
                   5851:             my $subquestnum = 1;
                   5852:             my $subquestions = $currentquest;
                   5853:             my @subanswers_needed = 
                   5854:                 split(/,/,$subdivided_bubble_lines{$questnum-1});  
                   5855:             foreach my $subans (@subanswers_needed) {
                   5856:                 my $subans_length =
                   5857:                     ($$scantron_config{'Qlength'} * $subans)  || 1;
                   5858:                 my $currsubquest = substr($subquestions,0,$subans_length);
                   5859:                 $subquestions   = substr($subquestions,$subans_length);
                   5860:                 $quest_id = "$questnum.$subquestnum";
                   5861:                 if (($$scantron_config{'Qon'} eq 'letter') ||
                   5862:                     ($$scantron_config{'Qon'} eq 'number')) {
                   5863:                     $ansnum = &scantron_validator_lettnum($ansnum, 
                   5864:                         $questnum,$quest_id,$subans,$currsubquest,$whichline,
                   5865:                         \@alphabet,\%record,$scantron_config,$scan_data);
                   5866:                 } else {
                   5867:                     $ansnum = &scantron_validator_positional($ansnum,
                   5868:                         $questnum,$quest_id,$subans,$currsubquest,$whichline,                        \@alphabet,\%record,$scantron_config,$scan_data);
                   5869:                 }
                   5870:                 $subquestnum ++;
                   5871:             }
                   5872:         } else {
                   5873:             if (($$scantron_config{'Qon'} eq 'letter') ||
                   5874:                 ($$scantron_config{'Qon'} eq 'number')) {
                   5875:                 $ansnum = &scantron_validator_lettnum($ansnum,$questnum,
                   5876:                     $quest_id,$answers_needed,$currentquest,$whichline,
                   5877:                     \@alphabet,\%record,$scantron_config,$scan_data);
                   5878:             } else {
                   5879:                 $ansnum = &scantron_validator_positional($ansnum,$questnum,
                   5880:                     $quest_id,$answers_needed,$currentquest,$whichline,
                   5881:                     \@alphabet,\%record,$scantron_config,$scan_data);
                   5882:             }
                   5883:         }
                   5884:     }
                   5885:     $record{'scantron.maxquest'}=$questnum;
                   5886:     return \%record;
                   5887: }
1.447     foxr     5888: 
1.503     raeburn  5889: sub scantron_validator_lettnum {
                   5890:     my ($ansnum,$questnum,$quest_id,$answers_needed,$currquest,$whichline,
                   5891:         $alphabet,$record,$scantron_config,$scan_data) = @_;
                   5892: 
                   5893:     # Qon 'letter' implies for each slot in currquest we have:
                   5894:     #    ? or * for doubles, a letter in A-Z for a bubble, and
                   5895:     #    about anything else (esp. a value of Qoff) for missing
                   5896:     #    bubbles.
                   5897:     #
                   5898:     # Qon 'number' implies each slot gives a digit that indexes the
                   5899:     #    bubbles filled, or Qoff, or a non-number for unbubbled lines,
                   5900:     #    and * or ? for double bubbles on a single line.
                   5901:     #
1.447     foxr     5902: 
1.503     raeburn  5903:     my $matchon;
                   5904:     if ($$scantron_config{'Qon'} eq 'letter') {
                   5905:         $matchon = '[A-Z]';
                   5906:     } elsif ($$scantron_config{'Qon'} eq 'number') {
                   5907:         $matchon = '\d';
                   5908:     }
                   5909:     my $occurrences = 0;
                   5910:     if (($responsetype_per_response{$questnum-1} eq 'essayresponse') ||
                   5911:         ($responsetype_per_response{$questnum-1} eq 'formularesponse') ||
1.510     raeburn  5912:         ($responsetype_per_response{$questnum-1} eq 'stringresponse') ||
                   5913:         ($responsetype_per_response{$questnum-1} eq 'imageresponse') ||
                   5914:         ($responsetype_per_response{$questnum-1} eq 'reactionresponse') ||
                   5915:         ($responsetype_per_response{$questnum-1} eq 'organicresponse')) {
1.503     raeburn  5916:         my @singlelines = split('',$currquest);
                   5917:         foreach my $entry (@singlelines) {
                   5918:             $occurrences = &occurence_count($entry,$matchon);
                   5919:             if ($occurrences > 1) {
                   5920:                 last;
                   5921:             }
                   5922:         } 
                   5923:     } else {
                   5924:         $occurrences = &occurence_count($currquest,$matchon); 
                   5925:     }
                   5926:     if (($currquest =~ /\?/ || $currquest =~ /\*/) || ($occurrences > 1)) {
                   5927:         push(@{$record->{'scantron.doubleerror'}},$quest_id);
                   5928:         for (my $ans=0; $ans<$answers_needed; $ans++) {
                   5929:             my $bubble = substr($currquest,$ans,1);
                   5930:             if ($bubble =~ /$matchon/ ) {
                   5931:                 if ($$scantron_config{'Qon'} eq 'number') {
                   5932:                     if ($bubble == 0) {
                   5933:                         $bubble = 10; 
                   5934:                     }
                   5935:                     $record->{"scantron.$ansnum.answer"} = 
                   5936:                         $alphabet->[$bubble-1];
                   5937:                 } else {
                   5938:                     $record->{"scantron.$ansnum.answer"} = $bubble;
                   5939:                 }
                   5940:             } else {
                   5941:                 $record->{"scantron.$ansnum.answer"}='';
                   5942:             }
                   5943:             $ansnum++;
                   5944:         }
                   5945:     } elsif (!defined($currquest)
                   5946:             || (&occurence_count($currquest, $$scantron_config{'Qoff'}) == length($currquest))
                   5947:             || (&occurence_count($currquest,$matchon) == 0)) {
                   5948:         for (my $ans=0; $ans<$answers_needed; $ans++ ) {
                   5949:             $record->{"scantron.$ansnum.answer"}='';
                   5950:             $ansnum++;
                   5951:         }
                   5952:         if (!&scan_data($scan_data,"$whichline.no_bubble.$quest_id")) {
                   5953:             push(@{$record->{'scantron.missingerror'}},$quest_id);
                   5954:         }
                   5955:     } else {
                   5956:         if ($$scantron_config{'Qon'} eq 'number') {
                   5957:             $currquest = &digits_to_letters($currquest);            
                   5958:         }
                   5959:         for (my $ans=0; $ans<$answers_needed; $ans++) {
                   5960:             my $bubble = substr($currquest,$ans,1);
                   5961:             $record->{"scantron.$ansnum.answer"} = $bubble;
                   5962:             $ansnum++;
                   5963:         }
                   5964:     }
                   5965:     return $ansnum;
                   5966: }
1.447     foxr     5967: 
1.503     raeburn  5968: sub scantron_validator_positional {
                   5969:     my ($ansnum,$questnum,$quest_id,$answers_needed,$currquest,
                   5970:         $whichline,$alphabet,$record,$scantron_config,$scan_data) = @_;
1.447     foxr     5971: 
1.503     raeburn  5972:     # Otherwise there's a positional notation;
                   5973:     # each bubble line requires Qlength items, and there are filled in
                   5974:     # bubbles for each case where there 'Qon' characters.
                   5975:     #
1.447     foxr     5976: 
1.503     raeburn  5977:     my @array=split($$scantron_config{'Qon'},$currquest,-1);
1.447     foxr     5978: 
1.503     raeburn  5979:     # If the split only gives us one element.. the full length of the
                   5980:     # answer string, no bubbles are filled in:
1.447     foxr     5981: 
1.507     raeburn  5982:     if ($answers_needed eq '') {
                   5983:         return;
                   5984:     }
                   5985: 
1.503     raeburn  5986:     if (length($array[0]) eq $$scantron_config{'Qlength'}*$answers_needed) {
                   5987:         for (my $ans=0; $ans<$answers_needed; $ans++ ) {
                   5988:             $record->{"scantron.$ansnum.answer"}='';
                   5989:             $ansnum++;
                   5990:         }
                   5991:         if (!&scan_data($scan_data,"$whichline.no_bubble.$quest_id")) {
                   5992:             push(@{$record->{"scantron.missingerror"}},$quest_id);
                   5993:         }
                   5994:     } elsif (scalar(@array) == 2) {
                   5995:         my $location = length($array[0]);
                   5996:         my $line_num = int($location / $$scantron_config{'Qlength'});
                   5997:         my $bubble   = $alphabet->[$location % $$scantron_config{'Qlength'}];
                   5998:         for (my $ans=0; $ans<$answers_needed; $ans++) {
                   5999:             if ($ans eq $line_num) {
                   6000:                 $record->{"scantron.$ansnum.answer"} = $bubble;
                   6001:             } else {
                   6002:                 $record->{"scantron.$ansnum.answer"} = ' ';
                   6003:             }
                   6004:             $ansnum++;
                   6005:          }
                   6006:     } else {
                   6007:         #  If there's more than one instance of a bubble character
                   6008:         #  That's a double bubble; with positional notation we can
                   6009:         #  record all the bubbles filled in as well as the
                   6010:         #  fact this response consists of multiple bubbles.
                   6011:         #
                   6012:         if (($responsetype_per_response{$questnum-1} eq 'essayresponse') ||
                   6013:             ($responsetype_per_response{$questnum-1} eq 'formularesponse') ||
1.510     raeburn  6014:             ($responsetype_per_response{$questnum-1} eq 'stringresponse') ||
                   6015:             ($responsetype_per_response{$questnum-1} eq 'imageresponse') ||
                   6016:             ($responsetype_per_response{$questnum-1} eq 'reactionresponse') ||
                   6017:             ($responsetype_per_response{$questnum-1} eq 'organicresponse')) {
1.503     raeburn  6018:             my $doubleerror = 0;
                   6019:             while (($currquest >= $$scantron_config{'Qlength'}) && 
                   6020:                    (!$doubleerror)) {
                   6021:                my $currline = substr($currquest,0,$$scantron_config{'Qlength'});
                   6022:                $currquest = substr($currquest,$$scantron_config{'Qlength'});
                   6023:                my @currarray = split($$scantron_config{'Qon'},$currline,-1);
                   6024:                if (length(@currarray) > 2) {
                   6025:                    $doubleerror = 1;
                   6026:                } 
                   6027:             }
                   6028:             if ($doubleerror) {
                   6029:                 push(@{$record->{'scantron.doubleerror'}},$quest_id);
                   6030:             }
                   6031:         } else {
                   6032:             push(@{$record->{'scantron.doubleerror'}},$quest_id);
                   6033:         }
                   6034:         my $item = $ansnum;
                   6035:         for (my $ans=0; $ans<$answers_needed; $ans++) {
                   6036:             $record->{"scantron.$item.answer"} = '';
                   6037:             $item ++;
                   6038:         }
1.447     foxr     6039: 
1.503     raeburn  6040:         my @ans=@array;
                   6041:         my $i=0;
                   6042:         my $increment = 0;
                   6043:         while ($#ans) {
                   6044:             $i+=length($ans[0]) + $increment;
                   6045:             my $line   = int($i/$$scantron_config{'Qlength'} + $ansnum);
                   6046:             my $bubble = $i%$$scantron_config{'Qlength'};
                   6047:             $record->{"scantron.$line.answer"}.=$alphabet->[$bubble];
                   6048:             shift(@ans);
                   6049:             $increment = 1;
                   6050:         }
                   6051:         $ansnum += $answers_needed;
1.82      albertel 6052:     }
1.503     raeburn  6053:     return $ansnum;
1.82      albertel 6054: }
                   6055: 
1.423     albertel 6056: =pod
                   6057: 
                   6058: =item scantron_add_delay
                   6059: 
                   6060:    Adds an error message that occurred during the grading phase to a
                   6061:    queue of messages to be shown after grading pass is complete
                   6062: 
                   6063:  Arguments:
1.424     albertel 6064:    $delayqueue  - arrary ref of hash ref of error messages
1.423     albertel 6065:    $scanline    - the scanline that caused the error
                   6066:    $errormesage - the error message
                   6067:    $errorcode   - a numeric code for the error
                   6068: 
                   6069:  Side Effects:
1.424     albertel 6070:    updates the $delayqueue to have a new hash ref of the error
1.423     albertel 6071: 
                   6072: =cut
                   6073: 
1.82      albertel 6074: sub scantron_add_delay {
1.140     albertel 6075:     my ($delayqueue,$scanline,$errormessage,$errorcode)=@_;
                   6076:     push(@$delayqueue,
                   6077: 	 {'line' => $scanline, 'emsg' => $errormessage,
                   6078: 	  'ecode' => $errorcode }
                   6079: 	 );
1.82      albertel 6080: }
                   6081: 
1.423     albertel 6082: =pod
                   6083: 
                   6084: =item scantron_find_student
                   6085: 
1.424     albertel 6086:    Finds the username for the current scanline
                   6087: 
                   6088:   Arguments:
                   6089:    $scantron_record - hash result from scantron_parse_scanline
                   6090:    $scan_data       - hash of correction information 
                   6091:                       (see &scantron_getfile() form more information)
                   6092:    $idmap           - hash from &username_to_idmap()
                   6093:    $line            - number of current scanline
                   6094:  
                   6095:   Returns:
                   6096:    Either 'username:domain' or undef if unknown
                   6097: 
1.423     albertel 6098: =cut
                   6099: 
1.82      albertel 6100: sub scantron_find_student {
1.157     albertel 6101:     my ($scantron_record,$scan_data,$idmap,$line)=@_;
1.83      albertel 6102:     my $scanID=$$scantron_record{'scantron.ID'};
1.157     albertel 6103:     if ($scanID =~ /^\s*$/) {
                   6104:  	return &scan_data($scan_data,"$line.user");
                   6105:     }
1.83      albertel 6106:     foreach my $id (keys(%$idmap)) {
1.157     albertel 6107:  	if (lc($id) eq lc($scanID)) {
                   6108:  	    return $$idmap{$id};
                   6109:  	}
1.83      albertel 6110:     }
                   6111:     return undef;
                   6112: }
                   6113: 
1.423     albertel 6114: =pod
                   6115: 
                   6116: =item scantron_filter
                   6117: 
1.424     albertel 6118:    Filter sub for lonnavmaps, filters out hidden resources if ignore
                   6119:    hidden resources was selected
                   6120: 
1.423     albertel 6121: =cut
                   6122: 
1.83      albertel 6123: sub scantron_filter {
                   6124:     my ($curres)=@_;
1.331     albertel 6125: 
                   6126:     if (ref($curres) && $curres->is_problem()) {
                   6127: 	# if the user has asked to not have either hidden
                   6128: 	# or 'randomout' controlled resources to be graded
                   6129: 	# don't include them
                   6130: 	if ($env{'form.scantron_options_hidden'} eq 'ignore_hidden'
                   6131: 	    && $curres->randomout) {
                   6132: 	    return 0;
                   6133: 	}
1.83      albertel 6134: 	return 1;
                   6135:     }
                   6136:     return 0;
1.82      albertel 6137: }
                   6138: 
1.423     albertel 6139: =pod
                   6140: 
                   6141: =item scantron_process_corrections
                   6142: 
1.424     albertel 6143:    Gets correction information out of submitted form data and corrects
                   6144:    the scanline
                   6145: 
1.423     albertel 6146: =cut
                   6147: 
1.157     albertel 6148: sub scantron_process_corrections {
                   6149:     my ($r) = @_;
1.257     albertel 6150:     my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
1.157     albertel 6151:     my ($scanlines,$scan_data)=&scantron_getfile();
                   6152:     my $classlist=&Apache::loncoursedata::get_classlist();
1.257     albertel 6153:     my $which=$env{'form.scantron_line'};
1.200     albertel 6154:     my $line=&scantron_get_line($scanlines,$scan_data,$which);
1.157     albertel 6155:     my ($skip,$err,$errmsg);
1.257     albertel 6156:     if ($env{'form.scantron_skip_record'}) {
1.157     albertel 6157: 	$skip=1;
1.257     albertel 6158:     } elsif ($env{'form.scantron_corrections'} =~ /^(duplicate|incorrect)ID$/) {
                   6159: 	my $newstudent=$env{'form.scantron_username'}.':'.
                   6160: 	    $env{'form.scantron_domain'};
1.157     albertel 6161: 	my $newid=$classlist->{$newstudent}->[&Apache::loncoursedata::CL_ID];
                   6162: 	($line,$err,$errmsg)=
                   6163: 	    &scantron_fixup_scanline(\%scantron_config,$scan_data,$line,$which,
                   6164: 				     'ID',{'newid'=>$newid,
1.257     albertel 6165: 				    'username'=>$env{'form.scantron_username'},
                   6166: 				    'domain'=>$env{'form.scantron_domain'}});
                   6167:     } elsif ($env{'form.scantron_corrections'} =~ /^(duplicate|incorrect)CODE$/) {
                   6168: 	my $resolution=$env{'form.scantron_CODE_resolution'};
1.190     albertel 6169: 	my $newCODE;
1.192     albertel 6170: 	my %args;
1.190     albertel 6171: 	if      ($resolution eq 'use_unfound') {
1.191     albertel 6172: 	    $newCODE='use_unfound';
1.190     albertel 6173: 	} elsif ($resolution eq 'use_found') {
1.257     albertel 6174: 	    $newCODE=$env{'form.scantron_CODE_selectedvalue'};
1.190     albertel 6175: 	} elsif ($resolution eq 'use_typed') {
1.257     albertel 6176: 	    $newCODE=$env{'form.scantron_CODE_newvalue'};
1.194     albertel 6177: 	} elsif ($resolution =~ /^use_closest_(\d+)/) {
1.257     albertel 6178: 	    $newCODE=$env{"form.scantron_CODE_closest_$1"};
1.190     albertel 6179: 	}
1.257     albertel 6180: 	if ($env{'form.scantron_corrections'} eq 'duplicateCODE') {
1.192     albertel 6181: 	    $args{'CODE_ignore_dup'}=1;
                   6182: 	}
                   6183: 	$args{'CODE'}=$newCODE;
1.186     albertel 6184: 	($line,$err,$errmsg)=
                   6185: 	    &scantron_fixup_scanline(\%scantron_config,$scan_data,$line,$which,
1.192     albertel 6186: 				     'CODE',\%args);
1.257     albertel 6187:     } elsif ($env{'form.scantron_corrections'} =~ /^(missing|double)bubble$/) {
                   6188: 	foreach my $question (split(',',$env{'form.scantron_questions'})) {
1.157     albertel 6189: 	    ($line,$err,$errmsg)=
                   6190: 		&scantron_fixup_scanline(\%scantron_config,$scan_data,$line,
                   6191: 					 $which,'answer',
                   6192: 					 { 'question'=>$question,
1.503     raeburn  6193: 		      		   'response'=>$env{"form.scantron_correct_Q_$question"},
                   6194:                                    'questionnum'=>$env{"form.scantron_questionnum_Q_$question"}});
1.157     albertel 6195: 	    if ($err) { last; }
                   6196: 	}
                   6197:     }
                   6198:     if ($err) {
1.398     albertel 6199: 	$r->print("<span class=\"LC_warning\">Unable to accept last correction, an error occurred :$errmsg:</span>");
1.157     albertel 6200:     } else {
1.200     albertel 6201: 	&scantron_put_line($scanlines,$scan_data,$which,$line,$skip);
1.157     albertel 6202: 	&scantron_putfile($scanlines,$scan_data);
                   6203:     }
                   6204: }
                   6205: 
1.423     albertel 6206: =pod
                   6207: 
                   6208: =item reset_skipping_status
                   6209: 
1.424     albertel 6210:    Forgets the current set of remember skipped scanlines (and thus
                   6211:    reverts back to considering all lines in the
                   6212:    scantron_skipped_<filename> file)
                   6213: 
1.423     albertel 6214: =cut
                   6215: 
1.200     albertel 6216: sub reset_skipping_status {
                   6217:     my ($scanlines,$scan_data)=&scantron_getfile();
                   6218:     &scan_data($scan_data,'remember_skipping',undef,1);
                   6219:     &scantron_putfile(undef,$scan_data);
                   6220: }
                   6221: 
1.423     albertel 6222: =pod
                   6223: 
                   6224: =item start_skipping
                   6225: 
1.424     albertel 6226:    Marks a scanline to be skipped. 
                   6227: 
1.423     albertel 6228: =cut
                   6229: 
1.376     albertel 6230: sub start_skipping {
1.200     albertel 6231:     my ($scan_data,$i)=@_;
                   6232:     my %remembered=split(':',&scan_data($scan_data,'remember_skipping'));
1.376     albertel 6233:     if ($env{'form.scantron_options_redo'} =~ /^redo_/) {
                   6234: 	$remembered{$i}=2;
                   6235:     } else {
                   6236: 	$remembered{$i}=1;
                   6237:     }
1.200     albertel 6238:     &scan_data($scan_data,'remember_skipping',join(':',%remembered));
                   6239: }
                   6240: 
1.423     albertel 6241: =pod
                   6242: 
                   6243: =item should_be_skipped
                   6244: 
1.424     albertel 6245:    Checks whether a scanline should be skipped.
                   6246: 
1.423     albertel 6247: =cut
                   6248: 
1.200     albertel 6249: sub should_be_skipped {
1.376     albertel 6250:     my ($scanlines,$scan_data,$i)=@_;
1.257     albertel 6251:     if ($env{'form.scantron_options_redo'} !~ /^redo_/) {
1.200     albertel 6252: 	# not redoing old skips
1.376     albertel 6253: 	if ($scanlines->{'skipped'}[$i]) { return 1; }
1.200     albertel 6254: 	return 0;
                   6255:     }
                   6256:     my %remembered=split(':',&scan_data($scan_data,'remember_skipping'));
1.376     albertel 6257: 
                   6258:     if (exists($remembered{$i}) && $remembered{$i} != 2 ) {
                   6259: 	return 0;
                   6260:     }
1.200     albertel 6261:     return 1;
                   6262: }
                   6263: 
1.423     albertel 6264: =pod
                   6265: 
                   6266: =item remember_current_skipped
                   6267: 
1.424     albertel 6268:    Discovers what scanlines are in the scantron_skipped_<filename>
                   6269:    file and remembers them into scan_data for later use.
                   6270: 
1.423     albertel 6271: =cut
                   6272: 
1.200     albertel 6273: sub remember_current_skipped {
                   6274:     my ($scanlines,$scan_data)=&scantron_getfile();
                   6275:     my %to_remember;
                   6276:     for (my $i=0;$i<=$scanlines->{'count'};$i++) {
                   6277: 	if ($scanlines->{'skipped'}[$i]) {
                   6278: 	    $to_remember{$i}=1;
                   6279: 	}
                   6280:     }
1.376     albertel 6281: 
1.200     albertel 6282:     &scan_data($scan_data,'remember_skipping',join(':',%to_remember));
                   6283:     &scantron_putfile(undef,$scan_data);
                   6284: }
                   6285: 
1.423     albertel 6286: =pod
                   6287: 
                   6288: =item check_for_error
                   6289: 
1.424     albertel 6290:     Checks if there was an error when attempting to remove a specific
                   6291:     scantron_.. bubble sheet data file. Prints out an error if
                   6292:     something went wrong.
                   6293: 
1.423     albertel 6294: =cut
                   6295: 
1.200     albertel 6296: sub check_for_error {
                   6297:     my ($r,$result)=@_;
                   6298:     if ($result ne 'ok' && $result ne 'not_found' ) {
1.492     albertel 6299: 	$r->print(&mt("An error occurred ([_1]) when trying to remove the existing corrections.",$result));
1.200     albertel 6300:     }
                   6301: }
1.157     albertel 6302: 
1.423     albertel 6303: =pod
                   6304: 
                   6305: =item scantron_warning_screen
                   6306: 
1.424     albertel 6307:    Interstitial screen to make sure the operator has selected the
                   6308:    correct options before we start the validation phase.
                   6309: 
1.423     albertel 6310: =cut
                   6311: 
1.203     albertel 6312: sub scantron_warning_screen {
                   6313:     my ($button_text)=@_;
1.257     albertel 6314:     my $title=&Apache::lonnet::gettitle($env{'form.selectpage'});
1.284     albertel 6315:     my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
1.373     albertel 6316:     my $CODElist;
1.284     albertel 6317:     if ($scantron_config{'CODElocation'} &&
                   6318: 	$scantron_config{'CODEstart'} &&
                   6319: 	$scantron_config{'CODElength'}) {
                   6320: 	$CODElist=$env{'form.scantron_CODElist'};
1.398     albertel 6321: 	if ($env{'form.scantron_CODElist'} eq '') { $CODElist='<span class="LC_warning">None</span>'; }
1.284     albertel 6322: 	$CODElist=
1.492     albertel 6323: 	    '<tr><td><b>'.&mt('List of CODES to validate against:').'</b></td><td><tt>'.
1.373     albertel 6324: 	    $env{'form.scantron_CODElist'}.'</tt></td></tr>';
1.284     albertel 6325:     }
1.492     albertel 6326:     return ('
1.203     albertel 6327: <p>
1.492     albertel 6328: <span class="LC_warning">
                   6329: '.&mt('Please double check the information below before clicking on \'[_1]\'',&mt($button_text)).'</span>
1.203     albertel 6330: </p>
                   6331: <table>
1.492     albertel 6332: <tr><td><b>'.&mt('Sequence to be Graded:').'</b></td><td>'.$title.'</td></tr>
                   6333: <tr><td><b>'.&mt('Data File that will be used:').'</b></td><td><tt>'.$env{'form.scantron_selectfile'}.'</tt></td></tr>
                   6334: '.$CODElist.'
1.203     albertel 6335: </table>
                   6336: <br />
1.492     albertel 6337: <p> '.&mt('If this information is correct, please click on \'[_1]\'.',&mt($button_text)).'</p>
                   6338: <p> '.&mt('If something is incorrect, please click the \'Grading Menu\' button to start over.').'</p>
1.203     albertel 6339: 
                   6340: <br />
1.492     albertel 6341: ');
1.203     albertel 6342: }
                   6343: 
1.423     albertel 6344: =pod
                   6345: 
                   6346: =item scantron_do_warning
                   6347: 
1.424     albertel 6348:    Check if the operator has picked something for all required
                   6349:    fields. Error out if something is missing.
                   6350: 
1.423     albertel 6351: =cut
                   6352: 
1.203     albertel 6353: sub scantron_do_warning {
                   6354:     my ($r)=@_;
1.324     albertel 6355:     my ($symb)=&get_symb($r);
1.203     albertel 6356:     if (!$symb) {return '';}
1.324     albertel 6357:     my $default_form_data=&defaultFormData($symb);
1.203     albertel 6358:     $r->print(&scantron_form_start().$default_form_data);
1.257     albertel 6359:     if ( $env{'form.selectpage'} eq '' ||
                   6360: 	 $env{'form.scantron_selectfile'} eq '' ||
                   6361: 	 $env{'form.scantron_format'} eq '' ) {
1.492     albertel 6362: 	$r->print("<p>".&mt('You have forgetten to specify some information. Please go Back and try again.')."</p>");
1.257     albertel 6363: 	if ( $env{'form.selectpage'} eq '') {
1.492     albertel 6364: 	    $r->print('<p><span class="LC_error">'.&mt('You have not selected a Sequence to grade').'</span></p>');
1.237     albertel 6365: 	} 
1.257     albertel 6366: 	if ( $env{'form.scantron_selectfile'} eq '') {
1.492     albertel 6367: 	    $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 6368: 	} 
1.257     albertel 6369: 	if ( $env{'form.scantron_format'} eq '') {
1.492     albertel 6370: 	    $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 6371: 	} 
                   6372:     } else {
1.265     www      6373: 	my $warning=&scantron_warning_screen('Grading: Validate Records');
1.492     albertel 6374: 	$r->print('
                   6375: '.$warning.'
                   6376: <input type="submit" name="submit" value="'.&mt('Grading: Validate Records').'" />
1.203     albertel 6377: <input type="hidden" name="command" value="scantron_validate" />
1.492     albertel 6378: ');
1.237     albertel 6379:     }
1.352     albertel 6380:     $r->print("</form><br />".&show_grading_menu_form($symb));
1.203     albertel 6381:     return '';
                   6382: }
                   6383: 
1.423     albertel 6384: =pod
                   6385: 
                   6386: =item scantron_form_start
                   6387: 
1.424     albertel 6388:     html hidden input for remembering all selected grading options
                   6389: 
1.423     albertel 6390: =cut
                   6391: 
1.203     albertel 6392: sub scantron_form_start {
                   6393:     my ($max_bubble)=@_;
                   6394:     my $result= <<SCANTRONFORM;
                   6395: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="scantronupload">
1.257     albertel 6396:   <input type="hidden" name="selectpage" value="$env{'form.selectpage'}" />
                   6397:   <input type="hidden" name="scantron_format" value="$env{'form.scantron_format'}" />
                   6398:   <input type="hidden" name="scantron_selectfile" value="$env{'form.scantron_selectfile'}" />
1.218     albertel 6399:   <input type="hidden" name="scantron_maxbubble" value="$max_bubble" />
1.257     albertel 6400:   <input type="hidden" name="scantron_CODElist" value="$env{'form.scantron_CODElist'}" />
                   6401:   <input type="hidden" name="scantron_CODEunique" value="$env{'form.scantron_CODEunique'}" />
                   6402:   <input type="hidden" name="scantron_options_redo" value="$env{'form.scantron_options_redo'}" />
                   6403:   <input type="hidden" name="scantron_options_ignore" value="$env{'form.scantron_options_ignore'}" />
1.331     albertel 6404:   <input type="hidden" name="scantron_options_hidden" value="$env{'form.scantron_options_hidden'}" />
1.203     albertel 6405: SCANTRONFORM
1.447     foxr     6406: 
                   6407:   my $line = 0;
                   6408:     while (defined($env{"form.scantron.bubblelines.$line"})) {
                   6409:        my $chunk =
                   6410: 	   '<input type="hidden" name="scantron.bubblelines.'.$line.'" value="'.$env{"form.scantron.bubblelines.$line"}.'" />'."\n";
1.448     foxr     6411:        $chunk .=
                   6412: 	   '<input type="hidden" name="scantron.first_bubble_line.'.$line.'" value="'.$env{"form.scantron.first_bubble_line.$line"}.'" />'."\n";
1.503     raeburn  6413:        $chunk .= 
                   6414:            '<input type="hidden" name="scantron.sub_bubblelines.'.$line.'" value="'.$env{"form.scantron.sub_bubblelines.$line"}.'" />'."\n";
1.504     raeburn  6415:        $chunk .=
                   6416:            '<input type="hidden" name="scantron.responsetype.'.$line.'" value="'.$env{"form.scantron.responsetype.$line"}.'" />'."\n";
1.447     foxr     6417:        $result .= $chunk;
                   6418:        $line++;
                   6419:    }
1.203     albertel 6420:     return $result;
                   6421: }
                   6422: 
1.423     albertel 6423: =pod
                   6424: 
                   6425: =item scantron_validate_file
                   6426: 
1.424     albertel 6427:     Dispatch routine for doing validation of a bubble sheet data file.
                   6428: 
                   6429:     Also processes any necessary information resets that need to
                   6430:     occur before validation begins (ignore previous corrections,
                   6431:     restarting the skipped records processing)
                   6432: 
1.423     albertel 6433: =cut
                   6434: 
1.157     albertel 6435: sub scantron_validate_file {
                   6436:     my ($r) = @_;
1.324     albertel 6437:     my ($symb)=&get_symb($r);
1.157     albertel 6438:     if (!$symb) {return '';}
1.324     albertel 6439:     my $default_form_data=&defaultFormData($symb);
1.200     albertel 6440:     
                   6441:     # do the detection of only doing skipped records first befroe we delete
1.424     albertel 6442:     # them when doing the corrections reset
1.257     albertel 6443:     if ($env{'form.scantron_options_redo'} ne 'redo_skipped_ready') {
1.200     albertel 6444: 	&reset_skipping_status();
                   6445:     }
1.257     albertel 6446:     if ($env{'form.scantron_options_redo'} eq 'redo_skipped') {
1.200     albertel 6447: 	&remember_current_skipped();
1.257     albertel 6448: 	$env{'form.scantron_options_redo'}='redo_skipped_ready';
1.200     albertel 6449:     }
                   6450: 
1.257     albertel 6451:     if ($env{'form.scantron_options_ignore'} eq 'ignore_corrections') {
1.200     albertel 6452: 	&check_for_error($r,&scantron_remove_file('corrected'));
                   6453: 	&check_for_error($r,&scantron_remove_file('skipped'));
                   6454: 	&check_for_error($r,&scantron_remove_scan_data());
1.257     albertel 6455: 	$env{'form.scantron_options_ignore'}='done';
1.192     albertel 6456:     }
1.200     albertel 6457: 
1.257     albertel 6458:     if ($env{'form.scantron_corrections'}) {
1.157     albertel 6459: 	&scantron_process_corrections($r);
                   6460:     }
1.503     raeburn  6461:     $r->print('<p>'.&mt('Gathering necessary information.').'</p>');$r->rflush();
1.157     albertel 6462:     #get the student pick code ready
                   6463:     $r->print(&Apache::loncommon::studentbrowser_javascript());
1.582     raeburn  6464:     my $nav_error;
                   6465:     my $max_bubble=&scantron_get_maxbubble(\$nav_error);
                   6466:     if ($nav_error) {
                   6467:         $r->print(&navmap_errormsg());
                   6468:         return '';
                   6469:     }
1.203     albertel 6470:     my $result=&scantron_form_start($max_bubble).$default_form_data;
1.157     albertel 6471:     $r->print($result);
                   6472:     
1.334     albertel 6473:     my @validate_phases=( 'sequence',
                   6474: 			  'ID',
1.157     albertel 6475: 			  'CODE',
                   6476: 			  'doublebubble',
                   6477: 			  'missingbubbles');
1.257     albertel 6478:     if (!$env{'form.validatepass'}) {
                   6479: 	$env{'form.validatepass'} = 0;
1.157     albertel 6480:     }
1.257     albertel 6481:     my $currentphase=$env{'form.validatepass'};
1.157     albertel 6482: 
1.448     foxr     6483: 
1.157     albertel 6484:     my $stop=0;
                   6485:     while (!$stop && $currentphase < scalar(@validate_phases)) {
1.503     raeburn  6486: 	$r->print(&mt('Validating '.$validate_phases[$currentphase]).'<br />');
1.157     albertel 6487: 	$r->rflush();
                   6488: 	my $which="scantron_validate_".$validate_phases[$currentphase];
                   6489: 	{
                   6490: 	    no strict 'refs';
                   6491: 	    ($stop,$currentphase)=&$which($r,$currentphase);
                   6492: 	}
                   6493:     }
                   6494:     if (!$stop) {
1.203     albertel 6495: 	my $warning=&scantron_warning_screen('Start Grading');
1.542     raeburn  6496: 	$r->print(&mt('Validation process complete.').'<br />'.
                   6497:                   $warning.
                   6498:                   &mt('Perform verification for each student after storage of submissions?').
                   6499:                   '&nbsp;<span class="LC_nobreak"><label>'.
                   6500:                   '<input type="radio" name="verifyrecord" value="1" />'.&mt('Yes').'</label>'.
                   6501:                   ('&nbsp;'x3).'<label>'.
                   6502:                   '<input type="radio" name="verifyrecord" value="0" checked="checked" />'.&mt('No').
                   6503:                   '</label></span><br />'.
                   6504:                   &mt('Grading will take longer if you use verification.').'<br />'.
1.572     www      6505:                   &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  6506:                   '<input type="submit" name="submit" value="'.&mt('Start Grading').'" />'.
                   6507:                   '<input type="hidden" name="command" value="scantron_process" />'."\n");
1.157     albertel 6508:     } else {
                   6509: 	$r->print('<input type="hidden" name="command" value="scantron_validate" />');
                   6510: 	$r->print("<input type='hidden' name='validatepass' value='".$currentphase."' />");
                   6511:     }
                   6512:     if ($stop) {
1.334     albertel 6513: 	if ($validate_phases[$currentphase] eq 'sequence') {
1.539     riegler  6514: 	    $r->print('<input type="submit" name="submit" value="'.&mt('Ignore').' &rarr; " />');
1.492     albertel 6515: 	    $r->print(' '.&mt('this error').' <br />');
1.334     albertel 6516: 
1.492     albertel 6517: 	    $r->print(" <p>".&mt("Or click the 'Grading Menu' button to start over.")."</p>");
1.334     albertel 6518: 	} else {
1.503     raeburn  6519:             if ($validate_phases[$currentphase] eq 'doublebubble' || $validate_phases[$currentphase] eq 'missingbubbles') {
1.539     riegler  6520: 	        $r->print('<input type="button" name="submitbutton" value="'.&mt('Continue').' &rarr;" onclick="javascript:verify_bubble_radio(this.form)" />');
1.503     raeburn  6521:             } else {
1.539     riegler  6522:                 $r->print('<input type="submit" name="submit" value="'.&mt('Continue').' &rarr;" />');
1.503     raeburn  6523:             }
1.492     albertel 6524: 	    $r->print(' '.&mt('using corrected info').' <br />');
                   6525: 	    $r->print("<input type='submit' value='".&mt("Skip")."' name='scantron_skip_record' />");
                   6526: 	    $r->print(" ".&mt("this scanline saving it for later."));
1.334     albertel 6527: 	}
1.157     albertel 6528:     }
1.352     albertel 6529:     $r->print(" </form><br />".&show_grading_menu_form($symb));
1.157     albertel 6530:     return '';
                   6531: }
                   6532: 
1.423     albertel 6533: 
                   6534: =pod
                   6535: 
                   6536: =item scantron_remove_file
                   6537: 
1.424     albertel 6538:    Removes the requested bubble sheet data file, makes sure that
                   6539:    scantron_original_<filename> is never removed
                   6540: 
                   6541: 
1.423     albertel 6542: =cut
                   6543: 
1.200     albertel 6544: sub scantron_remove_file {
1.192     albertel 6545:     my ($which)=@_;
1.257     albertel 6546:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   6547:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1.192     albertel 6548:     my $file='scantron_';
1.200     albertel 6549:     if ($which eq 'corrected' || $which eq 'skipped') {
                   6550: 	$file.=$which.'_';
1.192     albertel 6551:     } else {
                   6552: 	return 'refused';
                   6553:     }
1.257     albertel 6554:     $file.=$env{'form.scantron_selectfile'};
1.200     albertel 6555:     return &Apache::lonnet::removeuserfile($cname,$cdom,$file);
                   6556: }
                   6557: 
1.423     albertel 6558: 
                   6559: =pod
                   6560: 
                   6561: =item scantron_remove_scan_data
                   6562: 
1.424     albertel 6563:    Removes all scan_data correction for the requested bubble sheet
                   6564:    data file.  (In the case that both the are doing skipped records we need
                   6565:    to remember the old skipped lines for the time being so that element
                   6566:    persists for a while.)
                   6567: 
1.423     albertel 6568: =cut
                   6569: 
1.200     albertel 6570: sub scantron_remove_scan_data {
1.257     albertel 6571:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   6572:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1.192     albertel 6573:     my @keys=&Apache::lonnet::getkeys('nohist_scantrondata',$cdom,$cname);
                   6574:     my @todelete;
1.257     albertel 6575:     my $filename=$env{'form.scantron_selectfile'};
1.192     albertel 6576:     foreach my $key (@keys) {
                   6577: 	if ($key=~/^\Q$filename\E_/) {
1.257     albertel 6578: 	    if ($env{'form.scantron_options_redo'} eq 'redo_skipped_ready' &&
1.200     albertel 6579: 		$key=~/remember_skipping/) {
                   6580: 		next;
                   6581: 	    }
1.192     albertel 6582: 	    push(@todelete,$key);
                   6583: 	}
                   6584:     }
1.200     albertel 6585:     my $result;
1.192     albertel 6586:     if (@todelete) {
1.491     albertel 6587: 	$result = &Apache::lonnet::del('nohist_scantrondata',
                   6588: 				       \@todelete,$cdom,$cname);
                   6589:     } else {
                   6590: 	$result = 'ok';
1.192     albertel 6591:     }
                   6592:     return $result;
                   6593: }
                   6594: 
1.423     albertel 6595: 
                   6596: =pod
                   6597: 
                   6598: =item scantron_getfile
                   6599: 
1.424     albertel 6600:     Fetches the requested bubble sheet data file (all 3 versions), and
                   6601:     the scan_data hash
                   6602:   
                   6603:   Arguments:
                   6604:     None
                   6605: 
                   6606:   Returns:
                   6607:     2 hash references
                   6608: 
                   6609:      - first one has 
                   6610:          orig      -
                   6611:          corrected -
                   6612:          skipped   -  each of which points to an array ref of the specified
                   6613:                       file broken up into individual lines
                   6614:          count     - number of scanlines
                   6615:  
                   6616:      - second is the scan_data hash possible keys are
1.425     albertel 6617:        ($number refers to scanline numbered $number and thus the key affects
                   6618:         only that scanline
                   6619:         $bubline refers to the specific bubble line element and the aspects
                   6620:         refers to that specific bubble line element)
                   6621: 
                   6622:        $number.user - username:domain to use
                   6623:        $number.CODE_ignore_dup 
                   6624:                     - ignore the duplicate CODE error 
                   6625:        $number.useCODE
                   6626:                     - use the CODE in the scanline as is
                   6627:        $number.no_bubble.$bubline
                   6628:                     - it is valid that there is no bubbled in bubble
                   6629:                       at $number $bubline
                   6630:        remember_skipping
                   6631:                     - a frozen hash containing keys of $number and values
                   6632:                       of either 
                   6633:                         1 - we are on a 'do skipped records pass' and plan
                   6634:                             on processing this line
                   6635:                         2 - we are on a 'do skipped records pass' and this
                   6636:                             scanline has been marked to skip yet again
1.424     albertel 6637: 
1.423     albertel 6638: =cut
                   6639: 
1.157     albertel 6640: sub scantron_getfile {
1.200     albertel 6641:     #FIXME really would prefer a scantron directory
1.257     albertel 6642:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   6643:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1.157     albertel 6644:     my $lines;
                   6645:     $lines=&Apache::lonnet::getfile('/uploaded/'.$cdom.'/'.$cname.'/'.
1.257     albertel 6646: 		       'scantron_orig_'.$env{'form.scantron_selectfile'});
1.157     albertel 6647:     my %scanlines;
                   6648:     $scanlines{'orig'}=[(split("\n",$lines,-1))];
                   6649:     my $temp=$scanlines{'orig'};
                   6650:     $scanlines{'count'}=$#$temp;
                   6651: 
                   6652:     $lines=&Apache::lonnet::getfile('/uploaded/'.$cdom.'/'.$cname.'/'.
1.257     albertel 6653: 		       'scantron_corrected_'.$env{'form.scantron_selectfile'});
1.157     albertel 6654:     if ($lines eq '-1') {
                   6655: 	$scanlines{'corrected'}=[];
                   6656:     } else {
                   6657: 	$scanlines{'corrected'}=[(split("\n",$lines,-1))];
                   6658:     }
                   6659:     $lines=&Apache::lonnet::getfile('/uploaded/'.$cdom.'/'.$cname.'/'.
1.257     albertel 6660: 		       'scantron_skipped_'.$env{'form.scantron_selectfile'});
1.157     albertel 6661:     if ($lines eq '-1') {
                   6662: 	$scanlines{'skipped'}=[];
                   6663:     } else {
                   6664: 	$scanlines{'skipped'}=[(split("\n",$lines,-1))];
                   6665:     }
1.175     albertel 6666:     my @tmp=&Apache::lonnet::dump('nohist_scantrondata',$cdom,$cname);
1.157     albertel 6667:     if ($tmp[0] =~ /^(error:|no_such_host)/) { @tmp=(); }
                   6668:     my %scan_data = @tmp;
                   6669:     return (\%scanlines,\%scan_data);
                   6670: }
                   6671: 
1.423     albertel 6672: =pod
                   6673: 
                   6674: =item lonnet_putfile
                   6675: 
1.424     albertel 6676:    Wrapper routine to call &Apache::lonnet::finishuserfileupload
                   6677: 
                   6678:  Arguments:
                   6679:    $contents - data to store
                   6680:    $filename - filename to store $contents into
                   6681: 
                   6682:  Returns:
                   6683:    result value from &Apache::lonnet::finishuserfileupload
                   6684: 
1.423     albertel 6685: =cut
                   6686: 
1.157     albertel 6687: sub lonnet_putfile {
                   6688:     my ($contents,$filename)=@_;
1.257     albertel 6689:     my $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   6690:     my $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
                   6691:     $env{'form.sillywaytopassafilearound'}=$contents;
1.275     albertel 6692:     &Apache::lonnet::finishuserfileupload($docuname,$docudom,'sillywaytopassafilearound',$filename);
1.157     albertel 6693: 
                   6694: }
                   6695: 
1.423     albertel 6696: =pod
                   6697: 
                   6698: =item scantron_putfile
                   6699: 
1.424     albertel 6700:     Stores the current version of the bubble sheet data files, and the
                   6701:     scan_data hash. (Does not modify the original version only the
                   6702:     corrected and skipped versions.
                   6703: 
                   6704:  Arguments:
                   6705:     $scanlines - hash ref that looks like the first return value from
                   6706:                  &scantron_getfile()
                   6707:     $scan_data - hash ref that looks like the second return value from
                   6708:                  &scantron_getfile()
                   6709: 
1.423     albertel 6710: =cut
                   6711: 
1.157     albertel 6712: sub scantron_putfile {
                   6713:     my ($scanlines,$scan_data) = @_;
1.200     albertel 6714:     #FIXME really would prefer a scantron directory
1.257     albertel 6715:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   6716:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1.200     albertel 6717:     if ($scanlines) {
                   6718: 	my $prefix='scantron_';
1.157     albertel 6719: # no need to update orig, shouldn't change
                   6720: #   &lonnet_putfile(join("\n",@{$scanlines->{'orig'}}),$prefix.'orig_'.
1.257     albertel 6721: #		    $env{'form.scantron_selectfile'});
1.200     albertel 6722: 	&lonnet_putfile(join("\n",@{$scanlines->{'corrected'}}),
                   6723: 			$prefix.'corrected_'.
1.257     albertel 6724: 			$env{'form.scantron_selectfile'});
1.200     albertel 6725: 	&lonnet_putfile(join("\n",@{$scanlines->{'skipped'}}),
                   6726: 			$prefix.'skipped_'.
1.257     albertel 6727: 			$env{'form.scantron_selectfile'});
1.200     albertel 6728:     }
1.175     albertel 6729:     &Apache::lonnet::put('nohist_scantrondata',$scan_data,$cdom,$cname);
1.157     albertel 6730: }
                   6731: 
1.423     albertel 6732: =pod
                   6733: 
                   6734: =item scantron_get_line
                   6735: 
1.424     albertel 6736:    Returns the correct version of the scanline
                   6737: 
                   6738:  Arguments:
                   6739:     $scanlines - hash ref that looks like the first return value from
                   6740:                  &scantron_getfile()
                   6741:     $scan_data - hash ref that looks like the second return value from
                   6742:                  &scantron_getfile()
                   6743:     $i         - number of the requested line (starts at 0)
                   6744: 
                   6745:  Returns:
                   6746:    A scanline, (either the original or the corrected one if it
                   6747:    exists), or undef if the requested scanline should be
                   6748:    skipped. (Either because it's an skipped scanline, or it's an
                   6749:    unskipped scanline and we are not doing a 'do skipped scanlines'
                   6750:    pass.
                   6751: 
1.423     albertel 6752: =cut
                   6753: 
1.157     albertel 6754: sub scantron_get_line {
1.200     albertel 6755:     my ($scanlines,$scan_data,$i)=@_;
1.376     albertel 6756:     if (&should_be_skipped($scanlines,$scan_data,$i)) { return undef; }
                   6757:     #if ($scanlines->{'skipped'}[$i]) { return undef; }
1.157     albertel 6758:     if ($scanlines->{'corrected'}[$i]) {return $scanlines->{'corrected'}[$i];}
                   6759:     return $scanlines->{'orig'}[$i]; 
                   6760: }
                   6761: 
1.423     albertel 6762: =pod
                   6763: 
                   6764: =item scantron_todo_count
                   6765: 
1.424     albertel 6766:     Counts the number of scanlines that need processing.
                   6767: 
                   6768:  Arguments:
                   6769:     $scanlines - hash ref that looks like the first return value from
                   6770:                  &scantron_getfile()
                   6771:     $scan_data - hash ref that looks like the second return value from
                   6772:                  &scantron_getfile()
                   6773: 
                   6774:  Returns:
                   6775:     $count - number of scanlines to process
                   6776: 
1.423     albertel 6777: =cut
                   6778: 
1.200     albertel 6779: sub get_todo_count {
                   6780:     my ($scanlines,$scan_data)=@_;
                   6781:     my $count=0;
                   6782:     for (my $i=0;$i<=$scanlines->{'count'};$i++) {
                   6783: 	my $line=&scantron_get_line($scanlines,$scan_data,$i);
                   6784: 	if ($line=~/^[\s\cz]*$/) { next; }
                   6785: 	$count++;
                   6786:     }
                   6787:     return $count;
                   6788: }
                   6789: 
1.423     albertel 6790: =pod
                   6791: 
                   6792: =item scantron_put_line
                   6793: 
1.424     albertel 6794:     Updates the 'corrected' or 'skipped' versions of the bubble sheet
                   6795:     data file.
                   6796: 
                   6797:  Arguments:
                   6798:     $scanlines - hash ref that looks like the first return value from
                   6799:                  &scantron_getfile()
                   6800:     $scan_data - hash ref that looks like the second return value from
                   6801:                  &scantron_getfile()
                   6802:     $i         - line number to update
                   6803:     $newline   - contents of the updated scanline
                   6804:     $skip      - if true make the line for skipping and update the
                   6805:                  'skipped' file
                   6806: 
1.423     albertel 6807: =cut
                   6808: 
1.157     albertel 6809: sub scantron_put_line {
1.200     albertel 6810:     my ($scanlines,$scan_data,$i,$newline,$skip)=@_;
1.157     albertel 6811:     if ($skip) {
                   6812: 	$scanlines->{'skipped'}[$i]=$newline;
1.376     albertel 6813: 	&start_skipping($scan_data,$i);
1.157     albertel 6814: 	return;
                   6815:     }
                   6816:     $scanlines->{'corrected'}[$i]=$newline;
                   6817: }
                   6818: 
1.423     albertel 6819: =pod
                   6820: 
                   6821: =item scantron_clear_skip
                   6822: 
1.424     albertel 6823:    Remove a line from the 'skipped' file
                   6824: 
                   6825:  Arguments:
                   6826:     $scanlines - hash ref that looks like the first return value from
                   6827:                  &scantron_getfile()
                   6828:     $scan_data - hash ref that looks like the second return value from
                   6829:                  &scantron_getfile()
                   6830:     $i         - line number to update
                   6831: 
1.423     albertel 6832: =cut
                   6833: 
1.376     albertel 6834: sub scantron_clear_skip {
                   6835:     my ($scanlines,$scan_data,$i)=@_;
                   6836:     if (exists($scanlines->{'skipped'}[$i])) {
                   6837: 	undef($scanlines->{'skipped'}[$i]);
                   6838: 	return 1;
                   6839:     }
                   6840:     return 0;
                   6841: }
                   6842: 
1.423     albertel 6843: =pod
                   6844: 
                   6845: =item scantron_filter_not_exam
                   6846: 
1.424     albertel 6847:    Filter routine used by &Apache::lonnavmaps::retrieveResources(), to
                   6848:    filter out resources that are not marked as 'exam' mode
                   6849: 
1.423     albertel 6850: =cut
                   6851: 
1.334     albertel 6852: sub scantron_filter_not_exam {
                   6853:     my ($curres)=@_;
                   6854:     
                   6855:     if (ref($curres) && $curres->is_problem() && !$curres->is_exam()) {
                   6856: 	# if the user has asked to not have either hidden
                   6857: 	# or 'randomout' controlled resources to be graded
                   6858: 	# don't include them
                   6859: 	if ($env{'form.scantron_options_hidden'} eq 'ignore_hidden'
                   6860: 	    && $curres->randomout) {
                   6861: 	    return 0;
                   6862: 	}
                   6863: 	return 1;
                   6864:     }
                   6865:     return 0;
                   6866: }
                   6867: 
1.423     albertel 6868: =pod
                   6869: 
                   6870: =item scantron_validate_sequence
                   6871: 
1.424     albertel 6872:     Validates the selected sequence, checking for resource that are
                   6873:     not set to exam mode.
                   6874: 
1.423     albertel 6875: =cut
                   6876: 
1.334     albertel 6877: sub scantron_validate_sequence {
                   6878:     my ($r,$currentphase) = @_;
                   6879: 
                   6880:     my $navmap=Apache::lonnavmaps::navmap->new();
1.582     raeburn  6881:     unless (ref($navmap)) {
                   6882:         $r->print(&navmap_errormsg());
                   6883:         return (1,$currentphase);
                   6884:     }
1.334     albertel 6885:     my (undef,undef,$sequence)=
                   6886: 	&Apache::lonnet::decode_symb($env{'form.selectpage'});
                   6887: 
                   6888:     my $map=$navmap->getResourceByUrl($sequence);
                   6889: 
                   6890:     $r->print('<input type="hidden" name="validate_sequence_exam"
                   6891:                                     value="ignore" />');
                   6892:     if ($env{'form.validate_sequence_exam'} ne 'ignore') {
                   6893: 	my @resources=
                   6894: 	    $navmap->retrieveResources($map,\&scantron_filter_not_exam,1,0);
                   6895: 	if (@resources) {
1.357     banghart 6896: 	    $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 6897: 	    return (1,$currentphase);
                   6898: 	}
                   6899:     }
                   6900: 
                   6901:     return (0,$currentphase+1);
                   6902: }
                   6903: 
1.423     albertel 6904: 
                   6905: 
1.157     albertel 6906: sub scantron_validate_ID {
                   6907:     my ($r,$currentphase) = @_;
                   6908:     
                   6909:     #get student info
                   6910:     my $classlist=&Apache::loncoursedata::get_classlist();
                   6911:     my %idmap=&username_to_idmap($classlist);
                   6912: 
                   6913:     #get scantron line setup
1.257     albertel 6914:     my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
1.157     albertel 6915:     my ($scanlines,$scan_data)=&scantron_getfile();
1.582     raeburn  6916: 
                   6917:     my $nav_error;
                   6918:     &scantron_get_maxbubble(\$nav_error); # parse needs the bubble_lines.. array.
                   6919:     if ($nav_error) {
                   6920:         $r->print(&navmap_errormsg());
                   6921:         return(1,$currentphase);
                   6922:     }
1.157     albertel 6923: 
                   6924:     my %found=('ids'=>{},'usernames'=>{});
                   6925:     for (my $i=0;$i<=$scanlines->{'count'};$i++) {
1.200     albertel 6926: 	my $line=&scantron_get_line($scanlines,$scan_data,$i);
1.157     albertel 6927: 	if ($line=~/^[\s\cz]*$/) { next; }
                   6928: 	my $scan_record=&scantron_parse_scanline($line,$i,\%scantron_config,
                   6929: 						 $scan_data);
                   6930: 	my $id=$$scan_record{'scantron.ID'};
                   6931: 	my $found;
                   6932: 	foreach my $checkid (keys(%idmap)) {
                   6933: 	    if (lc($checkid) eq lc($id)) { $found=$checkid;last; }
                   6934: 	}
                   6935: 	if ($found) {
                   6936: 	    my $username=$idmap{$found};
                   6937: 	    if ($found{'ids'}{$found}) {
                   6938: 		&scantron_get_correction($r,$i,$scan_record,\%scantron_config,
                   6939: 					 $line,'duplicateID',$found);
1.194     albertel 6940: 		return(1,$currentphase);
1.157     albertel 6941: 	    } elsif ($found{'usernames'}{$username}) {
                   6942: 		&scantron_get_correction($r,$i,$scan_record,\%scantron_config,
                   6943: 					 $line,'duplicateID',$username);
1.194     albertel 6944: 		return(1,$currentphase);
1.157     albertel 6945: 	    }
1.186     albertel 6946: 	    #FIXME store away line we previously saw the ID on to use above
1.157     albertel 6947: 	    $found{'ids'}{$found}++;
                   6948: 	    $found{'usernames'}{$username}++;
                   6949: 	} else {
                   6950: 	    if ($id =~ /^\s*$/) {
1.158     albertel 6951: 		my $username=&scan_data($scan_data,"$i.user");
1.157     albertel 6952: 		if (defined($username) && $found{'usernames'}{$username}) {
                   6953: 		    &scantron_get_correction($r,$i,$scan_record,
                   6954: 					     \%scantron_config,
                   6955: 					     $line,'duplicateID',$username);
1.194     albertel 6956: 		    return(1,$currentphase);
1.157     albertel 6957: 		} elsif (!defined($username)) {
                   6958: 		    &scantron_get_correction($r,$i,$scan_record,
                   6959: 					     \%scantron_config,
                   6960: 					     $line,'incorrectID');
1.194     albertel 6961: 		    return(1,$currentphase);
1.157     albertel 6962: 		}
                   6963: 		$found{'usernames'}{$username}++;
                   6964: 	    } else {
                   6965: 		&scantron_get_correction($r,$i,$scan_record,\%scantron_config,
                   6966: 					 $line,'incorrectID');
1.194     albertel 6967: 		return(1,$currentphase);
1.157     albertel 6968: 	    }
                   6969: 	}
                   6970:     }
                   6971: 
                   6972:     return (0,$currentphase+1);
                   6973: }
                   6974: 
1.423     albertel 6975: 
1.157     albertel 6976: sub scantron_get_correction {
                   6977:     my ($r,$i,$scan_record,$scan_config,$line,$error,$arg)=@_;
1.454     banghart 6978: #FIXME in the case of a duplicated ID the previous line, probably need
1.157     albertel 6979: #to show both the current line and the previous one and allow skipping
                   6980: #the previous one or the current one
                   6981: 
1.333     albertel 6982:     if ( $$scan_record{'scantron.PaperID'} =~ /\S/) {
1.492     albertel 6983: 	$r->print("<p>".&mt("<b>An error was detected ($error)</b>".
                   6984: 			    " for PaperID <tt>[_1]</tt>",
                   6985: 			    $$scan_record{'scantron.PaperID'})."</p> \n");
1.157     albertel 6986:     } else {
1.492     albertel 6987: 	$r->print("<p>".&mt("<b>An error was detected ($error)</b>".
                   6988: 			    " in scanline [_1] <pre>[_2]</pre>",
                   6989: 			    $i,$line)."</p> \n");
                   6990:     }
                   6991:     my $message="<p>".&mt("The ID on the form is  <tt>[_1]</tt><br />".
                   6992: 			  "The name on the paper is [_2],[_3]",
                   6993: 			  $$scan_record{'scantron.ID'},
                   6994: 			  $$scan_record{'scantron.LastName'},
                   6995: 			  $$scan_record{'scantron.FirstName'})."</p>";
1.242     albertel 6996: 
1.157     albertel 6997:     $r->print('<input type="hidden" name="scantron_corrections" value="'.$error.'" />'."\n");
                   6998:     $r->print('<input type="hidden" name="scantron_line" value="'.$i.'" />'."\n");
1.503     raeburn  6999:                            # Array populated for doublebubble or
                   7000:     my @lines_to_correct;  # missingbubble errors to build javascript
                   7001:                            # to validate radio button checking   
                   7002: 
1.157     albertel 7003:     if ($error =~ /ID$/) {
1.186     albertel 7004: 	if ($error eq 'incorrectID') {
1.492     albertel 7005: 	    $r->print("<p>".&mt("The encoded ID is not in the classlist").
                   7006: 		      "</p>\n");
1.157     albertel 7007: 	} elsif ($error eq 'duplicateID') {
1.492     albertel 7008: 	    $r->print("<p>".&mt("The encoded ID has also been used by a previous paper [_1]",$arg)."</p>\n");
1.157     albertel 7009: 	}
1.242     albertel 7010: 	$r->print($message);
1.492     albertel 7011: 	$r->print("<p>".&mt("How should I handle this?")." <br /> \n");
1.157     albertel 7012: 	$r->print("\n<ul><li> ");
                   7013: 	#FIXME it would be nice if this sent back the user ID and
                   7014: 	#could do partial userID matches
                   7015: 	$r->print(&Apache::loncommon::selectstudent_link('scantronupload',
                   7016: 				       'scantron_username','scantron_domain'));
                   7017: 	$r->print(": <input type='text' name='scantron_username' value='' />");
                   7018: 	$r->print("\n@".
1.257     albertel 7019: 		 &Apache::loncommon::select_dom_form($env{'request.role.domain'},'scantron_domain'));
1.157     albertel 7020: 
                   7021: 	$r->print('</li>');
1.186     albertel 7022:     } elsif ($error =~ /CODE$/) {
                   7023: 	if ($error eq 'incorrectCODE') {
1.492     albertel 7024: 	    $r->print("<p>".&mt("The encoded CODE is not in the list of possible CODEs.")."</p>\n");
1.186     albertel 7025: 	} elsif ($error eq 'duplicateCODE') {
1.492     albertel 7026: 	    $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 7027: 	}
1.492     albertel 7028: 	$r->print("<p>".&mt("The CODE on the form is  <tt>'[_1]'</tt>",
                   7029: 			    $$scan_record{'scantron.CODE'})."<br />\n");
1.242     albertel 7030: 	$r->print($message);
1.492     albertel 7031: 	$r->print("<p>".&mt("How should I handle this?")." <br /> \n");
1.187     albertel 7032: 	$r->print("\n<br /> ");
1.194     albertel 7033: 	my $i=0;
1.273     albertel 7034: 	if ($error eq 'incorrectCODE' 
                   7035: 	    && $$scan_record{'scantron.CODE'}=~/\S/ ) {
1.194     albertel 7036: 	    my ($max,$closest)=&scantron_get_closely_matching_CODEs($arg,$$scan_record{'scantron.CODE'});
1.278     albertel 7037: 	    if ($closest > 0) {
                   7038: 		foreach my $testcode (@{$closest}) {
                   7039: 		    my $checked='';
1.569     bisitz   7040: 		    if (!$i) { $checked=' checked="checked"'; }
1.492     albertel 7041: 		    $r->print("
                   7042:    <label>
1.569     bisitz   7043:        <input type='radio' name='scantron_CODE_resolution' value='use_closest_$i'$checked />
1.492     albertel 7044:        ".&mt("Use the similar CODE [_1] instead.",
                   7045: 	    "<b><tt>".$testcode."</tt></b>")."
                   7046:     </label>
                   7047:     <input type='hidden' name='scantron_CODE_closest_$i' value='$testcode' />");
1.278     albertel 7048: 		    $r->print("\n<br />");
                   7049: 		    $i++;
                   7050: 		}
1.194     albertel 7051: 	    }
                   7052: 	}
1.273     albertel 7053: 	if ($$scan_record{'scantron.CODE'}=~/\S/ ) {
1.569     bisitz   7054: 	    my $checked; if (!$i) { $checked=' checked="checked"'; }
1.492     albertel 7055: 	    $r->print("
                   7056:     <label>
1.569     bisitz   7057:         <input type='radio' name='scantron_CODE_resolution' value='use_unfound'$checked />
1.492     albertel 7058:        ".&mt("Use the CODE [_1] that is was on the paper, ignoring the error.",
                   7059: 	     "<b><tt>".$$scan_record{'scantron.CODE'}."</tt></b>")."
                   7060:     </label>");
1.273     albertel 7061: 	    $r->print("\n<br />");
                   7062: 	}
1.194     albertel 7063: 
1.188     albertel 7064: 	$r->print(<<ENDSCRIPT);
                   7065: <script type="text/javascript">
                   7066: function change_radio(field) {
1.190     albertel 7067:     var slct=document.scantronupload.scantron_CODE_resolution;
1.188     albertel 7068:     var i;
                   7069:     for (i=0;i<slct.length;i++) {
                   7070:         if (slct[i].value==field) { slct[i].checked=true; }
                   7071:     }
                   7072: }
                   7073: </script>
                   7074: ENDSCRIPT
1.187     albertel 7075: 	my $href="/adm/pickcode?".
1.359     www      7076: 	   "form=".&escape("scantronupload").
                   7077: 	   "&scantron_format=".&escape($env{'form.scantron_format'}).
                   7078: 	   "&scantron_CODElist=".&escape($env{'form.scantron_CODElist'}).
                   7079: 	   "&curCODE=".&escape($$scan_record{'scantron.CODE'}).
                   7080: 	   "&scantron_selectfile=".&escape($env{'form.scantron_selectfile'});
1.332     albertel 7081: 	if ($env{'form.scantron_CODElist'} =~ /\S/) { 
1.492     albertel 7082: 	    $r->print("
                   7083:     <label>
                   7084:        <input type='radio' name='scantron_CODE_resolution' value='use_found' />
                   7085:        ".&mt("[_1]Select[_2] a CODE from the list of all CODEs and use it.",
                   7086: 	     "<a target='_blank' href='$href'>","</a>")."
                   7087:     </label> 
1.558     bisitz   7088:     ".&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 7089: 	    $r->print("\n<br />");
                   7090: 	}
1.492     albertel 7091: 	$r->print("
                   7092:     <label>
                   7093:        <input type='radio' name='scantron_CODE_resolution' value='use_typed' />
                   7094:        ".&mt("Use [_1] as the CODE.",
                   7095: 	     "</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 7096: 	$r->print("\n<br /><br />");
1.157     albertel 7097:     } elsif ($error eq 'doublebubble') {
1.503     raeburn  7098: 	$r->print("<p>".&mt("There have been multiple bubbles scanned for some question(s)")."</p>\n");
1.497     foxr     7099: 
                   7100: 	# The form field scantron_questions is acutally a list of line numbers.
                   7101: 	# represented by this form so:
                   7102: 
                   7103: 	my $line_list = &questions_to_line_list($arg);
                   7104: 
1.157     albertel 7105: 	$r->print('<input type="hidden" name="scantron_questions" value="'.
1.497     foxr     7106: 		  $line_list.'" />');
1.242     albertel 7107: 	$r->print($message);
1.492     albertel 7108: 	$r->print("<p>".&mt("Please indicate which bubble should be used for grading")."</p>");
1.157     albertel 7109: 	foreach my $question (@{$arg}) {
1.503     raeburn  7110: 	    my @linenums = &prompt_for_corrections($r,$question,$scan_config,
                   7111:                                                    $scan_record, $error);
1.524     raeburn  7112:             push(@lines_to_correct,@linenums);
1.157     albertel 7113: 	}
1.503     raeburn  7114:         $r->print(&verify_bubbles_checked(@lines_to_correct));
1.157     albertel 7115:     } elsif ($error eq 'missingbubble') {
1.492     albertel 7116: 	$r->print("<p>".&mt("There have been <b>no</b> bubbles scanned for some question(s)")."</p>\n");
1.242     albertel 7117: 	$r->print($message);
1.492     albertel 7118: 	$r->print("<p>".&mt("Please indicate which bubble should be used for grading.")."</p>");
1.503     raeburn  7119: 	$r->print(&mt("Some questions have no scanned bubbles.")."\n");
1.497     foxr     7120: 
1.503     raeburn  7121: 	# The form field scantron_questions is actually a list of line numbers not
1.497     foxr     7122: 	# a list of question numbers. Therefore:
                   7123: 	#
                   7124: 	
                   7125: 	my $line_list = &questions_to_line_list($arg);
                   7126: 
1.157     albertel 7127: 	$r->print('<input type="hidden" name="scantron_questions" value="'.
1.497     foxr     7128: 		  $line_list.'" />');
1.157     albertel 7129: 	foreach my $question (@{$arg}) {
1.503     raeburn  7130: 	    my @linenums = &prompt_for_corrections($r,$question,$scan_config,
                   7131:                                                    $scan_record, $error);
1.524     raeburn  7132:             push(@lines_to_correct,@linenums);
1.157     albertel 7133: 	}
1.503     raeburn  7134:         $r->print(&verify_bubbles_checked(@lines_to_correct));
1.157     albertel 7135:     } else {
                   7136: 	$r->print("\n<ul>");
                   7137:     }
                   7138:     $r->print("\n</li></ul>");
1.497     foxr     7139: }
                   7140: 
1.503     raeburn  7141: sub verify_bubbles_checked {
                   7142:     my (@ansnums) = @_;
                   7143:     my $ansnumstr = join('","',@ansnums);
                   7144:     my $warning = &mt("A bubble or 'No bubble' selection has not been made for one or more lines.");
                   7145:     my $output = (<<ENDSCRIPT);
                   7146: <script type="text/javascript">
                   7147: function verify_bubble_radio(form) {
                   7148:     var ansnumArray = new Array ("$ansnumstr");
                   7149:     var need_bubble_count = 0;
                   7150:     for (var i=0; i<ansnumArray.length; i++) {
                   7151:         if (form.elements["scantron_correct_Q_"+ansnumArray[i]].length > 1) {
                   7152:             var bubble_picked = 0; 
                   7153:             for (var j=0; j<form.elements["scantron_correct_Q_"+ansnumArray[i]].length; j++) {
                   7154:                 if (form.elements["scantron_correct_Q_"+ansnumArray[i]][j].checked == true) {
                   7155:                     bubble_picked = 1;
                   7156:                 }
                   7157:             }
                   7158:             if (bubble_picked == 0) {
                   7159:                 need_bubble_count ++;
                   7160:             }
                   7161:         }
                   7162:     }
                   7163:     if (need_bubble_count) {
                   7164:         alert("$warning");
                   7165:         return;
                   7166:     }
                   7167:     form.submit(); 
                   7168: }
                   7169: </script>
                   7170: ENDSCRIPT
                   7171:     return $output;
                   7172: }
                   7173: 
1.497     foxr     7174: =pod
                   7175: 
                   7176: =item  questions_to_line_list
1.157     albertel 7177: 
1.497     foxr     7178: Converts a list of questions into a string of comma separated
                   7179: line numbers in the answer sheet used by the questions.  This is
                   7180: used to fill in the scantron_questions form field.
                   7181: 
                   7182:   Arguments:
                   7183:      questions    - Reference to an array of questions.
                   7184: 
                   7185: =cut
                   7186: 
                   7187: 
                   7188: sub questions_to_line_list {
                   7189:     my ($questions) = @_;
                   7190:     my @lines;
                   7191: 
1.503     raeburn  7192:     foreach my $item (@{$questions}) {
                   7193:         my $question = $item;
                   7194:         my ($first,$count,$last);
                   7195:         if ($item =~ /^(\d+)\.(\d+)$/) {
                   7196:             $question = $1;
                   7197:             my $subquestion = $2;
                   7198:             $first = $first_bubble_line{$question-1} + 1;
                   7199:             my @subans = split(/,/,$subdivided_bubble_lines{$question-1});
                   7200:             my $subcount = 1;
                   7201:             while ($subcount<$subquestion) {
                   7202:                 $first += $subans[$subcount-1];
                   7203:                 $subcount ++;
                   7204:             }
                   7205:             $count = $subans[$subquestion-1];
                   7206:         } else {
                   7207: 	    $first   = $first_bubble_line{$question-1} + 1;
                   7208: 	    $count   = $bubble_lines_per_response{$question-1};
                   7209:         }
1.506     raeburn  7210:         $last = $first+$count-1;
1.503     raeburn  7211:         push(@lines, ($first..$last));
1.497     foxr     7212:     }
                   7213:     return join(',', @lines);
                   7214: }
                   7215: 
                   7216: =pod 
                   7217: 
                   7218: =item prompt_for_corrections
                   7219: 
                   7220: Prompts for a potentially multiline correction to the
                   7221: user's bubbling (factors out common code from scantron_get_correction
                   7222: for multi and missing bubble cases).
                   7223: 
                   7224:  Arguments:
                   7225:    $r           - Apache request object.
                   7226:    $question    - The question number to prompt for.
                   7227:    $scan_config - The scantron file configuration hash.
                   7228:    $scan_record - Reference to the hash that has the the parsed scanlines.
1.503     raeburn  7229:    $error       - Type of error
1.497     foxr     7230: 
                   7231:  Implicit inputs:
                   7232:    %bubble_lines_per_response   - Starting line numbers for each question.
                   7233:                                   Numbered from 0 (but question numbers are from
                   7234:                                   1.
                   7235:    %first_bubble_line           - Starting bubble line for each question.
1.509     raeburn  7236:    %subdivided_bubble_lines     - optionresponse, matchresponse and rankresponse 
                   7237:                                   type problems render as separate sub-questions, 
1.503     raeburn  7238:                                   in exam mode. This hash contains a 
                   7239:                                   comma-separated list of the lines per 
                   7240:                                   sub-question.
1.510     raeburn  7241:    %responsetype_per_response   - essayresponse, formularesponse,
                   7242:                                   stringresponse, imageresponse, reactionresponse,
                   7243:                                   and organicresponse type problem parts can have
1.503     raeburn  7244:                                   multiple lines per response if the weight
                   7245:                                   assigned exceeds 10.  In this case, only
                   7246:                                   one bubble per line is permitted, but more 
                   7247:                                   than one line might contain bubbles, e.g.
                   7248:                                   bubbling of: line 1 - J, line 2 - J, 
                   7249:                                   line 3 - B would assign 22 points.  
1.497     foxr     7250: 
                   7251: =cut
                   7252: 
                   7253: sub prompt_for_corrections {
1.503     raeburn  7254:     my ($r, $question, $scan_config, $scan_record, $error) = @_;
                   7255:     my ($current_line,$lines);
                   7256:     my @linenums;
                   7257:     my $questionnum = $question;
                   7258:     if ($question =~ /^(\d+)\.(\d+)$/) {
                   7259:         $question = $1;
                   7260:         $current_line = $first_bubble_line{$question-1} + 1 ;
                   7261:         my $subquestion = $2;
                   7262:         my @subans = split(/,/,$subdivided_bubble_lines{$question-1});
                   7263:         my $subcount = 1;
                   7264:         while ($subcount<$subquestion) {
                   7265:             $current_line += $subans[$subcount-1];
                   7266:             $subcount ++;
                   7267:         }
                   7268:         $lines = $subans[$subquestion-1];
                   7269:     } else {
                   7270:         $current_line = $first_bubble_line{$question-1} + 1 ;
                   7271:         $lines        = $bubble_lines_per_response{$question-1};
                   7272:     }
1.497     foxr     7273:     if ($lines > 1) {
1.503     raeburn  7274:         $r->print(&mt('The group of bubble lines below responds to a single question.').'<br />');
                   7275:         if (($responsetype_per_response{$question-1} eq 'essayresponse') ||
                   7276:             ($responsetype_per_response{$question-1} eq 'formularesponse') ||
1.510     raeburn  7277:             ($responsetype_per_response{$question-1} eq 'stringresponse') ||
                   7278:             ($responsetype_per_response{$question-1} eq 'imageresponse') ||
                   7279:             ($responsetype_per_response{$question-1} eq 'reactionresponse') ||
                   7280:             ($responsetype_per_response{$question-1} eq 'organicresponse')) {
1.572     www      7281:             $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  7282:         } else {
                   7283:             $r->print(&mt("Select at most one bubble in a single line and select 'No Bubble' in all the other lines. ")."<br />");
                   7284:         }
1.497     foxr     7285:     }
                   7286:     for (my $i =0; $i < $lines; $i++) {
1.503     raeburn  7287:         my $selected = $$scan_record{"scantron.$current_line.answer"};
                   7288: 	&scantron_bubble_selector($r,$scan_config,$current_line, 
                   7289: 	        		  $questionnum,$error,split('', $selected));
1.524     raeburn  7290:         push(@linenums,$current_line);
1.497     foxr     7291: 	$current_line++;
                   7292:     }
                   7293:     if ($lines > 1) {
                   7294: 	$r->print("<hr /><br />");
                   7295:     }
1.503     raeburn  7296:     return @linenums;
1.157     albertel 7297: }
1.423     albertel 7298: 
                   7299: =pod
                   7300: 
                   7301: =item scantron_bubble_selector
                   7302:   
                   7303:    Generates the html radiobuttons to correct a single bubble line
1.424     albertel 7304:    possibly showing the existing the selected bubbles if known
1.423     albertel 7305: 
                   7306:  Arguments:
                   7307:     $r           - Apache request object
                   7308:     $scan_config - hash from &get_scantron_config()
1.497     foxr     7309:     $line        - Number of the line being displayed.
1.503     raeburn  7310:     $questionnum - Question number (may include subquestion)
                   7311:     $error       - Type of error.
1.497     foxr     7312:     @selected    - Array of bubbles picked on this line.
1.423     albertel 7313: 
                   7314: =cut
                   7315: 
1.157     albertel 7316: sub scantron_bubble_selector {
1.503     raeburn  7317:     my ($r,$scan_config,$line,$questionnum,$error,@selected)=@_;
1.157     albertel 7318:     my $max=$$scan_config{'Qlength'};
1.274     albertel 7319: 
                   7320:     my $scmode=$$scan_config{'Qon'};
                   7321:     if ($scmode eq 'number' || $scmode eq 'letter') { $max=10; }	     
                   7322: 
1.157     albertel 7323:     my @alphabet=('A'..'Z');
1.503     raeburn  7324:     $r->print(&Apache::loncommon::start_data_table().
                   7325:               &Apache::loncommon::start_data_table_row());
                   7326:     $r->print('<td rowspan="2" class="LC_leftcol_header">'.$line.'</td>');
1.497     foxr     7327:     for (my $i=0;$i<$max+1;$i++) {
                   7328: 	$r->print("\n".'<td align="center">');
                   7329: 	if ($selected[0] eq $alphabet[$i]) { $r->print('X'); shift(@selected) }
                   7330: 	else { $r->print('&nbsp;'); }
                   7331: 	$r->print('</td>');
                   7332:     }
1.503     raeburn  7333:     $r->print(&Apache::loncommon::end_data_table_row().
                   7334:               &Apache::loncommon::start_data_table_row());
1.497     foxr     7335:     for (my $i=0;$i<$max;$i++) {
                   7336: 	$r->print("\n".
                   7337: 		  '<td><label><input type="radio" name="scantron_correct_Q_'.
                   7338: 		  $line.'" value="'.$i.'" />'.$alphabet[$i]."</label></td>");
                   7339:     }
1.503     raeburn  7340:     my $nobub_checked = ' ';
                   7341:     if ($error eq 'missingbubble') {
                   7342:         $nobub_checked = ' checked = "checked" ';
                   7343:     }
                   7344:     $r->print("\n".'<td><label><input type="radio" name="scantron_correct_Q_'.
                   7345: 	      $line.'" value="none"'.$nobub_checked.'/>'.&mt('No bubble').
                   7346:               '</label>'."\n".'<input type="hidden" name="scantron_questionnum_Q_'.
                   7347:               $line.'" value="'.$questionnum.'" /></td>');
                   7348:     $r->print(&Apache::loncommon::end_data_table_row().
                   7349:               &Apache::loncommon::end_data_table());
1.157     albertel 7350: }
                   7351: 
1.423     albertel 7352: =pod
                   7353: 
                   7354: =item num_matches
                   7355: 
1.424     albertel 7356:    Counts the number of characters that are the same between the two arguments.
                   7357: 
                   7358:  Arguments:
                   7359:    $orig - CODE from the scanline
                   7360:    $code - CODE to match against
                   7361: 
                   7362:  Returns:
                   7363:    $count - integer count of the number of same characters between the
                   7364:             two arguments
                   7365: 
1.423     albertel 7366: =cut
                   7367: 
1.194     albertel 7368: sub num_matches {
                   7369:     my ($orig,$code) = @_;
                   7370:     my @code=split(//,$code);
                   7371:     my @orig=split(//,$orig);
                   7372:     my $same=0;
                   7373:     for (my $i=0;$i<scalar(@code);$i++) {
                   7374: 	if ($code[$i] eq $orig[$i]) { $same++; }
                   7375:     }
                   7376:     return $same;
                   7377: }
                   7378: 
1.423     albertel 7379: =pod
                   7380: 
                   7381: =item scantron_get_closely_matching_CODEs
                   7382: 
1.424     albertel 7383:    Cycles through all CODEs and finds the set that has the greatest
                   7384:    number of same characters as the provided CODE
                   7385: 
                   7386:  Arguments:
                   7387:    $allcodes - hash ref returned by &get_codes()
                   7388:    $CODE     - CODE from the current scanline
                   7389: 
                   7390:  Returns:
                   7391:    2 element list
                   7392:     - first elements is number of how closely matching the best fit is 
                   7393:       (5 means best set has 5 matching characters)
                   7394:     - second element is an arrary ref containing the set of valid CODEs
                   7395:       that best fit the passed in CODE
                   7396: 
1.423     albertel 7397: =cut
                   7398: 
1.194     albertel 7399: sub scantron_get_closely_matching_CODEs {
                   7400:     my ($allcodes,$CODE)=@_;
                   7401:     my @CODEs;
                   7402:     foreach my $testcode (sort(keys(%{$allcodes}))) {
                   7403: 	push(@{$CODEs[&num_matches($CODE,$testcode)]},$testcode);
                   7404:     }
                   7405: 
                   7406:     return ($#CODEs,$CODEs[-1]);
                   7407: }
                   7408: 
1.423     albertel 7409: =pod
                   7410: 
                   7411: =item get_codes
                   7412: 
1.424     albertel 7413:    Builds a hash which has keys of all of the valid CODEs from the selected
                   7414:    set of remembered CODEs.
                   7415: 
                   7416:  Arguments:
                   7417:   $old_name - name of the set of remembered CODEs
                   7418:   $cdom     - domain of the course
                   7419:   $cnum     - internal course name
                   7420: 
                   7421:  Returns:
                   7422:   %allcodes - keys are the valid CODEs, values are all 1
                   7423: 
1.423     albertel 7424: =cut
                   7425: 
1.194     albertel 7426: sub get_codes {
1.280     foxr     7427:     my ($old_name, $cdom, $cnum) = @_;
                   7428:     if (!$old_name) {
                   7429: 	$old_name=$env{'form.scantron_CODElist'};
                   7430:     }
                   7431:     if (!$cdom) {
                   7432: 	$cdom =$env{'course.'.$env{'request.course.id'}.'.domain'};
                   7433:     }
                   7434:     if (!$cnum) {
                   7435: 	$cnum =$env{'course.'.$env{'request.course.id'}.'.num'};
                   7436:     }
1.278     albertel 7437:     my %result=&Apache::lonnet::get('CODEs',[$old_name,"type\0$old_name"],
                   7438: 				    $cdom,$cnum);
                   7439:     my %allcodes;
                   7440:     if ($result{"type\0$old_name"} eq 'number') {
                   7441: 	%allcodes=map {($_,1)} split(',',$result{$old_name});
                   7442:     } else {
                   7443: 	%allcodes=map {(&Apache::lonprintout::num_to_letters($_),1)} split(',',$result{$old_name});
                   7444:     }
1.194     albertel 7445:     return %allcodes;
                   7446: }
                   7447: 
1.423     albertel 7448: =pod
                   7449: 
                   7450: =item scantron_validate_CODE
                   7451: 
1.424     albertel 7452:    Validates all scanlines in the selected file to not have any
                   7453:    invalid or underspecified CODEs and that none of the codes are
                   7454:    duplicated if this was requested.
                   7455: 
1.423     albertel 7456: =cut
                   7457: 
1.157     albertel 7458: sub scantron_validate_CODE {
                   7459:     my ($r,$currentphase) = @_;
1.257     albertel 7460:     my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
1.186     albertel 7461:     if ($scantron_config{'CODElocation'} &&
                   7462: 	$scantron_config{'CODEstart'} &&
                   7463: 	$scantron_config{'CODElength'}) {
1.257     albertel 7464: 	if (!defined($env{'form.scantron_CODElist'})) {
1.186     albertel 7465: 	    &FIXME_blow_up()
                   7466: 	}
                   7467:     } else {
                   7468: 	return (0,$currentphase+1);
                   7469:     }
                   7470:     
                   7471:     my %usedCODEs;
                   7472: 
1.194     albertel 7473:     my %allcodes=&get_codes();
1.186     albertel 7474: 
1.582     raeburn  7475:     my $nav_error;
                   7476:     &scantron_get_maxbubble(\$nav_error); # parse needs the lines per response array.
                   7477:     if ($nav_error) {
                   7478:         $r->print(&navmap_errormsg());
                   7479:         return(1,$currentphase);
                   7480:     }
1.447     foxr     7481: 
1.186     albertel 7482:     my ($scanlines,$scan_data)=&scantron_getfile();
                   7483:     for (my $i=0;$i<=$scanlines->{'count'};$i++) {
1.200     albertel 7484: 	my $line=&scantron_get_line($scanlines,$scan_data,$i);
1.186     albertel 7485: 	if ($line=~/^[\s\cz]*$/) { next; }
                   7486: 	my $scan_record=&scantron_parse_scanline($line,$i,\%scantron_config,
                   7487: 						 $scan_data);
                   7488: 	my $CODE=$$scan_record{'scantron.CODE'};
                   7489: 	my $error=0;
1.224     albertel 7490: 	if (!&Apache::lonnet::validCODE($CODE)) {
                   7491: 	    &scantron_get_correction($r,$i,$scan_record,
                   7492: 				     \%scantron_config,
                   7493: 				     $line,'incorrectCODE',\%allcodes);
                   7494: 	    return(1,$currentphase);
                   7495: 	}
1.221     albertel 7496: 	if (%allcodes && !exists($allcodes{$CODE}) 
                   7497: 	    && !$$scan_record{'scantron.useCODE'}) {
1.186     albertel 7498: 	    &scantron_get_correction($r,$i,$scan_record,
                   7499: 				     \%scantron_config,
1.194     albertel 7500: 				     $line,'incorrectCODE',\%allcodes);
                   7501: 	    return(1,$currentphase);
1.186     albertel 7502: 	}
1.214     albertel 7503: 	if (exists($usedCODEs{$CODE}) 
1.257     albertel 7504: 	    && $env{'form.scantron_CODEunique'} eq 'yes'
1.192     albertel 7505: 	    && !$$scan_record{'scantron.CODE_ignore_dup'}) {
1.186     albertel 7506: 	    &scantron_get_correction($r,$i,$scan_record,
                   7507: 				     \%scantron_config,
1.194     albertel 7508: 				     $line,'duplicateCODE',$usedCODEs{$CODE});
                   7509: 	    return(1,$currentphase);
1.186     albertel 7510: 	}
1.524     raeburn  7511: 	push(@{$usedCODEs{$CODE}},$$scan_record{'scantron.PaperID'});
1.186     albertel 7512:     }
1.157     albertel 7513:     return (0,$currentphase+1);
                   7514: }
                   7515: 
1.423     albertel 7516: =pod
                   7517: 
                   7518: =item scantron_validate_doublebubble
                   7519: 
1.424     albertel 7520:    Validates all scanlines in the selected file to not have any
                   7521:    bubble lines with multiple bubbles marked.
                   7522: 
1.423     albertel 7523: =cut
                   7524: 
1.157     albertel 7525: sub scantron_validate_doublebubble {
                   7526:     my ($r,$currentphase) = @_;
                   7527:     #get student info
                   7528:     my $classlist=&Apache::loncoursedata::get_classlist();
                   7529:     my %idmap=&username_to_idmap($classlist);
                   7530: 
                   7531:     #get scantron line setup
1.257     albertel 7532:     my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
1.157     albertel 7533:     my ($scanlines,$scan_data)=&scantron_getfile();
1.583     raeburn  7534:     my $nav_error;
                   7535:     &scantron_get_maxbubble(\$nav_error); # parse needs the bubble line array.
                   7536:     if ($nav_error) {
                   7537:         $r->print(&navmap_errormsg());
                   7538:         return(1,$currentphase);
                   7539:     }
1.447     foxr     7540: 
1.157     albertel 7541:     for (my $i=0;$i<=$scanlines->{'count'};$i++) {
1.200     albertel 7542: 	my $line=&scantron_get_line($scanlines,$scan_data,$i);
1.157     albertel 7543: 	if ($line=~/^[\s\cz]*$/) { next; }
                   7544: 	my $scan_record=&scantron_parse_scanline($line,$i,\%scantron_config,
                   7545: 						 $scan_data);
                   7546: 	if (!defined($$scan_record{'scantron.doubleerror'})) { next; }
                   7547: 	&scantron_get_correction($r,$i,$scan_record,\%scantron_config,$line,
                   7548: 				 'doublebubble',
                   7549: 				 $$scan_record{'scantron.doubleerror'});
                   7550:     	return (1,$currentphase);
                   7551:     }
                   7552:     return (0,$currentphase+1);
                   7553: }
                   7554: 
1.423     albertel 7555: 
1.503     raeburn  7556: sub scantron_get_maxbubble {
1.582     raeburn  7557:     my ($nav_error) = @_;
1.257     albertel 7558:     if (defined($env{'form.scantron_maxbubble'}) &&
                   7559: 	$env{'form.scantron_maxbubble'}) {
1.447     foxr     7560: 	&restore_bubble_lines();
1.257     albertel 7561: 	return $env{'form.scantron_maxbubble'};
1.191     albertel 7562:     }
1.330     albertel 7563: 
1.447     foxr     7564:     my (undef, undef, $sequence) =
1.257     albertel 7565: 	&Apache::lonnet::decode_symb($env{'form.selectpage'});
1.330     albertel 7566: 
1.447     foxr     7567:     my $navmap=Apache::lonnavmaps::navmap->new();
1.582     raeburn  7568:     unless (ref($navmap)) {
                   7569:         if (ref($nav_error)) {
                   7570:             $$nav_error = 1;
                   7571:         }
1.591     raeburn  7572:         return;
1.582     raeburn  7573:     }
1.191     albertel 7574:     my $map=$navmap->getResourceByUrl($sequence);
                   7575:     my @resources=$navmap->retrieveResources($map,\&scantron_filter,1,0);
1.330     albertel 7576: 
                   7577:     &Apache::lonxml::clear_problem_counter();
                   7578: 
1.557     raeburn  7579:     my $uname       = $env{'user.name'};
                   7580:     my $udom        = $env{'user.domain'};
1.435     foxr     7581:     my $cid         = $env{'request.course.id'};
                   7582:     my $total_lines = 0;
                   7583:     %bubble_lines_per_response = ();
1.447     foxr     7584:     %first_bubble_line         = ();
1.503     raeburn  7585:     %subdivided_bubble_lines   = ();
                   7586:     %responsetype_per_response = ();
1.554     raeburn  7587: 
1.447     foxr     7588:     my $response_number = 0;
                   7589:     my $bubble_line     = 0;
1.191     albertel 7590:     foreach my $resource (@resources) {
1.542     raeburn  7591:         my ($analysis,$parts) = &scantron_partids_tograde($resource,$cid,$uname,$udom);
                   7592:         if ((ref($analysis) eq 'HASH') && (ref($parts) eq 'ARRAY')) {
                   7593: 	    foreach my $part_id (@{$parts}) {
                   7594:                 my $lines;
                   7595: 
                   7596: 	        # TODO - make this a persistent hash not an array.
                   7597: 
                   7598:                 # optionresponse, matchresponse and rankresponse type items 
                   7599:                 # render as separate sub-questions in exam mode.
                   7600:                 if (($analysis->{$part_id.'.type'} eq 'optionresponse') ||
                   7601:                     ($analysis->{$part_id.'.type'} eq 'matchresponse') ||
                   7602:                     ($analysis->{$part_id.'.type'} eq 'rankresponse')) {
                   7603:                     my ($numbub,$numshown);
                   7604:                     if ($analysis->{$part_id.'.type'} eq 'optionresponse') {
                   7605:                         if (ref($analysis->{$part_id.'.options'}) eq 'ARRAY') {
                   7606:                             $numbub = scalar(@{$analysis->{$part_id.'.options'}});
                   7607:                         }
                   7608:                     } elsif ($analysis->{$part_id.'.type'} eq 'matchresponse') {
                   7609:                         if (ref($analysis->{$part_id.'.items'}) eq 'ARRAY') {
                   7610:                             $numbub = scalar(@{$analysis->{$part_id.'.items'}});
                   7611:                         }
                   7612:                     } elsif ($analysis->{$part_id.'.type'} eq 'rankresponse') {
                   7613:                         if (ref($analysis->{$part_id.'.foils'}) eq 'ARRAY') {
                   7614:                             $numbub = scalar(@{$analysis->{$part_id.'.foils'}});
                   7615:                         }
                   7616:                     }
                   7617:                     if (ref($analysis->{$part_id.'.shown'}) eq 'ARRAY') {
                   7618:                         $numshown = scalar(@{$analysis->{$part_id.'.shown'}});
                   7619:                     }
                   7620:                     my $bubbles_per_line = 10;
                   7621:                     my $inner_bubble_lines = int($numbub/$bubbles_per_line);
                   7622:                     if (($numbub % $bubbles_per_line) != 0) {
                   7623:                         $inner_bubble_lines++;
                   7624:                     }
                   7625:                     for (my $i=0; $i<$numshown; $i++) {
                   7626:                         $subdivided_bubble_lines{$response_number} .= 
                   7627:                             $inner_bubble_lines.',';
                   7628:                     }
                   7629:                     $subdivided_bubble_lines{$response_number} =~ s/,$//;
                   7630:                     $lines = $numshown * $inner_bubble_lines;
                   7631:                 } else {
                   7632:                     $lines = $analysis->{"$part_id.bubble_lines"};
                   7633:                 } 
                   7634: 
                   7635:                 $first_bubble_line{$response_number} = $bubble_line;
                   7636: 	        $bubble_lines_per_response{$response_number} = $lines;
                   7637:                 $responsetype_per_response{$response_number} = 
                   7638:                     $analysis->{$part_id.'.type'};
                   7639: 	        $response_number++;
                   7640: 
                   7641: 	        $bubble_line +=  $lines;
                   7642: 	        $total_lines +=  $lines;
                   7643: 	    }
                   7644:         }
                   7645:     }
1.552     raeburn  7646:     &Apache::lonnet::delenv('scantron.');
1.542     raeburn  7647: 
                   7648:     &save_bubble_lines();
                   7649:     $env{'form.scantron_maxbubble'} =
                   7650: 	$total_lines;
                   7651:     return $env{'form.scantron_maxbubble'};
                   7652: }
1.523     raeburn  7653: 
1.157     albertel 7654: sub scantron_validate_missingbubbles {
                   7655:     my ($r,$currentphase) = @_;
                   7656:     #get student info
                   7657:     my $classlist=&Apache::loncoursedata::get_classlist();
                   7658:     my %idmap=&username_to_idmap($classlist);
                   7659: 
                   7660:     #get scantron line setup
1.257     albertel 7661:     my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
1.157     albertel 7662:     my ($scanlines,$scan_data)=&scantron_getfile();
1.582     raeburn  7663:     my $nav_error;
                   7664:     my $max_bubble=&scantron_get_maxbubble(\$nav_error);
                   7665:     if ($nav_error) {
                   7666:         return(1,$currentphase);
                   7667:     }
1.157     albertel 7668:     if (!$max_bubble) { $max_bubble=2**31; }
                   7669:     for (my $i=0;$i<=$scanlines->{'count'};$i++) {
1.200     albertel 7670: 	my $line=&scantron_get_line($scanlines,$scan_data,$i);
1.157     albertel 7671: 	if ($line=~/^[\s\cz]*$/) { next; }
                   7672: 	my $scan_record=&scantron_parse_scanline($line,$i,\%scantron_config,
                   7673: 						 $scan_data);
                   7674: 	if (!defined($$scan_record{'scantron.missingerror'})) { next; }
                   7675: 	my @to_correct;
1.470     foxr     7676: 	
                   7677: 	# Probably here's where the error is...
                   7678: 
1.157     albertel 7679: 	foreach my $missing (@{$$scan_record{'scantron.missingerror'}}) {
1.505     raeburn  7680:             my $lastbubble;
                   7681:             if ($missing =~ /^(\d+)\.(\d+)$/) {
                   7682:                my $question = $1;
                   7683:                my $subquestion = $2;
                   7684:                if (!defined($first_bubble_line{$question -1})) { next; }
                   7685:                my $first = $first_bubble_line{$question-1};
                   7686:                my @subans = split(/,/,$subdivided_bubble_lines{$question-1});
                   7687:                my $subcount = 1;
                   7688:                while ($subcount<$subquestion) {
                   7689:                    $first += $subans[$subcount-1];
                   7690:                    $subcount ++;
                   7691:                }
                   7692:                my $count = $subans[$subquestion-1];
                   7693:                $lastbubble = $first + $count;
                   7694:             } else {
                   7695:                 if (!defined($first_bubble_line{$missing - 1})) { next; }
                   7696:                 $lastbubble = $first_bubble_line{$missing - 1} + $bubble_lines_per_response{$missing - 1};
                   7697:             }
                   7698:             if ($lastbubble > $max_bubble) { next; }
1.157     albertel 7699: 	    push(@to_correct,$missing);
                   7700: 	}
                   7701: 	if (@to_correct) {
                   7702: 	    &scantron_get_correction($r,$i,$scan_record,\%scantron_config,
                   7703: 				     $line,'missingbubble',\@to_correct);
                   7704: 	    return (1,$currentphase);
                   7705: 	}
                   7706: 
                   7707:     }
                   7708:     return (0,$currentphase+1);
                   7709: }
                   7710: 
1.423     albertel 7711: 
1.82      albertel 7712: sub scantron_process_students {
1.75      albertel 7713:     my ($r) = @_;
1.513     foxr     7714: 
1.257     albertel 7715:     my (undef,undef,$sequence)=&Apache::lonnet::decode_symb($env{'form.selectpage'});
1.324     albertel 7716:     my ($symb)=&get_symb($r);
1.513     foxr     7717:     if (!$symb) {
                   7718: 	return '';
                   7719:     }
1.324     albertel 7720:     my $default_form_data=&defaultFormData($symb);
1.82      albertel 7721: 
1.257     albertel 7722:     my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
1.157     albertel 7723:     my ($scanlines,$scan_data)=&scantron_getfile();
1.82      albertel 7724:     my $classlist=&Apache::loncoursedata::get_classlist();
                   7725:     my %idmap=&username_to_idmap($classlist);
1.132     bowersj2 7726:     my $navmap=Apache::lonnavmaps::navmap->new();
1.582     raeburn  7727:     unless (ref($navmap)) {
                   7728:         $r->print(&navmap_errormsg());
                   7729:         return '';
                   7730:     }  
1.83      albertel 7731:     my $map=$navmap->getResourceByUrl($sequence);
                   7732:     my @resources=$navmap->retrieveResources($map,\&scantron_filter,1,0);
1.557     raeburn  7733:     my (%grader_partids_by_symb,%grader_randomlists_by_symb);
                   7734:     &graders_resources_pass(\@resources,\%grader_partids_by_symb,
                   7735:                             \%grader_randomlists_by_symb);
1.586     raeburn  7736:     my $resource_error;
1.557     raeburn  7737:     foreach my $resource (@resources) {
1.586     raeburn  7738:         my $ressymb;
                   7739:         if (ref($resource)) {
                   7740:             $ressymb = $resource->symb();
                   7741:         } else {
                   7742:             $resource_error = 1;
                   7743:             last;
                   7744:         }
1.557     raeburn  7745:         my ($analysis,$parts) =
                   7746:             &scantron_partids_tograde($resource,$env{'request.course.id'},
                   7747:                                       $env{'user.name'},$env{'user.domain'},1);
                   7748:         $grader_partids_by_symb{$ressymb} = $parts;
                   7749:         if (ref($analysis) eq 'HASH') {
                   7750:             if (ref($analysis->{'parts_withrandomlist'}) eq 'ARRAY') {
                   7751:                 $grader_randomlists_by_symb{$ressymb} = 
                   7752:                     $analysis->{'parts_withrandomlist'};
                   7753:             }
                   7754:         }
                   7755:     }
1.586     raeburn  7756:     if ($resource_error) {
                   7757:         $r->print(&navmap_errormsg());
                   7758:         return '';
                   7759:     }
1.557     raeburn  7760: 
1.554     raeburn  7761:     my ($uname,$udom);
1.82      albertel 7762:     my $result= <<SCANTRONFORM;
1.81      albertel 7763: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="scantronupload">
                   7764:   <input type="hidden" name="command" value="scantron_configphase" />
                   7765:   $default_form_data
                   7766: SCANTRONFORM
1.82      albertel 7767:     $r->print($result);
                   7768: 
                   7769:     my @delayqueue;
1.542     raeburn  7770:     my (%completedstudents,%scandata);
1.140     albertel 7771:     
1.520     www      7772:     my $lock=&Apache::lonnet::set_lock(&mt('Grading bubblesheet exam'));
1.200     albertel 7773:     my $count=&get_todo_count($scanlines,$scan_data);
1.575     www      7774:     my %prog_state=&Apache::lonhtmlcommon::Create_PrgWin($r,'Bubblesheet Status',
                   7775:  				    'Bubblesheet Progress',$count,
1.195     albertel 7776: 				    'inline',undef,'scantronupload');
1.140     albertel 7777:     &Apache::lonhtmlcommon::Update_PrgWin($r,\%prog_state,
                   7778: 					  'Processing first student');
1.542     raeburn  7779:     $r->print('<br />');
1.140     albertel 7780:     my $start=&Time::HiRes::time();
1.158     albertel 7781:     my $i=-1;
1.542     raeburn  7782:     my $started;
1.447     foxr     7783: 
1.582     raeburn  7784:     my $nav_error;
                   7785:     &scantron_get_maxbubble(\$nav_error); # Need the bubble lines array to parse.
                   7786:     if ($nav_error) {
                   7787:         $r->print(&navmap_errormsg());
                   7788:         return '';
                   7789:     }
                   7790: 
1.513     foxr     7791:     # If an ssi failed in scantron_get_maxbubble, put an error message out to
                   7792:     # the user and return.
                   7793: 
                   7794:     if ($ssi_error) {
                   7795: 	$r->print("</form>");
                   7796: 	&ssi_print_error($r);
                   7797: 	$r->print(&show_grading_menu_form($symb));
1.520     www      7798:         &Apache::lonnet::remove_lock($lock);
1.513     foxr     7799: 	return '';		# Dunno why the other returns return '' rather than just returning.
                   7800:     }
1.447     foxr     7801: 
1.542     raeburn  7802:     my %lettdig = &letter_to_digits();
                   7803:     my $numletts = scalar(keys(%lettdig));
                   7804: 
1.157     albertel 7805:     while ($i<$scanlines->{'count'}) {
                   7806:  	($uname,$udom)=('','');
                   7807:  	$i++;
1.200     albertel 7808:  	my $line=&scantron_get_line($scanlines,$scan_data,$i);
1.157     albertel 7809:  	if ($line=~/^[\s\cz]*$/) { next; }
1.200     albertel 7810: 	if ($started) {
                   7811: 	    &Apache::lonhtmlcommon::Increment_PrgWin($r,\%prog_state,
                   7812: 						     'last student');
                   7813: 	}
                   7814: 	$started=1;
1.157     albertel 7815:  	my $scan_record=&scantron_parse_scanline($line,$i,\%scantron_config,
                   7816:  						 $scan_data);
                   7817:  	unless ($uname=&scantron_find_student($scan_record,$scan_data,
                   7818:  					      \%idmap,$i)) {
                   7819:   	    &scantron_add_delay(\@delayqueue,$line,
                   7820:  				'Unable to find a student that matches',1);
                   7821:  	    next;
                   7822:   	}
                   7823:  	if (exists $completedstudents{$uname}) {
                   7824:  	    &scantron_add_delay(\@delayqueue,$line,
                   7825:  				'Student '.$uname.' has multiple sheets',2);
                   7826:  	    next;
                   7827:  	}
                   7828:   	($uname,$udom)=split(/:/,$uname);
1.330     albertel 7829: 
1.586     raeburn  7830:         my (%partids_by_symb,$res_error);
1.554     raeburn  7831:         foreach my $resource (@resources) {
1.586     raeburn  7832:             my $ressymb;
                   7833:             if (ref($resource)) {
                   7834:                 $ressymb = $resource->symb();
                   7835:             } else {
                   7836:                 $res_error = 1;
                   7837:                 last;
                   7838:             }
1.557     raeburn  7839:             if ((exists($grader_randomlists_by_symb{$ressymb})) ||
                   7840:                 (ref($grader_partids_by_symb{$ressymb}) ne 'ARRAY')) {
                   7841:                 my ($analysis,$parts) =
                   7842:                     &scantron_partids_tograde($resource,$env{'request.course.id'},$uname,$udom);
                   7843:                 $partids_by_symb{$ressymb} = $parts;
                   7844:             } else {
                   7845:                 $partids_by_symb{$ressymb} = $grader_partids_by_symb{$ressymb};
                   7846:             }
1.554     raeburn  7847:         }
                   7848: 
1.586     raeburn  7849:         if ($res_error) {
                   7850:             &scantron_add_delay(\@delayqueue,$line,
                   7851:                                 'An error occurred while grading student '.$uname,2);
                   7852:             next;
                   7853:         }
                   7854: 
1.330     albertel 7855: 	&Apache::lonxml::clear_problem_counter();
1.514     raeburn  7856:   	&Apache::lonnet::appenv($scan_record);
1.376     albertel 7857: 
                   7858: 	if (&scantron_clear_skip($scanlines,$scan_data,$i)) {
                   7859: 	    &scantron_putfile($scanlines,$scan_data);
                   7860: 	}
1.161     albertel 7861: 	
1.542     raeburn  7862:         my $scancode;
                   7863:         if ((exists($scan_record->{'scantron.CODE'})) &&
                   7864:             (&Apache::lonnet::validCODE($scan_record->{'scantron.CODE'}))) {
                   7865:             $scancode = $scan_record->{'scantron.CODE'};
                   7866:         } else {
                   7867:             $scancode = '';
                   7868:         }
                   7869: 
                   7870:         if (&grade_student_bubbles($r,$uname,$udom,$scan_record,$scancode,
1.554     raeburn  7871:                                    \@resources,\%partids_by_symb) eq 'ssi_error') {
1.542     raeburn  7872:             $ssi_error = 0; # So end of handler error message does not trigger.
                   7873:             $r->print("</form>");
                   7874:             &ssi_print_error($r);
                   7875:             $r->print(&show_grading_menu_form($symb));
                   7876:             &Apache::lonnet::remove_lock($lock);
                   7877:             return '';      # Why return ''?  Beats me.
                   7878:         }
1.513     foxr     7879: 
1.140     albertel 7880: 	$completedstudents{$uname}={'line'=>$line};
1.542     raeburn  7881:         if ($env{'form.verifyrecord'}) {
                   7882:             my $lastpos = $env{'form.scantron_maxbubble'}*$scantron_config{'Qlength'};
                   7883:             my $studentdata = substr($line,$scantron_config{'Qstart'}-1,$lastpos);
                   7884:             chomp($studentdata);
                   7885:             $studentdata =~ s/\r$//;
                   7886:             my $studentrecord = '';
                   7887:             my $counter = -1;
                   7888:             foreach my $resource (@resources) {
1.554     raeburn  7889:                 my $ressymb = $resource->symb();
1.542     raeburn  7890:                 ($counter,my $recording) =
                   7891:                     &verify_scantron_grading($resource,$udom,$uname,$env{'request.course.id'},
1.554     raeburn  7892:                                              $counter,$studentdata,$partids_by_symb{$ressymb},
1.542     raeburn  7893:                                              \%scantron_config,\%lettdig,$numletts);
                   7894:                 $studentrecord .= $recording;
                   7895:             }
                   7896:             if ($studentrecord ne $studentdata) {
1.554     raeburn  7897:                 &Apache::lonxml::clear_problem_counter();
                   7898:                 if (&grade_student_bubbles($r,$uname,$udom,$scan_record,$scancode,
                   7899:                                            \@resources,\%partids_by_symb) eq 'ssi_error') {
                   7900:                     $ssi_error = 0; # So end of handler error message does not trigger.
                   7901:                     $r->print("</form>");
                   7902:                     &ssi_print_error($r);
                   7903:                     $r->print(&show_grading_menu_form($symb));
                   7904:                     &Apache::lonnet::remove_lock($lock);
                   7905:                     delete($completedstudents{$uname});
                   7906:                     return '';
                   7907:                 }
1.542     raeburn  7908:                 $counter = -1;
                   7909:                 $studentrecord = '';
                   7910:                 foreach my $resource (@resources) {
1.554     raeburn  7911:                     my $ressymb = $resource->symb();
1.542     raeburn  7912:                     ($counter,my $recording) =
                   7913:                         &verify_scantron_grading($resource,$udom,$uname,$env{'request.course.id'},
1.554     raeburn  7914:                                                  $counter,$studentdata,$partids_by_symb{$ressymb},
1.542     raeburn  7915:                                                  \%scantron_config,\%lettdig,$numletts);
                   7916:                     $studentrecord .= $recording;
                   7917:                 }
                   7918:                 if ($studentrecord ne $studentdata) {
                   7919:                     $r->print('<p><span class="LC_error">');
                   7920:                     if ($scancode eq '') {
                   7921:                         $r->print(&mt('Mismatch grading bubble sheet for user: [_1] with ID: [_2].',
                   7922:                                   $uname.':'.$udom,$scan_record->{'scantron.ID'}));
                   7923:                     } else {
                   7924:                         $r->print(&mt('Mismatch grading bubble sheet for user: [_1] with ID: [_2] and CODE: [_3].',
                   7925:                                   $uname.':'.$udom,$scan_record->{'scantron.ID'},$scancode));
                   7926:                     }
                   7927:                     $r->print('</span><br />'.&Apache::loncommon::start_data_table()."\n".
                   7928:                               &Apache::loncommon::start_data_table_header_row()."\n".
                   7929:                               '<th>'.&mt('Source').'</th><th>'.&mt('Bubbled responses').'</th>'.
                   7930:                               &Apache::loncommon::end_data_table_header_row()."\n".
                   7931:                               &Apache::loncommon::start_data_table_row().
                   7932:                               '<td>'.&mt('Bubble Sheet').'</td>'.
                   7933:                               '<td><span class="LC_nobreak">'.$studentdata.'</span></td>'.
                   7934:                               &Apache::loncommon::end_data_table_row().
                   7935:                               &Apache::loncommon::start_data_table_row().
                   7936:                               '<td>Stored submissions</td>'.
                   7937:                               '<td><span class="LC_nobreak">'.$studentrecord.'</span></td>'."\n".
                   7938:                               &Apache::loncommon::end_data_table_row().
                   7939:                               &Apache::loncommon::end_data_table().'</p>');
                   7940:                 } else {
                   7941:                     $r->print('<br /><span class="LC_warning">'.
                   7942:                              &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 />'.
                   7943:                              &mt("As a consequence, this user's submission history records two tries.").
                   7944:                                  '</span><br />');
                   7945:                 }
                   7946:             }
                   7947:         }
1.543     raeburn  7948:         if (&Apache::loncommon::connection_aborted($r)) { last; }
1.140     albertel 7949:     } continue {
1.330     albertel 7950: 	&Apache::lonxml::clear_problem_counter();
1.552     raeburn  7951: 	&Apache::lonnet::delenv('scantron.');
1.82      albertel 7952:     }
1.140     albertel 7953:     &Apache::lonhtmlcommon::Close_PrgWin($r,\%prog_state);
1.520     www      7954:     &Apache::lonnet::remove_lock($lock);
1.172     albertel 7955: #    my $lasttime = &Time::HiRes::time()-$start;
                   7956: #    $r->print("<p>took $lasttime</p>");
1.140     albertel 7957: 
1.200     albertel 7958:     $r->print("</form>");
1.324     albertel 7959:     $r->print(&show_grading_menu_form($symb));
1.157     albertel 7960:     return '';
1.75      albertel 7961: }
1.157     albertel 7962: 
1.557     raeburn  7963: sub graders_resources_pass {
                   7964:     my ($resources,$grader_partids_by_symb,$grader_randomlists_by_symb) = @_;
                   7965:     if ((ref($resources) eq 'ARRAY') && (ref($grader_partids_by_symb)) && 
                   7966:         (ref($grader_randomlists_by_symb) eq 'HASH')) {
                   7967:         foreach my $resource (@{$resources}) {
                   7968:             my $ressymb = $resource->symb();
                   7969:             my ($analysis,$parts) =
                   7970:                 &scantron_partids_tograde($resource,$env{'request.course.id'},
                   7971:                                           $env{'user.name'},$env{'user.domain'},1);
                   7972:             $grader_partids_by_symb->{$ressymb} = $parts;
                   7973:             if (ref($analysis) eq 'HASH') {
                   7974:                 if (ref($analysis->{'parts_withrandomlist'}) eq 'ARRAY') {
                   7975:                     $grader_randomlists_by_symb->{$ressymb} =
                   7976:                         $analysis->{'parts_withrandomlist'};
                   7977:                 }
                   7978:             }
                   7979:         }
                   7980:     }
                   7981:     return;
                   7982: }
                   7983: 
1.542     raeburn  7984: sub grade_student_bubbles {
1.554     raeburn  7985:     my ($r,$uname,$udom,$scan_record,$scancode,$resources,$parts) = @_;
                   7986:     if (ref($resources) eq 'ARRAY') {
                   7987:         my $count = 0;
                   7988:         foreach my $resource (@{$resources}) {
                   7989:             my $ressymb = $resource->symb();
                   7990:             my %form = ('submitted'      => 'scantron',
                   7991:                         'grade_target'   => 'grade',
                   7992:                         'grade_username' => $uname,
                   7993:                         'grade_domain'   => $udom,
                   7994:                         'grade_courseid' => $env{'request.course.id'},
                   7995:                         'grade_symb'     => $ressymb,
                   7996:                         'CODE'           => $scancode
                   7997:                        );
                   7998:             if (ref($parts) eq 'HASH') {
                   7999:                 if (ref($parts->{$ressymb}) eq 'ARRAY') {
                   8000:                     foreach my $part (@{$parts->{$ressymb}}) {
                   8001:                         $form{'scantron_questnum_start.'.$part} =
                   8002:                             1+$env{'form.scantron.first_bubble_line.'.$count};
                   8003:                         $count++;
                   8004:                     }
                   8005:                 }
                   8006:             }
                   8007:             my $result=&ssi_with_retries($resource->src(),$ssi_retries,%form);
                   8008:             return 'ssi_error' if ($ssi_error);
                   8009:             last if (&Apache::loncommon::connection_aborted($r));
                   8010:         }
1.542     raeburn  8011:     }
                   8012:     return;
                   8013: }
                   8014: 
1.157     albertel 8015: sub scantron_upload_scantron_data {
                   8016:     my ($r)=@_;
1.565     raeburn  8017:     my $dom = $env{'request.role.domain'};
                   8018:     my $domdesc = &Apache::lonnet::domain($dom,'description');
                   8019:     $r->print(&Apache::loncommon::coursebrowser_javascript($dom));
1.157     albertel 8020:     my $select_link=&Apache::loncommon::selectcourse_link('rules','courseid',
1.181     albertel 8021: 							  'domainid',
1.565     raeburn  8022: 							  'coursename',$dom);
                   8023:     my $syllabuslink = '<a href="javascript:ToSyllabus();">'.&mt('Syllabus').'</a>'.
                   8024:                        ('&nbsp'x2).&mt('(shows course personnel)'); 
1.324     albertel 8025:     my $default_form_data=&defaultFormData(&get_symb($r,1));
1.579     raeburn  8026:     my $nofile_alert = &mt('Please use the browse button to select a file from your local directory.');
                   8027:     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 8028:     $r->print('
1.157     albertel 8029: <script type="text/javascript" language="javascript">
                   8030:     function checkUpload(formname) {
                   8031: 	if (formname.upfile.value == "") {
1.579     raeburn  8032: 	    alert("'.$nofile_alert.'");
1.157     albertel 8033: 	    return false;
                   8034: 	}
1.565     raeburn  8035:         if (formname.courseid.value == "") {
1.579     raeburn  8036:             alert("'.$nocourseid_alert.'");
1.565     raeburn  8037:             return false;
                   8038:         }
1.157     albertel 8039: 	formname.submit();
                   8040:     }
1.565     raeburn  8041: 
                   8042:     function ToSyllabus() {
                   8043:         var cdom = '."'$dom'".';
                   8044:         var cnum = document.rules.courseid.value;
                   8045:         if (cdom == "" || cdom == null) {
                   8046:             return;
                   8047:         }
                   8048:         if (cnum == "" || cnum == null) {
                   8049:            return;
                   8050:         }
                   8051:         syllwin=window.open("/public/"+cdom+"/"+cnum+"/syllabus","LONCAPASyllabus",
                   8052:                             "height=350,width=350,scrollbars=yes,menubar=no");
                   8053:         return;
                   8054:     }
                   8055: 
1.157     albertel 8056: </script>
                   8057: 
1.566     raeburn  8058: <h3>'.&mt('Send scanned bubblesheet data to a course').'</h3>
                   8059: 
1.492     albertel 8060: <form enctype="multipart/form-data" action="/adm/grades" name="rules" method="post">
1.565     raeburn  8061: '.$default_form_data.
                   8062:   &Apache::lonhtmlcommon::start_pick_box().
                   8063:   &Apache::lonhtmlcommon::row_title(&mt('Course ID')).
                   8064:   '<input name="courseid" type="text" size="30" />'.$select_link.
                   8065:   &Apache::lonhtmlcommon::row_closure().
                   8066:   &Apache::lonhtmlcommon::row_title(&mt('Course Name')).
                   8067:   '<input name="coursename" type="text" size="30" />'.$syllabuslink.
                   8068:   &Apache::lonhtmlcommon::row_closure().
                   8069:   &Apache::lonhtmlcommon::row_title(&mt('Domain')).
                   8070:   '<input name="domainid" type="hidden" />'.$domdesc.
                   8071:   &Apache::lonhtmlcommon::row_closure().
                   8072:   &Apache::lonhtmlcommon::row_title(&mt('File to upload')).
                   8073:   '<input type="file" name="upfile" size="50" />'.
                   8074:   &Apache::lonhtmlcommon::row_closure(1).
                   8075:   &Apache::lonhtmlcommon::end_pick_box().'<br />
                   8076: 
1.492     albertel 8077: <input name="command" value="scantronupload_save" type="hidden" />
1.589     bisitz   8078: <input type="button" onclick="javascript:checkUpload(this.form);" value="'.&mt('Upload Bubblesheet Data').'" />
1.157     albertel 8079: </form>
1.492     albertel 8080: ');
1.157     albertel 8081:     return '';
                   8082: }
                   8083: 
1.423     albertel 8084: 
1.157     albertel 8085: sub scantron_upload_scantron_data_save {
                   8086:     my($r)=@_;
1.324     albertel 8087:     my ($symb)=&get_symb($r,1);
1.182     albertel 8088:     my $doanotherupload=
                   8089: 	'<br /><form action="/adm/grades" method="post">'."\n".
                   8090: 	'<input type="hidden" name="command" value="scantronupload" />'."\n".
1.492     albertel 8091: 	'<input type="submit" name="submit" value="'.&mt('Do Another Upload').'" />'."\n".
1.182     albertel 8092: 	'</form>'."\n";
1.257     albertel 8093:     if (!&Apache::lonnet::allowed('usc',$env{'form.domainid'}) &&
1.162     albertel 8094: 	!&Apache::lonnet::allowed('usc',
1.257     albertel 8095: 			    $env{'form.domainid'}.'_'.$env{'form.courseid'})) {
1.575     www      8096: 	$r->print(&mt("You are not allowed to upload bubblesheet data to the requested course.")."<br />");
1.182     albertel 8097: 	if ($symb) {
1.324     albertel 8098: 	    $r->print(&show_grading_menu_form($symb));
1.182     albertel 8099: 	} else {
                   8100: 	    $r->print($doanotherupload);
                   8101: 	}
1.162     albertel 8102: 	return '';
                   8103:     }
1.257     albertel 8104:     my %coursedata=&Apache::lonnet::coursedescription($env{'form.domainid'}.'_'.$env{'form.courseid'});
1.568     raeburn  8105:     my $uploadedfile;
1.567     raeburn  8106:     $r->print('<h3>'.&mt("Uploading file to [_1]",$coursedata{'description'}).'</h3>');
1.257     albertel 8107:     if (length($env{'form.upfile'}) < 2) {
1.568     raeburn  8108:         $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 8109:     } else {
1.568     raeburn  8110:         my $result = 
                   8111:             &Apache::lonnet::userfileupload('upfile','','scantron','','','',
                   8112:                                             $env{'form.courseid'},$env{'form.domainid'});
                   8113: 	if ($result =~ m{^/uploaded/}) {
1.567     raeburn  8114: 	    $r->print(&mt('[_1]Success:[_2] Successfully uploaded [_3] bytes of data into location: [_4]',
                   8115:                           '<span class="LC_success">','</span>',(length($env{'form.upfile'})-1),
                   8116: 			  '<span class="LC_filename">'.$result.'</span>'));
1.568     raeburn  8117:             ($uploadedfile) = ($result =~ m{/([^/]+)$});
1.567     raeburn  8118:             $r->print(&validate_uploaded_scantron_file($env{'form.domainid'},
1.568     raeburn  8119:                                                        $env{'form.courseid'},$uploadedfile));
1.210     albertel 8120: 	} else {
1.567     raeburn  8121: 	    $r->print(&mt('[_1]Error:[_2] An error ([_3]) occurred when attempting to upload the file, [_4]',
                   8122:                           '<span class="LC_error">','</span>',$result,
1.568     raeburn  8123: 			  '<span class="LC_filename">'.&HTML::Entities::encode($env{'form.upfile.filename'},'<>&"').'</span>'));
1.183     albertel 8124: 	}
                   8125:     }
1.174     albertel 8126:     if ($symb) {
1.209     ng       8127: 	$r->print(&scantron_selectphase($r,$uploadedfile));
1.174     albertel 8128:     } else {
1.182     albertel 8129: 	$r->print($doanotherupload);
1.174     albertel 8130:     }
1.157     albertel 8131:     return '';
                   8132: }
                   8133: 
1.567     raeburn  8134: sub validate_uploaded_scantron_file {
                   8135:     my ($cdom,$cname,$fname) = @_;
                   8136:     my $scanlines=&Apache::lonnet::getfile('/uploaded/'.$cdom.'/'.$cname.'/'.$fname);
                   8137:     my @lines;
                   8138:     if ($scanlines ne '-1') {
                   8139:         @lines=split("\n",$scanlines,-1);
                   8140:     }
                   8141:     my $output;
                   8142:     if (@lines) {
                   8143:         my (%counts,$max_match_format);
                   8144:         my ($max_match_count,$max_match_pct) = (0,0);
                   8145:         my $classlist = &Apache::loncoursedata::get_classlist($cdom,$cname);
                   8146:         my %idmap = &username_to_idmap($classlist);
                   8147:         foreach my $key (keys(%idmap)) {
                   8148:             my $lckey = lc($key);
                   8149:             $idmap{$lckey} = $idmap{$key};
                   8150:         }
                   8151:         my %unique_formats;
                   8152:         my @formatlines = &get_scantronformat_file();
                   8153:         foreach my $line (@formatlines) {
                   8154:             chomp($line);
                   8155:             my @config = split(/:/,$line);
                   8156:             my $idstart = $config[5];
                   8157:             my $idlength = $config[6];
                   8158:             if (($idstart ne '') && ($idlength > 0)) {
                   8159:                 if (ref($unique_formats{$idstart.':'.$idlength}) eq 'ARRAY') {
                   8160:                     push(@{$unique_formats{$idstart.':'.$idlength}},$config[0].':'.$config[1]); 
                   8161:                 } else {
                   8162:                     $unique_formats{$idstart.':'.$idlength} = [$config[0].':'.$config[1]];
                   8163:                 }
                   8164:             }
                   8165:         }
                   8166:         foreach my $key (keys(%unique_formats)) {
                   8167:             my ($idstart,$idlength) = split(':',$key);
                   8168:             %{$counts{$key}} = (
                   8169:                                'found'   => 0,
                   8170:                                'total'   => 0,
                   8171:                               );
                   8172:             foreach my $line (@lines) {
                   8173:                 next if ($line =~ /^#/);
                   8174:                 next if ($line =~ /^[\s\cz]*$/);
                   8175:                 my $id = substr($line,$idstart-1,$idlength);
                   8176:                 $id = lc($id);
                   8177:                 if (exists($idmap{$id})) {
                   8178:                     $counts{$key}{'found'} ++;
                   8179:                 }
                   8180:                 $counts{$key}{'total'} ++;
                   8181:             }
                   8182:             if ($counts{$key}{'total'}) {
                   8183:                 my $percent_match = (100*$counts{$key}{'found'})/($counts{$key}{'total'});
                   8184:                 if (($max_match_format eq '') || ($percent_match > $max_match_pct)) {
                   8185:                     $max_match_pct = $percent_match;
                   8186:                     $max_match_format = $key;
                   8187:                     $max_match_count = $counts{$key}{'total'};
                   8188:                 }
                   8189:             }
                   8190:         }
                   8191:         if (ref($unique_formats{$max_match_format}) eq 'ARRAY') {
                   8192:             my $format_descs;
                   8193:             my $numwithformat = @{$unique_formats{$max_match_format}};
                   8194:             for (my $i=0; $i<$numwithformat; $i++) {
                   8195:                 my ($name,$desc) = split(':',$unique_formats{$max_match_format}[$i]);
                   8196:                 if ($i<$numwithformat-2) {
                   8197:                     $format_descs .= '"<i>'.$desc.'</i>", ';
                   8198:                 } elsif ($i==$numwithformat-2) {
                   8199:                     $format_descs .= '"<i>'.$desc.'</i>" '.&mt('and').' ';
                   8200:                 } elsif ($i==$numwithformat-1) {
                   8201:                     $format_descs .= '"<i>'.$desc.'</i>"';
                   8202:                 }
                   8203:             }
                   8204:             my $showpct = sprintf("%.0f",$max_match_pct).'%';
                   8205:             $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).
                   8206:                        '<br />'.&mt('A low percentage of matches results from one of the following:').'<ul>'.
                   8207:                        '<li>'.&mt('The file was uploaded to the wrong course').'</li>'.
                   8208:                        '<li>'.&mt('The data are not in the format expected for the domain: [_1]',
                   8209:                                   '<i>'.$cdom.'</i>').'</li>'.
                   8210:                        '<li>'.&mt('Students did not bubble their IDs, or mis-bubbled them').'</li>'.
                   8211:                        '<li>'.&mt('The course roster is not up to date').'</li>'.
                   8212:                        '</ul>';
                   8213:         }
                   8214:     } else {
                   8215:         $output = '<span class="LC_warning">'.&mt('Uploaded file contained no data').'</span>';
                   8216:     }
                   8217:     return $output;
                   8218: }
                   8219: 
1.202     albertel 8220: sub valid_file {
                   8221:     my ($requested_file)=@_;
                   8222:     foreach my $filename (sort(&scantron_filenames())) {
                   8223: 	if ($requested_file eq $filename) { return 1; }
                   8224:     }
                   8225:     return 0;
                   8226: }
                   8227: 
                   8228: sub scantron_download_scantron_data {
                   8229:     my ($r)=@_;
1.324     albertel 8230:     my $default_form_data=&defaultFormData(&get_symb($r,1));
1.257     albertel 8231:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   8232:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
                   8233:     my $file=$env{'form.scantron_selectfile'};
1.202     albertel 8234:     if (! &valid_file($file)) {
1.492     albertel 8235: 	$r->print('
1.202     albertel 8236: 	<p>
1.492     albertel 8237: 	    '.&mt('The requested file name was invalid.').'
1.202     albertel 8238:         </p>
1.492     albertel 8239: ');
1.324     albertel 8240: 	$r->print(&show_grading_menu_form(&get_symb($r,1)));
1.202     albertel 8241: 	return;
                   8242:     }
                   8243:     my $orig='/uploaded/'.$cdom.'/'.$cname.'/scantron_orig_'.$file;
                   8244:     my $corrected='/uploaded/'.$cdom.'/'.$cname.'/scantron_corrected_'.$file;
                   8245:     my $skipped='/uploaded/'.$cdom.'/'.$cname.'/scantron_skipped_'.$file;
                   8246:     &Apache::lonnet::allowuploaded('/adm/grades',$orig);
                   8247:     &Apache::lonnet::allowuploaded('/adm/grades',$corrected);
                   8248:     &Apache::lonnet::allowuploaded('/adm/grades',$skipped);
1.492     albertel 8249:     $r->print('
1.202     albertel 8250:     <p>
1.492     albertel 8251: 	'.&mt('[_1]Original[_2] file as uploaded by the scantron office.',
                   8252: 	      '<a href="'.$orig.'">','</a>').'
1.202     albertel 8253:     </p>
                   8254:     <p>
1.492     albertel 8255: 	'.&mt('[_1]Corrections[_2], a file of corrected records that were used in grading.',
                   8256: 	      '<a href="'.$corrected.'">','</a>').'
1.202     albertel 8257:     </p>
                   8258:     <p>
1.492     albertel 8259: 	'.&mt('[_1]Skipped[_2], a file of records that were skipped.',
                   8260: 	      '<a href="'.$skipped.'">','</a>').'
1.202     albertel 8261:     </p>
1.492     albertel 8262: ');
1.324     albertel 8263:     $r->print(&show_grading_menu_form(&get_symb($r,1)));
1.202     albertel 8264:     return '';
                   8265: }
1.157     albertel 8266: 
1.523     raeburn  8267: sub checkscantron_results {
                   8268:     my ($r) = @_;
                   8269:     my ($symb)=&get_symb($r);
                   8270:     if (!$symb) {return '';}
                   8271:     my $grading_menu_button=&show_grading_menu_form($symb);
                   8272:     my $cid = $env{'request.course.id'};
1.542     raeburn  8273:     my %lettdig = &letter_to_digits();
1.523     raeburn  8274:     my $numletts = scalar(keys(%lettdig));
                   8275:     my $cnum = $env{'course.'.$cid.'.num'};
                   8276:     my $cdom = $env{'course.'.$cid.'.domain'};
                   8277:     my (undef, undef, $sequence) = &Apache::lonnet::decode_symb($env{'form.selectpage'});
                   8278:     my %record;
                   8279:     my %scantron_config =
                   8280:         &Apache::grades::get_scantron_config($env{'form.scantron_format'});
                   8281:     my ($scanlines,$scan_data)=&Apache::grades::scantron_getfile();
                   8282:     my $classlist=&Apache::loncoursedata::get_classlist();
                   8283:     my %idmap=&Apache::grades::username_to_idmap($classlist);
                   8284:     my $navmap=Apache::lonnavmaps::navmap->new();
1.582     raeburn  8285:     unless (ref($navmap)) {
                   8286:         $r->print(&navmap_errormsg());
                   8287:         return '';
                   8288:     }
1.523     raeburn  8289:     my $map=$navmap->getResourceByUrl($sequence);
1.557     raeburn  8290:     my @resources=$navmap->retrieveResources($map,\&scantron_filter,1,0);
                   8291:     my (%grader_partids_by_symb,%grader_randomlists_by_symb);
                   8292:     &graders_resources_pass(\@resources,\%grader_partids_by_symb,                             \%grader_randomlists_by_symb);
                   8293: 
1.554     raeburn  8294:     my ($uname,$udom);
1.523     raeburn  8295:     my (%scandata,%lastname,%bylast);
                   8296:     $r->print('
                   8297: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="checkscantron">'."\n");
                   8298: 
                   8299:     my @delayqueue;
                   8300:     my %completedstudents;
                   8301: 
                   8302:     my $count=&Apache::grades::get_todo_count($scanlines,$scan_data);
1.581     www      8303:     my %prog_state=&Apache::lonhtmlcommon::Create_PrgWin($r,'Bubblesheet/Submissions Comparison Status',
                   8304:                                     'Progress of Bubblesheet Data/Submission Records Comparison',$count,
1.523     raeburn  8305:                                     'inline',undef,'checkscantron');
1.546     raeburn  8306:     my ($username,$domain,$started);
1.582     raeburn  8307:     my $nav_error;
                   8308:     &scantron_get_maxbubble(\$nav_error); # Need the bubble lines array to parse.
                   8309:     if ($nav_error) {
                   8310:         $r->print(&navmap_errormsg());
                   8311:         return '';
                   8312:     }
1.523     raeburn  8313: 
                   8314:     &Apache::lonhtmlcommon::Update_PrgWin($r,\%prog_state,
                   8315:                                           'Processing first student');
                   8316:     my $start=&Time::HiRes::time();
                   8317:     my $i=-1;
                   8318: 
                   8319:     while ($i<$scanlines->{'count'}) {
                   8320:         ($username,$domain,$uname)=('','','');
                   8321:         $i++;
                   8322:         my $line=&Apache::grades::scantron_get_line($scanlines,$scan_data,$i);
                   8323:         if ($line=~/^[\s\cz]*$/) { next; }
                   8324:         if ($started) {
                   8325:             &Apache::lonhtmlcommon::Increment_PrgWin($r,\%prog_state,
                   8326:                                                      'last student');
                   8327:         }
                   8328:         $started=1;
                   8329:         my $scan_record=
                   8330:             &Apache::grades::scantron_parse_scanline($line,$i,\%scantron_config,
                   8331:                                                      $scan_data);
                   8332:         unless ($uname=&Apache::grades::scantron_find_student($scan_record,$scan_data,
                   8333:                                                               \%idmap,$i)) {
                   8334:             &Apache::grades::scantron_add_delay(\@delayqueue,$line,
                   8335:                                 'Unable to find a student that matches',1);
                   8336:             next;
                   8337:         }
                   8338:         if (exists $completedstudents{$uname}) {
                   8339:             &Apache::grades::scantron_add_delay(\@delayqueue,$line,
                   8340:                                 'Student '.$uname.' has multiple sheets',2);
                   8341:             next;
                   8342:         }
                   8343:         my $pid = $scan_record->{'scantron.ID'};
                   8344:         $lastname{$pid} = $scan_record->{'scantron.LastName'};
                   8345:         push(@{$bylast{$lastname{$pid}}},$pid);
                   8346:         my $lastpos = $env{'form.scantron_maxbubble'}*$scantron_config{'Qlength'};
                   8347:         $scandata{$pid} = substr($line,$scantron_config{'Qstart'}-1,$lastpos);
                   8348:         chomp($scandata{$pid});
                   8349:         $scandata{$pid} =~ s/\r$//;
                   8350:         ($username,$domain)=split(/:/,$uname);
                   8351:         my $counter = -1;
                   8352:         foreach my $resource (@resources) {
1.557     raeburn  8353:             my $parts;
1.554     raeburn  8354:             my $ressymb = $resource->symb();
1.557     raeburn  8355:             if ((exists($grader_randomlists_by_symb{$ressymb})) ||
                   8356:                 (ref($grader_partids_by_symb{$ressymb}) ne 'ARRAY')) {
                   8357:                 (my $analysis,$parts) =
                   8358:                     &scantron_partids_tograde($resource,$env{'request.course.id'},$username,$domain);
                   8359:             } else {
                   8360:                 $parts = $grader_partids_by_symb{$ressymb};
                   8361:             }
1.542     raeburn  8362:             ($counter,my $recording) =
                   8363:                 &verify_scantron_grading($resource,$domain,$username,$cid,$counter,
1.554     raeburn  8364:                                          $scandata{$pid},$parts,
1.542     raeburn  8365:                                          \%scantron_config,\%lettdig,$numletts);
                   8366:             $record{$pid} .= $recording;
1.523     raeburn  8367:         }
                   8368:     }
                   8369:     &Apache::lonhtmlcommon::Close_PrgWin($r,\%prog_state);
                   8370:     $r->print('<br />');
                   8371:     my ($okstudents,$badstudents,$numstudents,$passed,$failed);
                   8372:     $passed = 0;
                   8373:     $failed = 0;
                   8374:     $numstudents = 0;
                   8375:     foreach my $last (sort(keys(%bylast))) {
                   8376:         if (ref($bylast{$last}) eq 'ARRAY') {
                   8377:             foreach my $pid (sort(@{$bylast{$last}})) {
                   8378:                 my $showscandata = $scandata{$pid};
                   8379:                 my $showrecord = $record{$pid};
                   8380:                 $showscandata =~ s/\s/&nbsp;/g;
                   8381:                 $showrecord =~ s/\s/&nbsp;/g;
                   8382:                 if ($scandata{$pid} eq $record{$pid}) {
                   8383:                     my $css_class = ($passed % 2)?'LC_odd_row':'LC_even_row';
                   8384:                     $okstudents .= '<tr class="'.$css_class.'">'.
1.581     www      8385: '<td>'.&mt('Bubblesheet').'</td><td>'.$showscandata.'</td><td rowspan="2">'.$last.'</td><td rowspan="2">'.$pid.'</td>'."\n".
1.523     raeburn  8386: '</tr>'."\n".
                   8387: '<tr class="'.$css_class.'">'."\n".
                   8388: '<td>Submissions</td><td>'.$showrecord.'</td></tr>'."\n";
                   8389:                     $passed ++;
                   8390:                 } else {
                   8391:                     my $css_class = ($failed % 2)?'LC_odd_row':'LC_even_row';
1.581     www      8392:                     $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  8393: '</tr>'."\n".
                   8394: '<tr class="'.$css_class.'">'."\n".
                   8395: '<td>Submissions</td><td><span class="LC_nobreak">'.$record{$pid}.'</span></td>'."\n".
                   8396: '</tr>'."\n";
                   8397:                     $failed ++;
                   8398:                 }
                   8399:                 $numstudents ++;
                   8400:             }
                   8401:         }
                   8402:     }
1.572     www      8403:     $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  8404:     $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>');
                   8405:     if ($passed) {
1.572     www      8406:         $r->print(&mt('Students with exact correspondence between bubblesheet data and submissions are as follows:').'<br /><br />');
1.523     raeburn  8407:         $r->print(&Apache::loncommon::start_data_table()."\n".
                   8408:                  &Apache::loncommon::start_data_table_header_row()."\n".
                   8409:                  '<th>'.&mt('Source').'</th><th>'.&mt('Bubble records').'</th><th>'.&mt('Name').'</th><th>'.&mt('ID').'</th>'.
                   8410:                  &Apache::loncommon::end_data_table_header_row()."\n".
                   8411:                  $okstudents."\n".
                   8412:                  &Apache::loncommon::end_data_table().'<br />');
                   8413:     }
                   8414:     if ($failed) {
1.572     www      8415:         $r->print(&mt('Students with differences between bubblesheet data and submissions are as follows:').'<br /><br />');
1.523     raeburn  8416:         $r->print(&Apache::loncommon::start_data_table()."\n".
                   8417:                  &Apache::loncommon::start_data_table_header_row()."\n".
                   8418:                  '<th>'.&mt('Source').'</th><th>'.&mt('Bubble records').'</th><th>'.&mt('Name').'</th><th>'.&mt('ID').'</th>'.
                   8419:                  &Apache::loncommon::end_data_table_header_row()."\n".
                   8420:                  $badstudents."\n".
                   8421:                  &Apache::loncommon::end_data_table()).'<br />'.
1.572     www      8422:                  &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  8423:     }
                   8424:     $r->print('</form><br />'.$grading_menu_button);
                   8425:     return;
                   8426: }
                   8427: 
1.542     raeburn  8428: sub verify_scantron_grading {
1.554     raeburn  8429:     my ($resource,$domain,$username,$cid,$counter,$scandata,$partids,
1.542     raeburn  8430:         $scantron_config,$lettdig,$numletts) = @_;
                   8431:     my ($record,%expected,%startpos);
                   8432:     return ($counter,$record) if (!ref($resource));
                   8433:     return ($counter,$record) if (!$resource->is_problem());
                   8434:     my $symb = $resource->symb();
1.554     raeburn  8435:     return ($counter,$record) if (ref($partids) ne 'ARRAY');
                   8436:     foreach my $part_id (@{$partids}) {
1.542     raeburn  8437:         $counter ++;
                   8438:         $expected{$part_id} = 0;
                   8439:         if ($env{"form.scantron.sub_bubblelines.$counter"}) {
                   8440:             my @sub_lines = split(/,/,$env{"form.scantron.sub_bubblelines.$counter"});
                   8441:             foreach my $item (@sub_lines) {
                   8442:                 $expected{$part_id} += $item;
                   8443:             }
                   8444:         } else {
                   8445:             $expected{$part_id} = $env{"form.scantron.bubblelines.$counter"};
                   8446:         }
                   8447:         $startpos{$part_id} = $env{"form.scantron.first_bubble_line.$counter"};
                   8448:     }
                   8449:     if ($symb) {
                   8450:         my %recorded;
                   8451:         my (%returnhash) = &Apache::lonnet::restore($symb,$cid,$domain,$username);
                   8452:         if ($returnhash{'version'}) {
                   8453:             my %lasthash=();
                   8454:             my $version;
                   8455:             for ($version=1;$version<=$returnhash{'version'};$version++) {
                   8456:                 foreach my $key (sort(split(/\:/,$returnhash{$version.':keys'}))) {
                   8457:                     $lasthash{$key}=$returnhash{$version.':'.$key};
                   8458:                 }
                   8459:             }
                   8460:             foreach my $key (keys(%lasthash)) {
                   8461:                 if ($key =~ /\.scantron$/) {
                   8462:                     my $value = &unescape($lasthash{$key});
                   8463:                     my ($part_id) = ($key =~ /^resource\.(.+)\.scantron$/);
                   8464:                     if ($value eq '') {
                   8465:                         for (my $i=0; $i<$expected{$part_id}; $i++) {
                   8466:                             for (my $j=0; $j<$scantron_config->{'length'}; $j++) {
                   8467:                                 $recorded{$part_id} .= $scantron_config->{'Qoff'};
                   8468:                             }
                   8469:                         }
                   8470:                     } else {
                   8471:                         my @tocheck;
                   8472:                         my @items = split(//,$value);
                   8473:                         if (($scantron_config->{'Qon'} eq 'letter') ||
                   8474:                             ($scantron_config->{'Qon'} eq 'number')) {
                   8475:                             if (@items < $expected{$part_id}) {
                   8476:                                 my $fragment = substr($scandata,$startpos{$part_id},$expected{$part_id});
                   8477:                                 my @singles = split(//,$fragment);
                   8478:                                 foreach my $pos (@singles) {
                   8479:                                     if ($pos eq ' ') {
                   8480:                                         push(@tocheck,$pos);
                   8481:                                     } else {
                   8482:                                         my $next = shift(@items);
                   8483:                                         push(@tocheck,$next);
                   8484:                                     }
                   8485:                                 }
                   8486:                             } else {
                   8487:                                 @tocheck = @items;
                   8488:                             }
                   8489:                             foreach my $letter (@tocheck) {
                   8490:                                 if ($scantron_config->{'Qon'} eq 'letter') {
                   8491:                                     if ($letter !~ /^[A-J]$/) {
                   8492:                                         $letter = $scantron_config->{'Qoff'};
                   8493:                                     }
                   8494:                                     $recorded{$part_id} .= $letter;
                   8495:                                 } elsif ($scantron_config->{'Qon'} eq 'number') {
                   8496:                                     my $digit;
                   8497:                                     if ($letter !~ /^[A-J]$/) {
                   8498:                                         $digit = $scantron_config->{'Qoff'};
                   8499:                                     } else {
                   8500:                                         $digit = $lettdig->{$letter};
                   8501:                                     }
                   8502:                                     $recorded{$part_id} .= $digit;
                   8503:                                 }
                   8504:                             }
                   8505:                         } else {
                   8506:                             @tocheck = @items;
                   8507:                             for (my $i=0; $i<$expected{$part_id}; $i++) {
                   8508:                                 my $curr_sub = shift(@tocheck);
                   8509:                                 my $digit;
                   8510:                                 if ($curr_sub =~ /^[A-J]$/) {
                   8511:                                     $digit = $lettdig->{$curr_sub}-1;
                   8512:                                 }
                   8513:                                 if ($curr_sub eq 'J') {
                   8514:                                     $digit += scalar($numletts);
                   8515:                                 }
                   8516:                                 for (my $j=0; $j<$scantron_config->{'Qlength'}; $j++) {
                   8517:                                     if ($j == $digit) {
                   8518:                                         $recorded{$part_id} .= $scantron_config->{'Qon'};
                   8519:                                     } else {
                   8520:                                         $recorded{$part_id} .= $scantron_config->{'Qoff'};
                   8521:                                     }
                   8522:                                 }
                   8523:                             }
                   8524:                         }
                   8525:                     }
                   8526:                 }
                   8527:             }
                   8528:         }
1.554     raeburn  8529:         foreach my $part_id (@{$partids}) {
1.542     raeburn  8530:             if ($recorded{$part_id} eq '') {
                   8531:                 for (my $i=0; $i<$expected{$part_id}; $i++) {
                   8532:                     for (my $j=0; $j<$scantron_config->{'Qlength'}; $j++) {
                   8533:                         $recorded{$part_id} .= $scantron_config->{'Qoff'};
                   8534:                     }
                   8535:                 }
                   8536:             }
                   8537:             $record .= $recorded{$part_id};
                   8538:         }
                   8539:     }
                   8540:     return ($counter,$record);
                   8541: }
                   8542: 
                   8543: sub letter_to_digits { 
                   8544:     my %lettdig = (
                   8545:                     A => 1,
                   8546:                     B => 2,
                   8547:                     C => 3,
                   8548:                     D => 4,
                   8549:                     E => 5,
                   8550:                     F => 6,
                   8551:                     G => 7,
                   8552:                     H => 8,
                   8553:                     I => 9,
                   8554:                     J => 0,
                   8555:                   );
                   8556:     return %lettdig;
                   8557: }
                   8558: 
1.423     albertel 8559: 
1.75      albertel 8560: #-------- end of section for handling grading scantron forms -------
                   8561: #
                   8562: #-------------------------------------------------------------------
                   8563: 
1.72      ng       8564: #-------------------------- Menu interface -------------------------
                   8565: #
                   8566: #--- Show a Grading Menu button - Calls the next routine ---
                   8567: sub show_grading_menu_form {
1.324     albertel 8568:     my ($symb)=@_;
1.125     ng       8569:     my $result.='<br /><form action="/adm/grades" method="post">'."\n".
1.418     albertel 8570: 	'<input type="hidden" name="symb" value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
1.257     albertel 8571: 	'<input type="hidden" name="saveState"  value="'.$env{'form.saveState'}.'" />'."\n".
1.72      ng       8572: 	'<input type="hidden" name="command" value="gradingmenu" />'."\n".
1.478     albertel 8573: 	'<input type="submit" name="submit" value="'.&mt('Grading Menu').'" />'."\n".
1.72      ng       8574: 	'</form>'."\n";
                   8575:     return $result;
                   8576: }
                   8577: 
1.77      ng       8578: # -- Retrieve choices for grading form
                   8579: sub savedState {
                   8580:     my %savedState = ();
1.257     albertel 8581:     if ($env{'form.saveState'}) {
                   8582: 	foreach (split(/:/,$env{'form.saveState'})) {
1.77      ng       8583: 	    my ($key,$value) = split(/=/,$_,2);
                   8584: 	    $savedState{$key} = $value;
                   8585: 	}
                   8586:     }
                   8587:     return \%savedState;
                   8588: }
1.76      ng       8589: 
1.443     banghart 8590: sub grading_menu {
                   8591:     my ($request) = @_;
                   8592:     my ($symb)=&get_symb($request);
                   8593:     if (!$symb) {return '';}
                   8594:     my $probTitle = &Apache::lonnet::gettitle($symb);
                   8595:     my ($table,undef,$hdgrade) = &showResourceInfo($symb,$probTitle);
                   8596: 
1.444     banghart 8597:     $request->print($table);
1.443     banghart 8598:     my %fields = ('symb'=>&Apache::lonenc::check_encrypt($symb),
                   8599:                   'handgrade'=>$hdgrade,
                   8600:                   'probTitle'=>$probTitle,
                   8601:                   'command'=>'submit_options',
                   8602:                   'saveState'=>"",
                   8603:                   'gradingMenu'=>1,
                   8604:                   'showgrading'=>"yes");
1.538     schulted 8605:     
                   8606:     my $url1 = &Apache::lonhtmlcommon::build_url('grades/',\%fields);
                   8607:     
1.443     banghart 8608:     $fields{'command'} = 'csvform';
1.538     schulted 8609:     my $url2 = &Apache::lonhtmlcommon::build_url('grades/',\%fields);
                   8610:     
1.443     banghart 8611:     $fields{'command'} = 'processclicker';
1.538     schulted 8612:     my $url3 = &Apache::lonhtmlcommon::build_url('grades/',\%fields);
                   8613:     
1.443     banghart 8614:     $fields{'command'} = 'scantron_selectphase';
1.538     schulted 8615:     my $url4 = &Apache::lonhtmlcommon::build_url('grades/',\%fields);
                   8616:     
                   8617:     my @menu = ({	categorytitle=>'Course Grading',
                   8618:             items =>[
                   8619:                         {	linktext => 'Manual Grading/View Submissions',
                   8620:                     		url => $url1,
                   8621:                     		permission => 'F',
                   8622:                     		icon => 'edit-find-replace.png',
                   8623:                     		linktitle => 'Start the process of hand grading submissions.'
                   8624:                         },
                   8625:                 	    {	linktext => 'Upload Scores',
                   8626:                     		url => $url2,
                   8627:                     		permission => 'F',
                   8628:                     		icon => 'uploadscores.png',
                   8629:                     		linktitle => 'Specify a file containing the class scores for current resource.'
                   8630:                 	    },
                   8631:                 	    {	linktext => 'Process Clicker',
                   8632:                     		url => $url3,
                   8633:                     		permission => 'F',
                   8634:                     		icon => 'addClickerInfoFile.png',
                   8635:                     		linktitle => 'Specify a file containing the clicker information for this resource.'
                   8636:                 	    },
1.587     raeburn  8637:                 	    {	linktext => 'Grade/Manage/Review Bubblesheets',
1.538     schulted 8638:                     		url => $url4,
                   8639:                     		permission => 'F',
                   8640:                     		icon => 'stat.png',
                   8641:                     		linktitle => 'Grade scantron exams, upload/download scantron data files, and review previously graded scantron exams.'
                   8642:                 	    }
                   8643:                     ]
                   8644:             });
                   8645: 
                   8646:     #$fields{'command'} = 'verify';
                   8647:     #$url = &Apache::lonhtmlcommon::build_url('grades/',\%fields);
1.443     banghart 8648:     #
                   8649:     # Create the menu
                   8650:     my $Str;
1.444     banghart 8651:     # $Str .= '<h2>'.&mt('Please select a grading task').'</h2>';
1.445     banghart 8652:     $Str .= '<form method="post" action="" name="gradingMenu">';
                   8653:     $Str .= '<input type="hidden" name="command" value="" />'.
                   8654:     	'<input type="hidden" name="symb"        value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
                   8655: 	'<input type="hidden" name="handgrade"   value="'.$hdgrade.'" />'."\n".
1.476     albertel 8656: 	'<input type="hidden" name="probTitle"   value="'.$probTitle.'" />'."\n".
1.445     banghart 8657: 	'<input type="hidden" name="saveState"   value="" />'."\n".
                   8658: 	'<input type="hidden" name="gradingMenu" value="1" />'."\n".
                   8659: 	'<input type="hidden" name="showgrading" value="yes" />'."\n";
                   8660: 
1.538     schulted 8661:     $Str .= Apache::lonhtmlcommon::generate_menu(@menu);
                   8662:     #$menudata->{'jscript'}
1.584     bisitz   8663:     $Str .='<hr /><input type="button" value="'.&mt('Verify Receipt No.').'" '.
1.589     bisitz   8664:         ' onclick="javascript:checkChoice(document.forms.gradingMenu,\'5\',\'verify\')" '.
1.538     schulted 8665:         ' /> '.
                   8666:         &Apache::lonnet::recprefix($env{'request.course.id'}).
1.589     bisitz   8667:         '-<input type="text" name="receipt" size="4" onchange="javascript:checkReceiptNo(this.form,\'OK\')" />';
1.538     schulted 8668: 
1.444     banghart 8669:     $Str .="</form>\n";
1.539     riegler  8670:     my $receiptalert = &mt("Please enter a receipt number given by a student in the receipt box.");
1.443     banghart 8671:     $request->print(<<GRADINGMENUJS);
                   8672: <script type="text/javascript" language="javascript">
                   8673:     function checkChoice(formname,val,cmdx) {
                   8674: 	if (val <= 2) {
                   8675: 	    var cmd = radioSelection(formname.radioChoice);
                   8676: 	    var cmdsave = cmd;
                   8677: 	} else {
                   8678: 	    cmd = cmdx;
                   8679: 	    cmdsave = 'submission';
                   8680: 	}
                   8681: 	formname.command.value = cmd;
                   8682: 	if (val < 5) formname.submit();
                   8683: 	if (val == 5) {
1.458     banghart 8684: 	    if (!checkReceiptNo(formname,'notOK')) { 
                   8685: 	        return false;
                   8686: 	    } else {
                   8687: 	        formname.submit();
                   8688: 	    }
1.445     banghart 8689: 	}
                   8690:     }
1.443     banghart 8691: 
                   8692:     function checkReceiptNo(formname,nospace) {
                   8693: 	var receiptNo = formname.receipt.value;
                   8694: 	var checkOpt = false;
                   8695: 	if (nospace == "OK" && isNaN(receiptNo)) {checkOpt = true;}
                   8696: 	if (nospace == "notOK" && (isNaN(receiptNo) || receiptNo == "")) {checkOpt = true;}
                   8697: 	if (checkOpt) {
1.539     riegler  8698: 	    alert("$receiptalert");
1.443     banghart 8699: 	    formname.receipt.value = "";
                   8700: 	    formname.receipt.focus();
                   8701: 	    return false;
                   8702: 	}
                   8703: 	return true;
                   8704:     }
                   8705: </script>
                   8706: GRADINGMENUJS
                   8707:     &commonJSfunctions($request);
                   8708:     return $Str;    
                   8709: }
                   8710: 
                   8711: 
                   8712: #--- Displays the submissions first page -------
                   8713: sub submit_options {
1.72      ng       8714:     my ($request) = @_;
1.324     albertel 8715:     my ($symb)=&get_symb($request);
1.72      ng       8716:     if (!$symb) {return '';}
1.76      ng       8717:     my $probTitle = &Apache::lonnet::gettitle($symb);
1.72      ng       8718: 
1.539     riegler  8719:     my $receiptalert = &mt("Please enter a receipt number given by a student in the receipt box."); 
1.72      ng       8720:     $request->print(<<GRADINGMENUJS);
                   8721: <script type="text/javascript" language="javascript">
1.116     ng       8722:     function checkChoice(formname,val,cmdx) {
                   8723: 	if (val <= 2) {
                   8724: 	    var cmd = radioSelection(formname.radioChoice);
1.118     ng       8725: 	    var cmdsave = cmd;
1.116     ng       8726: 	} else {
                   8727: 	    cmd = cmdx;
1.118     ng       8728: 	    cmdsave = 'submission';
1.116     ng       8729: 	}
                   8730: 	formname.command.value = cmd;
1.118     ng       8731: 	formname.saveState.value = "saveCmd="+cmdsave+":saveSec="+pullDownSelection(formname.section)+
1.145     albertel 8732: 	    ":saveSub="+pullDownSelection(formname.submitonly)+":saveStatus="+pullDownSelection(formname.Status);
1.116     ng       8733: 	if (val < 5) formname.submit();
                   8734: 	if (val == 5) {
1.72      ng       8735: 	    if (!checkReceiptNo(formname,'notOK')) { return false;}
                   8736: 	    formname.submit();
                   8737: 	}
1.238     albertel 8738: 	if (val < 7) formname.submit();
1.72      ng       8739:     }
                   8740: 
                   8741:     function checkReceiptNo(formname,nospace) {
                   8742: 	var receiptNo = formname.receipt.value;
                   8743: 	var checkOpt = false;
                   8744: 	if (nospace == "OK" && isNaN(receiptNo)) {checkOpt = true;}
                   8745: 	if (nospace == "notOK" && (isNaN(receiptNo) || receiptNo == "")) {checkOpt = true;}
                   8746: 	if (checkOpt) {
1.539     riegler  8747: 	    alert("$receiptalert");
1.72      ng       8748: 	    formname.receipt.value = "";
                   8749: 	    formname.receipt.focus();
                   8750: 	    return false;
                   8751: 	}
                   8752: 	return true;
                   8753:     }
                   8754: </script>
                   8755: GRADINGMENUJS
1.118     ng       8756:     &commonJSfunctions($request);
1.324     albertel 8757:     my ($table,undef,$hdgrade) = &showResourceInfo($symb,$probTitle);
1.473     albertel 8758:     my $result;
1.76      ng       8759:     my (undef,$sections) = &getclasslist('all','0');
1.77      ng       8760:     my $savedState = &savedState();
1.118     ng       8761:     my $saveCmd = ($$savedState{'saveCmd'} eq '' ? 'submission' : $$savedState{'saveCmd'});
1.77      ng       8762:     my $saveSec = ($$savedState{'saveSec'} eq '' ? 'all' : $$savedState{'saveSec'});
1.118     ng       8763:     my $saveSub = ($$savedState{'saveSub'} eq '' ? 'all' : $$savedState{'saveSub'});
1.77      ng       8764:     my $saveStatus = ($$savedState{'saveStatus'} eq '' ? 'Active' : $$savedState{'saveStatus'});
1.72      ng       8765: 
1.533     bisitz   8766:     # Preselect sections
                   8767:     my $selsec="";
                   8768:     if (ref($sections)) {
                   8769:         foreach my $section (sort(@$sections)) {
                   8770:             $selsec.='<option value="'.$section.'" '.
                   8771:                 ($saveSec eq $section ? 'selected="selected"':'').'>'.$section.'</option>'."\n";
                   8772:         }
                   8773:     }
                   8774: 
1.72      ng       8775:     $result.='<form action="/adm/grades" method="post" name="gradingMenu">'."\n".
1.418     albertel 8776: 	'<input type="hidden" name="symb"        value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
1.72      ng       8777: 	'<input type="hidden" name="handgrade"   value="'.$hdgrade.'" />'."\n".
                   8778: 	'<input type="hidden" name="probTitle"   value="'.$probTitle.'" />'."\n".
1.116     ng       8779: 	'<input type="hidden" name="command"     value="" />'."\n".
1.77      ng       8780: 	'<input type="hidden" name="saveState"   value="" />'."\n".
1.124     ng       8781: 	'<input type="hidden" name="gradingMenu" value="1" />'."\n".
1.72      ng       8782: 	'<input type="hidden" name="showgrading" value="yes" />'."\n";
                   8783: 
1.472     albertel 8784:     $result.='
1.533     bisitz   8785: <h2>
                   8786:   '.&mt('Grade Current Resource').'
                   8787: </h2>
                   8788: <div>
                   8789:   '.$table.'
                   8790: </div>
                   8791: 
1.537     harmsja  8792: <div class="LC_columnSection">
                   8793:   
1.533     bisitz   8794:     <fieldset>
                   8795:       <legend>
                   8796:        '.&mt('Sections').'
                   8797:       </legend>
                   8798:       <select name="section" multiple="multiple" size="5">'."\n";
                   8799:     $result.= $selsec;
1.401     albertel 8800:     $result.= '<option value="all" '.($saveSec eq 'all' ? 'selected="selected"' : ''). '>all</option></select> &nbsp; ';
1.472     albertel 8801:     $result.='
1.533     bisitz   8802:     </fieldset>
1.537     harmsja  8803:   
1.533     bisitz   8804:     <fieldset>
                   8805:       <legend>
                   8806:         '.&mt('Groups').'
                   8807:       </legend>
                   8808:       '.&Apache::lonstatistics::GroupSelect('group','multiple',5).'
                   8809:     </fieldset>
1.537     harmsja  8810:   
1.533     bisitz   8811:     <fieldset>
                   8812:       <legend>
                   8813:         '.&mt('Access Status').'
                   8814:       </legend>
                   8815:       '.&Apache::lonhtmlcommon::StatusOptions($saveStatus,undef,5,undef,'mult').'
                   8816:     </fieldset>
1.537     harmsja  8817:   
1.533     bisitz   8818:     <fieldset>
                   8819:       <legend>
                   8820:         '.&mt('Submission Status').'
                   8821:       </legend>
                   8822:       <select name="submitonly" size="5">
1.473     albertel 8823: 	         <option value="yes" '.      ($saveSub eq 'yes'       ? 'selected="selected"' : '').'>'.&mt('with submissions').'</option>
                   8824: 	         <option value="queued" '.   ($saveSub eq 'queued'    ? 'selected="selected"' : '').'>'.&mt('in grading queue').'</option>
                   8825: 	         <option value="graded" '.   ($saveSub eq 'graded'    ? 'selected="selected"' : '').'>'.&mt('with ungraded submissions').'</option>
                   8826: 	         <option value="incorrect" '.($saveSub eq 'incorrect' ? 'selected="selected"' : '').'>'.&mt('with incorrect submissions').'</option>
                   8827:                  <option value="all" '.      ($saveSub eq 'all'       ? 'selected="selected"' : '').'>'.&mt('with any status').'</option>
1.533     bisitz   8828:       </select>
                   8829:     </fieldset>
1.537     harmsja  8830:   
1.533     bisitz   8831: </div>
                   8832: 
                   8833: <br />
                   8834:           <div>
                   8835:             <div>
1.473     albertel 8836:               <label>
                   8837:                 <input type="radio" name="radioChoice" value="submission" '.
                   8838:                   ($saveCmd eq 'submission' ? 'checked="checked"' : '').' /> '.
                   8839:              &mt('Select individual students to grade and view submissions.').'
                   8840: 	      </label> 
                   8841:             </div>
1.533     bisitz   8842:             <div>
1.473     albertel 8843: 	      <label>
                   8844:                 <input type="radio" name="radioChoice" value="viewgrades" '.
                   8845:                   ($saveCmd eq 'viewgrades' ? 'checked="checked"' : '').' /> '.
                   8846:                     &mt('Grade all selected students in a grading table.').'
                   8847:               </label>
                   8848:             </div>
1.533     bisitz   8849:             <div>
1.589     bisitz   8850: 	      <input type="button" onclick="javascript:checkChoice(this.form,\'2\');" value="'.&mt('Next').' &rarr;" />
1.473     albertel 8851:             </div>
1.472     albertel 8852:           </div>
1.533     bisitz   8853: 
                   8854: 
1.473     albertel 8855:         <h2>
                   8856:          '.&mt('Grade Complete Folder for One Student').'
                   8857:         </h2>
1.533     bisitz   8858:         <div>
                   8859:             <div>
1.473     albertel 8860:               <label>
                   8861:                 <input type="radio" name="radioChoice" value="pickStudentPage" '.
                   8862: 	  ($saveCmd eq 'pickStudentPage' ? 'checked="checked"' : '').' /> '.
                   8863:   &mt('The <b>complete</b> page/sequence/folder: For one student').'
                   8864:               </label>
                   8865:             </div>
1.533     bisitz   8866:             <div>
1.589     bisitz   8867: 	      <input type="button" onclick="javascript:checkChoice(this.form,\'2\');" value="'.&mt('Next').' &rarr;" />
1.473     albertel 8868:             </div>
1.472     albertel 8869:         </div>
                   8870:   </form>';
1.499     albertel 8871:     $result .= &show_grading_menu_form($symb);
1.44      ng       8872:     return $result;
1.2       albertel 8873: }
                   8874: 
1.285     albertel 8875: sub reset_perm {
                   8876:     undef(%perm);
                   8877: }
                   8878: 
                   8879: sub init_perm {
                   8880:     &reset_perm();
1.300     albertel 8881:     foreach my $test_perm ('vgr','mgr','opa') {
                   8882: 
                   8883: 	my $scope = $env{'request.course.id'};
                   8884: 	if (!($perm{$test_perm}=&Apache::lonnet::allowed($test_perm,$scope))) {
                   8885: 
                   8886: 	    $scope .= '/'.$env{'request.course.sec'};
                   8887: 	    if ( $perm{$test_perm}=
                   8888: 		 &Apache::lonnet::allowed($test_perm,$scope)) {
                   8889: 		$perm{$test_perm.'_section'}=$env{'request.course.sec'};
                   8890: 	    } else {
                   8891: 		delete($perm{$test_perm});
                   8892: 	    }
1.285     albertel 8893: 	}
                   8894:     }
                   8895: }
                   8896: 
1.400     www      8897: sub gather_clicker_ids {
1.408     albertel 8898:     my %clicker_ids;
1.400     www      8899: 
                   8900:     my $classlist = &Apache::loncoursedata::get_classlist();
                   8901: 
                   8902:     # Set up a couple variables.
1.407     albertel 8903:     my $username_idx = &Apache::loncoursedata::CL_SNAME();
                   8904:     my $domain_idx   = &Apache::loncoursedata::CL_SDOM();
1.438     www      8905:     my $status_idx   = &Apache::loncoursedata::CL_STATUS();
1.400     www      8906: 
1.407     albertel 8907:     foreach my $student (keys(%$classlist)) {
1.438     www      8908:         if ($classlist->{$student}->[$status_idx] ne 'Active') { next; }
1.407     albertel 8909:         my $username = $classlist->{$student}->[$username_idx];
                   8910:         my $domain   = $classlist->{$student}->[$domain_idx];
1.400     www      8911:         my $clickers =
1.408     albertel 8912: 	    (&Apache::lonnet::userenvironment($domain,$username,'clickers'))[1];
1.400     www      8913:         foreach my $id (split(/\,/,$clickers)) {
1.414     www      8914:             $id=~s/^[\#0]+//;
1.421     www      8915:             $id=~s/[\-\:]//g;
1.407     albertel 8916:             if (exists($clicker_ids{$id})) {
1.408     albertel 8917: 		$clicker_ids{$id}.=','.$username.':'.$domain;
1.400     www      8918:             } else {
1.408     albertel 8919: 		$clicker_ids{$id}=$username.':'.$domain;
1.400     www      8920:             }
                   8921:         }
                   8922:     }
1.407     albertel 8923:     return %clicker_ids;
1.400     www      8924: }
                   8925: 
1.402     www      8926: sub gather_adv_clicker_ids {
1.408     albertel 8927:     my %clicker_ids;
1.402     www      8928:     my $cnum=$env{'course.'.$env{'request.course.id'}.'.num'};
                   8929:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
                   8930:     my %coursepersonnel=&Apache::lonnet::get_course_adv_roles($cdom.'/'.$cnum);
1.409     albertel 8931:     foreach my $element (sort(keys(%coursepersonnel))) {
1.402     www      8932:         foreach my $person (split(/\,/,$coursepersonnel{$element})) {
                   8933:             my ($puname,$pudom)=split(/\:/,$person);
                   8934:             my $clickers =
1.408     albertel 8935: 		(&Apache::lonnet::userenvironment($pudom,$puname,'clickers'))[1];
1.405     www      8936:             foreach my $id (split(/\,/,$clickers)) {
1.414     www      8937: 		$id=~s/^[\#0]+//;
1.421     www      8938:                 $id=~s/[\-\:]//g;
1.408     albertel 8939: 		if (exists($clicker_ids{$id})) {
                   8940: 		    $clicker_ids{$id}.=','.$puname.':'.$pudom;
                   8941: 		} else {
                   8942: 		    $clicker_ids{$id}=$puname.':'.$pudom;
                   8943: 		}
1.405     www      8944:             }
1.402     www      8945:         }
                   8946:     }
1.407     albertel 8947:     return %clicker_ids;
1.402     www      8948: }
                   8949: 
1.413     www      8950: sub clicker_grading_parameters {
                   8951:     return ('gradingmechanism' => 'scalar',
                   8952:             'upfiletype' => 'scalar',
                   8953:             'specificid' => 'scalar',
                   8954:             'pcorrect' => 'scalar',
                   8955:             'pincorrect' => 'scalar');
                   8956: }
                   8957: 
1.400     www      8958: sub process_clicker {
                   8959:     my ($r)=@_;
                   8960:     my ($symb)=&get_symb($r);
                   8961:     if (!$symb) {return '';}
                   8962:     my $result=&checkforfile_js();
                   8963:     $env{'form.probTitle'} = &Apache::lonnet::gettitle($symb);
                   8964:     my ($table) = &showResourceInfo($symb,$env{'form.probTitle'});
                   8965:     $result.=$table;
                   8966:     $result.='<br /><table width="100%" border="0"><tr><td bgcolor="#777777">'."\n";
                   8967:     $result.='<table width="100%" border="0"><tr bgcolor="#e6ffff"><td>'."\n";
1.538     schulted 8968:     $result.='&nbsp;<b>'.&mt('Specify a file containing the clicker information for this resource.').
                   8969:         '</b></td></tr>'."\n";
1.400     www      8970:     $result.='<tr bgcolor=#ffffe6><td>'."\n";
1.413     www      8971: # Attempt to restore parameters from last session, set defaults if not present
                   8972:     my %Saveable_Parameters=&clicker_grading_parameters();
                   8973:     &Apache::loncommon::restore_course_settings('grades_clicker',
                   8974:                                                  \%Saveable_Parameters);
                   8975:     if (!$env{'form.pcorrect'}) { $env{'form.pcorrect'}=100; }
                   8976:     if (!$env{'form.pincorrect'}) { $env{'form.pincorrect'}=100; }
                   8977:     if (!$env{'form.gradingmechanism'}) { $env{'form.gradingmechanism'}='attendance'; }
                   8978:     if (!$env{'form.upfiletype'}) { $env{'form.upfiletype'}='iclicker'; }
                   8979: 
                   8980:     my %checked;
1.521     www      8981:     foreach my $gradingmechanism ('attendance','personnel','specific','given') {
1.413     www      8982:        if ($env{'form.gradingmechanism'} eq $gradingmechanism) {
1.569     bisitz   8983:           $checked{$gradingmechanism}=' checked="checked"';
1.413     www      8984:        }
                   8985:     }
                   8986: 
1.400     www      8987:     my $upload=&mt("Upload File");
                   8988:     my $type=&mt("Type");
1.402     www      8989:     my $attendance=&mt("Award points just for participation");
                   8990:     my $personnel=&mt("Correctness determined from response by course personnel");
1.414     www      8991:     my $specific=&mt("Correctness determined from response with clicker ID(s)"); 
1.521     www      8992:     my $given=&mt("Correctness determined from given list of answers").' '.
                   8993:               '<font size="-2"><tt>('.&mt("Provide comma-separated list. Use '*' for any answer correct, '-' for skip").')</tt></font>';
1.402     www      8994:     my $pcorrect=&mt("Percentage points for correct solution");
                   8995:     my $pincorrect=&mt("Percentage points for incorrect solution");
1.413     www      8996:     my $selectform=&Apache::loncommon::select_form($env{'form.upfiletype'},'upfiletype',
1.596.2.1  raeburn  8997:                                                    {'iclicker' => 'i>clicker',
                   8998:                                                     'interwrite' => 'interwrite PRS'});
1.418     albertel 8999:     $symb = &Apache::lonenc::check_encrypt($symb);
1.400     www      9000:     $result.=<<ENDUPFORM;
1.402     www      9001: <script type="text/javascript">
                   9002: function sanitycheck() {
                   9003: // Accept only integer percentages
                   9004:    document.forms.gradesupload.pcorrect.value=Math.round(document.forms.gradesupload.pcorrect.value);
                   9005:    document.forms.gradesupload.pincorrect.value=Math.round(document.forms.gradesupload.pincorrect.value);
                   9006: // Find out grading choice
                   9007:    for (i=0; i<document.forms.gradesupload.gradingmechanism.length; i++) {
                   9008:       if (document.forms.gradesupload.gradingmechanism[i].checked) {
                   9009:          gradingchoice=document.forms.gradesupload.gradingmechanism[i].value;
                   9010:       }
                   9011:    }
                   9012: // By default, new choice equals user selection
                   9013:    newgradingchoice=gradingchoice;
                   9014: // Not good to give more points for false answers than correct ones
                   9015:    if (Math.round(document.forms.gradesupload.pcorrect.value)<Math.round(document.forms.gradesupload.pincorrect.value)) {
                   9016:       document.forms.gradesupload.pcorrect.value=document.forms.gradesupload.pincorrect.value;
                   9017:    }
                   9018: // If new choice is attendance only, and old choice was correctness-based, restore defaults
                   9019:    if ((gradingchoice=='attendance') && (document.forms.gradesupload.waschecked.value!='attendance')) {
                   9020:       document.forms.gradesupload.pcorrect.value=100;
                   9021:       document.forms.gradesupload.pincorrect.value=100;
                   9022:    }
                   9023: // If the values are different, cannot be attendance only
                   9024:    if ((Math.round(document.forms.gradesupload.pcorrect.value)!=Math.round(document.forms.gradesupload.pincorrect.value)) &&
                   9025:        (gradingchoice=='attendance')) {
                   9026:        newgradingchoice='personnel';
                   9027:    }
                   9028: // Change grading choice to new one
                   9029:    for (i=0; i<document.forms.gradesupload.gradingmechanism.length; i++) {
                   9030:       if (document.forms.gradesupload.gradingmechanism[i].value==newgradingchoice) {
                   9031:          document.forms.gradesupload.gradingmechanism[i].checked=true;
                   9032:       } else {
                   9033:          document.forms.gradesupload.gradingmechanism[i].checked=false;
                   9034:       }
                   9035:    }
                   9036: // Remember the old state
                   9037:    document.forms.gradesupload.waschecked.value=newgradingchoice;
                   9038: }
                   9039: </script>
1.400     www      9040: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="gradesupload">
                   9041: <input type="hidden" name="symb" value="$symb" />
                   9042: <input type="hidden" name="command" value="processclickerfile" />
                   9043: <input type="hidden" name="probTitle" value="$env{'form.probTitle'}" />
                   9044: <input type="hidden" name="saveState"  value="$env{'form.saveState'}" />
                   9045: <input type="file" name="upfile" size="50" />
                   9046: <br /><label>$type: $selectform</label>
1.589     bisitz   9047: <br /><label><input type="radio" name="gradingmechanism" value="attendance"$checked{'attendance'} onclick="sanitycheck()" />$attendance </label>
                   9048: <br /><label><input type="radio" name="gradingmechanism" value="personnel"$checked{'personnel'} onclick="sanitycheck()" />$personnel</label>
                   9049: <br /><label><input type="radio" name="gradingmechanism" value="specific"$checked{'specific'} onclick="sanitycheck()" />$specific </label>
1.414     www      9050: <input type="text" name="specificid" value="$env{'form.specificid'}" size="20" />
1.589     bisitz   9051: <br /><label><input type="radio" name="gradingmechanism" value="given"$checked{'given'} onclick="sanitycheck()" />$given </label>
1.521     www      9052: <br />&nbsp;&nbsp;&nbsp;
                   9053: <input type="text" name="givenanswer" size="50" />
1.413     www      9054: <input type="hidden" name="waschecked" value="$env{'form.gradingmechanism'}" />
1.589     bisitz   9055: <br /><label>$pcorrect: <input type="text" name="pcorrect" size="4" value="$env{'form.pcorrect'}" onchange="sanitycheck()" /></label>
                   9056: <br /><label>$pincorrect: <input type="text" name="pincorrect" size="4" value="$env{'form.pincorrect'}" onchange="sanitycheck()" /></label>
                   9057: <br /><input type="button" onclick="javascript:checkUpload(this.form);" value="$upload" />
1.400     www      9058: </form>
                   9059: ENDUPFORM
                   9060:     $result.='</td></tr></table>'."\n".
                   9061:              '</td></tr></table><br /><br />'."\n";
                   9062:     $result.=&show_grading_menu_form($symb);
                   9063:     return $result;
                   9064: }
                   9065: 
                   9066: sub process_clicker_file {
                   9067:     my ($r)=@_;
                   9068:     my ($symb)=&get_symb($r);
                   9069:     if (!$symb) {return '';}
1.413     www      9070: 
                   9071:     my %Saveable_Parameters=&clicker_grading_parameters();
                   9072:     &Apache::loncommon::store_course_settings('grades_clicker',
                   9073:                                               \%Saveable_Parameters);
                   9074: 
1.400     www      9075:     my ($result) = &showResourceInfo($symb,$env{'form.probTitle'});
1.404     www      9076:     if (($env{'form.gradingmechanism'} eq 'specific') && ($env{'form.specificid'}!~/\w/)) {
1.408     albertel 9077: 	$result.='<span class="LC_error">'.&mt('You need to specify a clicker ID for the correct answer').'</span>';
                   9078: 	return $result.&show_grading_menu_form($symb);
1.404     www      9079:     }
1.522     www      9080:     if (($env{'form.gradingmechanism'} eq 'given') && ($env{'form.givenanswer'}!~/\S/)) {
1.521     www      9081:         $result.='<span class="LC_error">'.&mt('You need to specify the correct answer').'</span>';
                   9082:         return $result.&show_grading_menu_form($symb);
                   9083:     }
1.522     www      9084:     my $foundgiven=0;
1.521     www      9085:     if ($env{'form.gradingmechanism'} eq 'given') {
                   9086:         $env{'form.givenanswer'}=~s/^\s*//gs;
                   9087:         $env{'form.givenanswer'}=~s/\s*$//gs;
                   9088:         $env{'form.givenanswer'}=~s/[^a-zA-Z0-9\.\*\-]+/\,/g;
                   9089:         $env{'form.givenanswer'}=uc($env{'form.givenanswer'});
1.522     www      9090:         my @answers=split(/\,/,$env{'form.givenanswer'});
                   9091:         $foundgiven=$#answers+1;
1.521     www      9092:     }
1.407     albertel 9093:     my %clicker_ids=&gather_clicker_ids();
1.408     albertel 9094:     my %correct_ids;
1.404     www      9095:     if ($env{'form.gradingmechanism'} eq 'personnel') {
1.408     albertel 9096: 	%correct_ids=&gather_adv_clicker_ids();
1.404     www      9097:     }
                   9098:     if ($env{'form.gradingmechanism'} eq 'specific') {
1.414     www      9099: 	foreach my $correct_id (split(/[\s\,]/,$env{'form.specificid'})) {;
                   9100: 	   $correct_id=~tr/a-z/A-Z/;
                   9101: 	   $correct_id=~s/\s//gs;
                   9102: 	   $correct_id=~s/^[\#0]+//;
1.421     www      9103:            $correct_id=~s/[\-\:]//g;
1.414     www      9104:            if ($correct_id) {
                   9105: 	      $correct_ids{$correct_id}='specified';
                   9106:            }
                   9107:         }
1.400     www      9108:     }
1.404     www      9109:     if ($env{'form.gradingmechanism'} eq 'attendance') {
1.408     albertel 9110: 	$result.=&mt('Score based on attendance only');
1.521     www      9111:     } elsif ($env{'form.gradingmechanism'} eq 'given') {
1.522     www      9112:         $result.=&mt('Score based on [_1] ([_2] answers)','<tt>'.$env{'form.givenanswer'}.'</tt>',$foundgiven);
1.404     www      9113:     } else {
1.408     albertel 9114: 	my $number=0;
1.411     www      9115: 	$result.='<p><b>'.&mt('Correctness determined by the following IDs').'</b>';
1.408     albertel 9116: 	foreach my $id (sort(keys(%correct_ids))) {
1.411     www      9117: 	    $result.='<br /><tt>'.$id.'</tt> - ';
1.408     albertel 9118: 	    if ($correct_ids{$id} eq 'specified') {
                   9119: 		$result.=&mt('specified');
                   9120: 	    } else {
                   9121: 		my ($uname,$udom)=split(/\:/,$correct_ids{$id});
                   9122: 		$result.=&Apache::loncommon::plainname($uname,$udom);
                   9123: 	    }
                   9124: 	    $number++;
                   9125: 	}
1.411     www      9126:         $result.="</p>\n";
1.408     albertel 9127: 	if ($number==0) {
                   9128: 	    $result.='<span class="LC_error">'.&mt('No IDs found to determine correct answer').'</span>';
                   9129: 	    return $result.&show_grading_menu_form($symb);
                   9130: 	}
1.404     www      9131:     }
1.405     www      9132:     if (length($env{'form.upfile'}) < 2) {
1.407     albertel 9133:         $result.=&mt('[_1] Error: [_2] The file you attempted to upload, [_3] contained no information. Please check that you entered the correct filename.',
                   9134: 		     '<span class="LC_error">',
                   9135: 		     '</span>',
                   9136: 		     '<span class="LC_filename">'.&HTML::Entities::encode($env{'form.upfile.filename'},'<>&"').'</span>');
1.405     www      9137:         return $result.&show_grading_menu_form($symb);
                   9138:     }
1.410     www      9139: 
                   9140: # Were able to get all the info needed, now analyze the file
                   9141: 
1.411     www      9142:     $result.=&Apache::loncommon::studentbrowser_javascript();
1.418     albertel 9143:     $symb = &Apache::lonenc::check_encrypt($symb);
1.410     www      9144:     my $heading=&mt('Scanning clicker file');
                   9145:     $result.=(<<ENDHEADER);
                   9146: <br /><table width="100%" border="0"><tr><td bgcolor="#777777">
                   9147: <table width="100%" border="0"><tr bgcolor="#e6ffff"><td>
                   9148: <b>$heading</b></td></tr><tr bgcolor=#ffffe6><td>
                   9149: <form method="post" action="/adm/grades" name="clickeranalysis">
                   9150: <input type="hidden" name="symb" value="$symb" />
                   9151: <input type="hidden" name="command" value="assignclickergrades" />
                   9152: <input type="hidden" name="probTitle" value="$env{'form.probTitle'}" />
                   9153: <input type="hidden" name="saveState"  value="$env{'form.saveState'}" />
1.411     www      9154: <input type="hidden" name="gradingmechanism" value="$env{'form.gradingmechanism'}" />
                   9155: <input type="hidden" name="pcorrect" value="$env{'form.pcorrect'}" />
                   9156: <input type="hidden" name="pincorrect" value="$env{'form.pincorrect'}" />
1.410     www      9157: ENDHEADER
1.522     www      9158:     if ($env{'form.gradingmechanism'} eq 'given') {
                   9159:        $result.='<input type="hidden" name="correct:given" value="'.$env{'form.givenanswer'}.'" />';
                   9160:     } 
1.408     albertel 9161:     my %responses;
                   9162:     my @questiontitles;
1.405     www      9163:     my $errormsg='';
                   9164:     my $number=0;
                   9165:     if ($env{'form.upfiletype'} eq 'iclicker') {
1.408     albertel 9166: 	($errormsg,$number)=&iclicker_eval(\@questiontitles,\%responses);
1.406     www      9167:     }
1.419     www      9168:     if ($env{'form.upfiletype'} eq 'interwrite') {
                   9169:         ($errormsg,$number)=&interwrite_eval(\@questiontitles,\%responses);
                   9170:     }
1.411     www      9171:     $result.='<br />'.&mt('Found [_1] question(s)',$number).'<br />'.
                   9172:              '<input type="hidden" name="number" value="'.$number.'" />'.
                   9173:              &mt('Awarding [_1] percent for correct and [_2] percent for incorrect responses',
                   9174:                  $env{'form.pcorrect'},$env{'form.pincorrect'}).
                   9175:              '<br />';
1.522     www      9176:     if (($env{'form.gradingmechanism'} eq 'given') && ($number!=$foundgiven)) {
                   9177:        $result.='<span class="LC_error">'.&mt('Number of given answers does not agree with number of questions in file.').'</span>';
                   9178:        return $result.&show_grading_menu_form($symb);
                   9179:     } 
1.414     www      9180: # Remember Question Titles
                   9181: # FIXME: Possibly need delimiter other than ":"
                   9182:     for (my $i=0;$i<$number;$i++) {
                   9183:         $result.='<input type="hidden" name="question:'.$i.'" value="'.
                   9184:                  &HTML::Entities::encode($questiontitles[$i],'"&<>').'" />';
                   9185:     }
1.411     www      9186:     my $correct_count=0;
                   9187:     my $student_count=0;
                   9188:     my $unknown_count=0;
1.414     www      9189: # Match answers with usernames
                   9190: # FIXME: Possibly need delimiter other than ":"
1.409     albertel 9191:     foreach my $id (keys(%responses)) {
1.410     www      9192:        if ($correct_ids{$id}) {
1.414     www      9193:           $result.="\n".'<input type="hidden" name="correct:'.$correct_count.':'.$correct_ids{$id}.'" value="'.$responses{$id}.'" />';
1.411     www      9194:           $correct_count++;
1.410     www      9195:        } elsif ($clicker_ids{$id}) {
1.437     www      9196:           if ($clicker_ids{$id}=~/\,/) {
                   9197: # More than one user with the same clicker!
                   9198:              $result.="\n<hr />".&mt('Clicker registered more than once').": <tt>".$id."</tt><br />";
                   9199:              $result.="\n".'<input type="hidden" name="unknown:'.$id.'" value="'.$responses{$id}.'" />'.
                   9200:                            "<select name='multi".$id."'>";
                   9201:              foreach my $reguser (sort(split(/\,/,$clicker_ids{$id}))) {
                   9202:                  $result.="<option value='".$reguser."'>".&Apache::loncommon::plainname(split(/\:/,$reguser)).' ('.$reguser.')</option>';
                   9203:              }
                   9204:              $result.='</select>';
                   9205:              $unknown_count++;
                   9206:           } else {
                   9207: # Good: found one and only one user with the right clicker
                   9208:              $result.="\n".'<input type="hidden" name="student:'.$clicker_ids{$id}.'" value="'.$responses{$id}.'" />';
                   9209:              $student_count++;
                   9210:           }
1.410     www      9211:        } else {
1.411     www      9212:           $result.="\n<hr />".&mt('Unregistered Clicker')." <tt>".$id."</tt><br />";
                   9213:           $result.="\n".'<input type="hidden" name="unknown:'.$id.'" value="'.$responses{$id}.'" />'.
                   9214:                    "\n".&mt("Username").": <input type='text' name='uname".$id."' />&nbsp;".
                   9215:                    "\n".&mt("Domain").": ".
                   9216:                    &Apache::loncommon::select_dom_form($env{'course.'.$env{'request.course.id'}.'.domain'},'udom'.$id).'&nbsp;'.
                   9217:                    &Apache::loncommon::selectstudent_link('clickeranalysis','uname'.$id,'udom'.$id);
                   9218:           $unknown_count++;
1.410     www      9219:        }
1.405     www      9220:     }
1.412     www      9221:     $result.='<hr />'.
                   9222:              &mt('Found [_1] registered and [_2] unregistered clickers.',$student_count,$unknown_count);
1.521     www      9223:     if (($env{'form.gradingmechanism'} ne 'attendance') && ($env{'form.gradingmechanism'} ne 'given')) {
1.412     www      9224:        if ($correct_count==0) {
                   9225:           $errormsg.="Found no correct answers answers for grading!";
                   9226:        } elsif ($correct_count>1) {
1.414     www      9227:           $result.='<br /><span class="LC_warning">'.&mt("Found [_1] entries for grading!",$correct_count).'</span>';
1.412     www      9228:        }
                   9229:     }
1.428     www      9230:     if ($number<1) {
                   9231:        $errormsg.="Found no questions.";
                   9232:     }
1.412     www      9233:     if ($errormsg) {
                   9234:        $result.='<br /><span class="LC_error">'.&mt($errormsg).'</span>';
                   9235:     } else {
                   9236:        $result.='<br /><input type="submit" name="finalize" value="'.&mt('Finalize Grading').'" />';
                   9237:     }
                   9238:     $result.='</form></td></tr></table>'."\n".
1.410     www      9239:              '</td></tr></table><br /><br />'."\n";
1.404     www      9240:     return $result.&show_grading_menu_form($symb);
1.400     www      9241: }
                   9242: 
1.405     www      9243: sub iclicker_eval {
1.406     www      9244:     my ($questiontitles,$responses)=@_;
1.405     www      9245:     my $number=0;
                   9246:     my $errormsg='';
                   9247:     foreach my $line (split(/[\n\r]/,$env{'form.upfile'})) {
1.410     www      9248:         my %components=&Apache::loncommon::record_sep($line);
                   9249:         my @entries=map {$components{$_}} (sort(keys(%components)));
1.408     albertel 9250: 	if ($entries[0] eq 'Question') {
                   9251: 	    for (my $i=3;$i<$#entries;$i+=6) {
                   9252: 		$$questiontitles[$number]=$entries[$i];
                   9253: 		$number++;
                   9254: 	    }
                   9255: 	}
                   9256: 	if ($entries[0]=~/^\#/) {
                   9257: 	    my $id=$entries[0];
                   9258: 	    my @idresponses;
                   9259: 	    $id=~s/^[\#0]+//;
                   9260: 	    for (my $i=0;$i<$number;$i++) {
                   9261: 		my $idx=3+$i*6;
                   9262: 		push(@idresponses,$entries[$idx]);
                   9263: 	    }
                   9264: 	    $$responses{$id}=join(',',@idresponses);
                   9265: 	}
1.405     www      9266:     }
                   9267:     return ($errormsg,$number);
                   9268: }
                   9269: 
1.419     www      9270: sub interwrite_eval {
                   9271:     my ($questiontitles,$responses)=@_;
                   9272:     my $number=0;
                   9273:     my $errormsg='';
1.420     www      9274:     my $skipline=1;
                   9275:     my $questionnumber=0;
                   9276:     my %idresponses=();
1.419     www      9277:     foreach my $line (split(/[\n\r]/,$env{'form.upfile'})) {
                   9278:         my %components=&Apache::loncommon::record_sep($line);
                   9279:         my @entries=map {$components{$_}} (sort(keys(%components)));
1.420     www      9280:         if ($entries[1] eq 'Time') { $skipline=0; next; }
                   9281:         if ($entries[1] eq 'Response') { $skipline=1; }
                   9282:         next if $skipline;
                   9283:         if ($entries[0]!=$questionnumber) {
                   9284:            $questionnumber=$entries[0];
                   9285:            $$questiontitles[$number]=&mt('Question [_1]',$questionnumber);
                   9286:            $number++;
1.419     www      9287:         }
1.420     www      9288:         my $id=$entries[4];
                   9289:         $id=~s/^[\#0]+//;
1.421     www      9290:         $id=~s/^v\d*\://i;
                   9291:         $id=~s/[\-\:]//g;
1.420     www      9292:         $idresponses{$id}[$number]=$entries[6];
                   9293:     }
1.524     raeburn  9294:     foreach my $id (keys(%idresponses)) {
1.420     www      9295:        $$responses{$id}=join(',',@{$idresponses{$id}});
                   9296:        $$responses{$id}=~s/^\s*\,//;
1.419     www      9297:     }
                   9298:     return ($errormsg,$number);
                   9299: }
                   9300: 
1.414     www      9301: sub assign_clicker_grades {
                   9302:     my ($r)=@_;
                   9303:     my ($symb)=&get_symb($r);
                   9304:     if (!$symb) {return '';}
1.416     www      9305: # See which part we are saving to
1.582     raeburn  9306:     my $res_error;
                   9307:     my ($partlist,$handgrade,$responseType) = &response_type($symb,\$res_error);
                   9308:     if ($res_error) {
                   9309:         return &navmap_errormsg();
                   9310:     }
1.416     www      9311: # FIXME: This should probably look for the first handgradeable part
                   9312:     my $part=$$partlist[0];
                   9313: # Start screen output
1.414     www      9314:     my ($result) = &showResourceInfo($symb,$env{'form.probTitle'});
1.416     www      9315: 
1.414     www      9316:     my $heading=&mt('Assigning grades based on clicker file');
                   9317:     $result.=(<<ENDHEADER);
                   9318: <br /><table width="100%" border="0"><tr><td bgcolor="#777777">
                   9319: <table width="100%" border="0"><tr bgcolor="#e6ffff"><td>
                   9320: <b>$heading</b></td></tr><tr bgcolor=#ffffe6><td>
                   9321: ENDHEADER
                   9322: # Get correct result
                   9323: # FIXME: Possibly need delimiter other than ":"
                   9324:     my @correct=();
1.415     www      9325:     my $gradingmechanism=$env{'form.gradingmechanism'};
                   9326:     my $number=$env{'form.number'};
                   9327:     if ($gradingmechanism ne 'attendance') {
1.414     www      9328:        foreach my $key (keys(%env)) {
                   9329:           if ($key=~/^form\.correct\:/) {
                   9330:              my @input=split(/\,/,$env{$key});
                   9331:              for (my $i=0;$i<=$#input;$i++) {
                   9332:                  if (($correct[$i]) && ($input[$i]) &&
                   9333:                      ($correct[$i] ne $input[$i])) {
                   9334:                     $result.='<br /><span class="LC_warning">'.
                   9335:                              &mt('More than one correct result given for question "[_1]": [_2] versus [_3].',
                   9336:                                  $env{'form.question:'.$i},$correct[$i],$input[$i]).'</span>';
                   9337:                  } elsif ($input[$i]) {
                   9338:                     $correct[$i]=$input[$i];
                   9339:                  }
                   9340:              }
                   9341:           }
                   9342:        }
1.415     www      9343:        for (my $i=0;$i<$number;$i++) {
1.414     www      9344:           if (!$correct[$i]) {
                   9345:              $result.='<br /><span class="LC_error">'.
                   9346:                       &mt('No correct result given for question "[_1]"!',
                   9347:                           $env{'form.question:'.$i}).'</span>';
                   9348:           }
                   9349:        }
                   9350:        $result.='<br />'.&mt("Correct answer: [_1]",join(', ',map { ($_?$_:'-') } @correct));
                   9351:     }
                   9352: # Start grading
1.415     www      9353:     my $pcorrect=$env{'form.pcorrect'};
                   9354:     my $pincorrect=$env{'form.pincorrect'};
1.416     www      9355:     my $storecount=0;
1.415     www      9356:     foreach my $key (keys(%env)) {
1.420     www      9357:        my $user='';
1.415     www      9358:        if ($key=~/^form\.student\:(.*)$/) {
1.420     www      9359:           $user=$1;
                   9360:        }
                   9361:        if ($key=~/^form\.unknown\:(.*)$/) {
                   9362:           my $id=$1;
                   9363:           if (($env{'form.uname'.$id}) && ($env{'form.udom'.$id})) {
                   9364:              $user=$env{'form.uname'.$id}.':'.$env{'form.udom'.$id};
1.437     www      9365:           } elsif ($env{'form.multi'.$id}) {
                   9366:              $user=$env{'form.multi'.$id};
1.420     www      9367:           }
                   9368:        }
                   9369:        if ($user) { 
1.415     www      9370:           my @answer=split(/\,/,$env{$key});
                   9371:           my $sum=0;
1.522     www      9372:           my $realnumber=$number;
1.415     www      9373:           for (my $i=0;$i<$number;$i++) {
1.576     www      9374:              if  ($correct[$i] eq '-') {
                   9375:                 $realnumber--;
                   9376:              } elsif ($answer[$i]) {
1.415     www      9377:                 if ($gradingmechanism eq 'attendance') {
                   9378:                    $sum+=$pcorrect;
1.576     www      9379:                 } elsif ($correct[$i] eq '*') {
1.522     www      9380:                    $sum+=$pcorrect;
1.415     www      9381:                 } else {
                   9382:                    if ($answer[$i] eq $correct[$i]) {
                   9383:                       $sum+=$pcorrect;
                   9384:                    } else {
                   9385:                       $sum+=$pincorrect;
                   9386:                    }
                   9387:                 }
                   9388:              }
                   9389:           }
1.522     www      9390:           my $ave=$sum/(100*$realnumber);
1.416     www      9391: # Store
                   9392:           my ($username,$domain)=split(/\:/,$user);
                   9393:           my %grades=();
                   9394:           $grades{"resource.$part.solved"}='correct_by_override';
                   9395:           $grades{"resource.$part.awarded"}=$ave;
                   9396:           $grades{"resource.regrader"}="$env{'user.name'}:$env{'user.domain'}";
                   9397:           my $returncode=&Apache::lonnet::cstore(\%grades,$symb,
                   9398:                                                  $env{'request.course.id'},
                   9399:                                                  $domain,$username);
                   9400:           if ($returncode ne 'ok') {
                   9401:              $result.="<br /><span class=\"LC_error\">Failed to save student $username:$domain. Message when trying to save was ($returncode)</span>";
                   9402:           } else {
                   9403:              $storecount++;
                   9404:           }
1.415     www      9405:        }
                   9406:     }
                   9407: # We are done
1.549     hauer    9408:     $result.='<br />'.&mt('Successfully stored grades for [quant,_1,student].',$storecount).
1.416     www      9409:              '</td></tr></table>'."\n".
1.414     www      9410:              '</td></tr></table><br /><br />'."\n";
                   9411:     return $result.&show_grading_menu_form($symb);
                   9412: }
                   9413: 
1.582     raeburn  9414: sub navmap_errormsg {
                   9415:     return '<div class="LC_error">'.
                   9416:            &mt('An error occurred retrieving information about resources in the course.').'<br />'.
1.595     raeburn  9417:            &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  9418:            '</div>';
                   9419: }
                   9420: 
1.1       albertel 9421: sub handler {
1.41      ng       9422:     my $request=$_[0];
1.434     albertel 9423:     &reset_caches();
1.257     albertel 9424:     if ($env{'browser.mathml'}) {
1.141     www      9425: 	&Apache::loncommon::content_type($request,'text/xml');
1.41      ng       9426:     } else {
1.141     www      9427: 	&Apache::loncommon::content_type($request,'text/html');
1.41      ng       9428:     }
                   9429:     $request->send_http_header;
1.44      ng       9430:     return '' if $request->header_only;
1.41      ng       9431:     &Apache::loncommon::get_unprocessed_cgi($ENV{'QUERY_STRING'});
1.324     albertel 9432:     my $symb=&get_symb($request,1);
1.160     albertel 9433:     my @commands=&Apache::loncommon::get_env_multiple('form.command');
                   9434:     my $command=$commands[0];
1.447     foxr     9435: 
1.160     albertel 9436:     if ($#commands > 0) {
                   9437: 	&Apache::lonnet::logthis("grades got multiple commands ".join(':',@commands));
                   9438:     }
1.447     foxr     9439: 
1.513     foxr     9440:     $ssi_error = 0;
1.535     raeburn  9441:     my $brcrum = [{href=>"/adm/grades",text=>"Grading"}];
                   9442:     $request->print(&Apache::loncommon::start_page('Grading',undef,
                   9443:                                           {'bread_crumbs' => $brcrum}));
1.324     albertel 9444:     if ($symb eq '' && $command eq '') {
1.257     albertel 9445: 	if ($env{'user.adv'}) {
                   9446: 	    if (($env{'form.codeone'}) && ($env{'form.codetwo'}) &&
                   9447: 		($env{'form.codethree'})) {
                   9448: 		my $token=$env{'form.codeone'}.'*'.$env{'form.codetwo'}.'*'.
                   9449: 		    $env{'form.codethree'};
1.41      ng       9450: 		my ($tsymb,$tuname,$tudom,$tcrsid)=
                   9451: 		    &Apache::lonnet::checkin($token);
                   9452: 		if ($tsymb) {
1.137     albertel 9453: 		    my ($map,$id,$url)=&Apache::lonnet::decode_symb($tsymb);
1.41      ng       9454: 		    if (&Apache::lonnet::allowed('mgr',$tcrsid)) {
1.513     foxr     9455: 			$request->print(&ssi_with_retries('/res/'.$url, $ssi_retries,
1.99      albertel 9456: 					  ('grade_username' => $tuname,
                   9457: 					   'grade_domain' => $tudom,
                   9458: 					   'grade_courseid' => $tcrsid,
                   9459: 					   'grade_symb' => $tsymb)));
1.41      ng       9460: 		    } else {
1.45      ng       9461: 			$request->print('<h3>Not authorized: '.$token.'</h3>');
1.99      albertel 9462: 		    }
1.41      ng       9463: 		} else {
1.45      ng       9464: 		    $request->print('<h3>Not a valid DocID: '.$token.'</h3>');
1.41      ng       9465: 		}
1.14      www      9466: 	    } else {
1.41      ng       9467: 		$request->print(&Apache::lonxml::tokeninputfield());
                   9468: 	    }
                   9469: 	}
                   9470:     } else {
1.285     albertel 9471: 	&init_perm();
1.104     albertel 9472: 	if ($command eq 'submission' && $perm{'vgr'}) {
1.257     albertel 9473: 	    ($env{'form.student'} eq '' ? &listStudents($request) : &submission($request,0,0));
1.103     albertel 9474: 	} elsif ($command eq 'pickStudentPage' && $perm{'vgr'}) {
1.68      ng       9475: 	    &pickStudentPage($request);
1.103     albertel 9476: 	} elsif ($command eq 'displayPage' && $perm{'vgr'}) {
1.68      ng       9477: 	    &displayPage($request);
1.104     albertel 9478: 	} elsif ($command eq 'gradeByPage' && $perm{'mgr'}) {
1.71      ng       9479: 	    &updateGradeByPage($request);
1.104     albertel 9480: 	} elsif ($command eq 'processGroup' && $perm{'vgr'}) {
1.41      ng       9481: 	    &processGroup($request);
1.104     albertel 9482: 	} elsif ($command eq 'gradingmenu' && $perm{'vgr'}) {
1.443     banghart 9483: 	    $request->print(&grading_menu($request));
                   9484: 	} elsif ($command eq 'submit_options' && $perm{'vgr'}) {
                   9485: 	    $request->print(&submit_options($request));
1.104     albertel 9486: 	} elsif ($command eq 'viewgrades' && $perm{'vgr'}) {
1.41      ng       9487: 	    $request->print(&viewgrades($request));
1.104     albertel 9488: 	} elsif ($command eq 'handgrade' && $perm{'mgr'}) {
1.41      ng       9489: 	    $request->print(&processHandGrade($request));
1.106     albertel 9490: 	} elsif ($command eq 'editgrades' && $perm{'mgr'}) {
1.41      ng       9491: 	    $request->print(&editgrades($request));
1.106     albertel 9492: 	} elsif ($command eq 'verify' && $perm{'vgr'}) {
1.41      ng       9493: 	    $request->print(&verifyreceipt($request));
1.400     www      9494:         } elsif ($command eq 'processclicker' && $perm{'mgr'}) {
                   9495:             $request->print(&process_clicker($request));
                   9496:         } elsif ($command eq 'processclickerfile' && $perm{'mgr'}) {
                   9497:             $request->print(&process_clicker_file($request));
1.414     www      9498:         } elsif ($command eq 'assignclickergrades' && $perm{'mgr'}) {
                   9499:             $request->print(&assign_clicker_grades($request));
1.106     albertel 9500: 	} elsif ($command eq 'csvform' && $perm{'mgr'}) {
1.72      ng       9501: 	    $request->print(&upcsvScores_form($request));
1.106     albertel 9502: 	} elsif ($command eq 'csvupload' && $perm{'mgr'}) {
1.41      ng       9503: 	    $request->print(&csvupload($request));
1.106     albertel 9504: 	} elsif ($command eq 'csvuploadmap' && $perm{'mgr'} ) {
1.41      ng       9505: 	    $request->print(&csvuploadmap($request));
1.246     albertel 9506: 	} elsif ($command eq 'csvuploadoptions' && $perm{'mgr'}) {
1.257     albertel 9507: 	    if ($env{'form.associate'} ne 'Reverse Association') {
1.246     albertel 9508: 		$request->print(&csvuploadoptions($request));
1.41      ng       9509: 	    } else {
1.257     albertel 9510: 		if ( $env{'form.upfile_associate'} ne 'reverse' ) {
                   9511: 		    $env{'form.upfile_associate'} = 'reverse';
1.41      ng       9512: 		} else {
1.257     albertel 9513: 		    $env{'form.upfile_associate'} = 'forward';
1.41      ng       9514: 		}
                   9515: 		$request->print(&csvuploadmap($request));
                   9516: 	    }
1.246     albertel 9517: 	} elsif ($command eq 'csvuploadassign' && $perm{'mgr'} ) {
                   9518: 	    $request->print(&csvuploadassign($request));
1.106     albertel 9519: 	} elsif ($command eq 'scantron_selectphase' && $perm{'mgr'}) {
1.75      albertel 9520: 	    $request->print(&scantron_selectphase($request));
1.203     albertel 9521:  	} elsif ($command eq 'scantron_warning' && $perm{'mgr'}) {
                   9522:  	    $request->print(&scantron_do_warning($request));
1.142     albertel 9523: 	} elsif ($command eq 'scantron_validate' && $perm{'mgr'}) {
                   9524: 	    $request->print(&scantron_validate_file($request));
1.106     albertel 9525: 	} elsif ($command eq 'scantron_process' && $perm{'mgr'}) {
1.82      albertel 9526: 	    $request->print(&scantron_process_students($request));
1.157     albertel 9527:  	} elsif ($command eq 'scantronupload' && 
1.257     albertel 9528:  		 (&Apache::lonnet::allowed('usc',$env{'request.role.domain'})||
                   9529: 		  &Apache::lonnet::allowed('usc',$env{'request.course.id'}))) {
1.162     albertel 9530:  	    $request->print(&scantron_upload_scantron_data($request)); 
1.157     albertel 9531:  	} elsif ($command eq 'scantronupload_save' &&
1.257     albertel 9532:  		 (&Apache::lonnet::allowed('usc',$env{'request.role.domain'})||
                   9533: 		  &Apache::lonnet::allowed('usc',$env{'request.course.id'}))) {
1.157     albertel 9534:  	    $request->print(&scantron_upload_scantron_data_save($request));
1.202     albertel 9535:  	} elsif ($command eq 'scantron_download' &&
1.257     albertel 9536: 		 &Apache::lonnet::allowed('usc',$env{'request.course.id'})) {
1.162     albertel 9537:  	    $request->print(&scantron_download_scantron_data($request));
1.523     raeburn  9538:         } elsif ($command eq 'checksubmissions' && $perm{'vgr'}) {
                   9539:             $request->print(&checkscantron_results($request));     
1.106     albertel 9540: 	} elsif ($command) {
1.562     bisitz   9541: 	    $request->print('<p class="LC_error">'.&mt('Access Denied ([_1])',$command).'</p>');
1.26      albertel 9542: 	}
1.2       albertel 9543:     }
1.513     foxr     9544:     if ($ssi_error) {
                   9545: 	&ssi_print_error($request);
                   9546:     }
1.353     albertel 9547:     $request->print(&Apache::loncommon::end_page());
1.434     albertel 9548:     &reset_caches();
1.44      ng       9549:     return '';
                   9550: }
                   9551: 
1.1       albertel 9552: 1;
                   9553: 
1.13      albertel 9554: __END__;
1.531     jms      9555: 
                   9556: 
                   9557: =head1 NAME
                   9558: 
                   9559: Apache::grades
                   9560: 
                   9561: =head1 SYNOPSIS
                   9562: 
                   9563: Handles the viewing of grades.
                   9564: 
                   9565: This is part of the LearningOnline Network with CAPA project
                   9566: described at http://www.lon-capa.org.
                   9567: 
                   9568: =head1 OVERVIEW
                   9569: 
                   9570: Do an ssi with retries:
                   9571: While I'd love to factor out this with the vesrion in lonprintout,
                   9572: 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
                   9573: I'm not quite ready to invent (e.g. an ssi_with_retry object).
                   9574: 
                   9575: At least the logic that drives this has been pulled out into loncommon.
                   9576: 
                   9577: 
                   9578: 
                   9579: ssi_with_retries - Does the server side include of a resource.
                   9580:                      if the ssi call returns an error we'll retry it up to
                   9581:                      the number of times requested by the caller.
                   9582:                      If we still have a proble, no text is appended to the
                   9583:                      output and we set some global variables.
                   9584:                      to indicate to the caller an SSI error occurred.  
                   9585:                      All of this is supposed to deal with the issues described
                   9586:                      in LonCAPA BZ 5631 see:
                   9587:                      http://bugs.lon-capa.org/show_bug.cgi?id=5631
                   9588:                      by informing the user that this happened.
                   9589: 
                   9590: Parameters:
                   9591:   resource   - The resource to include.  This is passed directly, without
                   9592:                interpretation to lonnet::ssi.
                   9593:   form       - The form hash parameters that guide the interpretation of the resource
                   9594:                
                   9595:   retries    - Number of retries allowed before giving up completely.
                   9596: Returns:
                   9597:   On success, returns the rendered resource identified by the resource parameter.
                   9598: Side Effects:
                   9599:   The following global variables can be set:
                   9600:    ssi_error                - If an unrecoverable error occurred this becomes true.
                   9601:                               It is up to the caller to initialize this to false
                   9602:                               if desired.
                   9603:    ssi_error_resource  - If an unrecoverable error occurred, this is the value
                   9604:                               of the resource that could not be rendered by the ssi
                   9605:                               call.
                   9606:    ssi_error_message   - The error string fetched from the ssi response
                   9607:                               in the event of an error.
                   9608: 
                   9609: 
                   9610: =head1 HANDLER SUBROUTINE
                   9611: 
                   9612: ssi_with_retries()
                   9613: 
                   9614: =head1 SUBROUTINES
                   9615: 
                   9616: =over
                   9617: 
                   9618: =item scantron_get_correction() : 
                   9619: 
                   9620:    Builds the interface screen to interact with the operator to fix a
                   9621:    specific error condition in a specific scanline
                   9622: 
                   9623:  Arguments:
                   9624:     $r           - Apache request object
                   9625:     $i           - number of the current scanline
                   9626:     $scan_record - hash ref as returned from &scantron_parse_scanline()
                   9627:     $scan_config - hash ref as returned from &get_scantron_config()
                   9628:     $line        - full contents of the current scanline
                   9629:     $error       - error condition, valid values are
                   9630:                    'incorrectCODE', 'duplicateCODE',
                   9631:                    'doublebubble', 'missingbubble',
                   9632:                    'duplicateID', 'incorrectID'
                   9633:     $arg         - extra information needed
                   9634:        For errors:
                   9635:          - duplicateID   - paper number that this studentID was seen before on
                   9636:          - duplicateCODE - array ref of the paper numbers this CODE was
                   9637:                            seen on before
                   9638:          - incorrectCODE - current incorrect CODE 
                   9639:          - doublebubble  - array ref of the bubble lines that have double
                   9640:                            bubble errors
                   9641:          - missingbubble - array ref of the bubble lines that have missing
                   9642:                            bubble errors
                   9643: 
                   9644: =item  scantron_get_maxbubble() : 
                   9645: 
1.582     raeburn  9646:    Arguments:
                   9647:        $nav_error  - Reference to scalar which is a flag to indicate a
                   9648:                       failure to retrieve a navmap object.
                   9649:        if $nav_error is set to 1 by scantron_get_maxbubble(), the 
                   9650:        calling routine should trap the error condition and display the warning
                   9651:        found in &navmap_errormsg().
                   9652: 
1.531     jms      9653:    Returns the maximum number of bubble lines that are expected to
                   9654:    occur. Does this by walking the selected sequence rendering the
                   9655:    resource and then checking &Apache::lonxml::get_problem_counter()
                   9656:    for what the current value of the problem counter is.
                   9657: 
                   9658:    Caches the results to $env{'form.scantron_maxbubble'},
                   9659:    $env{'form.scantron.bubble_lines.n'}, 
                   9660:    $env{'form.scantron.first_bubble_line.n'} and
                   9661:    $env{"form.scantron.sub_bubblelines.n"}
                   9662:    which are the total number of bubble, lines, the number of bubble
                   9663:    lines for response n and number of the first bubble line for response n,
                   9664:    and a comma separated list of numbers of bubble lines for sub-questions
                   9665:    (for optionresponse, matchresponse, and rankresponse items), for response n.  
                   9666: 
                   9667: 
                   9668: =item  scantron_validate_missingbubbles() : 
                   9669: 
                   9670:    Validates all scanlines in the selected file to not have any
                   9671:     answers that don't have bubbles that have not been verified
                   9672:     to be bubble free.
                   9673: 
                   9674: =item  scantron_process_students() : 
                   9675: 
                   9676:    Routine that does the actual grading of the bubble sheet information.
                   9677: 
                   9678:    The parsed scanline hash is added to %env 
                   9679: 
                   9680:    Then foreach unskipped scanline it does an &Apache::lonnet::ssi()
                   9681:    foreach resource , with the form data of
                   9682: 
                   9683: 	'submitted'     =>'scantron' 
                   9684: 	'grade_target'  =>'grade',
                   9685: 	'grade_username'=> username of student
                   9686: 	'grade_domain'  => domain of student
                   9687: 	'grade_courseid'=> of course
                   9688: 	'grade_symb'    => symb of resource to grade
                   9689: 
                   9690:     This triggers a grading pass. The problem grading code takes care
                   9691:     of converting the bubbled letter information (now in %env) into a
                   9692:     valid submission.
                   9693: 
                   9694: =item  scantron_upload_scantron_data() :
                   9695: 
                   9696:     Creates the screen for adding a new bubble sheet data file to a course.
                   9697: 
                   9698: =item  scantron_upload_scantron_data_save() : 
                   9699: 
                   9700:    Adds a provided bubble information data file to the course if user
                   9701:    has the correct privileges to do so. 
                   9702: 
                   9703: =item  valid_file() :
                   9704: 
                   9705:    Validates that the requested bubble data file exists in the course.
                   9706: 
                   9707: =item  scantron_download_scantron_data() : 
                   9708: 
                   9709:    Shows a list of the three internal files (original, corrected,
                   9710:    skipped) for a specific bubble sheet data file that exists in the
                   9711:    course.
                   9712: 
                   9713: =item  scantron_validate_ID() : 
                   9714: 
                   9715:    Validates all scanlines in the selected file to not have any
1.556     weissno  9716:    invalid or underspecified student/employee IDs
1.531     jms      9717: 
1.582     raeburn  9718: =item navmap_errormsg() :
                   9719: 
                   9720:    Returns HTML mark-up inside a <div></div> with a link to re-initialize the course.
                   9721:    Should be called whenever the request to instantiate a navmap object fails.  
                   9722: 
1.531     jms      9723: =back
                   9724: 
                   9725: =cut

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