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

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.13! raeburn     4: # $Id: grades.pm,v 1.596.2.12 2011/12/01 00:36: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.596.2.4  raeburn    43: use Apache::Constants qw(:common :http);
1.167     sakharuk   44: use Apache::lonlocal;
1.386     raeburn    45: use Apache::lonenc;
1.596.2.4  raeburn    46: use Apache::bridgetask();
1.170     albertel   47: use String::Similarity;
1.359     www        48: use LONCAPA;
                     49: 
1.315     bowersj2   50: use POSIX qw(floor);
1.87      www        51: 
1.435     foxr       52: 
1.513     foxr       53: 
1.435     foxr       54: my %perm=();
1.596.2.13! raeburn    55: my %old_essays=();
1.447     foxr       56: 
1.513     foxr       57: #  These variables are used to recover from ssi errors
                     58: 
                     59: my $ssi_retries = 5;
                     60: my $ssi_error;
                     61: my $ssi_error_resource;
                     62: my $ssi_error_message;
                     63: 
                     64: 
                     65: sub ssi_with_retries {
                     66:     my ($resource, $retries, %form) = @_;
                     67:     my ($content, $response) = &Apache::loncommon::ssi_with_retries($resource, $retries, %form);
                     68:     if ($response->is_error) {
                     69: 	$ssi_error          = 1;
                     70: 	$ssi_error_resource = $resource;
                     71: 	$ssi_error_message  = $response->code . " " . $response->message;
                     72:     }
                     73: 
                     74:     return $content;
                     75: 
                     76: }
                     77: #
                     78: #  Prodcuces an ssi retry failure error message to the user:
                     79: #
                     80: 
                     81: sub ssi_print_error {
                     82:     my ($r) = @_;
1.516     raeburn    83:     my $helpurl = &Apache::loncommon::top_nav_help('Helpdesk');
                     84:     $r->print('
                     85: <br />
                     86: <h2>'.&mt('An unrecoverable network error occurred:').'</h2>
                     87: <p>
                     88: '.&mt('Unable to retrieve a resource from a server:').'<br />
                     89: '.&mt('Resource:').' '.$ssi_error_resource.'<br />
                     90: '.&mt('Error:').' '.$ssi_error_message.'
                     91: </p>
                     92: <p>'.
                     93: &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 />'.
                     94: &mt('If the error persists, please contact the [_1] for assistance.',$helpurl).
                     95: '</p>');
                     96:     return;
1.513     foxr       97: }
                     98: 
1.44      ng         99: #
1.146     albertel  100: # --- Retrieve the parts from the metadata file.---
1.44      ng        101: sub getpartlist {
1.582     raeburn   102:     my ($symb,$errorref) = @_;
1.439     albertel  103: 
                    104:     my $navmap   = Apache::lonnavmaps::navmap->new();
1.582     raeburn   105:     unless (ref($navmap)) {
                    106:         if (ref($errorref)) { 
                    107:             $$errorref = 'navmap';
                    108:             return;
                    109:         }
                    110:     }
1.439     albertel  111:     my $res      = $navmap->getBySymb($symb);
                    112:     my $partlist = $res->parts();
                    113:     my $url      = $res->src();
                    114:     my @metakeys = split(/,/,&Apache::lonnet::metadata($url,'keys'));
                    115: 
1.146     albertel  116:     my @stores;
1.439     albertel  117:     foreach my $part (@{ $partlist }) {
1.146     albertel  118: 	foreach my $key (@metakeys) {
                    119: 	    if ($key =~ m/^stores_\Q$part\E_/) { push(@stores,$key); }
                    120: 	}
                    121:     }
                    122:     return @stores;
1.2       albertel  123: }
                    124: 
1.44      ng        125: # --- Get the symbolic name of a problem and the url
1.324     albertel  126: sub get_symb {
1.173     albertel  127:     my ($request,$silent) = @_;
1.257     albertel  128:     (my $url=$env{'form.url'}) =~ s-^http://($ENV{'SERVER_NAME'}|$ENV{'HTTP_HOST'})--;
                    129:     my $symb=($env{'form.symb'} ne '' ? $env{'form.symb'} : (&Apache::lonnet::symbread($url)));
1.173     albertel  130:     if ($symb eq '') { 
                    131: 	if (!$silent) {
1.596.2.4  raeburn   132:             $request->print(&mt("Unable to handle ambiguous references: [_1].",$url));
1.173     albertel  133: 	    return ();
                    134: 	}
                    135:     }
1.418     albertel  136:     &Apache::lonenc::check_decrypt(\$symb);
1.324     albertel  137:     return ($symb);
1.32      ng        138: }
                    139: 
1.129     ng        140: #--- Format fullname, username:domain if different for display
                    141: #--- Use anywhere where the student names are listed
                    142: sub nameUserString {
                    143:     my ($type,$fullname,$uname,$udom) = @_;
                    144:     if ($type eq 'header') {
1.485     albertel  145: 	return '<b>&nbsp;'.&mt('Fullname').'&nbsp;</b><span class="LC_internal_info">('.&mt('Username').')</span>';
1.129     ng        146:     } else {
1.398     albertel  147: 	return '&nbsp;'.$fullname.'<span class="LC_internal_info">&nbsp;('.$uname.
                    148: 	    ($env{'user.domain'} eq $udom ? '' : ' ('.$udom.')').')</span>';
1.129     ng        149:     }
                    150: }
                    151: 
1.44      ng        152: #--- Get the partlist and the response type for a given problem. ---
                    153: #--- Indicate if a response type is coded handgraded or not. ---
1.39      ng        154: sub response_type {
1.582     raeburn   155:     my ($symb,$response_error) = @_;
1.377     albertel  156: 
                    157:     my $navmap = Apache::lonnavmaps::navmap->new();
1.582     raeburn   158:     unless (ref($navmap)) {
                    159:         if (ref($response_error)) {
                    160:             $$response_error = 1;
                    161:         }
                    162:         return;
                    163:     }
1.377     albertel  164:     my $res = $navmap->getBySymb($symb);
1.593     raeburn   165:     unless (ref($res)) {
                    166:         $$response_error = 1;
                    167:         return;
                    168:     }
1.377     albertel  169:     my $partlist = $res->parts();
1.392     albertel  170:     my %vPart = 
                    171: 	map { $_ => 1 } (&Apache::loncommon::get_env_multiple('form.vPart'));
1.377     albertel  172:     my (%response_types,%handgrade);
                    173:     foreach my $part (@{ $partlist }) {
1.392     albertel  174: 	next if (%vPart && !exists($vPart{$part}));
                    175: 
1.377     albertel  176: 	my @types = $res->responseType($part);
                    177: 	my @ids = $res->responseIds($part);
                    178: 	for (my $i=0; $i < scalar(@ids); $i++) {
                    179: 	    $response_types{$part}{$ids[$i]} = $types[$i];
                    180: 	    $handgrade{$part.'_'.$ids[$i]} = 
                    181: 		&Apache::lonnet::EXT('resource.'.$part.'_'.$ids[$i].
                    182: 				     '.handgrade',$symb);
1.41      ng        183: 	}
                    184:     }
1.377     albertel  185:     return ($partlist,\%handgrade,\%response_types);
1.39      ng        186: }
                    187: 
1.375     albertel  188: sub flatten_responseType {
                    189:     my ($responseType) = @_;
                    190:     my @part_response_id =
                    191: 	map { 
                    192: 	    my $part = $_;
                    193: 	    map {
                    194: 		[$part,$_]
                    195: 		} sort(keys(%{ $responseType->{$part} }));
                    196: 	} sort(keys(%$responseType));
                    197:     return @part_response_id;
                    198: }
                    199: 
1.207     albertel  200: sub get_display_part {
1.324     albertel  201:     my ($partID,$symb)=@_;
1.207     albertel  202:     my $display=&Apache::lonnet::EXT('resource.'.$partID.'.display',$symb);
                    203:     if (defined($display) and $display ne '') {
1.577     bisitz    204:         $display.= ' (<span class="LC_internal_info">'
                    205:                   .&mt('Part ID: [_1]',$partID).'</span>)';
1.207     albertel  206:     } else {
                    207: 	$display=$partID;
                    208:     }
                    209:     return $display;
                    210: }
1.269     raeburn   211: 
1.118     ng        212: #--- Show resource title
                    213: #--- and parts and response type
                    214: sub showResourceInfo {
1.582     raeburn   215:     my ($symb,$probTitle,$checkboxes,$res_error) = @_;
1.398     albertel  216:     my $result = '<h3>'.&mt('Current Resource').': '.$probTitle.'</h3>'."\n";
1.582     raeburn   217:     my ($partlist,$handgrade,$responseType) = &response_type($symb,$res_error);
                    218:     if (ref($res_error)) {
                    219:         if ($$res_error) {
                    220:             return;
                    221:         }
                    222:     }
1.584     bisitz    223:     $result.=&Apache::loncommon::start_data_table()
                    224:             .&Apache::loncommon::start_data_table_header_row();
                    225:     if ($checkboxes) {
                    226:         $result.='<th>&nbsp;</th>';
                    227:     }
                    228:     $result.='<th>'.&mt('Problem Part').'</th>'
                    229:             .'<th>'.&mt('Res. ID').'</th>'
                    230:             .'<th>'.&mt('Type').'</th>'
                    231:             .&Apache::loncommon::end_data_table_header_row();
1.126     ng        232:     my %resptype = ();
1.122     ng        233:     my $hdgrade='no';
1.154     albertel  234:     my %partsseen;
1.524     raeburn   235:     foreach my $partID (sort(keys(%$responseType))) {
1.584     bisitz    236:         foreach my $resID (sort(keys(%{ $responseType->{$partID} }))) {
                    237:             my $handgrade=$$handgrade{$partID.'_'.$resID};
                    238:             my $responsetype = $responseType->{$partID}->{$resID};
                    239:             $hdgrade = $handgrade if ($handgrade eq 'yes');
                    240:             $result.=&Apache::loncommon::start_data_table_row();
                    241:             if ($checkboxes) {
                    242:                 if (exists($partsseen{$partID})) {
                    243:                     $result.="<td>&nbsp;</td>";
                    244:                 } else {
                    245:                     $result.="<td><input type='checkbox' name='vPart' value='$partID' checked='checked' /></td>";
                    246:                 }
                    247:                 $partsseen{$partID}=1;
                    248:             }
                    249:             my $display_part=&get_display_part($partID,$symb);
                    250:             $result.='<td>'.$display_part.'</td>'
                    251:                     .'<td>'.'<span class="LC_internal_info">'.$resID.'</span></td>'
                    252:                     .'<td>'.&mt($responsetype).'</td>'
                    253: #                   .'<td>'.&mt('<b>Handgrade: </b>[_1]',$handgrade).'</td>'
                    254:                     .&Apache::loncommon::end_data_table_row();
                    255:         }
1.118     ng        256:     }
1.584     bisitz    257:     $result.=&Apache::loncommon::end_data_table();
1.147     albertel  258:     return $result,$responseType,$hdgrade,$partlist,$handgrade;
1.118     ng        259: }
                    260: 
1.434     albertel  261: sub reset_caches {
                    262:     &reset_analyze_cache();
                    263:     &reset_perm();
1.596.2.13! raeburn   264:     &reset_old_essays();
1.434     albertel  265: }
                    266: 
                    267: {
                    268:     my %analyze_cache;
1.557     raeburn   269:     my %analyze_cache_formkeys;
1.148     albertel  270: 
1.434     albertel  271:     sub reset_analyze_cache {
                    272: 	undef(%analyze_cache);
1.557     raeburn   273:         undef(%analyze_cache_formkeys);
1.434     albertel  274:     }
                    275: 
                    276:     sub get_analyze {
1.596.2.2  raeburn   277: 	my ($symb,$uname,$udom,$no_increment,$add_to_hash,$type,$trial,$rndseed)=@_;
1.434     albertel  278: 	my $key = "$symb\0$uname\0$udom";
1.596.2.2  raeburn   279:         if ($type eq 'randomizetry') {
                    280:             if ($trial ne '') {
                    281:                 $key .= "\0".$trial;
                    282:             }
                    283:         }
1.557     raeburn   284: 	if (exists($analyze_cache{$key})) {
                    285:             my $getupdate = 0;
                    286:             if (ref($add_to_hash) eq 'HASH') {
                    287:                 foreach my $item (keys(%{$add_to_hash})) {
                    288:                     if (ref($analyze_cache_formkeys{$key}) eq 'HASH') {
                    289:                         if (!exists($analyze_cache_formkeys{$key}{$item})) {
                    290:                             $getupdate = 1;
                    291:                             last;
                    292:                         }
                    293:                     } else {
                    294:                         $getupdate = 1;
                    295:                     }
                    296:                 }
                    297:             }
                    298:             if (!$getupdate) {
                    299:                 return $analyze_cache{$key};
                    300:             }
                    301:         }
1.434     albertel  302: 
                    303: 	my (undef,undef,$url)=&Apache::lonnet::decode_symb($symb);
                    304: 	$url=&Apache::lonnet::clutter($url);
1.557     raeburn   305:         my %form = ('grade_target'      => 'analyze',
                    306:                     'grade_domain'      => $udom,
                    307:                     'grade_symb'        => $symb,
                    308:                     'grade_courseid'    =>  $env{'request.course.id'},
                    309:                     'grade_username'    => $uname,
                    310:                     'grade_noincrement' => $no_increment);
1.596.2.2  raeburn   311:         if ($type eq 'randomizetry') {
                    312:             $form{'grade_questiontype'} = $type;
                    313:             if ($rndseed ne '') {
                    314:                 $form{'grade_rndseed'} = $rndseed;
                    315:             }
                    316:         }
1.557     raeburn   317:         if (ref($add_to_hash)) {
                    318:             %form = (%form,%{$add_to_hash});
1.596.2.2  raeburn   319:         }
1.557     raeburn   320: 	my $subresult=&ssi_with_retries($url, $ssi_retries,%form);
1.434     albertel  321: 	(undef,$subresult)=split(/_HASH_REF__/,$subresult,2);
                    322: 	my %analyze=&Apache::lonnet::str2hash($subresult);
1.557     raeburn   323:         if (ref($add_to_hash) eq 'HASH') {
                    324:             $analyze_cache_formkeys{$key} = $add_to_hash;
                    325:         } else {
                    326:             $analyze_cache_formkeys{$key} = {};
                    327:         }
1.434     albertel  328: 	return $analyze_cache{$key} = \%analyze;
                    329:     }
                    330: 
                    331:     sub get_order {
1.596.2.2  raeburn   332: 	my ($partid,$respid,$symb,$uname,$udom,$no_increment,$type,$trial,$rndseed)=@_;
                    333: 	my $analyze = &get_analyze($symb,$uname,$udom,$no_increment,undef,$type,$trial,$rndseed);
1.434     albertel  334: 	return $analyze->{"$partid.$respid.shown"};
                    335:     }
                    336: 
                    337:     sub get_radiobutton_correct_foil {
1.596.2.2  raeburn   338: 	my ($partid,$respid,$symb,$uname,$udom,$type,$trial,$rndseed)=@_;
                    339: 	my $analyze = &get_analyze($symb,$uname,$udom,undef,undef,$type,$trial,$rndseed);
                    340:         my $foils = &get_order($partid,$respid,$symb,$uname,$udom,undef,$type,$trial,$rndseed);
1.555     raeburn   341:         if (ref($foils) eq 'ARRAY') {
                    342: 	    foreach my $foil (@{$foils}) {
                    343: 	        if ($analyze->{"$partid.$respid.foil.value.$foil"} eq 'true') {
                    344: 		    return $foil;
                    345: 	        }
1.434     albertel  346: 	    }
                    347: 	}
                    348:     }
1.554     raeburn   349: 
                    350:     sub scantron_partids_tograde {
1.557     raeburn   351:         my ($resource,$cid,$uname,$udom,$check_for_randomlist) = @_;
1.554     raeburn   352:         my (%analysis,@parts);
                    353:         if (ref($resource)) {
                    354:             my $symb = $resource->symb();
1.557     raeburn   355:             my $add_to_form;
                    356:             if ($check_for_randomlist) {
                    357:                 $add_to_form = { 'check_parts_withrandomlist' => 1,};
                    358:             }
                    359:             my $analyze = &get_analyze($symb,$uname,$udom,undef,$add_to_form);
1.554     raeburn   360:             if (ref($analyze) eq 'HASH') {
                    361:                 %analysis = %{$analyze};
                    362:             }
                    363:             if (ref($analysis{'parts'}) eq 'ARRAY') {
                    364:                 foreach my $part (@{$analysis{'parts'}}) {
                    365:                     my ($id,$respid) = split(/\./,$part);
                    366:                     if (!&Apache::loncommon::check_if_partid_hidden($id,$symb,$udom,$uname)) {
                    367:                         push(@parts,$part);
                    368:                     }
                    369:                 }
                    370:             }
                    371:         }
                    372:         return (\%analysis,\@parts);
                    373:     }
                    374: 
1.148     albertel  375: }
1.434     albertel  376: 
1.118     ng        377: #--- Clean response type for display
1.335     albertel  378: #--- Currently filters option/rank/radiobutton/match/essay/Task
                    379: #        response types only.
1.118     ng        380: sub cleanRecord {
1.336     albertel  381:     my ($answer,$response,$symb,$partid,$respid,$record,$order,$version,
1.596.2.2  raeburn   382: 	$uname,$udom,$type,$trial,$rndseed) = @_;
1.398     albertel  383:     my $grayFont = '<span class="LC_internal_info">';
1.148     albertel  384:     if ($response =~ /^(option|rank)$/) {
                    385: 	my %answer=&Apache::lonnet::str2hash($answer);
                    386: 	my %grading=&Apache::lonnet::str2hash($record->{$version."resource.$partid.$respid.submissiongrading"});
                    387: 	my ($toprow,$bottomrow);
                    388: 	foreach my $foil (@$order) {
                    389: 	    if ($grading{$foil} == 1) {
                    390: 		$toprow.='<td><b>'.$answer{$foil}.'&nbsp;</b></td>';
                    391: 	    } else {
                    392: 		$toprow.='<td><i>'.$answer{$foil}.'&nbsp;</i></td>';
                    393: 	    }
1.398     albertel  394: 	    $bottomrow.='<td>'.$grayFont.$foil.'</span>&nbsp;</td>';
1.148     albertel  395: 	}
                    396: 	return '<blockquote><table border="1">'.
1.466     albertel  397: 	    '<tr valign="top"><td>'.&mt('Answer').'</td>'.$toprow.'</tr>'.
                    398: 	    '<tr valign="top"><td>'.$grayFont.&mt('Option ID').'</span></td>'.
1.596.2.1  raeburn   399: 	    $bottomrow.'</tr></table></blockquote>';
1.148     albertel  400:     } elsif ($response eq 'match') {
                    401: 	my %answer=&Apache::lonnet::str2hash($answer);
                    402: 	my %grading=&Apache::lonnet::str2hash($record->{$version."resource.$partid.$respid.submissiongrading"});
                    403: 	my @items=&Apache::lonnet::str2array($record->{$version."resource.$partid.$respid.submissionitems"});
                    404: 	my ($toprow,$middlerow,$bottomrow);
                    405: 	foreach my $foil (@$order) {
                    406: 	    my $item=shift(@items);
                    407: 	    if ($grading{$foil} == 1) {
                    408: 		$toprow.='<td><b>'.$item.'&nbsp;</b></td>';
1.398     albertel  409: 		$middlerow.='<td><b>'.$grayFont.$answer{$foil}.'&nbsp;</span></b></td>';
1.148     albertel  410: 	    } else {
                    411: 		$toprow.='<td><i>'.$item.'&nbsp;</i></td>';
1.398     albertel  412: 		$middlerow.='<td><i>'.$grayFont.$answer{$foil}.'&nbsp;</span></i></td>';
1.148     albertel  413: 	    }
1.398     albertel  414: 	    $bottomrow.='<td>'.$grayFont.$foil.'</span>&nbsp;</td>';
1.118     ng        415: 	}
1.126     ng        416: 	return '<blockquote><table border="1">'.
1.466     albertel  417: 	    '<tr valign="top"><td>'.&mt('Answer').'</td>'.$toprow.'</tr>'.
                    418: 	    '<tr valign="top"><td>'.$grayFont.&mt('Item ID').'</span></td>'.
1.148     albertel  419: 	    $middlerow.'</tr>'.
1.466     albertel  420: 	    '<tr valign="top"><td>'.$grayFont.&mt('Option ID').'</span></td>'.
1.596.2.8  raeburn   421: 	    $bottomrow.'</tr></table></blockquote>';
1.148     albertel  422:     } elsif ($response eq 'radiobutton') {
                    423: 	my %answer=&Apache::lonnet::str2hash($answer);
                    424: 	my ($toprow,$bottomrow);
1.434     albertel  425: 	my $correct = 
1.596.2.2  raeburn   426: 	    &get_radiobutton_correct_foil($partid,$respid,$symb,$uname,$udom,$type,$trial,$rndseed);
1.434     albertel  427: 	foreach my $foil (@$order) {
1.148     albertel  428: 	    if (exists($answer{$foil})) {
1.434     albertel  429: 		if ($foil eq $correct) {
1.466     albertel  430: 		    $toprow.='<td><b>'.&mt('true').'</b></td>';
1.148     albertel  431: 		} else {
1.466     albertel  432: 		    $toprow.='<td><i>'.&mt('true').'</i></td>';
1.148     albertel  433: 		}
                    434: 	    } else {
1.466     albertel  435: 		$toprow.='<td>'.&mt('false').'</td>';
1.148     albertel  436: 	    }
1.398     albertel  437: 	    $bottomrow.='<td>'.$grayFont.$foil.'</span>&nbsp;</td>';
1.148     albertel  438: 	}
                    439: 	return '<blockquote><table border="1">'.
1.466     albertel  440: 	    '<tr valign="top"><td>'.&mt('Answer').'</td>'.$toprow.'</tr>'.
                    441: 	    '<tr valign="top"><td>'.$grayFont.&mt('Option ID').'</span></td>'.
1.596.2.4  raeburn   442: 	    $bottomrow.'</tr></table></blockquote>';
1.148     albertel  443:     } elsif ($response eq 'essay') {
1.257     albertel  444: 	if (! exists ($env{'form.'.$symb})) {
1.122     ng        445: 	    my (%keyhash) = &Apache::lonnet::dump('nohist_handgrade',
1.257     albertel  446: 						  $env{'course.'.$env{'request.course.id'}.'.domain'},
                    447: 						  $env{'course.'.$env{'request.course.id'}.'.num'});
1.122     ng        448: 
1.257     albertel  449: 	    my $loginuser = $env{'user.name'}.':'.$env{'user.domain'};
                    450: 	    $env{'form.keywords'} = $keyhash{$symb.'_keywords'} ne '' ? $keyhash{$symb.'_keywords'} : '';
                    451: 	    $env{'form.kwclr'}    = $keyhash{$loginuser.'_kwclr'} ne '' ? $keyhash{$loginuser.'_kwclr'} : 'red';
                    452: 	    $env{'form.kwsize'}   = $keyhash{$loginuser.'_kwsize'} ne '' ? $keyhash{$loginuser.'_kwsize'} : '0';
                    453: 	    $env{'form.kwstyle'}  = $keyhash{$loginuser.'_kwstyle'} ne '' ? $keyhash{$loginuser.'_kwstyle'} : '';
                    454: 	    $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        455: 	}
1.166     albertel  456: 	$answer =~ s-\n-<br />-g;
                    457: 	return '<br /><br /><blockquote><tt>'.&keywords_highlight($answer).'</tt></blockquote>';
1.268     albertel  458:     } elsif ( $response eq 'organic') {
                    459: 	my $result='Smile representation: "<tt>'.$answer.'</tt>"';
                    460: 	my $jme=$record->{$version."resource.$partid.$respid.molecule"};
                    461: 	$result.=&Apache::chemresponse::jme_img($jme,$answer,400);
                    462: 	return $result;
1.335     albertel  463:     } elsif ( $response eq 'Task') {
                    464: 	if ( $answer eq 'SUBMITTED') {
                    465: 	    my $files = $record->{$version."resource.$respid.$partid.bridgetask.portfiles"};
1.336     albertel  466: 	    my $result = &Apache::bridgetask::file_list($files,$uname,$udom);
1.335     albertel  467: 	    return $result;
                    468: 	} elsif ( grep(/^\Q$version\E.*?\.instance$/, keys(%{$record})) ) {
                    469: 	    my @matches = grep(/^\Q$version\E.*?\.instance$/,
                    470: 			       keys(%{$record}));
                    471: 	    return join('<br />',($version,@matches));
                    472: 			       
                    473: 			       
                    474: 	} else {
                    475: 	    my $result =
                    476: 		'<p>'
                    477: 		.&mt('Overall result: [_1]',
                    478: 		     $record->{$version."resource.$respid.$partid.status"})
                    479: 		.'</p>';
                    480: 	    
                    481: 	    $result .= '<ul>';
                    482: 	    my @grade = grep(/^\Q${version}resource.$respid.$partid.\E[^.]*[.]status$/,
                    483: 			     keys(%{$record}));
                    484: 	    foreach my $grade (sort(@grade)) {
                    485: 		my ($dim) = ($grade =~/[.]([^.]+)[.]status$/);
                    486: 		$result.= '<li>'.&mt("Dimension: [_1], status [_2] ",
                    487: 				     $dim, $record->{$grade}).
                    488: 			  '</li>';
                    489: 	    }
                    490: 	    $result.='</ul>';
                    491: 	    return $result;
                    492: 	}
1.440     albertel  493:     } elsif ( $response =~ m/(?:numerical|formula)/) {
                    494: 	$answer = 
                    495: 	    &Apache::loncommon::format_previous_attempt_value('submission',
                    496: 							      $answer);
1.122     ng        497:     }
1.118     ng        498:     return $answer;
                    499: }
                    500: 
                    501: #-- A couple of common js functions
                    502: sub commonJSfunctions {
                    503:     my $request = shift;
                    504:     $request->print(<<COMMONJSFUNCTIONS);
                    505: <script type="text/javascript" language="javascript">
                    506:     function radioSelection(radioButton) {
                    507: 	var selection=null;
                    508: 	if (radioButton.length > 1) {
                    509: 	    for (var i=0; i<radioButton.length; i++) {
                    510: 		if (radioButton[i].checked) {
                    511: 		    return radioButton[i].value;
                    512: 		}
                    513: 	    }
                    514: 	} else {
                    515: 	    if (radioButton.checked) return radioButton.value;
                    516: 	}
                    517: 	return selection;
                    518:     }
                    519: 
                    520:     function pullDownSelection(selectOne) {
                    521: 	var selection="";
                    522: 	if (selectOne.length > 1) {
                    523: 	    for (var i=0; i<selectOne.length; i++) {
                    524: 		if (selectOne[i].selected) {
                    525: 		    return selectOne[i].value;
                    526: 		}
                    527: 	    }
                    528: 	} else {
1.138     albertel  529:             // only one value it must be the selected one
                    530: 	    return selectOne.value;
1.118     ng        531: 	}
                    532:     }
                    533: </script>
                    534: COMMONJSFUNCTIONS
                    535: }
                    536: 
1.44      ng        537: #--- Dumps the class list with usernames,list of sections,
                    538: #--- section, ids and fullnames for each user.
                    539: sub getclasslist {
1.449     banghart  540:     my ($getsec,$filterlist,$getgroup) = @_;
1.291     albertel  541:     my @getsec;
1.450     banghart  542:     my @getgroup;
1.442     banghart  543:     my $stu_status = join(':',&Apache::loncommon::get_env_multiple('form.Status'));
1.291     albertel  544:     if (!ref($getsec)) {
                    545: 	if ($getsec ne '' && $getsec ne 'all') {
                    546: 	    @getsec=($getsec);
                    547: 	}
                    548:     } else {
                    549: 	@getsec=@{$getsec};
                    550:     }
                    551:     if (grep(/^all$/,@getsec)) { undef(@getsec); }
1.450     banghart  552:     if (!ref($getgroup)) {
                    553: 	if ($getgroup ne '' && $getgroup ne 'all') {
                    554: 	    @getgroup=($getgroup);
                    555: 	}
                    556:     } else {
                    557: 	@getgroup=@{$getgroup};
                    558:     }
                    559:     if (grep(/^all$/,@getgroup)) { undef(@getgroup); }
1.291     albertel  560: 
1.449     banghart  561:     my ($classlist,$keylist)=&Apache::loncoursedata::get_classlist();
1.49      albertel  562:     # Bail out if we were unable to get the classlist
1.56      matthew   563:     return if (! defined($classlist));
1.449     banghart  564:     &Apache::loncoursedata::get_group_memberships($classlist,$keylist);
1.56      matthew   565:     #
                    566:     my %sections;
                    567:     my %fullnames;
1.205     matthew   568:     foreach my $student (keys(%$classlist)) {
                    569:         my $end      = 
                    570:             $classlist->{$student}->[&Apache::loncoursedata::CL_END()];
                    571:         my $start    = 
                    572:             $classlist->{$student}->[&Apache::loncoursedata::CL_START()];
                    573:         my $id       = 
                    574:             $classlist->{$student}->[&Apache::loncoursedata::CL_ID()];
                    575:         my $section  = 
                    576:             $classlist->{$student}->[&Apache::loncoursedata::CL_SECTION()];
                    577:         my $fullname = 
                    578:             $classlist->{$student}->[&Apache::loncoursedata::CL_FULLNAME()];
                    579:         my $status   = 
                    580:             $classlist->{$student}->[&Apache::loncoursedata::CL_STATUS()];
1.449     banghart  581:         my $group   = 
                    582:             $classlist->{$student}->[&Apache::loncoursedata::CL_GROUP()];
1.76      ng        583: 	# filter students according to status selected
1.442     banghart  584: 	if ($filterlist && (!($stu_status =~ /Any/))) {
                    585: 	    if (!($stu_status =~ $status)) {
1.450     banghart  586: 		delete($classlist->{$student});
1.76      ng        587: 		next;
                    588: 	    }
                    589: 	}
1.450     banghart  590: 	# filter students according to groups selected
1.453     banghart  591: 	my @stu_groups = split(/,/,$group);
1.450     banghart  592: 	if (@getgroup) {
                    593: 	    my $exclude = 1;
1.454     banghart  594: 	    foreach my $grp (@getgroup) {
                    595: 	        foreach my $stu_group (@stu_groups) {
1.453     banghart  596: 	            if ($stu_group eq $grp) {
                    597: 	                $exclude = 0;
                    598:     	            } 
1.450     banghart  599: 	        }
1.453     banghart  600:     	        if (($grp eq 'none') && !$group) {
                    601:         	        $exclude = 0;
                    602:         	}
1.450     banghart  603: 	    }
                    604: 	    if ($exclude) {
                    605: 	        delete($classlist->{$student});
                    606: 	    }
                    607: 	}
1.205     matthew   608: 	$section = ($section ne '' ? $section : 'none');
1.106     albertel  609: 	if (&canview($section)) {
1.291     albertel  610: 	    if (!@getsec || grep(/^\Q$section\E$/,@getsec)) {
1.103     albertel  611: 		$sections{$section}++;
1.450     banghart  612: 		if ($classlist->{$student}) {
                    613: 		    $fullnames{$student}=$fullname;
                    614: 		}
1.103     albertel  615: 	    } else {
1.205     matthew   616: 		delete($classlist->{$student});
1.103     albertel  617: 	    }
                    618: 	} else {
1.205     matthew   619: 	    delete($classlist->{$student});
1.103     albertel  620: 	}
1.44      ng        621:     }
                    622:     my %seen = ();
1.56      matthew   623:     my @sections = sort(keys(%sections));
                    624:     return ($classlist,\@sections,\%fullnames);
1.44      ng        625: }
                    626: 
1.103     albertel  627: sub canmodify {
                    628:     my ($sec)=@_;
                    629:     if ($perm{'mgr'}) {
                    630: 	if (!defined($perm{'mgr_section'})) {
                    631: 	    # can modify whole class
                    632: 	    return 1;
                    633: 	} else {
                    634: 	    if ($sec eq $perm{'mgr_section'}) {
                    635: 		#can modify the requested section
                    636: 		return 1;
                    637: 	    } else {
                    638: 		# can't modify the request section
                    639: 		return 0;
                    640: 	    }
                    641: 	}
                    642:     }
                    643:     #can't modify
                    644:     return 0;
                    645: }
                    646: 
                    647: sub canview {
                    648:     my ($sec)=@_;
                    649:     if ($perm{'vgr'}) {
                    650: 	if (!defined($perm{'vgr_section'})) {
                    651: 	    # can modify whole class
                    652: 	    return 1;
                    653: 	} else {
                    654: 	    if ($sec eq $perm{'vgr_section'}) {
                    655: 		#can modify the requested section
                    656: 		return 1;
                    657: 	    } else {
                    658: 		# can't modify the request section
                    659: 		return 0;
                    660: 	    }
                    661: 	}
                    662:     }
                    663:     #can't modify
                    664:     return 0;
                    665: }
                    666: 
1.44      ng        667: #--- Retrieve the grade status of a student for all the parts
                    668: sub student_gradeStatus {
1.324     albertel  669:     my ($symb,$udom,$uname,$partlist) = @_;
1.257     albertel  670:     my %record     = &Apache::lonnet::restore($symb,$env{'request.course.id'},$udom,$uname);
1.44      ng        671:     my %partstatus = ();
                    672:     foreach (@$partlist) {
1.128     ng        673: 	my ($status,undef)   = split(/_/,$record{"resource.$_.solved"},2);
1.44      ng        674: 	$status              = 'nothing' if ($status eq '');
                    675: 	$partstatus{$_}      = $status;
                    676: 	my $subkey           = "resource.$_.submitted_by";
                    677: 	$partstatus{$subkey} = $record{$subkey} if ($record{$subkey} ne '');
                    678:     }
                    679:     return %partstatus;
                    680: }
                    681: 
1.45      ng        682: # hidden form and javascript that calls the form
                    683: # Use by verifyscript and viewgrades
                    684: # Shows a student's view of problem and submission
                    685: sub jscriptNform {
1.324     albertel  686:     my ($symb) = @_;
1.442     banghart  687:     my $stu_status = join(':',&Apache::loncommon::get_env_multiple('form.Status'));
1.45      ng        688:     my $jscript='<script type="text/javascript" language="javascript">'."\n".
                    689: 	'    function viewOneStudent(user,domain) {'."\n".
                    690: 	'	document.onestudent.student.value = user;'."\n".
                    691: 	'	document.onestudent.userdom.value = domain;'."\n".
                    692: 	'	document.onestudent.submit();'."\n".
                    693: 	'    }'."\n".
                    694: 	'</script>'."\n";
                    695:     $jscript.= '<form action="/adm/grades" method="post" name="onestudent">'."\n".
1.418     albertel  696: 	'<input type="hidden" name="symb"    value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
1.257     albertel  697: 	'<input type="hidden" name="saveState" value="'.$env{'form.saveState'}.'" />'."\n".
                    698: 	'<input type="hidden" name="probTitle" value="'.$env{'form.probTitle'}.'" />'."\n".
1.442     banghart  699: 	'<input type="hidden" name="Status"  value="'.$stu_status.'" />'."\n".
1.45      ng        700: 	'<input type="hidden" name="command" value="submission" />'."\n".
                    701: 	'<input type="hidden" name="student" value="" />'."\n".
                    702: 	'<input type="hidden" name="userdom" value="" />'."\n".
                    703: 	'</form>'."\n";
                    704:     return $jscript;
                    705: }
1.39      ng        706: 
1.447     foxr      707: 
                    708: 
1.315     bowersj2  709: # Given the score (as a number [0-1] and the weight) what is the final
                    710: # point value? This function will round to the nearest tenth, third,
                    711: # or quarter if one of those is within the tolerance of .00001.
1.316     albertel  712: sub compute_points {
1.315     bowersj2  713:     my ($score, $weight) = @_;
                    714:     
                    715:     my $tolerance = .00001;
                    716:     my $points = $score * $weight;
                    717: 
                    718:     # Check for nearness to 1/x.
                    719:     my $check_for_nearness = sub {
                    720:         my ($factor) = @_;
                    721:         my $num = ($points * $factor) + $tolerance;
                    722:         my $floored_num = floor($num);
1.316     albertel  723:         if ($num - $floored_num < 2 * $tolerance * $factor) {
1.315     bowersj2  724:             return $floored_num / $factor;
                    725:         }
                    726:         return $points;
                    727:     };
                    728: 
                    729:     $points = $check_for_nearness->(10);
                    730:     $points = $check_for_nearness->(3);
                    731:     $points = $check_for_nearness->(4);
                    732:     
                    733:     return $points;
                    734: }
                    735: 
1.44      ng        736: #------------------ End of general use routines --------------------
1.87      www       737: 
                    738: #
                    739: # Find most similar essay
                    740: #
                    741: 
                    742: sub most_similar {
1.596.2.13! raeburn   743:     my ($uname,$udom,$symb,$uessay)=@_;
        !           744: 
        !           745:     unless ($symb) { return ''; }
        !           746: 
        !           747:     unless (ref($old_essays{$symb}) eq 'HASH') { return ''; }
1.87      www       748: 
                    749: # ignore spaces and punctuation
                    750: 
                    751:     $uessay=~s/\W+/ /gs;
                    752: 
1.282     www       753: # ignore empty submissions (occuring when only files are sent)
                    754: 
1.596.2.4  raeburn   755:     unless ($uessay=~/\w+/s) { return ''; }
1.282     www       756: 
1.87      www       757: # these will be returned. Do not care if not at least 50 percent similar
1.88      www       758:     my $limit=0.6;
1.87      www       759:     my $sname='';
                    760:     my $sdom='';
                    761:     my $scrsid='';
                    762:     my $sessay='';
                    763: # go through all essays ...
1.596.2.13! raeburn   764:     foreach my $tkey (keys(%{$old_essays{$symb}})) {
1.426     albertel  765: 	my ($tname,$tdom,$tcrsid)=map {&unescape($_)} (split(/\./,$tkey));
1.87      www       766: # ... except the same student
1.426     albertel  767:         next if (($tname eq $uname) && ($tdom eq $udom));
1.596.2.13! raeburn   768: 	my $tessay=$old_essays{$symb}{$tkey};
1.426     albertel  769: 	$tessay=~s/\W+/ /gs;
1.87      www       770: # String similarity gives up if not even limit
1.426     albertel  771: 	my $tsimilar=&String::Similarity::similarity($uessay,$tessay,$limit);
1.87      www       772: # Found one
1.426     albertel  773: 	if ($tsimilar>$limit) {
                    774: 	    $limit=$tsimilar;
                    775: 	    $sname=$tname;
                    776: 	    $sdom=$tdom;
                    777: 	    $scrsid=$tcrsid;
1.596.2.13! raeburn   778: 	    $sessay=$old_essays{$symb}{$tkey};
1.426     albertel  779: 	}
1.87      www       780:     }
1.88      www       781:     if ($limit>0.6) {
1.87      www       782:        return ($sname,$sdom,$scrsid,$sessay,$limit);
                    783:     } else {
                    784:        return ('','','','',0);
                    785:     }
                    786: }
                    787: 
1.44      ng        788: #-------------------------------------------------------------------
                    789: 
                    790: #------------------------------------ Receipt Verification Routines
1.45      ng        791: #
1.44      ng        792: #--- Check whether a receipt number is valid.---
                    793: sub verifyreceipt {
                    794:     my $request  = shift;
                    795: 
1.257     albertel  796:     my $courseid = $env{'request.course.id'};
1.184     www       797:     my $receipt  = &Apache::lonnet::recprefix($courseid).'-'.
1.257     albertel  798: 	$env{'form.receipt'};
1.44      ng        799:     $receipt     =~ s/[^\-\d]//g;
1.378     albertel  800:     my ($symb)   = &get_symb($request);
1.44      ng        801: 
1.487     albertel  802:     my $title.=
                    803: 	'<h3><span class="LC_info">'.
1.584     bisitz    804: 	&mt('Verifying Receipt No. [_1]',$receipt).
1.487     albertel  805: 	'</span></h3>'."\n".
                    806: 	'<h4>'.&mt('<b>Resource: </b>[_1]',$env{'form.probTitle'}).
                    807: 	'</h4>'."\n";
1.44      ng        808: 
                    809:     my ($string,$contents,$matches) = ('','',0);
1.56      matthew   810:     my (undef,undef,$fullname) = &getclasslist('all','0');
1.177     albertel  811:     
                    812:     my $receiptparts=0;
1.390     albertel  813:     if ($env{"course.$courseid.receiptalg"} eq 'receipt2' ||
                    814: 	$env{"course.$courseid.receiptalg"} eq 'receipt3') { $receiptparts=1; }
1.177     albertel  815:     my $parts=['0'];
1.582     raeburn   816:     if ($receiptparts) {
                    817:         my $res_error; 
                    818:         ($parts)=&response_type($symb,\$res_error);
                    819:         if ($res_error) {
                    820:             return &navmap_errormsg();
                    821:         } 
                    822:     }
1.486     albertel  823:     
                    824:     my $header = 
                    825: 	&Apache::loncommon::start_data_table().
                    826: 	&Apache::loncommon::start_data_table_header_row().
1.487     albertel  827: 	'<th>&nbsp;'.&mt('Fullname').'&nbsp;</th>'."\n".
                    828: 	'<th>&nbsp;'.&mt('Username').'&nbsp;</th>'."\n".
                    829: 	'<th>&nbsp;'.&mt('Domain').'&nbsp;</th>';
1.486     albertel  830:     if ($receiptparts) {
1.487     albertel  831: 	$header.='<th>&nbsp;'.&mt('Problem Part').'&nbsp;</th>';
1.486     albertel  832:     }
                    833:     $header.=
                    834: 	&Apache::loncommon::end_data_table_header_row();
                    835: 
1.294     albertel  836:     foreach (sort 
                    837: 	     {
                    838: 		 if (lc($$fullname{$a}) ne lc($$fullname{$b})) {
                    839: 		     return (lc($$fullname{$a}) cmp lc($$fullname{$b}));
                    840: 		 }
                    841: 		 return $a cmp $b;
                    842: 	     } (keys(%$fullname))) {
1.44      ng        843: 	my ($uname,$udom)=split(/\:/);
1.177     albertel  844: 	foreach my $part (@$parts) {
                    845: 	    if ($receipt eq &Apache::lonnet::ireceipt($uname,$udom,$courseid,$symb,$part)) {
1.486     albertel  846: 		$contents.=
                    847: 		    &Apache::loncommon::start_data_table_row().
                    848: 		    '<td>&nbsp;'."\n".
1.177     albertel  849: 		    '<a href="javascript:viewOneStudent(\''.$uname.'\',\''.$udom.
1.417     albertel  850: 		    '\');" target="_self">'.$$fullname{$_}.'</a>&nbsp;</td>'."\n".
1.177     albertel  851: 		    '<td>&nbsp;'.$uname.'&nbsp;</td>'.
                    852: 		    '<td>&nbsp;'.$udom.'&nbsp;</td>';
                    853: 		if ($receiptparts) {
                    854: 		    $contents.='<td>&nbsp;'.$part.'&nbsp;</td>';
                    855: 		}
1.486     albertel  856: 		$contents.= 
                    857: 		    &Apache::loncommon::end_data_table_row()."\n";
1.177     albertel  858: 		
                    859: 		$matches++;
                    860: 	    }
1.44      ng        861: 	}
                    862:     }
                    863:     if ($matches == 0) {
1.584     bisitz    864:         $string = $title
                    865:                  .'<p class="LC_warning">'
                    866:                  .&mt('No match found for the above receipt number.')
                    867:                  .'</p>';
1.44      ng        868:     } else {
1.324     albertel  869: 	$string = &jscriptNform($symb).$title.
1.487     albertel  870: 	    '<p>'.
1.584     bisitz    871: 	    &mt('The above receipt number matches the following [quant,_1,student].',$matches).
1.487     albertel  872: 	    '</p>'.
1.486     albertel  873: 	    $header.
                    874: 	    $contents.
                    875: 	    &Apache::loncommon::end_data_table()."\n";
1.44      ng        876:     }
1.324     albertel  877:     return $string.&show_grading_menu_form($symb);
1.44      ng        878: }
                    879: 
                    880: #--- This is called by a number of programs.
                    881: #--- Called from the Grading Menu - View/Grade an individual student
                    882: #--- Also called directly when one clicks on the subm button 
                    883: #    on the problem page.
1.30      ng        884: sub listStudents {
1.41      ng        885:     my ($request) = shift;
1.49      albertel  886: 
1.324     albertel  887:     my ($symb) = &get_symb($request);
1.257     albertel  888:     my $cdom      = $env{"course.$env{'request.course.id'}.domain"};
                    889:     my $cnum      = $env{"course.$env{'request.course.id'}.num"};
                    890:     my $getsec    = $env{'form.section'} eq '' ? 'all' : $env{'form.section'};
1.449     banghart  891:     my $getgroup  = $env{'form.group'} eq '' ? 'all' : $env{'form.group'};
1.257     albertel  892:     my $submitonly= $env{'form.submitonly'} eq '' ? 'all' : $env{'form.submitonly'};
1.548     bisitz    893:     my $viewgrade = $env{'form.showgrading'} eq 'yes' ? 'View/Grade/Regrade' : 'View';
1.257     albertel  894:     $env{'form.probTitle'} = $env{'form.probTitle'} eq '' ? 
                    895: 	&Apache::lonnet::gettitle($symb) : $env{'form.probTitle'};
1.49      albertel  896: 
1.548     bisitz    897:     my $result='<h3><span class="LC_info">&nbsp;'
                    898: 	.&mt("$viewgrade Submissions for a Student or a Group of Students")
1.485     albertel  899: 	.'</span></h3>';
1.118     ng        900: 
1.324     albertel  901:     my ($table,undef,$hdgrade,$partlist,$handgrade) = &showResourceInfo($symb,$env{'form.probTitle'},($env{'form.showgrading'} eq 'yes'));
1.49      albertel  902: 
1.559     raeburn   903:     my %lt = &Apache::lonlocal::texthash (
                    904: 		'multiple' => 'Please select a student or group of students before clicking on the Next button.',
                    905: 		'single'   => 'Please select the student before clicking on the Next button.',
                    906: 	     );
1.45      ng        907:     $request->print(<<LISTJAVASCRIPT);
                    908: <script type="text/javascript" language="javascript">
1.110     ng        909:     function checkSelect(checkBox) {
                    910: 	var ctr=0;
                    911: 	var sense="";
                    912: 	if (checkBox.length > 1) {
                    913: 	    for (var i=0; i<checkBox.length; i++) {
                    914: 		if (checkBox[i].checked) {
                    915: 		    ctr++;
                    916: 		}
                    917: 	    }
1.485     albertel  918: 	    sense = '$lt{'multiple'}';
1.110     ng        919: 	} else {
                    920: 	    if (checkBox.checked) {
                    921: 		ctr = 1;
                    922: 	    }
1.485     albertel  923: 	    sense = '$lt{'single'}';
1.110     ng        924: 	}
                    925: 	if (ctr == 0) {
1.485     albertel  926: 	    alert(sense);
1.110     ng        927: 	    return false;
                    928: 	}
                    929: 	document.gradesub.submit();
                    930:     }
                    931: 
                    932:     function reLoadList(formname) {
1.112     ng        933: 	if (formname.saveStatusOld.value == pullDownSelection(formname.Status)) {return;}
1.110     ng        934: 	formname.command.value = 'submission';
                    935: 	formname.submit();
                    936:     }
1.45      ng        937: </script>
                    938: LISTJAVASCRIPT
                    939: 
1.118     ng        940:     &commonJSfunctions($request);
1.41      ng        941:     $request->print($result);
1.39      ng        942: 
1.401     albertel  943:     my $checkhdgrade = ($env{'form.handgrade'} eq 'yes' && scalar(@$partlist) > 1 ) ? 'checked="checked"' : '';
                    944:     my $checklastsub = $checkhdgrade eq '' ? 'checked="checked"' : '';
1.154     albertel  945:     my $gradeTable='<form action="/adm/grades" method="post" name="gradesub">'.
1.485     albertel  946: 	"\n".$table;
                    947: 	
1.561     bisitz    948:     $gradeTable .= &Apache::lonhtmlcommon::start_pick_box();
                    949:     $gradeTable .= &Apache::lonhtmlcommon::row_title(&mt('View Problem Text'))
                    950:                   .'<label><input type="radio" name="vProb" value="no" checked="checked" /> '.&mt('no').' </label>'."\n"
                    951:                   .'<label><input type="radio" name="vProb" value="yes" /> '.&mt('one student').' </label>'."\n"
                    952:                   .'<label><input type="radio" name="vProb" value="all" /> '.&mt('all students').' </label><br />'."\n"
                    953:                   .&Apache::lonhtmlcommon::row_closure();
                    954:     $gradeTable .= &Apache::lonhtmlcommon::row_title(&mt('View Answer'))
                    955:                   .'<label><input type="radio" name="vAns" value="no"  /> '.&mt('no').' </label>'."\n"
                    956:                   .'<label><input type="radio" name="vAns" value="yes" /> '.&mt('one student').' </label>'."\n"
                    957:                   .'<label><input type="radio" name="vAns" value="all" checked="checked" /> '.&mt('all students').' </label><br />'."\n"
                    958:                   .&Apache::lonhtmlcommon::row_closure();
1.485     albertel  959: 
                    960:     my $submission_options;
1.257     albertel  961:     if ($env{'form.handgrade'} eq 'yes' && scalar(@$partlist) > 1) {
1.485     albertel  962: 	$submission_options.=
                    963: 	    '<label><input type="radio" name="lastSub" value="hdgrade" '.$checkhdgrade.' /> '.&mt('essay part only').' </label>'."\n";
1.49      albertel  964:     }
1.442     banghart  965:     my $stu_status = join(':',&Apache::loncommon::get_env_multiple('form.Status'));
                    966:     my $saveStatus = $stu_status eq '' ? 'Active' : $stu_status;
1.257     albertel  967:     $env{'form.Status'} = $saveStatus;
1.485     albertel  968:     $submission_options.=
1.592     bisitz    969:         '<span class="LC_nobreak">'.
                    970:         '<label><input type="radio" name="lastSub" value="lastonly" '.$checklastsub.' /> '.
                    971:         &mt('last submission only').' </label></span>'."\n".
                    972:         '<span class="LC_nobreak">'.
                    973:         '<label><input type="radio" name="lastSub" value="last" /> '.
                    974:         &mt('last submission &amp; parts info').' </label></span>'."\n".
                    975:         '<span class="LC_nobreak">'.
                    976:         '<label><input type="radio" name="lastSub" value="datesub" /> '.
                    977:         &mt('by dates and submissions').'</label></span>'."\n".
                    978:         '<span class="LC_nobreak">'.
                    979:         '<label><input type="radio" name="lastSub" value="all" /> '.
                    980:         &mt('all details').'</label></span>';
1.561     bisitz    981:     $gradeTable .= &Apache::lonhtmlcommon::row_title(&mt('Submissions'))
                    982:                   .$submission_options
                    983:                   .&Apache::lonhtmlcommon::row_closure();
                    984: 
                    985:     $gradeTable .= &Apache::lonhtmlcommon::row_title(&mt('Grading Increments'))
                    986:                   .'<select name="increment">'
                    987:                   .'<option value="1">'.&mt('Whole Points').'</option>'
                    988:                   .'<option value=".5">'.&mt('Half Points').'</option>'
                    989:                   .'<option value=".25">'.&mt('Quarter Points').'</option>'
                    990:                   .'<option value=".1">'.&mt('Tenths of a Point').'</option>'
                    991:                   .'</select>'
                    992:                   .&Apache::lonhtmlcommon::row_closure();
1.485     albertel  993: 
                    994:     $gradeTable .= 
1.432     banghart  995:         &build_section_inputs().
1.45      ng        996: 	'<input type="hidden" name="submitonly"  value="'.$submitonly.'" />'."\n".
1.257     albertel  997: 	'<input type="hidden" name="handgrade"   value="'.$env{'form.handgrade'}.'" /><br />'."\n".
                    998: 	'<input type="hidden" name="showgrading" value="'.$env{'form.showgrading'}.'" /><br />'."\n".
                    999: 	'<input type="hidden" name="saveState"   value="'.$env{'form.saveState'}.'" />'."\n".
                   1000: 	'<input type="hidden" name="probTitle"   value="'.$env{'form.probTitle'}.'" />'."\n".
1.418     albertel 1001: 	'<input type="hidden" name="symb" value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
1.110     ng       1002: 	'<input type="hidden" name="saveStatusOld" value="'.$saveStatus.'" />'."\n";
                   1003: 
1.257     albertel 1004:     if (exists($env{'form.gradingMenu'}) && exists($env{'form.Status'})) {
1.561     bisitz   1005: 	$gradeTable .= '<input type="hidden" name="Status" value="'.$stu_status.'" />'."\n";
1.124     ng       1006:     } else {
1.561     bisitz   1007:         $gradeTable .= &Apache::lonhtmlcommon::row_title(&mt('Student Status'))
                   1008:                       .&Apache::lonhtmlcommon::StatusOptions(
                   1009:                            $saveStatus,undef,1,'javascript:reLoadList(this.form);')
                   1010:                       .&Apache::lonhtmlcommon::row_closure();
1.124     ng       1011:     }
1.112     ng       1012: 
1.561     bisitz   1013:     $gradeTable .= &Apache::lonhtmlcommon::row_title(&mt('Check For Plagiarism'))
                   1014:                   .'<input type="checkbox" name="checkPlag" checked="checked" />'
                   1015:                   .&Apache::lonhtmlcommon::row_closure(1)
                   1016:                   .&Apache::lonhtmlcommon::end_pick_box();
                   1017: 
                   1018:     $gradeTable .= '<p>'
                   1019:                   .&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"
                   1020:                   .'<input type="hidden" name="command" value="processGroup" />'
                   1021:                   .'</p>';
1.249     albertel 1022: 
                   1023: # checkall buttons
                   1024:     $gradeTable.=&check_script('gradesub', 'stuinfo');
1.110     ng       1025:     $gradeTable.='<input type="button" '."\n".
1.589     bisitz   1026:         'onclick="javascript:checkSelect(this.form.stuinfo);" '."\n".
                   1027:         'value="'.&mt('Next').' &rarr;" /> <br />'."\n";
1.249     albertel 1028:     $gradeTable.=&check_buttons();
1.450     banghart 1029:     my ($classlist, undef, $fullname) = &getclasslist($getsec,'1',$getgroup);
1.474     albertel 1030:     $gradeTable.= &Apache::loncommon::start_data_table().
                   1031: 	&Apache::loncommon::start_data_table_header_row();
1.110     ng       1032:     my $loop = 0;
                   1033:     while ($loop < 2) {
1.485     albertel 1034: 	$gradeTable.='<th>'.&mt('No.').'</th><th>'.&mt('Select').'</th>'.
                   1035: 	    '<th>'.&nameUserString('header').'&nbsp;'.&mt('Section/Group').'</th>';
1.301     albertel 1036: 	if ($env{'form.showgrading'} eq 'yes' 
                   1037: 	    && $submitonly ne 'queued'
                   1038: 	    && $submitonly ne 'all') {
1.485     albertel 1039: 	    foreach my $part (sort(@$partlist)) {
                   1040: 		my $display_part=
                   1041: 		    &get_display_part((split(/_/,$part))[0],$symb);
                   1042: 		$gradeTable.=
                   1043: 		    '<th>'.&mt('Part: [_1] Status',$display_part).'</th>';
1.110     ng       1044: 	    }
1.301     albertel 1045: 	} elsif ($submitonly eq 'queued') {
1.474     albertel 1046: 	    $gradeTable.='<th>'.&mt('Queue Status').'&nbsp;</th>';
1.110     ng       1047: 	}
                   1048: 	$loop++;
1.126     ng       1049: #	$gradeTable.='<td></td>' if ($loop%2 ==1);
1.41      ng       1050:     }
1.474     albertel 1051:     $gradeTable.=&Apache::loncommon::end_data_table_header_row()."\n";
1.41      ng       1052: 
1.45      ng       1053:     my $ctr = 0;
1.294     albertel 1054:     foreach my $student (sort 
                   1055: 			 {
                   1056: 			     if (lc($$fullname{$a}) ne lc($$fullname{$b})) {
                   1057: 				 return (lc($$fullname{$a}) cmp lc($$fullname{$b}));
                   1058: 			     }
                   1059: 			     return $a cmp $b;
                   1060: 			 }
                   1061: 			 (keys(%$fullname))) {
1.41      ng       1062: 	my ($uname,$udom) = split(/:/,$student);
1.301     albertel 1063: 
1.110     ng       1064: 	my %status = ();
1.301     albertel 1065: 
                   1066: 	if ($submitonly eq 'queued') {
                   1067: 	    my %queue_status = 
                   1068: 		&Apache::bridgetask::get_student_status($symb,$cdom,$cnum,
                   1069: 							$udom,$uname);
                   1070: 	    next if (!defined($queue_status{'gradingqueue'}));
                   1071: 	    $status{'gradingqueue'} = $queue_status{'gradingqueue'};
                   1072: 	}
                   1073: 
                   1074: 	if ($env{'form.showgrading'} eq 'yes' 
                   1075: 	    && $submitonly ne 'queued'
                   1076: 	    && $submitonly ne 'all') {
1.324     albertel 1077: 	    (%status) =&student_gradeStatus($symb,$udom,$uname,$partlist);
1.145     albertel 1078: 	    my $submitted = 0;
1.164     albertel 1079: 	    my $graded = 0;
1.248     albertel 1080: 	    my $incorrect = 0;
1.110     ng       1081: 	    foreach (keys(%status)) {
1.145     albertel 1082: 		$submitted = 1 if ($status{$_} ne 'nothing');
1.248     albertel 1083: 		$graded = 1 if ($status{$_} =~ /^ungraded/);
                   1084: 		$incorrect = 1 if ($status{$_} =~ /^incorrect/);
                   1085: 		
1.110     ng       1086: 		my ($foo,$partid,$foo1) = split(/\./,$_);
                   1087: 		if ($status{'resource.'.$partid.'.submitted_by'} ne '') {
1.145     albertel 1088: 		    $submitted = 0;
1.150     albertel 1089: 		    my ($part)=split(/\./,$partid);
1.110     ng       1090: 		    $gradeTable.='<input type="hidden" name="'.
1.150     albertel 1091: 			$student.':'.$part.':submitted_by" value="'.
1.110     ng       1092: 			$status{'resource.'.$partid.'.submitted_by'}.'" />';
                   1093: 		}
1.41      ng       1094: 	    }
1.248     albertel 1095: 	    
1.156     albertel 1096: 	    next if (!$submitted && ($submitonly eq 'yes' ||
                   1097: 				     $submitonly eq 'incorrect' ||
                   1098: 				     $submitonly eq 'graded'));
1.248     albertel 1099: 	    next if (!$graded && ($submitonly eq 'graded'));
                   1100: 	    next if (!$incorrect && $submitonly eq 'incorrect');
1.41      ng       1101: 	}
1.34      ng       1102: 
1.45      ng       1103: 	$ctr++;
1.249     albertel 1104: 	my $section = $classlist->{$student}->[&Apache::loncoursedata::CL_SECTION()];
1.452     banghart 1105:         my $group = $classlist->{$student}->[&Apache::loncoursedata::CL_GROUP()];
1.104     albertel 1106: 	if ( $perm{'vgr'} eq 'F' ) {
1.474     albertel 1107: 	    if ($ctr%2 ==1) {
                   1108: 		$gradeTable.= &Apache::loncommon::start_data_table_row();
                   1109: 	    }
1.126     ng       1110: 	    $gradeTable.='<td align="right">'.$ctr.'&nbsp;</td>'.
1.563     bisitz   1111:                '<td align="center"><label><input type="checkbox" name="stuinfo" value="'.
1.249     albertel 1112:                $student.':'.$$fullname{$student}.':::SECTION'.$section.
                   1113: 	       ')&nbsp;" />&nbsp;&nbsp;</label></td>'."\n".'<td>'.
                   1114: 	       &nameUserString(undef,$$fullname{$student},$uname,$udom).
1.474     albertel 1115: 	       '&nbsp;'.$section.($group ne '' ?'/'.$group:'').'</td>'."\n";
1.110     ng       1116: 
1.257     albertel 1117: 	    if ($env{'form.showgrading'} eq 'yes' && $submitonly ne 'all') {
1.524     raeburn  1118: 		foreach (sort(keys(%status))) {
1.485     albertel 1119: 		    next if ($_ =~ /^resource.*?submitted_by$/);
                   1120: 		    $gradeTable.='<td align="center">&nbsp;'.&mt($status{$_}).'&nbsp;</td>'."\n";
1.110     ng       1121: 		}
1.41      ng       1122: 	    }
1.126     ng       1123: #	    $gradeTable.='<td></td>' if ($ctr%2 ==1);
1.474     albertel 1124: 	    if ($ctr%2 ==0) {
                   1125: 		$gradeTable.=&Apache::loncommon::end_data_table_row()."\n";
                   1126: 	    }
1.41      ng       1127: 	}
                   1128:     }
1.110     ng       1129:     if ($ctr%2 ==1) {
1.126     ng       1130: 	$gradeTable.='<td>&nbsp;</td><td>&nbsp;</td><td>&nbsp;</td>';
1.301     albertel 1131: 	    if ($env{'form.showgrading'} eq 'yes' 
                   1132: 		&& $submitonly ne 'queued'
                   1133: 		&& $submitonly ne 'all') {
1.110     ng       1134: 		foreach (@$partlist) {
                   1135: 		    $gradeTable.='<td>&nbsp;</td>';
                   1136: 		}
1.301     albertel 1137: 	    } elsif ($submitonly eq 'queued') {
                   1138: 		$gradeTable.='<td>&nbsp;</td>';
1.110     ng       1139: 	    }
1.474     albertel 1140: 	$gradeTable.=&Apache::loncommon::end_data_table_row();
1.110     ng       1141:     }
                   1142: 
1.474     albertel 1143:     $gradeTable.=&Apache::loncommon::end_data_table()."\n".
1.589     bisitz   1144:         '<input type="button" '.
                   1145:         'onclick="javascript:checkSelect(this.form.stuinfo);" '.
                   1146:         'value="'.&mt('Next').' &rarr;" /></form>'."\n";
1.45      ng       1147:     if ($ctr == 0) {
1.96      albertel 1148: 	my $num_students=(scalar(keys(%$fullname)));
                   1149: 	if ($num_students eq 0) {
1.485     albertel 1150: 	    $gradeTable='<br />&nbsp;<span class="LC_warning">'.&mt('There are no students currently enrolled.').'</span>';
1.96      albertel 1151: 	} else {
1.171     albertel 1152: 	    my $submissions='submissions';
                   1153: 	    if ($submitonly eq 'incorrect') { $submissions = 'incorrect submissions'; }
                   1154: 	    if ($submitonly eq 'graded'   ) { $submissions = 'ungraded submissions'; }
1.301     albertel 1155: 	    if ($submitonly eq 'queued'   ) { $submissions = 'queued submissions'; }
1.398     albertel 1156: 	    $gradeTable='<br />&nbsp;<span class="LC_warning">'.
1.485     albertel 1157: 		&mt('No '.$submissions.' found for this resource for any students. ([_1] students checked for '.$submissions.')',
                   1158: 		    $num_students).
                   1159: 		'</span><br />';
1.96      albertel 1160: 	}
1.46      ng       1161:     } elsif ($ctr == 1) {
1.474     albertel 1162: 	$gradeTable =~ s/type="checkbox"/type="checkbox" checked="checked"/;
1.45      ng       1163:     }
1.324     albertel 1164:     $gradeTable.=&show_grading_menu_form($symb);
1.45      ng       1165:     $request->print($gradeTable);
1.44      ng       1166:     return '';
1.10      ng       1167: }
                   1168: 
1.44      ng       1169: #---- Called from the listStudents routine
1.249     albertel 1170: 
                   1171: sub check_script {
                   1172:     my ($form, $type)=@_;
                   1173:     my $chkallscript='<script type="text/javascript">
                   1174:     function checkall() {
                   1175:         for (i=0; i<document.forms.'.$form.'.elements.length; i++) {
                   1176:             ele = document.forms.'.$form.'.elements[i];
                   1177:             if (ele.name == "'.$type.'") {
                   1178:             document.forms.'.$form.'.elements[i].checked=true;
                   1179:                                        }
                   1180:         }
                   1181:     }
                   1182: 
                   1183:     function checksec() {
                   1184:         for (i=0; i<document.forms.'.$form.'.elements.length; i++) {
                   1185:             ele = document.forms.'.$form.'.elements[i];
                   1186:            string = document.forms.'.$form.'.chksec.value;
                   1187:            if
                   1188:           (ele.value.indexOf(":::SECTION"+string)>0) {
                   1189:               document.forms.'.$form.'.elements[i].checked=true;
                   1190:             }
                   1191:         }
                   1192:     }
                   1193: 
                   1194: 
                   1195:     function uncheckall() {
                   1196:         for (i=0; i<document.forms.'.$form.'.elements.length; i++) {
                   1197:             ele = document.forms.'.$form.'.elements[i];
                   1198:             if (ele.name == "'.$type.'") {
                   1199:             document.forms.'.$form.'.elements[i].checked=false;
                   1200:                                        }
                   1201:         }
                   1202:     }
                   1203: 
                   1204: </script>'."\n";
                   1205:     return $chkallscript;
                   1206: }
                   1207: 
                   1208: sub check_buttons {
1.485     albertel 1209:     my $buttons.='<input type="button" onclick="checkall()" value="'.&mt('Check All').'" />';
                   1210:     $buttons.='<input type="button" onclick="uncheckall()" value="'.&mt('Uncheck All').'" />&nbsp;';
                   1211:     $buttons.='<input type="button" onclick="checksec()" value="'.&mt('Check Section/Group').'" />';
1.249     albertel 1212:     $buttons.='<input type="text" size="5" name="chksec" />&nbsp;';
                   1213:     return $buttons;
                   1214: }
                   1215: 
1.44      ng       1216: #     Displays the submissions for one student or a group of students
1.34      ng       1217: sub processGroup {
1.41      ng       1218:     my ($request)  = shift;
                   1219:     my $ctr        = 0;
1.155     albertel 1220:     my @stuchecked = &Apache::loncommon::get_env_multiple('form.stuinfo');
1.41      ng       1221:     my $total      = scalar(@stuchecked)-1;
1.45      ng       1222: 
1.396     banghart 1223:     foreach my $student (@stuchecked) {
                   1224: 	my ($uname,$udom,$fullname) = split(/:/,$student);
1.257     albertel 1225: 	$env{'form.student'}        = $uname;
                   1226: 	$env{'form.userdom'}        = $udom;
                   1227: 	$env{'form.fullname'}       = $fullname;
1.41      ng       1228: 	&submission($request,$ctr,$total);
                   1229: 	$ctr++;
                   1230:     }
                   1231:     return '';
1.35      ng       1232: }
1.34      ng       1233: 
1.44      ng       1234: #------------------------------------------------------------------------------------
                   1235: #
                   1236: #-------------------------- Next few routines handles grading by student, essentially
                   1237: #                           handles essay response type problem/part
                   1238: #
                   1239: #--- Javascript to handle the submission page functionality ---
                   1240: sub sub_page_js {
                   1241:     my $request = shift;
1.539     riegler  1242: 	    my $alertmsg = &mt('A number equal or greater than 0 is expected. Entered value = ');
1.44      ng       1243:     $request->print(<<SUBJAVASCRIPT);
                   1244: <script type="text/javascript" language="javascript">
1.71      ng       1245:     function updateRadio(formname,id,weight) {
1.125     ng       1246: 	var gradeBox = formname["GD_BOX"+id];
                   1247: 	var radioButton = formname["RADVAL"+id];
                   1248: 	var oldpts = formname["oldpts"+id].value;
1.72      ng       1249: 	var pts = checkSolved(formname,id) == 'update' ? gradeBox.value : oldpts;
1.71      ng       1250: 	gradeBox.value = pts;
                   1251: 	var resetbox = false;
                   1252: 	if (isNaN(pts) || pts < 0) {
1.539     riegler  1253: 	    alert("$alertmsg"+pts);
1.71      ng       1254: 	    for (var i=0; i<radioButton.length; i++) {
                   1255: 		if (radioButton[i].checked) {
                   1256: 		    gradeBox.value = i;
                   1257: 		    resetbox = true;
                   1258: 		}
                   1259: 	    }
                   1260: 	    if (!resetbox) {
                   1261: 		formtextbox.value = "";
                   1262: 	    }
                   1263: 	    return;
1.44      ng       1264: 	}
1.71      ng       1265: 
                   1266: 	if (pts > weight) {
                   1267: 	    var resp = confirm("You entered a value ("+pts+
                   1268: 			       ") greater than the weight for the part. Accept?");
                   1269: 	    if (resp == false) {
1.125     ng       1270: 		gradeBox.value = oldpts;
1.71      ng       1271: 		return;
                   1272: 	    }
1.44      ng       1273: 	}
1.13      albertel 1274: 
1.71      ng       1275: 	for (var i=0; i<radioButton.length; i++) {
                   1276: 	    radioButton[i].checked=false;
                   1277: 	    if (pts == i && pts != "") {
                   1278: 		radioButton[i].checked=true;
                   1279: 	    }
                   1280: 	}
                   1281: 	updateSelect(formname,id);
1.125     ng       1282: 	formname["stores"+id].value = "0";
1.41      ng       1283:     }
1.5       albertel 1284: 
1.72      ng       1285:     function writeBox(formname,id,pts) {
1.125     ng       1286: 	var gradeBox = formname["GD_BOX"+id];
1.71      ng       1287: 	if (checkSolved(formname,id) == 'update') {
                   1288: 	    gradeBox.value = pts;
                   1289: 	} else {
1.125     ng       1290: 	    var oldpts = formname["oldpts"+id].value;
1.72      ng       1291: 	    gradeBox.value = oldpts;
1.125     ng       1292: 	    var radioButton = formname["RADVAL"+id];
1.71      ng       1293: 	    for (var i=0; i<radioButton.length; i++) {
                   1294: 		radioButton[i].checked=false;
1.72      ng       1295: 		if (i == oldpts) {
1.71      ng       1296: 		    radioButton[i].checked=true;
                   1297: 		}
                   1298: 	    }
1.41      ng       1299: 	}
1.125     ng       1300: 	formname["stores"+id].value = "0";
1.71      ng       1301: 	updateSelect(formname,id);
                   1302: 	return;
1.41      ng       1303:     }
1.44      ng       1304: 
1.71      ng       1305:     function clearRadBox(formname,id) {
                   1306: 	if (checkSolved(formname,id) == 'noupdate') {
                   1307: 	    updateSelect(formname,id);
                   1308: 	    return;
                   1309: 	}
1.125     ng       1310: 	gradeSelect = formname["GD_SEL"+id];
1.71      ng       1311: 	for (var i=0; i<gradeSelect.length; i++) {
                   1312: 	    if (gradeSelect[i].selected) {
                   1313: 		var selectx=i;
                   1314: 	    }
                   1315: 	}
1.125     ng       1316: 	var stores = formname["stores"+id];
1.71      ng       1317: 	if (selectx == stores.value) { return };
1.125     ng       1318: 	var gradeBox = formname["GD_BOX"+id];
1.71      ng       1319: 	gradeBox.value = "";
1.125     ng       1320: 	var radioButton = formname["RADVAL"+id];
1.71      ng       1321: 	for (var i=0; i<radioButton.length; i++) {
                   1322: 	    radioButton[i].checked=false;
                   1323: 	}
                   1324: 	stores.value = selectx;
                   1325:     }
1.5       albertel 1326: 
1.71      ng       1327:     function checkSolved(formname,id) {
1.125     ng       1328: 	if (formname["solved"+id].value == "correct_by_student" && formname.overRideScore.value == 'no') {
1.118     ng       1329: 	    var reply = confirm("This problem has been graded correct by the computer. Do you want to change the score?");
                   1330: 	    if (!reply) {return "noupdate";}
1.120     ng       1331: 	    formname.overRideScore.value = 'yes';
1.41      ng       1332: 	}
1.71      ng       1333: 	return "update";
1.13      albertel 1334:     }
1.71      ng       1335: 
                   1336:     function updateSelect(formname,id) {
1.125     ng       1337: 	formname["GD_SEL"+id][0].selected = true;
1.71      ng       1338: 	return;
1.41      ng       1339:     }
1.33      ng       1340: 
1.121     ng       1341: //=========== Check that a point is assigned for all the parts  ============
1.71      ng       1342:     function checksubmit(formname,val,total,parttot) {
1.121     ng       1343: 	formname.gradeOpt.value = val;
1.71      ng       1344: 	if (val == "Save & Next") {
                   1345: 	    for (i=0;i<=total;i++) {
                   1346: 		for (j=0;j<parttot;j++) {
1.125     ng       1347: 		    var partid = formname["partid"+i+"_"+j].value;
1.127     ng       1348: 		    if (formname["GD_SEL"+i+"_"+partid][0].selected) {
1.125     ng       1349: 			var points = formname["GD_BOX"+i+"_"+partid].value;
1.71      ng       1350: 			if (points == "") {
1.125     ng       1351: 			    var name = formname["name"+i].value;
1.129     ng       1352: 			    var studentID = (name != '' ? name : formname["unamedom"+i].value);
                   1353: 			    var resp = confirm("You did not assign a score for "+studentID+
                   1354: 					       ", part "+partid+". Continue?");
1.71      ng       1355: 			    if (resp == false) {
1.125     ng       1356: 				formname["GD_BOX"+i+"_"+partid].focus();
1.71      ng       1357: 				return false;
                   1358: 			    }
                   1359: 			}
                   1360: 		    }
                   1361: 		    
                   1362: 		}
                   1363: 	    }
                   1364: 	    
                   1365: 	}
1.121     ng       1366: 	if (val == "Grade Student") {
                   1367: 	    formname.showgrading.value = "yes";
                   1368: 	    if (formname.Status.value == "") {
                   1369: 		formname.Status.value = "Active";
                   1370: 	    }
                   1371: 	    formname.studentNo.value = total;
                   1372: 	}
1.120     ng       1373: 	formname.submit();
                   1374:     }
                   1375: 
1.71      ng       1376: //======= Check that a score is assigned for all the problems (page/sequence grading only) =========
                   1377:     function checkSubmitPage(formname,total) {
                   1378: 	noscore = new Array(100);
                   1379: 	var ptr = 0;
                   1380: 	for (i=1;i<total;i++) {
1.125     ng       1381: 	    var partid = formname["q_"+i].value;
1.127     ng       1382: 	    if (formname["GD_SEL"+i+"_"+partid][0].selected) {
1.125     ng       1383: 		var points = formname["GD_BOX"+i+"_"+partid].value;
                   1384: 		var status = formname["solved"+i+"_"+partid].value;
1.71      ng       1385: 		if (points == "" && status != "correct_by_student") {
                   1386: 		    noscore[ptr] = i;
                   1387: 		    ptr++;
                   1388: 		}
                   1389: 	    }
                   1390: 	}
                   1391: 	if (ptr != 0) {
                   1392: 	    var sense = ptr == 1 ? ": " : "s: ";
                   1393: 	    var prolist = "";
                   1394: 	    if (ptr == 1) {
                   1395: 		prolist = noscore[0];
                   1396: 	    } else {
                   1397: 		var i = 0;
                   1398: 		while (i < ptr-1) {
                   1399: 		    prolist += noscore[i]+", ";
                   1400: 		    i++;
                   1401: 		}
                   1402: 		prolist += "and "+noscore[i];
                   1403: 	    }
                   1404: 	    var resp = confirm("You did not assign any score for the following problem"+sense+prolist+". Continue?");
                   1405: 	    if (resp == false) {
                   1406: 		return false;
                   1407: 	    }
                   1408: 	}
1.45      ng       1409: 
1.71      ng       1410: 	formname.submit();
                   1411:     }
                   1412: </script>
                   1413: SUBJAVASCRIPT
                   1414: }
1.45      ng       1415: 
1.71      ng       1416: #--- javascript for essay type problem --
                   1417: sub sub_page_kw_js {
                   1418:     my $request = shift;
1.80      ng       1419:     my $iconpath = $request->dir_config('lonIconsURL');
1.118     ng       1420:     &commonJSfunctions($request);
1.350     albertel 1421: 
1.351     albertel 1422:     my $inner_js_msg_central=<<INNERJS;
1.350     albertel 1423:     <script text="text/javascript">
                   1424:     function checkInput() {
                   1425:       opener.document.SCORE.msgsub.value = opener.checkEntities(document.msgcenter.msgsub.value);
                   1426:       var nmsg   = opener.document.SCORE.savemsgN.value;
                   1427:       var usrctr = document.msgcenter.usrctr.value;
                   1428:       var newval = opener.document.SCORE["newmsg"+usrctr];
                   1429:       newval.value = opener.checkEntities(document.msgcenter.newmsg.value);
                   1430: 
                   1431:       var msgchk = "";
                   1432:       if (document.msgcenter.subchk.checked) {
                   1433:          msgchk = "msgsub,";
                   1434:       }
                   1435:       var includemsg = 0;
                   1436:       for (var i=1; i<=nmsg; i++) {
                   1437:           var opnmsg = opener.document.SCORE["savemsg"+i];
                   1438:           var frmmsg = document.msgcenter["msg"+i];
                   1439:           opnmsg.value = opener.checkEntities(frmmsg.value);
                   1440:           var showflg = opener.document.SCORE["shownOnce"+i];
                   1441:           showflg.value = "1";
                   1442:           var chkbox = document.msgcenter["msgn"+i];
                   1443:           if (chkbox.checked) {
                   1444:              msgchk += "savemsg"+i+",";
                   1445:              includemsg = 1;
                   1446:           }
                   1447:       }
                   1448:       if (document.msgcenter.newmsgchk.checked) {
                   1449:          msgchk += "newmsg"+usrctr;
                   1450:          includemsg = 1;
                   1451:       }
                   1452:       imgformname = opener.document.SCORE["mailicon"+usrctr];
                   1453:       imgformname.src = "$iconpath/"+((includemsg) ? "mailto.gif" : "mailbkgrd.gif");
                   1454:       var includemsg = opener.document.SCORE["includemsg"+usrctr];
                   1455:       includemsg.value = msgchk;
                   1456: 
                   1457:       self.close()
                   1458: 
                   1459:     }
                   1460:     </script>
                   1461: INNERJS
                   1462: 
1.351     albertel 1463:     my $inner_js_highlight_central=<<INNERJS;
                   1464:  <script type="text/javascript">
                   1465:     function updateChoice(flag) {
                   1466:       opener.document.SCORE.kwclr.value = opener.radioSelection(document.hlCenter.kwdclr);
                   1467:       opener.document.SCORE.kwsize.value = opener.radioSelection(document.hlCenter.kwdsize);
                   1468:       opener.document.SCORE.kwstyle.value = opener.radioSelection(document.hlCenter.kwdstyle);
                   1469:       opener.document.SCORE.refresh.value = "on";
                   1470:       if (opener.document.SCORE.keywords.value!=""){
                   1471:          opener.document.SCORE.submit();
                   1472:       }
                   1473:       self.close()
                   1474:     }
                   1475: </script>
                   1476: INNERJS
                   1477: 
                   1478:     my $start_page_msg_central = 
                   1479:         &Apache::loncommon::start_page('Message Central',$inner_js_msg_central,
                   1480: 				       {'js_ready'  => 1,
                   1481: 					'only_body' => 1,
                   1482: 					'bgcolor'   =>'#FFFFFF',});
                   1483:     my $end_page_msg_central = 
                   1484: 	&Apache::loncommon::end_page({'js_ready' => 1});
                   1485: 
                   1486: 
                   1487:     my $start_page_highlight_central = 
                   1488:         &Apache::loncommon::start_page('Highlight Central',
                   1489: 				       $inner_js_highlight_central,
1.350     albertel 1490: 				       {'js_ready'  => 1,
                   1491: 					'only_body' => 1,
                   1492: 					'bgcolor'   =>'#FFFFFF',});
1.351     albertel 1493:     my $end_page_highlight_central = 
1.350     albertel 1494: 	&Apache::loncommon::end_page({'js_ready' => 1});
                   1495: 
1.219     www      1496:     my $docopen=&Apache::lonhtmlcommon::javascript_docopen();
1.236     albertel 1497:     $docopen=~s/^document\.//;
1.596.2.4  raeburn  1498:     my %lt = &Apache::lonlocal::texthash(
                   1499:                 keyw => 'Keywords list, separated by a space. Add/delete to list if desired.',
                   1500:                 plse => 'Please select a word or group of words from document and then click this link.',
                   1501:                 adds => 'Add selection to keyword list? Edit if desired.',
                   1502:                 comp => 'Compose Message for: ',
                   1503:                 incl => 'Include',
                   1504:                 type => 'Type',
                   1505:                 subj => 'Subject',
                   1506:                 mesa => 'Message',
                   1507:                 new  => 'New',
                   1508:                 save => 'Save',
                   1509:                 canc => 'Cancel',
                   1510:                 kehi => 'Keyword Highlight Options',
                   1511:                 txtc => 'Text Color',
                   1512:                 font => 'Font Size',
                   1513:                 fnst => 'Font Style',
                   1514:              );
1.71      ng       1515:     $request->print(<<SUBJAVASCRIPT);
                   1516: <script type="text/javascript" language="javascript">
1.45      ng       1517: 
1.44      ng       1518: //===================== Show list of keywords ====================
1.122     ng       1519:   function keywords(formname) {
1.596.2.4  raeburn  1520:     var nret = prompt("$lt{'keyw'}",formname.keywords.value);
1.44      ng       1521:     if (nret==null) return;
1.122     ng       1522:     formname.keywords.value = nret;
1.44      ng       1523: 
1.122     ng       1524:     if (formname.keywords.value != "") {
1.128     ng       1525: 	formname.refresh.value = "on";
1.122     ng       1526: 	formname.submit();
1.44      ng       1527:     }
                   1528:     return;
                   1529:   }
                   1530: 
                   1531: //===================== Script to view submitted by ==================
                   1532:   function viewSubmitter(submitter) {
                   1533:     document.SCORE.refresh.value = "on";
                   1534:     document.SCORE.NCT.value = "1";
                   1535:     document.SCORE.unamedom0.value = submitter;
                   1536:     document.SCORE.submit();
                   1537:     return;
                   1538:   }
                   1539: 
                   1540: //===================== Script to add keyword(s) ==================
                   1541:   function getSel() {
                   1542:     if (document.getSelection) txt = document.getSelection();
                   1543:     else if (document.selection) txt = document.selection.createRange().text;
                   1544:     else return;
                   1545:     var cleantxt = txt.replace(new RegExp('([\\f\\n\\r\\t\\v ])+', 'g')," ");
                   1546:     if (cleantxt=="") {
1.596.2.4  raeburn  1547: 	alert("$lt{'plse'}");
1.44      ng       1548: 	return;
                   1549:     }
1.596.2.4  raeburn  1550:     var nret = prompt("$lt{'adds'}",cleantxt);
1.44      ng       1551:     if (nret==null) return;
1.127     ng       1552:     document.SCORE.keywords.value = document.SCORE.keywords.value+" "+nret;
1.44      ng       1553:     if (document.SCORE.keywords.value != "") {
1.127     ng       1554: 	document.SCORE.refresh.value = "on";
1.44      ng       1555: 	document.SCORE.submit();
                   1556:     }
                   1557:     return;
                   1558:   }
                   1559: 
                   1560: //====================== Script for composing message ==============
1.80      ng       1561:    // preload images
                   1562:    img1 = new Image();
                   1563:    img1.src = "$iconpath/mailbkgrd.gif";
                   1564:    img2 = new Image();
                   1565:    img2.src = "$iconpath/mailto.gif";
                   1566: 
1.44      ng       1567:   function msgCenter(msgform,usrctr,fullname) {
                   1568:     var Nmsg  = msgform.savemsgN.value;
                   1569:     savedMsgHeader(Nmsg,usrctr,fullname);
                   1570:     var subject = msgform.msgsub.value;
1.127     ng       1571:     var msgchk = document.SCORE["includemsg"+usrctr].value;
1.44      ng       1572:     re = /msgsub/;
                   1573:     var shwsel = "";
                   1574:     if (re.test(msgchk)) { shwsel = "checked" }
1.123     ng       1575:     subject = (document.SCORE.shownSub.value == 0 ? checkEntities(subject) : subject);
                   1576:     displaySubject(checkEntities(subject),shwsel);
1.44      ng       1577:     for (var i=1; i<=Nmsg; i++) {
1.123     ng       1578: 	var testmsg = "savemsg"+i+",";
                   1579: 	re = new RegExp(testmsg,"g");
1.44      ng       1580: 	shwsel = "";
                   1581: 	if (re.test(msgchk)) { shwsel = "checked" }
1.125     ng       1582: 	var message = document.SCORE["savemsg"+i].value;
1.126     ng       1583: 	message = (document.SCORE["shownOnce"+i].value == 0 ? checkEntities(message) : message);
1.123     ng       1584: 	displaySavedMsg(i,message,shwsel); //I do not get it. w/o checkEntities on saved messages,
                   1585: 	                                   //any &lt; is already converted to <, etc. However, only once!!
1.44      ng       1586:     }
1.125     ng       1587:     newmsg = document.SCORE["newmsg"+usrctr].value;
1.44      ng       1588:     shwsel = "";
                   1589:     re = /newmsg/;
                   1590:     if (re.test(msgchk)) { shwsel = "checked" }
                   1591:     newMsg(newmsg,shwsel);
                   1592:     msgTail(); 
                   1593:     return;
                   1594:   }
                   1595: 
1.123     ng       1596:   function checkEntities(strx) {
                   1597:     if (strx.length == 0) return strx;
                   1598:     var orgStr = ["&", "<", ">", '"']; 
                   1599:     var newStr = ["&amp;", "&lt;", "&gt;", "&quot;"];
                   1600:     var counter = 0;
                   1601:     while (counter < 4) {
                   1602: 	strx = strReplace(strx,orgStr[counter],newStr[counter]);
                   1603: 	counter++;
                   1604:     }
                   1605:     return strx;
                   1606:   }
                   1607: 
                   1608:   function strReplace(strx, orgStr, newStr) {
                   1609:     return strx.split(orgStr).join(newStr);
                   1610:   }
                   1611: 
1.44      ng       1612:   function savedMsgHeader(Nmsg,usrctr,fullname) {
1.76      ng       1613:     var height = 70*Nmsg+250;
1.44      ng       1614:     var scrollbar = "no";
                   1615:     if (height > 600) {
                   1616: 	height = 600;
                   1617: 	scrollbar = "yes";
                   1618:     }
1.118     ng       1619:     var xpos = (screen.width-600)/2;
                   1620:     xpos = (xpos < 0) ? '0' : xpos;
                   1621:     var ypos = (screen.height-height)/2-30;
                   1622:     ypos = (ypos < 0) ? '0' : ypos;
                   1623: 
1.596.2.4  raeburn  1624:     pWin = window.open('', 'MessageCenter', 'resizable=yes,toolbar=no,location=no,scrollbars='+scrollbar+',screenx='+xpos+',screeny='+ypos+',width=700,height='+height);
1.76      ng       1625:     pWin.focus();
                   1626:     pDoc = pWin.document;
1.219     www      1627:     pDoc.$docopen;
1.351     albertel 1628:     pDoc.write('$start_page_msg_central');
1.76      ng       1629: 
                   1630:     pDoc.write("<form action=\\"inactive\\" name=\\"msgcenter\\">");
                   1631:     pDoc.write("<input value=\\""+usrctr+"\\" name=\\"usrctr\\" type=\\"hidden\\">");
1.596.2.4  raeburn  1632:     pDoc.write("<h3><span class=\\"LC_info\\">&nbsp;$lt{'comp'}\"+fullname+\"<\\/span><\\/h3><br /><br />");
1.76      ng       1633: 
1.564     bisitz   1634:     pDoc.write('<table border="0" width="100%"><tr><td bgcolor="#777777">');
                   1635:     pDoc.write('<table border="0" width="100%"><tr bgcolor="#DDFFFF">');
1.596.2.4  raeburn  1636:     pDoc.write("<td><b>$lt{'type'}<\\/b><\\/td><td><b>$lt{'incl'}<\\/b><\\/td><td><b>$lt{'mesa'}<\\/td><\\/tr>");
1.44      ng       1637: }
                   1638:     function displaySubject(msg,shwsel) {
1.76      ng       1639:     pDoc = pWin.document;
                   1640:     pDoc.write("<tr bgcolor=\\"#ffffdd\\">");
1.596.2.4  raeburn  1641:     pDoc.write("<td>$lt{'subj'}<\\/td>");
1.465     albertel 1642:     pDoc.write("<td align=\\"center\\"><input name=\\"subchk\\" type=\\"checkbox\\"" +shwsel+"><\\/td>");
                   1643:     pDoc.write("<td><input name=\\"msgsub\\" type=\\"text\\" value=\\""+msg+"\\"size=\\"60\\" maxlength=\\"80\\"><\\/td><\\/tr>");
1.44      ng       1644: }
                   1645: 
1.72      ng       1646:   function displaySavedMsg(ctr,msg,shwsel) {
1.76      ng       1647:     pDoc = pWin.document;
                   1648:     pDoc.write("<tr bgcolor=\\"#ffffdd\\">");
1.465     albertel 1649:     pDoc.write("<td align=\\"center\\">"+ctr+"<\\/td>");
                   1650:     pDoc.write("<td align=\\"center\\"><input name=\\"msgn"+ctr+"\\" type=\\"checkbox\\"" +shwsel+"><\\/td>");
                   1651:     pDoc.write("<td><textarea name=\\"msg"+ctr+"\\" cols=\\"60\\" rows=\\"3\\">"+msg+"<\\/textarea><\\/td><\\/tr>");
1.44      ng       1652: }
                   1653: 
                   1654:   function newMsg(newmsg,shwsel) {
1.76      ng       1655:     pDoc = pWin.document;
                   1656:     pDoc.write("<tr bgcolor=\\"#ffffdd\\">");
1.596.2.4  raeburn  1657:     pDoc.write("<td align=\\"center\\">$lt{'new'}<\\/td>");
1.465     albertel 1658:     pDoc.write("<td align=\\"center\\"><input name=\\"newmsgchk\\" type=\\"checkbox\\"" +shwsel+"><\\/td>");
                   1659:     pDoc.write("<td><textarea name=\\"newmsg\\" cols=\\"60\\" rows=\\"3\\" onchange=\\"javascript:this.form.newmsgchk.checked=true\\" >"+newmsg+"<\\/textarea><\\/td><\\/tr>");
1.44      ng       1660: }
                   1661: 
                   1662:   function msgTail() {
1.76      ng       1663:     pDoc = pWin.document;
1.465     albertel 1664:     pDoc.write("<\\/table>");
                   1665:     pDoc.write("<\\/td><\\/tr><\\/table>&nbsp;");
1.596.2.4  raeburn  1666:     pDoc.write("<input type=\\"button\\" value=\\"$lt{'save'}\\" onclick=\\"javascript:checkInput()\\">&nbsp;&nbsp;");
                   1667:     pDoc.write("<input type=\\"button\\" value=\\"$lt{'canc'}\\" onclick=\\"self.close()\\"><br /><br />");
1.465     albertel 1668:     pDoc.write("<\\/form>");
1.351     albertel 1669:     pDoc.write('$end_page_msg_central');
1.128     ng       1670:     pDoc.close();
1.44      ng       1671: }
                   1672: 
                   1673: //====================== Script for keyword highlight options ==============
                   1674:   function kwhighlight() {
                   1675:     var kwclr    = document.SCORE.kwclr.value;
                   1676:     var kwsize   = document.SCORE.kwsize.value;
                   1677:     var kwstyle  = document.SCORE.kwstyle.value;
                   1678:     var redsel = "";
                   1679:     var grnsel = "";
                   1680:     var blusel = "";
                   1681:     if (kwclr=="red")   {var redsel="checked"};
                   1682:     if (kwclr=="green") {var grnsel="checked"};
                   1683:     if (kwclr=="blue")  {var blusel="checked"};
                   1684:     var sznsel = "";
                   1685:     var sz1sel = "";
                   1686:     var sz2sel = "";
                   1687:     if (kwsize=="0")  {var sznsel="checked"};
                   1688:     if (kwsize=="+1") {var sz1sel="checked"};
                   1689:     if (kwsize=="+2") {var sz2sel="checked"};
                   1690:     var synsel = "";
                   1691:     var syisel = "";
                   1692:     var sybsel = "";
                   1693:     if (kwstyle=="")    {var synsel="checked"};
                   1694:     if (kwstyle=="<i>") {var syisel="checked"};
                   1695:     if (kwstyle=="<b>") {var sybsel="checked"};
                   1696:     highlightCentral();
                   1697:     highlightbody('red','red',redsel,'0','normal',sznsel,'','normal',synsel);
                   1698:     highlightbody('green','green',grnsel,'+1','+1',sz1sel,'<i>','italic',syisel);
                   1699:     highlightbody('blue','blue',blusel,'+2','+2',sz2sel,'<b>','bold',sybsel);
                   1700:     highlightend();
                   1701:     return;
                   1702:   }
                   1703: 
                   1704:   function highlightCentral() {
1.76      ng       1705: //    if (window.hwdWin) window.hwdWin.close();
1.118     ng       1706:     var xpos = (screen.width-400)/2;
                   1707:     xpos = (xpos < 0) ? '0' : xpos;
                   1708:     var ypos = (screen.height-330)/2-30;
                   1709:     ypos = (ypos < 0) ? '0' : ypos;
                   1710: 
1.206     albertel 1711:     hwdWin = window.open('', 'KeywordHighlightCentral', 'resizeable=yes,toolbar=no,location=no,scrollbars=no,width=400,height=300,screenx='+xpos+',screeny='+ypos);
1.76      ng       1712:     hwdWin.focus();
                   1713:     var hDoc = hwdWin.document;
1.219     www      1714:     hDoc.$docopen;
1.351     albertel 1715:     hDoc.write('$start_page_highlight_central');
1.76      ng       1716:     hDoc.write("<form action=\\"inactive\\" name=\\"hlCenter\\">");
1.596.2.4  raeburn  1717:     hDoc.write("<h3><span class=\\"LC_info\\">&nbsp;$lt{'kehi'}<\\/span><\\/h3><br /><br />");
1.76      ng       1718: 
1.564     bisitz   1719:     hDoc.write('<table border="0" width="100%"><tr><td bgcolor="#777777">');
                   1720:     hDoc.write('<table border="0" width="100%"><tr bgcolor="#DDFFFF">');
1.596.2.4  raeburn  1721:     hDoc.write("<td><b>$lt{'txtc'}<\\/b><\\/td><td><b>$lt{'font'}<\\/b><\\/td><td><b>$lt{'fnst'}<\\/td><\\/tr>");
1.44      ng       1722:   }
                   1723: 
                   1724:   function highlightbody(clrval,clrtxt,clrsel,szval,sztxt,szsel,syval,sytxt,sysel) { 
1.76      ng       1725:     var hDoc = hwdWin.document;
                   1726:     hDoc.write("<tr bgcolor=\\"#ffffdd\\">");
                   1727:     hDoc.write("<td align=\\"left\\">");
1.465     albertel 1728:     hDoc.write("<input name=\\"kwdclr\\" type=\\"radio\\" value=\\""+clrval+"\\" "+clrsel+">&nbsp;"+clrtxt+"<\\/td>");
1.76      ng       1729:     hDoc.write("<td align=\\"left\\">");
1.465     albertel 1730:     hDoc.write("<input name=\\"kwdsize\\" type=\\"radio\\" value=\\""+szval+"\\" "+szsel+">&nbsp;"+sztxt+"<\\/td>");
1.76      ng       1731:     hDoc.write("<td align=\\"left\\">");
1.465     albertel 1732:     hDoc.write("<input name=\\"kwdstyle\\" type=\\"radio\\" value=\\""+syval+"\\" "+sysel+">&nbsp;"+sytxt+"<\\/td>");
                   1733:     hDoc.write("<\\/tr>");
1.44      ng       1734:   }
                   1735: 
                   1736:   function highlightend() { 
1.76      ng       1737:     var hDoc = hwdWin.document;
1.465     albertel 1738:     hDoc.write("<\\/table>");
                   1739:     hDoc.write("<\\/td><\\/tr><\\/table>&nbsp;");
1.596.2.4  raeburn  1740:     hDoc.write("<input type=\\"button\\" value=\\"$lt{'save'}\\" onclick=\\"javascript:updateChoice(1)\\">&nbsp;&nbsp;");
                   1741:     hDoc.write("<input type=\\"button\\" value=\\"$lt{'canc'}\\" onclick=\\"self.close()\\"><br /><br />");
1.465     albertel 1742:     hDoc.write("<\\/form>");
1.351     albertel 1743:     hDoc.write('$end_page_highlight_central');
1.128     ng       1744:     hDoc.close();
1.44      ng       1745:   }
                   1746: 
                   1747: </script>
                   1748: SUBJAVASCRIPT
                   1749: }
                   1750: 
1.349     albertel 1751: sub get_increment {
1.348     bowersj2 1752:     my $increment = $env{'form.increment'};
                   1753:     if ($increment != 1 && $increment != .5 && $increment != .25 &&
                   1754:         $increment != .1) {
                   1755:         $increment = 1;
                   1756:     }
                   1757:     return $increment;
                   1758: }
                   1759: 
1.585     bisitz   1760: sub gradeBox_start {
                   1761:     return (
                   1762:         &Apache::loncommon::start_data_table()
                   1763:        .&Apache::loncommon::start_data_table_header_row()
                   1764:        .'<th>'.&mt('Part').'</th>'
                   1765:        .'<th>'.&mt('Points').'</th>'
                   1766:        .'<th>&nbsp;</th>'
                   1767:        .'<th>'.&mt('Assign Grade').'</th>'
                   1768:        .'<th>'.&mt('Weight').'</th>'
                   1769:        .'<th>'.&mt('Grade Status').'</th>'
                   1770:        .&Apache::loncommon::end_data_table_header_row()
                   1771:     );
                   1772: }
                   1773: 
                   1774: sub gradeBox_end {
                   1775:     return (
                   1776:         &Apache::loncommon::end_data_table()
                   1777:     );
                   1778: }
1.71      ng       1779: #--- displays the grading box, used in essay type problem and grading by page/sequence
                   1780: sub gradeBox {
1.322     albertel 1781:     my ($request,$symb,$uname,$udom,$counter,$partid,$record) = @_;
1.381     albertel 1782:     my $checkIcon = '<img alt="'.&mt('Check Mark').
1.485     albertel 1783: 	'" src="'.&Apache::loncommon::lonhttpdurl($request->dir_config('lonIconsURL').'/check.gif').'" height="16" border="0" />';
1.71      ng       1784:     my $wgt    = &Apache::lonnet::EXT('resource.'.$partid.'.weight',$symb,$udom,$uname);
1.466     albertel 1785:     my $wgtmsg = ($wgt > 0) ? &mt('(problem weight)') 
                   1786:                            : '<span class="LC_info">'.&mt('problem weight assigned by computer').'</span>';
1.71      ng       1787:     $wgt       = ($wgt > 0 ? $wgt : '1');
                   1788:     my $score  = ($$record{'resource.'.$partid.'.awarded'} eq '' ?
1.320     albertel 1789: 		  '' : &compute_points($$record{'resource.'.$partid.'.awarded'},$wgt));
1.71      ng       1790:     my $result='<input type="hidden" name="WGT'.$counter.'_'.$partid.'" value="'.$wgt.'" />'."\n";
1.466     albertel 1791:     my $display_part= &get_display_part($partid,$symb);
1.270     albertel 1792:     my %last_resets = &get_last_resets($symb,$env{'request.course.id'},
                   1793: 				       [$partid]);
                   1794:     my $aggtries = $$record{'resource.'.$partid.'.tries'};
1.269     raeburn  1795:     if ($last_resets{$partid}) {
                   1796:         $aggtries = &get_num_tries($record,$last_resets{$partid},$partid);
                   1797:     }
1.585     bisitz   1798:     $result.=&Apache::loncommon::start_data_table_row();
1.71      ng       1799:     my $ctr = 0;
1.348     bowersj2 1800:     my $thisweight = 0;
1.349     albertel 1801:     my $increment = &get_increment();
1.485     albertel 1802: 
                   1803:     my $radio.='<table border="0"><tr>'."\n";  # display radio buttons in a nice table 10 across
1.348     bowersj2 1804:     while ($thisweight<=$wgt) {
1.532     bisitz   1805: 	$radio.= '<td><span class="LC_nobreak"><label><input type="radio" name="RADVAL'.$counter.'_'.$partid.'" '.
1.589     bisitz   1806:         'onclick="javascript:writeBox(this.form,\''.$counter.'_'.$partid.'\','.
1.348     bowersj2 1807: 	    $thisweight.')" value="'.$thisweight.'" '.
1.401     albertel 1808: 	    ($score eq $thisweight ? 'checked="checked"':'').' /> '.$thisweight."</label></span></td>\n";
1.485     albertel 1809: 	$radio.=(($ctr+1)%10 == 0 ? '</tr><tr>' : '');
1.348     bowersj2 1810:         $thisweight += $increment;
1.71      ng       1811: 	$ctr++;
                   1812:     }
1.485     albertel 1813:     $radio.='</tr></table>';
                   1814: 
                   1815:     my $line.='<input type="text" name="GD_BOX'.$counter.'_'.$partid.'"'.
1.71      ng       1816: 	($score ne ''? ' value = "'.$score.'"':'').' size="4" '.
1.589     bisitz   1817: 	'onchange="javascript:updateRadio(this.form,\''.$counter.'_'.$partid.'\','.
1.71      ng       1818: 	$wgt.')" /></td>'."\n";
1.485     albertel 1819:     $line.='<td>/'.$wgt.' '.$wgtmsg.
1.71      ng       1820: 	($$record{'resource.'.$partid.'.solved'} eq 'correct_by_student' ? '&nbsp;'.$checkIcon : '').
1.585     bisitz   1821: 	' </td>'."\n";
                   1822:     $line.='<td><select name="GD_SEL'.$counter.'_'.$partid.'" '.
1.589     bisitz   1823: 	'onchange="javascript:clearRadBox(this.form,\''.$counter.'_'.$partid.'\')" >'."\n";
1.71      ng       1824:     if ($$record{'resource.'.$partid.'.solved'} eq 'excused') {
1.485     albertel 1825: 	$line.='<option></option>'.
                   1826: 	    '<option value="excused" selected="selected">'.&mt('excused').'</option>';
1.71      ng       1827:     } else {
1.485     albertel 1828: 	$line.='<option selected="selected"></option>'.
                   1829: 	    '<option value="excused" >'.&mt('excused').'</option>';
1.71      ng       1830:     }
1.485     albertel 1831:     $line.='<option value="reset status">'.&mt('reset status').'</option></select>'."\n";
                   1832: 
                   1833: 
1.540     riegler  1834: 	#&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 1835:     $result .= 
1.585     bisitz   1836: 	    '<td>'.$display_part.'</td><td>'.$radio.'</td><td>'.&mt('or').'</td><td>'.$line.'</td>';
                   1837:     $result.=&Apache::loncommon::end_data_table_row();
1.71      ng       1838:     $result.='<input type="hidden" name="stores'.$counter.'_'.$partid.'" value="" />'."\n".
                   1839: 	'<input type="hidden" name="oldpts'.$counter.'_'.$partid.'" value="'.$score.'" />'."\n".
                   1840: 	'<input type="hidden" name="solved'.$counter.'_'.$partid.'" value="'.
1.269     raeburn  1841: 	$$record{'resource.'.$partid.'.solved'}.'" />'."\n".
                   1842:         '<input type="hidden" name="totaltries'.$counter.'_'.$partid.'" value="'.
                   1843:         $$record{'resource.'.$partid.'.tries'}.'" />'."\n".
                   1844:         '<input type="hidden" name="aggtries'.$counter.'_'.$partid.'" value="'.
                   1845:         $aggtries.'" />'."\n";
1.582     raeburn  1846:     my $res_error;
                   1847:     $result.=&handback_box($symb,$uname,$udom,$counter,$partid,$record,\$res_error);
                   1848:     if ($res_error) {
                   1849:         return &navmap_errormsg();
                   1850:     }
1.318     banghart 1851:     return $result;
                   1852: }
1.322     albertel 1853: 
                   1854: sub handback_box {
1.582     raeburn  1855:     my ($symb,$uname,$udom,$counter,$partid,$record,$res_error) = @_;
                   1856:     my ($partlist,$handgrade,$responseType) = &response_type($symb,$res_error);
1.323     banghart 1857:     my (@respids);
1.596.2.4  raeburn  1858:     my @part_response_id = &flatten_responseType($responseType);
1.375     albertel 1859:     foreach my $part_response_id (@part_response_id) {
                   1860:     	my ($part,$resp) = @{ $part_response_id };
1.323     banghart 1861:         if ($part eq $partid) {
1.375     albertel 1862:             push(@respids,$resp);
1.323     banghart 1863:         }
                   1864:     }
1.318     banghart 1865:     my $result;
1.323     banghart 1866:     foreach my $respid (@respids) {
1.322     albertel 1867: 	my $prefix = $counter.'_'.$partid.'_'.$respid.'_';
                   1868: 	my $files=&get_submitted_files($udom,$uname,$partid,$respid,$record);
                   1869: 	next if (!@$files);
1.596.2.4  raeburn  1870: 	my $file_counter = 0;
1.313     banghart 1871: 	foreach my $file (@$files) {
1.368     banghart 1872: 	    if ($file =~ /\/portfolio\//) {
1.596.2.4  raeburn  1873:                 $file_counter++;
1.368     banghart 1874:     	        my ($file_path, $file_disp) = ($file =~ m|(.+/)(.+)$|);
                   1875:     	        my ($name,$version,$ext) = &file_name_version_ext($file_disp);
                   1876:     	        $file_disp = "$name.$ext";
                   1877:     	        $file = $file_path.$file_disp;
                   1878:     	        $result.=&mt('Return commented version of [_1] to student.',
                   1879:     			 '<span class="LC_filename">'.$file_disp.'</span>');
                   1880:     	        $result.='<input type="file"   name="'.$prefix.'returndoc'.$file_counter.'" />'."\n";
1.596.2.4  raeburn  1881:     	        $result.='<input type="hidden" name="'.$prefix.'origdoc'.$file_counter.'" value="'.$file.'" /><br />'."\n";
1.368     banghart 1882: 	    }
1.322     albertel 1883: 	}
1.596.2.4  raeburn  1884:         if ($file_counter) {
                   1885:             $result .= '<input type="hidden" name="'.$prefix.'countreturndoc" value="'.$file_counter.'" />'."\n".
                   1886:                        '<span class="LC_info">'.
                   1887:                        '('.&mt('File(s) will be uploaded when you click on Save &amp; Next below.',$file_counter).')</span><br /><br />';
                   1888:         }
1.313     banghart 1889:     }
1.318     banghart 1890:     return $result;    
1.71      ng       1891: }
1.44      ng       1892: 
1.58      albertel 1893: sub show_problem {
1.382     albertel 1894:     my ($request,$symb,$uname,$udom,$removeform,$viewon,$mode,$form) = @_;
1.144     albertel 1895:     my $rendered;
1.382     albertel 1896:     my %form = ((ref($form) eq 'HASH')? %{$form} : ());
1.329     albertel 1897:     &Apache::lonxml::remember_problem_counter();
1.144     albertel 1898:     if ($mode eq 'both' or $mode eq 'text') {
                   1899: 	$rendered=&Apache::loncommon::get_student_view($symb,$uname,$udom,
1.382     albertel 1900: 						       $env{'request.course.id'},
                   1901: 						       undef,\%form);
1.144     albertel 1902:     }
1.58      albertel 1903:     if ($removeform) {
                   1904: 	$rendered=~s|<form(.*?)>||g;
                   1905: 	$rendered=~s|</form>||g;
1.374     albertel 1906: 	$rendered=~s|(<input[^>]*name\s*=\s*"?)(\w+)("?)|$1would_have_been_$2$3|g;
1.58      albertel 1907:     }
1.144     albertel 1908:     my $companswer;
                   1909:     if ($mode eq 'both' or $mode eq 'answer') {
1.329     albertel 1910: 	&Apache::lonxml::restore_problem_counter();
1.382     albertel 1911: 	$companswer=
                   1912: 	    &Apache::loncommon::get_student_answers($symb,$uname,$udom,
                   1913: 						    $env{'request.course.id'},
                   1914: 						    %form);
1.144     albertel 1915:     }
1.58      albertel 1916:     if ($removeform) {
                   1917: 	$companswer=~s|<form(.*?)>||g;
                   1918: 	$companswer=~s|</form>||g;
1.144     albertel 1919: 	$companswer=~s|name="submit"|name="would_have_been_submit"|g;
1.58      albertel 1920:     }
1.468     albertel 1921:     $rendered=
1.588     bisitz   1922:         '<div class="LC_Box">'
                   1923:        .'<h3 class="LC_hcell">'.&mt('View of the problem').'</h3>'
                   1924:        .$rendered
                   1925:        .'</div>';
1.468     albertel 1926:     $companswer=
1.588     bisitz   1927:         '<div class="LC_Box">'
                   1928:        .'<h3 class="LC_hcell">'.&mt('Correct answer').'</h3>'
                   1929:        .$companswer
                   1930:        .'</div>';
1.468     albertel 1931:     my $result;
1.144     albertel 1932:     if ($mode eq 'both') {
1.588     bisitz   1933:         $result=$rendered.$companswer;
1.144     albertel 1934:     } elsif ($mode eq 'text') {
1.588     bisitz   1935:         $result=$rendered;
1.144     albertel 1936:     } elsif ($mode eq 'answer') {
1.588     bisitz   1937:         $result=$companswer;
1.144     albertel 1938:     }
1.71      ng       1939:     return $result;
1.58      albertel 1940: }
1.397     albertel 1941: 
1.396     banghart 1942: sub files_exist {
                   1943:     my ($r, $symb) = @_;
                   1944:     my @students = &Apache::loncommon::get_env_multiple('form.stuinfo');
1.397     albertel 1945: 
1.396     banghart 1946:     foreach my $student (@students) {
                   1947:         my ($uname,$udom,$fullname) = split(/:/,$student);
1.397     albertel 1948:         my %record = &Apache::lonnet::restore($symb,$env{'request.course.id'},
                   1949: 					      $udom,$uname);
1.396     banghart 1950:         my ($string,$timestamp)= &get_last_submission(\%record);
1.397     albertel 1951:         foreach my $submission (@$string) {
                   1952:             my ($partid,$respid) =
                   1953: 		($submission =~ /^resource\.([^\.]*)\.([^\.]*)\.submission/);
                   1954:             my $files=&get_submitted_files($udom,$uname,$partid,$respid,
                   1955: 					   \%record);
                   1956:             return 1 if (@$files);
1.396     banghart 1957:         }
                   1958:     }
1.397     albertel 1959:     return 0;
1.396     banghart 1960: }
1.397     albertel 1961: 
1.394     banghart 1962: sub download_all_link {
                   1963:     my ($r,$symb) = @_;
1.395     albertel 1964:     my $all_students = 
                   1965: 	join("\n", &Apache::loncommon::get_env_multiple('form.stuinfo'));
                   1966: 
                   1967:     my $parts =
                   1968: 	join("\n",&Apache::loncommon::get_env_multiple('form.vPart'));
                   1969: 
1.394     banghart 1970:     my $identifier = &Apache::loncommon::get_cgi_id();
1.514     raeburn  1971:     &Apache::lonnet::appenv({'cgi.'.$identifier.'.students' => $all_students,
                   1972:                              'cgi.'.$identifier.'.symb' => $symb,
                   1973:                              'cgi.'.$identifier.'.parts' => $parts,});
1.395     albertel 1974:     $r->print('<a href="/cgi-bin/multidownload.pl?'.$identifier.'">'.
                   1975: 	      &mt('Download All Submitted Documents').'</a>');
1.394     banghart 1976:     return
                   1977: }
1.395     albertel 1978: 
1.432     banghart 1979: sub build_section_inputs {
                   1980:     my $section_inputs;
                   1981:     if ($env{'form.section'} eq '') {
                   1982:         $section_inputs .= '<input type="hidden" name="section" value="all" />'."\n";
                   1983:     } else {
                   1984:         my @sections = &Apache::loncommon::get_env_multiple('form.section');
1.434     albertel 1985:         foreach my $section (@sections) {
1.432     banghart 1986:             $section_inputs .= '<input type="hidden" name="section" value="'.$section.'" />'."\n";
                   1987:         }
                   1988:     }
                   1989:     return $section_inputs;
                   1990: }
                   1991: 
1.44      ng       1992: # --------------------------- show submissions of a student, option to grade 
                   1993: sub submission {
                   1994:     my ($request,$counter,$total) = @_;
1.257     albertel 1995:     my ($uname,$udom)     = ($env{'form.student'},$env{'form.userdom'});
                   1996:     $udom = ($udom eq '' ? $env{'user.domain'} : $udom); #has form.userdom changed for a student?
                   1997:     my $usec = &Apache::lonnet::getsection($udom,$uname,$env{'request.course.id'});
                   1998:     $env{'form.fullname'} = &Apache::loncommon::plainname($uname,$udom,'lastname') if $env{'form.fullname'} eq '';
1.324     albertel 1999:     my $symb = &get_symb($request); 
                   2000:     if ($symb eq '') { $request->print("Unable to handle ambiguous references:."); return ''; }
1.104     albertel 2001: 
                   2002:     if (!&canview($usec)) {
1.398     albertel 2003: 	$request->print('<span class="LC_warning">Unable to view requested student.('.
                   2004: 			$uname.':'.$udom.' in section '.$usec.' in course id '.
                   2005: 			$env{'request.course.id'}.')</span>');
1.324     albertel 2006: 	$request->print(&show_grading_menu_form($symb));
1.104     albertel 2007: 	return;
                   2008:     }
                   2009: 
1.257     albertel 2010:     if (!$env{'form.lastSub'}) { $env{'form.lastSub'} = 'datesub'; }
                   2011:     if (!$env{'form.vProb'}) { $env{'form.vProb'} = 'yes'; }
                   2012:     if (!$env{'form.vAns'}) { $env{'form.vAns'} = 'yes'; }
                   2013:     my $last = ($env{'form.lastSub'} eq 'last' ? 'last' : '');
1.381     albertel 2014:     my $checkIcon = '<img alt="'.&mt('Check Mark').
                   2015: 	'" src="'.$request->dir_config('lonIconsURL').
1.122     ng       2016: 	'/check.gif" height="16" border="0" />';
1.41      ng       2017: 
                   2018:     # header info
                   2019:     if ($counter == 0) {
                   2020: 	&sub_page_js($request);
1.257     albertel 2021: 	&sub_page_kw_js($request) if ($env{'form.handgrade'} eq 'yes');
                   2022: 	$env{'form.probTitle'} = $env{'form.probTitle'} eq '' ? 
                   2023: 	    &Apache::lonnet::gettitle($symb) : $env{'form.probTitle'};
1.397     albertel 2024: 	if ($env{'form.handgrade'} eq 'yes' && &files_exist($request, $symb)) {
1.396     banghart 2025: 	    &download_all_link($request, $symb);
                   2026: 	}
1.485     albertel 2027: 	$request->print('<h3>&nbsp;<span class="LC_info">'.&mt('Submission Record').'</span></h3>'."\n".
                   2028: 			'<h4>&nbsp;'.&mt('<b>Resource: </b> [_1]',$env{'form.probTitle'}).'</h4>'."\n");
1.118     ng       2029: 
1.44      ng       2030: 	# option to display problem, only once else it cause problems 
                   2031:         # with the form later since the problem has a form.
1.257     albertel 2032: 	if ($env{'form.vProb'} eq 'yes' or $env{'form.vAns'} eq 'yes') {
1.144     albertel 2033: 	    my $mode;
1.257     albertel 2034: 	    if ($env{'form.vProb'} eq 'yes' && $env{'form.vAns'} eq 'yes') {
1.144     albertel 2035: 		$mode='both';
1.257     albertel 2036: 	    } elsif ($env{'form.vProb'} eq 'yes') {
1.144     albertel 2037: 		$mode='text';
1.257     albertel 2038: 	    } elsif ($env{'form.vAns'} eq 'yes') {
1.144     albertel 2039: 		$mode='answer';
                   2040: 	    }
1.329     albertel 2041: 	    &Apache::lonxml::clear_problem_counter();
1.144     albertel 2042: 	    $request->print(&show_problem($request,$symb,$uname,$udom,0,1,$mode));
1.41      ng       2043: 	}
1.441     www      2044: 
1.44      ng       2045: 	# kwclr is the only variable that is guaranteed to be non blank 
                   2046:         # if this subroutine has been called once.
1.41      ng       2047: 	my %keyhash = ();
1.257     albertel 2048: 	if ($env{'form.kwclr'} eq '' && $env{'form.handgrade'} eq 'yes') {
1.41      ng       2049: 	    %keyhash = &Apache::lonnet::dump('nohist_handgrade',
1.257     albertel 2050: 					     $env{'course.'.$env{'request.course.id'}.'.domain'},
                   2051: 					     $env{'course.'.$env{'request.course.id'}.'.num'});
1.41      ng       2052: 
1.257     albertel 2053: 	    my $loginuser = $env{'user.name'}.':'.$env{'user.domain'};
                   2054: 	    $env{'form.keywords'} = $keyhash{$symb.'_keywords'} ne '' ? $keyhash{$symb.'_keywords'} : '';
                   2055: 	    $env{'form.kwclr'}    = $keyhash{$loginuser.'_kwclr'} ne '' ? $keyhash{$loginuser.'_kwclr'} : 'red';
                   2056: 	    $env{'form.kwsize'}   = $keyhash{$loginuser.'_kwsize'} ne '' ? $keyhash{$loginuser.'_kwsize'} : '0';
                   2057: 	    $env{'form.kwstyle'}  = $keyhash{$loginuser.'_kwstyle'} ne '' ? $keyhash{$loginuser.'_kwstyle'} : '';
                   2058: 	    $env{'form.msgsub'}   = $keyhash{$symb.'_subject'} ne '' ? 
                   2059: 		$keyhash{$symb.'_subject'} : $env{'form.probTitle'};
                   2060: 	    $env{'form.savemsgN'} = $keyhash{$symb.'_savemsgN'} ne '' ? $keyhash{$symb.'_savemsgN'} : '0';
1.41      ng       2061: 	}
1.257     albertel 2062: 	my $overRideScore = $env{'form.overRideScore'} eq '' ? 'no' : $env{'form.overRideScore'};
1.442     banghart 2063: 	my $stu_status = join(':',&Apache::loncommon::get_env_multiple('form.Status'));
1.303     banghart 2064: 	$request->print('<form action="/adm/grades" method="post" name="SCORE" enctype="multipart/form-data">'."\n".
1.41      ng       2065: 			'<input type="hidden" name="command"    value="handgrade" />'."\n".
1.257     albertel 2066: 			'<input type="hidden" name="saveState"  value="'.$env{'form.saveState'}.'" />'."\n".
1.442     banghart 2067: 			'<input type="hidden" name="Status"     value="'.$stu_status.'" />'."\n".
1.120     ng       2068: 			'<input type="hidden" name="overRideScore" value="'.$overRideScore.'" />'."\n".
1.257     albertel 2069: 			'<input type="hidden" name="probTitle"  value="'.$env{'form.probTitle'}.'" />'."\n".
1.41      ng       2070: 			'<input type="hidden" name="refresh"    value="off" />'."\n".
1.120     ng       2071: 			'<input type="hidden" name="studentNo"  value="" />'."\n".
                   2072: 			'<input type="hidden" name="gradeOpt"   value="" />'."\n".
1.418     albertel 2073: 			'<input type="hidden" name="symb"       value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
1.257     albertel 2074: 			'<input type="hidden" name="showgrading" value="'.$env{'form.showgrading'}.'" />'."\n".
                   2075: 			'<input type="hidden" name="vProb"      value="'.$env{'form.vProb'}.'" />'."\n".
                   2076: 			'<input type="hidden" name="vAns"       value="'.$env{'form.vAns'}.'" />'."\n".
                   2077: 			'<input type="hidden" name="lastSub"    value="'.$env{'form.lastSub'}.'" />'."\n".
1.432     banghart 2078: 			&build_section_inputs().
1.326     albertel 2079: 			'<input type="hidden" name="submitonly" value="'.$env{'form.submitonly'}.'" />'."\n".
                   2080: 			'<input type="hidden" name="handgrade"  value="'.$env{'form.handgrade'}.'" />'."\n".
1.41      ng       2081: 			'<input type="hidden" name="NCT"'.
1.257     albertel 2082: 			' value="'.($env{'form.NTSTU'} ne '' ? $env{'form.NTSTU'} : $total+1).'" />'."\n");
                   2083: 	if ($env{'form.handgrade'} eq 'yes') {
                   2084: 	    $request->print('<input type="hidden" name="keywords" value="'.$env{'form.keywords'}.'" />'."\n".
                   2085: 			    '<input type="hidden" name="kwclr"    value="'.$env{'form.kwclr'}.'" />'."\n".
                   2086: 			    '<input type="hidden" name="kwsize"   value="'.$env{'form.kwsize'}.'" />'."\n".
                   2087: 			    '<input type="hidden" name="kwstyle"  value="'.$env{'form.kwstyle'}.'" />'."\n".
                   2088: 			    '<input type="hidden" name="msgsub"   value="'.$env{'form.msgsub'}.'" />'."\n".
1.123     ng       2089: 			    '<input type="hidden" name="shownSub" value="0" />'."\n".
1.257     albertel 2090: 			    '<input type="hidden" name="savemsgN" value="'.$env{'form.savemsgN'}.'" />'."\n");
1.154     albertel 2091: 	    foreach my $partid (&Apache::loncommon::get_env_multiple('form.vPart')) {
                   2092: 		$request->print('<input type="hidden" name="vPart" value="'.$partid.'" />'."\n");
                   2093: 	    }
1.123     ng       2094: 	}
1.41      ng       2095: 	
                   2096: 	my ($cts,$prnmsg) = (1,'');
1.257     albertel 2097: 	while ($cts <= $env{'form.savemsgN'}) {
1.41      ng       2098: 	    $prnmsg.='<input type="hidden" name="savemsg'.$cts.'" value="'.
1.123     ng       2099: 		(!exists($keyhash{$symb.'_savemsg'.$cts}) ? 
1.257     albertel 2100: 		 &Apache::lonfeedback::clear_out_html($env{'form.savemsg'.$cts}) :
1.80      ng       2101: 		 &Apache::lonfeedback::clear_out_html($keyhash{$symb.'_savemsg'.$cts})).
1.123     ng       2102: 		'" />'."\n".
                   2103: 		'<input type="hidden" name="shownOnce'.$cts.'" value="0" />'."\n";
1.41      ng       2104: 	    $cts++;
                   2105: 	}
                   2106: 	$request->print($prnmsg);
1.32      ng       2107: 
1.257     albertel 2108: 	if ($env{'form.handgrade'} eq 'yes' && $env{'form.showgrading'} eq 'yes') {
1.596.2.4  raeburn  2109: 
                   2110:             my %lt = &Apache::lonlocal::texthash(
                   2111:                           keyw => 'Keyword Options',
                   2112:                           list => 'List',
                   2113:                           past => 'Paste Selection to List',
1.596.2.9  raeburn  2114:                           high => 'Highlight Attribute',
1.596.2.4  raeburn  2115:                      );
1.88      www      2116: #
                   2117: # Print out the keyword options line
                   2118: #
1.41      ng       2119: 	    $request->print(<<KEYWORDS);
1.596.2.4  raeburn  2120: &nbsp;<b>$lt{'keyw'}:</b>&nbsp;
                   2121: <a href="javascript:keywords(document.SCORE);" target="_self">$lt{'list'}</a>&nbsp; &nbsp;
1.589     bisitz   2122: <a href="#" onmousedown="javascript:getSel(); return false"
1.596.2.4  raeburn  2123:  CLASS="page">$lt{'past'}</a>&nbsp; &nbsp;
                   2124: <a href="javascript:kwhighlight();" target="_self">$lt{'high'}</a><br /><br />
1.38      ng       2125: KEYWORDS
1.88      www      2126: #
                   2127: # Load the other essays for similarity check
                   2128: #
1.324     albertel 2129:             my (undef,undef,$essayurl) = &Apache::lonnet::decode_symb($symb);
1.384     albertel 2130: 	    my ($adom,$aname,$apath)=($essayurl=~/^($LONCAPA::domain_re)\/($LONCAPA::username_re)\/(.*)$/);
1.359     www      2131: 	    $apath=&escape($apath);
1.88      www      2132: 	    $apath=~s/\W/\_/gs;
1.596.2.13! raeburn  2133: 	    &init_old_essays($symb,$apath,$adom,$aname);
1.41      ng       2134:         }
                   2135:     }
1.44      ng       2136: 
1.441     www      2137: # This is where output for one specific student would start
1.592     bisitz   2138:     my $add_class = ($counter%2) ? ' LC_grade_show_user_odd_row' : '';
                   2139:     $request->print(
                   2140:         "\n\n"
                   2141:        .'<div class="LC_grade_show_user'.$add_class.'">'
                   2142:        .'<h2>'.&nameUserString(undef,$env{'form.fullname'},$uname,$udom).'</h2>'
                   2143:        ."\n"
                   2144:     );
1.441     www      2145: 
1.592     bisitz   2146:     # Show additional functions if allowed
                   2147:     if ($perm{'vgr'}) {
                   2148:         $request->print(
                   2149:             &Apache::loncommon::track_student_link(
                   2150:                 &mt('View recent activity'),
                   2151:                 $uname,$udom,'check')
                   2152:            .' '
                   2153:         );
                   2154:     }
                   2155:     if ($perm{'opa'}) {
                   2156:         $request->print(
                   2157:             &Apache::loncommon::pprmlink(
                   2158:                 &mt('Set/Change parameters'),
                   2159:                 $uname,$udom,$symb,'check'));
                   2160:     }
                   2161: 
                   2162:     # Show Problem
1.257     albertel 2163:     if ($env{'form.vProb'} eq 'all' or $env{'form.vAns'} eq 'all') {
1.144     albertel 2164: 	my $mode;
1.257     albertel 2165: 	if ($env{'form.vProb'} eq 'all' && $env{'form.vAns'} eq 'all') {
1.144     albertel 2166: 	    $mode='both';
1.257     albertel 2167: 	} elsif ($env{'form.vProb'} eq 'all' ) {
1.144     albertel 2168: 	    $mode='text';
1.257     albertel 2169: 	} elsif ($env{'form.vAns'} eq 'all') {
1.144     albertel 2170: 	    $mode='answer';
                   2171: 	}
1.329     albertel 2172: 	&Apache::lonxml::clear_problem_counter();
1.475     albertel 2173: 	$request->print(&show_problem($request,$symb,$uname,$udom,1,1,$mode,{'request.prefix' => 'ctr'.$counter}));
1.58      albertel 2174:     }
1.144     albertel 2175: 
1.257     albertel 2176:     my %record = &Apache::lonnet::restore($symb,$env{'request.course.id'},$udom,$uname);
1.582     raeburn  2177:     my $res_error;
                   2178:     my ($partlist,$handgrade,$responseType) = &response_type($symb,\$res_error);
                   2179:     if ($res_error) {
                   2180:         $request->print(&navmap_errormsg());
                   2181:         return;
                   2182:     }
1.41      ng       2183: 
1.44      ng       2184:     # Display student info
1.41      ng       2185:     $request->print(($counter == 0 ? '' : '<br />'));
1.590     bisitz   2186: 
                   2187:     my $result='<div class="LC_Box">'
                   2188:               .'<h3 class="LC_hcell">'.&mt('Submissions').'</h3>';
1.45      ng       2189:     $result.='<input type="hidden" name="name'.$counter.
1.588     bisitz   2190:              '" value="'.$env{'form.fullname'}.'" />'."\n";
1.469     albertel 2191:     if ($env{'form.handgrade'} eq 'no') {
1.588     bisitz   2192:         $result.='<p class="LC_info">'
                   2193:                 .&mt('Part(s) graded correct by the computer is marked with a [_1] symbol.',$checkIcon)
                   2194:                 ."</p>\n";
1.469     albertel 2195:     }
                   2196: 
1.118     ng       2197:     # If any part of the problem is an essay-response (handgraded), then check for collaborators
1.464     albertel 2198:     my $fullname;
                   2199:     my $col_fullnames = [];
1.257     albertel 2200:     if ($env{'form.handgrade'} eq 'yes') {
1.464     albertel 2201: 	(my $sub_result,$fullname,$col_fullnames)=
                   2202: 	    &check_collaborators($symb,$uname,$udom,\%record,$handgrade,
                   2203: 				 $counter);
                   2204: 	$result.=$sub_result;
1.41      ng       2205:     }
1.44      ng       2206:     $request->print($result."\n");
1.588     bisitz   2207: 
1.44      ng       2208:     # print student answer/submission
1.588     bisitz   2209:     # Options are (1) Handgraded submission only
1.44      ng       2210:     #             (2) Last submission, includes submission that is not handgraded 
                   2211:     #                  (for multi-response type part)
                   2212:     #             (3) Last submission plus the parts info
                   2213:     #             (4) The whole record for this student
1.257     albertel 2214:     if ($env{'form.lastSub'} =~ /^(lastonly|hdgrade)$/) {
1.151     albertel 2215: 	my ($string,$timestamp)= &get_last_submission(\%record);
1.468     albertel 2216: 	
                   2217: 	my $lastsubonly;
                   2218: 
1.588     bisitz   2219:         if ($$timestamp eq '') {
                   2220:             $lastsubonly.='<div class="LC_grade_submissions_body">'.$$string[0].'</div>'; 
                   2221:         } else {
1.592     bisitz   2222:             $lastsubonly =
                   2223:                 '<div class="LC_grade_submissions_body">'
                   2224:                .'<b>'.&mt('Date Submitted:').'</b> '.$$timestamp."\n";
1.468     albertel 2225: 
1.151     albertel 2226: 	    my %seenparts;
1.375     albertel 2227: 	    my @part_response_id = &flatten_responseType($responseType);
                   2228: 	    foreach my $part (@part_response_id) {
1.393     albertel 2229: 		next if ($env{'form.lastSub'} eq 'hdgrade' 
                   2230: 			 && $$handgrade{$$part[0].'_'.$$part[1]} ne 'yes');
                   2231: 
1.375     albertel 2232: 		my ($partid,$respid) = @{ $part };
1.324     albertel 2233: 		my $display_part=&get_display_part($partid,$symb);
1.257     albertel 2234: 		if ($env{"form.$uname:$udom:$partid:submitted_by"}) {
1.151     albertel 2235: 		    if (exists($seenparts{$partid})) { next; }
                   2236: 		    $seenparts{$partid}=1;
1.207     albertel 2237: 		    my $submitby='<b>Part:</b> '.$display_part.
                   2238: 			' <b>Collaborative submission by:</b> '.
1.151     albertel 2239: 			'<a href="javascript:viewSubmitter(\''.
1.257     albertel 2240: 			$env{"form.$uname:$udom:$partid:submitted_by"}.
1.417     albertel 2241: 			'\');" target="_self">'.
1.257     albertel 2242: 			$$fullname{$env{"form.$uname:$udom:$partid:submitted_by"}}.'</a><br />';
1.151     albertel 2243: 		    $request->print($submitby);
                   2244: 		    next;
                   2245: 		}
                   2246: 		my $responsetype = $responseType->{$partid}->{$respid};
                   2247: 		if (!exists($record{"resource.$partid.$respid.submission"})) {
1.577     bisitz   2248:                     $lastsubonly.="\n".'<div class="LC_grade_submission_part">'.
                   2249:                         '<b>'.&mt('Part: [_1]',$display_part).'</b>'.
                   2250:                         ' <span class="LC_internal_info">'.
1.596.2.4  raeburn  2251:                         '('.&mt('Response ID: [_1]',$respid).')'.
1.577     bisitz   2252:                         '</span>&nbsp; &nbsp;'.
1.539     riegler  2253: 			'<span class="LC_warning">'.&mt('Nothing submitted - no attempts.').'</span><br /><br /></div>';
1.151     albertel 2254: 		    next;
                   2255: 		}
1.468     albertel 2256: 		foreach my $submission (@$string) {
                   2257: 		    my ($partid,$respid) = ($submission =~ /^resource\.([^\.]*)\.([^\.]*)\.submission/);
1.375     albertel 2258: 		    if (join('_',@{$part}) ne ($partid.'_'.$respid)) { next; }
1.596     raeburn  2259: 		    my ($ressub,$hide,$subval) = split(/:/,$submission,3);
1.151     albertel 2260: 		    # Similarity check
                   2261: 		    my $similar='';
1.596.2.2  raeburn  2262:                     my ($type,$trial,$rndseed);
                   2263:                     if ($hide eq 'rand') {
                   2264:                         $type = 'randomizetry';
                   2265:                         $trial = $record{"resource.$partid.tries"};
                   2266:                         $rndseed = $record{"resource.$partid.rndseed"};
                   2267:                     }
1.257     albertel 2268: 		    if($env{'form.checkPlag'}){
1.151     albertel 2269: 			my ($oname,$odom,$ocrsid,$oessay,$osim)=
1.596.2.13! raeburn  2270: 			    &most_similar($uname,$udom,$symb,$subval);
1.151     albertel 2271: 			if ($osim) {
                   2272: 			    $osim=int($osim*100.0);
1.426     albertel 2273: 			    my %old_course_desc = 
                   2274: 				&Apache::lonnet::coursedescription($ocrsid,
                   2275: 								   {'one_time' => 1});
                   2276: 
1.596.2.2  raeburn  2277:                             if ($hide eq 'anon') {
1.596     raeburn  2278:                                 $similar='<hr /><span class="LC_warning">'.&mt("Essay was found to be similar to another essay submitted for this assignment.").'<br />'.
                   2279:                                          &mt('As the current submission is for an anonymous survey, no other details are available.').'</span><hr />';
                   2280:                             } else {
                   2281: 			        $similar="<hr /><h3><span class=\"LC_warning\">".
                   2282: 				    &mt('Essay is [_1]% similar to an essay by [_2] in course [_3] (course id [_4]:[_5])',
                   2283: 				        $osim,
                   2284: 				        &Apache::loncommon::plainname($oname,$odom).' ('.$oname.':'.$odom.')',
                   2285: 				        $old_course_desc{'description'},
                   2286: 				        $old_course_desc{'num'},
                   2287: 				        $old_course_desc{'domain'}).
                   2288: 				    '</span></h3><blockquote><i>'.
                   2289: 				    &keywords_highlight($oessay).
                   2290: 				    '</i></blockquote><hr />';
                   2291:                             }
1.151     albertel 2292: 			}
1.150     albertel 2293: 		    }
1.596.2.2  raeburn  2294: 		    my $order=&get_order($partid,$respid,$symb,$uname,$udom,
                   2295:                                          undef,$type,$trial,$rndseed);
1.257     albertel 2296: 		    if ($env{'form.lastSub'} eq 'lastonly' || 
                   2297: 			($env{'form.lastSub'} eq 'hdgrade' && 
1.377     albertel 2298: 			 $$handgrade{$$part[0].'_'.$$part[1]} eq 'yes')) {
1.324     albertel 2299: 			my $display_part=&get_display_part($partid,$symb);
1.577     bisitz   2300:                         $lastsubonly.='<div class="LC_grade_submission_part">'.
                   2301:                             '<b>'.&mt('Part: [_1]',$display_part).'</b>'.
                   2302:                             ' <span class="LC_internal_info">'.
1.596.2.4  raeburn  2303:                             '('.&mt('Response ID: [_1]',$respid).')'.
                   2304:                             '</span>&nbsp; &nbsp;';
1.313     banghart 2305: 			my $files=&get_submitted_files($udom,$uname,$partid,$respid,\%record);
                   2306: 			if (@$files) {
1.596.2.2  raeburn  2307:                             if ($hide eq 'anon') {
1.596     raeburn  2308:                                 $lastsubonly.='<br />'.&mt('[quant,_1,file] uploaded to this anonymous survey',scalar(@{$files}));
                   2309:                             } else {
                   2310:                                 $lastsubonly.='<br /><span class="LC_warning">'.&mt('Like all files provided by users, this file may contain viruses').'</span><br />';
                   2311:                                 foreach my $file (@$files) {
                   2312:                                     &Apache::lonnet::allowuploaded('/adm/grades',$file);
                   2313:                                     $lastsubonly.='<br /><a href="'.$file.'?rawmode=1" target="lonGRDs"><img src="'.&Apache::loncommon::icon($file).'" border="0" /> '.$file.'</a>';
                   2314:                                 }
                   2315:                             }
1.236     albertel 2316: 			    $lastsubonly.='<br />';
1.41      ng       2317: 			}
1.596.2.2  raeburn  2318:                         if ($hide eq 'anon') {
1.596     raeburn  2319:                             $lastsubonly.='<b>'.&mt('Anonymous Survey').'</b>'; 
                   2320:                         } else {
                   2321: 			    $lastsubonly.='<b>'.&mt('Submitted Answer:').' </b>'.
                   2322: 			        &cleanRecord($subval,$responsetype,$symb,$partid,
1.596.2.2  raeburn  2323: 					     $respid,\%record,$order,undef,$uname,$udom,$type,$trial,$rndseed);
1.596     raeburn  2324:                         }
1.151     albertel 2325: 			if ($similar) {$lastsubonly.="<br /><br />$similar\n";}
1.468     albertel 2326: 			$lastsubonly.='</div>';
1.41      ng       2327: 		    }
                   2328: 		}
                   2329: 	    }
1.588     bisitz   2330: 	    $lastsubonly.='</div>'."\n"; # End: LC_grade_submissions_body
1.151     albertel 2331: 	}
                   2332: 	$request->print($lastsubonly);
1.468     albertel 2333:    } elsif ($env{'form.lastSub'} eq 'datesub') {
1.324     albertel 2334: 	my (undef,$responseType,undef,$parts) = &showResourceInfo($symb);
1.148     albertel 2335: 	$request->print(&displaySubByDates($symb,\%record,$parts,$responseType,$checkIcon,$uname,$udom));
1.257     albertel 2336:     } elsif ($env{'form.lastSub'} =~ /^(last|all)$/) {
1.41      ng       2337: 	$request->print(&Apache::loncommon::get_previous_attempt($symb,$uname,$udom,
1.257     albertel 2338: 								 $env{'request.course.id'},
1.44      ng       2339: 								 $last,'.submission',
                   2340: 								 'Apache::grades::keywords_highlight'));
1.41      ng       2341:     }
1.120     ng       2342: 
1.121     ng       2343:     $request->print('<input type="hidden" name="unamedom'.$counter.'" value="'.$uname.':'
                   2344: 	.$udom.'" />'."\n");
1.44      ng       2345:     # return if view submission with no grading option
1.257     albertel 2346:     if ($env{'form.showgrading'} eq '' || (!&canmodify($usec))) {
1.120     ng       2347: 	my $toGrade.='<input type="button" value="Grade Student" '.
1.589     bisitz   2348: 	    'onclick="javascript:checksubmit(this.form,\'Grade Student\',\''
1.417     albertel 2349: 	    .$counter.'\');" target="_self" /> &nbsp;'."\n" if (&canmodify($usec));
1.468     albertel 2350: 	$toGrade.='</div>'."\n";
1.257     albertel 2351: 	if (($env{'form.command'} eq 'submission') || 
                   2352: 	    ($env{'form.command'} eq 'processGroup' && $counter == $total)) {
1.324     albertel 2353: 	    $toGrade.='</form>'.&show_grading_menu_form($symb); 
1.169     albertel 2354: 	}
1.180     albertel 2355: 	$request->print($toGrade);
1.41      ng       2356: 	return;
1.180     albertel 2357:     } else {
1.468     albertel 2358: 	$request->print('</div>'."\n");
1.41      ng       2359:     }
1.33      ng       2360: 
1.121     ng       2361:     # essay grading message center
1.257     albertel 2362:     if ($env{'form.handgrade'} eq 'yes') {
1.468     albertel 2363: 	my $result='<div class="LC_grade_message_center">';
                   2364:     
                   2365: 	$result.='<div class="LC_grade_message_center_header">'.
                   2366: 	    &mt('Send Message').'</div><div class="LC_grade_message_center_body">';
1.257     albertel 2367: 	my ($lastname,$givenn) = split(/,/,$env{'form.fullname'});
1.118     ng       2368: 	my $msgfor = $givenn.' '.$lastname;
1.464     albertel 2369: 	if (scalar(@$col_fullnames) > 0) {
                   2370: 	    my $lastone = pop(@$col_fullnames);
                   2371: 	    $msgfor .= ', '.(join ', ',@$col_fullnames).' and '.$lastone.'.';
1.118     ng       2372: 	}
                   2373: 	$msgfor =~ s/\'/\\'/g; #' stupid emacs - no! javascript
1.468     albertel 2374: 	$result.='<input type="hidden" name="includemsg'.$counter.'" value="" />'."\n".
1.121     ng       2375: 	    '<input type="hidden" name="newmsg'.$counter.'" value="" />'."\n";
                   2376: 	$result.='&nbsp;<a href="javascript:msgCenter(document.SCORE,'.$counter.
1.417     albertel 2377: 	    ',\''.$msgfor.'\');" target="_self">'.
1.464     albertel 2378: 	    &mt('Compose message to student').(scalar(@$col_fullnames) >= 1 ? 's' : '').'</a><label> ('.
1.350     albertel 2379: 	    &mt('incl. grades').' <input type="checkbox" name="withgrades'.$counter.'" /></label>)'.
1.118     ng       2380: 	    '<img src="'.$request->dir_config('lonIconsURL').
                   2381: 	    '/mailbkgrd.gif" width="14" height="10" name="mailicon'.$counter.'" />'."\n".
1.298     www      2382: 	    '<br />&nbsp;('.
1.468     albertel 2383: 	    &mt('Message will be sent when you click on Save &amp; Next below.').")\n";
                   2384: 	$result.='</div></div>';
1.121     ng       2385: 	$request->print($result);
1.118     ng       2386:     }
1.41      ng       2387: 
                   2388:     my %seen = ();
                   2389:     my @partlist;
1.129     ng       2390:     my @gradePartRespid;
1.375     albertel 2391:     my @part_response_id = &flatten_responseType($responseType);
1.585     bisitz   2392:     $request->print(
1.588     bisitz   2393:         '<div class="LC_Box">'
                   2394:        .'<h3 class="LC_hcell">'.&mt('Assign Grades').'</h3>'
1.585     bisitz   2395:     );
1.592     bisitz   2396:     $request->print(&gradeBox_start());
1.375     albertel 2397:     foreach my $part_response_id (@part_response_id) {
                   2398:     	my ($partid,$respid) = @{ $part_response_id };
                   2399: 	my $part_resp = join('_',@{ $part_response_id });
1.322     albertel 2400: 	next if ($seen{$partid} > 0);
1.41      ng       2401: 	$seen{$partid}++;
1.393     albertel 2402: 	next if ($$handgrade{$part_resp} ne 'yes' 
                   2403: 		 && $env{'form.lastSub'} eq 'hdgrade');
1.524     raeburn  2404: 	push(@partlist,$partid);
                   2405: 	push(@gradePartRespid,$partid.'.'.$respid);
1.322     albertel 2406: 	$request->print(&gradeBox($request,$symb,$uname,$udom,$counter,$partid,\%record));
1.41      ng       2407:     }
1.585     bisitz   2408:     $request->print(&gradeBox_end()); # </div>
                   2409:     $request->print('</div>');
1.468     albertel 2410: 
                   2411:     $request->print('<div class="LC_grade_info_links">');
                   2412:     $request->print('</div>');
                   2413: 
1.45      ng       2414:     $result='<input type="hidden" name="partlist'.$counter.
                   2415: 	'" value="'.(join ":",@partlist).'" />'."\n";
1.129     ng       2416:     $result.='<input type="hidden" name="gradePartRespid'.
                   2417: 	'" value="'.(join ":",@gradePartRespid).'" />'."\n" if ($counter == 0);
1.45      ng       2418:     my $ctr = 0;
                   2419:     while ($ctr < scalar(@partlist)) {
                   2420: 	$result.='<input type="hidden" name="partid'.$counter.'_'.$ctr.'" value="'.
                   2421: 	    $partlist[$ctr].'" />'."\n";
                   2422: 	$ctr++;
                   2423:     }
1.468     albertel 2424:     $request->print($result.''."\n");
1.41      ng       2425: 
1.441     www      2426: # Done with printing info for one student
                   2427: 
1.468     albertel 2428:     $request->print('</div>');#LC_grade_show_user
1.441     www      2429: 
                   2430: 
1.41      ng       2431:     # print end of form
                   2432:     if ($counter == $total) {
1.592     bisitz   2433:         my $endform='<br /><hr /><table border="0"><tr><td>'."\n";
1.485     albertel 2434: 	$endform.='<input type="button" value="'.&mt('Save &amp; Next').'" '.
1.589     bisitz   2435: 	    'onclick="javascript:checksubmit(this.form,\'Save & Next\','.
1.417     albertel 2436: 	    $total.','.scalar(@partlist).');" target="_self" /> &nbsp;'."\n";
1.119     ng       2437: 	my $ntstu ='<select name="NTSTU">'.
                   2438: 	    '<option>1</option><option>2</option>'.
                   2439: 	    '<option>3</option><option>5</option>'.
                   2440: 	    '<option>7</option><option>10</option></select>'."\n";
1.257     albertel 2441: 	my $nsel = ($env{'form.NTSTU'} ne '' ? $env{'form.NTSTU'} : '1');
1.401     albertel 2442: 	$ntstu =~ s/<option>$nsel</<option selected="selected">$nsel</;
1.578     raeburn  2443:         $endform.=&mt('[_1]student(s)',$ntstu);
1.485     albertel 2444: 	$endform.='&nbsp;&nbsp;<input type="button" value="'.&mt('Previous').'" '.
1.589     bisitz   2445: 	    'onclick="javascript:checksubmit(this.form,\'Previous\');" target="_self" /> &nbsp;'."\n".
1.485     albertel 2446: 	    '<input type="button" value="'.&mt('Next').'" '.
1.589     bisitz   2447: 	    'onclick="javascript:checksubmit(this.form,\'Next\');" target="_self" /> &nbsp;';
1.592     bisitz   2448:         $endform.='<span class="LC_warning">'.
                   2449:                   &mt('(Next and Previous (student) do not save the scores.)').
                   2450:                   '</span>'."\n" ;
1.349     albertel 2451:         $endform.="<input type='hidden' value='".&get_increment().
1.348     bowersj2 2452:             "' name='increment' />";
1.485     albertel 2453: 	$endform.='</td></tr></table></form>';
1.324     albertel 2454: 	$endform.=&show_grading_menu_form($symb);
1.41      ng       2455: 	$request->print($endform);
                   2456:     }
                   2457:     return '';
1.38      ng       2458: }
                   2459: 
1.464     albertel 2460: sub check_collaborators {
                   2461:     my ($symb,$uname,$udom,$record,$handgrade,$counter) = @_;
                   2462:     my ($result,@col_fullnames);
                   2463:     my ($classlist,undef,$fullname) = &getclasslist('all','0');
                   2464:     foreach my $part (keys(%$handgrade)) {
                   2465: 	my $ncol = &Apache::lonnet::EXT('resource.'.$part.
                   2466: 					'.maxcollaborators',
                   2467: 					$symb,$udom,$uname);
                   2468: 	next if ($ncol <= 0);
                   2469: 	$part =~ s/\_/\./g;
                   2470: 	next if ($record->{'resource.'.$part.'.collaborators'} eq '');
                   2471: 	my (@good_collaborators, @bad_collaborators);
                   2472: 	foreach my $possible_collaborator
1.596.2.4  raeburn  2473: 	    (split(/[,;\s]+/,$record->{'resource.'.$part.'.collaborators'})) { 
1.464     albertel 2474: 	    $possible_collaborator =~ s/[\$\^\(\)]//g;
                   2475: 	    next if ($possible_collaborator eq '');
1.596.2.8  raeburn  2476: 	    my ($co_name,$co_dom) = split(/:/,$possible_collaborator);
1.464     albertel 2477: 	    $co_dom = $udom if (! defined($co_dom) || $co_dom =~ /^domain$/i);
                   2478: 	    next if ($co_name eq $uname && $co_dom eq $udom);
                   2479: 	    # Doing this grep allows 'fuzzy' specification
                   2480: 	    my @matches = grep(/^\Q$co_name\E:\Q$co_dom\E$/i, 
                   2481: 			       keys(%$classlist));
                   2482: 	    if (! scalar(@matches)) {
                   2483: 		push(@bad_collaborators, $possible_collaborator);
                   2484: 	    } else {
                   2485: 		push(@good_collaborators, @matches);
                   2486: 	    }
                   2487: 	}
                   2488: 	if (scalar(@good_collaborators) != 0) {
1.596.2.8  raeburn  2489: 	    $result.='<br />'.&mt('Collaborators:').'<ol>';
1.464     albertel 2490: 	    foreach my $name (@good_collaborators) {
                   2491: 		my ($lastname,$givenn) = split(/,/,$$fullname{$name});
                   2492: 		push(@col_fullnames, $givenn.' '.$lastname);
1.596.2.4  raeburn  2493: 		$result.='<li>'.$fullname->{$name}.'</li>';
1.464     albertel 2494: 	    }
1.596.2.4  raeburn  2495: 	    $result.='</ol><br />'."\n";
1.466     albertel 2496: 	    my ($part)=split(/\./,$part);
1.464     albertel 2497: 	    $result.='<input type="hidden" name="collaborator'.$counter.
                   2498: 		'" value="'.$part.':'.(join ':',@good_collaborators).'" />'.
                   2499: 		"\n";
                   2500: 	}
                   2501: 	if (scalar(@bad_collaborators) > 0) {
1.466     albertel 2502: 	    $result.='<div class="LC_warning">';
1.464     albertel 2503: 	    $result.=&mt('This student has submitted [quant,_1,invalid collaborator]: [_2]',scalar(@bad_collaborators),join(', ',@bad_collaborators));
                   2504: 	    $result .= '</div>';
                   2505: 	}         
                   2506: 	if (scalar(@bad_collaborators > $ncol)) {
1.466     albertel 2507: 	    $result .= '<div class="LC_warning">';
1.464     albertel 2508: 	    $result .= &mt('This student has submitted too many '.
                   2509: 		'collaborators.  Maximum is [_1].',$ncol);
                   2510: 	    $result .= '</div>';
                   2511: 	}
                   2512:     }
                   2513:     return ($result,$fullname,\@col_fullnames);
                   2514: }
                   2515: 
1.44      ng       2516: #--- Retrieve the last submission for all the parts
1.38      ng       2517: sub get_last_submission {
1.119     ng       2518:     my ($returnhash)=@_;
1.596     raeburn  2519:     my (@string,$timestamp,%lasthidden);
1.119     ng       2520:     if ($$returnhash{'version'}) {
1.46      ng       2521: 	my %lasthash=();
                   2522: 	my ($version);
1.119     ng       2523: 	for ($version=1;$version<=$$returnhash{'version'};$version++) {
1.397     albertel 2524: 	    foreach my $key (sort(split(/\:/,
                   2525: 					$$returnhash{$version.':keys'}))) {
                   2526: 		$lasthash{$key}=$$returnhash{$version.':'.$key};
                   2527: 		$timestamp = 
1.545     raeburn  2528: 		    &Apache::lonlocal::locallocaltime($$returnhash{$version.':timestamp'});
1.46      ng       2529: 	    }
                   2530: 	}
1.596.2.2  raeburn  2531:         my (%typeparts,%randombytry);
1.596     raeburn  2532:         my $showsurv = 
                   2533:             &Apache::lonnet::allowed('vas',$env{'request.course.id'});
                   2534:         foreach my $key (sort(keys(%lasthash))) {
                   2535:             if ($key =~ /\.type$/) {
                   2536:                 if (($lasthash{$key} eq 'anonsurvey') || 
1.596.2.2  raeburn  2537:                     ($lasthash{$key} eq 'anonsurveycred') ||
                   2538:                     ($lasthash{$key} eq 'randomizetry')) {
1.596     raeburn  2539:                     my ($ign,@parts) = split(/\./,$key);
                   2540:                     pop(@parts);
1.596.2.3  raeburn  2541:                     my $id = join('.',@parts);
1.596.2.2  raeburn  2542:                     if ($lasthash{$key} eq 'randomizetry') {
                   2543:                         $randombytry{$ign.'.'.$id} = $lasthash{$key};
                   2544:                     } else {
                   2545:                         unless ($showsurv) {
                   2546:                             $typeparts{$ign.'.'.$id} = $lasthash{$key};
                   2547:                         }
1.596     raeburn  2548:                     }
                   2549:                     delete($lasthash{$key});
                   2550:                 }
                   2551:             }
                   2552:         }
                   2553:         my @hidden = keys(%typeparts);
1.596.2.2  raeburn  2554:         my @randomize = keys(%randombytry);
1.397     albertel 2555: 	foreach my $key (keys(%lasthash)) {
                   2556: 	    next if ($key !~ /\.submission$/);
1.596     raeburn  2557:             my $hide;
                   2558:             if (@hidden) {
                   2559:                 foreach my $id (@hidden) {
                   2560:                     if ($key =~ /^\Q$id\E/) {
1.596.2.2  raeburn  2561:                         $hide = 'anon';
1.596     raeburn  2562:                         last;
                   2563:                     }
                   2564:                 }
                   2565:             }
1.596.2.2  raeburn  2566:             unless ($hide) {
                   2567:                 if (@randomize) {
                   2568:                     foreach my $id (@hidden) {
                   2569:                         if ($key =~ /^\Q$id\E/) {
                   2570:                             $hide = 'rand';
                   2571:                             last;
                   2572:                         }
                   2573:                     }
                   2574:                 }
                   2575:             }
1.397     albertel 2576: 	    my ($partid,$foo) = split(/submission$/,$key);
                   2577: 	    my $draft  = $lasthash{$partid.'awarddetail'} eq 'DRAFT' ?
1.398     albertel 2578: 		'<span class="LC_warning">Draft Copy</span> ' : '';
1.596     raeburn  2579: 	    push(@string, join(':', $key, $hide, $draft.$lasthash{$key}));
1.41      ng       2580: 	}
                   2581:     }
1.397     albertel 2582:     if (!@string) {
                   2583: 	$string[0] =
1.539     riegler  2584: 	    '<span class="LC_warning">'.&mt('Nothing submitted - no attempts.').'</span>';
1.397     albertel 2585:     }
                   2586:     return (\@string,\$timestamp);
1.38      ng       2587: }
1.35      ng       2588: 
1.44      ng       2589: #--- High light keywords, with style choosen by user.
1.38      ng       2590: sub keywords_highlight {
1.44      ng       2591:     my $string    = shift;
1.257     albertel 2592:     my $size      = $env{'form.kwsize'} eq '0' ? '' : 'size='.$env{'form.kwsize'};
                   2593:     my $styleon   = $env{'form.kwstyle'} eq ''  ? '' : $env{'form.kwstyle'};
1.41      ng       2594:     (my $styleoff = $styleon) =~ s/\</\<\//;
1.257     albertel 2595:     my @keylist   = split(/[,\s+]/,$env{'form.keywords'});
1.398     albertel 2596:     foreach my $keyword (@keylist) {
                   2597: 	$string =~ s/\b\Q$keyword\E(\b|\.)/<font color\=$env{'form.kwclr'} $size\>$styleon$keyword$styleoff<\/font>/gi;
1.41      ng       2598:     }
                   2599:     return $string;
1.38      ng       2600: }
1.36      ng       2601: 
1.44      ng       2602: #--- Called from submission routine
1.38      ng       2603: sub processHandGrade {
1.41      ng       2604:     my ($request) = shift;
1.324     albertel 2605:     my $symb   = &get_symb($request);
                   2606:     my (undef,undef,$url) = &Apache::lonnet::decode_symb($symb);
1.257     albertel 2607:     my $button = $env{'form.gradeOpt'};
                   2608:     my $ngrade = $env{'form.NCT'};
                   2609:     my $ntstu  = $env{'form.NTSTU'};
1.301     albertel 2610:     my $cdom   = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   2611:     my $cnum   = $env{'course.'.$env{'request.course.id'}.'.num'};
                   2612: 
1.44      ng       2613:     if ($button eq 'Save & Next') {
                   2614: 	my $ctr = 0;
                   2615: 	while ($ctr < $ngrade) {
1.257     albertel 2616: 	    my ($uname,$udom) = split(/:/,$env{'form.unamedom'.$ctr});
1.324     albertel 2617: 	    my ($errorflag,$pts,$wgt) = &saveHandGrade($request,$symb,$uname,$udom,$ctr);
1.71      ng       2618: 	    if ($errorflag eq 'no_score') {
                   2619: 		$ctr++;
                   2620: 		next;
                   2621: 	    }
1.104     albertel 2622: 	    if ($errorflag eq 'not_allowed') {
1.398     albertel 2623: 		$request->print("<span class=\"LC_warning\">Not allowed to modify grades for $uname:$udom</span>");
1.104     albertel 2624: 		$ctr++;
                   2625: 		next;
                   2626: 	    }
1.257     albertel 2627: 	    my $includemsg = $env{'form.includemsg'.$ctr};
1.44      ng       2628: 	    my ($subject,$message,$msgstatus) = ('','','');
1.418     albertel 2629: 	    my $restitle = &Apache::lonnet::gettitle($symb);
                   2630:             my ($feedurl,$showsymb) =
                   2631: 		&get_feedurl_and_symb($symb,$uname,$udom);
                   2632: 	    my $messagetail;
1.62      albertel 2633: 	    if ($includemsg =~ /savemsg|newmsg\Q$ctr\E/) {
1.298     www      2634: 		$subject = $env{'form.msgsub'} if ($includemsg =~ /msgsub/);
1.295     www      2635: 		unless ($subject=~/\w/) { $subject=&mt('Grading Feedback'); }
1.386     raeburn  2636: 		$subject.=' ['.$restitle.']';
1.44      ng       2637: 		my (@msgnum) = split(/,/,$includemsg);
                   2638: 		foreach (@msgnum) {
1.257     albertel 2639: 		    $message.=$env{'form.'.$_} if ($_ =~ /savemsg|newmsg/ && $_ ne '');
1.44      ng       2640: 		}
1.80      ng       2641: 		$message =&Apache::lonfeedback::clear_out_html($message);
1.298     www      2642: 		if ($env{'form.withgrades'.$ctr}) {
                   2643: 		    $message.="\n\nPoint".($pts > 1 ? 's':'').' awarded = '.$pts.' out of '.$wgt;
1.386     raeburn  2644: 		    $messagetail = " for <a href=\"".
1.418     albertel 2645: 		                   $feedurl."?symb=$showsymb\">$env{'form.probTitle'}</a>";
1.386     raeburn  2646: 		}
                   2647: 		$msgstatus = 
                   2648:                     &Apache::lonmsg::user_normal_msg($uname,$udom,$subject,
                   2649: 						     $message.$messagetail,
1.418     albertel 2650:                                                      undef,$feedurl,undef,
1.386     raeburn  2651:                                                      undef,undef,$showsymb,
                   2652:                                                      $restitle);
1.574     bisitz   2653: 		$request->print('<br />'.&mt('Sending message to [_1]',$uname.':'.$udom).': '.
1.596.2.4  raeburn  2654: 				$msgstatus.'<br />');
1.44      ng       2655: 	    }
1.257     albertel 2656: 	    if ($env{'form.collaborator'.$ctr}) {
1.155     albertel 2657: 		my @collabstrs=&Apache::loncommon::get_env_multiple("form.collaborator$ctr");
1.150     albertel 2658: 		foreach my $collabstr (@collabstrs) {
                   2659: 		    my ($part,@collaborators) = split(/:/,$collabstr);
1.310     banghart 2660: 		    foreach my $collaborator (@collaborators) {
1.150     albertel 2661: 			my ($errorflag,$pts,$wgt) = 
1.324     albertel 2662: 			    &saveHandGrade($request,$symb,$collaborator,$udom,$ctr,
1.257     albertel 2663: 					   $env{'form.unamedom'.$ctr},$part);
1.150     albertel 2664: 			if ($errorflag eq 'not_allowed') {
1.362     albertel 2665: 			    $request->print("<span class=\"LC_error\">".&mt('Not allowed to modify grades for [_1]',"$collaborator:$udom")."</span>");
1.150     albertel 2666: 			    next;
1.418     albertel 2667: 			} elsif ($message ne '') {
                   2668: 			    my ($baseurl,$showsymb) = 
                   2669: 				&get_feedurl_and_symb($symb,$collaborator,
                   2670: 						      $udom);
                   2671: 			    if ($env{'form.withgrades'.$ctr}) {
                   2672: 				$messagetail = " for <a href=\"".
1.386     raeburn  2673:                                     $baseurl."?symb=$showsymb\">$env{'form.probTitle'}</a>";
1.150     albertel 2674: 			    }
1.418     albertel 2675: 			    $msgstatus = 
                   2676: 				&Apache::lonmsg::user_normal_msg($collaborator,$udom,$subject,$message.$messagetail,undef,$baseurl,undef,undef,undef,$showsymb,$restitle);
1.104     albertel 2677: 			}
1.44      ng       2678: 		    }
                   2679: 		}
                   2680: 	    }
                   2681: 	    $ctr++;
                   2682: 	}
                   2683:     }
                   2684: 
1.257     albertel 2685:     if ($env{'form.handgrade'} eq 'yes') {
1.119     ng       2686: 	# Keywords sorted in alphabatical order
1.257     albertel 2687: 	my $loginuser = $env{'user.name'}.':'.$env{'user.domain'};
1.119     ng       2688: 	my %keyhash = ();
1.257     albertel 2689: 	$env{'form.keywords'}           =~ s/,\s{0,}|\s+/ /g;
                   2690: 	$env{'form.keywords'}           =~ s/^\s+|\s+$//;
                   2691: 	my (@keywords) = sort(split(/\s+/,$env{'form.keywords'}));
                   2692: 	$env{'form.keywords'} = join(' ',@keywords);
                   2693: 	$keyhash{$symb.'_keywords'}     = $env{'form.keywords'};
                   2694: 	$keyhash{$symb.'_subject'}      = $env{'form.msgsub'};
                   2695: 	$keyhash{$loginuser.'_kwclr'}   = $env{'form.kwclr'};
                   2696: 	$keyhash{$loginuser.'_kwsize'}  = $env{'form.kwsize'};
                   2697: 	$keyhash{$loginuser.'_kwstyle'} = $env{'form.kwstyle'};
1.119     ng       2698: 
                   2699: 	# message center - Order of message gets changed. Blank line is eliminated.
1.257     albertel 2700: 	# New messages are saved in env for the next student.
1.119     ng       2701: 	# All messages are saved in nohist_handgrade.db
                   2702: 	my ($ctr,$idx) = (1,1);
1.257     albertel 2703: 	while ($ctr <= $env{'form.savemsgN'}) {
                   2704: 	    if ($env{'form.savemsg'.$ctr} ne '') {
                   2705: 		$keyhash{$symb.'_savemsg'.$idx} = $env{'form.savemsg'.$ctr};
1.119     ng       2706: 		$idx++;
                   2707: 	    }
                   2708: 	    $ctr++;
1.41      ng       2709: 	}
1.119     ng       2710: 	$ctr = 0;
                   2711: 	while ($ctr < $ngrade) {
1.257     albertel 2712: 	    if ($env{'form.newmsg'.$ctr} ne '') {
                   2713: 		$keyhash{$symb.'_savemsg'.$idx} = $env{'form.newmsg'.$ctr};
                   2714: 		$env{'form.savemsg'.$idx} = $env{'form.newmsg'.$ctr};
1.119     ng       2715: 		$idx++;
                   2716: 	    }
                   2717: 	    $ctr++;
1.41      ng       2718: 	}
1.257     albertel 2719: 	$env{'form.savemsgN'} = --$idx;
                   2720: 	$keyhash{$symb.'_savemsgN'} = $env{'form.savemsgN'};
1.119     ng       2721: 	my $putresult = &Apache::lonnet::put
1.301     albertel 2722: 	    ('nohist_handgrade',\%keyhash,$cdom,$cnum);
1.41      ng       2723:     }
1.44      ng       2724:     # Called by Save & Refresh from Highlight Attribute Window
1.257     albertel 2725:     my (undef,undef,$fullname) = &getclasslist($env{'form.section'},'1');
                   2726:     if ($env{'form.refresh'} eq 'on') {
1.86      ng       2727: 	my ($ctr,$total) = (0,0);
                   2728: 	while ($ctr < $ngrade) {
1.257     albertel 2729: 	    $total++ if  $env{'form.unamedom'.$ctr} ne '';
1.86      ng       2730: 	    $ctr++;
                   2731: 	}
1.257     albertel 2732: 	$env{'form.NTSTU'}=$ngrade;
1.86      ng       2733: 	$ctr = 0;
                   2734: 	while ($ctr < $total) {
1.257     albertel 2735: 	    my $processUser = $env{'form.unamedom'.$ctr};
                   2736: 	    ($env{'form.student'},$env{'form.userdom'}) = split(/:/,$processUser);
                   2737: 	    $env{'form.fullname'} = $$fullname{$processUser};
1.86      ng       2738: 	    &submission($request,$ctr,$total-1);
1.41      ng       2739: 	    $ctr++;
                   2740: 	}
                   2741: 	return '';
                   2742:     }
1.36      ng       2743: 
1.121     ng       2744: # Go directly to grade student - from submission or link from chart page
1.120     ng       2745:     if ($button eq 'Grade Student') {
1.324     albertel 2746: 	(undef,undef,$env{'form.handgrade'},undef,undef) = &showResourceInfo($symb);
1.257     albertel 2747: 	my $processUser = $env{'form.unamedom'.$env{'form.studentNo'}};
                   2748: 	($env{'form.student'},$env{'form.userdom'}) = split(/:/,$processUser);
                   2749: 	$env{'form.fullname'} = $$fullname{$processUser};
1.120     ng       2750: 	&submission($request,0,0);
                   2751: 	return '';
                   2752:     }
                   2753: 
1.44      ng       2754:     # Get the next/previous one or group of students
1.257     albertel 2755:     my $firststu = $env{'form.unamedom0'};
                   2756:     my $laststu = $env{'form.unamedom'.($ngrade-1)};
1.119     ng       2757:     my $ctr = 2;
1.41      ng       2758:     while ($laststu eq '') {
1.257     albertel 2759: 	$laststu  = $env{'form.unamedom'.($ngrade-$ctr)};
1.41      ng       2760: 	$ctr++;
                   2761: 	$laststu = $firststu if ($ctr > $ngrade);
                   2762:     }
1.44      ng       2763: 
1.41      ng       2764:     my (@parsedlist,@nextlist);
                   2765:     my ($nextflg) = 0;
1.524     raeburn  2766:     foreach my $item (sort 
1.294     albertel 2767: 	     {
                   2768: 		 if (lc($$fullname{$a}) ne lc($$fullname{$b})) {
                   2769: 		     return (lc($$fullname{$a}) cmp lc($$fullname{$b}));
                   2770: 		 }
                   2771: 		 return $a cmp $b;
                   2772: 	     } (keys(%$fullname))) {
1.41      ng       2773: 	if ($nextflg == 1 && $button =~ /Next$/) {
1.524     raeburn  2774: 	    push(@parsedlist,$item);
1.41      ng       2775: 	}
1.524     raeburn  2776: 	$nextflg = 1 if ($item eq $laststu);
1.41      ng       2777: 	if ($button eq 'Previous') {
1.524     raeburn  2778: 	    last if ($item eq $firststu);
                   2779: 	    push(@parsedlist,$item);
1.41      ng       2780: 	}
                   2781:     }
                   2782:     $ctr = 0;
                   2783:     @parsedlist = reverse @parsedlist if ($button eq 'Previous');
1.582     raeburn  2784:     my $res_error;
                   2785:     my ($partlist) = &response_type($symb,\$res_error);
                   2786:     if ($res_error) {
                   2787:         $request->print(&navmap_errormsg());
                   2788:         return;
                   2789:     }
1.41      ng       2790:     foreach my $student (@parsedlist) {
1.257     albertel 2791: 	my $submitonly=$env{'form.submitonly'};
1.41      ng       2792: 	my ($uname,$udom) = split(/:/,$student);
1.301     albertel 2793: 	
                   2794: 	if ($submitonly eq 'queued') {
                   2795: 	    my %queue_status = 
                   2796: 		&Apache::bridgetask::get_student_status($symb,$cdom,$cnum,
                   2797: 							$udom,$uname);
                   2798: 	    next if (!defined($queue_status{'gradingqueue'}));
                   2799: 	}
                   2800: 
1.156     albertel 2801: 	if ($submitonly =~ /^(yes|graded|incorrect)$/) {
1.257     albertel 2802: #	    my %record = &Apache::lonnet::restore($symb,$env{'request.course.id'},$udom,$uname);
1.324     albertel 2803: 	    my %status=&student_gradeStatus($symb,$udom,$uname,$partlist);
1.145     albertel 2804: 	    my $submitted = 0;
1.248     albertel 2805: 	    my $ungraded = 0;
                   2806: 	    my $incorrect = 0;
1.524     raeburn  2807: 	    foreach my $item (keys(%status)) {
                   2808: 		$submitted = 1 if ($status{$item} ne 'nothing');
                   2809: 		$ungraded = 1 if ($status{$item} =~ /^ungraded/);
                   2810: 		$incorrect = 1 if ($status{$item} =~ /^incorrect/);
                   2811: 		my ($foo,$partid,$foo1) = split(/\./,$item);
1.145     albertel 2812: 		if ($status{'resource.'.$partid.'.submitted_by'} ne '') {
                   2813: 		    $submitted = 0;
                   2814: 		}
1.41      ng       2815: 	    }
1.156     albertel 2816: 	    next if (!$submitted && ($submitonly eq 'yes' ||
                   2817: 				     $submitonly eq 'incorrect' ||
                   2818: 				     $submitonly eq 'graded'));
1.248     albertel 2819: 	    next if (!$ungraded && ($submitonly eq 'graded'));
                   2820: 	    next if (!$incorrect && $submitonly eq 'incorrect');
1.41      ng       2821: 	}
1.524     raeburn  2822: 	push(@nextlist,$student) if ($ctr < $ntstu);
1.129     ng       2823: 	last if ($ctr == $ntstu);
1.41      ng       2824: 	$ctr++;
                   2825:     }
1.36      ng       2826: 
1.41      ng       2827:     $ctr = 0;
                   2828:     my $total = scalar(@nextlist)-1;
1.39      ng       2829: 
1.524     raeburn  2830:     foreach (sort(@nextlist)) {
1.41      ng       2831: 	my ($uname,$udom,$submitter) = split(/:/);
1.257     albertel 2832: 	$env{'form.student'}  = $uname;
                   2833: 	$env{'form.userdom'}  = $udom;
                   2834: 	$env{'form.fullname'} = $$fullname{$_};
1.41      ng       2835: 	&submission($request,$ctr,$total);
                   2836: 	$ctr++;
                   2837:     }
                   2838:     if ($total < 0) {
1.485     albertel 2839: 	my $the_end = '<h3><span class="LC_info">'.&mt('LON-CAPA User Message').'</span></h3><br />'."\n";
1.596.2.4  raeburn  2840: 	$the_end.='<p>'.&mt('[_1]Message:[_2] No more students for this section or class.','<b>','</b>').'</p>'."\n";
1.485     albertel 2841: 	$the_end.=&mt('Click on the button below to return to the grading menu.').'<br /><br />'."\n";
1.324     albertel 2842: 	$the_end.=&show_grading_menu_form($symb);
1.41      ng       2843: 	$request->print($the_end);
                   2844:     }
                   2845:     return '';
1.38      ng       2846: }
1.36      ng       2847: 
1.44      ng       2848: #---- Save the score and award for each student, if changed
1.38      ng       2849: sub saveHandGrade {
1.324     albertel 2850:     my ($request,$symb,$stuname,$domain,$newflg,$submitter,$part) = @_;
1.342     banghart 2851:     my @version_parts;
1.104     albertel 2852:     my $usec = &Apache::lonnet::getsection($domain,$stuname,
1.257     albertel 2853: 					   $env{'request.course.id'});
1.104     albertel 2854:     if (!&canmodify($usec)) { return('not_allowed'); }
1.337     banghart 2855:     my %record = &Apache::lonnet::restore($symb,$env{'request.course.id'},$domain,$stuname);
1.251     banghart 2856:     my @parts_graded;
1.77      ng       2857:     my %newrecord  = ();
                   2858:     my ($pts,$wgt) = ('','');
1.269     raeburn  2859:     my %aggregate = ();
                   2860:     my $aggregateflag = 0;
1.301     albertel 2861:     my @parts = split(/:/,$env{'form.partlist'.$newflg});
                   2862:     foreach my $new_part (@parts) {
1.337     banghart 2863: 	#collaborator ($submi may vary for different parts
1.259     banghart 2864: 	if ($submitter && $new_part ne $part) { next; }
                   2865: 	my $dropMenu = $env{'form.GD_SEL'.$newflg.'_'.$new_part};
1.125     ng       2866: 	if ($dropMenu eq 'excused') {
1.259     banghart 2867: 	    if ($record{'resource.'.$new_part.'.solved'} ne 'excused') {
                   2868: 		$newrecord{'resource.'.$new_part.'.solved'} = 'excused';
                   2869: 		if (exists($record{'resource.'.$new_part.'.awarded'})) {
                   2870: 		    $newrecord{'resource.'.$new_part.'.awarded'} = '';
1.58      albertel 2871: 		}
1.364     banghart 2872: 	        $newrecord{'resource.'.$new_part.'.regrader'}="$env{'user.name'}:$env{'user.domain'}";
1.58      albertel 2873: 	    }
1.125     ng       2874: 	} elsif ($dropMenu eq 'reset status'
1.259     banghart 2875: 		 && exists($record{'resource.'.$new_part.'.solved'})) { #don't bother if no old records -> no attempts
1.524     raeburn  2876: 	    foreach my $key (keys(%record)) {
1.259     banghart 2877: 		if ($key=~/^resource\.\Q$new_part\E\./) { $newrecord{$key} = ''; }
1.197     albertel 2878: 	    }
1.259     banghart 2879: 	    $newrecord{'resource.'.$new_part.'.regrader'}=
1.257     albertel 2880: 		"$env{'user.name'}:$env{'user.domain'}";
1.270     albertel 2881:             my $totaltries = $record{'resource.'.$part.'.tries'};
                   2882: 
                   2883:             my %last_resets = &get_last_resets($symb,$env{'request.course.id'},
                   2884: 					       [$new_part]);
                   2885:             my $aggtries =$totaltries;
1.269     raeburn  2886:             if ($last_resets{$new_part}) {
1.270     albertel 2887:                 $aggtries = &get_num_tries(\%record,$last_resets{$new_part},
                   2888: 					   $new_part);
1.269     raeburn  2889:             }
1.270     albertel 2890: 
                   2891:             my $solvedstatus = $record{'resource.'.$new_part.'.solved'};
1.269     raeburn  2892:             if ($aggtries > 0) {
1.327     albertel 2893:                 &decrement_aggs($symb,$new_part,\%aggregate,$aggtries,$totaltries,$solvedstatus);
1.269     raeburn  2894:                 $aggregateflag = 1;
                   2895:             }
1.125     ng       2896: 	} elsif ($dropMenu eq '') {
1.259     banghart 2897: 	    $pts = ($env{'form.GD_BOX'.$newflg.'_'.$new_part} ne '' ? 
                   2898: 		    $env{'form.GD_BOX'.$newflg.'_'.$new_part} : 
                   2899: 		    $env{'form.RADVAL'.$newflg.'_'.$new_part});
                   2900: 	    if ($pts eq '' && $env{'form.GD_SEL'.$newflg.'_'.$new_part} eq '') {
1.153     albertel 2901: 		next;
                   2902: 	    }
1.259     banghart 2903: 	    $wgt = $env{'form.WGT'.$newflg.'_'.$new_part} eq '' ? 1 : 
                   2904: 		$env{'form.WGT'.$newflg.'_'.$new_part};
1.41      ng       2905: 	    my $partial= $pts/$wgt;
1.259     banghart 2906: 	    if ($partial eq $record{'resource.'.$new_part.'.awarded'}) {
1.153     albertel 2907: 		#do not update score for part if not changed.
1.346     banghart 2908:                 &handback_files($request,$symb,$stuname,$domain,$newflg,$new_part,\%newrecord);
1.153     albertel 2909: 		next;
1.251     banghart 2910: 	    } else {
1.524     raeburn  2911: 	        push(@parts_graded,$new_part);
1.153     albertel 2912: 	    }
1.259     banghart 2913: 	    if ($record{'resource.'.$new_part.'.awarded'} ne $partial) {
                   2914: 		$newrecord{'resource.'.$new_part.'.awarded'}  = $partial;
1.153     albertel 2915: 	    }
1.259     banghart 2916: 	    my $reckey = 'resource.'.$new_part.'.solved';
1.41      ng       2917: 	    if ($partial == 0) {
1.153     albertel 2918: 		if ($record{$reckey} ne 'incorrect_by_override') {
                   2919: 		    $newrecord{$reckey} = 'incorrect_by_override';
                   2920: 		}
1.41      ng       2921: 	    } else {
1.153     albertel 2922: 		if ($record{$reckey} ne 'correct_by_override') {
                   2923: 		    $newrecord{$reckey} = 'correct_by_override';
                   2924: 		}
                   2925: 	    }	    
                   2926: 	    if ($submitter && 
1.259     banghart 2927: 		($record{'resource.'.$new_part.'.submitted_by'} ne $submitter)) {
                   2928: 		$newrecord{'resource.'.$new_part.'.submitted_by'} = $submitter;
1.41      ng       2929: 	    }
1.259     banghart 2930: 	    $newrecord{'resource.'.$new_part.'.regrader'}=
1.257     albertel 2931: 		"$env{'user.name'}:$env{'user.domain'}";
1.41      ng       2932: 	}
1.259     banghart 2933: 	# unless problem has been graded, set flag to version the submitted files
1.305     banghart 2934: 	unless ($record{'resource.'.$new_part.'.solved'} =~ /^correct_/  || 
                   2935: 	        $record{'resource.'.$new_part.'.solved'} eq 'incorrect_by_override' ||
                   2936: 	        $dropMenu eq 'reset status')
                   2937: 	   {
1.524     raeburn  2938: 	    push(@version_parts,$new_part);
1.259     banghart 2939: 	}
1.41      ng       2940:     }
1.301     albertel 2941:     my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   2942:     my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   2943: 
1.344     albertel 2944:     if (%newrecord) {
                   2945:         if (@version_parts) {
1.364     banghart 2946:             my @changed_keys = &version_portfiles(\%record, \@parts_graded, 
                   2947:                                 $env{'request.course.id'}, $symb, $domain, $stuname, \@version_parts);
1.344     albertel 2948: 	    @newrecord{@changed_keys} = @record{@changed_keys};
1.367     albertel 2949: 	    foreach my $new_part (@version_parts) {
                   2950: 		&handback_files($request,$symb,$stuname,$domain,$newflg,
                   2951: 				$new_part,\%newrecord);
                   2952: 	    }
1.259     banghart 2953:         }
1.44      ng       2954: 	&Apache::lonnet::cstore(\%newrecord,$symb,
1.257     albertel 2955: 				$env{'request.course.id'},$domain,$stuname);
1.380     albertel 2956: 	&check_and_remove_from_queue(\@parts,\%record,\%newrecord,$symb,
                   2957: 				     $cdom,$cnum,$domain,$stuname);
1.41      ng       2958:     }
1.269     raeburn  2959:     if ($aggregateflag) {
                   2960:         &Apache::lonnet::cinc('nohist_resourcetracker',\%aggregate,
1.301     albertel 2961: 			      $cdom,$cnum);
1.269     raeburn  2962:     }
1.301     albertel 2963:     return ('',$pts,$wgt);
1.36      ng       2964: }
1.322     albertel 2965: 
1.380     albertel 2966: sub check_and_remove_from_queue {
                   2967:     my ($parts,$record,$newrecord,$symb,$cdom,$cnum,$domain,$stuname) = @_;
                   2968:     my @ungraded_parts;
                   2969:     foreach my $part (@{$parts}) {
                   2970: 	if (    $record->{   'resource.'.$part.'.awarded'} eq ''
                   2971: 	     && $record->{   'resource.'.$part.'.solved' } ne 'excused'
                   2972: 	     && $newrecord->{'resource.'.$part.'.awarded'} eq ''
                   2973: 	     && $newrecord->{'resource.'.$part.'.solved' } ne 'excused'
                   2974: 		) {
                   2975: 	    push(@ungraded_parts, $part);
                   2976: 	}
                   2977:     }
                   2978:     if ( !@ungraded_parts ) {
                   2979: 	&Apache::bridgetask::remove_from_queue('gradingqueue',$symb,$cdom,
                   2980: 					       $cnum,$domain,$stuname);
                   2981:     }
                   2982: }
                   2983: 
1.337     banghart 2984: sub handback_files {
                   2985:     my ($request,$symb,$stuname,$domain,$newflg,$new_part,$newrecord) = @_;
1.517     raeburn  2986:     my $portfolio_root = '/userfiles/portfolio';
1.582     raeburn  2987:     my $res_error;
                   2988:     my ($partlist,$handgrade,$responseType) = &response_type($symb,\$res_error);
                   2989:     if ($res_error) {
                   2990:         $request->print('<br />'.&navmap_errormsg().'<br />');
                   2991:         return;
                   2992:     }
1.596.2.4  raeburn  2993:     my @handedback;
                   2994:     my $file_msg;
1.375     albertel 2995:     my @part_response_id = &flatten_responseType($responseType);
                   2996:     foreach my $part_response_id (@part_response_id) {
                   2997:     	my ($part_id,$resp_id) = @{ $part_response_id };
                   2998: 	my $part_resp = join('_',@{ $part_response_id });
1.596.2.4  raeburn  2999:         if (($env{'form.'.$newflg.'_'.$part_resp.'_countreturndoc'} =~ /^\d+$/) & ($new_part eq $part_id)) {
                   3000:             for (my $counter=1; $counter<=$env{'form.'.$newflg.'_'.$part_resp.'_countreturndoc'}; $counter++) {
1.337     banghart 3001:                 # if multiple files are uploaded names will be 'returndoc2','returndoc3'
1.596.2.4  raeburn  3002: 		if ($env{'form.'.$newflg.'_'.$part_resp.'_returndoc'.$counter}) {
                   3003:                     my $fname=$env{'form.'.$newflg.'_'.$part_resp.'_returndoc'.$counter.'.filename'};
1.338     banghart 3004:                     my ($directory,$answer_file) = 
1.596.2.4  raeburn  3005:                         ($env{'form.'.$newflg.'_'.$part_resp.'_origdoc'.$counter} =~ /^(.*?)([^\/]*)$/);
1.338     banghart 3006:                     my ($answer_name,$answer_ver,$answer_ext) =
                   3007: 		        &file_name_version_ext($answer_file);
1.355     banghart 3008: 		    my ($portfolio_path) = ($directory =~ /^.+$stuname\/portfolio(.*)/);
1.517     raeburn  3009:                     my $getpropath = 1;
                   3010: 		    my @dir_list = &Apache::lonnet::dirlist($portfolio_root.$portfolio_path,$domain,$stuname,$getpropath);
1.338     banghart 3011: 		    my $version = &get_next_version($answer_name, $answer_ext, \@dir_list);
1.355     banghart 3012:                     # fix file name
                   3013:                     my ($save_file_name) = (($directory.$answer_name.".$version.".$answer_ext) =~ /^.+\/${stuname}\/(.*)/);
                   3014:                     my $result=&Apache::lonnet::finishuserfileupload($stuname,$domain,
1.596.2.4  raeburn  3015:             	                                $newflg.'_'.$part_resp.'_returndoc'.$counter,
1.355     banghart 3016:             	                                $save_file_name);
1.337     banghart 3017:                     if ($result !~ m|^/uploaded/|) {
1.536     raeburn  3018:                         $request->print('<br /><span class="LC_error">'.
                   3019:                             &mt('An error occurred ([_1]) while trying to upload [_2].',
1.596.2.4  raeburn  3020:                                 $result,$newflg.'_'.$part_resp.'_returndoc'.$counter).
1.536     raeburn  3021:                                         '</span>');
1.356     banghart 3022:                     } else {
1.360     banghart 3023:                         # mark the file as read only
1.596.2.4  raeburn  3024:                         push(@handedback,$save_file_name);
1.367     albertel 3025: 			if (exists($$newrecord{"resource.$new_part.$resp_id.handback"})) {
                   3026: 			    $$newrecord{"resource.$new_part.$resp_id.handback"}.=',';
                   3027: 			}
                   3028:                         $$newrecord{"resource.$new_part.$resp_id.handback"} .= $save_file_name;
1.596.2.4  raeburn  3029: 			$file_msg.='<span class="LC_filename"><a href="/uploaded/'."$domain/$stuname/".$save_file_name.'">'.$save_file_name."</a></span> <br />";
1.367     albertel 3030: 
1.337     banghart 3031:                     }
1.596.2.4  raeburn  3032:                     $request->print('<br />'.&mt('[_1] will be the uploaded file name [_2]','<span class="LC_info">'.$fname.'</span>','<span class="LC_filename">'.$env{'form.'.$newflg.'_'.$part_resp.'_origdoc'.$counter}.'</span>'));
1.337     banghart 3033:                 }
                   3034:             }
                   3035:         }
1.596.2.4  raeburn  3036:     }
                   3037:     if (@handedback > 0) {
                   3038:         $request->print('<br />');
                   3039:         my @what = ($symb,$env{'request.course.id'},'handback');
                   3040:         &Apache::lonnet::mark_as_readonly($domain,$stuname,\@handedback,\@what);
                   3041:         my $user_lh = &Apache::loncommon::user_lang($stuname,$domain,$env{'request.course.id'});
                   3042:         my ($subject,$message);
                   3043:         if (scalar(@handedback) == 1) {
                   3044:             $subject = &mt_user($user_lh,'File Handed Back by Instructor');
                   3045:         } else {
                   3046:             $subject = &mt_user($user_lh,'Files Handed Back by Instructor');
                   3047:             $message = &mt_user($user_lh,'Files have been returned that were originally submitted in response to: ');
                   3048:         }
                   3049:         $message .= "<p><strong>".&Apache::lonnet::gettitle($symb)." </strong></p>";
                   3050:         $message .= &mt_user($user_lh,'The returned file(s) are named: [_1]',"<br />$file_msg <br />").
                   3051:                     &mt_user($user_lh,'The file(s) can be found in your [_1]portfolio[_2].','<a href="/adm/portfolio">','</a>');
                   3052:         my ($feedurl,$showsymb) =
                   3053:             &get_feedurl_and_symb($symb,$domain,$stuname);
                   3054:         my $restitle = &Apache::lonnet::gettitle($symb);
                   3055:         $subject .= ' '.&mt_user($user_lh,'(File Returned)').' ['.$restitle.']';
                   3056:         my $msgstatus =
                   3057:              &Apache::lonmsg::user_normal_msg($stuname,$domain,$subject,
                   3058:                  $message,undef,$feedurl,undef,undef,undef,$showsymb,
                   3059:                  $restitle);
                   3060:         if ($msgstatus) {
                   3061:             $request->print(&mt('Notification message status: [_1]','<span class="LC_info">'.$msgstatus.'</span>').'<br />');
                   3062:         }
                   3063:     }
1.338     banghart 3064:     return;
1.337     banghart 3065: }
                   3066: 
1.418     albertel 3067: sub get_feedurl_and_symb {
                   3068:     my ($symb,$uname,$udom) = @_;
                   3069:     my (undef,undef,$url) = &Apache::lonnet::decode_symb($symb);
                   3070:     $url = &Apache::lonnet::clutter($url);
                   3071:     my $encrypturl=&Apache::lonnet::EXT('resource.0.encrypturl',
                   3072: 					$symb,$udom,$uname);
                   3073:     if ($encrypturl =~ /^yes$/i) {
                   3074: 	&Apache::lonenc::encrypted(\$url,1);
                   3075: 	&Apache::lonenc::encrypted(\$symb,1);
                   3076:     }
                   3077:     return ($url,$symb);
                   3078: }
                   3079: 
1.313     banghart 3080: sub get_submitted_files {
                   3081:     my ($udom,$uname,$partid,$respid,$record) = @_;
                   3082:     my @files;
                   3083:     if ($$record{"resource.$partid.$respid.portfiles"}) {
                   3084:         my $file_url = '/uploaded/'.$udom.'/'.$uname.'/portfolio';
                   3085:         foreach my $file (split(',',$$record{"resource.$partid.$respid.portfiles"})) {
                   3086:     	    push(@files,$file_url.$file);
                   3087:         }
                   3088:     }
                   3089:     if ($$record{"resource.$partid.$respid.uploadedurl"}) {
                   3090:         push(@files,$$record{"resource.$partid.$respid.uploadedurl"});
                   3091:     }
                   3092:     return (\@files);
                   3093: }
1.322     albertel 3094: 
1.269     raeburn  3095: # ----------- Provides number of tries since last reset.
                   3096: sub get_num_tries {
                   3097:     my ($record,$last_reset,$part) = @_;
                   3098:     my $timestamp = '';
                   3099:     my $num_tries = 0;
                   3100:     if ($$record{'version'}) {
                   3101:         for (my $version=$$record{'version'};$version>=1;$version--) {
                   3102:             if (exists($$record{$version.':resource.'.$part.'.solved'})) {
                   3103:                 $timestamp = $$record{$version.':timestamp'};
                   3104:                 if ($timestamp > $last_reset) {
                   3105:                     $num_tries ++;
                   3106:                 } else {
                   3107:                     last;
                   3108:                 }
                   3109:             }
                   3110:         }
                   3111:     }
                   3112:     return $num_tries;
                   3113: }
                   3114: 
                   3115: # ----------- Determine decrements required in aggregate totals 
                   3116: sub decrement_aggs {
                   3117:     my ($symb,$part,$aggregate,$aggtries,$totaltries,$solvedstatus) = @_;
                   3118:     my %decrement = (
                   3119:                         attempts => 0,
                   3120:                         users => 0,
                   3121:                         correct => 0
                   3122:                     );
                   3123:     $decrement{'attempts'} = $aggtries;
                   3124:     if ($solvedstatus =~ /^correct/) {
                   3125:         $decrement{'correct'} = 1;
                   3126:     }
                   3127:     if ($aggtries == $totaltries) {
                   3128:         $decrement{'users'} = 1;
                   3129:     }
1.524     raeburn  3130:     foreach my $type (keys(%decrement)) {
1.269     raeburn  3131:         $$aggregate{$symb."\0".$part."\0".$type} = -$decrement{$type};
                   3132:     }
                   3133:     return;
                   3134: }
                   3135: 
                   3136: # ----------- Determine timestamps for last reset of aggregate totals for parts  
                   3137: sub get_last_resets {
1.270     albertel 3138:     my ($symb,$courseid,$partids) =@_;
                   3139:     my %last_resets;
1.269     raeburn  3140:     my $cdom = $env{'course.'.$courseid.'.domain'};
                   3141:     my $cname = $env{'course.'.$courseid.'.num'};
1.271     albertel 3142:     my @keys;
                   3143:     foreach my $part (@{$partids}) {
                   3144: 	push(@keys,"$symb\0$part\0resettime");
                   3145:     }
                   3146:     my %results=&Apache::lonnet::get('nohist_resourcetracker',\@keys,
                   3147: 				     $cdom,$cname);
                   3148:     foreach my $part (@{$partids}) {
                   3149: 	$last_resets{$part}=$results{"$symb\0$part\0resettime"};
1.269     raeburn  3150:     }
1.270     albertel 3151:     return %last_resets;
1.269     raeburn  3152: }
                   3153: 
1.251     banghart 3154: # ----------- Handles creating versions for portfolio files as answers
                   3155: sub version_portfiles {
1.343     banghart 3156:     my ($record, $parts_graded, $courseid, $symb, $domain, $stu_name, $v_flag) = @_;
1.263     banghart 3157:     my $version_parts = join('|',@$v_flag);
1.343     banghart 3158:     my @returned_keys;
1.255     banghart 3159:     my $parts = join('|', @$parts_graded);
1.517     raeburn  3160:     my $portfolio_root = '/userfiles/portfolio';
1.277     albertel 3161:     foreach my $key (keys(%$record)) {
1.259     banghart 3162:         my $new_portfiles;
1.263     banghart 3163:         if ($key =~ /^resource\.($version_parts)\./ && $key =~ /\.portfiles$/ ) {
1.342     banghart 3164:             my @versioned_portfiles;
1.367     albertel 3165:             my @portfiles = split(/\s*,\s*/,$$record{$key});
1.252     banghart 3166:             foreach my $file (@portfiles) {
1.306     banghart 3167:                 &Apache::lonnet::unmark_as_readonly($domain,$stu_name,[$symb,$env{'request.course.id'}],$file);
1.304     albertel 3168:                 my ($directory,$answer_file) =($file =~ /^(.*?)([^\/]*)$/);
                   3169: 		my ($answer_name,$answer_ver,$answer_ext) =
                   3170: 		    &file_name_version_ext($answer_file);
1.517     raeburn  3171:                 my $getpropath = 1;    
                   3172:                 my @dir_list = &Apache::lonnet::dirlist($portfolio_root.$directory,$domain,$stu_name,$getpropath);
1.342     banghart 3173:                 my $version = &get_next_version($answer_name, $answer_ext, \@dir_list);
1.306     banghart 3174:                 my $new_answer = &version_selected_portfile($domain, $stu_name, $directory, $answer_file, $version);
                   3175:                 if ($new_answer ne 'problem getting file') {
1.342     banghart 3176:                     push(@versioned_portfiles, $directory.$new_answer);
1.306     banghart 3177:                     &Apache::lonnet::mark_as_readonly($domain,$stu_name,
1.367     albertel 3178:                         [$directory.$new_answer],
1.306     banghart 3179:                         [$symb,$env{'request.course.id'},'graded']);
1.259     banghart 3180:                 }
1.252     banghart 3181:             }
1.343     banghart 3182:             $$record{$key} = join(',',@versioned_portfiles);
                   3183:             push(@returned_keys,$key);
1.251     banghart 3184:         }
                   3185:     } 
1.343     banghart 3186:     return (@returned_keys);   
1.305     banghart 3187: }
                   3188: 
1.307     banghart 3189: sub get_next_version {
1.341     banghart 3190:     my ($answer_name, $answer_ext, $dir_list) = @_;
1.307     banghart 3191:     my $version;
                   3192:     foreach my $row (@$dir_list) {
                   3193:         my ($file) = split(/\&/,$row,2);
                   3194:         my ($file_name,$file_version,$file_ext) =
                   3195: 	    &file_name_version_ext($file);
                   3196:         if (($file_name eq $answer_name) && 
                   3197: 	    ($file_ext eq $answer_ext)) {
                   3198:                 # gets here if filename and extension match, regardless of version
                   3199:                 if ($file_version ne '') {
                   3200:                 # a versioned file is found  so save it for later
                   3201:                 if ($file_version > $version) {
                   3202: 		    $version = $file_version;
                   3203: 	        }
                   3204:             }
                   3205:         }
                   3206:     } 
                   3207:     $version ++;
                   3208:     return($version);
                   3209: }
                   3210: 
1.305     banghart 3211: sub version_selected_portfile {
1.306     banghart 3212:     my ($domain,$stu_name,$directory,$file_name,$version) = @_;
                   3213:     my ($answer_name,$answer_ver,$answer_ext) =
                   3214:         &file_name_version_ext($file_name);
                   3215:     my $new_answer;
                   3216:     $env{'form.copy'} = &Apache::lonnet::getfile("/uploaded/$domain/$stu_name/portfolio$directory$file_name");
                   3217:     if($env{'form.copy'} eq '-1') {
                   3218:         $new_answer = 'problem getting file';
                   3219:     } else {
                   3220:         $new_answer = $answer_name.'.'.$version.'.'.$answer_ext;
                   3221:         my $copy_result = &Apache::lonnet::finishuserfileupload(
                   3222:                             $stu_name,$domain,'copy',
                   3223: 		        '/portfolio'.$directory.$new_answer);
                   3224:     }    
                   3225:     return ($new_answer);
1.251     banghart 3226: }
                   3227: 
1.304     albertel 3228: sub file_name_version_ext {
                   3229:     my ($file)=@_;
                   3230:     my @file_parts = split(/\./, $file);
                   3231:     my ($name,$version,$ext);
                   3232:     if (@file_parts > 1) {
                   3233: 	$ext=pop(@file_parts);
                   3234: 	if (@file_parts > 1 && $file_parts[-1] =~ /^\d+$/) {
                   3235: 	    $version=pop(@file_parts);
                   3236: 	}
                   3237: 	$name=join('.',@file_parts);
                   3238:     } else {
                   3239: 	$name=join('.',@file_parts);
                   3240:     }
                   3241:     return($name,$version,$ext);
                   3242: }
                   3243: 
1.44      ng       3244: #--------------------------------------------------------------------------------------
                   3245: #
                   3246: #-------------------------- Next few routines handles grading by section or whole class
                   3247: #
                   3248: #--- Javascript to handle grading by section or whole class
1.42      ng       3249: sub viewgrades_js {
                   3250:     my ($request) = shift;
                   3251: 
1.539     riegler  3252:     my $alertmsg = &mt('A number equal or greater than 0 is expected. Entered value = ');
1.41      ng       3253:     $request->print(<<VIEWJAVASCRIPT);
                   3254: <script type="text/javascript" language="javascript">
1.45      ng       3255:    function writePoint(partid,weight,point) {
1.125     ng       3256: 	var radioButton = document.classgrade["RADVAL_"+partid];
                   3257: 	var textbox = document.classgrade["TEXTVAL_"+partid];
1.42      ng       3258: 	if (point == "textval") {
1.125     ng       3259: 	    point = document.classgrade["TEXTVAL_"+partid].value;
1.109     matthew  3260: 	    if (isNaN(point) || parseFloat(point) < 0) {
1.539     riegler  3261: 		alert("$alertmsg"+parseFloat(point));
1.42      ng       3262: 		var resetbox = false;
                   3263: 		for (var i=0; i<radioButton.length; i++) {
                   3264: 		    if (radioButton[i].checked) {
                   3265: 			textbox.value = i;
                   3266: 			resetbox = true;
                   3267: 		    }
                   3268: 		}
                   3269: 		if (!resetbox) {
                   3270: 		    textbox.value = "";
                   3271: 		}
                   3272: 		return;
                   3273: 	    }
1.109     matthew  3274: 	    if (parseFloat(point) > parseFloat(weight)) {
                   3275: 		var resp = confirm("You entered a value ("+parseFloat(point)+
1.44      ng       3276: 				   ") greater than the weight for the part. Accept?");
                   3277: 		if (resp == false) {
                   3278: 		    textbox.value = "";
                   3279: 		    return;
                   3280: 		}
                   3281: 	    }
1.42      ng       3282: 	    for (var i=0; i<radioButton.length; i++) {
                   3283: 		radioButton[i].checked=false;
1.109     matthew  3284: 		if (parseFloat(point) == i) {
1.42      ng       3285: 		    radioButton[i].checked=true;
                   3286: 		}
                   3287: 	    }
1.41      ng       3288: 
1.42      ng       3289: 	} else {
1.125     ng       3290: 	    textbox.value = parseFloat(point);
1.42      ng       3291: 	}
1.41      ng       3292: 	for (i=0;i<document.classgrade.total.value;i++) {
1.125     ng       3293: 	    var user = document.classgrade["ctr"+i].value;
1.289     albertel 3294: 	    user = user.replace(new RegExp(':', 'g'),"_");
1.125     ng       3295: 	    var scorename = document.classgrade["GD_"+user+"_"+partid+"_awarded"];
                   3296: 	    var saveval   = document.classgrade["GD_"+user+"_"+partid+"_solved_s"].value;
                   3297: 	    var selname   = document.classgrade["GD_"+user+"_"+partid+"_solved"];
1.42      ng       3298: 	    if (saveval != "correct") {
                   3299: 		scorename.value = point;
1.43      ng       3300: 		if (selname[0].selected != true) {
                   3301: 		    selname[0].selected = true;
                   3302: 		}
1.42      ng       3303: 	    }
                   3304: 	}
1.125     ng       3305: 	document.classgrade["SELVAL_"+partid][0].selected = true;
1.42      ng       3306:     }
                   3307: 
                   3308:     function writeRadText(partid,weight) {
1.125     ng       3309: 	var selval   = document.classgrade["SELVAL_"+partid];
                   3310: 	var radioButton = document.classgrade["RADVAL_"+partid];
1.265     www      3311:         var override = document.classgrade["FORCE_"+partid].checked;
1.125     ng       3312: 	var textbox = document.classgrade["TEXTVAL_"+partid];
                   3313: 	if (selval[1].selected || selval[2].selected) {
1.42      ng       3314: 	    for (var i=0; i<radioButton.length; i++) {
                   3315: 		radioButton[i].checked=false;
                   3316: 
                   3317: 	    }
                   3318: 	    textbox.value = "";
                   3319: 
                   3320: 	    for (i=0;i<document.classgrade.total.value;i++) {
1.125     ng       3321: 		var user = document.classgrade["ctr"+i].value;
1.289     albertel 3322: 		user = user.replace(new RegExp(':', 'g'),"_");
1.125     ng       3323: 		var scorename = document.classgrade["GD_"+user+"_"+partid+"_awarded"];
                   3324: 		var saveval   = document.classgrade["GD_"+user+"_"+partid+"_solved_s"].value;
                   3325: 		var selname   = document.classgrade["GD_"+user+"_"+partid+"_solved"];
1.265     www      3326: 		if ((saveval != "correct") || override) {
1.42      ng       3327: 		    scorename.value = "";
1.125     ng       3328: 		    if (selval[1].selected) {
                   3329: 			selname[1].selected = true;
                   3330: 		    } else {
                   3331: 			selname[2].selected = true;
                   3332: 			if (Number(document.classgrade["GD_"+user+"_"+partid+"_tries"].value)) 
                   3333: 			{document.classgrade["GD_"+user+"_"+partid+"_tries"].value = '0';}
                   3334: 		    }
1.42      ng       3335: 		}
                   3336: 	    }
1.43      ng       3337: 	} else {
                   3338: 	    for (i=0;i<document.classgrade.total.value;i++) {
1.125     ng       3339: 		var user = document.classgrade["ctr"+i].value;
1.289     albertel 3340: 		user = user.replace(new RegExp(':', 'g'),"_");
1.125     ng       3341: 		var scorename = document.classgrade["GD_"+user+"_"+partid+"_awarded"];
                   3342: 		var saveval   = document.classgrade["GD_"+user+"_"+partid+"_solved_s"].value;
                   3343: 		var selname   = document.classgrade["GD_"+user+"_"+partid+"_solved"];
1.265     www      3344: 		if ((saveval != "correct") || override) {
1.125     ng       3345: 		    scorename.value = document.classgrade["GD_"+user+"_"+partid+"_awarded_s"].value;
1.43      ng       3346: 		    selname[0].selected = true;
                   3347: 		}
                   3348: 	    }
                   3349: 	}	    
1.42      ng       3350:     }
                   3351: 
                   3352:     function changeSelect(partid,user) {
1.125     ng       3353: 	var selval = document.classgrade["GD_"+user+'_'+partid+"_solved"];
                   3354: 	var textbox = document.classgrade["GD_"+user+'_'+partid+"_awarded"];
1.44      ng       3355: 	var point  = textbox.value;
1.125     ng       3356: 	var weight = document.classgrade["weight_"+partid].value;
1.44      ng       3357: 
1.109     matthew  3358: 	if (isNaN(point) || parseFloat(point) < 0) {
1.539     riegler  3359: 	    alert("$alertmsg"+parseFloat(point));
1.44      ng       3360: 	    textbox.value = "";
                   3361: 	    return;
                   3362: 	}
1.109     matthew  3363: 	if (parseFloat(point) > parseFloat(weight)) {
                   3364: 	    var resp = confirm("You entered a value ("+parseFloat(point)+
1.44      ng       3365: 			       ") greater than the weight of the part. Accept?");
                   3366: 	    if (resp == false) {
                   3367: 		textbox.value = "";
                   3368: 		return;
                   3369: 	    }
                   3370: 	}
1.42      ng       3371: 	selval[0].selected = true;
                   3372:     }
                   3373: 
                   3374:     function changeOneScore(partid,user) {
1.125     ng       3375: 	var selval = document.classgrade["GD_"+user+'_'+partid+"_solved"];
                   3376: 	if (selval[1].selected || selval[2].selected) {
                   3377: 	    document.classgrade["GD_"+user+'_'+partid+"_awarded"].value = "";
                   3378: 	    if (selval[2].selected) {
                   3379: 		document.classgrade["GD_"+user+'_'+partid+"_tries"].value = "0";
                   3380: 	    }
1.269     raeburn  3381:         }
1.42      ng       3382:     }
                   3383: 
                   3384:     function resetEntry(numpart) {
                   3385: 	for (ctpart=0;ctpart<numpart;ctpart++) {
1.125     ng       3386: 	    var partid = document.classgrade["partid_"+ctpart].value;
                   3387: 	    var radioButton = document.classgrade["RADVAL_"+partid];
                   3388: 	    var textbox = document.classgrade["TEXTVAL_"+partid];
                   3389: 	    var selval  = document.classgrade["SELVAL_"+partid];
1.42      ng       3390: 	    for (var i=0; i<radioButton.length; i++) {
                   3391: 		radioButton[i].checked=false;
                   3392: 
                   3393: 	    }
                   3394: 	    textbox.value = "";
                   3395: 	    selval[0].selected = true;
                   3396: 
                   3397: 	    for (i=0;i<document.classgrade.total.value;i++) {
1.125     ng       3398: 		var user = document.classgrade["ctr"+i].value;
1.289     albertel 3399: 		user = user.replace(new RegExp(':', 'g'),"_");
1.125     ng       3400: 		var resetscore = document.classgrade["GD_"+user+"_"+partid+"_awarded"];
                   3401: 		resetscore.value = document.classgrade["GD_"+user+"_"+partid+"_awarded_s"].value;
                   3402: 		var resettries = document.classgrade["GD_"+user+"_"+partid+"_tries"];
                   3403: 		resettries.value = document.classgrade["GD_"+user+"_"+partid+"_tries_s"].value;
                   3404: 		var saveselval   = document.classgrade["GD_"+user+"_"+partid+"_solved_s"].value;
                   3405: 		var selname   = document.classgrade["GD_"+user+"_"+partid+"_solved"];
1.42      ng       3406: 		if (saveselval == "excused") {
1.43      ng       3407: 		    if (selname[1].selected == false) { selname[1].selected = true;}
1.42      ng       3408: 		} else {
1.43      ng       3409: 		    if (selname[0].selected == false) {selname[0].selected = true};
1.42      ng       3410: 		}
                   3411: 	    }
1.41      ng       3412: 	}
1.42      ng       3413:     }
                   3414: 
1.41      ng       3415: </script>
                   3416: VIEWJAVASCRIPT
1.42      ng       3417: }
                   3418: 
1.44      ng       3419: #--- show scores for a section or whole class w/ option to change/update a score
1.42      ng       3420: sub viewgrades {
                   3421:     my ($request) = shift;
                   3422:     &viewgrades_js($request);
1.41      ng       3423: 
1.324     albertel 3424:     my ($symb) = &get_symb($request);
1.168     albertel 3425:     #need to make sure we have the correct data for later EXT calls, 
                   3426:     #thus invalidate the cache
                   3427:     &Apache::lonnet::devalidatecourseresdata(
1.257     albertel 3428:                  $env{'course.'.$env{'request.course.id'}.'.num'},
                   3429:                  $env{'course.'.$env{'request.course.id'}.'.domain'});
1.168     albertel 3430:     &Apache::lonnet::clear_EXT_cache_status();
                   3431: 
1.398     albertel 3432:     my $result='<h3><span class="LC_info">'.&mt('Manual Grading').'</span></h3>';
1.485     albertel 3433:     $result.='<h4>'.&mt('<b>Current Resource: </b>[_1]',$env{'form.probTitle'}).'</h4>'."\n";
1.41      ng       3434: 
                   3435:     #view individual student submission form - called using Javascript viewOneStudent
1.324     albertel 3436:     $result.=&jscriptNform($symb);
1.41      ng       3437: 
1.44      ng       3438:     #beginning of class grading form
1.442     banghart 3439:     my $stu_status = join(':',&Apache::loncommon::get_env_multiple('form.Status'));
1.41      ng       3440:     $result.= '<form action="/adm/grades" method="post" name="classgrade">'."\n".
1.418     albertel 3441: 	'<input type="hidden" name="symb"    value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
1.38      ng       3442: 	'<input type="hidden" name="command" value="editgrades" />'."\n".
1.432     banghart 3443: 	&build_section_inputs().
1.257     albertel 3444: 	'<input type="hidden" name="saveState" value="'.$env{'form.saveState'}.'" />'."\n".
1.442     banghart 3445: 	'<input type="hidden" name="Status" value="'.$env{'stu_status'}.'" />'."\n".
1.257     albertel 3446: 	'<input type="hidden" name="probTitle" value="'.$env{'form.probTitle'}.'" />'."\n";
1.72      ng       3447: 
1.560     raeburn  3448:     my ($common_header,$specific_header);
1.257     albertel 3449:     if ($env{'form.section'} eq 'all') {
1.560     raeburn  3450: 	$common_header = &mt('Assign Common Grade to Class');
                   3451:         $specific_header = &mt('Assign Grade to Specific Students in Class');
1.257     albertel 3452:     } elsif ($env{'form.section'} eq 'none') {
1.560     raeburn  3453:         $common_header = &mt('Assign Common Grade to Students in no Section');
                   3454: 	$specific_header = &mt('Assign Grade to Specific Students in no Section');
1.52      albertel 3455:     } else {
1.560     raeburn  3456:         my $section_display = join (", ",&Apache::loncommon::get_env_multiple('form.section'));
                   3457:         $common_header = &mt('Assign Common Grade to Students in Section(s) [_1]',$section_display);
                   3458: 	$specific_header = &mt('Assign Grade to Specific Students in Section(s) [_1]',$section_display);
1.52      albertel 3459:     }
1.560     raeburn  3460:     $result.= '<h3>'.$common_header.'</h3>'.&Apache::loncommon::start_data_table();
1.44      ng       3461:     #radio buttons/text box for assigning points for a section or class.
                   3462:     #handles different parts of a problem
1.582     raeburn  3463:     my $res_error;
                   3464:     my ($partlist,$handgrade,$responseType) = &response_type($symb,\$res_error);
                   3465:     if ($res_error) {
                   3466:         return &navmap_errormsg();
                   3467:     }
1.42      ng       3468:     my %weight = ();
                   3469:     my $ctsparts = 0;
1.45      ng       3470:     my %seen = ();
1.375     albertel 3471:     my @part_response_id = &flatten_responseType($responseType);
                   3472:     foreach my $part_response_id (@part_response_id) {
                   3473:     	my ($partid,$respid) = @{ $part_response_id };
                   3474: 	my $part_resp = join('_',@{ $part_response_id });
1.45      ng       3475: 	next if $seen{$partid};
                   3476: 	$seen{$partid}++;
1.375     albertel 3477: 	my $handgrade=$$handgrade{$part_resp};
1.42      ng       3478: 	my $wgt = &Apache::lonnet::EXT('resource.'.$partid.'.weight',$symb);
                   3479: 	$weight{$partid} = $wgt eq '' ? '1' : $wgt;
                   3480: 
1.324     albertel 3481: 	my $display_part=&get_display_part($partid,$symb);
1.485     albertel 3482: 	my $radio.='<table border="0"><tr>';  
1.41      ng       3483: 	my $ctr = 0;
1.42      ng       3484: 	while ($ctr<=$weight{$partid}) { # display radio buttons in a nice table 10 across
1.485     albertel 3485: 	    $radio.= '<td><label><input type="radio" name="RADVAL_'.$partid.'" '.
1.54      albertel 3486: 		'onclick="javascript:writePoint(\''.$partid.'\','.$weight{$partid}.
1.288     albertel 3487: 		','.$ctr.')" />'.$ctr."</label></td>\n";
1.41      ng       3488: 	    $result.=(($ctr+1)%10 == 0 ? '</tr><tr>' : '');
                   3489: 	    $ctr++;
                   3490: 	}
1.485     albertel 3491: 	$radio.='</tr></table>';
                   3492: 	my $line = '<input type="text" name="TEXTVAL_'.
1.589     bisitz   3493: 	    $partid.'" size="4" '.'onchange="javascript:writePoint(\''.
1.54      albertel 3494: 		$partid.'\','.$weight{$partid}.',\'textval\')" /> /'.
1.539     riegler  3495: 	    $weight{$partid}.' '.&mt('(problem weight)').'</td>'."\n";
                   3496: 	$line.= '<td><b>'.&mt('Grade Status').':</b><select name="SELVAL_'.$partid.'"'.
1.589     bisitz   3497: 	    'onchange="javascript:writeRadText(\''.$partid.'\','.
1.59      albertel 3498: 		$weight{$partid}.')"> '.
1.401     albertel 3499: 	    '<option selected="selected"> </option>'.
1.485     albertel 3500: 	    '<option value="excused">'.&mt('excused').'</option>'.
                   3501: 	    '<option value="reset status">'.&mt('reset status').'</option>'.
                   3502: 	    '</select></td>'.
                   3503:             '<td><label><input type="checkbox" name="FORCE_'.$partid.'" />'.&mt('Override "Correct"').'</label>';
                   3504: 	$line.='<input type="hidden" name="partid_'.
                   3505: 	    $ctsparts.'" value="'.$partid.'" />'."\n";
                   3506: 	$line.='<input type="hidden" name="weight_'.
                   3507: 	    $partid.'" value="'.$weight{$partid}.'" />'."\n";
                   3508: 
                   3509: 	$result.=
                   3510: 	    &Apache::loncommon::start_data_table_row()."\n".
1.577     bisitz   3511: 	    '<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 3512: 	    &Apache::loncommon::end_data_table_row()."\n";
1.42      ng       3513: 	$ctsparts++;
1.41      ng       3514:     }
1.474     albertel 3515:     $result.=&Apache::loncommon::end_data_table()."\n".
1.52      albertel 3516: 	'<input type="hidden" name="totalparts" value="'.$ctsparts.'" />';
1.485     albertel 3517:     $result.='<input type="button" value="'.&mt('Revert to Default').'" '.
1.589     bisitz   3518: 	'onclick="javascript:resetEntry('.$ctsparts.');" />';
1.41      ng       3519: 
1.44      ng       3520:     #table listing all the students in a section/class
                   3521:     #header of table
1.560     raeburn  3522:     $result.= '<h3>'.$specific_header.'</h3>'.
                   3523:               &Apache::loncommon::start_data_table().
                   3524: 	      &Apache::loncommon::start_data_table_header_row().
                   3525: 	      '<th>'.&mt('No.').'</th>'.
                   3526: 	      '<th>'.&nameUserString('header')."</th>\n";
1.582     raeburn  3527:     my $partserror;
                   3528:     my (@parts) = sort(&getpartlist($symb,\$partserror));
                   3529:     if ($partserror) {
                   3530:         return &navmap_errormsg();
                   3531:     }
1.324     albertel 3532:     my (undef,undef,$url)=&Apache::lonnet::decode_symb($symb);
1.269     raeburn  3533:     my @partids = ();
1.41      ng       3534:     foreach my $part (@parts) {
                   3535: 	my $display=&Apache::lonnet::metadata($url,$part.'.display');
1.539     riegler  3536:         my $narrowtext = &mt('Tries');
                   3537: 	$display =~ s|^Number of Attempts|$narrowtext <br />|; # makes the column narrower
1.41      ng       3538: 	if  (!$display) { $display = &Apache::lonnet::metadata($url,$part.'.name'); }
1.207     albertel 3539: 	my ($partid) = &split_part_type($part);
1.524     raeburn  3540:         push(@partids,$partid);
1.324     albertel 3541: 	my $display_part=&get_display_part($partid,$symb);
1.41      ng       3542: 	if ($display =~ /^Partial Credit Factor/) {
1.485     albertel 3543: 	    $result.='<th>'.
                   3544: 		&mt('Score Part: [_1]<br /> (weight = [_2])',
                   3545: 		    $display_part,$weight{$partid}).'</th>'."\n";
1.41      ng       3546: 	    next;
1.485     albertel 3547: 	    
1.207     albertel 3548: 	} else {
1.485     albertel 3549: 	    if ($display =~ /Problem Status/) {
                   3550: 		my $grade_status_mt = &mt('Grade Status');
                   3551: 		$display =~ s{Problem Status}{$grade_status_mt<br />};
                   3552: 	    }
                   3553: 	    my $part_mt = &mt('Part:');
                   3554: 	    $display =~s{\[Part: \Q$partid\E\]}{$part_mt $display_part};
1.41      ng       3555: 	}
1.485     albertel 3556: 
1.474     albertel 3557: 	$result.='<th>'.$display.'</th>'."\n";
1.41      ng       3558:     }
1.474     albertel 3559:     $result.=&Apache::loncommon::end_data_table_header_row();
1.44      ng       3560: 
1.270     albertel 3561:     my %last_resets = 
                   3562: 	&get_last_resets($symb,$env{'request.course.id'},\@partids);
1.269     raeburn  3563: 
1.41      ng       3564:     #get info for each student
1.44      ng       3565:     #list all the students - with points and grade status
1.257     albertel 3566:     my (undef,undef,$fullname) = &getclasslist($env{'form.section'},'1');
1.41      ng       3567:     my $ctr = 0;
1.294     albertel 3568:     foreach (sort 
                   3569: 	     {
                   3570: 		 if (lc($$fullname{$a}) ne lc($$fullname{$b})) {
                   3571: 		     return (lc($$fullname{$a}) cmp lc($$fullname{$b}));
                   3572: 		 }
                   3573: 		 return $a cmp $b;
                   3574: 	     } (keys(%$fullname))) {
1.126     ng       3575: 	$ctr++;
1.324     albertel 3576: 	$result.=&viewstudentgrade($symb,$env{'request.course.id'},
1.269     raeburn  3577: 				   $_,$$fullname{$_},\@parts,\%weight,$ctr,\%last_resets);
1.41      ng       3578:     }
1.474     albertel 3579:     $result.=&Apache::loncommon::end_data_table();
1.41      ng       3580:     $result.='<input type="hidden" name="total" value="'.$ctr.'" />'."\n";
1.485     albertel 3581:     $result.='<input type="button" value="'.&mt('Save').'" '.
1.589     bisitz   3582: 	'onclick="javascript:submit();" target="_self" /></form>'."\n";
1.96      albertel 3583:     if (scalar(%$fullname) eq 0) {
                   3584: 	my $colspan=3+scalar(@parts);
1.433     banghart 3585: 	my $section_display = join (", ",&Apache::loncommon::get_env_multiple('form.section'));
1.442     banghart 3586:         my $stu_status = join(' or ',&Apache::loncommon::get_env_multiple('form.Status'));
1.433     banghart 3587: 	$result='<span class="LC_warning">'.
1.485     albertel 3588: 	    &mt('There are no students in section(s) [_1] with enrollment status [_2] to modify or grade.',
1.442     banghart 3589: 	        $section_display, $stu_status).
1.433     banghart 3590: 	    '</span>';
1.96      albertel 3591:     }
1.324     albertel 3592:     $result.=&show_grading_menu_form($symb);
1.41      ng       3593:     return $result;
                   3594: }
                   3595: 
1.44      ng       3596: #--- call by previous routine to display each student
1.41      ng       3597: sub viewstudentgrade {
1.324     albertel 3598:     my ($symb,$courseid,$student,$fullname,$parts,$weight,$ctr,$last_resets) = @_;
1.44      ng       3599:     my ($uname,$udom) = split(/:/,$student);
                   3600:     my %record=&Apache::lonnet::restore($symb,$courseid,$udom,$uname);
1.269     raeburn  3601:     my %aggregates = (); 
1.474     albertel 3602:     my $result=&Apache::loncommon::start_data_table_row().'<td align="right">'.
1.233     albertel 3603: 	'<input type="hidden" name="ctr'.($ctr-1).'" value="'.$student.'" />'.
                   3604: 	"\n".$ctr.'&nbsp;</td><td>&nbsp;'.
1.44      ng       3605: 	'<a href="javascript:viewOneStudent(\''.$uname.'\',\''.$udom.
1.417     albertel 3606: 	'\');" target="_self">'.$fullname.'</a> '.
1.398     albertel 3607: 	'<span class="LC_internal_info">('.$uname.($env{'user.domain'} eq $udom ? '' : ':'.$udom).')</span></td>'."\n";
1.281     albertel 3608:     $student=~s/:/_/; # colon doen't work in javascript for names
1.63      albertel 3609:     foreach my $apart (@$parts) {
                   3610: 	my ($part,$type) = &split_part_type($apart);
1.41      ng       3611: 	my $score=$record{"resource.$part.$type"};
1.276     albertel 3612:         $result.='<td align="center">';
1.269     raeburn  3613:         my ($aggtries,$totaltries);
                   3614:         unless (exists($aggregates{$part})) {
1.270     albertel 3615: 	    $totaltries = $record{'resource.'.$part.'.tries'};
                   3616: 
                   3617: 	    $aggtries = $totaltries;
1.269     raeburn  3618:             if ($$last_resets{$part}) {  
1.270     albertel 3619:                 $aggtries = &get_num_tries(\%record,$$last_resets{$part},
                   3620: 					   $part);
                   3621:             }
1.269     raeburn  3622:             $result.='<input type="hidden" name="'.
                   3623:                 'GD_'.$student.'_'.$part.'_aggtries" value="'.$aggtries.'" />'."\n";
                   3624:             $result.='<input type="hidden" name="'.
                   3625:                 'GD_'.$student.'_'.$part.'_totaltries" value="'.$totaltries.'" />'."\n";
                   3626:             $aggregates{$part} = 1;
                   3627:         }
1.41      ng       3628: 	if ($type eq 'awarded') {
1.320     albertel 3629: 	    my $pts = $score eq '' ? '' : &compute_points($score,$$weight{$part});
1.42      ng       3630: 	    $result.='<input type="hidden" name="'.
1.89      albertel 3631: 		'GD_'.$student.'_'.$part.'_awarded_s" value="'.$pts.'" />'."\n";
1.233     albertel 3632: 	    $result.='<input type="text" name="'.
1.89      albertel 3633: 		'GD_'.$student.'_'.$part.'_awarded" '.
1.589     bisitz   3634:                 'onchange="javascript:changeSelect(\''.$part.'\',\''.$student.
1.44      ng       3635: 		'\')" value="'.$pts.'" size="4" /></td>'."\n";
1.41      ng       3636: 	} elsif ($type eq 'solved') {
                   3637: 	    my ($status,$foo)=split(/_/,$score,2);
                   3638: 	    $status = 'nothing' if ($status eq '');
1.89      albertel 3639: 	    $result.='<input type="hidden" name="'.'GD_'.$student.'_'.
1.54      albertel 3640: 		$part.'_solved_s" value="'.$status.'" />'."\n";
1.233     albertel 3641: 	    $result.='&nbsp;<select name="'.
1.89      albertel 3642: 		'GD_'.$student.'_'.$part.'_solved" '.
1.589     bisitz   3643:                 'onchange="javascript:changeOneScore(\''.$part.'\',\''.$student.'\')" >'."\n";
1.485     albertel 3644: 	    $result.= (($status eq 'excused') ? '<option> </option><option selected="selected" value="excused">'.&mt('excused').'</option>' 
                   3645: 		: '<option selected="selected"> </option><option value="excused">'.&mt('excused').'</option>')."\n";
                   3646: 	    $result.='<option value="reset status">'.&mt('reset status').'</option>';
1.126     ng       3647: 	    $result.="</select>&nbsp;</td>\n";
1.122     ng       3648: 	} else {
                   3649: 	    $result.='<input type="hidden" name="'.
                   3650: 		'GD_'.$student.'_'.$part.'_'.$type.'_s" value="'.$score.'" />'.
                   3651: 		    "\n";
1.233     albertel 3652: 	    $result.='<input type="text" name="'.
1.122     ng       3653: 		'GD_'.$student.'_'.$part.'_'.$type.'" '.
                   3654: 		'value="'.$score.'" size="4" /></td>'."\n";
1.41      ng       3655: 	}
                   3656:     }
1.474     albertel 3657:     $result.=&Apache::loncommon::end_data_table_row();
1.41      ng       3658:     return $result;
1.38      ng       3659: }
                   3660: 
1.44      ng       3661: #--- change scores for all the students in a section/class
                   3662: #    record does not get update if unchanged
1.38      ng       3663: sub editgrades {
1.41      ng       3664:     my ($request) = @_;
                   3665: 
1.324     albertel 3666:     my $symb=&get_symb($request);
1.433     banghart 3667:     my $section_display = join (", ",&Apache::loncommon::get_env_multiple('form.section'));
1.477     albertel 3668:     my $title='<h2>'.&mt('Current Grade Status').'</h2>';
                   3669:     $title.='<h4>'.&mt('<b>Current Resource: </b>[_1]',$env{'form.probTitle'}).'</h4>'."\n";
1.433     banghart 3670:     $title.='<h4>'.&mt('<b>Section: </b>[_1]',$section_display).'</h4>'."\n";
1.126     ng       3671: 
1.477     albertel 3672:     my $result= &Apache::loncommon::start_data_table().
                   3673: 	&Apache::loncommon::start_data_table_header_row().
                   3674: 	'<th rowspan="2" valign="middle">'.&mt('No.').'</th>'.
                   3675: 	'<th rowspan="2" valign="middle">'.&nameUserString('header')."</th>\n";
1.43      ng       3676:     my %scoreptr = (
                   3677: 		    'correct'  =>'correct_by_override',
                   3678: 		    'incorrect'=>'incorrect_by_override',
                   3679: 		    'excused'  =>'excused',
                   3680: 		    'ungraded' =>'ungraded_attempted',
1.596     raeburn  3681:                     'credited' =>'credit_attempted',
1.43      ng       3682: 		    'nothing'  => '',
                   3683: 		    );
1.257     albertel 3684:     my ($classlist,undef,$fullname) = &getclasslist($env{'form.section'},'0');
1.34      ng       3685: 
1.44      ng       3686:     my (@partid);
                   3687:     my %weight = ();
1.54      albertel 3688:     my %columns = ();
1.44      ng       3689:     my ($i,$ctr,$count,$rec_update) = (0,0,0,0);
1.54      albertel 3690: 
1.582     raeburn  3691:     my $partserror;
                   3692:     my (@parts) = sort(&getpartlist($symb,\$partserror));
                   3693:     if ($partserror) {
                   3694:         return &navmap_errormsg();
                   3695:     }
1.54      albertel 3696:     my $header;
1.257     albertel 3697:     while ($ctr < $env{'form.totalparts'}) {
                   3698: 	my $partid = $env{'form.partid_'.$ctr};
1.524     raeburn  3699: 	push(@partid,$partid);
1.257     albertel 3700: 	$weight{$partid} = $env{'form.weight_'.$partid};
1.44      ng       3701: 	$ctr++;
1.54      albertel 3702:     }
1.324     albertel 3703:     my (undef,undef,$url) = &Apache::lonnet::decode_symb($symb);
1.54      albertel 3704:     foreach my $partid (@partid) {
1.478     albertel 3705: 	$header .= '<th align="center">'.&mt('Old Score').'</th>'.
                   3706: 	    '<th align="center">'.&mt('New Score').'</th>';
1.54      albertel 3707: 	$columns{$partid}=2;
                   3708: 	foreach my $stores (@parts) {
                   3709: 	    my ($part,$type) = &split_part_type($stores);
                   3710: 	    if ($part !~ m/^\Q$partid\E/) { next;}
                   3711: 	    if ($type eq 'awarded' || $type eq 'solved') { next; }
                   3712: 	    my $display=&Apache::lonnet::metadata($url,$stores.'.display');
1.551     raeburn  3713: 	    $display =~ s/\[Part: \Q$part\E\]//;
1.539     riegler  3714:             my $narrowtext = &mt('Tries');
                   3715: 	    $display =~ s/Number of Attempts/$narrowtext/;
                   3716: 	    $header .= '<th align="center">'.&mt('Old').' '.$display.'</th>'.
                   3717: 		'<th align="center">'.&mt('New').' '.$display.'</th>';
1.54      albertel 3718: 	    $columns{$partid}+=2;
                   3719: 	}
                   3720:     }
                   3721:     foreach my $partid (@partid) {
1.324     albertel 3722: 	my $display_part=&get_display_part($partid,$symb);
1.478     albertel 3723: 	$result .= '<th colspan="'.$columns{$partid}.'" align="center">'.
                   3724: 	    &mt('Part: [_1] (Weight = [_2])',$display_part,$weight{$partid}).
                   3725: 	    '</th>';
1.54      albertel 3726: 
1.44      ng       3727:     }
1.477     albertel 3728:     $result .= &Apache::loncommon::end_data_table_header_row().
                   3729: 	&Apache::loncommon::start_data_table_header_row().
                   3730: 	$header.
                   3731: 	&Apache::loncommon::end_data_table_header_row();
                   3732:     my @noupdate;
1.126     ng       3733:     my ($updateCtr,$noupdateCtr) = (1,1);
1.257     albertel 3734:     for ($i=0; $i<$env{'form.total'}; $i++) {
1.93      albertel 3735: 	my $line;
1.257     albertel 3736: 	my $user = $env{'form.ctr'.$i};
1.281     albertel 3737: 	my ($uname,$udom)=split(/:/,$user);
1.44      ng       3738: 	my %newrecord;
                   3739: 	my $updateflag = 0;
1.281     albertel 3740: 	$line .= '<td>'.&nameUserString(undef,$$fullname{$user},$uname,$udom).'</td>';
1.108     albertel 3741: 	my $usec=$classlist->{"$uname:$udom"}[5];
1.105     albertel 3742: 	if (!&canmodify($usec)) {
1.126     ng       3743: 	    my $numcols=scalar(@partid)*4+2;
1.477     albertel 3744: 	    push(@noupdate,
1.478     albertel 3745: 		 $line."<td colspan=\"$numcols\"><span class=\"LC_warning\">".
                   3746: 		 &mt('Not allowed to modify student')."</span></td></tr>");
1.105     albertel 3747: 	    next;
                   3748: 	}
1.269     raeburn  3749:         my %aggregate = ();
                   3750:         my $aggregateflag = 0;
1.281     albertel 3751: 	$user=~s/:/_/; # colon doen't work in javascript for names
1.44      ng       3752: 	foreach (@partid) {
1.257     albertel 3753: 	    my $old_aw    = $env{'form.GD_'.$user.'_'.$_.'_awarded_s'};
1.54      albertel 3754: 	    my $old_part_pcr = $old_aw/($weight{$_} ne '0' ? $weight{$_}:1);
                   3755: 	    my $old_part  = $old_aw eq '' ? '' : $old_part_pcr;
1.257     albertel 3756: 	    my $old_score = $scoreptr{$env{'form.GD_'.$user.'_'.$_.'_solved_s'}};
                   3757: 	    my $awarded   = $env{'form.GD_'.$user.'_'.$_.'_awarded'};
1.54      albertel 3758: 	    my $pcr       = $awarded/($weight{$_} ne '0' ? $weight{$_} : 1);
                   3759: 	    my $partial   = $awarded eq '' ? '' : $pcr;
1.44      ng       3760: 	    my $score;
                   3761: 	    if ($partial eq '') {
1.257     albertel 3762: 		$score = $scoreptr{$env{'form.GD_'.$user.'_'.$_.'_solved_s'}};
1.44      ng       3763: 	    } elsif ($partial > 0) {
                   3764: 		$score = 'correct_by_override';
                   3765: 	    } elsif ($partial == 0) {
                   3766: 		$score = 'incorrect_by_override';
                   3767: 	    }
1.257     albertel 3768: 	    my $dropMenu = $env{'form.GD_'.$user.'_'.$_.'_solved'};
1.125     ng       3769: 	    $score = 'excused' if (($dropMenu eq 'excused') && ($score ne 'excused'));
                   3770: 
1.292     albertel 3771: 	    $newrecord{'resource.'.$_.'.regrader'}=
                   3772: 		"$env{'user.name'}:$env{'user.domain'}";
1.125     ng       3773: 	    if ($dropMenu eq 'reset status' &&
                   3774: 		$old_score ne '') { # ignore if no previous attempts => nothing to reset
1.299     albertel 3775: 		$newrecord{'resource.'.$_.'.tries'} = '';
1.125     ng       3776: 		$newrecord{'resource.'.$_.'.solved'} = '';
                   3777: 		$newrecord{'resource.'.$_.'.award'} = '';
1.299     albertel 3778: 		$newrecord{'resource.'.$_.'.awarded'} = '';
1.125     ng       3779: 		$updateflag = 1;
1.269     raeburn  3780:                 if ($env{'form.GD_'.$user.'_'.$_.'_aggtries'} > 0) {
                   3781:                     my $aggtries = $env{'form.GD_'.$user.'_'.$_.'_aggtries'};
                   3782:                     my $totaltries = $env{'form.GD_'.$user.'_'.$_.'_totaltries'};
                   3783:                     my $solvedstatus = $env{'form.GD_'.$user.'_'.$_.'_solved_s'};
                   3784:                     &decrement_aggs($symb,$_,\%aggregate,$aggtries,$totaltries,$solvedstatus);
                   3785:                     $aggregateflag = 1;
                   3786:                 }
1.139     albertel 3787: 	    } elsif (!($old_part eq $partial && $old_score eq $score)) {
                   3788: 		$updateflag = 1;
                   3789: 		$newrecord{'resource.'.$_.'.awarded'}  = $partial if $partial ne '';
                   3790: 		$newrecord{'resource.'.$_.'.solved'}   = $score;
                   3791: 		$rec_update++;
1.125     ng       3792: 	    }
                   3793: 
1.93      albertel 3794: 	    $line .= '<td align="center">'.$old_aw.'&nbsp;</td>'.
1.44      ng       3795: 		'<td align="center">'.$awarded.
                   3796: 		($score eq 'excused' ? $score : '').'&nbsp;</td>';
1.5       albertel 3797: 
1.54      albertel 3798: 
                   3799: 	    my $partid=$_;
                   3800: 	    foreach my $stores (@parts) {
                   3801: 		my ($part,$type) = &split_part_type($stores);
                   3802: 		if ($part !~ m/^\Q$partid\E/) { next;}
                   3803: 		if ($type eq 'awarded' || $type eq 'solved') { next; }
1.257     albertel 3804: 		my $old_aw    = $env{'form.GD_'.$user.'_'.$part.'_'.$type.'_s'};
                   3805: 		my $awarded   = $env{'form.GD_'.$user.'_'.$part.'_'.$type};
1.54      albertel 3806: 		if ($awarded ne '' && $awarded ne $old_aw) {
                   3807: 		    $newrecord{'resource.'.$part.'.'.$type}= $awarded;
1.257     albertel 3808: 		    $newrecord{'resource.'.$part.'.regrader'}="$env{'user.name'}:$env{'user.domain'}";
1.54      albertel 3809: 		    $updateflag=1;
                   3810: 		}
1.93      albertel 3811: 		$line .= '<td align="center">'.$old_aw.'&nbsp;</td>'.
1.54      albertel 3812: 		    '<td align="center">'.$awarded.'&nbsp;</td>';
                   3813: 	    }
1.44      ng       3814: 	}
1.477     albertel 3815: 	$line.="\n";
1.301     albertel 3816: 
                   3817: 	my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   3818: 	my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   3819: 
1.44      ng       3820: 	if ($updateflag) {
                   3821: 	    $count++;
1.257     albertel 3822: 	    &Apache::lonnet::cstore(\%newrecord,$symb,$env{'request.course.id'},
1.89      albertel 3823: 				    $udom,$uname);
1.301     albertel 3824: 
                   3825: 	    if (&Apache::bridgetask::in_queue('gradingqueue',$symb,$cdom,
                   3826: 					      $cnum,$udom,$uname)) {
                   3827: 		# need to figure out if should be in queue.
                   3828: 		my %record =  
                   3829: 		    &Apache::lonnet::restore($symb,$env{'request.course.id'},
                   3830: 					     $udom,$uname);
                   3831: 		my $all_graded = 1;
                   3832: 		my $none_graded = 1;
                   3833: 		foreach my $part (@parts) {
                   3834: 		    if ( $record{'resource.'.$part.'.awarded'} eq '' ) {
                   3835: 			$all_graded = 0;
                   3836: 		    } else {
                   3837: 			$none_graded = 0;
                   3838: 		    }
                   3839: 		}
                   3840: 
                   3841: 		if ($all_graded || $none_graded) {
                   3842: 		    &Apache::bridgetask::remove_from_queue('gradingqueue',
                   3843: 							   $symb,$cdom,$cnum,
                   3844: 							   $udom,$uname);
                   3845: 		}
                   3846: 	    }
                   3847: 
1.477     albertel 3848: 	    $result.=&Apache::loncommon::start_data_table_row().
                   3849: 		'<td align="right">&nbsp;'.$updateCtr.'&nbsp;</td>'.$line.
                   3850: 		&Apache::loncommon::end_data_table_row();
1.126     ng       3851: 	    $updateCtr++;
1.93      albertel 3852: 	} else {
1.477     albertel 3853: 	    push(@noupdate,
                   3854: 		 '<td align="right">&nbsp;'.$noupdateCtr.'&nbsp;</td>'.$line);
1.126     ng       3855: 	    $noupdateCtr++;
1.44      ng       3856: 	}
1.269     raeburn  3857:         if ($aggregateflag) {
                   3858:             &Apache::lonnet::cinc('nohist_resourcetracker',\%aggregate,
1.301     albertel 3859: 				  $cdom,$cnum);
1.269     raeburn  3860:         }
1.93      albertel 3861:     }
1.477     albertel 3862:     if (@noupdate) {
1.126     ng       3863: #	my $numcols=(scalar(@partid)*(scalar(@parts)-1)*2)+3;
                   3864: 	my $numcols=scalar(@partid)*4+2;
1.477     albertel 3865: 	$result .= &Apache::loncommon::start_data_table_row('LC_empty_row').
1.478     albertel 3866: 	    '<td align="center" colspan="'.$numcols.'">'.
                   3867: 	    &mt('No Changes Occurred For the Students Below').
                   3868: 	    '</td>'.
1.477     albertel 3869: 	    &Apache::loncommon::end_data_table_row();
                   3870: 	foreach my $line (@noupdate) {
                   3871: 	    $result.=
                   3872: 		&Apache::loncommon::start_data_table_row().
                   3873: 		$line.
                   3874: 		&Apache::loncommon::end_data_table_row();
                   3875: 	}
1.44      ng       3876:     }
1.477     albertel 3877:     $result .= &Apache::loncommon::end_data_table().
                   3878: 	&show_grading_menu_form($symb);
1.478     albertel 3879:     my $msg = '<p><b>'.
                   3880: 	&mt('Number of records updated = [_1] for [quant,_2,student].',
                   3881: 	    $rec_update,$count).'</b><br />'.
                   3882: 	'<b>'.&mt('Total number of students = [_1]',$env{'form.total'}).
                   3883: 	'</b></p>';
1.44      ng       3884:     return $title.$msg.$result;
1.5       albertel 3885: }
1.54      albertel 3886: 
                   3887: sub split_part_type {
                   3888:     my ($partstr) = @_;
                   3889:     my ($temp,@allparts)=split(/_/,$partstr);
                   3890:     my $type=pop(@allparts);
1.439     albertel 3891:     my $part=join('_',@allparts);
1.54      albertel 3892:     return ($part,$type);
                   3893: }
                   3894: 
1.44      ng       3895: #------------- end of section for handling grading by section/class ---------
                   3896: #
                   3897: #----------------------------------------------------------------------------
                   3898: 
1.5       albertel 3899: 
1.44      ng       3900: #----------------------------------------------------------------------------
                   3901: #
                   3902: #-------------------------- Next few routines handles grading by csv upload
                   3903: #
                   3904: #--- Javascript to handle csv upload
1.27      albertel 3905: sub csvupload_javascript_reverse_associate {
1.573     bisitz   3906:     my $error1=&mt('You need to specify the username or the student/employee ID');
1.246     albertel 3907:     my $error2=&mt('You need to specify at least one grading field');
1.27      albertel 3908:   return(<<ENDPICK);
                   3909:   function verify(vf) {
                   3910:     var foundsomething=0;
                   3911:     var founduname=0;
1.243     albertel 3912:     var foundID=0;
1.27      albertel 3913:     for (i=0;i<=vf.nfields.value;i++) {
                   3914:       tw=eval('vf.f'+i+'.selectedIndex');
1.243     albertel 3915:       if (i==0 && tw!=0) { foundID=1; }
                   3916:       if (i==1 && tw!=0) { founduname=1; }
                   3917:       if (i!=0 && i!=1 && i!=2 && tw!=0) { foundsomething=1; }
1.27      albertel 3918:     }
1.246     albertel 3919:     if (founduname==0 && foundID==0) {
                   3920: 	alert('$error1');
                   3921: 	return;
1.27      albertel 3922:     }
                   3923:     if (foundsomething==0) {
1.246     albertel 3924: 	alert('$error2');
                   3925: 	return;
1.27      albertel 3926:     }
                   3927:     vf.submit();
                   3928:   }
                   3929:   function flip(vf,tf) {
                   3930:     var nw=eval('vf.f'+tf+'.selectedIndex');
                   3931:     var i;
                   3932:     for (i=0;i<=vf.nfields.value;i++) {
                   3933:       //can not pick the same destination field for both name and domain
                   3934:       if (((i ==0)||(i ==1)) && 
                   3935:           ((tf==0)||(tf==1)) && 
                   3936:           (i!=tf) &&
                   3937:           (eval('vf.f'+i+'.selectedIndex')==nw)) {
                   3938:         eval('vf.f'+i+'.selectedIndex=0;')
                   3939:       }
                   3940:     }
                   3941:   }
                   3942: ENDPICK
                   3943: }
                   3944: 
                   3945: sub csvupload_javascript_forward_associate {
1.573     bisitz   3946:     my $error1=&mt('You need to specify the username or the student/employee ID');
1.246     albertel 3947:     my $error2=&mt('You need to specify at least one grading field');
1.27      albertel 3948:   return(<<ENDPICK);
                   3949:   function verify(vf) {
                   3950:     var foundsomething=0;
                   3951:     var founduname=0;
1.243     albertel 3952:     var foundID=0;
1.27      albertel 3953:     for (i=0;i<=vf.nfields.value;i++) {
                   3954:       tw=eval('vf.f'+i+'.selectedIndex');
1.243     albertel 3955:       if (tw==1) { foundID=1; }
                   3956:       if (tw==2) { founduname=1; }
                   3957:       if (tw>3) { foundsomething=1; }
1.27      albertel 3958:     }
1.246     albertel 3959:     if (founduname==0 && foundID==0) {
                   3960: 	alert('$error1');
                   3961: 	return;
1.27      albertel 3962:     }
                   3963:     if (foundsomething==0) {
1.246     albertel 3964: 	alert('$error2');
                   3965: 	return;
1.27      albertel 3966:     }
                   3967:     vf.submit();
                   3968:   }
                   3969:   function flip(vf,tf) {
                   3970:     var nw=eval('vf.f'+tf+'.selectedIndex');
                   3971:     var i;
                   3972:     //can not pick the same destination field twice
                   3973:     for (i=0;i<=vf.nfields.value;i++) {
                   3974:       if ((i!=tf) && (eval('vf.f'+i+'.selectedIndex')==nw)) {
                   3975:         eval('vf.f'+i+'.selectedIndex=0;')
                   3976:       }
                   3977:     }
                   3978:   }
                   3979: ENDPICK
                   3980: }
                   3981: 
1.26      albertel 3982: sub csvuploadmap_header {
1.324     albertel 3983:     my ($request,$symb,$datatoken,$distotal)= @_;
1.41      ng       3984:     my $javascript;
1.257     albertel 3985:     if ($env{'form.upfile_associate'} eq 'reverse') {
1.41      ng       3986: 	$javascript=&csvupload_javascript_reverse_associate();
                   3987:     } else {
                   3988: 	$javascript=&csvupload_javascript_forward_associate();
                   3989:     }
1.45      ng       3990: 
1.324     albertel 3991:     my ($result) = &showResourceInfo($symb,$env{'form.probTitle'});
1.257     albertel 3992:     my $checked=(($env{'form.noFirstLine'})?' checked="checked"':'');
1.245     albertel 3993:     my $ignore=&mt('Ignore First Line');
1.418     albertel 3994:     $symb = &Apache::lonenc::check_encrypt($symb);
1.41      ng       3995:     $request->print(<<ENDPICK);
1.26      albertel 3996: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="gradesupload">
1.398     albertel 3997: <h3><span class="LC_info">Uploading Class Grades</span></h3>
1.45      ng       3998: $result
1.326     albertel 3999: <hr />
1.26      albertel 4000: <h3>Identify fields</h3>
                   4001: Total number of records found in file: $distotal <hr />
                   4002: Enter as many fields as you can. The system will inform you and bring you back
                   4003: to this page if the data selected is insufficient to run your class.<hr />
1.589     bisitz   4004: <input type="button" value="Reverse Association" onclick="javascript:this.form.associate.value='Reverse Association';submit(this.form);" />
1.245     albertel 4005: <label><input type="checkbox" name="noFirstLine" $checked />$ignore</label>
1.26      albertel 4006: <input type="hidden" name="associate"  value="" />
                   4007: <input type="hidden" name="phase"      value="three" />
                   4008: <input type="hidden" name="datatoken"  value="$datatoken" />
1.257     albertel 4009: <input type="hidden" name="fileupload" value="$env{'form.fileupload'}" />
                   4010: <input type="hidden" name="upfiletype" value="$env{'form.upfiletype'}" />
1.26      albertel 4011: <input type="hidden" name="upfile_associate" 
1.257     albertel 4012:                                        value="$env{'form.upfile_associate'}" />
1.26      albertel 4013: <input type="hidden" name="symb"       value="$symb" />
1.257     albertel 4014: <input type="hidden" name="saveState"  value="$env{'form.saveState'}" />
                   4015: <input type="hidden" name="probTitle"  value="$env{'form.probTitle'}" />
1.246     albertel 4016: <input type="hidden" name="command"    value="csvuploadoptions" />
1.26      albertel 4017: <hr />
                   4018: <script type="text/javascript" language="Javascript">
                   4019: $javascript
                   4020: </script>
                   4021: ENDPICK
1.118     ng       4022:     return '';
1.26      albertel 4023: 
                   4024: }
                   4025: 
                   4026: sub csvupload_fields {
1.582     raeburn  4027:     my ($symb,$errorref) = @_;
                   4028:     my (@parts) = &getpartlist($symb,$errorref);
                   4029:     if (ref($errorref)) {
                   4030:         if ($$errorref) {
                   4031:             return;
                   4032:         }
                   4033:     }
                   4034: 
1.556     weissno  4035:     my @fields=(['ID','Student/Employee ID'],
1.243     albertel 4036: 		['username','Student Username'],
                   4037: 		['domain','Student Domain']);
1.324     albertel 4038:     my (undef,undef,$url) = &Apache::lonnet::decode_symb($symb);
1.41      ng       4039:     foreach my $part (sort(@parts)) {
                   4040: 	my @datum;
                   4041: 	my $display=&Apache::lonnet::metadata($url,$part.'.display');
                   4042: 	my $name=$part;
                   4043: 	if  (!$display) { $display = $name; }
                   4044: 	@datum=($name,$display);
1.244     albertel 4045: 	if ($name=~/^stores_(.*)_awarded/) {
                   4046: 	    push(@fields,['stores_'.$1.'_points',"Points [Part: $1]"]);
                   4047: 	}
1.41      ng       4048: 	push(@fields,\@datum);
                   4049:     }
                   4050:     return (@fields);
1.26      albertel 4051: }
                   4052: 
                   4053: sub csvuploadmap_footer {
1.41      ng       4054:     my ($request,$i,$keyfields) =@_;
                   4055:     $request->print(<<ENDPICK);
1.26      albertel 4056: </table>
                   4057: <input type="hidden" name="nfields" value="$i" />
                   4058: <input type="hidden" name="keyfields" value="$keyfields" />
1.589     bisitz   4059: <input type="button" onclick="javascript:verify(this.form)" value="Assign Grades" /><br />
1.26      albertel 4060: </form>
                   4061: ENDPICK
                   4062: }
                   4063: 
1.283     albertel 4064: sub checkforfile_js {
1.539     riegler  4065:     my $alertmsg = &mt('Please use the browse button to select a file from your local directory.');
1.86      ng       4066:     my $result =<<CSVFORMJS;
                   4067: <script type="text/javascript" language="javascript">
                   4068:     function checkUpload(formname) {
                   4069: 	if (formname.upfile.value == "") {
1.539     riegler  4070: 	    alert("$alertmsg");
1.86      ng       4071: 	    return false;
                   4072: 	}
                   4073: 	formname.submit();
                   4074:     }
                   4075:     </script>
                   4076: CSVFORMJS
1.283     albertel 4077:     return $result;
                   4078: }
                   4079: 
                   4080: sub upcsvScores_form {
                   4081:     my ($request) = shift;
1.324     albertel 4082:     my ($symb)=&get_symb($request);
1.283     albertel 4083:     if (!$symb) {return '';}
                   4084:     my $result=&checkforfile_js();
1.257     albertel 4085:     $env{'form.probTitle'} = &Apache::lonnet::gettitle($symb);
1.324     albertel 4086:     my ($table) = &showResourceInfo($symb,$env{'form.probTitle'});
1.118     ng       4087:     $result.=$table;
1.326     albertel 4088:     $result.='<br /><table width="100%" border="0"><tr><td bgcolor="#777777">'."\n";
                   4089:     $result.='<table width="100%" border="0"><tr bgcolor="#e6ffff"><td>'."\n";
1.538     schulted 4090:     $result.='&nbsp;<b>'.&mt('Specify a file containing the class scores for current resource.').
                   4091: 	'</b></td></tr>'."\n";
1.596.2.4  raeburn  4092:     $result.='<tr bgcolor="#ffffe6"><td>'."\n";
1.370     www      4093:     my $upload=&mt("Upload Scores");
1.86      ng       4094:     my $upfile_select=&Apache::loncommon::upfile_select_html();
1.245     albertel 4095:     my $ignore=&mt('Ignore First Line');
1.418     albertel 4096:     $symb = &Apache::lonenc::check_encrypt($symb);
1.86      ng       4097:     $result.=<<ENDUPFORM;
1.106     albertel 4098: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="gradesupload">
1.86      ng       4099: <input type="hidden" name="symb" value="$symb" />
                   4100: <input type="hidden" name="command" value="csvuploadmap" />
1.257     albertel 4101: <input type="hidden" name="probTitle" value="$env{'form.probTitle'}" />
                   4102: <input type="hidden" name="saveState"  value="$env{'form.saveState'}" />
1.86      ng       4103: $upfile_select
1.589     bisitz   4104: <br /><input type="button" onclick="javascript:checkUpload(this.form);" value="$upload" />
1.283     albertel 4105: <label><input type="checkbox" name="noFirstLine" />$ignore</label>
1.86      ng       4106: </form>
                   4107: ENDUPFORM
1.370     www      4108:     $result.=&Apache::loncommon::help_open_topic("Course_Convert_To_CSV",
                   4109:                            &mt("How do I create a CSV file from a spreadsheet"))
                   4110:     .'</td></tr></table>'."\n";
1.86      ng       4111:     $result.='</td></tr></table><br /><br />'."\n";
1.324     albertel 4112:     $result.=&show_grading_menu_form($symb);
1.86      ng       4113:     return $result;
                   4114: }
                   4115: 
                   4116: 
1.26      albertel 4117: sub csvuploadmap {
1.41      ng       4118:     my ($request)= @_;
1.324     albertel 4119:     my ($symb)=&get_symb($request);
1.41      ng       4120:     if (!$symb) {return '';}
1.72      ng       4121: 
1.41      ng       4122:     my $datatoken;
1.257     albertel 4123:     if (!$env{'form.datatoken'}) {
1.41      ng       4124: 	$datatoken=&Apache::loncommon::upfile_store($request);
1.26      albertel 4125:     } else {
1.257     albertel 4126: 	$datatoken=$env{'form.datatoken'};
1.41      ng       4127: 	&Apache::loncommon::load_tmp_file($request);
1.26      albertel 4128:     }
1.41      ng       4129:     my @records=&Apache::loncommon::upfile_record_sep();
1.257     albertel 4130:     if ($env{'form.noFirstLine'}) { shift(@records); }
1.324     albertel 4131:     &csvuploadmap_header($request,$symb,$datatoken,$#records+1);
1.41      ng       4132:     my ($i,$keyfields);
                   4133:     if (@records) {
1.582     raeburn  4134:         my $fieldserror;
                   4135: 	my @fields=&csvupload_fields($symb,\$fieldserror);
                   4136:         if ($fieldserror) {
                   4137:             $request->print(&navmap_errormsg());
                   4138:             return;
                   4139:         }
1.257     albertel 4140: 	if ($env{'form.upfile_associate'} eq 'reverse') {	
1.41      ng       4141: 	    &Apache::loncommon::csv_print_samples($request,\@records);
                   4142: 	    $i=&Apache::loncommon::csv_print_select_table($request,\@records,
                   4143: 							  \@fields);
                   4144: 	    foreach (@fields) { $keyfields.=$_->[0].','; }
                   4145: 	    chop($keyfields);
                   4146: 	} else {
                   4147: 	    unshift(@fields,['none','']);
                   4148: 	    $i=&Apache::loncommon::csv_samples_select_table($request,\@records,
                   4149: 							    \@fields);
1.311     banghart 4150:             foreach my $rec (@records) {
                   4151:                 my %temp = &Apache::loncommon::record_sep($rec);
                   4152:                 if (%temp) {
                   4153:                     $keyfields=join(',',sort(keys(%temp)));
                   4154:                     last;
                   4155:                 }
                   4156:             }
1.41      ng       4157: 	}
                   4158:     }
                   4159:     &csvuploadmap_footer($request,$i,$keyfields);
1.324     albertel 4160:     $request->print(&show_grading_menu_form($symb));
1.72      ng       4161: 
1.41      ng       4162:     return '';
1.27      albertel 4163: }
                   4164: 
1.246     albertel 4165: sub csvuploadoptions {
1.41      ng       4166:     my ($request)= @_;
1.324     albertel 4167:     my ($symb)=&get_symb($request);
1.257     albertel 4168:     my $checked=(($env{'form.noFirstLine'})?'1':'0');
1.246     albertel 4169:     my $ignore=&mt('Ignore First Line');
                   4170:     $request->print(<<ENDPICK);
                   4171: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="gradesupload">
1.398     albertel 4172: <h3><span class="LC_info">Uploading Class Grade Options</span></h3>
1.246     albertel 4173: <input type="hidden" name="command"    value="csvuploadassign" />
1.302     albertel 4174: <!--
1.246     albertel 4175: <p>
                   4176: <label>
                   4177:    <input type="checkbox" name="show_full_results" />
                   4178:    Show a table of all changes
                   4179: </label>
                   4180: </p>
1.302     albertel 4181: -->
1.246     albertel 4182: <p>
                   4183: <label>
                   4184:    <input type="checkbox" name="overwite_scores" checked="checked" />
                   4185:    Overwrite any existing score
                   4186: </label>
                   4187: </p>
                   4188: ENDPICK
                   4189:     my %fields=&get_fields();
                   4190:     if (!defined($fields{'domain'})) {
1.257     albertel 4191: 	my $domform = &Apache::loncommon::select_dom_form($env{'request.role.domain'},'default_domain');
1.246     albertel 4192: 	$request->print("\n<p> Users are in domain: ".$domform."</p>\n");
                   4193:     }
1.257     albertel 4194:     foreach my $key (sort(keys(%env))) {
1.246     albertel 4195: 	if ($key !~ /^form\.(.*)$/) { next; }
                   4196: 	my $cleankey=$1;
                   4197: 	if ($cleankey eq 'command') { next; }
                   4198: 	$request->print('<input type="hidden" name="'.$cleankey.
1.257     albertel 4199: 			'"  value="'.$env{$key}.'" />'."\n");
1.246     albertel 4200:     }
                   4201:     # FIXME do a check for any duplicated user ids...
                   4202:     # FIXME do a check for any invalid user ids?...
1.290     albertel 4203:     $request->print('<input type="submit" value="Assign Grades" /><br />
                   4204: <hr /></form>'."\n");
1.324     albertel 4205:     $request->print(&show_grading_menu_form($symb));
1.246     albertel 4206:     return '';
                   4207: }
                   4208: 
                   4209: sub get_fields {
                   4210:     my %fields;
1.257     albertel 4211:     my @keyfields = split(/\,/,$env{'form.keyfields'});
                   4212:     for (my $i=0; $i<=$env{'form.nfields'}; $i++) {
                   4213: 	if ($env{'form.upfile_associate'} eq 'reverse') {
                   4214: 	    if ($env{'form.f'.$i} ne 'none') {
                   4215: 		$fields{$keyfields[$i]}=$env{'form.f'.$i};
1.41      ng       4216: 	    }
                   4217: 	} else {
1.257     albertel 4218: 	    if ($env{'form.f'.$i} ne 'none') {
                   4219: 		$fields{$env{'form.f'.$i}}=$keyfields[$i];
1.41      ng       4220: 	    }
                   4221: 	}
1.27      albertel 4222:     }
1.246     albertel 4223:     return %fields;
                   4224: }
                   4225: 
                   4226: sub csvuploadassign {
                   4227:     my ($request)= @_;
1.324     albertel 4228:     my ($symb)=&get_symb($request);
1.246     albertel 4229:     if (!$symb) {return '';}
1.345     bowersj2 4230:     my $error_msg = '';
1.246     albertel 4231:     &Apache::loncommon::load_tmp_file($request);
                   4232:     my @gradedata = &Apache::loncommon::upfile_record_sep();
1.257     albertel 4233:     if ($env{'form.noFirstLine'}) { shift(@gradedata); }
1.246     albertel 4234:     my %fields=&get_fields();
1.41      ng       4235:     $request->print('<h3>Assigning Grades</h3>');
1.257     albertel 4236:     my $courseid=$env{'request.course.id'};
1.97      albertel 4237:     my ($classlist) = &getclasslist('all',0);
1.106     albertel 4238:     my @notallowed;
1.41      ng       4239:     my @skipped;
1.596.2.4  raeburn  4240:     my @warnings;
1.41      ng       4241:     my $countdone=0;
                   4242:     foreach my $grade (@gradedata) {
                   4243: 	my %entries=&Apache::loncommon::record_sep($grade);
1.246     albertel 4244: 	my $domain;
                   4245: 	if ($entries{$fields{'domain'}}) {
                   4246: 	    $domain=$entries{$fields{'domain'}};
                   4247: 	} else {
1.257     albertel 4248: 	    $domain=$env{'form.default_domain'};
1.246     albertel 4249: 	}
1.243     albertel 4250: 	$domain=~s/\s//g;
1.41      ng       4251: 	my $username=$entries{$fields{'username'}};
1.160     albertel 4252: 	$username=~s/\s//g;
1.243     albertel 4253: 	if (!$username) {
                   4254: 	    my $id=$entries{$fields{'ID'}};
1.247     albertel 4255: 	    $id=~s/\s//g;
1.243     albertel 4256: 	    my %ids=&Apache::lonnet::idget($domain,$id);
                   4257: 	    $username=$ids{$id};
                   4258: 	}
1.41      ng       4259: 	if (!exists($$classlist{"$username:$domain"})) {
1.247     albertel 4260: 	    my $id=$entries{$fields{'ID'}};
                   4261: 	    $id=~s/\s//g;
                   4262: 	    if ($id) {
                   4263: 		push(@skipped,"$id:$domain");
                   4264: 	    } else {
                   4265: 		push(@skipped,"$username:$domain");
                   4266: 	    }
1.41      ng       4267: 	    next;
                   4268: 	}
1.108     albertel 4269: 	my $usec=$classlist->{"$username:$domain"}[5];
1.106     albertel 4270: 	if (!&canmodify($usec)) {
                   4271: 	    push(@notallowed,"$username:$domain");
                   4272: 	    next;
                   4273: 	}
1.244     albertel 4274: 	my %points;
1.41      ng       4275: 	my %grades;
                   4276: 	foreach my $dest (keys(%fields)) {
1.244     albertel 4277: 	    if ($dest eq 'ID' || $dest eq 'username' ||
                   4278: 		$dest eq 'domain') { next; }
                   4279: 	    if ($entries{$fields{$dest}} =~ /^\s*$/) { next; }
                   4280: 	    if ($dest=~/stores_(.*)_points/) {
                   4281: 		my $part=$1;
                   4282: 		my $wgt =&Apache::lonnet::EXT('resource.'.$part.'.weight',
                   4283: 					      $symb,$domain,$username);
1.345     bowersj2 4284:                 if ($wgt) {
                   4285:                     $entries{$fields{$dest}}=~s/\s//g;
                   4286:                     my $pcr=$entries{$fields{$dest}} / $wgt;
1.463     albertel 4287:                     my $award=($pcr == 0) ? 'incorrect_by_override'
                   4288:                                           : 'correct_by_override';
1.596.2.4  raeburn  4289:                     if ($pcr>1) {
                   4290:                         push(@warnings,&mt("[_1]: point value larger than weight","$username:$domain"));
                   4291:                     }
1.345     bowersj2 4292:                     $grades{"resource.$part.awarded"}=$pcr;
                   4293:                     $grades{"resource.$part.solved"}=$award;
                   4294:                     $points{$part}=1;
                   4295:                 } else {
                   4296:                     $error_msg = "<br />" .
                   4297:                         &mt("Some point values were assigned"
                   4298:                             ." for problems with a weight "
                   4299:                             ."of zero. These values were "
                   4300:                             ."ignored.");
                   4301:                 }
1.244     albertel 4302: 	    } else {
                   4303: 		if ($dest=~/stores_(.*)_awarded/) { if ($points{$1}) {next;} }
                   4304: 		if ($dest=~/stores_(.*)_solved/)  { if ($points{$1}) {next;} }
                   4305: 		my $store_key=$dest;
                   4306: 		$store_key=~s/^stores/resource/;
                   4307: 		$store_key=~s/_/\./g;
                   4308: 		$grades{$store_key}=$entries{$fields{$dest}};
                   4309: 	    }
1.41      ng       4310: 	}
1.508     www      4311: 	if (! %grades) { 
                   4312:            push(@skipped,&mt("[_1]: no data to save","$username:$domain")); 
                   4313:         } else {
                   4314: 	   $grades{"resource.regrader"}="$env{'user.name'}:$env{'user.domain'}";
                   4315: 	   my $result=&Apache::lonnet::cstore(\%grades,$symb,
1.302     albertel 4316: 					   $env{'request.course.id'},
                   4317: 					   $domain,$username);
1.508     www      4318: 	   if ($result eq 'ok') {
                   4319: 	      $request->print('.');
1.596.2.4  raeburn  4320: # Remove from grading queue
                   4321:               &Apache::bridgetask::remove_from_queue('gradingqueue',$symb,
                   4322:                                              $env{'course.'.$env{'request.course.id'}.'.domain'},
                   4323:                                              $env{'course.'.$env{'request.course.id'}.'.num'},
                   4324:                                              $domain,$username);
1.508     www      4325: 	   } else {
                   4326: 	      $request->print("<p><span class=\"LC_error\">".
                   4327:                               &mt("Failed to save data for student [_1]. Message when trying to save was: [_2]",
                   4328:                                   "$username:$domain",$result)."</span></p>");
                   4329: 	   }
                   4330: 	   $request->rflush();
                   4331: 	   $countdone++;
                   4332:         }
1.41      ng       4333:     }
1.570     www      4334:     $request->print('<br />'.&Apache::lonhtmlcommon::confirm_success(&mt("Saved scores for [quant,_1,student]",$countdone),$countdone==0));
1.596.2.4  raeburn  4335:     if (@warnings) {
                   4336:         $request->print('<br />'.&Apache::lonhtmlcommon::confirm_success(&mt('Warnings generated for the following saved scores:'),1).'<br />');
                   4337:         $request->print(join(', ',@warnings));
                   4338:     }
1.41      ng       4339:     if (@skipped) {
1.571     www      4340: 	$request->print('<br />'.&Apache::lonhtmlcommon::confirm_success(&mt('No scores stored for the following username(s):'),1).'<br />');
                   4341:         $request->print(join(', ',@skipped));
1.106     albertel 4342:     }
                   4343:     if (@notallowed) {
1.571     www      4344: 	$request->print('<br />'.&Apache::lonhtmlcommon::confirm_success(&mt('Modification of scores not allowed for the following username(s):'),1).'<br />');
                   4345: 	$request->print(join(', ',@notallowed));
1.41      ng       4346:     }
1.106     albertel 4347:     $request->print("<br />\n");
1.324     albertel 4348:     $request->print(&show_grading_menu_form($symb));
1.345     bowersj2 4349:     return $error_msg;
1.26      albertel 4350: }
1.44      ng       4351: #------------- end of section for handling csv file upload ---------
                   4352: #
                   4353: #-------------------------------------------------------------------
                   4354: #
1.122     ng       4355: #-------------- Next few routines handle grading by page/sequence
1.72      ng       4356: #
                   4357: #--- Select a page/sequence and a student to grade
1.68      ng       4358: sub pickStudentPage {
                   4359:     my ($request) = shift;
                   4360: 
1.539     riegler  4361:     my $alertmsg = &mt('Please select the student you wish to grade.');
1.68      ng       4362:     $request->print(<<LISTJAVASCRIPT);
                   4363: <script type="text/javascript" language="javascript">
                   4364: 
                   4365: function checkPickOne(formname) {
1.76      ng       4366:     if (radioSelection(formname.student) == null) {
1.539     riegler  4367: 	alert("$alertmsg");
1.68      ng       4368: 	return;
                   4369:     }
1.125     ng       4370:     ptr = pullDownSelection(formname.selectpage);
                   4371:     formname.page.value = formname["page"+ptr].value;
                   4372:     formname.title.value = formname["title"+ptr].value;
1.68      ng       4373:     formname.submit();
                   4374: }
                   4375: 
                   4376: </script>
                   4377: LISTJAVASCRIPT
1.118     ng       4378:     &commonJSfunctions($request);
1.324     albertel 4379:     my ($symb) = &get_symb($request);
1.257     albertel 4380:     my $cdom      = $env{"course.$env{'request.course.id'}.domain"};
                   4381:     my $cnum      = $env{"course.$env{'request.course.id'}.num"};
                   4382:     my $getsec    = $env{'form.section'} eq '' ? 'all' : $env{'form.section'};
1.68      ng       4383: 
1.398     albertel 4384:     my $result='<h3><span class="LC_info">&nbsp;'.
1.485     albertel 4385: 	&mt('Manual Grading by Page or Sequence').'</span></h3>';
1.68      ng       4386: 
1.80      ng       4387:     $result.='<form action="/adm/grades" method="post" name="displayPage">'."\n";
1.582     raeburn  4388:     my $map_error;
                   4389:     my ($titles,$symbx) = &getSymbMap($map_error);
                   4390:     if ($map_error) {
                   4391:         $request->print(&navmap_errormsg());
                   4392:         return; 
                   4393:     }
1.137     albertel 4394:     my ($curpage) =&Apache::lonnet::decode_symb($symb); 
                   4395: #    my ($curpage,$mapId) =&Apache::lonnet::decode_symb($symb); 
                   4396: #    my $type=($curpage =~ /\.(page|sequence)/);
1.485     albertel 4397:     my $select = '<select name="selectpage">'."\n";
1.70      ng       4398:     my $ctr=0;
1.68      ng       4399:     foreach (@$titles) {
                   4400: 	my ($minder,$showtitle) = ($_ =~ /(\d+)\.(.*)/);
1.485     albertel 4401: 	$select.='<option value="'.$ctr.'" '.
1.401     albertel 4402: 	    ($$symbx{$_} =~ /$curpage$/ ? 'selected="selected"' : '').
1.71      ng       4403: 	    '>'.$showtitle.'</option>'."\n";
1.70      ng       4404: 	$ctr++;
1.68      ng       4405:     }
1.485     albertel 4406:     $select.= '</select>';
1.539     riegler  4407:     $result.='&nbsp;<b>'.&mt('Problems from').':</b> '.$select."<br />\n";
1.485     albertel 4408: 
1.70      ng       4409:     $ctr=0;
                   4410:     foreach (@$titles) {
                   4411: 	my ($minder,$showtitle) = ($_ =~ /(\d+)\.(.*)/);
                   4412: 	$result.='<input type="hidden" name="page'.$ctr.'" value="'.$$symbx{$_}.'" />'."\n";
                   4413: 	$result.='<input type="hidden" name="title'.$ctr.'" value="'.$showtitle.'" />'."\n";
                   4414: 	$ctr++;
                   4415:     }
1.72      ng       4416:     $result.='<input type="hidden" name="page" />'."\n".
                   4417: 	'<input type="hidden" name="title" />'."\n";
1.68      ng       4418: 
1.485     albertel 4419:     my $options =
                   4420: 	'<label><input type="radio" name="vProb" value="no" checked="checked" /> '.&mt('no').' </label>'."\n".
                   4421: 	'<label><input type="radio" name="vProb" value="yes" /> '.&mt('yes').' </label>'."<br />\n";
1.539     riegler  4422:     $result.='&nbsp;<b>'.&mt('View Problem Text').': </b>'.$options;
1.485     albertel 4423: 
                   4424:     $options =
                   4425: 	'<label><input type="radio" name="lastSub" value="none" /> '.&mt('none').' </label>'."\n".
                   4426: 	'<label><input type="radio" name="lastSub" value="datesub" checked="checked" /> '.&mt('by dates and submissions').'</label>'."\n".
                   4427: 	'<label><input type="radio" name="lastSub" value="all" /> '.&mt('all details').' </label>'."\n";
1.539     riegler  4428:     $result.='&nbsp;<b>'.&mt('Submissions').': </b>'.$options;
1.432     banghart 4429:     
                   4430:     $result.=&build_section_inputs();
1.442     banghart 4431:     my $stu_status = join(':',&Apache::loncommon::get_env_multiple('form.Status'));
                   4432:     $result.='<input type="hidden" name="Status"  value="'.$stu_status.'" />'."\n".
1.72      ng       4433: 	'<input type="hidden" name="command" value="displayPage" />'."\n".
1.418     albertel 4434: 	'<input type="hidden" name="symb"    value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
1.257     albertel 4435: 	'<input type="hidden" name="saveState" value="'.$env{'form.saveState'}.'" />'."<br />\n";
1.72      ng       4436: 
1.539     riegler  4437:     $result.='&nbsp;<b>'.&mt('Use CODE').': </b> <input type="text" name="CODE" value="" /> <br />'."\n";
1.382     albertel 4438: 
1.80      ng       4439:     $result.='&nbsp;<input type="button" '.
1.589     bisitz   4440:              'onclick="javascript:checkPickOne(this.form);" value="'.&mt('Next').' &rarr;" /><br />'."\n";
1.72      ng       4441: 
1.68      ng       4442:     $request->print($result);
                   4443: 
1.485     albertel 4444:     my $studentTable.='&nbsp;<b>'.&mt('Select a student you wish to grade and then click on the Next button.').'</b><br />'.
1.484     albertel 4445: 	&Apache::loncommon::start_data_table().
                   4446: 	&Apache::loncommon::start_data_table_header_row().
1.485     albertel 4447: 	'<th align="right">&nbsp;'.&mt('No.').'</th>'.
1.484     albertel 4448: 	'<th>'.&nameUserString('header').'</th>'.
1.485     albertel 4449: 	'<th align="right">&nbsp;'.&mt('No.').'</th>'.
1.484     albertel 4450: 	'<th>'.&nameUserString('header').'</th>'.
                   4451: 	&Apache::loncommon::end_data_table_header_row();
1.68      ng       4452:  
1.76      ng       4453:     my (undef,undef,$fullname) = &getclasslist($getsec,'1');
1.68      ng       4454:     my $ptr = 1;
1.294     albertel 4455:     foreach my $student (sort 
                   4456: 			 {
                   4457: 			     if (lc($$fullname{$a}) ne lc($$fullname{$b})) {
                   4458: 				 return (lc($$fullname{$a}) cmp lc($$fullname{$b}));
                   4459: 			     }
                   4460: 			     return $a cmp $b;
                   4461: 			 } (keys(%$fullname))) {
1.68      ng       4462: 	my ($uname,$udom) = split(/:/,$student);
1.484     albertel 4463: 	$studentTable.=($ptr%2==1 ? &Apache::loncommon::start_data_table_row()
                   4464:                                   : '</td>');
1.126     ng       4465: 	$studentTable.='<td align="right">'.$ptr.'&nbsp;</td>';
1.288     albertel 4466: 	$studentTable.='<td>&nbsp;<label><input type="radio" name="student" value="'.$student.'" /> '
                   4467: 	    .&nameUserString(undef,$$fullname{$student},$uname,$udom)."</label>\n";
1.484     albertel 4468: 	$studentTable.=
                   4469: 	    ($ptr%2 == 0 ? '</td>'.&Apache::loncommon::end_data_table_row() 
                   4470:                          : '');
1.68      ng       4471: 	$ptr++;
                   4472:     }
1.484     albertel 4473:     if ($ptr%2 == 0) {
                   4474: 	$studentTable.='</td><td>&nbsp;</td><td>&nbsp;</td>'.
                   4475: 	    &Apache::loncommon::end_data_table_row();
                   4476:     }
                   4477:     $studentTable.=&Apache::loncommon::end_data_table()."\n";
1.126     ng       4478:     $studentTable.='<input type="button" '.
1.589     bisitz   4479:                    'onclick="javascript:checkPickOne(this.form);" value="'.&mt('Next').' &rarr;" /></form>'."\n";
1.68      ng       4480: 
1.324     albertel 4481:     $studentTable.=&show_grading_menu_form($symb);
1.68      ng       4482:     $request->print($studentTable);
                   4483: 
                   4484:     return '';
                   4485: }
                   4486: 
                   4487: sub getSymbMap {
1.582     raeburn  4488:     my ($map_error) = @_;
1.132     bowersj2 4489:     my $navmap = Apache::lonnavmaps::navmap->new();
1.582     raeburn  4490:     unless (ref($navmap)) {
                   4491:         if (ref($map_error)) {
                   4492:             $$map_error = 'navmap';
                   4493:         }
                   4494:         return;
                   4495:     }
1.68      ng       4496:     my %symbx = ();
                   4497:     my @titles = ();
1.117     bowersj2 4498:     my $minder = 0;
                   4499: 
                   4500:     # Gather every sequence that has problems.
1.240     albertel 4501:     my @sequences = $navmap->retrieveResources(undef, sub { shift->is_map(); },
                   4502: 					       1,0,1);
1.117     bowersj2 4503:     for my $sequence ($navmap->getById('0.0'), @sequences) {
1.241     albertel 4504: 	if ($navmap->hasResource($sequence, sub { shift->is_problem(); }, 0) ) {
1.381     albertel 4505: 	    my $title = $minder.'.'.
                   4506: 		&HTML::Entities::encode($sequence->compTitle(),'"\'&');
                   4507: 	    push(@titles, $title); # minder in case two titles are identical
                   4508: 	    $symbx{$title} = &HTML::Entities::encode($sequence->symb(),'"\'&');
1.117     bowersj2 4509: 	    $minder++;
1.241     albertel 4510: 	}
1.68      ng       4511:     }
                   4512:     return \@titles,\%symbx;
                   4513: }
                   4514: 
1.72      ng       4515: #
                   4516: #--- Displays a page/sequence w/wo problems, w/wo submissions
1.68      ng       4517: sub displayPage {
                   4518:     my ($request) = shift;
                   4519: 
1.324     albertel 4520:     my ($symb) = &get_symb($request);
1.257     albertel 4521:     my $cdom      = $env{"course.$env{'request.course.id'}.domain"};
                   4522:     my $cnum      = $env{"course.$env{'request.course.id'}.num"};
                   4523:     my $getsec    = $env{'form.section'} eq '' ? 'all' : $env{'form.section'};
                   4524:     my $pageTitle = $env{'form.page'};
1.103     albertel 4525:     my ($classlist,undef,$fullname) = &getclasslist($getsec,'1');
1.257     albertel 4526:     my ($uname,$udom) = split(/:/,$env{'form.student'});
                   4527:     my $usec=$classlist->{$env{'form.student'}}[5];
1.168     albertel 4528: 
                   4529:     #need to make sure we have the correct data for later EXT calls, 
                   4530:     #thus invalidate the cache
                   4531:     &Apache::lonnet::devalidatecourseresdata(
1.257     albertel 4532:                  $env{'course.'.$env{'request.course.id'}.'.num'},
                   4533:                  $env{'course.'.$env{'request.course.id'}.'.domain'});
1.168     albertel 4534:     &Apache::lonnet::clear_EXT_cache_status();
                   4535: 
1.103     albertel 4536:     if (!&canview($usec)) {
1.485     albertel 4537: 	$request->print('<span class="LC_warning">'.&mt('Unable to view requested student. ([_1])',$env{'form.student'}).'</span>');
1.324     albertel 4538: 	$request->print(&show_grading_menu_form($symb));
1.103     albertel 4539: 	return;
                   4540:     }
1.398     albertel 4541:     my $result='<h3><span class="LC_info">&nbsp;'.$env{'form.title'}.'</span></h3>';
1.485     albertel 4542:     $result.='<h3>&nbsp;'.&mt('Student: [_1]',&nameUserString(undef,$$fullname{$env{'form.student'}},$uname,$udom)).
1.129     ng       4543: 	'</h3>'."\n";
1.500     albertel 4544:     $env{'form.CODE'} = uc($env{'form.CODE'});
1.501     foxr     4545:     if (&Apache::lonnet::validCODE(uc($env{'form.CODE'}))) {
1.485     albertel 4546: 	$result.='<h3>&nbsp;'.&mt('CODE: [_1]',$env{'form.CODE'}).'</h3>'."\n";
1.382     albertel 4547:     } else {
                   4548: 	delete($env{'form.CODE'});
                   4549:     }
1.71      ng       4550:     &sub_page_js($request);
                   4551:     $request->print($result);
                   4552: 
1.132     bowersj2 4553:     my $navmap = Apache::lonnavmaps::navmap->new();
1.582     raeburn  4554:     unless (ref($navmap)) {
                   4555:         $request->print(&navmap_errormsg());
                   4556:         $request->print(&show_grading_menu_form($symb));
                   4557:         return;
                   4558:     }
1.257     albertel 4559:     my ($mapUrl, $id, $resUrl)=&Apache::lonnet::decode_symb($env{'form.page'});
1.68      ng       4560:     my $map = $navmap->getResourceByUrl($resUrl); # add to navmaps
1.288     albertel 4561:     if (!$map) {
1.485     albertel 4562: 	$request->print('<span class="LC_warning">'.&mt('Unable to view requested sequence. ([_1])',$resUrl).'</span>');
1.324     albertel 4563: 	$request->print(&show_grading_menu_form($symb));
1.288     albertel 4564: 	return; 
                   4565:     }
1.68      ng       4566:     my $iterator = $navmap->getIterator($map->map_start(),
                   4567: 					$map->map_finish());
                   4568: 
1.71      ng       4569:     my $studentTable='<form action="/adm/grades" method="post" name="gradePage">'."\n".
1.72      ng       4570: 	'<input type="hidden" name="command" value="gradeByPage" />'."\n".
1.257     albertel 4571: 	'<input type="hidden" name="fullname" value="'.$$fullname{$env{'form.student'}}.'" />'."\n".
                   4572: 	'<input type="hidden" name="student" value="'.$env{'form.student'}.'" />'."\n".
1.72      ng       4573: 	'<input type="hidden" name="page"    value="'.$pageTitle.'" />'."\n".
1.257     albertel 4574: 	'<input type="hidden" name="title"   value="'.$env{'form.title'}.'" />'."\n".
1.418     albertel 4575: 	'<input type="hidden" name="symb"    value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
1.125     ng       4576: 	'<input type="hidden" name="overRideScore" value="no" />'."\n".
1.257     albertel 4577: 	'<input type="hidden" name="saveState" value="'.$env{'form.saveState'}.'" />'."\n";
1.71      ng       4578: 
1.382     albertel 4579:     if (defined($env{'form.CODE'})) {
                   4580: 	$studentTable.=
                   4581: 	    '<input type="hidden" name="CODE" value="'.$env{'form.CODE'}.'" />'."\n";
                   4582:     }
1.381     albertel 4583:     my $checkIcon = '<img alt="'.&mt('Check Mark').
1.485     albertel 4584: 	'" src="'.&Apache::loncommon::lonhttpdurl($request->dir_config('lonIconsURL').'/check.gif').'" height="16" border="0" />';
1.71      ng       4585: 
1.594     bisitz   4586:     $studentTable.='&nbsp;<span class="LC_info">'.
                   4587:         &mt('Problems graded correct by the computer are marked with a [_1] symbol.',$checkIcon).
                   4588:         '</span>'."\n".
1.484     albertel 4589: 	&Apache::loncommon::start_data_table().
                   4590: 	&Apache::loncommon::start_data_table_header_row().
                   4591: 	'<th align="center">&nbsp;Prob.&nbsp;</th>'.
1.485     albertel 4592: 	'<th>&nbsp;'.($env{'form.vProb'} eq 'no' ? &mt('Title') : &mt('Problem Text')).'/'.&mt('Grade').'</th>'.
1.484     albertel 4593: 	&Apache::loncommon::end_data_table_header_row();
1.71      ng       4594: 
1.329     albertel 4595:     &Apache::lonxml::clear_problem_counter();
1.196     albertel 4596:     my ($depth,$question,$prob) = (1,1,1);
1.68      ng       4597:     $iterator->next(); # skip the first BEGIN_MAP
                   4598:     my $curRes = $iterator->next(); # for "current resource"
1.101     albertel 4599:     while ($depth > 0) {
1.68      ng       4600:         if($curRes == $iterator->BEGIN_MAP) { $depth++; }
1.100     bowersj2 4601:         if($curRes == $iterator->END_MAP) { $depth--; }
1.68      ng       4602: 
1.385     albertel 4603:         if (ref($curRes) && $curRes->is_problem()) {
1.91      albertel 4604: 	    my $parts = $curRes->parts();
1.68      ng       4605:             my $title = $curRes->compTitle();
1.71      ng       4606: 	    my $symbx = $curRes->symb();
1.484     albertel 4607: 	    $studentTable.=
                   4608: 		&Apache::loncommon::start_data_table_row().
                   4609: 		'<td align="center" valign="top" >'.$prob.
1.485     albertel 4610: 		(scalar(@{$parts}) == 1 ? '' 
1.596.2.2  raeburn  4611: 		                        : '<br />('.&mt('[_1]parts)',
                   4612: 							scalar(@{$parts}).'&nbsp;')
1.485     albertel 4613: 		 ).
                   4614: 		 '</td>';
1.71      ng       4615: 	    $studentTable.='<td valign="top">';
1.382     albertel 4616: 	    my %form = ('CODE' => $env{'form.CODE'},);
1.257     albertel 4617: 	    if ($env{'form.vProb'} eq 'yes' ) {
1.144     albertel 4618: 		$studentTable.=&show_problem($request,$symbx,$uname,$udom,1,
1.383     albertel 4619: 					     undef,'both',\%form);
1.71      ng       4620: 	    } else {
1.382     albertel 4621: 		my $companswer = &Apache::loncommon::get_student_answers($symbx,$uname,$udom,$env{'request.course.id'},%form);
1.80      ng       4622: 		$companswer =~ s|<form(.*?)>||g;
                   4623: 		$companswer =~ s|</form>||g;
1.71      ng       4624: #		while ($companswer =~ /(<a href\=\"javascript:newWindow.*?Script Vars<\/a>)/s) { #<a href="javascript:newWindow</a>
1.116     ng       4625: #		    $companswer =~ s/$1/ /ms;
1.326     albertel 4626: #		    $request->print('match='.$1."<br />\n");
1.71      ng       4627: #		}
1.116     ng       4628: #		$companswer =~ s|<table border=\"1\">|<table border=\"0\">|g;
1.539     riegler  4629: 		$studentTable.='&nbsp;<b>'.$title.'</b>&nbsp;<br />&nbsp;<b>'.&mt('Correct answer').':</b><br />'.$companswer;
1.71      ng       4630: 	    }
                   4631: 
1.257     albertel 4632: 	    my %record = &Apache::lonnet::restore($symbx,$env{'request.course.id'},$udom,$uname);
1.125     ng       4633: 
1.257     albertel 4634: 	    if ($env{'form.lastSub'} eq 'datesub') {
1.71      ng       4635: 		if ($record{'version'} eq '') {
1.485     albertel 4636: 		    $studentTable.='<br />&nbsp;<span class="LC_warning">'.&mt('No recorded submission for this problem.').'</span><br />';
1.71      ng       4637: 		} else {
1.116     ng       4638: 		    my %responseType = ();
                   4639: 		    foreach my $partid (@{$parts}) {
1.147     albertel 4640: 			my @responseIds =$curRes->responseIds($partid);
                   4641: 			my @responseType =$curRes->responseType($partid);
                   4642: 			my %responseIds;
                   4643: 			for (my $i=0;$i<=$#responseIds;$i++) {
                   4644: 			    $responseIds{$responseIds[$i]}=$responseType[$i];
                   4645: 			}
                   4646: 			$responseType{$partid} = \%responseIds;
1.116     ng       4647: 		    }
1.148     albertel 4648: 		    $studentTable.= &displaySubByDates($symbx,\%record,$parts,\%responseType,$checkIcon,$uname,$udom);
1.147     albertel 4649: 
1.71      ng       4650: 		}
1.257     albertel 4651: 	    } elsif ($env{'form.lastSub'} eq 'all') {
                   4652: 		my $last = ($env{'form.lastSub'} eq 'last' ? 'last' : '');
1.71      ng       4653: 		$studentTable.=&Apache::loncommon::get_previous_attempt($symbx,$uname,$udom,
1.257     albertel 4654: 									$env{'request.course.id'},
1.71      ng       4655: 									'','.submission');
                   4656:  
                   4657: 	    }
1.103     albertel 4658: 	    if (&canmodify($usec)) {
1.585     bisitz   4659:             $studentTable.=&gradeBox_start();
1.103     albertel 4660: 		foreach my $partid (@{$parts}) {
                   4661: 		    $studentTable.=&gradeBox($request,$symbx,$uname,$udom,$question,$partid,\%record);
                   4662: 		    $studentTable.='<input type="hidden" name="q_'.$question.'" value="'.$partid.'" />'."\n";
                   4663: 		    $question++;
                   4664: 		}
1.585     bisitz   4665:             $studentTable.=&gradeBox_end();
1.196     albertel 4666: 		$prob++;
1.71      ng       4667: 	    }
                   4668: 	    $studentTable.='</td></tr>';
1.68      ng       4669: 
1.103     albertel 4670: 	}
1.68      ng       4671:         $curRes = $iterator->next();
                   4672:     }
                   4673: 
1.589     bisitz   4674:     $studentTable.=
                   4675:         '</table>'."\n".
                   4676:         '<input type="button" value="'.&mt('Save').'" '.
                   4677:         'onclick="javascript:checkSubmitPage(this.form,'.$question.');" />'.
                   4678:         '</form>'."\n";
1.324     albertel 4679:     $studentTable.=&show_grading_menu_form($symb);
1.71      ng       4680:     $request->print($studentTable);
                   4681: 
                   4682:     return '';
1.119     ng       4683: }
                   4684: 
                   4685: sub displaySubByDates {
1.148     albertel 4686:     my ($symb,$record,$parts,$responseType,$checkIcon,$uname,$udom) = @_;
1.224     albertel 4687:     my $isCODE=0;
1.335     albertel 4688:     my $isTask = ($symb =~/\.task$/);
1.224     albertel 4689:     if (exists($record->{'resource.CODE'})) { $isCODE=1; }
1.467     albertel 4690:     my $studentTable=&Apache::loncommon::start_data_table().
                   4691: 	&Apache::loncommon::start_data_table_header_row().
                   4692: 	'<th>'.&mt('Date/Time').'</th>'.
                   4693: 	($isCODE?'<th>'.&mt('CODE').'</th>':'').
                   4694: 	'<th>'.&mt('Submission').'</th>'.
                   4695: 	'<th>'.&mt('Status').'</th>'.
                   4696: 	&Apache::loncommon::end_data_table_header_row();
1.119     ng       4697:     my ($version);
                   4698:     my %mark;
1.148     albertel 4699:     my %orders;
1.119     ng       4700:     $mark{'correct_by_student'} = $checkIcon;
1.147     albertel 4701:     if (!exists($$record{'1:timestamp'})) {
1.539     riegler  4702: 	return '<br />&nbsp;<span class="LC_warning">'.&mt('Nothing submitted - no attempts.').'</span><br />';
1.147     albertel 4703:     }
1.335     albertel 4704: 
                   4705:     my $interaction;
1.525     raeburn  4706:     my $no_increment = 1;
1.596.2.2  raeburn  4707:     my %lastrndseed;
1.119     ng       4708:     for ($version=1;$version<=$$record{'version'};$version++) {
1.467     albertel 4709: 	my $timestamp = 
                   4710: 	    &Apache::lonlocal::locallocaltime($$record{$version.':timestamp'});
1.335     albertel 4711: 	if (exists($$record{$version.':resource.0.version'})) {
                   4712: 	    $interaction = $$record{$version.':resource.0.version'};
                   4713: 	}
                   4714: 
                   4715: 	my $where = ($isTask ? "$version:resource.$interaction"
                   4716: 		             : "$version:resource");
1.467     albertel 4717: 	$studentTable.=&Apache::loncommon::start_data_table_row().
                   4718: 	    '<td>'.$timestamp.'</td>';
1.224     albertel 4719: 	if ($isCODE) {
                   4720: 	    $studentTable.='<td>'.$record->{$version.':resource.CODE'}.'</td>';
                   4721: 	}
1.119     ng       4722: 	my @versionKeys = split(/\:/,$$record{$version.':keys'});
                   4723: 	my @displaySub = ();
                   4724: 	foreach my $partid (@{$parts}) {
1.596.2.2  raeburn  4725:             my ($hidden,$type);
                   4726:             $type = $$record{$version.':resource.'.$partid.'.type'};
                   4727:             if (($type eq 'anonsurvey') || ($type eq 'anonsurveycred')) {
1.596     raeburn  4728:                 $hidden = 1;
                   4729:             }
1.335     albertel 4730: 	    my @matchKey = ($isTask ? sort(grep /^resource\.\d+\.\Q$partid\E\.award$/,@versionKeys)
                   4731: 			            : sort(grep /^resource\.\Q$partid\E\..*?\.submission$/,@versionKeys));
                   4732: 	    
1.122     ng       4733: #	    next if ($$record{"$version:resource.$partid.solved"} eq '');
1.324     albertel 4734: 	    my $display_part=&get_display_part($partid,$symb);
1.147     albertel 4735: 	    foreach my $matchKey (@matchKey) {
1.198     albertel 4736: 		if (exists($$record{$version.':'.$matchKey}) &&
                   4737: 		    $$record{$version.':'.$matchKey} ne '') {
1.596     raeburn  4738:                     
1.335     albertel 4739: 		    my ($responseId)= ($isTask ? ($matchKey=~ /^resource\.(.*?)\.\Q$partid\E\.award$/)
                   4740: 				               : ($matchKey=~ /^resource\.\Q$partid\E\.(.*?)\.submission$/));
1.577     bisitz   4741:                     $displaySub[0].='<span class="LC_nobreak"';
                   4742:                     $displaySub[0].='<b>'.&mt('Part: [_1]',$display_part).'</b>'
                   4743:                                    .' <span class="LC_internal_info">'
1.596.2.4  raeburn  4744:                                    .'('.&mt('Response ID: [_1]',$responseId).')'
1.577     bisitz   4745:                                    .'</span>'
                   4746:                                    .' <b>';
1.596     raeburn  4747:                     if ($hidden) {
                   4748:                         $displaySub[0].= &mt('Anonymous Survey').'</b>';
                   4749:                     } else {
1.596.2.2  raeburn  4750:                         my ($trial,$rndseed,$newvariation);
                   4751:                         if ($type eq 'randomizetry') {
                   4752:                             $trial = $$record{"$where.$partid.tries"};
                   4753:                             $rndseed = $$record{"$where.$partid.rndseed"};
                   4754:                         }
1.596     raeburn  4755: 		        if ($$record{"$where.$partid.tries"} eq '') {
                   4756: 			    $displaySub[0].=&mt('Trial not counted');
                   4757: 		        } else {
                   4758: 			    $displaySub[0].=&mt('Trial: [_1]',
1.467     albertel 4759: 					    $$record{"$where.$partid.tries"});
1.596.2.2  raeburn  4760:                             if ($rndseed || $lastrndseed{$partid}) {
                   4761:                                 if ($rndseed ne $lastrndseed{$partid}) {
                   4762:                                     $newvariation = '&nbsp;('.&mt('New variation this try').')';
                   4763:                                 }
                   4764:                             }
1.596     raeburn  4765: 		        }
                   4766: 		        my $responseType=($isTask ? 'Task'
1.335     albertel 4767:                                               : $responseType->{$partid}->{$responseId});
1.596     raeburn  4768: 		        if (!exists($orders{$partid})) { $orders{$partid}={}; }
1.596.2.2  raeburn  4769: 		        if ((!exists($orders{$partid}->{$responseId})) || ($trial)) {
1.596     raeburn  4770: 			    $orders{$partid}->{$responseId}=
                   4771: 			        &get_order($partid,$responseId,$symb,$uname,$udom,
1.596.2.2  raeburn  4772:                                            $no_increment,$type,$trial,$rndseed);
1.596     raeburn  4773: 		        }
1.596.2.2  raeburn  4774: 		        $displaySub[0].='</b>'.$newvariation.'</span>'; # /nobreak
1.596     raeburn  4775: 		        $displaySub[0].='&nbsp; '.
1.596.2.2  raeburn  4776: 			    &cleanRecord($$record{$version.':'.$matchKey},$responseType,$symb,$partid,$responseId,$record,$orders{$partid}->{$responseId},"$version:",$uname,$udom,$type,$trial,$rndseed).'<br />';
1.596     raeburn  4777:                     }
1.147     albertel 4778: 		}
                   4779: 	    }
1.335     albertel 4780: 	    if (exists($$record{"$where.$partid.checkedin"})) {
1.485     albertel 4781: 		$displaySub[1].=&mt('Checked in by [_1] into slot [_2]',
                   4782: 				    $$record{"$where.$partid.checkedin"},
                   4783: 				    $$record{"$where.$partid.checkedin.slot"}).
                   4784: 					'<br />';
1.335     albertel 4785: 	    }
                   4786: 	    if (exists $$record{"$where.$partid.award"}) {
1.485     albertel 4787: 		$displaySub[1].='<b>'.&mt('Part:').'</b>&nbsp;'.$display_part.' &nbsp;'.
1.335     albertel 4788: 		    lc($$record{"$where.$partid.award"}).' '.
                   4789: 		    $mark{$$record{"$where.$partid.solved"}}.
1.147     albertel 4790: 		    '<br />';
                   4791: 	    }
1.335     albertel 4792: 	    if (exists $$record{"$where.$partid.regrader"}) {
                   4793: 		$displaySub[2].=$$record{"$where.$partid.regrader"}.
                   4794: 		    ' (<b>'.&mt('Part').':</b> '.$display_part.')';
                   4795: 	    } elsif ($$record{"$version:resource.$partid.regrader"} =~ /\S/) {
                   4796: 		$displaySub[2].=
                   4797: 		    $$record{"$version:resource.$partid.regrader"}.
1.207     albertel 4798: 		    ' (<b>'.&mt('Part').':</b> '.$display_part.')';
1.147     albertel 4799: 	    }
                   4800: 	}
                   4801: 	# needed because old essay regrader has not parts info
                   4802: 	if (exists $$record{"$version:resource.regrader"}) {
                   4803: 	    $displaySub[2].=$$record{"$version:resource.regrader"};
                   4804: 	}
                   4805: 	$studentTable.='<td>'.$displaySub[0].'&nbsp;</td><td>'.$displaySub[1];
                   4806: 	if ($displaySub[2]) {
1.467     albertel 4807: 	    $studentTable.=&mt('Manually graded by [_1]',$displaySub[2]);
1.147     albertel 4808: 	}
1.467     albertel 4809: 	$studentTable.='&nbsp;</td>'.
                   4810: 	    &Apache::loncommon::end_data_table_row();
1.119     ng       4811:     }
1.467     albertel 4812:     $studentTable.=&Apache::loncommon::end_data_table();
1.119     ng       4813:     return $studentTable;
1.71      ng       4814: }
                   4815: 
                   4816: sub updateGradeByPage {
                   4817:     my ($request) = shift;
                   4818: 
1.257     albertel 4819:     my $cdom      = $env{"course.$env{'request.course.id'}.domain"};
                   4820:     my $cnum      = $env{"course.$env{'request.course.id'}.num"};
                   4821:     my $getsec    = $env{'form.section'} eq '' ? 'all' : $env{'form.section'};
                   4822:     my $pageTitle = $env{'form.page'};
1.103     albertel 4823:     my ($classlist,undef,$fullname) = &getclasslist($getsec,'1');
1.257     albertel 4824:     my ($uname,$udom) = split(/:/,$env{'form.student'});
                   4825:     my $usec=$classlist->{$env{'form.student'}}[5];
1.103     albertel 4826:     if (!&canmodify($usec)) {
1.526     raeburn  4827: 	$request->print('<span class="LC_warning">'.&mt('Unable to modify requested student ([_1])',$env{'form.student'}).'</span>');
1.324     albertel 4828: 	$request->print(&show_grading_menu_form($env{'form.symb'}));
1.103     albertel 4829: 	return;
                   4830:     }
1.398     albertel 4831:     my $result='<h3><span class="LC_info">&nbsp;'.$env{'form.title'}.'</span></h3>';
1.526     raeburn  4832:     $result.='<h3>&nbsp;'.&mt('Student: ').&nameUserString(undef,$env{'form.fullname'},$uname,$udom).
1.129     ng       4833: 	'</h3>'."\n";
1.70      ng       4834: 
1.68      ng       4835:     $request->print($result);
                   4836: 
1.582     raeburn  4837: 
1.132     bowersj2 4838:     my $navmap = Apache::lonnavmaps::navmap->new();
1.582     raeburn  4839:     unless (ref($navmap)) {
                   4840:         $request->print(&navmap_errormsg());
                   4841:         return;
                   4842:     }
1.257     albertel 4843:     my ($mapUrl, $id, $resUrl) = &Apache::lonnet::decode_symb( $env{'form.page'});
1.71      ng       4844:     my $map = $navmap->getResourceByUrl($resUrl); # add to navmaps
1.288     albertel 4845:     if (!$map) {
1.527     raeburn  4846: 	$request->print('<span class="LC_warning">'.&mt('Unable to grade requested sequence ([_1]).',$resUrl).'</span>');
1.324     albertel 4847: 	my ($symb)=&get_symb($request);
                   4848: 	$request->print(&show_grading_menu_form($symb));
1.288     albertel 4849: 	return; 
                   4850:     }
1.71      ng       4851:     my $iterator = $navmap->getIterator($map->map_start(),
                   4852: 					$map->map_finish());
1.70      ng       4853: 
1.484     albertel 4854:     my $studentTable=
                   4855: 	&Apache::loncommon::start_data_table().
                   4856: 	&Apache::loncommon::start_data_table_header_row().
1.485     albertel 4857: 	'<th align="center">&nbsp;'.&mt('Prob.').'&nbsp;</th>'.
                   4858: 	'<th>&nbsp;'.&mt('Title').'&nbsp;</th>'.
                   4859: 	'<th>&nbsp;'.&mt('Previous Score').'&nbsp;</th>'.
                   4860: 	'<th>&nbsp;'.&mt('New Score').'&nbsp;</th>'.
1.484     albertel 4861: 	&Apache::loncommon::end_data_table_header_row();
1.71      ng       4862: 
                   4863:     $iterator->next(); # skip the first BEGIN_MAP
                   4864:     my $curRes = $iterator->next(); # for "current resource"
1.196     albertel 4865:     my ($depth,$question,$prob,$changeflag)= (1,1,1,0);
1.101     albertel 4866:     while ($depth > 0) {
1.71      ng       4867:         if($curRes == $iterator->BEGIN_MAP) { $depth++; }
1.100     bowersj2 4868:         if($curRes == $iterator->END_MAP) { $depth--; }
1.71      ng       4869: 
1.385     albertel 4870:         if (ref($curRes) && $curRes->is_problem()) {
1.91      albertel 4871: 	    my $parts = $curRes->parts();
1.71      ng       4872:             my $title = $curRes->compTitle();
                   4873: 	    my $symbx = $curRes->symb();
1.484     albertel 4874: 	    $studentTable.=
                   4875: 		&Apache::loncommon::start_data_table_row().
                   4876: 		'<td align="center" valign="top" >'.$prob.
1.485     albertel 4877: 		(scalar(@{$parts}) == 1 ? '' 
1.596.2.2  raeburn  4878:                                         : '<br />('.&mt('[quant,_1,part]',scalar(@{$parts}))
1.526     raeburn  4879: 		.')').'</td>';
1.71      ng       4880: 	    $studentTable.='<td valign="top">&nbsp;<b>'.$title.'</b>&nbsp;</td>';
                   4881: 
                   4882: 	    my %newrecord=();
                   4883: 	    my @displayPts=();
1.269     raeburn  4884:             my %aggregate = ();
                   4885:             my $aggregateflag = 0;
1.71      ng       4886: 	    foreach my $partid (@{$parts}) {
1.257     albertel 4887: 		my $newpts = $env{'form.GD_BOX'.$question.'_'.$partid};
                   4888: 		my $oldpts = $env{'form.oldpts'.$question.'_'.$partid};
1.71      ng       4889: 
1.257     albertel 4890: 		my $wgt = $env{'form.WGT'.$question.'_'.$partid} != 0 ? 
                   4891: 		    $env{'form.WGT'.$question.'_'.$partid} : 1;
1.71      ng       4892: 		my $partial = $newpts/$wgt;
                   4893: 		my $score;
                   4894: 		if ($partial > 0) {
                   4895: 		    $score = 'correct_by_override';
1.125     ng       4896: 		} elsif ($newpts ne '') { #empty is taken as 0
1.71      ng       4897: 		    $score = 'incorrect_by_override';
                   4898: 		}
1.257     albertel 4899: 		my $dropMenu = $env{'form.GD_SEL'.$question.'_'.$partid};
1.125     ng       4900: 		if ($dropMenu eq 'excused') {
1.71      ng       4901: 		    $partial = '';
                   4902: 		    $score = 'excused';
1.125     ng       4903: 		} elsif ($dropMenu eq 'reset status'
1.257     albertel 4904: 			 && $env{'form.solved'.$question.'_'.$partid} ne '') { #update only if previous record exists
1.125     ng       4905: 		    $newrecord{'resource.'.$partid.'.tries'} = 0;
                   4906: 		    $newrecord{'resource.'.$partid.'.solved'} = '';
                   4907: 		    $newrecord{'resource.'.$partid.'.award'} = '';
                   4908: 		    $newrecord{'resource.'.$partid.'.awarded'} = 0;
1.257     albertel 4909: 		    $newrecord{'resource.'.$partid.'.regrader'} = "$env{'user.name'}:$env{'user.domain'}";
1.125     ng       4910: 		    $changeflag++;
                   4911: 		    $newpts = '';
1.269     raeburn  4912:                     
                   4913:                     my $aggtries =  $env{'form.aggtries'.$question.'_'.$partid};
                   4914:                     my $totaltries = $env{'form.totaltries'.$question.'_'.$partid};
                   4915:                     my $solvedstatus = $env{'form.solved'.$question.'_'.$partid};
                   4916:                     if ($aggtries > 0) {
                   4917:                         &decrement_aggs($symbx,$partid,\%aggregate,$aggtries,$totaltries,$solvedstatus);
                   4918:                         $aggregateflag = 1;
                   4919:                     }
1.71      ng       4920: 		}
1.324     albertel 4921: 		my $display_part=&get_display_part($partid,$curRes->symb());
1.257     albertel 4922: 		my $oldstatus = $env{'form.solved'.$question.'_'.$partid};
1.526     raeburn  4923: 		$displayPts[0].='&nbsp;<b>'.&mt('Part').':</b> '.$display_part.' = '.
1.71      ng       4924: 		    (($oldstatus eq 'excused') ? 'excused' : $oldpts).
1.326     albertel 4925: 		    '&nbsp;<br />';
1.526     raeburn  4926: 		$displayPts[1].='&nbsp;<b>'.&mt('Part').':</b> '.$display_part.' = '.
1.125     ng       4927: 		     (($score eq 'excused') ? 'excused' : $newpts).
1.326     albertel 4928: 		    '&nbsp;<br />';
1.71      ng       4929: 		$question++;
1.380     albertel 4930: 		next if ($dropMenu eq 'reset status' || ($newpts eq $oldpts && $score ne 'excused'));
1.125     ng       4931: 
1.71      ng       4932: 		$newrecord{'resource.'.$partid.'.awarded'}  = $partial if $partial ne '';
1.125     ng       4933: 		$newrecord{'resource.'.$partid.'.solved'}   = $score if $score ne '';
1.257     albertel 4934: 		$newrecord{'resource.'.$partid.'.regrader'} = "$env{'user.name'}:$env{'user.domain'}"
1.125     ng       4935: 		    if (scalar(keys(%newrecord)) > 0);
1.71      ng       4936: 
                   4937: 		$changeflag++;
                   4938: 	    }
                   4939: 	    if (scalar(keys(%newrecord)) > 0) {
1.382     albertel 4940: 		my %record = 
                   4941: 		    &Apache::lonnet::restore($symbx,$env{'request.course.id'},
                   4942: 					     $udom,$uname);
                   4943: 
                   4944: 		if (&Apache::lonnet::validCODE($env{'form.CODE'})) {
                   4945: 		    $newrecord{'resource.CODE'} = $env{'form.CODE'};
                   4946: 		} elsif (&Apache::lonnet::validCODE($record{'resource.CODE'})) {
                   4947: 		    $newrecord{'resource.CODE'} = '';
                   4948: 		}
1.257     albertel 4949: 		&Apache::lonnet::cstore(\%newrecord,$symbx,$env{'request.course.id'},
1.71      ng       4950: 					$udom,$uname);
1.382     albertel 4951: 		%record = &Apache::lonnet::restore($symbx,
                   4952: 						   $env{'request.course.id'},
                   4953: 						   $udom,$uname);
1.380     albertel 4954: 		&check_and_remove_from_queue($parts,\%record,undef,$symbx,
                   4955: 					     $cdom,$cnum,$udom,$uname);
1.71      ng       4956: 	    }
1.380     albertel 4957: 	    
1.269     raeburn  4958:             if ($aggregateflag) {
                   4959:                 &Apache::lonnet::cinc('nohist_resourcetracker',\%aggregate,
                   4960:                       $env{'course.'.$env{'request.course.id'}.'.domain'},
                   4961:                       $env{'course.'.$env{'request.course.id'}.'.num'});
                   4962:             }
1.125     ng       4963: 
1.71      ng       4964: 	    $studentTable.='<td valign="top">'.$displayPts[0].'</td>'.
                   4965: 		'<td valign="top">'.$displayPts[1].'</td>'.
1.484     albertel 4966: 		&Apache::loncommon::end_data_table_row();
1.68      ng       4967: 
1.196     albertel 4968: 	    $prob++;
1.68      ng       4969: 	}
1.71      ng       4970:         $curRes = $iterator->next();
1.68      ng       4971:     }
1.98      albertel 4972: 
1.484     albertel 4973:     $studentTable.=&Apache::loncommon::end_data_table();
1.324     albertel 4974:     $studentTable.=&show_grading_menu_form($env{'form.symb'});
1.526     raeburn  4975:     my $grademsg=($changeflag == 0 ? &mt('No score was changed or updated.') :
                   4976: 		  &mt('The scores were changed for [quant,_1,problem].',
                   4977: 		  $changeflag));
1.76      ng       4978:     $request->print($grademsg.$studentTable);
1.68      ng       4979: 
1.70      ng       4980:     return '';
                   4981: }
                   4982: 
1.72      ng       4983: #-------- end of section for handling grading by page/sequence ---------
                   4984: #
                   4985: #-------------------------------------------------------------------
                   4986: 
1.581     www      4987: #-------------------- Bubblesheet (Scantron) Grading -------------------
1.75      albertel 4988: #
                   4989: #------ start of section for handling grading by page/sequence ---------
                   4990: 
1.423     albertel 4991: =pod
                   4992: 
                   4993: =head1 Bubble sheet grading routines
                   4994: 
1.424     albertel 4995:   For this documentation:
                   4996: 
                   4997:    'scanline' refers to the full line of characters
                   4998:    from the file that we are parsing that represents one entire sheet
                   4999: 
                   5000:    'bubble line' refers to the data
1.596.2.6  raeburn  5001:    representing the line of bubbles that are on the physical bubblesheet
1.424     albertel 5002: 
                   5003: 
1.596.2.6  raeburn  5004: The overall process is that a scanned in bubblesheet data is uploaded
1.424     albertel 5005: into a course. When a user wants to grade, they select a
1.596.2.6  raeburn  5006: sequence/folder of resources, a file of bubblesheet info, and pick
1.424     albertel 5007: one of the predefined configurations for what each scanline looks
                   5008: like.
                   5009: 
                   5010: Next each scanline is checked for any errors of either 'missing
1.435     foxr     5011: bubbles' (it's an error because it may have been mis-scanned
1.424     albertel 5012: because too light bubbling), 'double bubble' (each bubble line should
                   5013: have no more that one letter picked), invalid or duplicated CODE,
1.556     weissno  5014: invalid student/employee ID
1.424     albertel 5015: 
                   5016: If the CODE option is used that determines the randomization of the
1.556     weissno  5017: homework problems, either way the student/employee ID is looked up into a
1.424     albertel 5018: username:domain.
                   5019: 
                   5020: During the validation phase the instructor can choose to skip scanlines. 
                   5021: 
1.596.2.6  raeburn  5022: After the validation phase, there are now 3 bubblesheet files
1.424     albertel 5023: 
                   5024:   scantron_original_filename (unmodified original file)
                   5025:   scantron_corrected_filename (file where the corrected information has replaced the original information)
                   5026:   scantron_skipped_filename (contains the exact text of scanlines that where skipped)
                   5027: 
                   5028: Also there is a separate hash nohist_scantrondata that contains extra
1.596.2.6  raeburn  5029: correction information that isn't representable in the bubblesheet
1.424     albertel 5030: file (see &scantron_getfile() for more information)
                   5031: 
                   5032: After all scanlines are either valid, marked as valid or skipped, then
                   5033: foreach line foreach problem in the picked sequence, an ssi request is
                   5034: made that simulates a user submitting their selected letter(s) against
                   5035: the homework problem.
1.423     albertel 5036: 
                   5037: =over 4
                   5038: 
                   5039: 
                   5040: 
                   5041: =item defaultFormData
                   5042: 
                   5043:   Returns html hidden inputs used to hold context/default values.
                   5044: 
                   5045:  Arguments:
                   5046:   $symb - $symb of the current resource 
                   5047: 
                   5048: =cut
1.422     foxr     5049: 
1.81      albertel 5050: sub defaultFormData {
1.324     albertel 5051:     my ($symb)=@_;
1.447     foxr     5052:     return '<input type="hidden" name="symb"    value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
1.257     albertel 5053:      '<input type="hidden" name="saveState" value="'.$env{'form.saveState'}.'" />'."\n".
                   5054:      '<input type="hidden" name="probTitle" value="'.$env{'form.probTitle'}.'" />'."\n";
1.81      albertel 5055: }
                   5056: 
1.447     foxr     5057: 
1.423     albertel 5058: =pod 
                   5059: 
                   5060: =item getSequenceDropDown
                   5061: 
                   5062:    Return html dropdown of possible sequences to grade
                   5063:  
                   5064:  Arguments:
1.582     raeburn  5065:    $symb - $symb of the current resource
                   5066:    $map_error - ref to scalar which will container error if
                   5067:                 $navmap object is unavailable in &getSymbMap().
1.423     albertel 5068: 
                   5069: =cut
1.422     foxr     5070: 
1.75      albertel 5071: sub getSequenceDropDown {
1.582     raeburn  5072:     my ($symb,$map_error)=@_;
1.75      albertel 5073:     my $result='<select name="selectpage">'."\n";
1.582     raeburn  5074:     my ($titles,$symbx) = &getSymbMap($map_error);
                   5075:     if (ref($map_error)) {
                   5076:         return if ($$map_error);
                   5077:     }
1.137     albertel 5078:     my ($curpage)=&Apache::lonnet::decode_symb($symb); 
1.75      albertel 5079:     my $ctr=0;
                   5080:     foreach (@$titles) {
                   5081: 	my ($minder,$showtitle) = ($_ =~ /(\d+)\.(.*)/);
                   5082: 	$result.='<option value="'.$$symbx{$_}.'" '.
1.401     albertel 5083: 	    ($$symbx{$_} =~ /$curpage$/ ? 'selected="selected"' : '').
1.75      albertel 5084: 	    '>'.$showtitle.'</option>'."\n";
                   5085: 	$ctr++;
                   5086:     }
                   5087:     $result.= '</select>';
                   5088:     return $result;
                   5089: }
                   5090: 
1.495     albertel 5091: my %bubble_lines_per_response;     # no. bubble lines for each response.
1.554     raeburn  5092:                                    # key is zero-based index - 0, 1, 2 ...
1.495     albertel 5093: 
                   5094: my %first_bubble_line;             # First bubble line no. for each bubble.
                   5095: 
1.509     raeburn  5096: my %subdivided_bubble_lines;       # no. bubble lines for optionresponse, 
                   5097:                                    # matchresponse or rankresponse, where 
                   5098:                                    # an individual response can have multiple 
                   5099:                                    # lines
1.503     raeburn  5100: 
                   5101: my %responsetype_per_response;     # responsetype for each response
                   5102: 
1.495     albertel 5103: # Save and restore the bubble lines array to the form env.
                   5104: 
                   5105: 
                   5106: sub save_bubble_lines {
                   5107:     foreach my $line (keys(%bubble_lines_per_response)) {
                   5108: 	$env{"form.scantron.bubblelines.$line"}  = $bubble_lines_per_response{$line};
                   5109: 	$env{"form.scantron.first_bubble_line.$line"} =
                   5110: 	    $first_bubble_line{$line};
1.503     raeburn  5111:         $env{"form.scantron.sub_bubblelines.$line"} = 
                   5112:             $subdivided_bubble_lines{$line};
                   5113:         $env{"form.scantron.responsetype.$line"} =
                   5114:             $responsetype_per_response{$line};
1.495     albertel 5115:     }
                   5116: }
                   5117: 
                   5118: 
                   5119: sub restore_bubble_lines {
                   5120:     my $line = 0;
                   5121:     %bubble_lines_per_response = ();
                   5122:     while ($env{"form.scantron.bubblelines.$line"}) {
                   5123: 	my $value = $env{"form.scantron.bubblelines.$line"};
                   5124: 	$bubble_lines_per_response{$line} = $value;
                   5125: 	$first_bubble_line{$line}  =
                   5126: 	    $env{"form.scantron.first_bubble_line.$line"};
1.503     raeburn  5127:         $subdivided_bubble_lines{$line} =
                   5128:             $env{"form.scantron.sub_bubblelines.$line"};
                   5129:         $responsetype_per_response{$line} =
                   5130:             $env{"form.scantron.responsetype.$line"};
1.495     albertel 5131: 	$line++;
                   5132:     }
                   5133: }
                   5134: 
                   5135: #  Given the parsed scanline, get the response for 
                   5136: #  'answer' number n:
                   5137: 
                   5138: sub get_response_bubbles {
                   5139:     my ($parsed_line, $response)  = @_;
                   5140: 
                   5141:     my $bubble_line = $first_bubble_line{$response-1} +1;
                   5142:     my $bubble_lines= $bubble_lines_per_response{$response-1};
                   5143:     
                   5144:     my $selected = "";
                   5145: 
                   5146:     for (my $bline = 0; $bline < $bubble_lines; $bline++) {
                   5147: 	$selected .= $$parsed_line{"scantron.$bubble_line.answer"}.":";
                   5148: 	$bubble_line++;
                   5149:     }
                   5150:     return $selected;
                   5151: }
1.423     albertel 5152: 
                   5153: =pod 
                   5154: 
                   5155: =item scantron_filenames
                   5156: 
                   5157:    Returns a list of the scantron files in the current course 
                   5158: 
                   5159: =cut
1.422     foxr     5160: 
1.202     albertel 5161: sub scantron_filenames {
1.257     albertel 5162:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
                   5163:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
1.517     raeburn  5164:     my $getpropath = 1;
1.157     albertel 5165:     my @files=&Apache::lonnet::dirlist('userfiles',$cdom,$cname,
1.517     raeburn  5166:                                        $getpropath);
1.202     albertel 5167:     my @possiblenames;
1.201     albertel 5168:     foreach my $filename (sort(@files)) {
1.157     albertel 5169: 	($filename)=split(/&/,$filename);
                   5170: 	if ($filename!~/^scantron_orig_/) { next ; }
                   5171: 	$filename=~s/^scantron_orig_//;
1.202     albertel 5172: 	push(@possiblenames,$filename);
                   5173:     }
                   5174:     return @possiblenames;
                   5175: }
                   5176: 
1.423     albertel 5177: =pod 
                   5178: 
                   5179: =item scantron_uploads
                   5180: 
                   5181:    Returns  html drop-down list of scantron files in current course.
                   5182: 
                   5183:  Arguments:
                   5184:    $file2grade - filename to set as selected in the dropdown
                   5185: 
                   5186: =cut
1.422     foxr     5187: 
1.202     albertel 5188: sub scantron_uploads {
1.209     ng       5189:     my ($file2grade) = @_;
1.202     albertel 5190:     my $result=	'<select name="scantron_selectfile">';
                   5191:     $result.="<option></option>";
                   5192:     foreach my $filename (sort(&scantron_filenames())) {
1.401     albertel 5193: 	$result.="<option".($filename eq $file2grade ? ' selected="selected"':'').">$filename</option>\n";
1.81      albertel 5194:     }
                   5195:     $result.="</select>";
                   5196:     return $result;
                   5197: }
                   5198: 
1.423     albertel 5199: =pod 
                   5200: 
                   5201: =item scantron_scantab
                   5202: 
                   5203:   Returns html drop down of the scantron formats in the scantronformat.tab
                   5204:   file.
                   5205: 
                   5206: =cut
1.422     foxr     5207: 
1.82      albertel 5208: sub scantron_scantab {
                   5209:     my $result='<select name="scantron_format">'."\n";
1.191     albertel 5210:     $result.='<option></option>'."\n";
1.518     raeburn  5211:     my @lines = &get_scantronformat_file();
                   5212:     if (@lines > 0) {
                   5213:         foreach my $line (@lines) {
                   5214:             next if (($line =~ /^\#/) || ($line eq ''));
                   5215: 	    my ($name,$descrip)=split(/:/,$line);
                   5216: 	    $result.='<option value="'.$name.'">'.$descrip.'</option>'."\n";
                   5217:         }
1.82      albertel 5218:     }
                   5219:     $result.='</select>'."\n";
1.518     raeburn  5220:     return $result;
                   5221: }
                   5222: 
                   5223: =pod
                   5224: 
                   5225: =item get_scantronformat_file
                   5226: 
                   5227:   Returns an array containing lines from the scantron format file for
                   5228:   the domain of the course.
                   5229: 
                   5230:   If a url for a custom.tab file is listed in domain's configuration.db, 
                   5231:   lines are from this file.
                   5232: 
                   5233:   Otherwise, if a default.tab has been published in RES space by the 
                   5234:   domainconfig user, lines are from this file.
                   5235: 
                   5236:   Otherwise, fall back to getting lines from the legacy file on the
1.519     raeburn  5237:   local server:  /home/httpd/lonTabs/default_scantronformat.tab    
1.82      albertel 5238: 
1.518     raeburn  5239: =cut
                   5240: 
                   5241: sub get_scantronformat_file {
                   5242:     my $cdom= $env{'course.'.$env{'request.course.id'}.'.domain'};
                   5243:     my %domconfig = &Apache::lonnet::get_dom('configuration',['scantron'],$cdom);
                   5244:     my $gottab = 0;
                   5245:     my @lines;
                   5246:     if (ref($domconfig{'scantron'}) eq 'HASH') {
                   5247:         if ($domconfig{'scantron'}{'scantronformat'} ne '') {
                   5248:             my $formatfile = &Apache::lonnet::getfile($Apache::lonnet::perlvar{'lonDocRoot'}.$domconfig{'scantron'}{'scantronformat'});
                   5249:             if ($formatfile ne '-1') {
                   5250:                 @lines = split("\n",$formatfile,-1);
                   5251:                 $gottab = 1;
                   5252:             }
                   5253:         }
                   5254:     }
                   5255:     if (!$gottab) {
                   5256:         my $confname = $cdom.'-domainconfig';
                   5257:         my $default = $Apache::lonnet::perlvar{'lonDocRoot'}.'/res/'.$cdom.'/'.$confname.'/default.tab';
                   5258:         my $formatfile =  &Apache::lonnet::getfile($default);
                   5259:         if ($formatfile ne '-1') {
                   5260:             @lines = split("\n",$formatfile,-1);
                   5261:             $gottab = 1;
                   5262:         }
                   5263:     }
                   5264:     if (!$gottab) {
1.519     raeburn  5265:         my @domains = &Apache::lonnet::current_machine_domains();
                   5266:         if (grep(/^\Q$cdom\E$/,@domains)) {
                   5267:             my $fh=Apache::File->new($Apache::lonnet::perlvar{'lonTabDir'}.'/scantronformat.tab');
                   5268:             @lines = <$fh>;
                   5269:             close($fh);
                   5270:         } else {
                   5271:             my $fh=Apache::File->new($Apache::lonnet::perlvar{'lonTabDir'}.'/default_scantronformat.tab');
                   5272:             @lines = <$fh>;
                   5273:             close($fh);
                   5274:         }
1.518     raeburn  5275:     }
                   5276:     return @lines;
1.82      albertel 5277: }
                   5278: 
1.423     albertel 5279: =pod 
                   5280: 
                   5281: =item scantron_CODElist
                   5282: 
                   5283:   Returns html drop down of the saved CODE lists from current course,
                   5284:   generated from earlier printings.
                   5285: 
                   5286: =cut
1.422     foxr     5287: 
1.186     albertel 5288: sub scantron_CODElist {
1.257     albertel 5289:     my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   5290:     my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
1.186     albertel 5291:     my @names=&Apache::lonnet::getkeys('CODEs',$cdom,$cnum);
                   5292:     my $namechoice='<option></option>';
1.225     albertel 5293:     foreach my $name (sort {uc($a) cmp uc($b)} @names) {
1.191     albertel 5294: 	if ($name =~ /^error: 2 /) { next; }
1.278     albertel 5295: 	if ($name =~ /^type\0/) { next; }
1.186     albertel 5296: 	$namechoice.='<option value="'.$name.'">'.$name.'</option>';
                   5297:     }
                   5298:     $namechoice='<select name="scantron_CODElist">'.$namechoice.'</select>';
                   5299:     return $namechoice;
                   5300: }
                   5301: 
1.423     albertel 5302: =pod 
                   5303: 
                   5304: =item scantron_CODEunique
                   5305: 
                   5306:   Returns the html for "Each CODE to be used once" radio.
                   5307: 
                   5308: =cut
1.422     foxr     5309: 
1.186     albertel 5310: sub scantron_CODEunique {
1.532     bisitz   5311:     my $result='<span class="LC_nobreak">
1.272     albertel 5312:                  <label><input type="radio" name="scantron_CODEunique"
1.423     albertel 5313:                         value="yes" checked="checked" />'.&mt('Yes').' </label>
1.381     albertel 5314:                 </span>
1.532     bisitz   5315:                 <span class="LC_nobreak">
1.272     albertel 5316:                  <label><input type="radio" name="scantron_CODEunique"
1.423     albertel 5317:                         value="no" />'.&mt('No').' </label>
1.381     albertel 5318:                 </span>';
1.186     albertel 5319:     return $result;
                   5320: }
1.423     albertel 5321: 
                   5322: =pod 
                   5323: 
                   5324: =item scantron_selectphase
                   5325: 
1.596.2.6  raeburn  5326:   Generates the initial screen to start the bubblesheet process.
1.423     albertel 5327:   Allows for - starting a grading run.
1.424     albertel 5328:              - downloading existing scan data (original, corrected
1.423     albertel 5329:                                                 or skipped info)
                   5330: 
                   5331:              - uploading new scan data
                   5332: 
                   5333:  Arguments:
                   5334:   $r          - The Apache request object
                   5335:   $file2grade - name of the file that contain the scanned data to score
                   5336: 
                   5337: =cut
1.186     albertel 5338: 
1.75      albertel 5339: sub scantron_selectphase {
1.209     ng       5340:     my ($r,$file2grade) = @_;
1.324     albertel 5341:     my ($symb)=&get_symb($r);
1.75      albertel 5342:     if (!$symb) {return '';}
1.582     raeburn  5343:     my $map_error;
                   5344:     my $sequence_selector=&getSequenceDropDown($symb,\$map_error);
                   5345:     if ($map_error) {
                   5346:         $r->print('<br />'.&navmap_errormsg().'<br />');
                   5347:         return;
                   5348:     }
1.324     albertel 5349:     my $default_form_data=&defaultFormData($symb);
                   5350:     my $grading_menu_button=&show_grading_menu_form($symb);
1.209     ng       5351:     my $file_selector=&scantron_uploads($file2grade);
1.82      albertel 5352:     my $format_selector=&scantron_scantab();
1.186     albertel 5353:     my $CODE_selector=&scantron_CODElist();
                   5354:     my $CODE_unique=&scantron_CODEunique();
1.75      albertel 5355:     my $result;
1.422     foxr     5356: 
1.513     foxr     5357:     $ssi_error = 0;
                   5358: 
1.596.2.4  raeburn  5359:     if (&Apache::lonnet::allowed('usc',$env{'request.role.domain'}) ||
                   5360:         &Apache::lonnet::allowed('usc',$env{'request.course.id'})) {
                   5361: 
                   5362:         # Chunk of form to prompt for a scantron file upload.
                   5363: 
                   5364:         $r->print('
                   5365:     <br />
                   5366:     '.&Apache::loncommon::start_data_table('LC_scantron_action').'
                   5367:        '.&Apache::loncommon::start_data_table_header_row().'
                   5368:             <th>
                   5369:               &nbsp;'.&mt('Specify a bubblesheet data file to upload.').'
                   5370:             </th>
                   5371:        '.&Apache::loncommon::end_data_table_header_row().'
                   5372:        '.&Apache::loncommon::start_data_table_row().'
                   5373:             <td>
                   5374: ');
                   5375:     my $default_form_data=&defaultFormData(&get_symb($r,1));
                   5376:     my $cdom= $env{'course.'.$env{'request.course.id'}.'.domain'};
                   5377:     my $cnum= $env{'course.'.$env{'request.course.id'}.'.num'};
                   5378:     $r->print('
                   5379:               <script type="text/javascript" language="javascript">
                   5380:     function checkUpload(formname) {
                   5381:         if (formname.upfile.value == "") {
                   5382:             alert("'.&mt('Please use the browse button to select a file from your local directory.').'");
                   5383:             return false;
                   5384:         }
                   5385:         formname.submit();
                   5386:     }
                   5387:               </script>
                   5388: 
                   5389:               <form enctype="multipart/form-data" action="/adm/grades" name="rules" method="post">
                   5390:                 '.$default_form_data.'
                   5391:                 <input name="courseid" type="hidden" value="'.$cnum.'" />
                   5392:                 <input name="domainid" type="hidden" value="'.$cdom.'" />
                   5393:                 <input name="command" value="scantronupload_save" type="hidden" />
                   5394:                 '.&mt('File to upload: [_1]','<input type="file" name="upfile" size="50" />').'
                   5395:                 <br />
                   5396:                 <input type="button" onclick="javascript:checkUpload(this.form);" value="'.&mt('Upload Bubblesheet Data').'" />
                   5397:               </form>
                   5398: ');
                   5399: 
                   5400:         $r->print('
                   5401:             </td>
                   5402:        '.&Apache::loncommon::end_data_table_row().'
                   5403:        '.&Apache::loncommon::end_data_table().'
                   5404: ');
                   5405:     }
                   5406: 
1.422     foxr     5407:     # Chunk of form to prompt for a file to grade and how:
                   5408: 
1.489     albertel 5409:     $result.= '
                   5410:     <br />
                   5411:     <form method="post" enctype="multipart/form-data" action="/adm/grades" name="scantron_process">
                   5412:     <input type="hidden" name="command" value="scantron_warning" />
                   5413:     '.$default_form_data.'
                   5414:     '.&Apache::loncommon::start_data_table('LC_scantron_action').'
                   5415:        '.&Apache::loncommon::start_data_table_header_row().'
                   5416:             <th colspan="2">
1.492     albertel 5417:               &nbsp;'.&mt('Specify file and which Folder/Sequence to grade').'
1.489     albertel 5418:             </th>
                   5419:        '.&Apache::loncommon::end_data_table_header_row().'
                   5420:        '.&Apache::loncommon::start_data_table_row().'
1.492     albertel 5421:             <td> '.&mt('Sequence to grade:').' </td><td> '.$sequence_selector.' </td>
1.489     albertel 5422:        '.&Apache::loncommon::end_data_table_row().'
                   5423:        '.&Apache::loncommon::start_data_table_row().'
1.572     www      5424:             <td> '.&mt('Filename of bubblesheet data file:').' </td><td> '.$file_selector.' </td>
1.489     albertel 5425:        '.&Apache::loncommon::end_data_table_row().'
                   5426:        '.&Apache::loncommon::start_data_table_row().'
1.572     www      5427:             <td> '.&mt('Format of bubblesheet data file:').' </td><td> '.$format_selector.' </td>
1.489     albertel 5428:        '.&Apache::loncommon::end_data_table_row().'
                   5429:        '.&Apache::loncommon::start_data_table_row().'
1.492     albertel 5430:             <td> '.&mt('Saved CODEs to validate against:').' </td><td> '.$CODE_selector.' </td>
1.489     albertel 5431:        '.&Apache::loncommon::end_data_table_row().'
                   5432:        '.&Apache::loncommon::start_data_table_row().'
1.492     albertel 5433:             <td> '.&mt('Each CODE is only to be used once:').'</td><td> '.$CODE_unique.' </td>
1.489     albertel 5434:        '.&Apache::loncommon::end_data_table_row().'
                   5435:        '.&Apache::loncommon::start_data_table_row().'
1.492     albertel 5436: 	    <td> '.&mt('Options:').' </td>
1.187     albertel 5437:             <td>
1.492     albertel 5438: 	       <label><input type="checkbox" name="scantron_options_redo" value="redo_skipped"/> '.&mt('Do only previously skipped records').'</label> <br />
                   5439:                <label><input type="checkbox" name="scantron_options_ignore" value="ignore_corrections"/> '.&mt('Remove all existing corrections').'</label> <br />
                   5440:                <label><input type="checkbox" name="scantron_options_hidden" value="ignore_hidden"/> '.&mt('Skip hidden resources when grading').'</label>
1.187     albertel 5441: 	    </td>
1.489     albertel 5442:        '.&Apache::loncommon::end_data_table_row().'
                   5443:        '.&Apache::loncommon::start_data_table_row().'
1.174     albertel 5444:             <td colspan="2">
1.572     www      5445:               <input type="submit" value="'.&mt('Grading: Validate Bubblesheet Records').'" />
1.162     albertel 5446:             </td>
1.489     albertel 5447:        '.&Apache::loncommon::end_data_table_row().'
                   5448:     '.&Apache::loncommon::end_data_table().'
                   5449:     </form>
                   5450: ';
1.162     albertel 5451:    
                   5452:     $r->print($result);
                   5453: 
1.422     foxr     5454:     # Chunk of the form that prompts to view a scoring office file,
                   5455:     # corrected file, skipped records in a file.
                   5456: 
1.489     albertel 5457:     $r->print('
                   5458:    <br />
                   5459:    <form action="/adm/grades" name="scantron_download">
                   5460:      '.$default_form_data.'
                   5461:      <input type="hidden" name="command" value="scantron_download" />
                   5462:      '.&Apache::loncommon::start_data_table('LC_scantron_action').'
                   5463:        '.&Apache::loncommon::start_data_table_header_row().'
                   5464:               <th>
1.492     albertel 5465:                 &nbsp;'.&mt('Download a scoring office file').'
1.489     albertel 5466:               </th>
                   5467:        '.&Apache::loncommon::end_data_table_header_row().'
                   5468:        '.&Apache::loncommon::start_data_table_row().'
1.492     albertel 5469:               <td> '.&mt('Filename of scoring office file: [_1]',$file_selector).' 
1.489     albertel 5470:                 <br />
1.492     albertel 5471:                 <input type="submit" value="'.&mt('Download: Show List of Associated Files').'" />
1.489     albertel 5472:        '.&Apache::loncommon::end_data_table_row().'
                   5473:      '.&Apache::loncommon::end_data_table().'
                   5474:    </form>
                   5475:    <br />
                   5476: ');
1.162     albertel 5477: 
1.457     banghart 5478:     &Apache::lonpickcode::code_list($r,2);
1.523     raeburn  5479: 
1.528     raeburn  5480:     $r->print('<br /><form method="post" name="checkscantron">'.
1.523     raeburn  5481:              $default_form_data."\n".
                   5482:              &Apache::loncommon::start_data_table('LC_scantron_action')."\n".
                   5483:              &Apache::loncommon::start_data_table_header_row()."\n".
                   5484:              '<th colspan="2">
1.572     www      5485:               &nbsp;'.&mt('Review bubblesheet data and submissions for a previously graded folder/sequence')."\n".
1.523     raeburn  5486:              '</th>'."\n".
                   5487:               &Apache::loncommon::end_data_table_header_row()."\n".
                   5488:               &Apache::loncommon::start_data_table_row()."\n".
                   5489:               '<td> '.&mt('Graded folder/sequence:').' </td>'."\n".
                   5490:               '<td> '.$sequence_selector.' </td>'.
                   5491:               &Apache::loncommon::end_data_table_row()."\n".
                   5492:               &Apache::loncommon::start_data_table_row()."\n".
                   5493:               '<td> '.&mt('Filename of scoring office file:').' </td>'."\n".
                   5494:               '<td> '.$file_selector.' </td>'."\n".
                   5495:               &Apache::loncommon::end_data_table_row()."\n".
                   5496:               &Apache::loncommon::start_data_table_row()."\n".
                   5497:               '<td> '.&mt('Format of data file:').' </td>'."\n".
                   5498:               '<td> '.$format_selector.' </td>'."\n".
                   5499:               &Apache::loncommon::end_data_table_row()."\n".
                   5500:               &Apache::loncommon::start_data_table_row()."\n".
1.557     raeburn  5501:               '<td> '.&mt('Options').' </td>'."\n".
                   5502:               '<td> <label><input type="checkbox" name="scantron_options_hidden" value="ignore_hidden"/> '.&mt('Skip hidden resources').'</label></td>'.
                   5503:               &Apache::loncommon::end_data_table_row()."\n".
                   5504:               &Apache::loncommon::start_data_table_row()."\n".
1.523     raeburn  5505:               '<td colspan="2">'."\n".
                   5506:               '<input type="hidden" name="command" value="checksubmissions" />'."\n".
1.575     www      5507:               '<input type="submit" value="'.&mt('Review Bubblesheet Data and Submission Records').'" />'."\n".
1.523     raeburn  5508:               '</td>'."\n".
                   5509:               &Apache::loncommon::end_data_table_row()."\n".
                   5510:               &Apache::loncommon::end_data_table()."\n".
                   5511:               '</form><br />');
1.457     banghart 5512:     $r->print($grading_menu_button);
1.523     raeburn  5513:     return;
1.75      albertel 5514: }
                   5515: 
1.423     albertel 5516: =pod
                   5517: 
                   5518: =item get_scantron_config
                   5519: 
                   5520:    Parse and return the scantron configuration line selected as a
                   5521:    hash of configuration file fields.
                   5522: 
                   5523:  Arguments:
                   5524:     which - the name of the configuration to parse from the file.
                   5525: 
                   5526: 
                   5527:  Returns:
                   5528:             If the named configuration is not in the file, an empty
                   5529:             hash is returned.
                   5530:     a hash with the fields
                   5531:       name         - internal name for the this configuration setup
                   5532:       description  - text to display to operator that describes this config
                   5533:       CODElocation - if 0 or the string 'none'
                   5534:                           - no CODE exists for this config
                   5535:                      if -1 || the string 'letter'
                   5536:                           - a CODE exists for this config and is
                   5537:                             a string of letters
                   5538:                      Unsupported value (but planned for future support)
                   5539:                           if a positive integer
                   5540:                                - The CODE exists as the first n items from
                   5541:                                  the question section of the form
                   5542:                           if the string 'number'
                   5543:                                - The CODE exists for this config and is
                   5544:                                  a string of numbers
                   5545:       CODEstart   - (only matter if a CODE exists) column in the line where
                   5546:                      the CODE starts
                   5547:       CODElength  - length of the CODE
1.573     bisitz   5548:       IDstart     - column where the student/employee ID starts
1.556     weissno  5549:       IDlength    - length of the student/employee ID info
1.423     albertel 5550:       Qstart      - column where the information from the bubbled
                   5551:                     'questions' start
                   5552:       Qlength     - number of columns comprising a single bubble line from
                   5553:                     the sheet. (usually either 1 or 10)
1.424     albertel 5554:       Qon         - either a single character representing the character used
1.423     albertel 5555:                     to signal a bubble was chosen in the positional setup, or
                   5556:                     the string 'letter' if the letter of the chosen bubble is
                   5557:                     in the final, or 'number' if a number representing the
                   5558:                     chosen bubble is in the file (1->A 0->J)
1.424     albertel 5559:       Qoff        - the character used to represent that a bubble was
                   5560:                     left blank
1.423     albertel 5561:       PaperID     - if the scanning process generates a unique number for each
                   5562:                     sheet scanned the column that this ID number starts in
                   5563:       PaperIDlength - number of columns that comprise the unique ID number
                   5564:                       for the sheet of paper
1.424     albertel 5565:       FirstName   - column that the first name starts in
1.423     albertel 5566:       FirstNameLength - number of columns that the first name spans
                   5567:  
                   5568:       LastName    - column that the last name starts in
                   5569:       LastNameLength - number of columns that the last name spans
                   5570: 
                   5571: =cut
1.422     foxr     5572: 
1.82      albertel 5573: sub get_scantron_config {
                   5574:     my ($which) = @_;
1.518     raeburn  5575:     my @lines = &get_scantronformat_file();
1.82      albertel 5576:     my %config;
1.157     albertel 5577:     #FIXME probably should move to XML it has already gotten a bit much now
1.518     raeburn  5578:     foreach my $line (@lines) {
1.82      albertel 5579: 	my ($name,$descrip)=split(/:/,$line);
                   5580: 	if ($name ne $which ) { next; }
                   5581: 	chomp($line);
                   5582: 	my @config=split(/:/,$line);
                   5583: 	$config{'name'}=$config[0];
                   5584: 	$config{'description'}=$config[1];
                   5585: 	$config{'CODElocation'}=$config[2];
                   5586: 	$config{'CODEstart'}=$config[3];
                   5587: 	$config{'CODElength'}=$config[4];
                   5588: 	$config{'IDstart'}=$config[5];
                   5589: 	$config{'IDlength'}=$config[6];
                   5590: 	$config{'Qstart'}=$config[7];
1.497     foxr     5591:  	$config{'Qlength'}=$config[8];
1.82      albertel 5592: 	$config{'Qoff'}=$config[9];
                   5593: 	$config{'Qon'}=$config[10];
1.157     albertel 5594: 	$config{'PaperID'}=$config[11];
                   5595: 	$config{'PaperIDlength'}=$config[12];
                   5596: 	$config{'FirstName'}=$config[13];
                   5597: 	$config{'FirstNamelength'}=$config[14];
                   5598: 	$config{'LastName'}=$config[15];
                   5599: 	$config{'LastNamelength'}=$config[16];
1.82      albertel 5600: 	last;
                   5601:     }
                   5602:     return %config;
                   5603: }
                   5604: 
1.423     albertel 5605: =pod 
                   5606: 
                   5607: =item username_to_idmap
                   5608: 
1.556     weissno  5609:     creates a hash keyed by student/employee ID with values of the corresponding
1.423     albertel 5610:     student username:domain.
                   5611: 
                   5612:   Arguments:
                   5613: 
                   5614:     $classlist - reference to the class list hash. This is a hash
                   5615:                  keyed by student name:domain  whose elements are references
1.424     albertel 5616:                  to arrays containing various chunks of information
1.423     albertel 5617:                  about the student. (See loncoursedata for more info).
                   5618: 
                   5619:   Returns
                   5620:     %idmap - the constructed hash
                   5621: 
                   5622: =cut
                   5623: 
1.82      albertel 5624: sub username_to_idmap {
                   5625:     my ($classlist)= @_;
                   5626:     my %idmap;
                   5627:     foreach my $student (keys(%$classlist)) {
                   5628: 	$idmap{$classlist->{$student}->[&Apache::loncoursedata::CL_ID]}=
                   5629: 	    $student;
                   5630:     }
                   5631:     return %idmap;
                   5632: }
1.423     albertel 5633: 
                   5634: =pod
                   5635: 
1.424     albertel 5636: =item scantron_fixup_scanline
1.423     albertel 5637: 
                   5638:    Process a requested correction to a scanline.
                   5639: 
                   5640:   Arguments:
                   5641:     $scantron_config   - hash from &get_scantron_config()
                   5642:     $scan_data         - hash of correction information 
                   5643:                           (see &scantron_getfile())
                   5644:     $line              - existing scanline
                   5645:     $whichline         - line number of the passed in scanline
                   5646:     $field             - type of change to process 
                   5647:                          (either 
1.573     bisitz   5648:                           'ID'     -> correct the student/employee ID
1.423     albertel 5649:                           'CODE'   -> correct the CODE
                   5650:                           'answer' -> fixup the submitted answers)
                   5651:     
                   5652:    $args               - hash of additional info,
                   5653:                           - 'ID' 
                   5654:                                'newid' -> studentID to use in replacement
1.424     albertel 5655:                                           of existing one
1.423     albertel 5656:                           - 'CODE' 
                   5657:                                'CODE_ignore_dup' - set to true if duplicates
                   5658:                                                    should be ignored.
                   5659: 	                       'CODE' - is new code or 'use_unfound'
1.424     albertel 5660:                                         if the existing unfound code should
1.423     albertel 5661:                                         be used as is
                   5662:                           - 'answer'
                   5663:                                'response' - new answer or 'none' if blank
                   5664:                                'question' - the bubble line to change
1.503     raeburn  5665:                                'questionnum' - the question identifier,
                   5666:                                                may include subquestion. 
1.423     albertel 5667: 
                   5668:   Returns:
                   5669:     $line - the modified scanline
                   5670: 
                   5671:   Side effects: 
                   5672:     $scan_data - may be updated
                   5673: 
                   5674: =cut
                   5675: 
1.82      albertel 5676: 
1.157     albertel 5677: sub scantron_fixup_scanline {
                   5678:     my ($scantron_config,$scan_data,$line,$whichline,$field,$args)=@_;
                   5679:     if ($field eq 'ID') {
                   5680: 	if (length($args->{'newid'}) > $$scantron_config{'IDlength'}) {
1.186     albertel 5681: 	    return ($line,1,'New value too large');
1.157     albertel 5682: 	}
                   5683: 	if (length($args->{'newid'}) < $$scantron_config{'IDlength'}) {
                   5684: 	    $args->{'newid'}=sprintf('%-'.$$scantron_config{'IDlength'}.'s',
                   5685: 				     $args->{'newid'});
                   5686: 	}
                   5687: 	substr($line,$$scantron_config{'IDstart'}-1,
                   5688: 	       $$scantron_config{'IDlength'})=$args->{'newid'};
                   5689: 	if ($args->{'newid'}=~/^\s*$/) {
                   5690: 	    &scan_data($scan_data,"$whichline.user",
                   5691: 		       $args->{'username'}.':'.$args->{'domain'});
                   5692: 	}
1.186     albertel 5693:     } elsif ($field eq 'CODE') {
1.192     albertel 5694: 	if ($args->{'CODE_ignore_dup'}) {
                   5695: 	    &scan_data($scan_data,"$whichline.CODE_ignore_dup",'1');
                   5696: 	}
                   5697: 	&scan_data($scan_data,"$whichline.useCODE",'1');
                   5698: 	if ($args->{'CODE'} ne 'use_unfound') {
1.191     albertel 5699: 	    if (length($args->{'CODE'}) > $$scantron_config{'CODElength'}) {
                   5700: 		return ($line,1,'New CODE value too large');
                   5701: 	    }
                   5702: 	    if (length($args->{'CODE'}) < $$scantron_config{'CODElength'}) {
                   5703: 		$args->{'CODE'}=sprintf('%-'.$$scantron_config{'CODElength'}.'s',$args->{'CODE'});
                   5704: 	    }
                   5705: 	    substr($line,$$scantron_config{'CODEstart'}-1,
                   5706: 		   $$scantron_config{'CODElength'})=$args->{'CODE'};
1.186     albertel 5707: 	}
1.157     albertel 5708:     } elsif ($field eq 'answer') {
1.497     foxr     5709: 	my $length=$scantron_config->{'Qlength'};
1.157     albertel 5710: 	my $off=$scantron_config->{'Qoff'};
                   5711: 	my $on=$scantron_config->{'Qon'};
1.497     foxr     5712: 	my $answer=${off}x$length;
                   5713: 	if ($args->{'response'} eq 'none') {
                   5714: 	    &scan_data($scan_data,
1.503     raeburn  5715: 		       "$whichline.no_bubble.".$args->{'questionnum'},'1');
1.497     foxr     5716: 	} else {
                   5717: 	    if ($on eq 'letter') {
                   5718: 		my @alphabet=('A'..'Z');
                   5719: 		$answer=$alphabet[$args->{'response'}];
                   5720: 	    } elsif ($on eq 'number') {
                   5721: 		$answer=$args->{'response'}+1;
                   5722: 		if ($answer == 10) { $answer = '0'; }
1.274     albertel 5723: 	    } else {
1.497     foxr     5724: 		substr($answer,$args->{'response'},1)=$on;
1.274     albertel 5725: 	    }
1.497     foxr     5726: 	    &scan_data($scan_data,
1.503     raeburn  5727: 		       "$whichline.no_bubble.".$args->{'questionnum'},undef,'1');
1.157     albertel 5728: 	}
1.497     foxr     5729: 	my $where=$length*($args->{'question'}-1)+$scantron_config->{'Qstart'};
                   5730: 	substr($line,$where-1,$length)=$answer;
1.157     albertel 5731:     }
                   5732:     return $line;
                   5733: }
1.423     albertel 5734: 
                   5735: =pod
                   5736: 
                   5737: =item scan_data
                   5738: 
                   5739:     Edit or look up  an item in the scan_data hash.
                   5740: 
                   5741:   Arguments:
                   5742:     $scan_data  - The hash (see scantron_getfile)
                   5743:     $key        - shorthand of the key to edit (actual key is
1.424     albertel 5744:                   scantronfilename_key).
1.423     albertel 5745:     $data        - New value of the hash entry.
                   5746:     $delete      - If true, the entry is removed from the hash.
                   5747: 
                   5748:   Returns:
                   5749:     The new value of the hash table field (undefined if deleted).
                   5750: 
                   5751: =cut
                   5752: 
                   5753: 
1.157     albertel 5754: sub scan_data {
                   5755:     my ($scan_data,$key,$value,$delete)=@_;
1.257     albertel 5756:     my $filename=$env{'form.scantron_selectfile'};
1.157     albertel 5757:     if (defined($value)) {
                   5758: 	$scan_data->{$filename.'_'.$key} = $value;
                   5759:     }
                   5760:     if ($delete) { delete($scan_data->{$filename.'_'.$key}); }
                   5761:     return $scan_data->{$filename.'_'.$key};
                   5762: }
1.423     albertel 5763: 
1.495     albertel 5764: # ----- These first few routines are general use routines.----
                   5765: 
                   5766: # Return the number of occurences of a pattern in a string.
                   5767: 
                   5768: sub occurence_count {
                   5769:     my ($string, $pattern) = @_;
                   5770: 
                   5771:     my @matches = ($string =~ /$pattern/g);
                   5772: 
                   5773:     return scalar(@matches);
                   5774: }
                   5775: 
                   5776: 
                   5777: # Take a string known to have digits and convert all the
                   5778: # digits into letters in the range J,A..I.
                   5779: 
                   5780: sub digits_to_letters {
                   5781:     my ($input) = @_;
                   5782: 
                   5783:     my @alphabet = ('J', 'A'..'I');
                   5784: 
                   5785:     my @input    = split(//, $input);
                   5786:     my $output ='';
                   5787:     for (my $i = 0; $i < scalar(@input); $i++) {
                   5788: 	if ($input[$i] =~ /\d/) {
                   5789: 	    $output .= $alphabet[$input[$i]];
                   5790: 	} else {
                   5791: 	    $output .= $input[$i];
                   5792: 	}
                   5793:     }
                   5794:     return $output;
                   5795: }
                   5796: 
1.423     albertel 5797: =pod 
                   5798: 
                   5799: =item scantron_parse_scanline
                   5800: 
                   5801:   Decodes a scanline from the selected scantron file
                   5802: 
                   5803:  Arguments:
                   5804:     line             - The text of the scantron file line to process
                   5805:     whichline        - Line number
                   5806:     scantron_config  - Hash describing the format of the scantron lines.
                   5807:     scan_data        - Hash of extra information about the scanline
                   5808:                        (see scantron_getfile for more information)
                   5809:     just_header      - True if should not process question answers but only
                   5810:                        the stuff to the left of the answers.
                   5811:  Returns:
                   5812:    Hash containing the result of parsing the scanline
                   5813: 
                   5814:    Keys are all proceeded by the string 'scantron.'
                   5815: 
                   5816:        CODE    - the CODE in use for this scanline
                   5817:        useCODE - 1 if the CODE is invalid but it usage has been forced
                   5818:                  by the operator
                   5819:        CODE_ignore_dup - 1 if the CODE is a duplicated use when unique
                   5820:                             CODEs were selected, but the usage has been
                   5821:                             forced by the operator
1.556     weissno  5822:        ID  - student/employee ID
1.423     albertel 5823:        PaperID - if used, the ID number printed on the sheet when the 
                   5824:                  paper was scanned
                   5825:        FirstName - first name from the sheet
                   5826:        LastName  - last name from the sheet
                   5827: 
                   5828:      if just_header was not true these key may also exist
                   5829: 
1.447     foxr     5830:        missingerror - a list of bubble ranges that are considered to be answers
                   5831:                       to a single question that don't have any bubbles filled in.
                   5832:                       Of the form questionnumber:firstbubblenumber:count.
                   5833:        doubleerror  - a list of bubble ranges that are considered to be answers
                   5834:                       to a single question that have more than one bubble filled in.
                   5835:                       Of the form questionnumber::firstbubblenumber:count
                   5836:    
                   5837:                 In the above, count is the number of bubble responses in the
                   5838:                 input line needed to represent the possible answers to the question.
                   5839:                 e.g. a radioresponse with 15 choices in an answer sheet with 10 choices
                   5840:                 per line would have count = 2.
                   5841: 
1.423     albertel 5842:        maxquest     - the number of the last bubble line that was parsed
                   5843: 
                   5844:        (<number> starts at 1)
                   5845:        <number>.answer - zero or more letters representing the selected
                   5846:                          letters from the scanline for the bubble line 
                   5847:                          <number>.
                   5848:                          if blank there was either no bubble or there where
                   5849:                          multiple bubbles, (consult the keys missingerror and
                   5850:                          doubleerror if this is an error condition)
                   5851: 
                   5852: =cut
                   5853: 
1.82      albertel 5854: sub scantron_parse_scanline {
1.423     albertel 5855:     my ($line,$whichline,$scantron_config,$scan_data,$just_header)=@_;
1.470     foxr     5856: 
1.82      albertel 5857:     my %record;
1.550     raeburn  5858:     my $lastpos = $env{'form.scantron_maxbubble'}*$$scantron_config{'Qlength'};
                   5859:     my $questions=substr($line,$$scantron_config{'Qstart'}-1,$lastpos);  # Answers
1.422     foxr     5860:     my $data=substr($line,0,$$scantron_config{'Qstart'}-1);     # earlier stuff
1.278     albertel 5861:     if (!($$scantron_config{'CODElocation'} eq 0 ||
                   5862: 	  $$scantron_config{'CODElocation'} eq 'none')) {
                   5863: 	if ($$scantron_config{'CODElocation'} < 0 ||
                   5864: 	    $$scantron_config{'CODElocation'} eq 'letter' ||
                   5865: 	    $$scantron_config{'CODElocation'} eq 'number') {
1.191     albertel 5866: 	    $record{'scantron.CODE'}=substr($data,
                   5867: 					    $$scantron_config{'CODEstart'}-1,
1.83      albertel 5868: 					    $$scantron_config{'CODElength'});
1.191     albertel 5869: 	    if (&scan_data($scan_data,"$whichline.useCODE")) {
                   5870: 		$record{'scantron.useCODE'}=1;
                   5871: 	    }
1.192     albertel 5872: 	    if (&scan_data($scan_data,"$whichline.CODE_ignore_dup")) {
                   5873: 		$record{'scantron.CODE_ignore_dup'}=1;
                   5874: 	    }
1.82      albertel 5875: 	} else {
                   5876: 	    #FIXME interpret first N questions
                   5877: 	}
                   5878:     }
1.83      albertel 5879:     $record{'scantron.ID'}=substr($data,$$scantron_config{'IDstart'}-1,
                   5880: 				  $$scantron_config{'IDlength'});
1.157     albertel 5881:     $record{'scantron.PaperID'}=
                   5882: 	substr($data,$$scantron_config{'PaperID'}-1,
                   5883: 	       $$scantron_config{'PaperIDlength'});
                   5884:     $record{'scantron.FirstName'}=
                   5885: 	substr($data,$$scantron_config{'FirstName'}-1,
                   5886: 	       $$scantron_config{'FirstNamelength'});
                   5887:     $record{'scantron.LastName'}=
                   5888: 	substr($data,$$scantron_config{'LastName'}-1,
                   5889: 	       $$scantron_config{'LastNamelength'});
1.423     albertel 5890:     if ($just_header) { return \%record; }
1.194     albertel 5891: 
1.82      albertel 5892:     my @alphabet=('A'..'Z');
                   5893:     my $questnum=0;
1.447     foxr     5894:     my $ansnum  =1;		# Multiple 'answer lines'/question.
                   5895: 
1.470     foxr     5896:     chomp($questions);		# Get rid of any trailing \n.
                   5897:     $questions =~ s/\r$//;      # Get rid of trailing \r too (MAC or Win uploads).
                   5898:     while (length($questions)) {
1.447     foxr     5899: 	my $answers_needed = $bubble_lines_per_response{$questnum};
1.503     raeburn  5900:         my $answer_length  = ($$scantron_config{'Qlength'} * $answers_needed)
                   5901:                              || 1;
                   5902:         $questnum++;
                   5903:         my $quest_id = $questnum;
                   5904:         my $currentquest = substr($questions,0,$answer_length);
                   5905:         $questions       = substr($questions,$answer_length);
                   5906:         if (length($currentquest) < $answer_length) { next; }
                   5907: 
                   5908:         if ($subdivided_bubble_lines{$questnum-1} =~ /,/) {
                   5909:             my $subquestnum = 1;
                   5910:             my $subquestions = $currentquest;
                   5911:             my @subanswers_needed = 
                   5912:                 split(/,/,$subdivided_bubble_lines{$questnum-1});  
                   5913:             foreach my $subans (@subanswers_needed) {
                   5914:                 my $subans_length =
                   5915:                     ($$scantron_config{'Qlength'} * $subans)  || 1;
                   5916:                 my $currsubquest = substr($subquestions,0,$subans_length);
                   5917:                 $subquestions   = substr($subquestions,$subans_length);
                   5918:                 $quest_id = "$questnum.$subquestnum";
                   5919:                 if (($$scantron_config{'Qon'} eq 'letter') ||
                   5920:                     ($$scantron_config{'Qon'} eq 'number')) {
                   5921:                     $ansnum = &scantron_validator_lettnum($ansnum, 
                   5922:                         $questnum,$quest_id,$subans,$currsubquest,$whichline,
                   5923:                         \@alphabet,\%record,$scantron_config,$scan_data);
                   5924:                 } else {
                   5925:                     $ansnum = &scantron_validator_positional($ansnum,
                   5926:                         $questnum,$quest_id,$subans,$currsubquest,$whichline,                        \@alphabet,\%record,$scantron_config,$scan_data);
                   5927:                 }
                   5928:                 $subquestnum ++;
                   5929:             }
                   5930:         } else {
                   5931:             if (($$scantron_config{'Qon'} eq 'letter') ||
                   5932:                 ($$scantron_config{'Qon'} eq 'number')) {
                   5933:                 $ansnum = &scantron_validator_lettnum($ansnum,$questnum,
                   5934:                     $quest_id,$answers_needed,$currentquest,$whichline,
                   5935:                     \@alphabet,\%record,$scantron_config,$scan_data);
                   5936:             } else {
                   5937:                 $ansnum = &scantron_validator_positional($ansnum,$questnum,
                   5938:                     $quest_id,$answers_needed,$currentquest,$whichline,
                   5939:                     \@alphabet,\%record,$scantron_config,$scan_data);
                   5940:             }
                   5941:         }
                   5942:     }
                   5943:     $record{'scantron.maxquest'}=$questnum;
                   5944:     return \%record;
                   5945: }
1.447     foxr     5946: 
1.503     raeburn  5947: sub scantron_validator_lettnum {
                   5948:     my ($ansnum,$questnum,$quest_id,$answers_needed,$currquest,$whichline,
                   5949:         $alphabet,$record,$scantron_config,$scan_data) = @_;
                   5950: 
                   5951:     # Qon 'letter' implies for each slot in currquest we have:
                   5952:     #    ? or * for doubles, a letter in A-Z for a bubble, and
                   5953:     #    about anything else (esp. a value of Qoff) for missing
                   5954:     #    bubbles.
                   5955:     #
                   5956:     # Qon 'number' implies each slot gives a digit that indexes the
                   5957:     #    bubbles filled, or Qoff, or a non-number for unbubbled lines,
                   5958:     #    and * or ? for double bubbles on a single line.
                   5959:     #
1.447     foxr     5960: 
1.503     raeburn  5961:     my $matchon;
                   5962:     if ($$scantron_config{'Qon'} eq 'letter') {
                   5963:         $matchon = '[A-Z]';
                   5964:     } elsif ($$scantron_config{'Qon'} eq 'number') {
                   5965:         $matchon = '\d';
                   5966:     }
                   5967:     my $occurrences = 0;
                   5968:     if (($responsetype_per_response{$questnum-1} eq 'essayresponse') ||
                   5969:         ($responsetype_per_response{$questnum-1} eq 'formularesponse') ||
1.510     raeburn  5970:         ($responsetype_per_response{$questnum-1} eq 'stringresponse') ||
                   5971:         ($responsetype_per_response{$questnum-1} eq 'imageresponse') ||
                   5972:         ($responsetype_per_response{$questnum-1} eq 'reactionresponse') ||
                   5973:         ($responsetype_per_response{$questnum-1} eq 'organicresponse')) {
1.503     raeburn  5974:         my @singlelines = split('',$currquest);
                   5975:         foreach my $entry (@singlelines) {
                   5976:             $occurrences = &occurence_count($entry,$matchon);
                   5977:             if ($occurrences > 1) {
                   5978:                 last;
                   5979:             }
                   5980:         } 
                   5981:     } else {
                   5982:         $occurrences = &occurence_count($currquest,$matchon); 
                   5983:     }
                   5984:     if (($currquest =~ /\?/ || $currquest =~ /\*/) || ($occurrences > 1)) {
                   5985:         push(@{$record->{'scantron.doubleerror'}},$quest_id);
                   5986:         for (my $ans=0; $ans<$answers_needed; $ans++) {
                   5987:             my $bubble = substr($currquest,$ans,1);
                   5988:             if ($bubble =~ /$matchon/ ) {
                   5989:                 if ($$scantron_config{'Qon'} eq 'number') {
                   5990:                     if ($bubble == 0) {
                   5991:                         $bubble = 10; 
                   5992:                     }
                   5993:                     $record->{"scantron.$ansnum.answer"} = 
                   5994:                         $alphabet->[$bubble-1];
                   5995:                 } else {
                   5996:                     $record->{"scantron.$ansnum.answer"} = $bubble;
                   5997:                 }
                   5998:             } else {
                   5999:                 $record->{"scantron.$ansnum.answer"}='';
                   6000:             }
                   6001:             $ansnum++;
                   6002:         }
                   6003:     } elsif (!defined($currquest)
                   6004:             || (&occurence_count($currquest, $$scantron_config{'Qoff'}) == length($currquest))
                   6005:             || (&occurence_count($currquest,$matchon) == 0)) {
                   6006:         for (my $ans=0; $ans<$answers_needed; $ans++ ) {
                   6007:             $record->{"scantron.$ansnum.answer"}='';
                   6008:             $ansnum++;
                   6009:         }
                   6010:         if (!&scan_data($scan_data,"$whichline.no_bubble.$quest_id")) {
                   6011:             push(@{$record->{'scantron.missingerror'}},$quest_id);
                   6012:         }
                   6013:     } else {
                   6014:         if ($$scantron_config{'Qon'} eq 'number') {
                   6015:             $currquest = &digits_to_letters($currquest);            
                   6016:         }
                   6017:         for (my $ans=0; $ans<$answers_needed; $ans++) {
                   6018:             my $bubble = substr($currquest,$ans,1);
                   6019:             $record->{"scantron.$ansnum.answer"} = $bubble;
                   6020:             $ansnum++;
                   6021:         }
                   6022:     }
                   6023:     return $ansnum;
                   6024: }
1.447     foxr     6025: 
1.503     raeburn  6026: sub scantron_validator_positional {
                   6027:     my ($ansnum,$questnum,$quest_id,$answers_needed,$currquest,
                   6028:         $whichline,$alphabet,$record,$scantron_config,$scan_data) = @_;
1.447     foxr     6029: 
1.503     raeburn  6030:     # Otherwise there's a positional notation;
                   6031:     # each bubble line requires Qlength items, and there are filled in
                   6032:     # bubbles for each case where there 'Qon' characters.
                   6033:     #
1.447     foxr     6034: 
1.503     raeburn  6035:     my @array=split($$scantron_config{'Qon'},$currquest,-1);
1.447     foxr     6036: 
1.503     raeburn  6037:     # If the split only gives us one element.. the full length of the
                   6038:     # answer string, no bubbles are filled in:
1.447     foxr     6039: 
1.507     raeburn  6040:     if ($answers_needed eq '') {
                   6041:         return;
                   6042:     }
                   6043: 
1.503     raeburn  6044:     if (length($array[0]) eq $$scantron_config{'Qlength'}*$answers_needed) {
                   6045:         for (my $ans=0; $ans<$answers_needed; $ans++ ) {
                   6046:             $record->{"scantron.$ansnum.answer"}='';
                   6047:             $ansnum++;
                   6048:         }
                   6049:         if (!&scan_data($scan_data,"$whichline.no_bubble.$quest_id")) {
                   6050:             push(@{$record->{"scantron.missingerror"}},$quest_id);
                   6051:         }
                   6052:     } elsif (scalar(@array) == 2) {
                   6053:         my $location = length($array[0]);
                   6054:         my $line_num = int($location / $$scantron_config{'Qlength'});
                   6055:         my $bubble   = $alphabet->[$location % $$scantron_config{'Qlength'}];
                   6056:         for (my $ans=0; $ans<$answers_needed; $ans++) {
                   6057:             if ($ans eq $line_num) {
                   6058:                 $record->{"scantron.$ansnum.answer"} = $bubble;
                   6059:             } else {
                   6060:                 $record->{"scantron.$ansnum.answer"} = ' ';
                   6061:             }
                   6062:             $ansnum++;
                   6063:          }
                   6064:     } else {
                   6065:         #  If there's more than one instance of a bubble character
                   6066:         #  That's a double bubble; with positional notation we can
                   6067:         #  record all the bubbles filled in as well as the
                   6068:         #  fact this response consists of multiple bubbles.
                   6069:         #
                   6070:         if (($responsetype_per_response{$questnum-1} eq 'essayresponse') ||
                   6071:             ($responsetype_per_response{$questnum-1} eq 'formularesponse') ||
1.510     raeburn  6072:             ($responsetype_per_response{$questnum-1} eq 'stringresponse') ||
                   6073:             ($responsetype_per_response{$questnum-1} eq 'imageresponse') ||
                   6074:             ($responsetype_per_response{$questnum-1} eq 'reactionresponse') ||
                   6075:             ($responsetype_per_response{$questnum-1} eq 'organicresponse')) {
1.503     raeburn  6076:             my $doubleerror = 0;
                   6077:             while (($currquest >= $$scantron_config{'Qlength'}) && 
                   6078:                    (!$doubleerror)) {
                   6079:                my $currline = substr($currquest,0,$$scantron_config{'Qlength'});
                   6080:                $currquest = substr($currquest,$$scantron_config{'Qlength'});
                   6081:                my @currarray = split($$scantron_config{'Qon'},$currline,-1);
                   6082:                if (length(@currarray) > 2) {
                   6083:                    $doubleerror = 1;
                   6084:                } 
                   6085:             }
                   6086:             if ($doubleerror) {
                   6087:                 push(@{$record->{'scantron.doubleerror'}},$quest_id);
                   6088:             }
                   6089:         } else {
                   6090:             push(@{$record->{'scantron.doubleerror'}},$quest_id);
                   6091:         }
                   6092:         my $item = $ansnum;
                   6093:         for (my $ans=0; $ans<$answers_needed; $ans++) {
                   6094:             $record->{"scantron.$item.answer"} = '';
                   6095:             $item ++;
                   6096:         }
1.447     foxr     6097: 
1.503     raeburn  6098:         my @ans=@array;
                   6099:         my $i=0;
                   6100:         my $increment = 0;
                   6101:         while ($#ans) {
                   6102:             $i+=length($ans[0]) + $increment;
                   6103:             my $line   = int($i/$$scantron_config{'Qlength'} + $ansnum);
                   6104:             my $bubble = $i%$$scantron_config{'Qlength'};
                   6105:             $record->{"scantron.$line.answer"}.=$alphabet->[$bubble];
                   6106:             shift(@ans);
                   6107:             $increment = 1;
                   6108:         }
                   6109:         $ansnum += $answers_needed;
1.82      albertel 6110:     }
1.503     raeburn  6111:     return $ansnum;
1.82      albertel 6112: }
                   6113: 
1.423     albertel 6114: =pod
                   6115: 
                   6116: =item scantron_add_delay
                   6117: 
                   6118:    Adds an error message that occurred during the grading phase to a
                   6119:    queue of messages to be shown after grading pass is complete
                   6120: 
                   6121:  Arguments:
1.424     albertel 6122:    $delayqueue  - arrary ref of hash ref of error messages
1.423     albertel 6123:    $scanline    - the scanline that caused the error
                   6124:    $errormesage - the error message
                   6125:    $errorcode   - a numeric code for the error
                   6126: 
                   6127:  Side Effects:
1.424     albertel 6128:    updates the $delayqueue to have a new hash ref of the error
1.423     albertel 6129: 
                   6130: =cut
                   6131: 
1.82      albertel 6132: sub scantron_add_delay {
1.140     albertel 6133:     my ($delayqueue,$scanline,$errormessage,$errorcode)=@_;
                   6134:     push(@$delayqueue,
                   6135: 	 {'line' => $scanline, 'emsg' => $errormessage,
                   6136: 	  'ecode' => $errorcode }
                   6137: 	 );
1.82      albertel 6138: }
                   6139: 
1.423     albertel 6140: =pod
                   6141: 
                   6142: =item scantron_find_student
                   6143: 
1.424     albertel 6144:    Finds the username for the current scanline
                   6145: 
                   6146:   Arguments:
                   6147:    $scantron_record - hash result from scantron_parse_scanline
                   6148:    $scan_data       - hash of correction information 
                   6149:                       (see &scantron_getfile() form more information)
                   6150:    $idmap           - hash from &username_to_idmap()
                   6151:    $line            - number of current scanline
                   6152:  
                   6153:   Returns:
                   6154:    Either 'username:domain' or undef if unknown
                   6155: 
1.423     albertel 6156: =cut
                   6157: 
1.82      albertel 6158: sub scantron_find_student {
1.157     albertel 6159:     my ($scantron_record,$scan_data,$idmap,$line)=@_;
1.83      albertel 6160:     my $scanID=$$scantron_record{'scantron.ID'};
1.157     albertel 6161:     if ($scanID =~ /^\s*$/) {
                   6162:  	return &scan_data($scan_data,"$line.user");
                   6163:     }
1.83      albertel 6164:     foreach my $id (keys(%$idmap)) {
1.157     albertel 6165:  	if (lc($id) eq lc($scanID)) {
                   6166:  	    return $$idmap{$id};
                   6167:  	}
1.83      albertel 6168:     }
                   6169:     return undef;
                   6170: }
                   6171: 
1.423     albertel 6172: =pod
                   6173: 
                   6174: =item scantron_filter
                   6175: 
1.424     albertel 6176:    Filter sub for lonnavmaps, filters out hidden resources if ignore
                   6177:    hidden resources was selected
                   6178: 
1.423     albertel 6179: =cut
                   6180: 
1.83      albertel 6181: sub scantron_filter {
                   6182:     my ($curres)=@_;
1.331     albertel 6183: 
                   6184:     if (ref($curres) && $curres->is_problem()) {
                   6185: 	# if the user has asked to not have either hidden
                   6186: 	# or 'randomout' controlled resources to be graded
                   6187: 	# don't include them
                   6188: 	if ($env{'form.scantron_options_hidden'} eq 'ignore_hidden'
                   6189: 	    && $curres->randomout) {
                   6190: 	    return 0;
                   6191: 	}
1.83      albertel 6192: 	return 1;
                   6193:     }
                   6194:     return 0;
1.82      albertel 6195: }
                   6196: 
1.423     albertel 6197: =pod
                   6198: 
                   6199: =item scantron_process_corrections
                   6200: 
1.424     albertel 6201:    Gets correction information out of submitted form data and corrects
                   6202:    the scanline
                   6203: 
1.423     albertel 6204: =cut
                   6205: 
1.157     albertel 6206: sub scantron_process_corrections {
                   6207:     my ($r) = @_;
1.257     albertel 6208:     my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
1.157     albertel 6209:     my ($scanlines,$scan_data)=&scantron_getfile();
                   6210:     my $classlist=&Apache::loncoursedata::get_classlist();
1.257     albertel 6211:     my $which=$env{'form.scantron_line'};
1.200     albertel 6212:     my $line=&scantron_get_line($scanlines,$scan_data,$which);
1.157     albertel 6213:     my ($skip,$err,$errmsg);
1.257     albertel 6214:     if ($env{'form.scantron_skip_record'}) {
1.157     albertel 6215: 	$skip=1;
1.257     albertel 6216:     } elsif ($env{'form.scantron_corrections'} =~ /^(duplicate|incorrect)ID$/) {
                   6217: 	my $newstudent=$env{'form.scantron_username'}.':'.
                   6218: 	    $env{'form.scantron_domain'};
1.157     albertel 6219: 	my $newid=$classlist->{$newstudent}->[&Apache::loncoursedata::CL_ID];
                   6220: 	($line,$err,$errmsg)=
                   6221: 	    &scantron_fixup_scanline(\%scantron_config,$scan_data,$line,$which,
                   6222: 				     'ID',{'newid'=>$newid,
1.257     albertel 6223: 				    'username'=>$env{'form.scantron_username'},
                   6224: 				    'domain'=>$env{'form.scantron_domain'}});
                   6225:     } elsif ($env{'form.scantron_corrections'} =~ /^(duplicate|incorrect)CODE$/) {
                   6226: 	my $resolution=$env{'form.scantron_CODE_resolution'};
1.190     albertel 6227: 	my $newCODE;
1.192     albertel 6228: 	my %args;
1.190     albertel 6229: 	if      ($resolution eq 'use_unfound') {
1.191     albertel 6230: 	    $newCODE='use_unfound';
1.190     albertel 6231: 	} elsif ($resolution eq 'use_found') {
1.257     albertel 6232: 	    $newCODE=$env{'form.scantron_CODE_selectedvalue'};
1.190     albertel 6233: 	} elsif ($resolution eq 'use_typed') {
1.257     albertel 6234: 	    $newCODE=$env{'form.scantron_CODE_newvalue'};
1.194     albertel 6235: 	} elsif ($resolution =~ /^use_closest_(\d+)/) {
1.257     albertel 6236: 	    $newCODE=$env{"form.scantron_CODE_closest_$1"};
1.190     albertel 6237: 	}
1.257     albertel 6238: 	if ($env{'form.scantron_corrections'} eq 'duplicateCODE') {
1.192     albertel 6239: 	    $args{'CODE_ignore_dup'}=1;
                   6240: 	}
                   6241: 	$args{'CODE'}=$newCODE;
1.186     albertel 6242: 	($line,$err,$errmsg)=
                   6243: 	    &scantron_fixup_scanline(\%scantron_config,$scan_data,$line,$which,
1.192     albertel 6244: 				     'CODE',\%args);
1.257     albertel 6245:     } elsif ($env{'form.scantron_corrections'} =~ /^(missing|double)bubble$/) {
                   6246: 	foreach my $question (split(',',$env{'form.scantron_questions'})) {
1.157     albertel 6247: 	    ($line,$err,$errmsg)=
                   6248: 		&scantron_fixup_scanline(\%scantron_config,$scan_data,$line,
                   6249: 					 $which,'answer',
                   6250: 					 { 'question'=>$question,
1.503     raeburn  6251: 		      		   'response'=>$env{"form.scantron_correct_Q_$question"},
                   6252:                                    'questionnum'=>$env{"form.scantron_questionnum_Q_$question"}});
1.157     albertel 6253: 	    if ($err) { last; }
                   6254: 	}
                   6255:     }
                   6256:     if ($err) {
1.398     albertel 6257: 	$r->print("<span class=\"LC_warning\">Unable to accept last correction, an error occurred :$errmsg:</span>");
1.157     albertel 6258:     } else {
1.200     albertel 6259: 	&scantron_put_line($scanlines,$scan_data,$which,$line,$skip);
1.157     albertel 6260: 	&scantron_putfile($scanlines,$scan_data);
                   6261:     }
                   6262: }
                   6263: 
1.423     albertel 6264: =pod
                   6265: 
                   6266: =item reset_skipping_status
                   6267: 
1.424     albertel 6268:    Forgets the current set of remember skipped scanlines (and thus
                   6269:    reverts back to considering all lines in the
                   6270:    scantron_skipped_<filename> file)
                   6271: 
1.423     albertel 6272: =cut
                   6273: 
1.200     albertel 6274: sub reset_skipping_status {
                   6275:     my ($scanlines,$scan_data)=&scantron_getfile();
                   6276:     &scan_data($scan_data,'remember_skipping',undef,1);
                   6277:     &scantron_putfile(undef,$scan_data);
                   6278: }
                   6279: 
1.423     albertel 6280: =pod
                   6281: 
                   6282: =item start_skipping
                   6283: 
1.424     albertel 6284:    Marks a scanline to be skipped. 
                   6285: 
1.423     albertel 6286: =cut
                   6287: 
1.376     albertel 6288: sub start_skipping {
1.200     albertel 6289:     my ($scan_data,$i)=@_;
                   6290:     my %remembered=split(':',&scan_data($scan_data,'remember_skipping'));
1.376     albertel 6291:     if ($env{'form.scantron_options_redo'} =~ /^redo_/) {
                   6292: 	$remembered{$i}=2;
                   6293:     } else {
                   6294: 	$remembered{$i}=1;
                   6295:     }
1.200     albertel 6296:     &scan_data($scan_data,'remember_skipping',join(':',%remembered));
                   6297: }
                   6298: 
1.423     albertel 6299: =pod
                   6300: 
                   6301: =item should_be_skipped
                   6302: 
1.424     albertel 6303:    Checks whether a scanline should be skipped.
                   6304: 
1.423     albertel 6305: =cut
                   6306: 
1.200     albertel 6307: sub should_be_skipped {
1.376     albertel 6308:     my ($scanlines,$scan_data,$i)=@_;
1.257     albertel 6309:     if ($env{'form.scantron_options_redo'} !~ /^redo_/) {
1.200     albertel 6310: 	# not redoing old skips
1.376     albertel 6311: 	if ($scanlines->{'skipped'}[$i]) { return 1; }
1.200     albertel 6312: 	return 0;
                   6313:     }
                   6314:     my %remembered=split(':',&scan_data($scan_data,'remember_skipping'));
1.376     albertel 6315: 
                   6316:     if (exists($remembered{$i}) && $remembered{$i} != 2 ) {
                   6317: 	return 0;
                   6318:     }
1.200     albertel 6319:     return 1;
                   6320: }
                   6321: 
1.423     albertel 6322: =pod
                   6323: 
                   6324: =item remember_current_skipped
                   6325: 
1.424     albertel 6326:    Discovers what scanlines are in the scantron_skipped_<filename>
                   6327:    file and remembers them into scan_data for later use.
                   6328: 
1.423     albertel 6329: =cut
                   6330: 
1.200     albertel 6331: sub remember_current_skipped {
                   6332:     my ($scanlines,$scan_data)=&scantron_getfile();
                   6333:     my %to_remember;
                   6334:     for (my $i=0;$i<=$scanlines->{'count'};$i++) {
                   6335: 	if ($scanlines->{'skipped'}[$i]) {
                   6336: 	    $to_remember{$i}=1;
                   6337: 	}
                   6338:     }
1.376     albertel 6339: 
1.200     albertel 6340:     &scan_data($scan_data,'remember_skipping',join(':',%to_remember));
                   6341:     &scantron_putfile(undef,$scan_data);
                   6342: }
                   6343: 
1.423     albertel 6344: =pod
                   6345: 
                   6346: =item check_for_error
                   6347: 
1.424     albertel 6348:     Checks if there was an error when attempting to remove a specific
1.596.2.6  raeburn  6349:     scantron_.. bubblesheet data file. Prints out an error if
1.424     albertel 6350:     something went wrong.
                   6351: 
1.423     albertel 6352: =cut
                   6353: 
1.200     albertel 6354: sub check_for_error {
                   6355:     my ($r,$result)=@_;
                   6356:     if ($result ne 'ok' && $result ne 'not_found' ) {
1.492     albertel 6357: 	$r->print(&mt("An error occurred ([_1]) when trying to remove the existing corrections.",$result));
1.200     albertel 6358:     }
                   6359: }
1.157     albertel 6360: 
1.423     albertel 6361: =pod
                   6362: 
                   6363: =item scantron_warning_screen
                   6364: 
1.424     albertel 6365:    Interstitial screen to make sure the operator has selected the
                   6366:    correct options before we start the validation phase.
                   6367: 
1.423     albertel 6368: =cut
                   6369: 
1.203     albertel 6370: sub scantron_warning_screen {
                   6371:     my ($button_text)=@_;
1.257     albertel 6372:     my $title=&Apache::lonnet::gettitle($env{'form.selectpage'});
1.284     albertel 6373:     my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
1.373     albertel 6374:     my $CODElist;
1.284     albertel 6375:     if ($scantron_config{'CODElocation'} &&
                   6376: 	$scantron_config{'CODEstart'} &&
                   6377: 	$scantron_config{'CODElength'}) {
                   6378: 	$CODElist=$env{'form.scantron_CODElist'};
1.398     albertel 6379: 	if ($env{'form.scantron_CODElist'} eq '') { $CODElist='<span class="LC_warning">None</span>'; }
1.284     albertel 6380: 	$CODElist=
1.492     albertel 6381: 	    '<tr><td><b>'.&mt('List of CODES to validate against:').'</b></td><td><tt>'.
1.373     albertel 6382: 	    $env{'form.scantron_CODElist'}.'</tt></td></tr>';
1.284     albertel 6383:     }
1.492     albertel 6384:     return ('
1.203     albertel 6385: <p>
1.492     albertel 6386: <span class="LC_warning">
                   6387: '.&mt('Please double check the information below before clicking on \'[_1]\'',&mt($button_text)).'</span>
1.203     albertel 6388: </p>
                   6389: <table>
1.492     albertel 6390: <tr><td><b>'.&mt('Sequence to be Graded:').'</b></td><td>'.$title.'</td></tr>
                   6391: <tr><td><b>'.&mt('Data File that will be used:').'</b></td><td><tt>'.$env{'form.scantron_selectfile'}.'</tt></td></tr>
                   6392: '.$CODElist.'
1.203     albertel 6393: </table>
                   6394: <br />
1.492     albertel 6395: <p> '.&mt('If this information is correct, please click on \'[_1]\'.',&mt($button_text)).'</p>
                   6396: <p> '.&mt('If something is incorrect, please click the \'Grading Menu\' button to start over.').'</p>
1.203     albertel 6397: 
                   6398: <br />
1.492     albertel 6399: ');
1.203     albertel 6400: }
                   6401: 
1.423     albertel 6402: =pod
                   6403: 
                   6404: =item scantron_do_warning
                   6405: 
1.424     albertel 6406:    Check if the operator has picked something for all required
                   6407:    fields. Error out if something is missing.
                   6408: 
1.423     albertel 6409: =cut
                   6410: 
1.203     albertel 6411: sub scantron_do_warning {
                   6412:     my ($r)=@_;
1.324     albertel 6413:     my ($symb)=&get_symb($r);
1.203     albertel 6414:     if (!$symb) {return '';}
1.324     albertel 6415:     my $default_form_data=&defaultFormData($symb);
1.203     albertel 6416:     $r->print(&scantron_form_start().$default_form_data);
1.257     albertel 6417:     if ( $env{'form.selectpage'} eq '' ||
                   6418: 	 $env{'form.scantron_selectfile'} eq '' ||
                   6419: 	 $env{'form.scantron_format'} eq '' ) {
1.596.2.4  raeburn  6420: 	$r->print("<p>".&mt('You have forgotten to specify some information. Please go Back and try again.')."</p>");
1.257     albertel 6421: 	if ( $env{'form.selectpage'} eq '') {
1.492     albertel 6422: 	    $r->print('<p><span class="LC_error">'.&mt('You have not selected a Sequence to grade').'</span></p>');
1.237     albertel 6423: 	} 
1.257     albertel 6424: 	if ( $env{'form.scantron_selectfile'} eq '') {
1.596.2.4  raeburn  6425: 	    $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 6426: 	} 
1.257     albertel 6427: 	if ( $env{'form.scantron_format'} eq '') {
1.596.2.5  raeburn  6428: 	    $r->print('<p><span class="LC_error">'.&mt("You have not selected the format of the student's response data.").'</span></p>');
1.237     albertel 6429: 	} 
                   6430:     } else {
1.265     www      6431: 	my $warning=&scantron_warning_screen('Grading: Validate Records');
1.492     albertel 6432: 	$r->print('
                   6433: '.$warning.'
                   6434: <input type="submit" name="submit" value="'.&mt('Grading: Validate Records').'" />
1.203     albertel 6435: <input type="hidden" name="command" value="scantron_validate" />
1.492     albertel 6436: ');
1.237     albertel 6437:     }
1.352     albertel 6438:     $r->print("</form><br />".&show_grading_menu_form($symb));
1.203     albertel 6439:     return '';
                   6440: }
                   6441: 
1.423     albertel 6442: =pod
                   6443: 
                   6444: =item scantron_form_start
                   6445: 
1.424     albertel 6446:     html hidden input for remembering all selected grading options
                   6447: 
1.423     albertel 6448: =cut
                   6449: 
1.203     albertel 6450: sub scantron_form_start {
                   6451:     my ($max_bubble)=@_;
                   6452:     my $result= <<SCANTRONFORM;
                   6453: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="scantronupload">
1.257     albertel 6454:   <input type="hidden" name="selectpage" value="$env{'form.selectpage'}" />
                   6455:   <input type="hidden" name="scantron_format" value="$env{'form.scantron_format'}" />
                   6456:   <input type="hidden" name="scantron_selectfile" value="$env{'form.scantron_selectfile'}" />
1.218     albertel 6457:   <input type="hidden" name="scantron_maxbubble" value="$max_bubble" />
1.257     albertel 6458:   <input type="hidden" name="scantron_CODElist" value="$env{'form.scantron_CODElist'}" />
                   6459:   <input type="hidden" name="scantron_CODEunique" value="$env{'form.scantron_CODEunique'}" />
                   6460:   <input type="hidden" name="scantron_options_redo" value="$env{'form.scantron_options_redo'}" />
                   6461:   <input type="hidden" name="scantron_options_ignore" value="$env{'form.scantron_options_ignore'}" />
1.331     albertel 6462:   <input type="hidden" name="scantron_options_hidden" value="$env{'form.scantron_options_hidden'}" />
1.203     albertel 6463: SCANTRONFORM
1.447     foxr     6464: 
                   6465:   my $line = 0;
                   6466:     while (defined($env{"form.scantron.bubblelines.$line"})) {
                   6467:        my $chunk =
                   6468: 	   '<input type="hidden" name="scantron.bubblelines.'.$line.'" value="'.$env{"form.scantron.bubblelines.$line"}.'" />'."\n";
1.448     foxr     6469:        $chunk .=
                   6470: 	   '<input type="hidden" name="scantron.first_bubble_line.'.$line.'" value="'.$env{"form.scantron.first_bubble_line.$line"}.'" />'."\n";
1.503     raeburn  6471:        $chunk .= 
                   6472:            '<input type="hidden" name="scantron.sub_bubblelines.'.$line.'" value="'.$env{"form.scantron.sub_bubblelines.$line"}.'" />'."\n";
1.504     raeburn  6473:        $chunk .=
                   6474:            '<input type="hidden" name="scantron.responsetype.'.$line.'" value="'.$env{"form.scantron.responsetype.$line"}.'" />'."\n";
1.447     foxr     6475:        $result .= $chunk;
                   6476:        $line++;
                   6477:    }
1.203     albertel 6478:     return $result;
                   6479: }
                   6480: 
1.423     albertel 6481: =pod
                   6482: 
                   6483: =item scantron_validate_file
                   6484: 
1.596.2.6  raeburn  6485:     Dispatch routine for doing validation of a bubblesheet data file.
1.424     albertel 6486: 
                   6487:     Also processes any necessary information resets that need to
                   6488:     occur before validation begins (ignore previous corrections,
                   6489:     restarting the skipped records processing)
                   6490: 
1.423     albertel 6491: =cut
                   6492: 
1.157     albertel 6493: sub scantron_validate_file {
                   6494:     my ($r) = @_;
1.324     albertel 6495:     my ($symb)=&get_symb($r);
1.157     albertel 6496:     if (!$symb) {return '';}
1.324     albertel 6497:     my $default_form_data=&defaultFormData($symb);
1.200     albertel 6498:     
                   6499:     # do the detection of only doing skipped records first befroe we delete
1.424     albertel 6500:     # them when doing the corrections reset
1.257     albertel 6501:     if ($env{'form.scantron_options_redo'} ne 'redo_skipped_ready') {
1.200     albertel 6502: 	&reset_skipping_status();
                   6503:     }
1.257     albertel 6504:     if ($env{'form.scantron_options_redo'} eq 'redo_skipped') {
1.200     albertel 6505: 	&remember_current_skipped();
1.257     albertel 6506: 	$env{'form.scantron_options_redo'}='redo_skipped_ready';
1.200     albertel 6507:     }
                   6508: 
1.257     albertel 6509:     if ($env{'form.scantron_options_ignore'} eq 'ignore_corrections') {
1.200     albertel 6510: 	&check_for_error($r,&scantron_remove_file('corrected'));
                   6511: 	&check_for_error($r,&scantron_remove_file('skipped'));
                   6512: 	&check_for_error($r,&scantron_remove_scan_data());
1.257     albertel 6513: 	$env{'form.scantron_options_ignore'}='done';
1.192     albertel 6514:     }
1.200     albertel 6515: 
1.257     albertel 6516:     if ($env{'form.scantron_corrections'}) {
1.157     albertel 6517: 	&scantron_process_corrections($r);
                   6518:     }
1.503     raeburn  6519:     $r->print('<p>'.&mt('Gathering necessary information.').'</p>');$r->rflush();
1.157     albertel 6520:     #get the student pick code ready
                   6521:     $r->print(&Apache::loncommon::studentbrowser_javascript());
1.582     raeburn  6522:     my $nav_error;
                   6523:     my $max_bubble=&scantron_get_maxbubble(\$nav_error);
                   6524:     if ($nav_error) {
                   6525:         $r->print(&navmap_errormsg());
                   6526:         return '';
                   6527:     }
1.203     albertel 6528:     my $result=&scantron_form_start($max_bubble).$default_form_data;
1.157     albertel 6529:     $r->print($result);
                   6530:     
1.334     albertel 6531:     my @validate_phases=( 'sequence',
                   6532: 			  'ID',
1.157     albertel 6533: 			  'CODE',
                   6534: 			  'doublebubble',
                   6535: 			  'missingbubbles');
1.257     albertel 6536:     if (!$env{'form.validatepass'}) {
                   6537: 	$env{'form.validatepass'} = 0;
1.157     albertel 6538:     }
1.257     albertel 6539:     my $currentphase=$env{'form.validatepass'};
1.157     albertel 6540: 
1.448     foxr     6541: 
1.157     albertel 6542:     my $stop=0;
                   6543:     while (!$stop && $currentphase < scalar(@validate_phases)) {
1.503     raeburn  6544: 	$r->print(&mt('Validating '.$validate_phases[$currentphase]).'<br />');
1.157     albertel 6545: 	$r->rflush();
                   6546: 	my $which="scantron_validate_".$validate_phases[$currentphase];
                   6547: 	{
                   6548: 	    no strict 'refs';
                   6549: 	    ($stop,$currentphase)=&$which($r,$currentphase);
                   6550: 	}
                   6551:     }
                   6552:     if (!$stop) {
1.203     albertel 6553: 	my $warning=&scantron_warning_screen('Start Grading');
1.542     raeburn  6554: 	$r->print(&mt('Validation process complete.').'<br />'.
                   6555:                   $warning.
                   6556:                   &mt('Perform verification for each student after storage of submissions?').
                   6557:                   '&nbsp;<span class="LC_nobreak"><label>'.
                   6558:                   '<input type="radio" name="verifyrecord" value="1" />'.&mt('Yes').'</label>'.
                   6559:                   ('&nbsp;'x3).'<label>'.
                   6560:                   '<input type="radio" name="verifyrecord" value="0" checked="checked" />'.&mt('No').
                   6561:                   '</label></span><br />'.
                   6562:                   &mt('Grading will take longer if you use verification.').'<br />'.
1.572     www      6563:                   &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  6564:                   '<input type="submit" name="submit" value="'.&mt('Start Grading').'" />'.
                   6565:                   '<input type="hidden" name="command" value="scantron_process" />'."\n");
1.157     albertel 6566:     } else {
                   6567: 	$r->print('<input type="hidden" name="command" value="scantron_validate" />');
                   6568: 	$r->print("<input type='hidden' name='validatepass' value='".$currentphase."' />");
                   6569:     }
                   6570:     if ($stop) {
1.334     albertel 6571: 	if ($validate_phases[$currentphase] eq 'sequence') {
1.539     riegler  6572: 	    $r->print('<input type="submit" name="submit" value="'.&mt('Ignore').' &rarr; " />');
1.492     albertel 6573: 	    $r->print(' '.&mt('this error').' <br />');
1.334     albertel 6574: 
1.492     albertel 6575: 	    $r->print(" <p>".&mt("Or click the 'Grading Menu' button to start over.")."</p>");
1.334     albertel 6576: 	} else {
1.503     raeburn  6577:             if ($validate_phases[$currentphase] eq 'doublebubble' || $validate_phases[$currentphase] eq 'missingbubbles') {
1.539     riegler  6578: 	        $r->print('<input type="button" name="submitbutton" value="'.&mt('Continue').' &rarr;" onclick="javascript:verify_bubble_radio(this.form)" />');
1.503     raeburn  6579:             } else {
1.539     riegler  6580:                 $r->print('<input type="submit" name="submit" value="'.&mt('Continue').' &rarr;" />');
1.503     raeburn  6581:             }
1.492     albertel 6582: 	    $r->print(' '.&mt('using corrected info').' <br />');
                   6583: 	    $r->print("<input type='submit' value='".&mt("Skip")."' name='scantron_skip_record' />");
                   6584: 	    $r->print(" ".&mt("this scanline saving it for later."));
1.334     albertel 6585: 	}
1.157     albertel 6586:     }
1.352     albertel 6587:     $r->print(" </form><br />".&show_grading_menu_form($symb));
1.157     albertel 6588:     return '';
                   6589: }
                   6590: 
1.423     albertel 6591: 
                   6592: =pod
                   6593: 
                   6594: =item scantron_remove_file
                   6595: 
1.596.2.6  raeburn  6596:    Removes the requested bubblesheet data file, makes sure that
1.424     albertel 6597:    scantron_original_<filename> is never removed
                   6598: 
                   6599: 
1.423     albertel 6600: =cut
                   6601: 
1.200     albertel 6602: sub scantron_remove_file {
1.192     albertel 6603:     my ($which)=@_;
1.257     albertel 6604:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   6605:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1.192     albertel 6606:     my $file='scantron_';
1.200     albertel 6607:     if ($which eq 'corrected' || $which eq 'skipped') {
                   6608: 	$file.=$which.'_';
1.192     albertel 6609:     } else {
                   6610: 	return 'refused';
                   6611:     }
1.257     albertel 6612:     $file.=$env{'form.scantron_selectfile'};
1.200     albertel 6613:     return &Apache::lonnet::removeuserfile($cname,$cdom,$file);
                   6614: }
                   6615: 
1.423     albertel 6616: 
                   6617: =pod
                   6618: 
                   6619: =item scantron_remove_scan_data
                   6620: 
1.596.2.6  raeburn  6621:    Removes all scan_data correction for the requested bubblesheet
1.424     albertel 6622:    data file.  (In the case that both the are doing skipped records we need
                   6623:    to remember the old skipped lines for the time being so that element
                   6624:    persists for a while.)
                   6625: 
1.423     albertel 6626: =cut
                   6627: 
1.200     albertel 6628: sub scantron_remove_scan_data {
1.257     albertel 6629:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   6630:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1.192     albertel 6631:     my @keys=&Apache::lonnet::getkeys('nohist_scantrondata',$cdom,$cname);
                   6632:     my @todelete;
1.257     albertel 6633:     my $filename=$env{'form.scantron_selectfile'};
1.192     albertel 6634:     foreach my $key (@keys) {
                   6635: 	if ($key=~/^\Q$filename\E_/) {
1.257     albertel 6636: 	    if ($env{'form.scantron_options_redo'} eq 'redo_skipped_ready' &&
1.200     albertel 6637: 		$key=~/remember_skipping/) {
                   6638: 		next;
                   6639: 	    }
1.192     albertel 6640: 	    push(@todelete,$key);
                   6641: 	}
                   6642:     }
1.200     albertel 6643:     my $result;
1.192     albertel 6644:     if (@todelete) {
1.491     albertel 6645: 	$result = &Apache::lonnet::del('nohist_scantrondata',
                   6646: 				       \@todelete,$cdom,$cname);
                   6647:     } else {
                   6648: 	$result = 'ok';
1.192     albertel 6649:     }
                   6650:     return $result;
                   6651: }
                   6652: 
1.423     albertel 6653: 
                   6654: =pod
                   6655: 
                   6656: =item scantron_getfile
                   6657: 
1.596.2.6  raeburn  6658:     Fetches the requested bubblesheet data file (all 3 versions), and
1.424     albertel 6659:     the scan_data hash
                   6660:   
                   6661:   Arguments:
                   6662:     None
                   6663: 
                   6664:   Returns:
                   6665:     2 hash references
                   6666: 
                   6667:      - first one has 
                   6668:          orig      -
                   6669:          corrected -
                   6670:          skipped   -  each of which points to an array ref of the specified
                   6671:                       file broken up into individual lines
                   6672:          count     - number of scanlines
                   6673:  
                   6674:      - second is the scan_data hash possible keys are
1.425     albertel 6675:        ($number refers to scanline numbered $number and thus the key affects
                   6676:         only that scanline
                   6677:         $bubline refers to the specific bubble line element and the aspects
                   6678:         refers to that specific bubble line element)
                   6679: 
                   6680:        $number.user - username:domain to use
                   6681:        $number.CODE_ignore_dup 
                   6682:                     - ignore the duplicate CODE error 
                   6683:        $number.useCODE
                   6684:                     - use the CODE in the scanline as is
                   6685:        $number.no_bubble.$bubline
                   6686:                     - it is valid that there is no bubbled in bubble
                   6687:                       at $number $bubline
                   6688:        remember_skipping
                   6689:                     - a frozen hash containing keys of $number and values
                   6690:                       of either 
                   6691:                         1 - we are on a 'do skipped records pass' and plan
                   6692:                             on processing this line
                   6693:                         2 - we are on a 'do skipped records pass' and this
                   6694:                             scanline has been marked to skip yet again
1.424     albertel 6695: 
1.423     albertel 6696: =cut
                   6697: 
1.157     albertel 6698: sub scantron_getfile {
1.200     albertel 6699:     #FIXME really would prefer a scantron directory
1.257     albertel 6700:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   6701:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1.157     albertel 6702:     my $lines;
                   6703:     $lines=&Apache::lonnet::getfile('/uploaded/'.$cdom.'/'.$cname.'/'.
1.257     albertel 6704: 		       'scantron_orig_'.$env{'form.scantron_selectfile'});
1.157     albertel 6705:     my %scanlines;
                   6706:     $scanlines{'orig'}=[(split("\n",$lines,-1))];
                   6707:     my $temp=$scanlines{'orig'};
                   6708:     $scanlines{'count'}=$#$temp;
                   6709: 
                   6710:     $lines=&Apache::lonnet::getfile('/uploaded/'.$cdom.'/'.$cname.'/'.
1.257     albertel 6711: 		       'scantron_corrected_'.$env{'form.scantron_selectfile'});
1.157     albertel 6712:     if ($lines eq '-1') {
                   6713: 	$scanlines{'corrected'}=[];
                   6714:     } else {
                   6715: 	$scanlines{'corrected'}=[(split("\n",$lines,-1))];
                   6716:     }
                   6717:     $lines=&Apache::lonnet::getfile('/uploaded/'.$cdom.'/'.$cname.'/'.
1.257     albertel 6718: 		       'scantron_skipped_'.$env{'form.scantron_selectfile'});
1.157     albertel 6719:     if ($lines eq '-1') {
                   6720: 	$scanlines{'skipped'}=[];
                   6721:     } else {
                   6722: 	$scanlines{'skipped'}=[(split("\n",$lines,-1))];
                   6723:     }
1.175     albertel 6724:     my @tmp=&Apache::lonnet::dump('nohist_scantrondata',$cdom,$cname);
1.157     albertel 6725:     if ($tmp[0] =~ /^(error:|no_such_host)/) { @tmp=(); }
                   6726:     my %scan_data = @tmp;
                   6727:     return (\%scanlines,\%scan_data);
                   6728: }
                   6729: 
1.423     albertel 6730: =pod
                   6731: 
                   6732: =item lonnet_putfile
                   6733: 
1.424     albertel 6734:    Wrapper routine to call &Apache::lonnet::finishuserfileupload
                   6735: 
                   6736:  Arguments:
                   6737:    $contents - data to store
                   6738:    $filename - filename to store $contents into
                   6739: 
                   6740:  Returns:
                   6741:    result value from &Apache::lonnet::finishuserfileupload
                   6742: 
1.423     albertel 6743: =cut
                   6744: 
1.157     albertel 6745: sub lonnet_putfile {
                   6746:     my ($contents,$filename)=@_;
1.257     albertel 6747:     my $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   6748:     my $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
                   6749:     $env{'form.sillywaytopassafilearound'}=$contents;
1.275     albertel 6750:     &Apache::lonnet::finishuserfileupload($docuname,$docudom,'sillywaytopassafilearound',$filename);
1.157     albertel 6751: 
                   6752: }
                   6753: 
1.423     albertel 6754: =pod
                   6755: 
                   6756: =item scantron_putfile
                   6757: 
1.596.2.6  raeburn  6758:     Stores the current version of the bubblesheet data files, and the
1.424     albertel 6759:     scan_data hash. (Does not modify the original version only the
                   6760:     corrected and skipped versions.
                   6761: 
                   6762:  Arguments:
                   6763:     $scanlines - hash ref that looks like the first return value from
                   6764:                  &scantron_getfile()
                   6765:     $scan_data - hash ref that looks like the second return value from
                   6766:                  &scantron_getfile()
                   6767: 
1.423     albertel 6768: =cut
                   6769: 
1.157     albertel 6770: sub scantron_putfile {
                   6771:     my ($scanlines,$scan_data) = @_;
1.200     albertel 6772:     #FIXME really would prefer a scantron directory
1.257     albertel 6773:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   6774:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1.200     albertel 6775:     if ($scanlines) {
                   6776: 	my $prefix='scantron_';
1.157     albertel 6777: # no need to update orig, shouldn't change
                   6778: #   &lonnet_putfile(join("\n",@{$scanlines->{'orig'}}),$prefix.'orig_'.
1.257     albertel 6779: #		    $env{'form.scantron_selectfile'});
1.200     albertel 6780: 	&lonnet_putfile(join("\n",@{$scanlines->{'corrected'}}),
                   6781: 			$prefix.'corrected_'.
1.257     albertel 6782: 			$env{'form.scantron_selectfile'});
1.200     albertel 6783: 	&lonnet_putfile(join("\n",@{$scanlines->{'skipped'}}),
                   6784: 			$prefix.'skipped_'.
1.257     albertel 6785: 			$env{'form.scantron_selectfile'});
1.200     albertel 6786:     }
1.175     albertel 6787:     &Apache::lonnet::put('nohist_scantrondata',$scan_data,$cdom,$cname);
1.157     albertel 6788: }
                   6789: 
1.423     albertel 6790: =pod
                   6791: 
                   6792: =item scantron_get_line
                   6793: 
1.424     albertel 6794:    Returns the correct version of the scanline
                   6795: 
                   6796:  Arguments:
                   6797:     $scanlines - hash ref that looks like the first return value from
                   6798:                  &scantron_getfile()
                   6799:     $scan_data - hash ref that looks like the second return value from
                   6800:                  &scantron_getfile()
                   6801:     $i         - number of the requested line (starts at 0)
                   6802: 
                   6803:  Returns:
                   6804:    A scanline, (either the original or the corrected one if it
                   6805:    exists), or undef if the requested scanline should be
                   6806:    skipped. (Either because it's an skipped scanline, or it's an
                   6807:    unskipped scanline and we are not doing a 'do skipped scanlines'
                   6808:    pass.
                   6809: 
1.423     albertel 6810: =cut
                   6811: 
1.157     albertel 6812: sub scantron_get_line {
1.200     albertel 6813:     my ($scanlines,$scan_data,$i)=@_;
1.376     albertel 6814:     if (&should_be_skipped($scanlines,$scan_data,$i)) { return undef; }
                   6815:     #if ($scanlines->{'skipped'}[$i]) { return undef; }
1.157     albertel 6816:     if ($scanlines->{'corrected'}[$i]) {return $scanlines->{'corrected'}[$i];}
                   6817:     return $scanlines->{'orig'}[$i]; 
                   6818: }
                   6819: 
1.423     albertel 6820: =pod
                   6821: 
                   6822: =item scantron_todo_count
                   6823: 
1.424     albertel 6824:     Counts the number of scanlines that need processing.
                   6825: 
                   6826:  Arguments:
                   6827:     $scanlines - hash ref that looks like the first return value from
                   6828:                  &scantron_getfile()
                   6829:     $scan_data - hash ref that looks like the second return value from
                   6830:                  &scantron_getfile()
                   6831: 
                   6832:  Returns:
                   6833:     $count - number of scanlines to process
                   6834: 
1.423     albertel 6835: =cut
                   6836: 
1.200     albertel 6837: sub get_todo_count {
                   6838:     my ($scanlines,$scan_data)=@_;
                   6839:     my $count=0;
                   6840:     for (my $i=0;$i<=$scanlines->{'count'};$i++) {
                   6841: 	my $line=&scantron_get_line($scanlines,$scan_data,$i);
                   6842: 	if ($line=~/^[\s\cz]*$/) { next; }
                   6843: 	$count++;
                   6844:     }
                   6845:     return $count;
                   6846: }
                   6847: 
1.423     albertel 6848: =pod
                   6849: 
                   6850: =item scantron_put_line
                   6851: 
1.596.2.6  raeburn  6852:     Updates the 'corrected' or 'skipped' versions of the bubblesheet
1.424     albertel 6853:     data file.
                   6854: 
                   6855:  Arguments:
                   6856:     $scanlines - hash ref that looks like the first return value from
                   6857:                  &scantron_getfile()
                   6858:     $scan_data - hash ref that looks like the second return value from
                   6859:                  &scantron_getfile()
                   6860:     $i         - line number to update
                   6861:     $newline   - contents of the updated scanline
                   6862:     $skip      - if true make the line for skipping and update the
                   6863:                  'skipped' file
                   6864: 
1.423     albertel 6865: =cut
                   6866: 
1.157     albertel 6867: sub scantron_put_line {
1.200     albertel 6868:     my ($scanlines,$scan_data,$i,$newline,$skip)=@_;
1.157     albertel 6869:     if ($skip) {
                   6870: 	$scanlines->{'skipped'}[$i]=$newline;
1.376     albertel 6871: 	&start_skipping($scan_data,$i);
1.157     albertel 6872: 	return;
                   6873:     }
                   6874:     $scanlines->{'corrected'}[$i]=$newline;
                   6875: }
                   6876: 
1.423     albertel 6877: =pod
                   6878: 
                   6879: =item scantron_clear_skip
                   6880: 
1.424     albertel 6881:    Remove a line from the 'skipped' file
                   6882: 
                   6883:  Arguments:
                   6884:     $scanlines - hash ref that looks like the first return value from
                   6885:                  &scantron_getfile()
                   6886:     $scan_data - hash ref that looks like the second return value from
                   6887:                  &scantron_getfile()
                   6888:     $i         - line number to update
                   6889: 
1.423     albertel 6890: =cut
                   6891: 
1.376     albertel 6892: sub scantron_clear_skip {
                   6893:     my ($scanlines,$scan_data,$i)=@_;
                   6894:     if (exists($scanlines->{'skipped'}[$i])) {
                   6895: 	undef($scanlines->{'skipped'}[$i]);
                   6896: 	return 1;
                   6897:     }
                   6898:     return 0;
                   6899: }
                   6900: 
1.423     albertel 6901: =pod
                   6902: 
                   6903: =item scantron_filter_not_exam
                   6904: 
1.424     albertel 6905:    Filter routine used by &Apache::lonnavmaps::retrieveResources(), to
                   6906:    filter out resources that are not marked as 'exam' mode
                   6907: 
1.423     albertel 6908: =cut
                   6909: 
1.334     albertel 6910: sub scantron_filter_not_exam {
                   6911:     my ($curres)=@_;
                   6912:     
                   6913:     if (ref($curres) && $curres->is_problem() && !$curres->is_exam()) {
                   6914: 	# if the user has asked to not have either hidden
                   6915: 	# or 'randomout' controlled resources to be graded
                   6916: 	# don't include them
                   6917: 	if ($env{'form.scantron_options_hidden'} eq 'ignore_hidden'
                   6918: 	    && $curres->randomout) {
                   6919: 	    return 0;
                   6920: 	}
                   6921: 	return 1;
                   6922:     }
                   6923:     return 0;
                   6924: }
                   6925: 
1.423     albertel 6926: =pod
                   6927: 
                   6928: =item scantron_validate_sequence
                   6929: 
1.424     albertel 6930:     Validates the selected sequence, checking for resource that are
                   6931:     not set to exam mode.
                   6932: 
1.423     albertel 6933: =cut
                   6934: 
1.334     albertel 6935: sub scantron_validate_sequence {
                   6936:     my ($r,$currentphase) = @_;
                   6937: 
                   6938:     my $navmap=Apache::lonnavmaps::navmap->new();
1.582     raeburn  6939:     unless (ref($navmap)) {
                   6940:         $r->print(&navmap_errormsg());
                   6941:         return (1,$currentphase);
                   6942:     }
1.334     albertel 6943:     my (undef,undef,$sequence)=
                   6944: 	&Apache::lonnet::decode_symb($env{'form.selectpage'});
                   6945: 
                   6946:     my $map=$navmap->getResourceByUrl($sequence);
                   6947: 
                   6948:     $r->print('<input type="hidden" name="validate_sequence_exam"
                   6949:                                     value="ignore" />');
                   6950:     if ($env{'form.validate_sequence_exam'} ne 'ignore') {
                   6951: 	my @resources=
                   6952: 	    $navmap->retrieveResources($map,\&scantron_filter_not_exam,1,0);
                   6953: 	if (@resources) {
1.357     banghart 6954: 	    $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 6955: 	    return (1,$currentphase);
                   6956: 	}
                   6957:     }
                   6958: 
                   6959:     return (0,$currentphase+1);
                   6960: }
                   6961: 
1.423     albertel 6962: 
                   6963: 
1.157     albertel 6964: sub scantron_validate_ID {
                   6965:     my ($r,$currentphase) = @_;
                   6966:     
                   6967:     #get student info
                   6968:     my $classlist=&Apache::loncoursedata::get_classlist();
                   6969:     my %idmap=&username_to_idmap($classlist);
                   6970: 
                   6971:     #get scantron line setup
1.257     albertel 6972:     my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
1.157     albertel 6973:     my ($scanlines,$scan_data)=&scantron_getfile();
1.582     raeburn  6974: 
                   6975:     my $nav_error;
                   6976:     &scantron_get_maxbubble(\$nav_error); # parse needs the bubble_lines.. array.
                   6977:     if ($nav_error) {
                   6978:         $r->print(&navmap_errormsg());
                   6979:         return(1,$currentphase);
                   6980:     }
1.157     albertel 6981: 
                   6982:     my %found=('ids'=>{},'usernames'=>{});
                   6983:     for (my $i=0;$i<=$scanlines->{'count'};$i++) {
1.200     albertel 6984: 	my $line=&scantron_get_line($scanlines,$scan_data,$i);
1.157     albertel 6985: 	if ($line=~/^[\s\cz]*$/) { next; }
                   6986: 	my $scan_record=&scantron_parse_scanline($line,$i,\%scantron_config,
                   6987: 						 $scan_data);
                   6988: 	my $id=$$scan_record{'scantron.ID'};
                   6989: 	my $found;
                   6990: 	foreach my $checkid (keys(%idmap)) {
                   6991: 	    if (lc($checkid) eq lc($id)) { $found=$checkid;last; }
                   6992: 	}
                   6993: 	if ($found) {
                   6994: 	    my $username=$idmap{$found};
                   6995: 	    if ($found{'ids'}{$found}) {
                   6996: 		&scantron_get_correction($r,$i,$scan_record,\%scantron_config,
                   6997: 					 $line,'duplicateID',$found);
1.194     albertel 6998: 		return(1,$currentphase);
1.157     albertel 6999: 	    } elsif ($found{'usernames'}{$username}) {
                   7000: 		&scantron_get_correction($r,$i,$scan_record,\%scantron_config,
                   7001: 					 $line,'duplicateID',$username);
1.194     albertel 7002: 		return(1,$currentphase);
1.157     albertel 7003: 	    }
1.186     albertel 7004: 	    #FIXME store away line we previously saw the ID on to use above
1.157     albertel 7005: 	    $found{'ids'}{$found}++;
                   7006: 	    $found{'usernames'}{$username}++;
                   7007: 	} else {
                   7008: 	    if ($id =~ /^\s*$/) {
1.158     albertel 7009: 		my $username=&scan_data($scan_data,"$i.user");
1.157     albertel 7010: 		if (defined($username) && $found{'usernames'}{$username}) {
                   7011: 		    &scantron_get_correction($r,$i,$scan_record,
                   7012: 					     \%scantron_config,
                   7013: 					     $line,'duplicateID',$username);
1.194     albertel 7014: 		    return(1,$currentphase);
1.157     albertel 7015: 		} elsif (!defined($username)) {
                   7016: 		    &scantron_get_correction($r,$i,$scan_record,
                   7017: 					     \%scantron_config,
                   7018: 					     $line,'incorrectID');
1.194     albertel 7019: 		    return(1,$currentphase);
1.157     albertel 7020: 		}
                   7021: 		$found{'usernames'}{$username}++;
                   7022: 	    } else {
                   7023: 		&scantron_get_correction($r,$i,$scan_record,\%scantron_config,
                   7024: 					 $line,'incorrectID');
1.194     albertel 7025: 		return(1,$currentphase);
1.157     albertel 7026: 	    }
                   7027: 	}
                   7028:     }
                   7029: 
                   7030:     return (0,$currentphase+1);
                   7031: }
                   7032: 
1.423     albertel 7033: 
1.157     albertel 7034: sub scantron_get_correction {
                   7035:     my ($r,$i,$scan_record,$scan_config,$line,$error,$arg)=@_;
1.454     banghart 7036: #FIXME in the case of a duplicated ID the previous line, probably need
1.157     albertel 7037: #to show both the current line and the previous one and allow skipping
                   7038: #the previous one or the current one
                   7039: 
1.333     albertel 7040:     if ( $$scan_record{'scantron.PaperID'} =~ /\S/) {
1.596.2.6  raeburn  7041:         $r->print(
                   7042:             '<p class="LC_warning">'
                   7043:            .&mt('An error was detected ([_1]) for PaperID [_2]',
                   7044:                 "<b>$error</b>",
                   7045:                 '<tt>'.$$scan_record{'scantron.PaperID'}.'</tt>')
                   7046:            ."</p> \n");
1.157     albertel 7047:     } else {
1.596.2.6  raeburn  7048:         $r->print(
                   7049:             '<p class="LC_warning">'
                   7050:            .&mt('An error was detected ([_1]) in scanline [_2] [_3]',
                   7051:                 "<b>$error</b>", $i, "<pre>$line</pre>")
                   7052:            ."</p> \n");
                   7053:     }
                   7054:     my $message =
                   7055:         '<p>'
                   7056:        .&mt('The ID on the form is [_1]',
                   7057:             "<tt>$$scan_record{'scantron.ID'}</tt>")
                   7058:        .'<br />'
1.596.2.12  raeburn  7059:        .&mt('The name on the paper is [_1], [_2]',
1.596.2.6  raeburn  7060:             $$scan_record{'scantron.LastName'},
                   7061:             $$scan_record{'scantron.FirstName'})
                   7062:        .'</p>';
1.242     albertel 7063: 
1.157     albertel 7064:     $r->print('<input type="hidden" name="scantron_corrections" value="'.$error.'" />'."\n");
                   7065:     $r->print('<input type="hidden" name="scantron_line" value="'.$i.'" />'."\n");
1.503     raeburn  7066:                            # Array populated for doublebubble or
                   7067:     my @lines_to_correct;  # missingbubble errors to build javascript
                   7068:                            # to validate radio button checking   
                   7069: 
1.157     albertel 7070:     if ($error =~ /ID$/) {
1.186     albertel 7071: 	if ($error eq 'incorrectID') {
1.596.2.6  raeburn  7072: 	    $r->print('<p class="LC_warning">'.&mt("The encoded ID is not in the classlist").
1.492     albertel 7073: 		      "</p>\n");
1.157     albertel 7074: 	} elsif ($error eq 'duplicateID') {
1.596.2.6  raeburn  7075: 	    $r->print('<p class="LC_warning">'.&mt("The encoded ID has also been used by a previous paper [_1]",$arg)."</p>\n");
1.157     albertel 7076: 	}
1.242     albertel 7077: 	$r->print($message);
1.492     albertel 7078: 	$r->print("<p>".&mt("How should I handle this?")." <br /> \n");
1.157     albertel 7079: 	$r->print("\n<ul><li> ");
                   7080: 	#FIXME it would be nice if this sent back the user ID and
                   7081: 	#could do partial userID matches
                   7082: 	$r->print(&Apache::loncommon::selectstudent_link('scantronupload',
                   7083: 				       'scantron_username','scantron_domain'));
                   7084: 	$r->print(": <input type='text' name='scantron_username' value='' />");
                   7085: 	$r->print("\n@".
1.257     albertel 7086: 		 &Apache::loncommon::select_dom_form($env{'request.role.domain'},'scantron_domain'));
1.157     albertel 7087: 
                   7088: 	$r->print('</li>');
1.186     albertel 7089:     } elsif ($error =~ /CODE$/) {
                   7090: 	if ($error eq 'incorrectCODE') {
1.596.2.6  raeburn  7091: 	    $r->print('<p class="LC_warning">'.&mt("The encoded CODE is not in the list of possible CODEs.")."</p>\n");
1.186     albertel 7092: 	} elsif ($error eq 'duplicateCODE') {
1.596.2.6  raeburn  7093: 	    $r->print('<p class="LC_warning">'.&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 7094: 	}
1.596.2.6  raeburn  7095:         $r->print("<p>".&mt('The CODE on the form is [_1]',
                   7096:                             "<tt>'$$scan_record{'scantron.CODE'}'</tt>")
                   7097:                  ."</p>\n");
1.242     albertel 7098: 	$r->print($message);
1.596.2.6  raeburn  7099: 	$r->print("<p>".&mt("How should I handle this?")."</p>\n");
1.187     albertel 7100: 	$r->print("\n<br /> ");
1.194     albertel 7101: 	my $i=0;
1.273     albertel 7102: 	if ($error eq 'incorrectCODE' 
                   7103: 	    && $$scan_record{'scantron.CODE'}=~/\S/ ) {
1.194     albertel 7104: 	    my ($max,$closest)=&scantron_get_closely_matching_CODEs($arg,$$scan_record{'scantron.CODE'});
1.278     albertel 7105: 	    if ($closest > 0) {
                   7106: 		foreach my $testcode (@{$closest}) {
                   7107: 		    my $checked='';
1.569     bisitz   7108: 		    if (!$i) { $checked=' checked="checked"'; }
1.492     albertel 7109: 		    $r->print("
                   7110:    <label>
1.569     bisitz   7111:        <input type='radio' name='scantron_CODE_resolution' value='use_closest_$i'$checked />
1.492     albertel 7112:        ".&mt("Use the similar CODE [_1] instead.",
                   7113: 	    "<b><tt>".$testcode."</tt></b>")."
                   7114:     </label>
                   7115:     <input type='hidden' name='scantron_CODE_closest_$i' value='$testcode' />");
1.278     albertel 7116: 		    $r->print("\n<br />");
                   7117: 		    $i++;
                   7118: 		}
1.194     albertel 7119: 	    }
                   7120: 	}
1.273     albertel 7121: 	if ($$scan_record{'scantron.CODE'}=~/\S/ ) {
1.569     bisitz   7122: 	    my $checked; if (!$i) { $checked=' checked="checked"'; }
1.492     albertel 7123: 	    $r->print("
                   7124:     <label>
1.569     bisitz   7125:         <input type='radio' name='scantron_CODE_resolution' value='use_unfound'$checked />
1.596.2.6  raeburn  7126:        ".&mt("Use the CODE [_1] that was on the paper, ignoring the error.",
1.492     albertel 7127: 	     "<b><tt>".$$scan_record{'scantron.CODE'}."</tt></b>")."
                   7128:     </label>");
1.273     albertel 7129: 	    $r->print("\n<br />");
                   7130: 	}
1.194     albertel 7131: 
1.188     albertel 7132: 	$r->print(<<ENDSCRIPT);
                   7133: <script type="text/javascript">
                   7134: function change_radio(field) {
1.190     albertel 7135:     var slct=document.scantronupload.scantron_CODE_resolution;
1.188     albertel 7136:     var i;
                   7137:     for (i=0;i<slct.length;i++) {
                   7138:         if (slct[i].value==field) { slct[i].checked=true; }
                   7139:     }
                   7140: }
                   7141: </script>
                   7142: ENDSCRIPT
1.187     albertel 7143: 	my $href="/adm/pickcode?".
1.359     www      7144: 	   "form=".&escape("scantronupload").
                   7145: 	   "&scantron_format=".&escape($env{'form.scantron_format'}).
                   7146: 	   "&scantron_CODElist=".&escape($env{'form.scantron_CODElist'}).
                   7147: 	   "&curCODE=".&escape($$scan_record{'scantron.CODE'}).
                   7148: 	   "&scantron_selectfile=".&escape($env{'form.scantron_selectfile'});
1.332     albertel 7149: 	if ($env{'form.scantron_CODElist'} =~ /\S/) { 
1.492     albertel 7150: 	    $r->print("
                   7151:     <label>
                   7152:        <input type='radio' name='scantron_CODE_resolution' value='use_found' />
                   7153:        ".&mt("[_1]Select[_2] a CODE from the list of all CODEs and use it.",
                   7154: 	     "<a target='_blank' href='$href'>","</a>")."
                   7155:     </label> 
1.558     bisitz   7156:     ".&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 7157: 	    $r->print("\n<br />");
                   7158: 	}
1.492     albertel 7159: 	$r->print("
                   7160:     <label>
                   7161:        <input type='radio' name='scantron_CODE_resolution' value='use_typed' />
                   7162:        ".&mt("Use [_1] as the CODE.",
                   7163: 	     "</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 7164: 	$r->print("\n<br /><br />");
1.157     albertel 7165:     } elsif ($error eq 'doublebubble') {
1.596.2.6  raeburn  7166: 	$r->print('<p class="LC_warning">'.&mt("There have been multiple bubbles scanned for some question(s)")."</p>\n");
1.497     foxr     7167: 
                   7168: 	# The form field scantron_questions is acutally a list of line numbers.
                   7169: 	# represented by this form so:
                   7170: 
                   7171: 	my $line_list = &questions_to_line_list($arg);
                   7172: 
1.157     albertel 7173: 	$r->print('<input type="hidden" name="scantron_questions" value="'.
1.497     foxr     7174: 		  $line_list.'" />');
1.242     albertel 7175: 	$r->print($message);
1.492     albertel 7176: 	$r->print("<p>".&mt("Please indicate which bubble should be used for grading")."</p>");
1.157     albertel 7177: 	foreach my $question (@{$arg}) {
1.503     raeburn  7178: 	    my @linenums = &prompt_for_corrections($r,$question,$scan_config,
                   7179:                                                    $scan_record, $error);
1.524     raeburn  7180:             push(@lines_to_correct,@linenums);
1.157     albertel 7181: 	}
1.503     raeburn  7182:         $r->print(&verify_bubbles_checked(@lines_to_correct));
1.157     albertel 7183:     } elsif ($error eq 'missingbubble') {
1.596.2.9  raeburn  7184: 	$r->print('<p class="LC_warning">'.&mt("There have been [_1]no[_2] bubbles scanned for some question(s)",'<b>','</b>')."</p>\n");
1.242     albertel 7185: 	$r->print($message);
1.492     albertel 7186: 	$r->print("<p>".&mt("Please indicate which bubble should be used for grading.")."</p>");
1.503     raeburn  7187: 	$r->print(&mt("Some questions have no scanned bubbles.")."\n");
1.497     foxr     7188: 
1.503     raeburn  7189: 	# The form field scantron_questions is actually a list of line numbers not
1.497     foxr     7190: 	# a list of question numbers. Therefore:
                   7191: 	#
                   7192: 	
                   7193: 	my $line_list = &questions_to_line_list($arg);
                   7194: 
1.157     albertel 7195: 	$r->print('<input type="hidden" name="scantron_questions" value="'.
1.497     foxr     7196: 		  $line_list.'" />');
1.157     albertel 7197: 	foreach my $question (@{$arg}) {
1.503     raeburn  7198: 	    my @linenums = &prompt_for_corrections($r,$question,$scan_config,
                   7199:                                                    $scan_record, $error);
1.524     raeburn  7200:             push(@lines_to_correct,@linenums);
1.157     albertel 7201: 	}
1.503     raeburn  7202:         $r->print(&verify_bubbles_checked(@lines_to_correct));
1.157     albertel 7203:     } else {
                   7204: 	$r->print("\n<ul>");
                   7205:     }
                   7206:     $r->print("\n</li></ul>");
1.497     foxr     7207: }
                   7208: 
1.503     raeburn  7209: sub verify_bubbles_checked {
                   7210:     my (@ansnums) = @_;
                   7211:     my $ansnumstr = join('","',@ansnums);
                   7212:     my $warning = &mt("A bubble or 'No bubble' selection has not been made for one or more lines.");
                   7213:     my $output = (<<ENDSCRIPT);
                   7214: <script type="text/javascript">
                   7215: function verify_bubble_radio(form) {
                   7216:     var ansnumArray = new Array ("$ansnumstr");
                   7217:     var need_bubble_count = 0;
                   7218:     for (var i=0; i<ansnumArray.length; i++) {
                   7219:         if (form.elements["scantron_correct_Q_"+ansnumArray[i]].length > 1) {
                   7220:             var bubble_picked = 0; 
                   7221:             for (var j=0; j<form.elements["scantron_correct_Q_"+ansnumArray[i]].length; j++) {
                   7222:                 if (form.elements["scantron_correct_Q_"+ansnumArray[i]][j].checked == true) {
                   7223:                     bubble_picked = 1;
                   7224:                 }
                   7225:             }
                   7226:             if (bubble_picked == 0) {
                   7227:                 need_bubble_count ++;
                   7228:             }
                   7229:         }
                   7230:     }
                   7231:     if (need_bubble_count) {
                   7232:         alert("$warning");
                   7233:         return;
                   7234:     }
                   7235:     form.submit(); 
                   7236: }
                   7237: </script>
                   7238: ENDSCRIPT
                   7239:     return $output;
                   7240: }
                   7241: 
1.497     foxr     7242: =pod
                   7243: 
                   7244: =item  questions_to_line_list
1.157     albertel 7245: 
1.497     foxr     7246: Converts a list of questions into a string of comma separated
                   7247: line numbers in the answer sheet used by the questions.  This is
                   7248: used to fill in the scantron_questions form field.
                   7249: 
                   7250:   Arguments:
                   7251:      questions    - Reference to an array of questions.
                   7252: 
                   7253: =cut
                   7254: 
                   7255: 
                   7256: sub questions_to_line_list {
                   7257:     my ($questions) = @_;
                   7258:     my @lines;
                   7259: 
1.503     raeburn  7260:     foreach my $item (@{$questions}) {
                   7261:         my $question = $item;
                   7262:         my ($first,$count,$last);
                   7263:         if ($item =~ /^(\d+)\.(\d+)$/) {
                   7264:             $question = $1;
                   7265:             my $subquestion = $2;
                   7266:             $first = $first_bubble_line{$question-1} + 1;
                   7267:             my @subans = split(/,/,$subdivided_bubble_lines{$question-1});
                   7268:             my $subcount = 1;
                   7269:             while ($subcount<$subquestion) {
                   7270:                 $first += $subans[$subcount-1];
                   7271:                 $subcount ++;
                   7272:             }
                   7273:             $count = $subans[$subquestion-1];
                   7274:         } else {
                   7275: 	    $first   = $first_bubble_line{$question-1} + 1;
                   7276: 	    $count   = $bubble_lines_per_response{$question-1};
                   7277:         }
1.506     raeburn  7278:         $last = $first+$count-1;
1.503     raeburn  7279:         push(@lines, ($first..$last));
1.497     foxr     7280:     }
                   7281:     return join(',', @lines);
                   7282: }
                   7283: 
                   7284: =pod 
                   7285: 
                   7286: =item prompt_for_corrections
                   7287: 
                   7288: Prompts for a potentially multiline correction to the
                   7289: user's bubbling (factors out common code from scantron_get_correction
                   7290: for multi and missing bubble cases).
                   7291: 
                   7292:  Arguments:
                   7293:    $r           - Apache request object.
                   7294:    $question    - The question number to prompt for.
                   7295:    $scan_config - The scantron file configuration hash.
                   7296:    $scan_record - Reference to the hash that has the the parsed scanlines.
1.503     raeburn  7297:    $error       - Type of error
1.497     foxr     7298: 
                   7299:  Implicit inputs:
                   7300:    %bubble_lines_per_response   - Starting line numbers for each question.
                   7301:                                   Numbered from 0 (but question numbers are from
                   7302:                                   1.
                   7303:    %first_bubble_line           - Starting bubble line for each question.
1.509     raeburn  7304:    %subdivided_bubble_lines     - optionresponse, matchresponse and rankresponse 
                   7305:                                   type problems render as separate sub-questions, 
1.503     raeburn  7306:                                   in exam mode. This hash contains a 
                   7307:                                   comma-separated list of the lines per 
                   7308:                                   sub-question.
1.510     raeburn  7309:    %responsetype_per_response   - essayresponse, formularesponse,
                   7310:                                   stringresponse, imageresponse, reactionresponse,
                   7311:                                   and organicresponse type problem parts can have
1.503     raeburn  7312:                                   multiple lines per response if the weight
                   7313:                                   assigned exceeds 10.  In this case, only
                   7314:                                   one bubble per line is permitted, but more 
                   7315:                                   than one line might contain bubbles, e.g.
                   7316:                                   bubbling of: line 1 - J, line 2 - J, 
                   7317:                                   line 3 - B would assign 22 points.  
1.497     foxr     7318: 
                   7319: =cut
                   7320: 
                   7321: sub prompt_for_corrections {
1.503     raeburn  7322:     my ($r, $question, $scan_config, $scan_record, $error) = @_;
                   7323:     my ($current_line,$lines);
                   7324:     my @linenums;
                   7325:     my $questionnum = $question;
                   7326:     if ($question =~ /^(\d+)\.(\d+)$/) {
                   7327:         $question = $1;
                   7328:         $current_line = $first_bubble_line{$question-1} + 1 ;
                   7329:         my $subquestion = $2;
                   7330:         my @subans = split(/,/,$subdivided_bubble_lines{$question-1});
                   7331:         my $subcount = 1;
                   7332:         while ($subcount<$subquestion) {
                   7333:             $current_line += $subans[$subcount-1];
                   7334:             $subcount ++;
                   7335:         }
                   7336:         $lines = $subans[$subquestion-1];
                   7337:     } else {
                   7338:         $current_line = $first_bubble_line{$question-1} + 1 ;
                   7339:         $lines        = $bubble_lines_per_response{$question-1};
                   7340:     }
1.497     foxr     7341:     if ($lines > 1) {
1.503     raeburn  7342:         $r->print(&mt('The group of bubble lines below responds to a single question.').'<br />');
                   7343:         if (($responsetype_per_response{$question-1} eq 'essayresponse') ||
                   7344:             ($responsetype_per_response{$question-1} eq 'formularesponse') ||
1.510     raeburn  7345:             ($responsetype_per_response{$question-1} eq 'stringresponse') ||
                   7346:             ($responsetype_per_response{$question-1} eq 'imageresponse') ||
                   7347:             ($responsetype_per_response{$question-1} eq 'reactionresponse') ||
                   7348:             ($responsetype_per_response{$question-1} eq 'organicresponse')) {
1.572     www      7349:             $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  7350:         } else {
                   7351:             $r->print(&mt("Select at most one bubble in a single line and select 'No Bubble' in all the other lines. ")."<br />");
                   7352:         }
1.497     foxr     7353:     }
                   7354:     for (my $i =0; $i < $lines; $i++) {
1.503     raeburn  7355:         my $selected = $$scan_record{"scantron.$current_line.answer"};
                   7356: 	&scantron_bubble_selector($r,$scan_config,$current_line, 
                   7357: 	        		  $questionnum,$error,split('', $selected));
1.524     raeburn  7358:         push(@linenums,$current_line);
1.497     foxr     7359: 	$current_line++;
                   7360:     }
                   7361:     if ($lines > 1) {
                   7362: 	$r->print("<hr /><br />");
                   7363:     }
1.503     raeburn  7364:     return @linenums;
1.157     albertel 7365: }
1.423     albertel 7366: 
                   7367: =pod
                   7368: 
                   7369: =item scantron_bubble_selector
                   7370:   
                   7371:    Generates the html radiobuttons to correct a single bubble line
1.424     albertel 7372:    possibly showing the existing the selected bubbles if known
1.423     albertel 7373: 
                   7374:  Arguments:
                   7375:     $r           - Apache request object
                   7376:     $scan_config - hash from &get_scantron_config()
1.497     foxr     7377:     $line        - Number of the line being displayed.
1.503     raeburn  7378:     $questionnum - Question number (may include subquestion)
                   7379:     $error       - Type of error.
1.497     foxr     7380:     @selected    - Array of bubbles picked on this line.
1.423     albertel 7381: 
                   7382: =cut
                   7383: 
1.157     albertel 7384: sub scantron_bubble_selector {
1.503     raeburn  7385:     my ($r,$scan_config,$line,$questionnum,$error,@selected)=@_;
1.157     albertel 7386:     my $max=$$scan_config{'Qlength'};
1.274     albertel 7387: 
                   7388:     my $scmode=$$scan_config{'Qon'};
                   7389:     if ($scmode eq 'number' || $scmode eq 'letter') { $max=10; }	     
                   7390: 
1.157     albertel 7391:     my @alphabet=('A'..'Z');
1.503     raeburn  7392:     $r->print(&Apache::loncommon::start_data_table().
                   7393:               &Apache::loncommon::start_data_table_row());
                   7394:     $r->print('<td rowspan="2" class="LC_leftcol_header">'.$line.'</td>');
1.497     foxr     7395:     for (my $i=0;$i<$max+1;$i++) {
                   7396: 	$r->print("\n".'<td align="center">');
                   7397: 	if ($selected[0] eq $alphabet[$i]) { $r->print('X'); shift(@selected) }
                   7398: 	else { $r->print('&nbsp;'); }
                   7399: 	$r->print('</td>');
                   7400:     }
1.503     raeburn  7401:     $r->print(&Apache::loncommon::end_data_table_row().
                   7402:               &Apache::loncommon::start_data_table_row());
1.497     foxr     7403:     for (my $i=0;$i<$max;$i++) {
                   7404: 	$r->print("\n".
                   7405: 		  '<td><label><input type="radio" name="scantron_correct_Q_'.
                   7406: 		  $line.'" value="'.$i.'" />'.$alphabet[$i]."</label></td>");
                   7407:     }
1.503     raeburn  7408:     my $nobub_checked = ' ';
                   7409:     if ($error eq 'missingbubble') {
                   7410:         $nobub_checked = ' checked = "checked" ';
                   7411:     }
                   7412:     $r->print("\n".'<td><label><input type="radio" name="scantron_correct_Q_'.
                   7413: 	      $line.'" value="none"'.$nobub_checked.'/>'.&mt('No bubble').
                   7414:               '</label>'."\n".'<input type="hidden" name="scantron_questionnum_Q_'.
                   7415:               $line.'" value="'.$questionnum.'" /></td>');
                   7416:     $r->print(&Apache::loncommon::end_data_table_row().
                   7417:               &Apache::loncommon::end_data_table());
1.157     albertel 7418: }
                   7419: 
1.423     albertel 7420: =pod
                   7421: 
                   7422: =item num_matches
                   7423: 
1.424     albertel 7424:    Counts the number of characters that are the same between the two arguments.
                   7425: 
                   7426:  Arguments:
                   7427:    $orig - CODE from the scanline
                   7428:    $code - CODE to match against
                   7429: 
                   7430:  Returns:
                   7431:    $count - integer count of the number of same characters between the
                   7432:             two arguments
                   7433: 
1.423     albertel 7434: =cut
                   7435: 
1.194     albertel 7436: sub num_matches {
                   7437:     my ($orig,$code) = @_;
                   7438:     my @code=split(//,$code);
                   7439:     my @orig=split(//,$orig);
                   7440:     my $same=0;
                   7441:     for (my $i=0;$i<scalar(@code);$i++) {
                   7442: 	if ($code[$i] eq $orig[$i]) { $same++; }
                   7443:     }
                   7444:     return $same;
                   7445: }
                   7446: 
1.423     albertel 7447: =pod
                   7448: 
                   7449: =item scantron_get_closely_matching_CODEs
                   7450: 
1.424     albertel 7451:    Cycles through all CODEs and finds the set that has the greatest
                   7452:    number of same characters as the provided CODE
                   7453: 
                   7454:  Arguments:
                   7455:    $allcodes - hash ref returned by &get_codes()
                   7456:    $CODE     - CODE from the current scanline
                   7457: 
                   7458:  Returns:
                   7459:    2 element list
                   7460:     - first elements is number of how closely matching the best fit is 
                   7461:       (5 means best set has 5 matching characters)
                   7462:     - second element is an arrary ref containing the set of valid CODEs
                   7463:       that best fit the passed in CODE
                   7464: 
1.423     albertel 7465: =cut
                   7466: 
1.194     albertel 7467: sub scantron_get_closely_matching_CODEs {
                   7468:     my ($allcodes,$CODE)=@_;
                   7469:     my @CODEs;
                   7470:     foreach my $testcode (sort(keys(%{$allcodes}))) {
                   7471: 	push(@{$CODEs[&num_matches($CODE,$testcode)]},$testcode);
                   7472:     }
                   7473: 
                   7474:     return ($#CODEs,$CODEs[-1]);
                   7475: }
                   7476: 
1.423     albertel 7477: =pod
                   7478: 
                   7479: =item get_codes
                   7480: 
1.424     albertel 7481:    Builds a hash which has keys of all of the valid CODEs from the selected
                   7482:    set of remembered CODEs.
                   7483: 
                   7484:  Arguments:
                   7485:   $old_name - name of the set of remembered CODEs
                   7486:   $cdom     - domain of the course
                   7487:   $cnum     - internal course name
                   7488: 
                   7489:  Returns:
                   7490:   %allcodes - keys are the valid CODEs, values are all 1
                   7491: 
1.423     albertel 7492: =cut
                   7493: 
1.194     albertel 7494: sub get_codes {
1.280     foxr     7495:     my ($old_name, $cdom, $cnum) = @_;
                   7496:     if (!$old_name) {
                   7497: 	$old_name=$env{'form.scantron_CODElist'};
                   7498:     }
                   7499:     if (!$cdom) {
                   7500: 	$cdom =$env{'course.'.$env{'request.course.id'}.'.domain'};
                   7501:     }
                   7502:     if (!$cnum) {
                   7503: 	$cnum =$env{'course.'.$env{'request.course.id'}.'.num'};
                   7504:     }
1.278     albertel 7505:     my %result=&Apache::lonnet::get('CODEs',[$old_name,"type\0$old_name"],
                   7506: 				    $cdom,$cnum);
                   7507:     my %allcodes;
                   7508:     if ($result{"type\0$old_name"} eq 'number') {
                   7509: 	%allcodes=map {($_,1)} split(',',$result{$old_name});
                   7510:     } else {
                   7511: 	%allcodes=map {(&Apache::lonprintout::num_to_letters($_),1)} split(',',$result{$old_name});
                   7512:     }
1.194     albertel 7513:     return %allcodes;
                   7514: }
                   7515: 
1.423     albertel 7516: =pod
                   7517: 
                   7518: =item scantron_validate_CODE
                   7519: 
1.424     albertel 7520:    Validates all scanlines in the selected file to not have any
                   7521:    invalid or underspecified CODEs and that none of the codes are
                   7522:    duplicated if this was requested.
                   7523: 
1.423     albertel 7524: =cut
                   7525: 
1.157     albertel 7526: sub scantron_validate_CODE {
                   7527:     my ($r,$currentphase) = @_;
1.257     albertel 7528:     my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
1.186     albertel 7529:     if ($scantron_config{'CODElocation'} &&
                   7530: 	$scantron_config{'CODEstart'} &&
                   7531: 	$scantron_config{'CODElength'}) {
1.257     albertel 7532: 	if (!defined($env{'form.scantron_CODElist'})) {
1.186     albertel 7533: 	    &FIXME_blow_up()
                   7534: 	}
                   7535:     } else {
                   7536: 	return (0,$currentphase+1);
                   7537:     }
                   7538:     
                   7539:     my %usedCODEs;
                   7540: 
1.194     albertel 7541:     my %allcodes=&get_codes();
1.186     albertel 7542: 
1.582     raeburn  7543:     my $nav_error;
                   7544:     &scantron_get_maxbubble(\$nav_error); # parse needs the lines per response array.
                   7545:     if ($nav_error) {
                   7546:         $r->print(&navmap_errormsg());
                   7547:         return(1,$currentphase);
                   7548:     }
1.447     foxr     7549: 
1.186     albertel 7550:     my ($scanlines,$scan_data)=&scantron_getfile();
                   7551:     for (my $i=0;$i<=$scanlines->{'count'};$i++) {
1.200     albertel 7552: 	my $line=&scantron_get_line($scanlines,$scan_data,$i);
1.186     albertel 7553: 	if ($line=~/^[\s\cz]*$/) { next; }
                   7554: 	my $scan_record=&scantron_parse_scanline($line,$i,\%scantron_config,
                   7555: 						 $scan_data);
                   7556: 	my $CODE=$$scan_record{'scantron.CODE'};
                   7557: 	my $error=0;
1.224     albertel 7558: 	if (!&Apache::lonnet::validCODE($CODE)) {
                   7559: 	    &scantron_get_correction($r,$i,$scan_record,
                   7560: 				     \%scantron_config,
                   7561: 				     $line,'incorrectCODE',\%allcodes);
                   7562: 	    return(1,$currentphase);
                   7563: 	}
1.221     albertel 7564: 	if (%allcodes && !exists($allcodes{$CODE}) 
                   7565: 	    && !$$scan_record{'scantron.useCODE'}) {
1.186     albertel 7566: 	    &scantron_get_correction($r,$i,$scan_record,
                   7567: 				     \%scantron_config,
1.194     albertel 7568: 				     $line,'incorrectCODE',\%allcodes);
                   7569: 	    return(1,$currentphase);
1.186     albertel 7570: 	}
1.214     albertel 7571: 	if (exists($usedCODEs{$CODE}) 
1.257     albertel 7572: 	    && $env{'form.scantron_CODEunique'} eq 'yes'
1.192     albertel 7573: 	    && !$$scan_record{'scantron.CODE_ignore_dup'}) {
1.186     albertel 7574: 	    &scantron_get_correction($r,$i,$scan_record,
                   7575: 				     \%scantron_config,
1.194     albertel 7576: 				     $line,'duplicateCODE',$usedCODEs{$CODE});
                   7577: 	    return(1,$currentphase);
1.186     albertel 7578: 	}
1.524     raeburn  7579: 	push(@{$usedCODEs{$CODE}},$$scan_record{'scantron.PaperID'});
1.186     albertel 7580:     }
1.157     albertel 7581:     return (0,$currentphase+1);
                   7582: }
                   7583: 
1.423     albertel 7584: =pod
                   7585: 
                   7586: =item scantron_validate_doublebubble
                   7587: 
1.424     albertel 7588:    Validates all scanlines in the selected file to not have any
                   7589:    bubble lines with multiple bubbles marked.
                   7590: 
1.423     albertel 7591: =cut
                   7592: 
1.157     albertel 7593: sub scantron_validate_doublebubble {
                   7594:     my ($r,$currentphase) = @_;
                   7595:     #get student info
                   7596:     my $classlist=&Apache::loncoursedata::get_classlist();
                   7597:     my %idmap=&username_to_idmap($classlist);
                   7598: 
                   7599:     #get scantron line setup
1.257     albertel 7600:     my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
1.157     albertel 7601:     my ($scanlines,$scan_data)=&scantron_getfile();
1.583     raeburn  7602:     my $nav_error;
                   7603:     &scantron_get_maxbubble(\$nav_error); # parse needs the bubble line array.
                   7604:     if ($nav_error) {
                   7605:         $r->print(&navmap_errormsg());
                   7606:         return(1,$currentphase);
                   7607:     }
1.447     foxr     7608: 
1.157     albertel 7609:     for (my $i=0;$i<=$scanlines->{'count'};$i++) {
1.200     albertel 7610: 	my $line=&scantron_get_line($scanlines,$scan_data,$i);
1.157     albertel 7611: 	if ($line=~/^[\s\cz]*$/) { next; }
                   7612: 	my $scan_record=&scantron_parse_scanline($line,$i,\%scantron_config,
                   7613: 						 $scan_data);
                   7614: 	if (!defined($$scan_record{'scantron.doubleerror'})) { next; }
                   7615: 	&scantron_get_correction($r,$i,$scan_record,\%scantron_config,$line,
                   7616: 				 'doublebubble',
                   7617: 				 $$scan_record{'scantron.doubleerror'});
                   7618:     	return (1,$currentphase);
                   7619:     }
                   7620:     return (0,$currentphase+1);
                   7621: }
                   7622: 
1.423     albertel 7623: 
1.503     raeburn  7624: sub scantron_get_maxbubble {
1.582     raeburn  7625:     my ($nav_error) = @_;
1.257     albertel 7626:     if (defined($env{'form.scantron_maxbubble'}) &&
                   7627: 	$env{'form.scantron_maxbubble'}) {
1.447     foxr     7628: 	&restore_bubble_lines();
1.257     albertel 7629: 	return $env{'form.scantron_maxbubble'};
1.191     albertel 7630:     }
1.330     albertel 7631: 
1.447     foxr     7632:     my (undef, undef, $sequence) =
1.257     albertel 7633: 	&Apache::lonnet::decode_symb($env{'form.selectpage'});
1.330     albertel 7634: 
1.447     foxr     7635:     my $navmap=Apache::lonnavmaps::navmap->new();
1.582     raeburn  7636:     unless (ref($navmap)) {
                   7637:         if (ref($nav_error)) {
                   7638:             $$nav_error = 1;
                   7639:         }
1.591     raeburn  7640:         return;
1.582     raeburn  7641:     }
1.191     albertel 7642:     my $map=$navmap->getResourceByUrl($sequence);
                   7643:     my @resources=$navmap->retrieveResources($map,\&scantron_filter,1,0);
1.330     albertel 7644: 
                   7645:     &Apache::lonxml::clear_problem_counter();
                   7646: 
1.557     raeburn  7647:     my $uname       = $env{'user.name'};
                   7648:     my $udom        = $env{'user.domain'};
1.435     foxr     7649:     my $cid         = $env{'request.course.id'};
                   7650:     my $total_lines = 0;
                   7651:     %bubble_lines_per_response = ();
1.447     foxr     7652:     %first_bubble_line         = ();
1.503     raeburn  7653:     %subdivided_bubble_lines   = ();
                   7654:     %responsetype_per_response = ();
1.554     raeburn  7655: 
1.447     foxr     7656:     my $response_number = 0;
                   7657:     my $bubble_line     = 0;
1.191     albertel 7658:     foreach my $resource (@resources) {
1.542     raeburn  7659:         my ($analysis,$parts) = &scantron_partids_tograde($resource,$cid,$uname,$udom);
                   7660:         if ((ref($analysis) eq 'HASH') && (ref($parts) eq 'ARRAY')) {
                   7661: 	    foreach my $part_id (@{$parts}) {
                   7662:                 my $lines;
                   7663: 
                   7664: 	        # TODO - make this a persistent hash not an array.
                   7665: 
                   7666:                 # optionresponse, matchresponse and rankresponse type items 
                   7667:                 # render as separate sub-questions in exam mode.
                   7668:                 if (($analysis->{$part_id.'.type'} eq 'optionresponse') ||
                   7669:                     ($analysis->{$part_id.'.type'} eq 'matchresponse') ||
                   7670:                     ($analysis->{$part_id.'.type'} eq 'rankresponse')) {
                   7671:                     my ($numbub,$numshown);
                   7672:                     if ($analysis->{$part_id.'.type'} eq 'optionresponse') {
                   7673:                         if (ref($analysis->{$part_id.'.options'}) eq 'ARRAY') {
                   7674:                             $numbub = scalar(@{$analysis->{$part_id.'.options'}});
                   7675:                         }
                   7676:                     } elsif ($analysis->{$part_id.'.type'} eq 'matchresponse') {
                   7677:                         if (ref($analysis->{$part_id.'.items'}) eq 'ARRAY') {
                   7678:                             $numbub = scalar(@{$analysis->{$part_id.'.items'}});
                   7679:                         }
                   7680:                     } elsif ($analysis->{$part_id.'.type'} eq 'rankresponse') {
                   7681:                         if (ref($analysis->{$part_id.'.foils'}) eq 'ARRAY') {
                   7682:                             $numbub = scalar(@{$analysis->{$part_id.'.foils'}});
                   7683:                         }
                   7684:                     }
                   7685:                     if (ref($analysis->{$part_id.'.shown'}) eq 'ARRAY') {
                   7686:                         $numshown = scalar(@{$analysis->{$part_id.'.shown'}});
                   7687:                     }
                   7688:                     my $bubbles_per_line = 10;
                   7689:                     my $inner_bubble_lines = int($numbub/$bubbles_per_line);
                   7690:                     if (($numbub % $bubbles_per_line) != 0) {
                   7691:                         $inner_bubble_lines++;
                   7692:                     }
                   7693:                     for (my $i=0; $i<$numshown; $i++) {
                   7694:                         $subdivided_bubble_lines{$response_number} .= 
                   7695:                             $inner_bubble_lines.',';
                   7696:                     }
                   7697:                     $subdivided_bubble_lines{$response_number} =~ s/,$//;
                   7698:                     $lines = $numshown * $inner_bubble_lines;
                   7699:                 } else {
                   7700:                     $lines = $analysis->{"$part_id.bubble_lines"};
                   7701:                 } 
                   7702: 
                   7703:                 $first_bubble_line{$response_number} = $bubble_line;
                   7704: 	        $bubble_lines_per_response{$response_number} = $lines;
                   7705:                 $responsetype_per_response{$response_number} = 
                   7706:                     $analysis->{$part_id.'.type'};
                   7707: 	        $response_number++;
                   7708: 
                   7709: 	        $bubble_line +=  $lines;
                   7710: 	        $total_lines +=  $lines;
                   7711: 	    }
                   7712:         }
                   7713:     }
1.552     raeburn  7714:     &Apache::lonnet::delenv('scantron.');
1.542     raeburn  7715: 
                   7716:     &save_bubble_lines();
                   7717:     $env{'form.scantron_maxbubble'} =
                   7718: 	$total_lines;
                   7719:     return $env{'form.scantron_maxbubble'};
                   7720: }
1.523     raeburn  7721: 
1.157     albertel 7722: sub scantron_validate_missingbubbles {
                   7723:     my ($r,$currentphase) = @_;
                   7724:     #get student info
                   7725:     my $classlist=&Apache::loncoursedata::get_classlist();
                   7726:     my %idmap=&username_to_idmap($classlist);
                   7727: 
                   7728:     #get scantron line setup
1.257     albertel 7729:     my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
1.157     albertel 7730:     my ($scanlines,$scan_data)=&scantron_getfile();
1.582     raeburn  7731:     my $nav_error;
                   7732:     my $max_bubble=&scantron_get_maxbubble(\$nav_error);
                   7733:     if ($nav_error) {
                   7734:         return(1,$currentphase);
                   7735:     }
1.157     albertel 7736:     if (!$max_bubble) { $max_bubble=2**31; }
                   7737:     for (my $i=0;$i<=$scanlines->{'count'};$i++) {
1.200     albertel 7738: 	my $line=&scantron_get_line($scanlines,$scan_data,$i);
1.157     albertel 7739: 	if ($line=~/^[\s\cz]*$/) { next; }
                   7740: 	my $scan_record=&scantron_parse_scanline($line,$i,\%scantron_config,
                   7741: 						 $scan_data);
                   7742: 	if (!defined($$scan_record{'scantron.missingerror'})) { next; }
                   7743: 	my @to_correct;
1.470     foxr     7744: 	
                   7745: 	# Probably here's where the error is...
                   7746: 
1.157     albertel 7747: 	foreach my $missing (@{$$scan_record{'scantron.missingerror'}}) {
1.505     raeburn  7748:             my $lastbubble;
                   7749:             if ($missing =~ /^(\d+)\.(\d+)$/) {
                   7750:                my $question = $1;
                   7751:                my $subquestion = $2;
                   7752:                if (!defined($first_bubble_line{$question -1})) { next; }
                   7753:                my $first = $first_bubble_line{$question-1};
                   7754:                my @subans = split(/,/,$subdivided_bubble_lines{$question-1});
                   7755:                my $subcount = 1;
                   7756:                while ($subcount<$subquestion) {
                   7757:                    $first += $subans[$subcount-1];
                   7758:                    $subcount ++;
                   7759:                }
                   7760:                my $count = $subans[$subquestion-1];
                   7761:                $lastbubble = $first + $count;
                   7762:             } else {
                   7763:                 if (!defined($first_bubble_line{$missing - 1})) { next; }
                   7764:                 $lastbubble = $first_bubble_line{$missing - 1} + $bubble_lines_per_response{$missing - 1};
                   7765:             }
                   7766:             if ($lastbubble > $max_bubble) { next; }
1.157     albertel 7767: 	    push(@to_correct,$missing);
                   7768: 	}
                   7769: 	if (@to_correct) {
                   7770: 	    &scantron_get_correction($r,$i,$scan_record,\%scantron_config,
                   7771: 				     $line,'missingbubble',\@to_correct);
                   7772: 	    return (1,$currentphase);
                   7773: 	}
                   7774: 
                   7775:     }
                   7776:     return (0,$currentphase+1);
                   7777: }
                   7778: 
1.423     albertel 7779: 
1.82      albertel 7780: sub scantron_process_students {
1.75      albertel 7781:     my ($r) = @_;
1.513     foxr     7782: 
1.257     albertel 7783:     my (undef,undef,$sequence)=&Apache::lonnet::decode_symb($env{'form.selectpage'});
1.324     albertel 7784:     my ($symb)=&get_symb($r);
1.513     foxr     7785:     if (!$symb) {
                   7786: 	return '';
                   7787:     }
1.324     albertel 7788:     my $default_form_data=&defaultFormData($symb);
1.82      albertel 7789: 
1.257     albertel 7790:     my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
1.157     albertel 7791:     my ($scanlines,$scan_data)=&scantron_getfile();
1.82      albertel 7792:     my $classlist=&Apache::loncoursedata::get_classlist();
                   7793:     my %idmap=&username_to_idmap($classlist);
1.132     bowersj2 7794:     my $navmap=Apache::lonnavmaps::navmap->new();
1.582     raeburn  7795:     unless (ref($navmap)) {
                   7796:         $r->print(&navmap_errormsg());
                   7797:         return '';
                   7798:     }  
1.83      albertel 7799:     my $map=$navmap->getResourceByUrl($sequence);
                   7800:     my @resources=$navmap->retrieveResources($map,\&scantron_filter,1,0);
1.557     raeburn  7801:     my (%grader_partids_by_symb,%grader_randomlists_by_symb);
                   7802:     &graders_resources_pass(\@resources,\%grader_partids_by_symb,
                   7803:                             \%grader_randomlists_by_symb);
1.586     raeburn  7804:     my $resource_error;
1.557     raeburn  7805:     foreach my $resource (@resources) {
1.586     raeburn  7806:         my $ressymb;
                   7807:         if (ref($resource)) {
                   7808:             $ressymb = $resource->symb();
                   7809:         } else {
                   7810:             $resource_error = 1;
                   7811:             last;
                   7812:         }
1.557     raeburn  7813:         my ($analysis,$parts) =
                   7814:             &scantron_partids_tograde($resource,$env{'request.course.id'},
                   7815:                                       $env{'user.name'},$env{'user.domain'},1);
                   7816:         $grader_partids_by_symb{$ressymb} = $parts;
                   7817:         if (ref($analysis) eq 'HASH') {
                   7818:             if (ref($analysis->{'parts_withrandomlist'}) eq 'ARRAY') {
                   7819:                 $grader_randomlists_by_symb{$ressymb} = 
                   7820:                     $analysis->{'parts_withrandomlist'};
                   7821:             }
                   7822:         }
                   7823:     }
1.586     raeburn  7824:     if ($resource_error) {
                   7825:         $r->print(&navmap_errormsg());
                   7826:         return '';
                   7827:     }
1.557     raeburn  7828: 
1.554     raeburn  7829:     my ($uname,$udom);
1.82      albertel 7830:     my $result= <<SCANTRONFORM;
1.81      albertel 7831: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="scantronupload">
                   7832:   <input type="hidden" name="command" value="scantron_configphase" />
                   7833:   $default_form_data
                   7834: SCANTRONFORM
1.82      albertel 7835:     $r->print($result);
                   7836: 
                   7837:     my @delayqueue;
1.542     raeburn  7838:     my (%completedstudents,%scandata);
1.140     albertel 7839:     
1.520     www      7840:     my $lock=&Apache::lonnet::set_lock(&mt('Grading bubblesheet exam'));
1.200     albertel 7841:     my $count=&get_todo_count($scanlines,$scan_data);
1.575     www      7842:     my %prog_state=&Apache::lonhtmlcommon::Create_PrgWin($r,'Bubblesheet Status',
                   7843:  				    'Bubblesheet Progress',$count,
1.195     albertel 7844: 				    'inline',undef,'scantronupload');
1.140     albertel 7845:     &Apache::lonhtmlcommon::Update_PrgWin($r,\%prog_state,
                   7846: 					  'Processing first student');
1.542     raeburn  7847:     $r->print('<br />');
1.140     albertel 7848:     my $start=&Time::HiRes::time();
1.158     albertel 7849:     my $i=-1;
1.542     raeburn  7850:     my $started;
1.447     foxr     7851: 
1.582     raeburn  7852:     my $nav_error;
                   7853:     &scantron_get_maxbubble(\$nav_error); # Need the bubble lines array to parse.
                   7854:     if ($nav_error) {
                   7855:         $r->print(&navmap_errormsg());
                   7856:         return '';
                   7857:     }
                   7858: 
1.513     foxr     7859:     # If an ssi failed in scantron_get_maxbubble, put an error message out to
                   7860:     # the user and return.
                   7861: 
                   7862:     if ($ssi_error) {
                   7863: 	$r->print("</form>");
                   7864: 	&ssi_print_error($r);
                   7865: 	$r->print(&show_grading_menu_form($symb));
1.520     www      7866:         &Apache::lonnet::remove_lock($lock);
1.513     foxr     7867: 	return '';		# Dunno why the other returns return '' rather than just returning.
                   7868:     }
1.447     foxr     7869: 
1.542     raeburn  7870:     my %lettdig = &letter_to_digits();
                   7871:     my $numletts = scalar(keys(%lettdig));
                   7872: 
1.157     albertel 7873:     while ($i<$scanlines->{'count'}) {
                   7874:  	($uname,$udom)=('','');
                   7875:  	$i++;
1.200     albertel 7876:  	my $line=&scantron_get_line($scanlines,$scan_data,$i);
1.157     albertel 7877:  	if ($line=~/^[\s\cz]*$/) { next; }
1.200     albertel 7878: 	if ($started) {
                   7879: 	    &Apache::lonhtmlcommon::Increment_PrgWin($r,\%prog_state,
                   7880: 						     'last student');
                   7881: 	}
                   7882: 	$started=1;
1.157     albertel 7883:  	my $scan_record=&scantron_parse_scanline($line,$i,\%scantron_config,
                   7884:  						 $scan_data);
                   7885:  	unless ($uname=&scantron_find_student($scan_record,$scan_data,
                   7886:  					      \%idmap,$i)) {
                   7887:   	    &scantron_add_delay(\@delayqueue,$line,
                   7888:  				'Unable to find a student that matches',1);
                   7889:  	    next;
                   7890:   	}
                   7891:  	if (exists $completedstudents{$uname}) {
                   7892:  	    &scantron_add_delay(\@delayqueue,$line,
                   7893:  				'Student '.$uname.' has multiple sheets',2);
                   7894:  	    next;
                   7895:  	}
                   7896:   	($uname,$udom)=split(/:/,$uname);
1.330     albertel 7897: 
1.586     raeburn  7898:         my (%partids_by_symb,$res_error);
1.554     raeburn  7899:         foreach my $resource (@resources) {
1.586     raeburn  7900:             my $ressymb;
                   7901:             if (ref($resource)) {
                   7902:                 $ressymb = $resource->symb();
                   7903:             } else {
                   7904:                 $res_error = 1;
                   7905:                 last;
                   7906:             }
1.557     raeburn  7907:             if ((exists($grader_randomlists_by_symb{$ressymb})) ||
                   7908:                 (ref($grader_partids_by_symb{$ressymb}) ne 'ARRAY')) {
                   7909:                 my ($analysis,$parts) =
                   7910:                     &scantron_partids_tograde($resource,$env{'request.course.id'},$uname,$udom);
                   7911:                 $partids_by_symb{$ressymb} = $parts;
                   7912:             } else {
                   7913:                 $partids_by_symb{$ressymb} = $grader_partids_by_symb{$ressymb};
                   7914:             }
1.554     raeburn  7915:         }
                   7916: 
1.586     raeburn  7917:         if ($res_error) {
                   7918:             &scantron_add_delay(\@delayqueue,$line,
                   7919:                                 'An error occurred while grading student '.$uname,2);
                   7920:             next;
                   7921:         }
                   7922: 
1.330     albertel 7923: 	&Apache::lonxml::clear_problem_counter();
1.514     raeburn  7924:   	&Apache::lonnet::appenv($scan_record);
1.376     albertel 7925: 
                   7926: 	if (&scantron_clear_skip($scanlines,$scan_data,$i)) {
                   7927: 	    &scantron_putfile($scanlines,$scan_data);
                   7928: 	}
1.161     albertel 7929: 	
1.542     raeburn  7930:         my $scancode;
                   7931:         if ((exists($scan_record->{'scantron.CODE'})) &&
                   7932:             (&Apache::lonnet::validCODE($scan_record->{'scantron.CODE'}))) {
                   7933:             $scancode = $scan_record->{'scantron.CODE'};
                   7934:         } else {
                   7935:             $scancode = '';
                   7936:         }
                   7937: 
                   7938:         if (&grade_student_bubbles($r,$uname,$udom,$scan_record,$scancode,
1.554     raeburn  7939:                                    \@resources,\%partids_by_symb) eq 'ssi_error') {
1.542     raeburn  7940:             $ssi_error = 0; # So end of handler error message does not trigger.
                   7941:             $r->print("</form>");
                   7942:             &ssi_print_error($r);
                   7943:             $r->print(&show_grading_menu_form($symb));
                   7944:             &Apache::lonnet::remove_lock($lock);
                   7945:             return '';      # Why return ''?  Beats me.
                   7946:         }
1.513     foxr     7947: 
1.140     albertel 7948: 	$completedstudents{$uname}={'line'=>$line};
1.542     raeburn  7949:         if ($env{'form.verifyrecord'}) {
                   7950:             my $lastpos = $env{'form.scantron_maxbubble'}*$scantron_config{'Qlength'};
                   7951:             my $studentdata = substr($line,$scantron_config{'Qstart'}-1,$lastpos);
                   7952:             chomp($studentdata);
                   7953:             $studentdata =~ s/\r$//;
                   7954:             my $studentrecord = '';
                   7955:             my $counter = -1;
                   7956:             foreach my $resource (@resources) {
1.554     raeburn  7957:                 my $ressymb = $resource->symb();
1.542     raeburn  7958:                 ($counter,my $recording) =
                   7959:                     &verify_scantron_grading($resource,$udom,$uname,$env{'request.course.id'},
1.554     raeburn  7960:                                              $counter,$studentdata,$partids_by_symb{$ressymb},
1.542     raeburn  7961:                                              \%scantron_config,\%lettdig,$numletts);
                   7962:                 $studentrecord .= $recording;
                   7963:             }
                   7964:             if ($studentrecord ne $studentdata) {
1.554     raeburn  7965:                 &Apache::lonxml::clear_problem_counter();
                   7966:                 if (&grade_student_bubbles($r,$uname,$udom,$scan_record,$scancode,
                   7967:                                            \@resources,\%partids_by_symb) eq 'ssi_error') {
                   7968:                     $ssi_error = 0; # So end of handler error message does not trigger.
                   7969:                     $r->print("</form>");
                   7970:                     &ssi_print_error($r);
                   7971:                     $r->print(&show_grading_menu_form($symb));
                   7972:                     &Apache::lonnet::remove_lock($lock);
                   7973:                     delete($completedstudents{$uname});
                   7974:                     return '';
                   7975:                 }
1.542     raeburn  7976:                 $counter = -1;
                   7977:                 $studentrecord = '';
                   7978:                 foreach my $resource (@resources) {
1.554     raeburn  7979:                     my $ressymb = $resource->symb();
1.542     raeburn  7980:                     ($counter,my $recording) =
                   7981:                         &verify_scantron_grading($resource,$udom,$uname,$env{'request.course.id'},
1.554     raeburn  7982:                                                  $counter,$studentdata,$partids_by_symb{$ressymb},
1.542     raeburn  7983:                                                  \%scantron_config,\%lettdig,$numletts);
                   7984:                     $studentrecord .= $recording;
                   7985:                 }
                   7986:                 if ($studentrecord ne $studentdata) {
1.596.2.6  raeburn  7987:                     $r->print('<p><span class="LC_warning">');
1.542     raeburn  7988:                     if ($scancode eq '') {
1.596.2.6  raeburn  7989:                         $r->print(&mt('Mismatch grading bubblesheet for user: [_1] with ID: [_2].',
1.542     raeburn  7990:                                   $uname.':'.$udom,$scan_record->{'scantron.ID'}));
                   7991:                     } else {
1.596.2.6  raeburn  7992:                         $r->print(&mt('Mismatch grading bubblesheet for user: [_1] with ID: [_2] and CODE: [_3].',
1.542     raeburn  7993:                                   $uname.':'.$udom,$scan_record->{'scantron.ID'},$scancode));
                   7994:                     }
                   7995:                     $r->print('</span><br />'.&Apache::loncommon::start_data_table()."\n".
                   7996:                               &Apache::loncommon::start_data_table_header_row()."\n".
                   7997:                               '<th>'.&mt('Source').'</th><th>'.&mt('Bubbled responses').'</th>'.
                   7998:                               &Apache::loncommon::end_data_table_header_row()."\n".
                   7999:                               &Apache::loncommon::start_data_table_row().
1.596.2.6  raeburn  8000:                               '<td>'.&mt('Bubblesheet').'</td>'.
1.542     raeburn  8001:                               '<td><span class="LC_nobreak">'.$studentdata.'</span></td>'.
                   8002:                               &Apache::loncommon::end_data_table_row().
                   8003:                               &Apache::loncommon::start_data_table_row().
1.596.2.6  raeburn  8004:                               '<td>'.&mt('Stored submissions').'</td>'.
1.542     raeburn  8005:                               '<td><span class="LC_nobreak">'.$studentrecord.'</span></td>'."\n".
                   8006:                               &Apache::loncommon::end_data_table_row().
                   8007:                               &Apache::loncommon::end_data_table().'</p>');
                   8008:                 } else {
                   8009:                     $r->print('<br /><span class="LC_warning">'.
                   8010:                              &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 />'.
                   8011:                              &mt("As a consequence, this user's submission history records two tries.").
                   8012:                                  '</span><br />');
                   8013:                 }
                   8014:             }
                   8015:         }
1.543     raeburn  8016:         if (&Apache::loncommon::connection_aborted($r)) { last; }
1.140     albertel 8017:     } continue {
1.330     albertel 8018: 	&Apache::lonxml::clear_problem_counter();
1.552     raeburn  8019: 	&Apache::lonnet::delenv('scantron.');
1.82      albertel 8020:     }
1.140     albertel 8021:     &Apache::lonhtmlcommon::Close_PrgWin($r,\%prog_state);
1.520     www      8022:     &Apache::lonnet::remove_lock($lock);
1.172     albertel 8023: #    my $lasttime = &Time::HiRes::time()-$start;
                   8024: #    $r->print("<p>took $lasttime</p>");
1.140     albertel 8025: 
1.200     albertel 8026:     $r->print("</form>");
1.324     albertel 8027:     $r->print(&show_grading_menu_form($symb));
1.157     albertel 8028:     return '';
1.75      albertel 8029: }
1.157     albertel 8030: 
1.557     raeburn  8031: sub graders_resources_pass {
                   8032:     my ($resources,$grader_partids_by_symb,$grader_randomlists_by_symb) = @_;
                   8033:     if ((ref($resources) eq 'ARRAY') && (ref($grader_partids_by_symb)) && 
                   8034:         (ref($grader_randomlists_by_symb) eq 'HASH')) {
                   8035:         foreach my $resource (@{$resources}) {
                   8036:             my $ressymb = $resource->symb();
                   8037:             my ($analysis,$parts) =
                   8038:                 &scantron_partids_tograde($resource,$env{'request.course.id'},
                   8039:                                           $env{'user.name'},$env{'user.domain'},1);
                   8040:             $grader_partids_by_symb->{$ressymb} = $parts;
                   8041:             if (ref($analysis) eq 'HASH') {
                   8042:                 if (ref($analysis->{'parts_withrandomlist'}) eq 'ARRAY') {
                   8043:                     $grader_randomlists_by_symb->{$ressymb} =
                   8044:                         $analysis->{'parts_withrandomlist'};
                   8045:                 }
                   8046:             }
                   8047:         }
                   8048:     }
                   8049:     return;
                   8050: }
                   8051: 
1.542     raeburn  8052: sub grade_student_bubbles {
1.554     raeburn  8053:     my ($r,$uname,$udom,$scan_record,$scancode,$resources,$parts) = @_;
                   8054:     if (ref($resources) eq 'ARRAY') {
                   8055:         my $count = 0;
                   8056:         foreach my $resource (@{$resources}) {
                   8057:             my $ressymb = $resource->symb();
                   8058:             my %form = ('submitted'      => 'scantron',
                   8059:                         'grade_target'   => 'grade',
                   8060:                         'grade_username' => $uname,
                   8061:                         'grade_domain'   => $udom,
                   8062:                         'grade_courseid' => $env{'request.course.id'},
                   8063:                         'grade_symb'     => $ressymb,
                   8064:                         'CODE'           => $scancode
                   8065:                        );
                   8066:             if (ref($parts) eq 'HASH') {
                   8067:                 if (ref($parts->{$ressymb}) eq 'ARRAY') {
                   8068:                     foreach my $part (@{$parts->{$ressymb}}) {
                   8069:                         $form{'scantron_questnum_start.'.$part} =
                   8070:                             1+$env{'form.scantron.first_bubble_line.'.$count};
                   8071:                         $count++;
                   8072:                     }
                   8073:                 }
                   8074:             }
                   8075:             my $result=&ssi_with_retries($resource->src(),$ssi_retries,%form);
                   8076:             return 'ssi_error' if ($ssi_error);
                   8077:             last if (&Apache::loncommon::connection_aborted($r));
                   8078:         }
1.542     raeburn  8079:     }
                   8080:     return;
                   8081: }
                   8082: 
1.157     albertel 8083: sub scantron_upload_scantron_data {
                   8084:     my ($r)=@_;
1.565     raeburn  8085:     my $dom = $env{'request.role.domain'};
                   8086:     my $domdesc = &Apache::lonnet::domain($dom,'description');
                   8087:     $r->print(&Apache::loncommon::coursebrowser_javascript($dom));
1.157     albertel 8088:     my $select_link=&Apache::loncommon::selectcourse_link('rules','courseid',
1.181     albertel 8089: 							  'domainid',
1.565     raeburn  8090: 							  'coursename',$dom);
                   8091:     my $syllabuslink = '<a href="javascript:ToSyllabus();">'.&mt('Syllabus').'</a>'.
                   8092:                        ('&nbsp'x2).&mt('(shows course personnel)'); 
1.324     albertel 8093:     my $default_form_data=&defaultFormData(&get_symb($r,1));
1.579     raeburn  8094:     my $nofile_alert = &mt('Please use the browse button to select a file from your local directory.');
                   8095:     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 8096:     $r->print('
1.157     albertel 8097: <script type="text/javascript" language="javascript">
                   8098:     function checkUpload(formname) {
                   8099: 	if (formname.upfile.value == "") {
1.579     raeburn  8100: 	    alert("'.$nofile_alert.'");
1.157     albertel 8101: 	    return false;
                   8102: 	}
1.565     raeburn  8103:         if (formname.courseid.value == "") {
1.579     raeburn  8104:             alert("'.$nocourseid_alert.'");
1.565     raeburn  8105:             return false;
                   8106:         }
1.157     albertel 8107: 	formname.submit();
                   8108:     }
1.565     raeburn  8109: 
                   8110:     function ToSyllabus() {
                   8111:         var cdom = '."'$dom'".';
                   8112:         var cnum = document.rules.courseid.value;
                   8113:         if (cdom == "" || cdom == null) {
                   8114:             return;
                   8115:         }
                   8116:         if (cnum == "" || cnum == null) {
                   8117:            return;
                   8118:         }
                   8119:         syllwin=window.open("/public/"+cdom+"/"+cnum+"/syllabus","LONCAPASyllabus",
                   8120:                             "height=350,width=350,scrollbars=yes,menubar=no");
                   8121:         return;
                   8122:     }
                   8123: 
1.157     albertel 8124: </script>
                   8125: 
1.596.2.4  raeburn  8126: <h3>'.&mt('Send bubblesheet data to a course').'</h3>
1.566     raeburn  8127: 
1.492     albertel 8128: <form enctype="multipart/form-data" action="/adm/grades" name="rules" method="post">
1.565     raeburn  8129: '.$default_form_data.
                   8130:   &Apache::lonhtmlcommon::start_pick_box().
                   8131:   &Apache::lonhtmlcommon::row_title(&mt('Course ID')).
                   8132:   '<input name="courseid" type="text" size="30" />'.$select_link.
                   8133:   &Apache::lonhtmlcommon::row_closure().
                   8134:   &Apache::lonhtmlcommon::row_title(&mt('Course Name')).
                   8135:   '<input name="coursename" type="text" size="30" />'.$syllabuslink.
                   8136:   &Apache::lonhtmlcommon::row_closure().
                   8137:   &Apache::lonhtmlcommon::row_title(&mt('Domain')).
                   8138:   '<input name="domainid" type="hidden" />'.$domdesc.
                   8139:   &Apache::lonhtmlcommon::row_closure().
                   8140:   &Apache::lonhtmlcommon::row_title(&mt('File to upload')).
                   8141:   '<input type="file" name="upfile" size="50" />'.
                   8142:   &Apache::lonhtmlcommon::row_closure(1).
                   8143:   &Apache::lonhtmlcommon::end_pick_box().'<br />
                   8144: 
1.492     albertel 8145: <input name="command" value="scantronupload_save" type="hidden" />
1.589     bisitz   8146: <input type="button" onclick="javascript:checkUpload(this.form);" value="'.&mt('Upload Bubblesheet Data').'" />
1.157     albertel 8147: </form>
1.492     albertel 8148: ');
1.157     albertel 8149:     return '';
                   8150: }
                   8151: 
1.423     albertel 8152: 
1.157     albertel 8153: sub scantron_upload_scantron_data_save {
                   8154:     my($r)=@_;
1.324     albertel 8155:     my ($symb)=&get_symb($r,1);
1.182     albertel 8156:     my $doanotherupload=
                   8157: 	'<br /><form action="/adm/grades" method="post">'."\n".
                   8158: 	'<input type="hidden" name="command" value="scantronupload" />'."\n".
1.492     albertel 8159: 	'<input type="submit" name="submit" value="'.&mt('Do Another Upload').'" />'."\n".
1.182     albertel 8160: 	'</form>'."\n";
1.257     albertel 8161:     if (!&Apache::lonnet::allowed('usc',$env{'form.domainid'}) &&
1.162     albertel 8162: 	!&Apache::lonnet::allowed('usc',
1.257     albertel 8163: 			    $env{'form.domainid'}.'_'.$env{'form.courseid'})) {
1.575     www      8164: 	$r->print(&mt("You are not allowed to upload bubblesheet data to the requested course.")."<br />");
1.182     albertel 8165: 	if ($symb) {
1.324     albertel 8166: 	    $r->print(&show_grading_menu_form($symb));
1.182     albertel 8167: 	} else {
                   8168: 	    $r->print($doanotherupload);
                   8169: 	}
1.162     albertel 8170: 	return '';
                   8171:     }
1.257     albertel 8172:     my %coursedata=&Apache::lonnet::coursedescription($env{'form.domainid'}.'_'.$env{'form.courseid'});
1.568     raeburn  8173:     my $uploadedfile;
1.567     raeburn  8174:     $r->print('<h3>'.&mt("Uploading file to [_1]",$coursedata{'description'}).'</h3>');
1.257     albertel 8175:     if (length($env{'form.upfile'}) < 2) {
1.568     raeburn  8176:         $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 8177:     } else {
1.568     raeburn  8178:         my $result = 
                   8179:             &Apache::lonnet::userfileupload('upfile','','scantron','','','',
                   8180:                                             $env{'form.courseid'},$env{'form.domainid'});
                   8181: 	if ($result =~ m{^/uploaded/}) {
1.567     raeburn  8182: 	    $r->print(&mt('[_1]Success:[_2] Successfully uploaded [_3] bytes of data into location: [_4]',
                   8183:                           '<span class="LC_success">','</span>',(length($env{'form.upfile'})-1),
                   8184: 			  '<span class="LC_filename">'.$result.'</span>'));
1.568     raeburn  8185:             ($uploadedfile) = ($result =~ m{/([^/]+)$});
1.567     raeburn  8186:             $r->print(&validate_uploaded_scantron_file($env{'form.domainid'},
1.568     raeburn  8187:                                                        $env{'form.courseid'},$uploadedfile));
1.210     albertel 8188: 	} else {
1.567     raeburn  8189: 	    $r->print(&mt('[_1]Error:[_2] An error ([_3]) occurred when attempting to upload the file, [_4]',
                   8190:                           '<span class="LC_error">','</span>',$result,
1.568     raeburn  8191: 			  '<span class="LC_filename">'.&HTML::Entities::encode($env{'form.upfile.filename'},'<>&"').'</span>'));
1.183     albertel 8192: 	}
                   8193:     }
1.174     albertel 8194:     if ($symb) {
1.209     ng       8195: 	$r->print(&scantron_selectphase($r,$uploadedfile));
1.174     albertel 8196:     } else {
1.182     albertel 8197: 	$r->print($doanotherupload);
1.174     albertel 8198:     }
1.157     albertel 8199:     return '';
                   8200: }
                   8201: 
1.567     raeburn  8202: sub validate_uploaded_scantron_file {
                   8203:     my ($cdom,$cname,$fname) = @_;
                   8204:     my $scanlines=&Apache::lonnet::getfile('/uploaded/'.$cdom.'/'.$cname.'/'.$fname);
                   8205:     my @lines;
                   8206:     if ($scanlines ne '-1') {
                   8207:         @lines=split("\n",$scanlines,-1);
                   8208:     }
                   8209:     my $output;
                   8210:     if (@lines) {
                   8211:         my (%counts,$max_match_format);
                   8212:         my ($max_match_count,$max_match_pct) = (0,0);
                   8213:         my $classlist = &Apache::loncoursedata::get_classlist($cdom,$cname);
                   8214:         my %idmap = &username_to_idmap($classlist);
                   8215:         foreach my $key (keys(%idmap)) {
                   8216:             my $lckey = lc($key);
                   8217:             $idmap{$lckey} = $idmap{$key};
                   8218:         }
                   8219:         my %unique_formats;
                   8220:         my @formatlines = &get_scantronformat_file();
                   8221:         foreach my $line (@formatlines) {
                   8222:             chomp($line);
                   8223:             my @config = split(/:/,$line);
                   8224:             my $idstart = $config[5];
                   8225:             my $idlength = $config[6];
                   8226:             if (($idstart ne '') && ($idlength > 0)) {
                   8227:                 if (ref($unique_formats{$idstart.':'.$idlength}) eq 'ARRAY') {
                   8228:                     push(@{$unique_formats{$idstart.':'.$idlength}},$config[0].':'.$config[1]); 
                   8229:                 } else {
                   8230:                     $unique_formats{$idstart.':'.$idlength} = [$config[0].':'.$config[1]];
                   8231:                 }
                   8232:             }
                   8233:         }
                   8234:         foreach my $key (keys(%unique_formats)) {
                   8235:             my ($idstart,$idlength) = split(':',$key);
                   8236:             %{$counts{$key}} = (
                   8237:                                'found'   => 0,
                   8238:                                'total'   => 0,
                   8239:                               );
                   8240:             foreach my $line (@lines) {
                   8241:                 next if ($line =~ /^#/);
                   8242:                 next if ($line =~ /^[\s\cz]*$/);
                   8243:                 my $id = substr($line,$idstart-1,$idlength);
                   8244:                 $id = lc($id);
                   8245:                 if (exists($idmap{$id})) {
                   8246:                     $counts{$key}{'found'} ++;
                   8247:                 }
                   8248:                 $counts{$key}{'total'} ++;
                   8249:             }
                   8250:             if ($counts{$key}{'total'}) {
                   8251:                 my $percent_match = (100*$counts{$key}{'found'})/($counts{$key}{'total'});
                   8252:                 if (($max_match_format eq '') || ($percent_match > $max_match_pct)) {
                   8253:                     $max_match_pct = $percent_match;
                   8254:                     $max_match_format = $key;
                   8255:                     $max_match_count = $counts{$key}{'total'};
                   8256:                 }
                   8257:             }
                   8258:         }
                   8259:         if (ref($unique_formats{$max_match_format}) eq 'ARRAY') {
                   8260:             my $format_descs;
                   8261:             my $numwithformat = @{$unique_formats{$max_match_format}};
                   8262:             for (my $i=0; $i<$numwithformat; $i++) {
                   8263:                 my ($name,$desc) = split(':',$unique_formats{$max_match_format}[$i]);
                   8264:                 if ($i<$numwithformat-2) {
                   8265:                     $format_descs .= '"<i>'.$desc.'</i>", ';
                   8266:                 } elsif ($i==$numwithformat-2) {
                   8267:                     $format_descs .= '"<i>'.$desc.'</i>" '.&mt('and').' ';
                   8268:                 } elsif ($i==$numwithformat-1) {
                   8269:                     $format_descs .= '"<i>'.$desc.'</i>"';
                   8270:                 }
                   8271:             }
                   8272:             my $showpct = sprintf("%.0f",$max_match_pct).'%';
                   8273:             $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).
                   8274:                        '<br />'.&mt('A low percentage of matches results from one of the following:').'<ul>'.
                   8275:                        '<li>'.&mt('The file was uploaded to the wrong course').'</li>'.
                   8276:                        '<li>'.&mt('The data are not in the format expected for the domain: [_1]',
                   8277:                                   '<i>'.$cdom.'</i>').'</li>'.
                   8278:                        '<li>'.&mt('Students did not bubble their IDs, or mis-bubbled them').'</li>'.
                   8279:                        '<li>'.&mt('The course roster is not up to date').'</li>'.
                   8280:                        '</ul>';
                   8281:         }
                   8282:     } else {
                   8283:         $output = '<span class="LC_warning">'.&mt('Uploaded file contained no data').'</span>';
                   8284:     }
                   8285:     return $output;
                   8286: }
                   8287: 
1.202     albertel 8288: sub valid_file {
                   8289:     my ($requested_file)=@_;
                   8290:     foreach my $filename (sort(&scantron_filenames())) {
                   8291: 	if ($requested_file eq $filename) { return 1; }
                   8292:     }
                   8293:     return 0;
                   8294: }
                   8295: 
                   8296: sub scantron_download_scantron_data {
                   8297:     my ($r)=@_;
1.324     albertel 8298:     my $default_form_data=&defaultFormData(&get_symb($r,1));
1.257     albertel 8299:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   8300:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
                   8301:     my $file=$env{'form.scantron_selectfile'};
1.202     albertel 8302:     if (! &valid_file($file)) {
1.492     albertel 8303: 	$r->print('
1.202     albertel 8304: 	<p>
1.492     albertel 8305: 	    '.&mt('The requested file name was invalid.').'
1.202     albertel 8306:         </p>
1.492     albertel 8307: ');
1.324     albertel 8308: 	$r->print(&show_grading_menu_form(&get_symb($r,1)));
1.202     albertel 8309: 	return;
                   8310:     }
                   8311:     my $orig='/uploaded/'.$cdom.'/'.$cname.'/scantron_orig_'.$file;
                   8312:     my $corrected='/uploaded/'.$cdom.'/'.$cname.'/scantron_corrected_'.$file;
                   8313:     my $skipped='/uploaded/'.$cdom.'/'.$cname.'/scantron_skipped_'.$file;
                   8314:     &Apache::lonnet::allowuploaded('/adm/grades',$orig);
                   8315:     &Apache::lonnet::allowuploaded('/adm/grades',$corrected);
                   8316:     &Apache::lonnet::allowuploaded('/adm/grades',$skipped);
1.492     albertel 8317:     $r->print('
1.202     albertel 8318:     <p>
1.492     albertel 8319: 	'.&mt('[_1]Original[_2] file as uploaded by the scantron office.',
                   8320: 	      '<a href="'.$orig.'">','</a>').'
1.202     albertel 8321:     </p>
                   8322:     <p>
1.492     albertel 8323: 	'.&mt('[_1]Corrections[_2], a file of corrected records that were used in grading.',
                   8324: 	      '<a href="'.$corrected.'">','</a>').'
1.202     albertel 8325:     </p>
                   8326:     <p>
1.492     albertel 8327: 	'.&mt('[_1]Skipped[_2], a file of records that were skipped.',
                   8328: 	      '<a href="'.$skipped.'">','</a>').'
1.202     albertel 8329:     </p>
1.492     albertel 8330: ');
1.324     albertel 8331:     $r->print(&show_grading_menu_form(&get_symb($r,1)));
1.202     albertel 8332:     return '';
                   8333: }
1.157     albertel 8334: 
1.523     raeburn  8335: sub checkscantron_results {
                   8336:     my ($r) = @_;
                   8337:     my ($symb)=&get_symb($r);
                   8338:     if (!$symb) {return '';}
                   8339:     my $grading_menu_button=&show_grading_menu_form($symb);
                   8340:     my $cid = $env{'request.course.id'};
1.542     raeburn  8341:     my %lettdig = &letter_to_digits();
1.523     raeburn  8342:     my $numletts = scalar(keys(%lettdig));
                   8343:     my $cnum = $env{'course.'.$cid.'.num'};
                   8344:     my $cdom = $env{'course.'.$cid.'.domain'};
                   8345:     my (undef, undef, $sequence) = &Apache::lonnet::decode_symb($env{'form.selectpage'});
                   8346:     my %record;
                   8347:     my %scantron_config =
                   8348:         &Apache::grades::get_scantron_config($env{'form.scantron_format'});
                   8349:     my ($scanlines,$scan_data)=&Apache::grades::scantron_getfile();
                   8350:     my $classlist=&Apache::loncoursedata::get_classlist();
                   8351:     my %idmap=&Apache::grades::username_to_idmap($classlist);
                   8352:     my $navmap=Apache::lonnavmaps::navmap->new();
1.582     raeburn  8353:     unless (ref($navmap)) {
                   8354:         $r->print(&navmap_errormsg());
                   8355:         return '';
                   8356:     }
1.523     raeburn  8357:     my $map=$navmap->getResourceByUrl($sequence);
1.557     raeburn  8358:     my @resources=$navmap->retrieveResources($map,\&scantron_filter,1,0);
                   8359:     my (%grader_partids_by_symb,%grader_randomlists_by_symb);
                   8360:     &graders_resources_pass(\@resources,\%grader_partids_by_symb,                             \%grader_randomlists_by_symb);
                   8361: 
1.554     raeburn  8362:     my ($uname,$udom);
1.523     raeburn  8363:     my (%scandata,%lastname,%bylast);
                   8364:     $r->print('
                   8365: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="checkscantron">'."\n");
                   8366: 
                   8367:     my @delayqueue;
                   8368:     my %completedstudents;
                   8369: 
                   8370:     my $count=&Apache::grades::get_todo_count($scanlines,$scan_data);
1.581     www      8371:     my %prog_state=&Apache::lonhtmlcommon::Create_PrgWin($r,'Bubblesheet/Submissions Comparison Status',
                   8372:                                     'Progress of Bubblesheet Data/Submission Records Comparison',$count,
1.523     raeburn  8373:                                     'inline',undef,'checkscantron');
1.546     raeburn  8374:     my ($username,$domain,$started);
1.582     raeburn  8375:     my $nav_error;
                   8376:     &scantron_get_maxbubble(\$nav_error); # Need the bubble lines array to parse.
                   8377:     if ($nav_error) {
                   8378:         $r->print(&navmap_errormsg());
                   8379:         return '';
                   8380:     }
1.523     raeburn  8381: 
                   8382:     &Apache::lonhtmlcommon::Update_PrgWin($r,\%prog_state,
                   8383:                                           'Processing first student');
                   8384:     my $start=&Time::HiRes::time();
                   8385:     my $i=-1;
                   8386: 
                   8387:     while ($i<$scanlines->{'count'}) {
                   8388:         ($username,$domain,$uname)=('','','');
                   8389:         $i++;
                   8390:         my $line=&Apache::grades::scantron_get_line($scanlines,$scan_data,$i);
                   8391:         if ($line=~/^[\s\cz]*$/) { next; }
                   8392:         if ($started) {
                   8393:             &Apache::lonhtmlcommon::Increment_PrgWin($r,\%prog_state,
                   8394:                                                      'last student');
                   8395:         }
                   8396:         $started=1;
                   8397:         my $scan_record=
                   8398:             &Apache::grades::scantron_parse_scanline($line,$i,\%scantron_config,
                   8399:                                                      $scan_data);
                   8400:         unless ($uname=&Apache::grades::scantron_find_student($scan_record,$scan_data,
                   8401:                                                               \%idmap,$i)) {
                   8402:             &Apache::grades::scantron_add_delay(\@delayqueue,$line,
                   8403:                                 'Unable to find a student that matches',1);
                   8404:             next;
                   8405:         }
                   8406:         if (exists $completedstudents{$uname}) {
                   8407:             &Apache::grades::scantron_add_delay(\@delayqueue,$line,
                   8408:                                 'Student '.$uname.' has multiple sheets',2);
                   8409:             next;
                   8410:         }
                   8411:         my $pid = $scan_record->{'scantron.ID'};
                   8412:         $lastname{$pid} = $scan_record->{'scantron.LastName'};
                   8413:         push(@{$bylast{$lastname{$pid}}},$pid);
                   8414:         my $lastpos = $env{'form.scantron_maxbubble'}*$scantron_config{'Qlength'};
                   8415:         $scandata{$pid} = substr($line,$scantron_config{'Qstart'}-1,$lastpos);
                   8416:         chomp($scandata{$pid});
                   8417:         $scandata{$pid} =~ s/\r$//;
                   8418:         ($username,$domain)=split(/:/,$uname);
                   8419:         my $counter = -1;
                   8420:         foreach my $resource (@resources) {
1.557     raeburn  8421:             my $parts;
1.554     raeburn  8422:             my $ressymb = $resource->symb();
1.557     raeburn  8423:             if ((exists($grader_randomlists_by_symb{$ressymb})) ||
                   8424:                 (ref($grader_partids_by_symb{$ressymb}) ne 'ARRAY')) {
                   8425:                 (my $analysis,$parts) =
                   8426:                     &scantron_partids_tograde($resource,$env{'request.course.id'},$username,$domain);
                   8427:             } else {
                   8428:                 $parts = $grader_partids_by_symb{$ressymb};
                   8429:             }
1.542     raeburn  8430:             ($counter,my $recording) =
                   8431:                 &verify_scantron_grading($resource,$domain,$username,$cid,$counter,
1.554     raeburn  8432:                                          $scandata{$pid},$parts,
1.542     raeburn  8433:                                          \%scantron_config,\%lettdig,$numletts);
                   8434:             $record{$pid} .= $recording;
1.523     raeburn  8435:         }
                   8436:     }
                   8437:     &Apache::lonhtmlcommon::Close_PrgWin($r,\%prog_state);
                   8438:     $r->print('<br />');
                   8439:     my ($okstudents,$badstudents,$numstudents,$passed,$failed);
                   8440:     $passed = 0;
                   8441:     $failed = 0;
                   8442:     $numstudents = 0;
                   8443:     foreach my $last (sort(keys(%bylast))) {
                   8444:         if (ref($bylast{$last}) eq 'ARRAY') {
                   8445:             foreach my $pid (sort(@{$bylast{$last}})) {
                   8446:                 my $showscandata = $scandata{$pid};
                   8447:                 my $showrecord = $record{$pid};
                   8448:                 $showscandata =~ s/\s/&nbsp;/g;
                   8449:                 $showrecord =~ s/\s/&nbsp;/g;
                   8450:                 if ($scandata{$pid} eq $record{$pid}) {
                   8451:                     my $css_class = ($passed % 2)?'LC_odd_row':'LC_even_row';
                   8452:                     $okstudents .= '<tr class="'.$css_class.'">'.
1.581     www      8453: '<td>'.&mt('Bubblesheet').'</td><td>'.$showscandata.'</td><td rowspan="2">'.$last.'</td><td rowspan="2">'.$pid.'</td>'."\n".
1.523     raeburn  8454: '</tr>'."\n".
                   8455: '<tr class="'.$css_class.'">'."\n".
                   8456: '<td>Submissions</td><td>'.$showrecord.'</td></tr>'."\n";
                   8457:                     $passed ++;
                   8458:                 } else {
                   8459:                     my $css_class = ($failed % 2)?'LC_odd_row':'LC_even_row';
1.581     www      8460:                     $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  8461: '</tr>'."\n".
                   8462: '<tr class="'.$css_class.'">'."\n".
                   8463: '<td>Submissions</td><td><span class="LC_nobreak">'.$record{$pid}.'</span></td>'."\n".
                   8464: '</tr>'."\n";
                   8465:                     $failed ++;
                   8466:                 }
                   8467:                 $numstudents ++;
                   8468:             }
                   8469:         }
                   8470:     }
1.596.2.4  raeburn  8471:     $r->print('<p>'.
1.596.2.8  raeburn  8472:               &mt('Comparison of bubblesheet data (including corrections) with corresponding submission records (most recent submission) for [_1][quant,_2,student][_3] ([quant,_4,bubblesheet line] per student).',
1.596.2.4  raeburn  8473:                   '<b>',
                   8474:                   $numstudents,
                   8475:                   '</b>',
                   8476:                   $env{'form.scantron_maxbubble'}).
                   8477:               '</p>'
                   8478:     );
1.523     raeburn  8479:     $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>');
                   8480:     if ($passed) {
1.572     www      8481:         $r->print(&mt('Students with exact correspondence between bubblesheet data and submissions are as follows:').'<br /><br />');
1.523     raeburn  8482:         $r->print(&Apache::loncommon::start_data_table()."\n".
                   8483:                  &Apache::loncommon::start_data_table_header_row()."\n".
                   8484:                  '<th>'.&mt('Source').'</th><th>'.&mt('Bubble records').'</th><th>'.&mt('Name').'</th><th>'.&mt('ID').'</th>'.
                   8485:                  &Apache::loncommon::end_data_table_header_row()."\n".
                   8486:                  $okstudents."\n".
                   8487:                  &Apache::loncommon::end_data_table().'<br />');
                   8488:     }
                   8489:     if ($failed) {
1.572     www      8490:         $r->print(&mt('Students with differences between bubblesheet data and submissions are as follows:').'<br /><br />');
1.523     raeburn  8491:         $r->print(&Apache::loncommon::start_data_table()."\n".
                   8492:                  &Apache::loncommon::start_data_table_header_row()."\n".
                   8493:                  '<th>'.&mt('Source').'</th><th>'.&mt('Bubble records').'</th><th>'.&mt('Name').'</th><th>'.&mt('ID').'</th>'.
                   8494:                  &Apache::loncommon::end_data_table_header_row()."\n".
                   8495:                  $badstudents."\n".
                   8496:                  &Apache::loncommon::end_data_table()).'<br />'.
1.572     www      8497:                  &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  8498:     }
                   8499:     $r->print('</form><br />'.$grading_menu_button);
                   8500:     return;
                   8501: }
                   8502: 
1.542     raeburn  8503: sub verify_scantron_grading {
1.554     raeburn  8504:     my ($resource,$domain,$username,$cid,$counter,$scandata,$partids,
1.542     raeburn  8505:         $scantron_config,$lettdig,$numletts) = @_;
                   8506:     my ($record,%expected,%startpos);
                   8507:     return ($counter,$record) if (!ref($resource));
                   8508:     return ($counter,$record) if (!$resource->is_problem());
                   8509:     my $symb = $resource->symb();
1.554     raeburn  8510:     return ($counter,$record) if (ref($partids) ne 'ARRAY');
                   8511:     foreach my $part_id (@{$partids}) {
1.542     raeburn  8512:         $counter ++;
                   8513:         $expected{$part_id} = 0;
                   8514:         if ($env{"form.scantron.sub_bubblelines.$counter"}) {
                   8515:             my @sub_lines = split(/,/,$env{"form.scantron.sub_bubblelines.$counter"});
                   8516:             foreach my $item (@sub_lines) {
                   8517:                 $expected{$part_id} += $item;
                   8518:             }
                   8519:         } else {
                   8520:             $expected{$part_id} = $env{"form.scantron.bubblelines.$counter"};
                   8521:         }
                   8522:         $startpos{$part_id} = $env{"form.scantron.first_bubble_line.$counter"};
                   8523:     }
                   8524:     if ($symb) {
                   8525:         my %recorded;
                   8526:         my (%returnhash) = &Apache::lonnet::restore($symb,$cid,$domain,$username);
                   8527:         if ($returnhash{'version'}) {
                   8528:             my %lasthash=();
                   8529:             my $version;
                   8530:             for ($version=1;$version<=$returnhash{'version'};$version++) {
                   8531:                 foreach my $key (sort(split(/\:/,$returnhash{$version.':keys'}))) {
                   8532:                     $lasthash{$key}=$returnhash{$version.':'.$key};
                   8533:                 }
                   8534:             }
                   8535:             foreach my $key (keys(%lasthash)) {
                   8536:                 if ($key =~ /\.scantron$/) {
                   8537:                     my $value = &unescape($lasthash{$key});
                   8538:                     my ($part_id) = ($key =~ /^resource\.(.+)\.scantron$/);
                   8539:                     if ($value eq '') {
                   8540:                         for (my $i=0; $i<$expected{$part_id}; $i++) {
                   8541:                             for (my $j=0; $j<$scantron_config->{'length'}; $j++) {
                   8542:                                 $recorded{$part_id} .= $scantron_config->{'Qoff'};
                   8543:                             }
                   8544:                         }
                   8545:                     } else {
                   8546:                         my @tocheck;
                   8547:                         my @items = split(//,$value);
                   8548:                         if (($scantron_config->{'Qon'} eq 'letter') ||
                   8549:                             ($scantron_config->{'Qon'} eq 'number')) {
                   8550:                             if (@items < $expected{$part_id}) {
                   8551:                                 my $fragment = substr($scandata,$startpos{$part_id},$expected{$part_id});
                   8552:                                 my @singles = split(//,$fragment);
                   8553:                                 foreach my $pos (@singles) {
                   8554:                                     if ($pos eq ' ') {
                   8555:                                         push(@tocheck,$pos);
                   8556:                                     } else {
                   8557:                                         my $next = shift(@items);
                   8558:                                         push(@tocheck,$next);
                   8559:                                     }
                   8560:                                 }
                   8561:                             } else {
                   8562:                                 @tocheck = @items;
                   8563:                             }
                   8564:                             foreach my $letter (@tocheck) {
                   8565:                                 if ($scantron_config->{'Qon'} eq 'letter') {
                   8566:                                     if ($letter !~ /^[A-J]$/) {
                   8567:                                         $letter = $scantron_config->{'Qoff'};
                   8568:                                     }
                   8569:                                     $recorded{$part_id} .= $letter;
                   8570:                                 } elsif ($scantron_config->{'Qon'} eq 'number') {
                   8571:                                     my $digit;
                   8572:                                     if ($letter !~ /^[A-J]$/) {
                   8573:                                         $digit = $scantron_config->{'Qoff'};
                   8574:                                     } else {
                   8575:                                         $digit = $lettdig->{$letter};
                   8576:                                     }
                   8577:                                     $recorded{$part_id} .= $digit;
                   8578:                                 }
                   8579:                             }
                   8580:                         } else {
                   8581:                             @tocheck = @items;
                   8582:                             for (my $i=0; $i<$expected{$part_id}; $i++) {
                   8583:                                 my $curr_sub = shift(@tocheck);
                   8584:                                 my $digit;
                   8585:                                 if ($curr_sub =~ /^[A-J]$/) {
                   8586:                                     $digit = $lettdig->{$curr_sub}-1;
                   8587:                                 }
                   8588:                                 if ($curr_sub eq 'J') {
                   8589:                                     $digit += scalar($numletts);
                   8590:                                 }
                   8591:                                 for (my $j=0; $j<$scantron_config->{'Qlength'}; $j++) {
                   8592:                                     if ($j == $digit) {
                   8593:                                         $recorded{$part_id} .= $scantron_config->{'Qon'};
                   8594:                                     } else {
                   8595:                                         $recorded{$part_id} .= $scantron_config->{'Qoff'};
                   8596:                                     }
                   8597:                                 }
                   8598:                             }
                   8599:                         }
                   8600:                     }
                   8601:                 }
                   8602:             }
                   8603:         }
1.554     raeburn  8604:         foreach my $part_id (@{$partids}) {
1.542     raeburn  8605:             if ($recorded{$part_id} eq '') {
                   8606:                 for (my $i=0; $i<$expected{$part_id}; $i++) {
                   8607:                     for (my $j=0; $j<$scantron_config->{'Qlength'}; $j++) {
                   8608:                         $recorded{$part_id} .= $scantron_config->{'Qoff'};
                   8609:                     }
                   8610:                 }
                   8611:             }
                   8612:             $record .= $recorded{$part_id};
                   8613:         }
                   8614:     }
                   8615:     return ($counter,$record);
                   8616: }
                   8617: 
                   8618: sub letter_to_digits { 
                   8619:     my %lettdig = (
                   8620:                     A => 1,
                   8621:                     B => 2,
                   8622:                     C => 3,
                   8623:                     D => 4,
                   8624:                     E => 5,
                   8625:                     F => 6,
                   8626:                     G => 7,
                   8627:                     H => 8,
                   8628:                     I => 9,
                   8629:                     J => 0,
                   8630:                   );
                   8631:     return %lettdig;
                   8632: }
                   8633: 
1.423     albertel 8634: 
1.75      albertel 8635: #-------- end of section for handling grading scantron forms -------
                   8636: #
                   8637: #-------------------------------------------------------------------
                   8638: 
1.72      ng       8639: #-------------------------- Menu interface -------------------------
                   8640: #
                   8641: #--- Show a Grading Menu button - Calls the next routine ---
                   8642: sub show_grading_menu_form {
1.324     albertel 8643:     my ($symb)=@_;
1.125     ng       8644:     my $result.='<br /><form action="/adm/grades" method="post">'."\n".
1.418     albertel 8645: 	'<input type="hidden" name="symb" value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
1.257     albertel 8646: 	'<input type="hidden" name="saveState"  value="'.$env{'form.saveState'}.'" />'."\n".
1.72      ng       8647: 	'<input type="hidden" name="command" value="gradingmenu" />'."\n".
1.478     albertel 8648: 	'<input type="submit" name="submit" value="'.&mt('Grading Menu').'" />'."\n".
1.72      ng       8649: 	'</form>'."\n";
                   8650:     return $result;
                   8651: }
                   8652: 
1.77      ng       8653: # -- Retrieve choices for grading form
                   8654: sub savedState {
                   8655:     my %savedState = ();
1.257     albertel 8656:     if ($env{'form.saveState'}) {
                   8657: 	foreach (split(/:/,$env{'form.saveState'})) {
1.77      ng       8658: 	    my ($key,$value) = split(/=/,$_,2);
                   8659: 	    $savedState{$key} = $value;
                   8660: 	}
                   8661:     }
                   8662:     return \%savedState;
                   8663: }
1.76      ng       8664: 
1.443     banghart 8665: sub grading_menu {
                   8666:     my ($request) = @_;
                   8667:     my ($symb)=&get_symb($request);
                   8668:     if (!$symb) {return '';}
                   8669:     my $probTitle = &Apache::lonnet::gettitle($symb);
                   8670:     my ($table,undef,$hdgrade) = &showResourceInfo($symb,$probTitle);
                   8671: 
1.444     banghart 8672:     $request->print($table);
1.443     banghart 8673:     my %fields = ('symb'=>&Apache::lonenc::check_encrypt($symb),
                   8674:                   'handgrade'=>$hdgrade,
                   8675:                   'probTitle'=>$probTitle,
                   8676:                   'command'=>'submit_options',
                   8677:                   'saveState'=>"",
                   8678:                   'gradingMenu'=>1,
                   8679:                   'showgrading'=>"yes");
1.538     schulted 8680:     
                   8681:     my $url1 = &Apache::lonhtmlcommon::build_url('grades/',\%fields);
                   8682:     
1.443     banghart 8683:     $fields{'command'} = 'csvform';
1.538     schulted 8684:     my $url2 = &Apache::lonhtmlcommon::build_url('grades/',\%fields);
                   8685:     
1.443     banghart 8686:     $fields{'command'} = 'processclicker';
1.538     schulted 8687:     my $url3 = &Apache::lonhtmlcommon::build_url('grades/',\%fields);
                   8688:     
1.443     banghart 8689:     $fields{'command'} = 'scantron_selectphase';
1.538     schulted 8690:     my $url4 = &Apache::lonhtmlcommon::build_url('grades/',\%fields);
                   8691:     
                   8692:     my @menu = ({	categorytitle=>'Course Grading',
                   8693:             items =>[
                   8694:                         {	linktext => 'Manual Grading/View Submissions',
                   8695:                     		url => $url1,
                   8696:                     		permission => 'F',
                   8697:                     		icon => 'edit-find-replace.png',
                   8698:                     		linktitle => 'Start the process of hand grading submissions.'
                   8699:                         },
                   8700:                 	    {	linktext => 'Upload Scores',
                   8701:                     		url => $url2,
                   8702:                     		permission => 'F',
                   8703:                     		icon => 'uploadscores.png',
                   8704:                     		linktitle => 'Specify a file containing the class scores for current resource.'
                   8705:                 	    },
                   8706:                 	    {	linktext => 'Process Clicker',
                   8707:                     		url => $url3,
                   8708:                     		permission => 'F',
                   8709:                     		icon => 'addClickerInfoFile.png',
                   8710:                     		linktitle => 'Specify a file containing the clicker information for this resource.'
                   8711:                 	    },
1.587     raeburn  8712:                 	    {	linktext => 'Grade/Manage/Review Bubblesheets',
1.538     schulted 8713:                     		url => $url4,
                   8714:                     		permission => 'F',
                   8715:                     		icon => 'stat.png',
1.596.2.4  raeburn  8716:                     		linktitle => 'Grade bubblesheet exams, upload/download bubblesheet data files, and review previously graded bubblesheet exams.'
1.538     schulted 8717:                 	    }
                   8718:                     ]
                   8719:             });
                   8720: 
                   8721:     #$fields{'command'} = 'verify';
                   8722:     #$url = &Apache::lonhtmlcommon::build_url('grades/',\%fields);
1.443     banghart 8723:     #
                   8724:     # Create the menu
                   8725:     my $Str;
1.444     banghart 8726:     # $Str .= '<h2>'.&mt('Please select a grading task').'</h2>';
1.445     banghart 8727:     $Str .= '<form method="post" action="" name="gradingMenu">';
                   8728:     $Str .= '<input type="hidden" name="command" value="" />'.
                   8729:     	'<input type="hidden" name="symb"        value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
                   8730: 	'<input type="hidden" name="handgrade"   value="'.$hdgrade.'" />'."\n".
1.476     albertel 8731: 	'<input type="hidden" name="probTitle"   value="'.$probTitle.'" />'."\n".
1.445     banghart 8732: 	'<input type="hidden" name="saveState"   value="" />'."\n".
                   8733: 	'<input type="hidden" name="gradingMenu" value="1" />'."\n".
                   8734: 	'<input type="hidden" name="showgrading" value="yes" />'."\n";
                   8735: 
1.538     schulted 8736:     $Str .= Apache::lonhtmlcommon::generate_menu(@menu);
                   8737:     #$menudata->{'jscript'}
1.584     bisitz   8738:     $Str .='<hr /><input type="button" value="'.&mt('Verify Receipt No.').'" '.
1.589     bisitz   8739:         ' onclick="javascript:checkChoice(document.forms.gradingMenu,\'5\',\'verify\')" '.
1.538     schulted 8740:         ' /> '.
                   8741:         &Apache::lonnet::recprefix($env{'request.course.id'}).
1.589     bisitz   8742:         '-<input type="text" name="receipt" size="4" onchange="javascript:checkReceiptNo(this.form,\'OK\')" />';
1.538     schulted 8743: 
1.444     banghart 8744:     $Str .="</form>\n";
1.539     riegler  8745:     my $receiptalert = &mt("Please enter a receipt number given by a student in the receipt box.");
1.443     banghart 8746:     $request->print(<<GRADINGMENUJS);
                   8747: <script type="text/javascript" language="javascript">
                   8748:     function checkChoice(formname,val,cmdx) {
                   8749: 	if (val <= 2) {
                   8750: 	    var cmd = radioSelection(formname.radioChoice);
                   8751: 	    var cmdsave = cmd;
                   8752: 	} else {
                   8753: 	    cmd = cmdx;
                   8754: 	    cmdsave = 'submission';
                   8755: 	}
                   8756: 	formname.command.value = cmd;
                   8757: 	if (val < 5) formname.submit();
                   8758: 	if (val == 5) {
1.458     banghart 8759: 	    if (!checkReceiptNo(formname,'notOK')) { 
                   8760: 	        return false;
                   8761: 	    } else {
                   8762: 	        formname.submit();
                   8763: 	    }
1.445     banghart 8764: 	}
                   8765:     }
1.443     banghart 8766: 
                   8767:     function checkReceiptNo(formname,nospace) {
                   8768: 	var receiptNo = formname.receipt.value;
                   8769: 	var checkOpt = false;
                   8770: 	if (nospace == "OK" && isNaN(receiptNo)) {checkOpt = true;}
                   8771: 	if (nospace == "notOK" && (isNaN(receiptNo) || receiptNo == "")) {checkOpt = true;}
                   8772: 	if (checkOpt) {
1.539     riegler  8773: 	    alert("$receiptalert");
1.443     banghart 8774: 	    formname.receipt.value = "";
                   8775: 	    formname.receipt.focus();
                   8776: 	    return false;
                   8777: 	}
                   8778: 	return true;
                   8779:     }
                   8780: </script>
                   8781: GRADINGMENUJS
                   8782:     &commonJSfunctions($request);
                   8783:     return $Str;    
                   8784: }
                   8785: 
                   8786: 
                   8787: #--- Displays the submissions first page -------
                   8788: sub submit_options {
1.72      ng       8789:     my ($request) = @_;
1.324     albertel 8790:     my ($symb)=&get_symb($request);
1.72      ng       8791:     if (!$symb) {return '';}
1.76      ng       8792:     my $probTitle = &Apache::lonnet::gettitle($symb);
1.72      ng       8793: 
1.539     riegler  8794:     my $receiptalert = &mt("Please enter a receipt number given by a student in the receipt box."); 
1.72      ng       8795:     $request->print(<<GRADINGMENUJS);
                   8796: <script type="text/javascript" language="javascript">
1.116     ng       8797:     function checkChoice(formname,val,cmdx) {
                   8798: 	if (val <= 2) {
                   8799: 	    var cmd = radioSelection(formname.radioChoice);
1.118     ng       8800: 	    var cmdsave = cmd;
1.116     ng       8801: 	} else {
                   8802: 	    cmd = cmdx;
1.118     ng       8803: 	    cmdsave = 'submission';
1.116     ng       8804: 	}
                   8805: 	formname.command.value = cmd;
1.118     ng       8806: 	formname.saveState.value = "saveCmd="+cmdsave+":saveSec="+pullDownSelection(formname.section)+
1.145     albertel 8807: 	    ":saveSub="+pullDownSelection(formname.submitonly)+":saveStatus="+pullDownSelection(formname.Status);
1.116     ng       8808: 	if (val < 5) formname.submit();
                   8809: 	if (val == 5) {
1.72      ng       8810: 	    if (!checkReceiptNo(formname,'notOK')) { return false;}
                   8811: 	    formname.submit();
                   8812: 	}
1.238     albertel 8813: 	if (val < 7) formname.submit();
1.72      ng       8814:     }
                   8815: 
                   8816:     function checkReceiptNo(formname,nospace) {
                   8817: 	var receiptNo = formname.receipt.value;
                   8818: 	var checkOpt = false;
                   8819: 	if (nospace == "OK" && isNaN(receiptNo)) {checkOpt = true;}
                   8820: 	if (nospace == "notOK" && (isNaN(receiptNo) || receiptNo == "")) {checkOpt = true;}
                   8821: 	if (checkOpt) {
1.539     riegler  8822: 	    alert("$receiptalert");
1.72      ng       8823: 	    formname.receipt.value = "";
                   8824: 	    formname.receipt.focus();
                   8825: 	    return false;
                   8826: 	}
                   8827: 	return true;
                   8828:     }
                   8829: </script>
                   8830: GRADINGMENUJS
1.118     ng       8831:     &commonJSfunctions($request);
1.324     albertel 8832:     my ($table,undef,$hdgrade) = &showResourceInfo($symb,$probTitle);
1.473     albertel 8833:     my $result;
1.76      ng       8834:     my (undef,$sections) = &getclasslist('all','0');
1.77      ng       8835:     my $savedState = &savedState();
1.118     ng       8836:     my $saveCmd = ($$savedState{'saveCmd'} eq '' ? 'submission' : $$savedState{'saveCmd'});
1.77      ng       8837:     my $saveSec = ($$savedState{'saveSec'} eq '' ? 'all' : $$savedState{'saveSec'});
1.118     ng       8838:     my $saveSub = ($$savedState{'saveSub'} eq '' ? 'all' : $$savedState{'saveSub'});
1.77      ng       8839:     my $saveStatus = ($$savedState{'saveStatus'} eq '' ? 'Active' : $$savedState{'saveStatus'});
1.72      ng       8840: 
1.533     bisitz   8841:     # Preselect sections
                   8842:     my $selsec="";
                   8843:     if (ref($sections)) {
                   8844:         foreach my $section (sort(@$sections)) {
                   8845:             $selsec.='<option value="'.$section.'" '.
                   8846:                 ($saveSec eq $section ? 'selected="selected"':'').'>'.$section.'</option>'."\n";
                   8847:         }
                   8848:     }
                   8849: 
1.72      ng       8850:     $result.='<form action="/adm/grades" method="post" name="gradingMenu">'."\n".
1.418     albertel 8851: 	'<input type="hidden" name="symb"        value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
1.72      ng       8852: 	'<input type="hidden" name="handgrade"   value="'.$hdgrade.'" />'."\n".
                   8853: 	'<input type="hidden" name="probTitle"   value="'.$probTitle.'" />'."\n".
1.116     ng       8854: 	'<input type="hidden" name="command"     value="" />'."\n".
1.77      ng       8855: 	'<input type="hidden" name="saveState"   value="" />'."\n".
1.124     ng       8856: 	'<input type="hidden" name="gradingMenu" value="1" />'."\n".
1.72      ng       8857: 	'<input type="hidden" name="showgrading" value="yes" />'."\n";
                   8858: 
1.472     albertel 8859:     $result.='
1.533     bisitz   8860: <h2>
                   8861:   '.&mt('Grade Current Resource').'
                   8862: </h2>
                   8863: <div>
                   8864:   '.$table.'
                   8865: </div>
                   8866: 
1.537     harmsja  8867: <div class="LC_columnSection">
                   8868:   
1.533     bisitz   8869:     <fieldset>
                   8870:       <legend>
                   8871:        '.&mt('Sections').'
                   8872:       </legend>
                   8873:       <select name="section" multiple="multiple" size="5">'."\n";
                   8874:     $result.= $selsec;
1.401     albertel 8875:     $result.= '<option value="all" '.($saveSec eq 'all' ? 'selected="selected"' : ''). '>all</option></select> &nbsp; ';
1.472     albertel 8876:     $result.='
1.533     bisitz   8877:     </fieldset>
1.537     harmsja  8878:   
1.533     bisitz   8879:     <fieldset>
                   8880:       <legend>
                   8881:         '.&mt('Groups').'
                   8882:       </legend>
                   8883:       '.&Apache::lonstatistics::GroupSelect('group','multiple',5).'
                   8884:     </fieldset>
1.537     harmsja  8885:   
1.533     bisitz   8886:     <fieldset>
                   8887:       <legend>
                   8888:         '.&mt('Access Status').'
                   8889:       </legend>
                   8890:       '.&Apache::lonhtmlcommon::StatusOptions($saveStatus,undef,5,undef,'mult').'
                   8891:     </fieldset>
1.537     harmsja  8892:   
1.533     bisitz   8893:     <fieldset>
                   8894:       <legend>
                   8895:         '.&mt('Submission Status').'
                   8896:       </legend>
                   8897:       <select name="submitonly" size="5">
1.473     albertel 8898: 	         <option value="yes" '.      ($saveSub eq 'yes'       ? 'selected="selected"' : '').'>'.&mt('with submissions').'</option>
                   8899: 	         <option value="queued" '.   ($saveSub eq 'queued'    ? 'selected="selected"' : '').'>'.&mt('in grading queue').'</option>
                   8900: 	         <option value="graded" '.   ($saveSub eq 'graded'    ? 'selected="selected"' : '').'>'.&mt('with ungraded submissions').'</option>
                   8901: 	         <option value="incorrect" '.($saveSub eq 'incorrect' ? 'selected="selected"' : '').'>'.&mt('with incorrect submissions').'</option>
                   8902:                  <option value="all" '.      ($saveSub eq 'all'       ? 'selected="selected"' : '').'>'.&mt('with any status').'</option>
1.533     bisitz   8903:       </select>
                   8904:     </fieldset>
1.537     harmsja  8905:   
1.533     bisitz   8906: </div>
                   8907: 
                   8908: <br />
                   8909:           <div>
                   8910:             <div>
1.473     albertel 8911:               <label>
                   8912:                 <input type="radio" name="radioChoice" value="submission" '.
                   8913:                   ($saveCmd eq 'submission' ? 'checked="checked"' : '').' /> '.
                   8914:              &mt('Select individual students to grade and view submissions.').'
                   8915: 	      </label> 
                   8916:             </div>
1.533     bisitz   8917:             <div>
1.473     albertel 8918: 	      <label>
                   8919:                 <input type="radio" name="radioChoice" value="viewgrades" '.
                   8920:                   ($saveCmd eq 'viewgrades' ? 'checked="checked"' : '').' /> '.
                   8921:                     &mt('Grade all selected students in a grading table.').'
                   8922:               </label>
                   8923:             </div>
1.533     bisitz   8924:             <div>
1.589     bisitz   8925: 	      <input type="button" onclick="javascript:checkChoice(this.form,\'2\');" value="'.&mt('Next').' &rarr;" />
1.473     albertel 8926:             </div>
1.472     albertel 8927:           </div>
1.533     bisitz   8928: 
                   8929: 
1.473     albertel 8930:         <h2>
                   8931:          '.&mt('Grade Complete Folder for One Student').'
                   8932:         </h2>
1.533     bisitz   8933:         <div>
                   8934:             <div>
1.473     albertel 8935:               <label>
                   8936:                 <input type="radio" name="radioChoice" value="pickStudentPage" '.
                   8937: 	  ($saveCmd eq 'pickStudentPage' ? 'checked="checked"' : '').' /> '.
                   8938:   &mt('The <b>complete</b> page/sequence/folder: For one student').'
                   8939:               </label>
                   8940:             </div>
1.533     bisitz   8941:             <div>
1.589     bisitz   8942: 	      <input type="button" onclick="javascript:checkChoice(this.form,\'2\');" value="'.&mt('Next').' &rarr;" />
1.473     albertel 8943:             </div>
1.472     albertel 8944:         </div>
                   8945:   </form>';
1.499     albertel 8946:     $result .= &show_grading_menu_form($symb);
1.44      ng       8947:     return $result;
1.2       albertel 8948: }
                   8949: 
1.285     albertel 8950: sub reset_perm {
                   8951:     undef(%perm);
                   8952: }
                   8953: 
                   8954: sub init_perm {
                   8955:     &reset_perm();
1.300     albertel 8956:     foreach my $test_perm ('vgr','mgr','opa') {
                   8957: 
                   8958: 	my $scope = $env{'request.course.id'};
                   8959: 	if (!($perm{$test_perm}=&Apache::lonnet::allowed($test_perm,$scope))) {
                   8960: 
                   8961: 	    $scope .= '/'.$env{'request.course.sec'};
                   8962: 	    if ( $perm{$test_perm}=
                   8963: 		 &Apache::lonnet::allowed($test_perm,$scope)) {
                   8964: 		$perm{$test_perm.'_section'}=$env{'request.course.sec'};
                   8965: 	    } else {
                   8966: 		delete($perm{$test_perm});
                   8967: 	    }
1.285     albertel 8968: 	}
                   8969:     }
                   8970: }
                   8971: 
1.596.2.13! raeburn  8972: sub init_old_essays {
        !          8973:     my ($symb,$apath,$adom,$aname) = @_;
        !          8974:     if ($symb ne '') {
        !          8975:         my %essays = &Apache::lonnet::dump('nohist_essay_'.$apath,$adom,$aname);
        !          8976:         if (keys(%essays) > 0) {
        !          8977:             $old_essays{$symb} = \%essays;
        !          8978:         }
        !          8979:     }
        !          8980:     return;
        !          8981: }
        !          8982: 
        !          8983: sub reset_old_essays {
        !          8984:     undef(%old_essays);
        !          8985: }
        !          8986: 
1.400     www      8987: sub gather_clicker_ids {
1.408     albertel 8988:     my %clicker_ids;
1.400     www      8989: 
                   8990:     my $classlist = &Apache::loncoursedata::get_classlist();
                   8991: 
                   8992:     # Set up a couple variables.
1.407     albertel 8993:     my $username_idx = &Apache::loncoursedata::CL_SNAME();
                   8994:     my $domain_idx   = &Apache::loncoursedata::CL_SDOM();
1.438     www      8995:     my $status_idx   = &Apache::loncoursedata::CL_STATUS();
1.400     www      8996: 
1.407     albertel 8997:     foreach my $student (keys(%$classlist)) {
1.438     www      8998:         if ($classlist->{$student}->[$status_idx] ne 'Active') { next; }
1.407     albertel 8999:         my $username = $classlist->{$student}->[$username_idx];
                   9000:         my $domain   = $classlist->{$student}->[$domain_idx];
1.400     www      9001:         my $clickers =
1.408     albertel 9002: 	    (&Apache::lonnet::userenvironment($domain,$username,'clickers'))[1];
1.400     www      9003:         foreach my $id (split(/\,/,$clickers)) {
1.414     www      9004:             $id=~s/^[\#0]+//;
1.421     www      9005:             $id=~s/[\-\:]//g;
1.407     albertel 9006:             if (exists($clicker_ids{$id})) {
1.408     albertel 9007: 		$clicker_ids{$id}.=','.$username.':'.$domain;
1.400     www      9008:             } else {
1.408     albertel 9009: 		$clicker_ids{$id}=$username.':'.$domain;
1.400     www      9010:             }
                   9011:         }
                   9012:     }
1.407     albertel 9013:     return %clicker_ids;
1.400     www      9014: }
                   9015: 
1.402     www      9016: sub gather_adv_clicker_ids {
1.408     albertel 9017:     my %clicker_ids;
1.402     www      9018:     my $cnum=$env{'course.'.$env{'request.course.id'}.'.num'};
                   9019:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
                   9020:     my %coursepersonnel=&Apache::lonnet::get_course_adv_roles($cdom.'/'.$cnum);
1.409     albertel 9021:     foreach my $element (sort(keys(%coursepersonnel))) {
1.402     www      9022:         foreach my $person (split(/\,/,$coursepersonnel{$element})) {
                   9023:             my ($puname,$pudom)=split(/\:/,$person);
                   9024:             my $clickers =
1.408     albertel 9025: 		(&Apache::lonnet::userenvironment($pudom,$puname,'clickers'))[1];
1.405     www      9026:             foreach my $id (split(/\,/,$clickers)) {
1.414     www      9027: 		$id=~s/^[\#0]+//;
1.421     www      9028:                 $id=~s/[\-\:]//g;
1.408     albertel 9029: 		if (exists($clicker_ids{$id})) {
                   9030: 		    $clicker_ids{$id}.=','.$puname.':'.$pudom;
                   9031: 		} else {
                   9032: 		    $clicker_ids{$id}=$puname.':'.$pudom;
                   9033: 		}
1.405     www      9034:             }
1.402     www      9035:         }
                   9036:     }
1.407     albertel 9037:     return %clicker_ids;
1.402     www      9038: }
                   9039: 
1.413     www      9040: sub clicker_grading_parameters {
                   9041:     return ('gradingmechanism' => 'scalar',
                   9042:             'upfiletype' => 'scalar',
                   9043:             'specificid' => 'scalar',
                   9044:             'pcorrect' => 'scalar',
                   9045:             'pincorrect' => 'scalar');
                   9046: }
                   9047: 
1.400     www      9048: sub process_clicker {
                   9049:     my ($r)=@_;
                   9050:     my ($symb)=&get_symb($r);
                   9051:     if (!$symb) {return '';}
                   9052:     my $result=&checkforfile_js();
                   9053:     $env{'form.probTitle'} = &Apache::lonnet::gettitle($symb);
                   9054:     my ($table) = &showResourceInfo($symb,$env{'form.probTitle'});
                   9055:     $result.=$table;
                   9056:     $result.='<br /><table width="100%" border="0"><tr><td bgcolor="#777777">'."\n";
                   9057:     $result.='<table width="100%" border="0"><tr bgcolor="#e6ffff"><td>'."\n";
1.538     schulted 9058:     $result.='&nbsp;<b>'.&mt('Specify a file containing the clicker information for this resource.').
                   9059:         '</b></td></tr>'."\n";
1.596.2.4  raeburn  9060:     $result.='<tr bgcolor="#ffffe6"><td>'."\n";
1.413     www      9061: # Attempt to restore parameters from last session, set defaults if not present
                   9062:     my %Saveable_Parameters=&clicker_grading_parameters();
                   9063:     &Apache::loncommon::restore_course_settings('grades_clicker',
                   9064:                                                  \%Saveable_Parameters);
                   9065:     if (!$env{'form.pcorrect'}) { $env{'form.pcorrect'}=100; }
                   9066:     if (!$env{'form.pincorrect'}) { $env{'form.pincorrect'}=100; }
                   9067:     if (!$env{'form.gradingmechanism'}) { $env{'form.gradingmechanism'}='attendance'; }
                   9068:     if (!$env{'form.upfiletype'}) { $env{'form.upfiletype'}='iclicker'; }
                   9069: 
                   9070:     my %checked;
1.521     www      9071:     foreach my $gradingmechanism ('attendance','personnel','specific','given') {
1.413     www      9072:        if ($env{'form.gradingmechanism'} eq $gradingmechanism) {
1.569     bisitz   9073:           $checked{$gradingmechanism}=' checked="checked"';
1.413     www      9074:        }
                   9075:     }
                   9076: 
1.400     www      9077:     my $upload=&mt("Upload File");
                   9078:     my $type=&mt("Type");
1.402     www      9079:     my $attendance=&mt("Award points just for participation");
                   9080:     my $personnel=&mt("Correctness determined from response by course personnel");
1.414     www      9081:     my $specific=&mt("Correctness determined from response with clicker ID(s)"); 
1.521     www      9082:     my $given=&mt("Correctness determined from given list of answers").' '.
                   9083:               '<font size="-2"><tt>('.&mt("Provide comma-separated list. Use '*' for any answer correct, '-' for skip").')</tt></font>';
1.402     www      9084:     my $pcorrect=&mt("Percentage points for correct solution");
                   9085:     my $pincorrect=&mt("Percentage points for incorrect solution");
1.413     www      9086:     my $selectform=&Apache::loncommon::select_form($env{'form.upfiletype'},'upfiletype',
1.596.2.1  raeburn  9087:                                                    {'iclicker' => 'i>clicker',
                   9088:                                                     'interwrite' => 'interwrite PRS'});
1.418     albertel 9089:     $symb = &Apache::lonenc::check_encrypt($symb);
1.400     www      9090:     $result.=<<ENDUPFORM;
1.402     www      9091: <script type="text/javascript">
                   9092: function sanitycheck() {
                   9093: // Accept only integer percentages
                   9094:    document.forms.gradesupload.pcorrect.value=Math.round(document.forms.gradesupload.pcorrect.value);
                   9095:    document.forms.gradesupload.pincorrect.value=Math.round(document.forms.gradesupload.pincorrect.value);
                   9096: // Find out grading choice
                   9097:    for (i=0; i<document.forms.gradesupload.gradingmechanism.length; i++) {
                   9098:       if (document.forms.gradesupload.gradingmechanism[i].checked) {
                   9099:          gradingchoice=document.forms.gradesupload.gradingmechanism[i].value;
                   9100:       }
                   9101:    }
                   9102: // By default, new choice equals user selection
                   9103:    newgradingchoice=gradingchoice;
                   9104: // Not good to give more points for false answers than correct ones
                   9105:    if (Math.round(document.forms.gradesupload.pcorrect.value)<Math.round(document.forms.gradesupload.pincorrect.value)) {
                   9106:       document.forms.gradesupload.pcorrect.value=document.forms.gradesupload.pincorrect.value;
                   9107:    }
                   9108: // If new choice is attendance only, and old choice was correctness-based, restore defaults
                   9109:    if ((gradingchoice=='attendance') && (document.forms.gradesupload.waschecked.value!='attendance')) {
                   9110:       document.forms.gradesupload.pcorrect.value=100;
                   9111:       document.forms.gradesupload.pincorrect.value=100;
                   9112:    }
                   9113: // If the values are different, cannot be attendance only
                   9114:    if ((Math.round(document.forms.gradesupload.pcorrect.value)!=Math.round(document.forms.gradesupload.pincorrect.value)) &&
                   9115:        (gradingchoice=='attendance')) {
                   9116:        newgradingchoice='personnel';
                   9117:    }
                   9118: // Change grading choice to new one
                   9119:    for (i=0; i<document.forms.gradesupload.gradingmechanism.length; i++) {
                   9120:       if (document.forms.gradesupload.gradingmechanism[i].value==newgradingchoice) {
                   9121:          document.forms.gradesupload.gradingmechanism[i].checked=true;
                   9122:       } else {
                   9123:          document.forms.gradesupload.gradingmechanism[i].checked=false;
                   9124:       }
                   9125:    }
                   9126: // Remember the old state
                   9127:    document.forms.gradesupload.waschecked.value=newgradingchoice;
                   9128: }
                   9129: </script>
1.400     www      9130: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="gradesupload">
                   9131: <input type="hidden" name="symb" value="$symb" />
                   9132: <input type="hidden" name="command" value="processclickerfile" />
                   9133: <input type="hidden" name="probTitle" value="$env{'form.probTitle'}" />
                   9134: <input type="hidden" name="saveState"  value="$env{'form.saveState'}" />
                   9135: <input type="file" name="upfile" size="50" />
                   9136: <br /><label>$type: $selectform</label>
1.589     bisitz   9137: <br /><label><input type="radio" name="gradingmechanism" value="attendance"$checked{'attendance'} onclick="sanitycheck()" />$attendance </label>
                   9138: <br /><label><input type="radio" name="gradingmechanism" value="personnel"$checked{'personnel'} onclick="sanitycheck()" />$personnel</label>
                   9139: <br /><label><input type="radio" name="gradingmechanism" value="specific"$checked{'specific'} onclick="sanitycheck()" />$specific </label>
1.414     www      9140: <input type="text" name="specificid" value="$env{'form.specificid'}" size="20" />
1.589     bisitz   9141: <br /><label><input type="radio" name="gradingmechanism" value="given"$checked{'given'} onclick="sanitycheck()" />$given </label>
1.521     www      9142: <br />&nbsp;&nbsp;&nbsp;
                   9143: <input type="text" name="givenanswer" size="50" />
1.413     www      9144: <input type="hidden" name="waschecked" value="$env{'form.gradingmechanism'}" />
1.589     bisitz   9145: <br /><label>$pcorrect: <input type="text" name="pcorrect" size="4" value="$env{'form.pcorrect'}" onchange="sanitycheck()" /></label>
                   9146: <br /><label>$pincorrect: <input type="text" name="pincorrect" size="4" value="$env{'form.pincorrect'}" onchange="sanitycheck()" /></label>
                   9147: <br /><input type="button" onclick="javascript:checkUpload(this.form);" value="$upload" />
1.400     www      9148: </form>
                   9149: ENDUPFORM
                   9150:     $result.='</td></tr></table>'."\n".
                   9151:              '</td></tr></table><br /><br />'."\n";
                   9152:     $result.=&show_grading_menu_form($symb);
                   9153:     return $result;
                   9154: }
                   9155: 
                   9156: sub process_clicker_file {
                   9157:     my ($r)=@_;
                   9158:     my ($symb)=&get_symb($r);
                   9159:     if (!$symb) {return '';}
1.413     www      9160: 
                   9161:     my %Saveable_Parameters=&clicker_grading_parameters();
                   9162:     &Apache::loncommon::store_course_settings('grades_clicker',
                   9163:                                               \%Saveable_Parameters);
                   9164: 
1.400     www      9165:     my ($result) = &showResourceInfo($symb,$env{'form.probTitle'});
1.404     www      9166:     if (($env{'form.gradingmechanism'} eq 'specific') && ($env{'form.specificid'}!~/\w/)) {
1.408     albertel 9167: 	$result.='<span class="LC_error">'.&mt('You need to specify a clicker ID for the correct answer').'</span>';
                   9168: 	return $result.&show_grading_menu_form($symb);
1.404     www      9169:     }
1.522     www      9170:     if (($env{'form.gradingmechanism'} eq 'given') && ($env{'form.givenanswer'}!~/\S/)) {
1.521     www      9171:         $result.='<span class="LC_error">'.&mt('You need to specify the correct answer').'</span>';
                   9172:         return $result.&show_grading_menu_form($symb);
                   9173:     }
1.522     www      9174:     my $foundgiven=0;
1.521     www      9175:     if ($env{'form.gradingmechanism'} eq 'given') {
                   9176:         $env{'form.givenanswer'}=~s/^\s*//gs;
                   9177:         $env{'form.givenanswer'}=~s/\s*$//gs;
1.596.2.4  raeburn  9178:         $env{'form.givenanswer'}=~s/[^a-zA-Z0-9\.\*\-\+]+/\,/g;
1.521     www      9179:         $env{'form.givenanswer'}=uc($env{'form.givenanswer'});
1.522     www      9180:         my @answers=split(/\,/,$env{'form.givenanswer'});
                   9181:         $foundgiven=$#answers+1;
1.521     www      9182:     }
1.407     albertel 9183:     my %clicker_ids=&gather_clicker_ids();
1.408     albertel 9184:     my %correct_ids;
1.404     www      9185:     if ($env{'form.gradingmechanism'} eq 'personnel') {
1.408     albertel 9186: 	%correct_ids=&gather_adv_clicker_ids();
1.404     www      9187:     }
                   9188:     if ($env{'form.gradingmechanism'} eq 'specific') {
1.414     www      9189: 	foreach my $correct_id (split(/[\s\,]/,$env{'form.specificid'})) {;
                   9190: 	   $correct_id=~tr/a-z/A-Z/;
                   9191: 	   $correct_id=~s/\s//gs;
                   9192: 	   $correct_id=~s/^[\#0]+//;
1.421     www      9193:            $correct_id=~s/[\-\:]//g;
1.414     www      9194:            if ($correct_id) {
                   9195: 	      $correct_ids{$correct_id}='specified';
                   9196:            }
                   9197:         }
1.400     www      9198:     }
1.404     www      9199:     if ($env{'form.gradingmechanism'} eq 'attendance') {
1.408     albertel 9200: 	$result.=&mt('Score based on attendance only');
1.521     www      9201:     } elsif ($env{'form.gradingmechanism'} eq 'given') {
1.522     www      9202:         $result.=&mt('Score based on [_1] ([_2] answers)','<tt>'.$env{'form.givenanswer'}.'</tt>',$foundgiven);
1.404     www      9203:     } else {
1.408     albertel 9204: 	my $number=0;
1.411     www      9205: 	$result.='<p><b>'.&mt('Correctness determined by the following IDs').'</b>';
1.408     albertel 9206: 	foreach my $id (sort(keys(%correct_ids))) {
1.411     www      9207: 	    $result.='<br /><tt>'.$id.'</tt> - ';
1.408     albertel 9208: 	    if ($correct_ids{$id} eq 'specified') {
                   9209: 		$result.=&mt('specified');
                   9210: 	    } else {
                   9211: 		my ($uname,$udom)=split(/\:/,$correct_ids{$id});
                   9212: 		$result.=&Apache::loncommon::plainname($uname,$udom);
                   9213: 	    }
                   9214: 	    $number++;
                   9215: 	}
1.411     www      9216:         $result.="</p>\n";
1.408     albertel 9217: 	if ($number==0) {
                   9218: 	    $result.='<span class="LC_error">'.&mt('No IDs found to determine correct answer').'</span>';
                   9219: 	    return $result.&show_grading_menu_form($symb);
                   9220: 	}
1.404     www      9221:     }
1.405     www      9222:     if (length($env{'form.upfile'}) < 2) {
1.407     albertel 9223:         $result.=&mt('[_1] Error: [_2] The file you attempted to upload, [_3] contained no information. Please check that you entered the correct filename.',
                   9224: 		     '<span class="LC_error">',
                   9225: 		     '</span>',
                   9226: 		     '<span class="LC_filename">'.&HTML::Entities::encode($env{'form.upfile.filename'},'<>&"').'</span>');
1.405     www      9227:         return $result.&show_grading_menu_form($symb);
                   9228:     }
1.410     www      9229: 
                   9230: # Were able to get all the info needed, now analyze the file
                   9231: 
1.411     www      9232:     $result.=&Apache::loncommon::studentbrowser_javascript();
1.418     albertel 9233:     $symb = &Apache::lonenc::check_encrypt($symb);
1.410     www      9234:     my $heading=&mt('Scanning clicker file');
                   9235:     $result.=(<<ENDHEADER);
                   9236: <br /><table width="100%" border="0"><tr><td bgcolor="#777777">
                   9237: <table width="100%" border="0"><tr bgcolor="#e6ffff"><td>
1.596.2.4  raeburn  9238: <b>$heading</b></td></tr><tr bgcolor="#ffffe6"><td>
1.410     www      9239: <form method="post" action="/adm/grades" name="clickeranalysis">
                   9240: <input type="hidden" name="symb" value="$symb" />
                   9241: <input type="hidden" name="command" value="assignclickergrades" />
                   9242: <input type="hidden" name="probTitle" value="$env{'form.probTitle'}" />
                   9243: <input type="hidden" name="saveState"  value="$env{'form.saveState'}" />
1.411     www      9244: <input type="hidden" name="gradingmechanism" value="$env{'form.gradingmechanism'}" />
                   9245: <input type="hidden" name="pcorrect" value="$env{'form.pcorrect'}" />
                   9246: <input type="hidden" name="pincorrect" value="$env{'form.pincorrect'}" />
1.410     www      9247: ENDHEADER
1.522     www      9248:     if ($env{'form.gradingmechanism'} eq 'given') {
                   9249:        $result.='<input type="hidden" name="correct:given" value="'.$env{'form.givenanswer'}.'" />';
                   9250:     } 
1.408     albertel 9251:     my %responses;
                   9252:     my @questiontitles;
1.405     www      9253:     my $errormsg='';
                   9254:     my $number=0;
                   9255:     if ($env{'form.upfiletype'} eq 'iclicker') {
1.408     albertel 9256: 	($errormsg,$number)=&iclicker_eval(\@questiontitles,\%responses);
1.406     www      9257:     }
1.419     www      9258:     if ($env{'form.upfiletype'} eq 'interwrite') {
                   9259:         ($errormsg,$number)=&interwrite_eval(\@questiontitles,\%responses);
                   9260:     }
1.411     www      9261:     $result.='<br />'.&mt('Found [_1] question(s)',$number).'<br />'.
                   9262:              '<input type="hidden" name="number" value="'.$number.'" />'.
                   9263:              &mt('Awarding [_1] percent for correct and [_2] percent for incorrect responses',
                   9264:                  $env{'form.pcorrect'},$env{'form.pincorrect'}).
                   9265:              '<br />';
1.522     www      9266:     if (($env{'form.gradingmechanism'} eq 'given') && ($number!=$foundgiven)) {
                   9267:        $result.='<span class="LC_error">'.&mt('Number of given answers does not agree with number of questions in file.').'</span>';
                   9268:        return $result.&show_grading_menu_form($symb);
                   9269:     } 
1.414     www      9270: # Remember Question Titles
                   9271: # FIXME: Possibly need delimiter other than ":"
                   9272:     for (my $i=0;$i<$number;$i++) {
                   9273:         $result.='<input type="hidden" name="question:'.$i.'" value="'.
                   9274:                  &HTML::Entities::encode($questiontitles[$i],'"&<>').'" />';
                   9275:     }
1.411     www      9276:     my $correct_count=0;
                   9277:     my $student_count=0;
                   9278:     my $unknown_count=0;
1.414     www      9279: # Match answers with usernames
                   9280: # FIXME: Possibly need delimiter other than ":"
1.409     albertel 9281:     foreach my $id (keys(%responses)) {
1.410     www      9282:        if ($correct_ids{$id}) {
1.414     www      9283:           $result.="\n".'<input type="hidden" name="correct:'.$correct_count.':'.$correct_ids{$id}.'" value="'.$responses{$id}.'" />';
1.411     www      9284:           $correct_count++;
1.410     www      9285:        } elsif ($clicker_ids{$id}) {
1.437     www      9286:           if ($clicker_ids{$id}=~/\,/) {
                   9287: # More than one user with the same clicker!
                   9288:              $result.="\n<hr />".&mt('Clicker registered more than once').": <tt>".$id."</tt><br />";
                   9289:              $result.="\n".'<input type="hidden" name="unknown:'.$id.'" value="'.$responses{$id}.'" />'.
                   9290:                            "<select name='multi".$id."'>";
                   9291:              foreach my $reguser (sort(split(/\,/,$clicker_ids{$id}))) {
                   9292:                  $result.="<option value='".$reguser."'>".&Apache::loncommon::plainname(split(/\:/,$reguser)).' ('.$reguser.')</option>';
                   9293:              }
                   9294:              $result.='</select>';
                   9295:              $unknown_count++;
                   9296:           } else {
                   9297: # Good: found one and only one user with the right clicker
                   9298:              $result.="\n".'<input type="hidden" name="student:'.$clicker_ids{$id}.'" value="'.$responses{$id}.'" />';
                   9299:              $student_count++;
                   9300:           }
1.410     www      9301:        } else {
1.411     www      9302:           $result.="\n<hr />".&mt('Unregistered Clicker')." <tt>".$id."</tt><br />";
                   9303:           $result.="\n".'<input type="hidden" name="unknown:'.$id.'" value="'.$responses{$id}.'" />'.
                   9304:                    "\n".&mt("Username").": <input type='text' name='uname".$id."' />&nbsp;".
                   9305:                    "\n".&mt("Domain").": ".
                   9306:                    &Apache::loncommon::select_dom_form($env{'course.'.$env{'request.course.id'}.'.domain'},'udom'.$id).'&nbsp;'.
1.596.2.4  raeburn  9307:                    &Apache::loncommon::selectstudent_link('clickeranalysis','uname'.$id,'udom'.$id,0,$id);
1.411     www      9308:           $unknown_count++;
1.410     www      9309:        }
1.405     www      9310:     }
1.412     www      9311:     $result.='<hr />'.
                   9312:              &mt('Found [_1] registered and [_2] unregistered clickers.',$student_count,$unknown_count);
1.521     www      9313:     if (($env{'form.gradingmechanism'} ne 'attendance') && ($env{'form.gradingmechanism'} ne 'given')) {
1.412     www      9314:        if ($correct_count==0) {
                   9315:           $errormsg.="Found no correct answers answers for grading!";
                   9316:        } elsif ($correct_count>1) {
1.414     www      9317:           $result.='<br /><span class="LC_warning">'.&mt("Found [_1] entries for grading!",$correct_count).'</span>';
1.412     www      9318:        }
                   9319:     }
1.428     www      9320:     if ($number<1) {
                   9321:        $errormsg.="Found no questions.";
                   9322:     }
1.412     www      9323:     if ($errormsg) {
                   9324:        $result.='<br /><span class="LC_error">'.&mt($errormsg).'</span>';
                   9325:     } else {
                   9326:        $result.='<br /><input type="submit" name="finalize" value="'.&mt('Finalize Grading').'" />';
                   9327:     }
                   9328:     $result.='</form></td></tr></table>'."\n".
1.410     www      9329:              '</td></tr></table><br /><br />'."\n";
1.404     www      9330:     return $result.&show_grading_menu_form($symb);
1.400     www      9331: }
                   9332: 
1.405     www      9333: sub iclicker_eval {
1.406     www      9334:     my ($questiontitles,$responses)=@_;
1.405     www      9335:     my $number=0;
                   9336:     my $errormsg='';
                   9337:     foreach my $line (split(/[\n\r]/,$env{'form.upfile'})) {
1.410     www      9338:         my %components=&Apache::loncommon::record_sep($line);
                   9339:         my @entries=map {$components{$_}} (sort(keys(%components)));
1.408     albertel 9340: 	if ($entries[0] eq 'Question') {
                   9341: 	    for (my $i=3;$i<$#entries;$i+=6) {
                   9342: 		$$questiontitles[$number]=$entries[$i];
                   9343: 		$number++;
                   9344: 	    }
                   9345: 	}
                   9346: 	if ($entries[0]=~/^\#/) {
                   9347: 	    my $id=$entries[0];
                   9348: 	    my @idresponses;
                   9349: 	    $id=~s/^[\#0]+//;
                   9350: 	    for (my $i=0;$i<$number;$i++) {
                   9351: 		my $idx=3+$i*6;
1.596.2.4  raeburn  9352:                 $entries[$idx]=~s/[^a-zA-Z0-9\.\*\-\+]+//g;
1.408     albertel 9353: 		push(@idresponses,$entries[$idx]);
                   9354: 	    }
                   9355: 	    $$responses{$id}=join(',',@idresponses);
                   9356: 	}
1.405     www      9357:     }
                   9358:     return ($errormsg,$number);
                   9359: }
                   9360: 
1.419     www      9361: sub interwrite_eval {
                   9362:     my ($questiontitles,$responses)=@_;
                   9363:     my $number=0;
                   9364:     my $errormsg='';
1.420     www      9365:     my $skipline=1;
                   9366:     my $questionnumber=0;
                   9367:     my %idresponses=();
1.419     www      9368:     foreach my $line (split(/[\n\r]/,$env{'form.upfile'})) {
                   9369:         my %components=&Apache::loncommon::record_sep($line);
                   9370:         my @entries=map {$components{$_}} (sort(keys(%components)));
1.420     www      9371:         if ($entries[1] eq 'Time') { $skipline=0; next; }
                   9372:         if ($entries[1] eq 'Response') { $skipline=1; }
                   9373:         next if $skipline;
                   9374:         if ($entries[0]!=$questionnumber) {
                   9375:            $questionnumber=$entries[0];
                   9376:            $$questiontitles[$number]=&mt('Question [_1]',$questionnumber);
                   9377:            $number++;
1.419     www      9378:         }
1.420     www      9379:         my $id=$entries[4];
                   9380:         $id=~s/^[\#0]+//;
1.421     www      9381:         $id=~s/^v\d*\://i;
                   9382:         $id=~s/[\-\:]//g;
1.420     www      9383:         $idresponses{$id}[$number]=$entries[6];
                   9384:     }
1.524     raeburn  9385:     foreach my $id (keys(%idresponses)) {
1.420     www      9386:        $$responses{$id}=join(',',@{$idresponses{$id}});
                   9387:        $$responses{$id}=~s/^\s*\,//;
1.419     www      9388:     }
                   9389:     return ($errormsg,$number);
                   9390: }
                   9391: 
1.414     www      9392: sub assign_clicker_grades {
                   9393:     my ($r)=@_;
                   9394:     my ($symb)=&get_symb($r);
                   9395:     if (!$symb) {return '';}
1.416     www      9396: # See which part we are saving to
1.582     raeburn  9397:     my $res_error;
                   9398:     my ($partlist,$handgrade,$responseType) = &response_type($symb,\$res_error);
                   9399:     if ($res_error) {
                   9400:         return &navmap_errormsg();
                   9401:     }
1.416     www      9402: # FIXME: This should probably look for the first handgradeable part
                   9403:     my $part=$$partlist[0];
                   9404: # Start screen output
1.596.2.10  raeburn  9405:     my ($result) = &showResourceInfo($symb,$env{'form.probTitle'});
1.596.2.4  raeburn  9406: 
1.596.2.10  raeburn  9407:     $result .= '<br />'.
                   9408:                &Apache::loncommon::start_data_table().
1.596.2.4  raeburn  9409:                &Apache::loncommon::start_data_table_header_row().
                   9410:                '<th>'.&mt('Assigning grades based on clicker file').'</th>'.
                   9411:                &Apache::loncommon::end_data_table_header_row().
                   9412:                &Apache::loncommon::start_data_table_row().'<td>';
1.416     www      9413: 
1.414     www      9414: # Get correct result
                   9415: # FIXME: Possibly need delimiter other than ":"
                   9416:     my @correct=();
1.415     www      9417:     my $gradingmechanism=$env{'form.gradingmechanism'};
                   9418:     my $number=$env{'form.number'};
                   9419:     if ($gradingmechanism ne 'attendance') {
1.414     www      9420:        foreach my $key (keys(%env)) {
                   9421:           if ($key=~/^form\.correct\:/) {
                   9422:              my @input=split(/\,/,$env{$key});
                   9423:              for (my $i=0;$i<=$#input;$i++) {
                   9424:                  if (($correct[$i]) && ($input[$i]) &&
                   9425:                      ($correct[$i] ne $input[$i])) {
                   9426:                     $result.='<br /><span class="LC_warning">'.
                   9427:                              &mt('More than one correct result given for question "[_1]": [_2] versus [_3].',
                   9428:                                  $env{'form.question:'.$i},$correct[$i],$input[$i]).'</span>';
1.596.2.4  raeburn  9429:                  } elsif (($input[$i]) || ($input[$i] eq '0')) {
1.414     www      9430:                     $correct[$i]=$input[$i];
                   9431:                  }
                   9432:              }
                   9433:           }
                   9434:        }
1.415     www      9435:        for (my $i=0;$i<$number;$i++) {
1.596.2.4  raeburn  9436:           if ((!$correct[$i]) && ($correct[$i] ne '0')) {
1.414     www      9437:              $result.='<br /><span class="LC_error">'.
                   9438:                       &mt('No correct result given for question "[_1]"!',
                   9439:                           $env{'form.question:'.$i}).'</span>';
                   9440:           }
                   9441:        }
1.596.2.4  raeburn  9442:        $result.='<br />'.&mt("Correct answer: [_1]",join(', ',map { ((($_) || ($_ eq '0'))?$_:'-') } @correct));
1.414     www      9443:     }
                   9444: # Start grading
1.415     www      9445:     my $pcorrect=$env{'form.pcorrect'};
                   9446:     my $pincorrect=$env{'form.pincorrect'};
1.416     www      9447:     my $storecount=0;
1.596.2.4  raeburn  9448:     my %users=();
1.415     www      9449:     foreach my $key (keys(%env)) {
1.420     www      9450:        my $user='';
1.415     www      9451:        if ($key=~/^form\.student\:(.*)$/) {
1.420     www      9452:           $user=$1;
                   9453:        }
                   9454:        if ($key=~/^form\.unknown\:(.*)$/) {
                   9455:           my $id=$1;
                   9456:           if (($env{'form.uname'.$id}) && ($env{'form.udom'.$id})) {
                   9457:              $user=$env{'form.uname'.$id}.':'.$env{'form.udom'.$id};
1.437     www      9458:           } elsif ($env{'form.multi'.$id}) {
                   9459:              $user=$env{'form.multi'.$id};
1.420     www      9460:           }
                   9461:        }
1.596.2.4  raeburn  9462:        if ($user) {
                   9463:           if ($users{$user}) {
                   9464:              $result.='<br /><span class="LC_warning">'.
                   9465:                       &mt("More than one entry found for <tt>[_1]</tt>!",$user).
                   9466:                       '</span><br />';
                   9467:           }
                   9468:           $users{$user}=1;
1.415     www      9469:           my @answer=split(/\,/,$env{$key});
                   9470:           my $sum=0;
1.522     www      9471:           my $realnumber=$number;
1.415     www      9472:           for (my $i=0;$i<$number;$i++) {
1.576     www      9473:              if  ($correct[$i] eq '-') {
                   9474:                 $realnumber--;
                   9475:              } elsif ($answer[$i]) {
1.415     www      9476:                 if ($gradingmechanism eq 'attendance') {
                   9477:                    $sum+=$pcorrect;
1.576     www      9478:                 } elsif ($correct[$i] eq '*') {
1.522     www      9479:                    $sum+=$pcorrect;
1.415     www      9480:                 } else {
1.596.2.4  raeburn  9481: # We actually grade if correct or not
                   9482:                    my $increment=$pincorrect;
                   9483: # Special case: numerical answer "0"
                   9484:                    if ($correct[$i] eq '0') {
                   9485:                       if ($answer[$i]=~/^[0\.]+$/) {
                   9486:                          $increment=$pcorrect;
                   9487:                       }
                   9488: # General numerical answer, both evaluate to something non-zero
                   9489:                    } elsif ((1.0*$correct[$i]!=0) && (1.0*$answer[$i]!=0)) {
                   9490:                       if (1.0*$correct[$i]==1.0*$answer[$i]) {
                   9491:                          $increment=$pcorrect;
                   9492:                       }
                   9493: # Must be just alphanumeric
                   9494:                    } elsif ($answer[$i] eq $correct[$i]) {
                   9495:                       $increment=$pcorrect;
1.415     www      9496:                    }
1.596.2.4  raeburn  9497:                    $sum+=$increment;
1.415     www      9498:                 }
                   9499:              }
                   9500:           }
1.522     www      9501:           my $ave=$sum/(100*$realnumber);
1.416     www      9502: # Store
                   9503:           my ($username,$domain)=split(/\:/,$user);
                   9504:           my %grades=();
                   9505:           $grades{"resource.$part.solved"}='correct_by_override';
                   9506:           $grades{"resource.$part.awarded"}=$ave;
                   9507:           $grades{"resource.regrader"}="$env{'user.name'}:$env{'user.domain'}";
                   9508:           my $returncode=&Apache::lonnet::cstore(\%grades,$symb,
                   9509:                                                  $env{'request.course.id'},
                   9510:                                                  $domain,$username);
                   9511:           if ($returncode ne 'ok') {
                   9512:              $result.="<br /><span class=\"LC_error\">Failed to save student $username:$domain. Message when trying to save was ($returncode)</span>";
                   9513:           } else {
                   9514:              $storecount++;
                   9515:           }
1.415     www      9516:        }
                   9517:     }
                   9518: # We are done
1.549     hauer    9519:     $result.='<br />'.&mt('Successfully stored grades for [quant,_1,student].',$storecount).
1.596.2.4  raeburn  9520:              '</td>'.
                   9521:              &Apache::loncommon::end_data_table_row().
                   9522:              &Apache::loncommon::end_data_table()."<br /><br />\n";
1.414     www      9523:     return $result.&show_grading_menu_form($symb);
                   9524: }
                   9525: 
1.582     raeburn  9526: sub navmap_errormsg {
                   9527:     return '<div class="LC_error">'.
                   9528:            &mt('An error occurred retrieving information about resources in the course.').'<br />'.
1.595     raeburn  9529:            &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  9530:            '</div>';
                   9531: }
                   9532: 
1.1       albertel 9533: sub handler {
1.41      ng       9534:     my $request=$_[0];
1.434     albertel 9535:     &reset_caches();
1.596.2.4  raeburn  9536:     if ($request->header_only) {
                   9537:         &Apache::loncommon::content_type($request,'text/html');
                   9538:         $request->send_http_header;
                   9539:         return OK;
1.41      ng       9540:     }
                   9541:     &Apache::loncommon::get_unprocessed_cgi($ENV{'QUERY_STRING'});
1.596.2.4  raeburn  9542: 
1.324     albertel 9543:     my $symb=&get_symb($request,1);
1.160     albertel 9544:     my @commands=&Apache::loncommon::get_env_multiple('form.command');
                   9545:     my $command=$commands[0];
1.447     foxr     9546: 
1.160     albertel 9547:     if ($#commands > 0) {
                   9548: 	&Apache::lonnet::logthis("grades got multiple commands ".join(':',@commands));
                   9549:     }
1.447     foxr     9550: 
1.513     foxr     9551:     $ssi_error = 0;
1.535     raeburn  9552:     my $brcrum = [{href=>"/adm/grades",text=>"Grading"}];
1.596.2.4  raeburn  9553:     my $start_page = &Apache::loncommon::start_page('Grading',undef,
1.596.2.5  raeburn  9554:                                           {'bread_crumbs' => $brcrum});
1.324     albertel 9555:     if ($symb eq '' && $command eq '') {
1.257     albertel 9556: 	if ($env{'user.adv'}) {
1.596.2.4  raeburn  9557:             &Apache::loncommon::content_type($request,'text/html');
                   9558:             $request->send_http_header;
                   9559:             $request->print($start_page);
1.257     albertel 9560: 	    if (($env{'form.codeone'}) && ($env{'form.codetwo'}) &&
                   9561: 		($env{'form.codethree'})) {
                   9562: 		my $token=$env{'form.codeone'}.'*'.$env{'form.codetwo'}.'*'.
                   9563: 		    $env{'form.codethree'};
1.41      ng       9564: 		my ($tsymb,$tuname,$tudom,$tcrsid)=
                   9565: 		    &Apache::lonnet::checkin($token);
                   9566: 		if ($tsymb) {
1.137     albertel 9567: 		    my ($map,$id,$url)=&Apache::lonnet::decode_symb($tsymb);
1.41      ng       9568: 		    if (&Apache::lonnet::allowed('mgr',$tcrsid)) {
1.513     foxr     9569: 			$request->print(&ssi_with_retries('/res/'.$url, $ssi_retries,
1.99      albertel 9570: 					  ('grade_username' => $tuname,
                   9571: 					   'grade_domain' => $tudom,
                   9572: 					   'grade_courseid' => $tcrsid,
                   9573: 					   'grade_symb' => $tsymb)));
1.41      ng       9574: 		    } else {
1.45      ng       9575: 			$request->print('<h3>Not authorized: '.$token.'</h3>');
1.99      albertel 9576: 		    }
1.41      ng       9577: 		} else {
1.45      ng       9578: 		    $request->print('<h3>Not a valid DocID: '.$token.'</h3>');
1.41      ng       9579: 		}
1.14      www      9580: 	    } else {
1.41      ng       9581: 		$request->print(&Apache::lonxml::tokeninputfield());
                   9582: 	    }
1.596.2.4  raeburn  9583:         } elsif ($env{'request.course.id'}) {
                   9584:             &init_perm(); 
                   9585:             if (!%perm) {
                   9586:                 $request->internal_redirect('/adm/quickgrades');
                   9587:             } else {
                   9588:                 &Apache::loncommon::content_type($request,'text/html');
                   9589:                 $request->send_http_header;
                   9590:                 $request->print($start_page);
                   9591:             }
                   9592:         }
1.41      ng       9593:     } else {
1.596.2.4  raeburn  9594:         &init_perm();
                   9595:         if (!$env{'request.course.id'}) {
1.596.2.11  raeburn  9596:             unless ((&Apache::lonnet::allowed('usc',$env{'request.role.domain'})) &&
                   9597:                     ($command =~ /^scantronupload/)) {
                   9598:                 # Not in a course.
                   9599:                 $env{'user.error.msg'}="/adm/grades::vgr:0:0:Cannot display grades page outside course context";
                   9600:                 return HTTP_NOT_ACCEPTABLE;
                   9601:             }
1.596.2.4  raeburn  9602:         } elsif (!%perm) {
                   9603:             $request->internal_redirect('/adm/quickgrades');
                   9604:         }
                   9605:         &Apache::loncommon::content_type($request,'text/html');
                   9606:         $request->send_http_header;
                   9607:         $request->print($start_page);
1.104     albertel 9608: 	if ($command eq 'submission' && $perm{'vgr'}) {
1.257     albertel 9609: 	    ($env{'form.student'} eq '' ? &listStudents($request) : &submission($request,0,0));
1.103     albertel 9610: 	} elsif ($command eq 'pickStudentPage' && $perm{'vgr'}) {
1.68      ng       9611: 	    &pickStudentPage($request);
1.103     albertel 9612: 	} elsif ($command eq 'displayPage' && $perm{'vgr'}) {
1.68      ng       9613: 	    &displayPage($request);
1.104     albertel 9614: 	} elsif ($command eq 'gradeByPage' && $perm{'mgr'}) {
1.71      ng       9615: 	    &updateGradeByPage($request);
1.104     albertel 9616: 	} elsif ($command eq 'processGroup' && $perm{'vgr'}) {
1.41      ng       9617: 	    &processGroup($request);
1.104     albertel 9618: 	} elsif ($command eq 'gradingmenu' && $perm{'vgr'}) {
1.443     banghart 9619: 	    $request->print(&grading_menu($request));
                   9620: 	} elsif ($command eq 'submit_options' && $perm{'vgr'}) {
                   9621: 	    $request->print(&submit_options($request));
1.104     albertel 9622: 	} elsif ($command eq 'viewgrades' && $perm{'vgr'}) {
1.41      ng       9623: 	    $request->print(&viewgrades($request));
1.104     albertel 9624: 	} elsif ($command eq 'handgrade' && $perm{'mgr'}) {
1.41      ng       9625: 	    $request->print(&processHandGrade($request));
1.106     albertel 9626: 	} elsif ($command eq 'editgrades' && $perm{'mgr'}) {
1.41      ng       9627: 	    $request->print(&editgrades($request));
1.106     albertel 9628: 	} elsif ($command eq 'verify' && $perm{'vgr'}) {
1.41      ng       9629: 	    $request->print(&verifyreceipt($request));
1.400     www      9630:         } elsif ($command eq 'processclicker' && $perm{'mgr'}) {
                   9631:             $request->print(&process_clicker($request));
                   9632:         } elsif ($command eq 'processclickerfile' && $perm{'mgr'}) {
                   9633:             $request->print(&process_clicker_file($request));
1.414     www      9634:         } elsif ($command eq 'assignclickergrades' && $perm{'mgr'}) {
                   9635:             $request->print(&assign_clicker_grades($request));
1.106     albertel 9636: 	} elsif ($command eq 'csvform' && $perm{'mgr'}) {
1.72      ng       9637: 	    $request->print(&upcsvScores_form($request));
1.106     albertel 9638: 	} elsif ($command eq 'csvupload' && $perm{'mgr'}) {
1.41      ng       9639: 	    $request->print(&csvupload($request));
1.106     albertel 9640: 	} elsif ($command eq 'csvuploadmap' && $perm{'mgr'} ) {
1.41      ng       9641: 	    $request->print(&csvuploadmap($request));
1.246     albertel 9642: 	} elsif ($command eq 'csvuploadoptions' && $perm{'mgr'}) {
1.257     albertel 9643: 	    if ($env{'form.associate'} ne 'Reverse Association') {
1.246     albertel 9644: 		$request->print(&csvuploadoptions($request));
1.41      ng       9645: 	    } else {
1.257     albertel 9646: 		if ( $env{'form.upfile_associate'} ne 'reverse' ) {
                   9647: 		    $env{'form.upfile_associate'} = 'reverse';
1.41      ng       9648: 		} else {
1.257     albertel 9649: 		    $env{'form.upfile_associate'} = 'forward';
1.41      ng       9650: 		}
                   9651: 		$request->print(&csvuploadmap($request));
                   9652: 	    }
1.246     albertel 9653: 	} elsif ($command eq 'csvuploadassign' && $perm{'mgr'} ) {
                   9654: 	    $request->print(&csvuploadassign($request));
1.106     albertel 9655: 	} elsif ($command eq 'scantron_selectphase' && $perm{'mgr'}) {
1.75      albertel 9656: 	    $request->print(&scantron_selectphase($request));
1.203     albertel 9657:  	} elsif ($command eq 'scantron_warning' && $perm{'mgr'}) {
                   9658:  	    $request->print(&scantron_do_warning($request));
1.142     albertel 9659: 	} elsif ($command eq 'scantron_validate' && $perm{'mgr'}) {
                   9660: 	    $request->print(&scantron_validate_file($request));
1.106     albertel 9661: 	} elsif ($command eq 'scantron_process' && $perm{'mgr'}) {
1.82      albertel 9662: 	    $request->print(&scantron_process_students($request));
1.157     albertel 9663:  	} elsif ($command eq 'scantronupload' && 
1.257     albertel 9664:  		 (&Apache::lonnet::allowed('usc',$env{'request.role.domain'})||
                   9665: 		  &Apache::lonnet::allowed('usc',$env{'request.course.id'}))) {
1.162     albertel 9666:  	    $request->print(&scantron_upload_scantron_data($request)); 
1.157     albertel 9667:  	} elsif ($command eq 'scantronupload_save' &&
1.257     albertel 9668:  		 (&Apache::lonnet::allowed('usc',$env{'request.role.domain'})||
                   9669: 		  &Apache::lonnet::allowed('usc',$env{'request.course.id'}))) {
1.157     albertel 9670:  	    $request->print(&scantron_upload_scantron_data_save($request));
1.202     albertel 9671:  	} elsif ($command eq 'scantron_download' &&
1.257     albertel 9672: 		 &Apache::lonnet::allowed('usc',$env{'request.course.id'})) {
1.162     albertel 9673:  	    $request->print(&scantron_download_scantron_data($request));
1.523     raeburn  9674:         } elsif ($command eq 'checksubmissions' && $perm{'vgr'}) {
                   9675:             $request->print(&checkscantron_results($request));     
1.106     albertel 9676: 	} elsif ($command) {
1.562     bisitz   9677: 	    $request->print('<p class="LC_error">'.&mt('Access Denied ([_1])',$command).'</p>');
1.26      albertel 9678: 	}
1.2       albertel 9679:     }
1.513     foxr     9680:     if ($ssi_error) {
                   9681: 	&ssi_print_error($request);
                   9682:     }
1.353     albertel 9683:     $request->print(&Apache::loncommon::end_page());
1.434     albertel 9684:     &reset_caches();
1.596.2.4  raeburn  9685:     return OK;
1.44      ng       9686: }
                   9687: 
1.1       albertel 9688: 1;
                   9689: 
1.13      albertel 9690: __END__;
1.531     jms      9691: 
                   9692: 
                   9693: =head1 NAME
                   9694: 
                   9695: Apache::grades
                   9696: 
                   9697: =head1 SYNOPSIS
                   9698: 
                   9699: Handles the viewing of grades.
                   9700: 
                   9701: This is part of the LearningOnline Network with CAPA project
                   9702: described at http://www.lon-capa.org.
                   9703: 
                   9704: =head1 OVERVIEW
                   9705: 
                   9706: Do an ssi with retries:
                   9707: While I'd love to factor out this with the vesrion in lonprintout,
                   9708: 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
                   9709: I'm not quite ready to invent (e.g. an ssi_with_retry object).
                   9710: 
                   9711: At least the logic that drives this has been pulled out into loncommon.
                   9712: 
                   9713: 
                   9714: 
                   9715: ssi_with_retries - Does the server side include of a resource.
                   9716:                      if the ssi call returns an error we'll retry it up to
                   9717:                      the number of times requested by the caller.
                   9718:                      If we still have a proble, no text is appended to the
                   9719:                      output and we set some global variables.
                   9720:                      to indicate to the caller an SSI error occurred.  
                   9721:                      All of this is supposed to deal with the issues described
                   9722:                      in LonCAPA BZ 5631 see:
                   9723:                      http://bugs.lon-capa.org/show_bug.cgi?id=5631
                   9724:                      by informing the user that this happened.
                   9725: 
                   9726: Parameters:
                   9727:   resource   - The resource to include.  This is passed directly, without
                   9728:                interpretation to lonnet::ssi.
                   9729:   form       - The form hash parameters that guide the interpretation of the resource
                   9730:                
                   9731:   retries    - Number of retries allowed before giving up completely.
                   9732: Returns:
                   9733:   On success, returns the rendered resource identified by the resource parameter.
                   9734: Side Effects:
                   9735:   The following global variables can be set:
                   9736:    ssi_error                - If an unrecoverable error occurred this becomes true.
                   9737:                               It is up to the caller to initialize this to false
                   9738:                               if desired.
                   9739:    ssi_error_resource  - If an unrecoverable error occurred, this is the value
                   9740:                               of the resource that could not be rendered by the ssi
                   9741:                               call.
                   9742:    ssi_error_message   - The error string fetched from the ssi response
                   9743:                               in the event of an error.
                   9744: 
                   9745: 
                   9746: =head1 HANDLER SUBROUTINE
                   9747: 
                   9748: ssi_with_retries()
                   9749: 
                   9750: =head1 SUBROUTINES
                   9751: 
                   9752: =over
                   9753: 
                   9754: =item scantron_get_correction() : 
                   9755: 
                   9756:    Builds the interface screen to interact with the operator to fix a
                   9757:    specific error condition in a specific scanline
                   9758: 
                   9759:  Arguments:
                   9760:     $r           - Apache request object
                   9761:     $i           - number of the current scanline
                   9762:     $scan_record - hash ref as returned from &scantron_parse_scanline()
                   9763:     $scan_config - hash ref as returned from &get_scantron_config()
                   9764:     $line        - full contents of the current scanline
                   9765:     $error       - error condition, valid values are
                   9766:                    'incorrectCODE', 'duplicateCODE',
                   9767:                    'doublebubble', 'missingbubble',
                   9768:                    'duplicateID', 'incorrectID'
                   9769:     $arg         - extra information needed
                   9770:        For errors:
                   9771:          - duplicateID   - paper number that this studentID was seen before on
                   9772:          - duplicateCODE - array ref of the paper numbers this CODE was
                   9773:                            seen on before
                   9774:          - incorrectCODE - current incorrect CODE 
                   9775:          - doublebubble  - array ref of the bubble lines that have double
                   9776:                            bubble errors
                   9777:          - missingbubble - array ref of the bubble lines that have missing
                   9778:                            bubble errors
                   9779: 
                   9780: =item  scantron_get_maxbubble() : 
                   9781: 
1.582     raeburn  9782:    Arguments:
                   9783:        $nav_error  - Reference to scalar which is a flag to indicate a
                   9784:                       failure to retrieve a navmap object.
                   9785:        if $nav_error is set to 1 by scantron_get_maxbubble(), the 
                   9786:        calling routine should trap the error condition and display the warning
                   9787:        found in &navmap_errormsg().
                   9788: 
1.531     jms      9789:    Returns the maximum number of bubble lines that are expected to
                   9790:    occur. Does this by walking the selected sequence rendering the
                   9791:    resource and then checking &Apache::lonxml::get_problem_counter()
                   9792:    for what the current value of the problem counter is.
                   9793: 
                   9794:    Caches the results to $env{'form.scantron_maxbubble'},
                   9795:    $env{'form.scantron.bubble_lines.n'}, 
                   9796:    $env{'form.scantron.first_bubble_line.n'} and
                   9797:    $env{"form.scantron.sub_bubblelines.n"}
                   9798:    which are the total number of bubble, lines, the number of bubble
                   9799:    lines for response n and number of the first bubble line for response n,
                   9800:    and a comma separated list of numbers of bubble lines for sub-questions
                   9801:    (for optionresponse, matchresponse, and rankresponse items), for response n.  
                   9802: 
                   9803: 
                   9804: =item  scantron_validate_missingbubbles() : 
                   9805: 
                   9806:    Validates all scanlines in the selected file to not have any
                   9807:     answers that don't have bubbles that have not been verified
                   9808:     to be bubble free.
                   9809: 
                   9810: =item  scantron_process_students() : 
                   9811: 
1.596.2.6  raeburn  9812:    Routine that does the actual grading of the bubblesheet information.
1.531     jms      9813: 
                   9814:    The parsed scanline hash is added to %env 
                   9815: 
                   9816:    Then foreach unskipped scanline it does an &Apache::lonnet::ssi()
                   9817:    foreach resource , with the form data of
                   9818: 
                   9819: 	'submitted'     =>'scantron' 
                   9820: 	'grade_target'  =>'grade',
                   9821: 	'grade_username'=> username of student
                   9822: 	'grade_domain'  => domain of student
                   9823: 	'grade_courseid'=> of course
                   9824: 	'grade_symb'    => symb of resource to grade
                   9825: 
                   9826:     This triggers a grading pass. The problem grading code takes care
                   9827:     of converting the bubbled letter information (now in %env) into a
                   9828:     valid submission.
                   9829: 
                   9830: =item  scantron_upload_scantron_data() :
                   9831: 
1.596.2.6  raeburn  9832:     Creates the screen for adding a new bubblesheet data file to a course.
1.531     jms      9833: 
                   9834: =item  scantron_upload_scantron_data_save() : 
                   9835: 
                   9836:    Adds a provided bubble information data file to the course if user
                   9837:    has the correct privileges to do so. 
                   9838: 
                   9839: =item  valid_file() :
                   9840: 
                   9841:    Validates that the requested bubble data file exists in the course.
                   9842: 
                   9843: =item  scantron_download_scantron_data() : 
                   9844: 
                   9845:    Shows a list of the three internal files (original, corrected,
1.596.2.6  raeburn  9846:    skipped) for a specific bubblesheet data file that exists in the
1.531     jms      9847:    course.
                   9848: 
                   9849: =item  scantron_validate_ID() : 
                   9850: 
                   9851:    Validates all scanlines in the selected file to not have any
1.556     weissno  9852:    invalid or underspecified student/employee IDs
1.531     jms      9853: 
1.582     raeburn  9854: =item navmap_errormsg() :
                   9855: 
                   9856:    Returns HTML mark-up inside a <div></div> with a link to re-initialize the course.
                   9857:    Should be called whenever the request to instantiate a navmap object fails.  
                   9858: 
1.531     jms      9859: =back
                   9860: 
                   9861: =cut

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