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

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.12.2.  (raeburn    4:): # $Id: grades.pm,v 1.596.2.12.2.3 2012/05/02 15:21:00 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.447     foxr       55: 
1.513     foxr       56: #  These variables are used to recover from ssi errors
                     57: 
                     58: my $ssi_retries = 5;
                     59: my $ssi_error;
                     60: my $ssi_error_resource;
                     61: my $ssi_error_message;
                     62: 
                     63: 
                     64: sub ssi_with_retries {
                     65:     my ($resource, $retries, %form) = @_;
                     66:     my ($content, $response) = &Apache::loncommon::ssi_with_retries($resource, $retries, %form);
                     67:     if ($response->is_error) {
                     68: 	$ssi_error          = 1;
                     69: 	$ssi_error_resource = $resource;
                     70: 	$ssi_error_message  = $response->code . " " . $response->message;
                     71:     }
                     72: 
                     73:     return $content;
                     74: 
                     75: }
                     76: #
                     77: #  Prodcuces an ssi retry failure error message to the user:
                     78: #
                     79: 
                     80: sub ssi_print_error {
                     81:     my ($r) = @_;
1.516     raeburn    82:     my $helpurl = &Apache::loncommon::top_nav_help('Helpdesk');
                     83:     $r->print('
                     84: <br />
                     85: <h2>'.&mt('An unrecoverable network error occurred:').'</h2>
                     86: <p>
                     87: '.&mt('Unable to retrieve a resource from a server:').'<br />
                     88: '.&mt('Resource:').' '.$ssi_error_resource.'<br />
                     89: '.&mt('Error:').' '.$ssi_error_message.'
                     90: </p>
                     91: <p>'.
                     92: &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 />'.
                     93: &mt('If the error persists, please contact the [_1] for assistance.',$helpurl).
                     94: '</p>');
                     95:     return;
1.513     foxr       96: }
                     97: 
1.44      ng         98: #
1.146     albertel   99: # --- Retrieve the parts from the metadata file.---
1.44      ng        100: sub getpartlist {
1.582     raeburn   101:     my ($symb,$errorref) = @_;
1.439     albertel  102: 
                    103:     my $navmap   = Apache::lonnavmaps::navmap->new();
1.582     raeburn   104:     unless (ref($navmap)) {
                    105:         if (ref($errorref)) { 
                    106:             $$errorref = 'navmap';
                    107:             return;
                    108:         }
                    109:     }
1.439     albertel  110:     my $res      = $navmap->getBySymb($symb);
                    111:     my $partlist = $res->parts();
                    112:     my $url      = $res->src();
                    113:     my @metakeys = split(/,/,&Apache::lonnet::metadata($url,'keys'));
                    114: 
1.146     albertel  115:     my @stores;
1.439     albertel  116:     foreach my $part (@{ $partlist }) {
1.146     albertel  117: 	foreach my $key (@metakeys) {
                    118: 	    if ($key =~ m/^stores_\Q$part\E_/) { push(@stores,$key); }
                    119: 	}
                    120:     }
                    121:     return @stores;
1.2       albertel  122: }
                    123: 
1.44      ng        124: # --- Get the symbolic name of a problem and the url
1.324     albertel  125: sub get_symb {
1.173     albertel  126:     my ($request,$silent) = @_;
1.257     albertel  127:     (my $url=$env{'form.url'}) =~ s-^http://($ENV{'SERVER_NAME'}|$ENV{'HTTP_HOST'})--;
                    128:     my $symb=($env{'form.symb'} ne '' ? $env{'form.symb'} : (&Apache::lonnet::symbread($url)));
1.173     albertel  129:     if ($symb eq '') { 
                    130: 	if (!$silent) {
1.596.2.4  raeburn   131:             $request->print(&mt("Unable to handle ambiguous references: [_1].",$url));
1.173     albertel  132: 	    return ();
                    133: 	}
                    134:     }
1.418     albertel  135:     &Apache::lonenc::check_decrypt(\$symb);
1.324     albertel  136:     return ($symb);
1.32      ng        137: }
                    138: 
1.129     ng        139: #--- Format fullname, username:domain if different for display
                    140: #--- Use anywhere where the student names are listed
                    141: sub nameUserString {
                    142:     my ($type,$fullname,$uname,$udom) = @_;
                    143:     if ($type eq 'header') {
1.485     albertel  144: 	return '<b>&nbsp;'.&mt('Fullname').'&nbsp;</b><span class="LC_internal_info">('.&mt('Username').')</span>';
1.129     ng        145:     } else {
1.398     albertel  146: 	return '&nbsp;'.$fullname.'<span class="LC_internal_info">&nbsp;('.$uname.
                    147: 	    ($env{'user.domain'} eq $udom ? '' : ' ('.$udom.')').')</span>';
1.129     ng        148:     }
                    149: }
                    150: 
1.44      ng        151: #--- Get the partlist and the response type for a given problem. ---
                    152: #--- Indicate if a response type is coded handgraded or not. ---
1.39      ng        153: sub response_type {
1.582     raeburn   154:     my ($symb,$response_error) = @_;
1.377     albertel  155: 
                    156:     my $navmap = Apache::lonnavmaps::navmap->new();
1.582     raeburn   157:     unless (ref($navmap)) {
                    158:         if (ref($response_error)) {
                    159:             $$response_error = 1;
                    160:         }
                    161:         return;
                    162:     }
1.377     albertel  163:     my $res = $navmap->getBySymb($symb);
1.593     raeburn   164:     unless (ref($res)) {
                    165:         $$response_error = 1;
                    166:         return;
                    167:     }
1.377     albertel  168:     my $partlist = $res->parts();
1.392     albertel  169:     my %vPart = 
                    170: 	map { $_ => 1 } (&Apache::loncommon::get_env_multiple('form.vPart'));
1.377     albertel  171:     my (%response_types,%handgrade);
                    172:     foreach my $part (@{ $partlist }) {
1.392     albertel  173: 	next if (%vPart && !exists($vPart{$part}));
                    174: 
1.377     albertel  175: 	my @types = $res->responseType($part);
                    176: 	my @ids = $res->responseIds($part);
                    177: 	for (my $i=0; $i < scalar(@ids); $i++) {
                    178: 	    $response_types{$part}{$ids[$i]} = $types[$i];
                    179: 	    $handgrade{$part.'_'.$ids[$i]} = 
                    180: 		&Apache::lonnet::EXT('resource.'.$part.'_'.$ids[$i].
                    181: 				     '.handgrade',$symb);
1.41      ng        182: 	}
                    183:     }
1.377     albertel  184:     return ($partlist,\%handgrade,\%response_types);
1.39      ng        185: }
                    186: 
1.375     albertel  187: sub flatten_responseType {
                    188:     my ($responseType) = @_;
                    189:     my @part_response_id =
                    190: 	map { 
                    191: 	    my $part = $_;
                    192: 	    map {
                    193: 		[$part,$_]
                    194: 		} sort(keys(%{ $responseType->{$part} }));
                    195: 	} sort(keys(%$responseType));
                    196:     return @part_response_id;
                    197: }
                    198: 
1.207     albertel  199: sub get_display_part {
1.324     albertel  200:     my ($partID,$symb)=@_;
1.207     albertel  201:     my $display=&Apache::lonnet::EXT('resource.'.$partID.'.display',$symb);
                    202:     if (defined($display) and $display ne '') {
1.577     bisitz    203:         $display.= ' (<span class="LC_internal_info">'
                    204:                   .&mt('Part ID: [_1]',$partID).'</span>)';
1.207     albertel  205:     } else {
                    206: 	$display=$partID;
                    207:     }
                    208:     return $display;
                    209: }
1.269     raeburn   210: 
1.118     ng        211: #--- Show resource title
                    212: #--- and parts and response type
                    213: sub showResourceInfo {
1.582     raeburn   214:     my ($symb,$probTitle,$checkboxes,$res_error) = @_;
1.398     albertel  215:     my $result = '<h3>'.&mt('Current Resource').': '.$probTitle.'</h3>'."\n";
1.582     raeburn   216:     my ($partlist,$handgrade,$responseType) = &response_type($symb,$res_error);
                    217:     if (ref($res_error)) {
                    218:         if ($$res_error) {
                    219:             return;
                    220:         }
                    221:     }
1.584     bisitz    222:     $result.=&Apache::loncommon::start_data_table()
                    223:             .&Apache::loncommon::start_data_table_header_row();
                    224:     if ($checkboxes) {
                    225:         $result.='<th>&nbsp;</th>';
                    226:     }
                    227:     $result.='<th>'.&mt('Problem Part').'</th>'
                    228:             .'<th>'.&mt('Res. ID').'</th>'
                    229:             .'<th>'.&mt('Type').'</th>'
                    230:             .&Apache::loncommon::end_data_table_header_row();
1.126     ng        231:     my %resptype = ();
1.122     ng        232:     my $hdgrade='no';
1.154     albertel  233:     my %partsseen;
1.524     raeburn   234:     foreach my $partID (sort(keys(%$responseType))) {
1.584     bisitz    235:         foreach my $resID (sort(keys(%{ $responseType->{$partID} }))) {
                    236:             my $handgrade=$$handgrade{$partID.'_'.$resID};
                    237:             my $responsetype = $responseType->{$partID}->{$resID};
                    238:             $hdgrade = $handgrade if ($handgrade eq 'yes');
                    239:             $result.=&Apache::loncommon::start_data_table_row();
                    240:             if ($checkboxes) {
                    241:                 if (exists($partsseen{$partID})) {
                    242:                     $result.="<td>&nbsp;</td>";
                    243:                 } else {
                    244:                     $result.="<td><input type='checkbox' name='vPart' value='$partID' checked='checked' /></td>";
                    245:                 }
                    246:                 $partsseen{$partID}=1;
                    247:             }
                    248:             my $display_part=&get_display_part($partID,$symb);
                    249:             $result.='<td>'.$display_part.'</td>'
                    250:                     .'<td>'.'<span class="LC_internal_info">'.$resID.'</span></td>'
                    251:                     .'<td>'.&mt($responsetype).'</td>'
                    252: #                   .'<td>'.&mt('<b>Handgrade: </b>[_1]',$handgrade).'</td>'
                    253:                     .&Apache::loncommon::end_data_table_row();
                    254:         }
1.118     ng        255:     }
1.584     bisitz    256:     $result.=&Apache::loncommon::end_data_table();
1.147     albertel  257:     return $result,$responseType,$hdgrade,$partlist,$handgrade;
1.118     ng        258: }
                    259: 
1.434     albertel  260: sub reset_caches {
                    261:     &reset_analyze_cache();
                    262:     &reset_perm();
                    263: }
                    264: 
                    265: {
                    266:     my %analyze_cache;
1.557     raeburn   267:     my %analyze_cache_formkeys;
1.148     albertel  268: 
1.434     albertel  269:     sub reset_analyze_cache {
                    270: 	undef(%analyze_cache);
1.557     raeburn   271:         undef(%analyze_cache_formkeys);
1.434     albertel  272:     }
                    273: 
                    274:     sub get_analyze {
1.596.2.12.2.  (raeburn  275:): 	my ($symb,$uname,$udom,$no_increment,$add_to_hash,$type,$trial,$rndseed,$bubbles_per_row)=@_;
1.434     albertel  276: 	my $key = "$symb\0$uname\0$udom";
1.596.2.2  raeburn   277:         if ($type eq 'randomizetry') {
                    278:             if ($trial ne '') {
                    279:                 $key .= "\0".$trial;
                    280:             }
                    281:         }
1.557     raeburn   282: 	if (exists($analyze_cache{$key})) {
                    283:             my $getupdate = 0;
                    284:             if (ref($add_to_hash) eq 'HASH') {
                    285:                 foreach my $item (keys(%{$add_to_hash})) {
                    286:                     if (ref($analyze_cache_formkeys{$key}) eq 'HASH') {
                    287:                         if (!exists($analyze_cache_formkeys{$key}{$item})) {
                    288:                             $getupdate = 1;
                    289:                             last;
                    290:                         }
                    291:                     } else {
                    292:                         $getupdate = 1;
                    293:                     }
                    294:                 }
                    295:             }
                    296:             if (!$getupdate) {
                    297:                 return $analyze_cache{$key};
                    298:             }
                    299:         }
1.434     albertel  300: 
                    301: 	my (undef,undef,$url)=&Apache::lonnet::decode_symb($symb);
                    302: 	$url=&Apache::lonnet::clutter($url);
1.557     raeburn   303:         my %form = ('grade_target'      => 'analyze',
                    304:                     'grade_domain'      => $udom,
                    305:                     'grade_symb'        => $symb,
                    306:                     'grade_courseid'    =>  $env{'request.course.id'},
                    307:                     'grade_username'    => $uname,
                    308:                     'grade_noincrement' => $no_increment);
1.596.2.12.2.  (raeburn  309:):         if ($bubbles_per_row ne '') {
                    310:):             $form{'bubbles_per_row'} = $bubbles_per_row;
                    311:):         }
1.596.2.2  raeburn   312:         if ($type eq 'randomizetry') {
                    313:             $form{'grade_questiontype'} = $type;
                    314:             if ($rndseed ne '') {
                    315:                 $form{'grade_rndseed'} = $rndseed;
                    316:             }
                    317:         }
1.557     raeburn   318:         if (ref($add_to_hash)) {
                    319:             %form = (%form,%{$add_to_hash});
1.596.2.2  raeburn   320:         }
1.557     raeburn   321: 	my $subresult=&ssi_with_retries($url, $ssi_retries,%form);
1.434     albertel  322: 	(undef,$subresult)=split(/_HASH_REF__/,$subresult,2);
                    323: 	my %analyze=&Apache::lonnet::str2hash($subresult);
1.557     raeburn   324:         if (ref($add_to_hash) eq 'HASH') {
                    325:             $analyze_cache_formkeys{$key} = $add_to_hash;
                    326:         } else {
                    327:             $analyze_cache_formkeys{$key} = {};
                    328:         }
1.434     albertel  329: 	return $analyze_cache{$key} = \%analyze;
                    330:     }
                    331: 
                    332:     sub get_order {
1.596.2.2  raeburn   333: 	my ($partid,$respid,$symb,$uname,$udom,$no_increment,$type,$trial,$rndseed)=@_;
                    334: 	my $analyze = &get_analyze($symb,$uname,$udom,$no_increment,undef,$type,$trial,$rndseed);
1.434     albertel  335: 	return $analyze->{"$partid.$respid.shown"};
                    336:     }
                    337: 
                    338:     sub get_radiobutton_correct_foil {
1.596.2.2  raeburn   339: 	my ($partid,$respid,$symb,$uname,$udom,$type,$trial,$rndseed)=@_;
                    340: 	my $analyze = &get_analyze($symb,$uname,$udom,undef,undef,$type,$trial,$rndseed);
                    341:         my $foils = &get_order($partid,$respid,$symb,$uname,$udom,undef,$type,$trial,$rndseed);
1.555     raeburn   342:         if (ref($foils) eq 'ARRAY') {
                    343: 	    foreach my $foil (@{$foils}) {
                    344: 	        if ($analyze->{"$partid.$respid.foil.value.$foil"} eq 'true') {
                    345: 		    return $foil;
                    346: 	        }
1.434     albertel  347: 	    }
                    348: 	}
                    349:     }
1.554     raeburn   350: 
                    351:     sub scantron_partids_tograde {
1.596.2.12.2.  (raeburn  352:):         my ($resource,$cid,$uname,$udom,$check_for_randomlist,$bubbles_per_row) = @_;
1.554     raeburn   353:         my (%analysis,@parts);
                    354:         if (ref($resource)) {
                    355:             my $symb = $resource->symb();
1.557     raeburn   356:             my $add_to_form;
                    357:             if ($check_for_randomlist) {
                    358:                 $add_to_form = { 'check_parts_withrandomlist' => 1,};
                    359:             }
1.596.2.12.2.  (raeburn  360:):             my $analyze =
                    361:):                 &get_analyze($symb,$uname,$udom,undef,$add_to_form,
                    362:):                              undef,undef,undef,$bubbles_per_row);
1.554     raeburn   363:             if (ref($analyze) eq 'HASH') {
                    364:                 %analysis = %{$analyze};
                    365:             }
                    366:             if (ref($analysis{'parts'}) eq 'ARRAY') {
                    367:                 foreach my $part (@{$analysis{'parts'}}) {
                    368:                     my ($id,$respid) = split(/\./,$part);
                    369:                     if (!&Apache::loncommon::check_if_partid_hidden($id,$symb,$udom,$uname)) {
                    370:                         push(@parts,$part);
                    371:                     }
                    372:                 }
                    373:             }
                    374:         }
                    375:         return (\%analysis,\@parts);
                    376:     }
                    377: 
1.148     albertel  378: }
1.434     albertel  379: 
1.118     ng        380: #--- Clean response type for display
1.335     albertel  381: #--- Currently filters option/rank/radiobutton/match/essay/Task
                    382: #        response types only.
1.118     ng        383: sub cleanRecord {
1.336     albertel  384:     my ($answer,$response,$symb,$partid,$respid,$record,$order,$version,
1.596.2.2  raeburn   385: 	$uname,$udom,$type,$trial,$rndseed) = @_;
1.398     albertel  386:     my $grayFont = '<span class="LC_internal_info">';
1.148     albertel  387:     if ($response =~ /^(option|rank)$/) {
                    388: 	my %answer=&Apache::lonnet::str2hash($answer);
                    389: 	my %grading=&Apache::lonnet::str2hash($record->{$version."resource.$partid.$respid.submissiongrading"});
                    390: 	my ($toprow,$bottomrow);
                    391: 	foreach my $foil (@$order) {
                    392: 	    if ($grading{$foil} == 1) {
                    393: 		$toprow.='<td><b>'.$answer{$foil}.'&nbsp;</b></td>';
                    394: 	    } else {
                    395: 		$toprow.='<td><i>'.$answer{$foil}.'&nbsp;</i></td>';
                    396: 	    }
1.398     albertel  397: 	    $bottomrow.='<td>'.$grayFont.$foil.'</span>&nbsp;</td>';
1.148     albertel  398: 	}
                    399: 	return '<blockquote><table border="1">'.
1.466     albertel  400: 	    '<tr valign="top"><td>'.&mt('Answer').'</td>'.$toprow.'</tr>'.
                    401: 	    '<tr valign="top"><td>'.$grayFont.&mt('Option ID').'</span></td>'.
1.596.2.1  raeburn   402: 	    $bottomrow.'</tr></table></blockquote>';
1.148     albertel  403:     } elsif ($response eq 'match') {
                    404: 	my %answer=&Apache::lonnet::str2hash($answer);
                    405: 	my %grading=&Apache::lonnet::str2hash($record->{$version."resource.$partid.$respid.submissiongrading"});
                    406: 	my @items=&Apache::lonnet::str2array($record->{$version."resource.$partid.$respid.submissionitems"});
                    407: 	my ($toprow,$middlerow,$bottomrow);
                    408: 	foreach my $foil (@$order) {
                    409: 	    my $item=shift(@items);
                    410: 	    if ($grading{$foil} == 1) {
                    411: 		$toprow.='<td><b>'.$item.'&nbsp;</b></td>';
1.398     albertel  412: 		$middlerow.='<td><b>'.$grayFont.$answer{$foil}.'&nbsp;</span></b></td>';
1.148     albertel  413: 	    } else {
                    414: 		$toprow.='<td><i>'.$item.'&nbsp;</i></td>';
1.398     albertel  415: 		$middlerow.='<td><i>'.$grayFont.$answer{$foil}.'&nbsp;</span></i></td>';
1.148     albertel  416: 	    }
1.398     albertel  417: 	    $bottomrow.='<td>'.$grayFont.$foil.'</span>&nbsp;</td>';
1.118     ng        418: 	}
1.126     ng        419: 	return '<blockquote><table border="1">'.
1.466     albertel  420: 	    '<tr valign="top"><td>'.&mt('Answer').'</td>'.$toprow.'</tr>'.
                    421: 	    '<tr valign="top"><td>'.$grayFont.&mt('Item ID').'</span></td>'.
1.148     albertel  422: 	    $middlerow.'</tr>'.
1.466     albertel  423: 	    '<tr valign="top"><td>'.$grayFont.&mt('Option ID').'</span></td>'.
1.596.2.8  raeburn   424: 	    $bottomrow.'</tr></table></blockquote>';
1.148     albertel  425:     } elsif ($response eq 'radiobutton') {
                    426: 	my %answer=&Apache::lonnet::str2hash($answer);
                    427: 	my ($toprow,$bottomrow);
1.434     albertel  428: 	my $correct = 
1.596.2.2  raeburn   429: 	    &get_radiobutton_correct_foil($partid,$respid,$symb,$uname,$udom,$type,$trial,$rndseed);
1.434     albertel  430: 	foreach my $foil (@$order) {
1.148     albertel  431: 	    if (exists($answer{$foil})) {
1.434     albertel  432: 		if ($foil eq $correct) {
1.466     albertel  433: 		    $toprow.='<td><b>'.&mt('true').'</b></td>';
1.148     albertel  434: 		} else {
1.466     albertel  435: 		    $toprow.='<td><i>'.&mt('true').'</i></td>';
1.148     albertel  436: 		}
                    437: 	    } else {
1.466     albertel  438: 		$toprow.='<td>'.&mt('false').'</td>';
1.148     albertel  439: 	    }
1.398     albertel  440: 	    $bottomrow.='<td>'.$grayFont.$foil.'</span>&nbsp;</td>';
1.148     albertel  441: 	}
                    442: 	return '<blockquote><table border="1">'.
1.466     albertel  443: 	    '<tr valign="top"><td>'.&mt('Answer').'</td>'.$toprow.'</tr>'.
                    444: 	    '<tr valign="top"><td>'.$grayFont.&mt('Option ID').'</span></td>'.
1.596.2.4  raeburn   445: 	    $bottomrow.'</tr></table></blockquote>';
1.148     albertel  446:     } elsif ($response eq 'essay') {
1.257     albertel  447: 	if (! exists ($env{'form.'.$symb})) {
1.122     ng        448: 	    my (%keyhash) = &Apache::lonnet::dump('nohist_handgrade',
1.257     albertel  449: 						  $env{'course.'.$env{'request.course.id'}.'.domain'},
                    450: 						  $env{'course.'.$env{'request.course.id'}.'.num'});
1.122     ng        451: 
1.257     albertel  452: 	    my $loginuser = $env{'user.name'}.':'.$env{'user.domain'};
                    453: 	    $env{'form.keywords'} = $keyhash{$symb.'_keywords'} ne '' ? $keyhash{$symb.'_keywords'} : '';
                    454: 	    $env{'form.kwclr'}    = $keyhash{$loginuser.'_kwclr'} ne '' ? $keyhash{$loginuser.'_kwclr'} : 'red';
                    455: 	    $env{'form.kwsize'}   = $keyhash{$loginuser.'_kwsize'} ne '' ? $keyhash{$loginuser.'_kwsize'} : '0';
                    456: 	    $env{'form.kwstyle'}  = $keyhash{$loginuser.'_kwstyle'} ne '' ? $keyhash{$loginuser.'_kwstyle'} : '';
                    457: 	    $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        458: 	}
1.166     albertel  459: 	$answer =~ s-\n-<br />-g;
                    460: 	return '<br /><br /><blockquote><tt>'.&keywords_highlight($answer).'</tt></blockquote>';
1.268     albertel  461:     } elsif ( $response eq 'organic') {
                    462: 	my $result='Smile representation: "<tt>'.$answer.'</tt>"';
                    463: 	my $jme=$record->{$version."resource.$partid.$respid.molecule"};
                    464: 	$result.=&Apache::chemresponse::jme_img($jme,$answer,400);
                    465: 	return $result;
1.335     albertel  466:     } elsif ( $response eq 'Task') {
                    467: 	if ( $answer eq 'SUBMITTED') {
                    468: 	    my $files = $record->{$version."resource.$respid.$partid.bridgetask.portfiles"};
1.336     albertel  469: 	    my $result = &Apache::bridgetask::file_list($files,$uname,$udom);
1.335     albertel  470: 	    return $result;
                    471: 	} elsif ( grep(/^\Q$version\E.*?\.instance$/, keys(%{$record})) ) {
                    472: 	    my @matches = grep(/^\Q$version\E.*?\.instance$/,
                    473: 			       keys(%{$record}));
                    474: 	    return join('<br />',($version,@matches));
                    475: 			       
                    476: 			       
                    477: 	} else {
                    478: 	    my $result =
                    479: 		'<p>'
                    480: 		.&mt('Overall result: [_1]',
                    481: 		     $record->{$version."resource.$respid.$partid.status"})
                    482: 		.'</p>';
                    483: 	    
                    484: 	    $result .= '<ul>';
                    485: 	    my @grade = grep(/^\Q${version}resource.$respid.$partid.\E[^.]*[.]status$/,
                    486: 			     keys(%{$record}));
                    487: 	    foreach my $grade (sort(@grade)) {
                    488: 		my ($dim) = ($grade =~/[.]([^.]+)[.]status$/);
                    489: 		$result.= '<li>'.&mt("Dimension: [_1], status [_2] ",
                    490: 				     $dim, $record->{$grade}).
                    491: 			  '</li>';
                    492: 	    }
                    493: 	    $result.='</ul>';
                    494: 	    return $result;
                    495: 	}
1.440     albertel  496:     } elsif ( $response =~ m/(?:numerical|formula)/) {
                    497: 	$answer = 
                    498: 	    &Apache::loncommon::format_previous_attempt_value('submission',
                    499: 							      $answer);
1.122     ng        500:     }
1.118     ng        501:     return $answer;
                    502: }
                    503: 
                    504: #-- A couple of common js functions
                    505: sub commonJSfunctions {
                    506:     my $request = shift;
                    507:     $request->print(<<COMMONJSFUNCTIONS);
                    508: <script type="text/javascript" language="javascript">
                    509:     function radioSelection(radioButton) {
                    510: 	var selection=null;
                    511: 	if (radioButton.length > 1) {
                    512: 	    for (var i=0; i<radioButton.length; i++) {
                    513: 		if (radioButton[i].checked) {
                    514: 		    return radioButton[i].value;
                    515: 		}
                    516: 	    }
                    517: 	} else {
                    518: 	    if (radioButton.checked) return radioButton.value;
                    519: 	}
                    520: 	return selection;
                    521:     }
                    522: 
                    523:     function pullDownSelection(selectOne) {
                    524: 	var selection="";
                    525: 	if (selectOne.length > 1) {
                    526: 	    for (var i=0; i<selectOne.length; i++) {
                    527: 		if (selectOne[i].selected) {
                    528: 		    return selectOne[i].value;
                    529: 		}
                    530: 	    }
                    531: 	} else {
1.138     albertel  532:             // only one value it must be the selected one
                    533: 	    return selectOne.value;
1.118     ng        534: 	}
                    535:     }
                    536: </script>
                    537: COMMONJSFUNCTIONS
                    538: }
                    539: 
1.44      ng        540: #--- Dumps the class list with usernames,list of sections,
                    541: #--- section, ids and fullnames for each user.
                    542: sub getclasslist {
1.449     banghart  543:     my ($getsec,$filterlist,$getgroup) = @_;
1.291     albertel  544:     my @getsec;
1.450     banghart  545:     my @getgroup;
1.442     banghart  546:     my $stu_status = join(':',&Apache::loncommon::get_env_multiple('form.Status'));
1.291     albertel  547:     if (!ref($getsec)) {
                    548: 	if ($getsec ne '' && $getsec ne 'all') {
                    549: 	    @getsec=($getsec);
                    550: 	}
                    551:     } else {
                    552: 	@getsec=@{$getsec};
                    553:     }
                    554:     if (grep(/^all$/,@getsec)) { undef(@getsec); }
1.450     banghart  555:     if (!ref($getgroup)) {
                    556: 	if ($getgroup ne '' && $getgroup ne 'all') {
                    557: 	    @getgroup=($getgroup);
                    558: 	}
                    559:     } else {
                    560: 	@getgroup=@{$getgroup};
                    561:     }
                    562:     if (grep(/^all$/,@getgroup)) { undef(@getgroup); }
1.291     albertel  563: 
1.449     banghart  564:     my ($classlist,$keylist)=&Apache::loncoursedata::get_classlist();
1.49      albertel  565:     # Bail out if we were unable to get the classlist
1.56      matthew   566:     return if (! defined($classlist));
1.449     banghart  567:     &Apache::loncoursedata::get_group_memberships($classlist,$keylist);
1.56      matthew   568:     #
                    569:     my %sections;
                    570:     my %fullnames;
1.205     matthew   571:     foreach my $student (keys(%$classlist)) {
                    572:         my $end      = 
                    573:             $classlist->{$student}->[&Apache::loncoursedata::CL_END()];
                    574:         my $start    = 
                    575:             $classlist->{$student}->[&Apache::loncoursedata::CL_START()];
                    576:         my $id       = 
                    577:             $classlist->{$student}->[&Apache::loncoursedata::CL_ID()];
                    578:         my $section  = 
                    579:             $classlist->{$student}->[&Apache::loncoursedata::CL_SECTION()];
                    580:         my $fullname = 
                    581:             $classlist->{$student}->[&Apache::loncoursedata::CL_FULLNAME()];
                    582:         my $status   = 
                    583:             $classlist->{$student}->[&Apache::loncoursedata::CL_STATUS()];
1.449     banghart  584:         my $group   = 
                    585:             $classlist->{$student}->[&Apache::loncoursedata::CL_GROUP()];
1.76      ng        586: 	# filter students according to status selected
1.442     banghart  587: 	if ($filterlist && (!($stu_status =~ /Any/))) {
                    588: 	    if (!($stu_status =~ $status)) {
1.450     banghart  589: 		delete($classlist->{$student});
1.76      ng        590: 		next;
                    591: 	    }
                    592: 	}
1.450     banghart  593: 	# filter students according to groups selected
1.453     banghart  594: 	my @stu_groups = split(/,/,$group);
1.450     banghart  595: 	if (@getgroup) {
                    596: 	    my $exclude = 1;
1.454     banghart  597: 	    foreach my $grp (@getgroup) {
                    598: 	        foreach my $stu_group (@stu_groups) {
1.453     banghart  599: 	            if ($stu_group eq $grp) {
                    600: 	                $exclude = 0;
                    601:     	            } 
1.450     banghart  602: 	        }
1.453     banghart  603:     	        if (($grp eq 'none') && !$group) {
                    604:         	        $exclude = 0;
                    605:         	}
1.450     banghart  606: 	    }
                    607: 	    if ($exclude) {
                    608: 	        delete($classlist->{$student});
                    609: 	    }
                    610: 	}
1.205     matthew   611: 	$section = ($section ne '' ? $section : 'none');
1.106     albertel  612: 	if (&canview($section)) {
1.291     albertel  613: 	    if (!@getsec || grep(/^\Q$section\E$/,@getsec)) {
1.103     albertel  614: 		$sections{$section}++;
1.450     banghart  615: 		if ($classlist->{$student}) {
                    616: 		    $fullnames{$student}=$fullname;
                    617: 		}
1.103     albertel  618: 	    } else {
1.205     matthew   619: 		delete($classlist->{$student});
1.103     albertel  620: 	    }
                    621: 	} else {
1.205     matthew   622: 	    delete($classlist->{$student});
1.103     albertel  623: 	}
1.44      ng        624:     }
                    625:     my %seen = ();
1.56      matthew   626:     my @sections = sort(keys(%sections));
                    627:     return ($classlist,\@sections,\%fullnames);
1.44      ng        628: }
                    629: 
1.103     albertel  630: sub canmodify {
                    631:     my ($sec)=@_;
                    632:     if ($perm{'mgr'}) {
                    633: 	if (!defined($perm{'mgr_section'})) {
                    634: 	    # can modify whole class
                    635: 	    return 1;
                    636: 	} else {
                    637: 	    if ($sec eq $perm{'mgr_section'}) {
                    638: 		#can modify the requested section
                    639: 		return 1;
                    640: 	    } else {
                    641: 		# can't modify the request section
                    642: 		return 0;
                    643: 	    }
                    644: 	}
                    645:     }
                    646:     #can't modify
                    647:     return 0;
                    648: }
                    649: 
                    650: sub canview {
                    651:     my ($sec)=@_;
                    652:     if ($perm{'vgr'}) {
                    653: 	if (!defined($perm{'vgr_section'})) {
                    654: 	    # can modify whole class
                    655: 	    return 1;
                    656: 	} else {
                    657: 	    if ($sec eq $perm{'vgr_section'}) {
                    658: 		#can modify the requested section
                    659: 		return 1;
                    660: 	    } else {
                    661: 		# can't modify the request section
                    662: 		return 0;
                    663: 	    }
                    664: 	}
                    665:     }
                    666:     #can't modify
                    667:     return 0;
                    668: }
                    669: 
1.44      ng        670: #--- Retrieve the grade status of a student for all the parts
                    671: sub student_gradeStatus {
1.324     albertel  672:     my ($symb,$udom,$uname,$partlist) = @_;
1.257     albertel  673:     my %record     = &Apache::lonnet::restore($symb,$env{'request.course.id'},$udom,$uname);
1.44      ng        674:     my %partstatus = ();
                    675:     foreach (@$partlist) {
1.128     ng        676: 	my ($status,undef)   = split(/_/,$record{"resource.$_.solved"},2);
1.44      ng        677: 	$status              = 'nothing' if ($status eq '');
                    678: 	$partstatus{$_}      = $status;
                    679: 	my $subkey           = "resource.$_.submitted_by";
                    680: 	$partstatus{$subkey} = $record{$subkey} if ($record{$subkey} ne '');
                    681:     }
                    682:     return %partstatus;
                    683: }
                    684: 
1.45      ng        685: # hidden form and javascript that calls the form
                    686: # Use by verifyscript and viewgrades
                    687: # Shows a student's view of problem and submission
                    688: sub jscriptNform {
1.324     albertel  689:     my ($symb) = @_;
1.442     banghart  690:     my $stu_status = join(':',&Apache::loncommon::get_env_multiple('form.Status'));
1.45      ng        691:     my $jscript='<script type="text/javascript" language="javascript">'."\n".
                    692: 	'    function viewOneStudent(user,domain) {'."\n".
                    693: 	'	document.onestudent.student.value = user;'."\n".
                    694: 	'	document.onestudent.userdom.value = domain;'."\n".
                    695: 	'	document.onestudent.submit();'."\n".
                    696: 	'    }'."\n".
                    697: 	'</script>'."\n";
                    698:     $jscript.= '<form action="/adm/grades" method="post" name="onestudent">'."\n".
1.418     albertel  699: 	'<input type="hidden" name="symb"    value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
1.257     albertel  700: 	'<input type="hidden" name="saveState" value="'.$env{'form.saveState'}.'" />'."\n".
                    701: 	'<input type="hidden" name="probTitle" value="'.$env{'form.probTitle'}.'" />'."\n".
1.442     banghart  702: 	'<input type="hidden" name="Status"  value="'.$stu_status.'" />'."\n".
1.45      ng        703: 	'<input type="hidden" name="command" value="submission" />'."\n".
                    704: 	'<input type="hidden" name="student" value="" />'."\n".
                    705: 	'<input type="hidden" name="userdom" value="" />'."\n".
                    706: 	'</form>'."\n";
                    707:     return $jscript;
                    708: }
1.39      ng        709: 
1.447     foxr      710: 
                    711: 
1.315     bowersj2  712: # Given the score (as a number [0-1] and the weight) what is the final
                    713: # point value? This function will round to the nearest tenth, third,
                    714: # or quarter if one of those is within the tolerance of .00001.
1.316     albertel  715: sub compute_points {
1.315     bowersj2  716:     my ($score, $weight) = @_;
                    717:     
                    718:     my $tolerance = .00001;
                    719:     my $points = $score * $weight;
                    720: 
                    721:     # Check for nearness to 1/x.
                    722:     my $check_for_nearness = sub {
                    723:         my ($factor) = @_;
                    724:         my $num = ($points * $factor) + $tolerance;
                    725:         my $floored_num = floor($num);
1.316     albertel  726:         if ($num - $floored_num < 2 * $tolerance * $factor) {
1.315     bowersj2  727:             return $floored_num / $factor;
                    728:         }
                    729:         return $points;
                    730:     };
                    731: 
                    732:     $points = $check_for_nearness->(10);
                    733:     $points = $check_for_nearness->(3);
                    734:     $points = $check_for_nearness->(4);
                    735:     
                    736:     return $points;
                    737: }
                    738: 
1.44      ng        739: #------------------ End of general use routines --------------------
1.87      www       740: 
                    741: #
                    742: # Find most similar essay
                    743: #
                    744: 
                    745: sub most_similar {
1.426     albertel  746:     my ($uname,$udom,$uessay,$old_essays)=@_;
1.87      www       747: 
                    748: # ignore spaces and punctuation
                    749: 
                    750:     $uessay=~s/\W+/ /gs;
                    751: 
1.282     www       752: # ignore empty submissions (occuring when only files are sent)
                    753: 
1.596.2.4  raeburn   754:     unless ($uessay=~/\w+/s) { return ''; }
1.282     www       755: 
1.87      www       756: # these will be returned. Do not care if not at least 50 percent similar
1.88      www       757:     my $limit=0.6;
1.87      www       758:     my $sname='';
                    759:     my $sdom='';
                    760:     my $scrsid='';
                    761:     my $sessay='';
                    762: # go through all essays ...
1.426     albertel  763:     foreach my $tkey (keys(%$old_essays)) {
                    764: 	my ($tname,$tdom,$tcrsid)=map {&unescape($_)} (split(/\./,$tkey));
1.87      www       765: # ... except the same student
1.426     albertel  766:         next if (($tname eq $uname) && ($tdom eq $udom));
                    767: 	my $tessay=$old_essays->{$tkey};
                    768: 	$tessay=~s/\W+/ /gs;
1.87      www       769: # String similarity gives up if not even limit
1.426     albertel  770: 	my $tsimilar=&String::Similarity::similarity($uessay,$tessay,$limit);
1.87      www       771: # Found one
1.426     albertel  772: 	if ($tsimilar>$limit) {
                    773: 	    $limit=$tsimilar;
                    774: 	    $sname=$tname;
                    775: 	    $sdom=$tdom;
                    776: 	    $scrsid=$tcrsid;
                    777: 	    $sessay=$old_essays->{$tkey};
                    778: 	}
1.87      www       779:     }
1.88      www       780:     if ($limit>0.6) {
1.87      www       781:        return ($sname,$sdom,$scrsid,$sessay,$limit);
                    782:     } else {
                    783:        return ('','','','',0);
                    784:     }
                    785: }
                    786: 
1.44      ng        787: #-------------------------------------------------------------------
                    788: 
                    789: #------------------------------------ Receipt Verification Routines
1.45      ng        790: #
1.44      ng        791: #--- Check whether a receipt number is valid.---
                    792: sub verifyreceipt {
                    793:     my $request  = shift;
                    794: 
1.257     albertel  795:     my $courseid = $env{'request.course.id'};
1.184     www       796:     my $receipt  = &Apache::lonnet::recprefix($courseid).'-'.
1.257     albertel  797: 	$env{'form.receipt'};
1.44      ng        798:     $receipt     =~ s/[^\-\d]//g;
1.378     albertel  799:     my ($symb)   = &get_symb($request);
1.44      ng        800: 
1.487     albertel  801:     my $title.=
                    802: 	'<h3><span class="LC_info">'.
1.584     bisitz    803: 	&mt('Verifying Receipt No. [_1]',$receipt).
1.487     albertel  804: 	'</span></h3>'."\n".
                    805: 	'<h4>'.&mt('<b>Resource: </b>[_1]',$env{'form.probTitle'}).
                    806: 	'</h4>'."\n";
1.44      ng        807: 
                    808:     my ($string,$contents,$matches) = ('','',0);
1.56      matthew   809:     my (undef,undef,$fullname) = &getclasslist('all','0');
1.177     albertel  810:     
                    811:     my $receiptparts=0;
1.390     albertel  812:     if ($env{"course.$courseid.receiptalg"} eq 'receipt2' ||
                    813: 	$env{"course.$courseid.receiptalg"} eq 'receipt3') { $receiptparts=1; }
1.177     albertel  814:     my $parts=['0'];
1.582     raeburn   815:     if ($receiptparts) {
                    816:         my $res_error; 
                    817:         ($parts)=&response_type($symb,\$res_error);
                    818:         if ($res_error) {
                    819:             return &navmap_errormsg();
                    820:         } 
                    821:     }
1.486     albertel  822:     
                    823:     my $header = 
                    824: 	&Apache::loncommon::start_data_table().
                    825: 	&Apache::loncommon::start_data_table_header_row().
1.487     albertel  826: 	'<th>&nbsp;'.&mt('Fullname').'&nbsp;</th>'."\n".
                    827: 	'<th>&nbsp;'.&mt('Username').'&nbsp;</th>'."\n".
                    828: 	'<th>&nbsp;'.&mt('Domain').'&nbsp;</th>';
1.486     albertel  829:     if ($receiptparts) {
1.487     albertel  830: 	$header.='<th>&nbsp;'.&mt('Problem Part').'&nbsp;</th>';
1.486     albertel  831:     }
                    832:     $header.=
                    833: 	&Apache::loncommon::end_data_table_header_row();
                    834: 
1.294     albertel  835:     foreach (sort 
                    836: 	     {
                    837: 		 if (lc($$fullname{$a}) ne lc($$fullname{$b})) {
                    838: 		     return (lc($$fullname{$a}) cmp lc($$fullname{$b}));
                    839: 		 }
                    840: 		 return $a cmp $b;
                    841: 	     } (keys(%$fullname))) {
1.44      ng        842: 	my ($uname,$udom)=split(/\:/);
1.177     albertel  843: 	foreach my $part (@$parts) {
                    844: 	    if ($receipt eq &Apache::lonnet::ireceipt($uname,$udom,$courseid,$symb,$part)) {
1.486     albertel  845: 		$contents.=
                    846: 		    &Apache::loncommon::start_data_table_row().
                    847: 		    '<td>&nbsp;'."\n".
1.177     albertel  848: 		    '<a href="javascript:viewOneStudent(\''.$uname.'\',\''.$udom.
1.417     albertel  849: 		    '\');" target="_self">'.$$fullname{$_}.'</a>&nbsp;</td>'."\n".
1.177     albertel  850: 		    '<td>&nbsp;'.$uname.'&nbsp;</td>'.
                    851: 		    '<td>&nbsp;'.$udom.'&nbsp;</td>';
                    852: 		if ($receiptparts) {
                    853: 		    $contents.='<td>&nbsp;'.$part.'&nbsp;</td>';
                    854: 		}
1.486     albertel  855: 		$contents.= 
                    856: 		    &Apache::loncommon::end_data_table_row()."\n";
1.177     albertel  857: 		
                    858: 		$matches++;
                    859: 	    }
1.44      ng        860: 	}
                    861:     }
                    862:     if ($matches == 0) {
1.584     bisitz    863:         $string = $title
                    864:                  .'<p class="LC_warning">'
                    865:                  .&mt('No match found for the above receipt number.')
                    866:                  .'</p>';
1.44      ng        867:     } else {
1.324     albertel  868: 	$string = &jscriptNform($symb).$title.
1.487     albertel  869: 	    '<p>'.
1.584     bisitz    870: 	    &mt('The above receipt number matches the following [quant,_1,student].',$matches).
1.487     albertel  871: 	    '</p>'.
1.486     albertel  872: 	    $header.
                    873: 	    $contents.
                    874: 	    &Apache::loncommon::end_data_table()."\n";
1.44      ng        875:     }
1.324     albertel  876:     return $string.&show_grading_menu_form($symb);
1.44      ng        877: }
                    878: 
                    879: #--- This is called by a number of programs.
                    880: #--- Called from the Grading Menu - View/Grade an individual student
                    881: #--- Also called directly when one clicks on the subm button 
                    882: #    on the problem page.
1.30      ng        883: sub listStudents {
1.41      ng        884:     my ($request) = shift;
1.49      albertel  885: 
1.324     albertel  886:     my ($symb) = &get_symb($request);
1.257     albertel  887:     my $cdom      = $env{"course.$env{'request.course.id'}.domain"};
                    888:     my $cnum      = $env{"course.$env{'request.course.id'}.num"};
                    889:     my $getsec    = $env{'form.section'} eq '' ? 'all' : $env{'form.section'};
1.449     banghart  890:     my $getgroup  = $env{'form.group'} eq '' ? 'all' : $env{'form.group'};
1.257     albertel  891:     my $submitonly= $env{'form.submitonly'} eq '' ? 'all' : $env{'form.submitonly'};
1.548     bisitz    892:     my $viewgrade = $env{'form.showgrading'} eq 'yes' ? 'View/Grade/Regrade' : 'View';
1.257     albertel  893:     $env{'form.probTitle'} = $env{'form.probTitle'} eq '' ? 
                    894: 	&Apache::lonnet::gettitle($symb) : $env{'form.probTitle'};
1.49      albertel  895: 
1.548     bisitz    896:     my $result='<h3><span class="LC_info">&nbsp;'
                    897: 	.&mt("$viewgrade Submissions for a Student or a Group of Students")
1.485     albertel  898: 	.'</span></h3>';
1.118     ng        899: 
1.324     albertel  900:     my ($table,undef,$hdgrade,$partlist,$handgrade) = &showResourceInfo($symb,$env{'form.probTitle'},($env{'form.showgrading'} eq 'yes'));
1.49      albertel  901: 
1.559     raeburn   902:     my %lt = &Apache::lonlocal::texthash (
                    903: 		'multiple' => 'Please select a student or group of students before clicking on the Next button.',
                    904: 		'single'   => 'Please select the student before clicking on the Next button.',
                    905: 	     );
1.45      ng        906:     $request->print(<<LISTJAVASCRIPT);
                    907: <script type="text/javascript" language="javascript">
1.110     ng        908:     function checkSelect(checkBox) {
                    909: 	var ctr=0;
                    910: 	var sense="";
                    911: 	if (checkBox.length > 1) {
                    912: 	    for (var i=0; i<checkBox.length; i++) {
                    913: 		if (checkBox[i].checked) {
                    914: 		    ctr++;
                    915: 		}
                    916: 	    }
1.485     albertel  917: 	    sense = '$lt{'multiple'}';
1.110     ng        918: 	} else {
                    919: 	    if (checkBox.checked) {
                    920: 		ctr = 1;
                    921: 	    }
1.485     albertel  922: 	    sense = '$lt{'single'}';
1.110     ng        923: 	}
                    924: 	if (ctr == 0) {
1.485     albertel  925: 	    alert(sense);
1.110     ng        926: 	    return false;
                    927: 	}
                    928: 	document.gradesub.submit();
                    929:     }
                    930: 
                    931:     function reLoadList(formname) {
1.112     ng        932: 	if (formname.saveStatusOld.value == pullDownSelection(formname.Status)) {return;}
1.110     ng        933: 	formname.command.value = 'submission';
                    934: 	formname.submit();
                    935:     }
1.45      ng        936: </script>
                    937: LISTJAVASCRIPT
                    938: 
1.118     ng        939:     &commonJSfunctions($request);
1.41      ng        940:     $request->print($result);
1.39      ng        941: 
1.401     albertel  942:     my $checkhdgrade = ($env{'form.handgrade'} eq 'yes' && scalar(@$partlist) > 1 ) ? 'checked="checked"' : '';
                    943:     my $checklastsub = $checkhdgrade eq '' ? 'checked="checked"' : '';
1.154     albertel  944:     my $gradeTable='<form action="/adm/grades" method="post" name="gradesub">'.
1.485     albertel  945: 	"\n".$table;
                    946: 	
1.561     bisitz    947:     $gradeTable .= &Apache::lonhtmlcommon::start_pick_box();
                    948:     $gradeTable .= &Apache::lonhtmlcommon::row_title(&mt('View Problem Text'))
                    949:                   .'<label><input type="radio" name="vProb" value="no" checked="checked" /> '.&mt('no').' </label>'."\n"
                    950:                   .'<label><input type="radio" name="vProb" value="yes" /> '.&mt('one student').' </label>'."\n"
                    951:                   .'<label><input type="radio" name="vProb" value="all" /> '.&mt('all students').' </label><br />'."\n"
                    952:                   .&Apache::lonhtmlcommon::row_closure();
                    953:     $gradeTable .= &Apache::lonhtmlcommon::row_title(&mt('View Answer'))
                    954:                   .'<label><input type="radio" name="vAns" value="no"  /> '.&mt('no').' </label>'."\n"
                    955:                   .'<label><input type="radio" name="vAns" value="yes" /> '.&mt('one student').' </label>'."\n"
                    956:                   .'<label><input type="radio" name="vAns" value="all" checked="checked" /> '.&mt('all students').' </label><br />'."\n"
                    957:                   .&Apache::lonhtmlcommon::row_closure();
1.485     albertel  958: 
                    959:     my $submission_options;
1.257     albertel  960:     if ($env{'form.handgrade'} eq 'yes' && scalar(@$partlist) > 1) {
1.485     albertel  961: 	$submission_options.=
                    962: 	    '<label><input type="radio" name="lastSub" value="hdgrade" '.$checkhdgrade.' /> '.&mt('essay part only').' </label>'."\n";
1.49      albertel  963:     }
1.442     banghart  964:     my $stu_status = join(':',&Apache::loncommon::get_env_multiple('form.Status'));
                    965:     my $saveStatus = $stu_status eq '' ? 'Active' : $stu_status;
1.257     albertel  966:     $env{'form.Status'} = $saveStatus;
1.485     albertel  967:     $submission_options.=
1.592     bisitz    968:         '<span class="LC_nobreak">'.
                    969:         '<label><input type="radio" name="lastSub" value="lastonly" '.$checklastsub.' /> '.
                    970:         &mt('last submission only').' </label></span>'."\n".
                    971:         '<span class="LC_nobreak">'.
                    972:         '<label><input type="radio" name="lastSub" value="last" /> '.
                    973:         &mt('last submission &amp; parts info').' </label></span>'."\n".
                    974:         '<span class="LC_nobreak">'.
                    975:         '<label><input type="radio" name="lastSub" value="datesub" /> '.
                    976:         &mt('by dates and submissions').'</label></span>'."\n".
                    977:         '<span class="LC_nobreak">'.
                    978:         '<label><input type="radio" name="lastSub" value="all" /> '.
                    979:         &mt('all details').'</label></span>';
1.561     bisitz    980:     $gradeTable .= &Apache::lonhtmlcommon::row_title(&mt('Submissions'))
                    981:                   .$submission_options
                    982:                   .&Apache::lonhtmlcommon::row_closure();
                    983: 
                    984:     $gradeTable .= &Apache::lonhtmlcommon::row_title(&mt('Grading Increments'))
                    985:                   .'<select name="increment">'
                    986:                   .'<option value="1">'.&mt('Whole Points').'</option>'
                    987:                   .'<option value=".5">'.&mt('Half Points').'</option>'
                    988:                   .'<option value=".25">'.&mt('Quarter Points').'</option>'
                    989:                   .'<option value=".1">'.&mt('Tenths of a Point').'</option>'
                    990:                   .'</select>'
                    991:                   .&Apache::lonhtmlcommon::row_closure();
1.485     albertel  992: 
                    993:     $gradeTable .= 
1.432     banghart  994:         &build_section_inputs().
1.45      ng        995: 	'<input type="hidden" name="submitonly"  value="'.$submitonly.'" />'."\n".
1.257     albertel  996: 	'<input type="hidden" name="handgrade"   value="'.$env{'form.handgrade'}.'" /><br />'."\n".
                    997: 	'<input type="hidden" name="showgrading" value="'.$env{'form.showgrading'}.'" /><br />'."\n".
                    998: 	'<input type="hidden" name="saveState"   value="'.$env{'form.saveState'}.'" />'."\n".
                    999: 	'<input type="hidden" name="probTitle"   value="'.$env{'form.probTitle'}.'" />'."\n".
1.418     albertel 1000: 	'<input type="hidden" name="symb" value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
1.110     ng       1001: 	'<input type="hidden" name="saveStatusOld" value="'.$saveStatus.'" />'."\n";
                   1002: 
1.257     albertel 1003:     if (exists($env{'form.gradingMenu'}) && exists($env{'form.Status'})) {
1.561     bisitz   1004: 	$gradeTable .= '<input type="hidden" name="Status" value="'.$stu_status.'" />'."\n";
1.124     ng       1005:     } else {
1.561     bisitz   1006:         $gradeTable .= &Apache::lonhtmlcommon::row_title(&mt('Student Status'))
                   1007:                       .&Apache::lonhtmlcommon::StatusOptions(
                   1008:                            $saveStatus,undef,1,'javascript:reLoadList(this.form);')
                   1009:                       .&Apache::lonhtmlcommon::row_closure();
1.124     ng       1010:     }
1.112     ng       1011: 
1.561     bisitz   1012:     $gradeTable .= &Apache::lonhtmlcommon::row_title(&mt('Check For Plagiarism'))
                   1013:                   .'<input type="checkbox" name="checkPlag" checked="checked" />'
                   1014:                   .&Apache::lonhtmlcommon::row_closure(1)
                   1015:                   .&Apache::lonhtmlcommon::end_pick_box();
                   1016: 
                   1017:     $gradeTable .= '<p>'
                   1018:                   .&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"
                   1019:                   .'<input type="hidden" name="command" value="processGroup" />'
                   1020:                   .'</p>';
1.249     albertel 1021: 
                   1022: # checkall buttons
                   1023:     $gradeTable.=&check_script('gradesub', 'stuinfo');
1.110     ng       1024:     $gradeTable.='<input type="button" '."\n".
1.589     bisitz   1025:         'onclick="javascript:checkSelect(this.form.stuinfo);" '."\n".
                   1026:         'value="'.&mt('Next').' &rarr;" /> <br />'."\n";
1.249     albertel 1027:     $gradeTable.=&check_buttons();
1.450     banghart 1028:     my ($classlist, undef, $fullname) = &getclasslist($getsec,'1',$getgroup);
1.474     albertel 1029:     $gradeTable.= &Apache::loncommon::start_data_table().
                   1030: 	&Apache::loncommon::start_data_table_header_row();
1.110     ng       1031:     my $loop = 0;
                   1032:     while ($loop < 2) {
1.485     albertel 1033: 	$gradeTable.='<th>'.&mt('No.').'</th><th>'.&mt('Select').'</th>'.
                   1034: 	    '<th>'.&nameUserString('header').'&nbsp;'.&mt('Section/Group').'</th>';
1.301     albertel 1035: 	if ($env{'form.showgrading'} eq 'yes' 
                   1036: 	    && $submitonly ne 'queued'
                   1037: 	    && $submitonly ne 'all') {
1.485     albertel 1038: 	    foreach my $part (sort(@$partlist)) {
                   1039: 		my $display_part=
                   1040: 		    &get_display_part((split(/_/,$part))[0],$symb);
                   1041: 		$gradeTable.=
                   1042: 		    '<th>'.&mt('Part: [_1] Status',$display_part).'</th>';
1.110     ng       1043: 	    }
1.301     albertel 1044: 	} elsif ($submitonly eq 'queued') {
1.474     albertel 1045: 	    $gradeTable.='<th>'.&mt('Queue Status').'&nbsp;</th>';
1.110     ng       1046: 	}
                   1047: 	$loop++;
1.126     ng       1048: #	$gradeTable.='<td></td>' if ($loop%2 ==1);
1.41      ng       1049:     }
1.474     albertel 1050:     $gradeTable.=&Apache::loncommon::end_data_table_header_row()."\n";
1.41      ng       1051: 
1.45      ng       1052:     my $ctr = 0;
1.294     albertel 1053:     foreach my $student (sort 
                   1054: 			 {
                   1055: 			     if (lc($$fullname{$a}) ne lc($$fullname{$b})) {
                   1056: 				 return (lc($$fullname{$a}) cmp lc($$fullname{$b}));
                   1057: 			     }
                   1058: 			     return $a cmp $b;
                   1059: 			 }
                   1060: 			 (keys(%$fullname))) {
1.41      ng       1061: 	my ($uname,$udom) = split(/:/,$student);
1.301     albertel 1062: 
1.110     ng       1063: 	my %status = ();
1.301     albertel 1064: 
                   1065: 	if ($submitonly eq 'queued') {
                   1066: 	    my %queue_status = 
                   1067: 		&Apache::bridgetask::get_student_status($symb,$cdom,$cnum,
                   1068: 							$udom,$uname);
                   1069: 	    next if (!defined($queue_status{'gradingqueue'}));
                   1070: 	    $status{'gradingqueue'} = $queue_status{'gradingqueue'};
                   1071: 	}
                   1072: 
                   1073: 	if ($env{'form.showgrading'} eq 'yes' 
                   1074: 	    && $submitonly ne 'queued'
                   1075: 	    && $submitonly ne 'all') {
1.324     albertel 1076: 	    (%status) =&student_gradeStatus($symb,$udom,$uname,$partlist);
1.145     albertel 1077: 	    my $submitted = 0;
1.164     albertel 1078: 	    my $graded = 0;
1.248     albertel 1079: 	    my $incorrect = 0;
1.110     ng       1080: 	    foreach (keys(%status)) {
1.145     albertel 1081: 		$submitted = 1 if ($status{$_} ne 'nothing');
1.248     albertel 1082: 		$graded = 1 if ($status{$_} =~ /^ungraded/);
                   1083: 		$incorrect = 1 if ($status{$_} =~ /^incorrect/);
                   1084: 		
1.110     ng       1085: 		my ($foo,$partid,$foo1) = split(/\./,$_);
                   1086: 		if ($status{'resource.'.$partid.'.submitted_by'} ne '') {
1.145     albertel 1087: 		    $submitted = 0;
1.150     albertel 1088: 		    my ($part)=split(/\./,$partid);
1.110     ng       1089: 		    $gradeTable.='<input type="hidden" name="'.
1.150     albertel 1090: 			$student.':'.$part.':submitted_by" value="'.
1.110     ng       1091: 			$status{'resource.'.$partid.'.submitted_by'}.'" />';
                   1092: 		}
1.41      ng       1093: 	    }
1.248     albertel 1094: 	    
1.156     albertel 1095: 	    next if (!$submitted && ($submitonly eq 'yes' ||
                   1096: 				     $submitonly eq 'incorrect' ||
                   1097: 				     $submitonly eq 'graded'));
1.248     albertel 1098: 	    next if (!$graded && ($submitonly eq 'graded'));
                   1099: 	    next if (!$incorrect && $submitonly eq 'incorrect');
1.41      ng       1100: 	}
1.34      ng       1101: 
1.45      ng       1102: 	$ctr++;
1.249     albertel 1103: 	my $section = $classlist->{$student}->[&Apache::loncoursedata::CL_SECTION()];
1.452     banghart 1104:         my $group = $classlist->{$student}->[&Apache::loncoursedata::CL_GROUP()];
1.104     albertel 1105: 	if ( $perm{'vgr'} eq 'F' ) {
1.474     albertel 1106: 	    if ($ctr%2 ==1) {
                   1107: 		$gradeTable.= &Apache::loncommon::start_data_table_row();
                   1108: 	    }
1.126     ng       1109: 	    $gradeTable.='<td align="right">'.$ctr.'&nbsp;</td>'.
1.563     bisitz   1110:                '<td align="center"><label><input type="checkbox" name="stuinfo" value="'.
1.249     albertel 1111:                $student.':'.$$fullname{$student}.':::SECTION'.$section.
                   1112: 	       ')&nbsp;" />&nbsp;&nbsp;</label></td>'."\n".'<td>'.
                   1113: 	       &nameUserString(undef,$$fullname{$student},$uname,$udom).
1.474     albertel 1114: 	       '&nbsp;'.$section.($group ne '' ?'/'.$group:'').'</td>'."\n";
1.110     ng       1115: 
1.257     albertel 1116: 	    if ($env{'form.showgrading'} eq 'yes' && $submitonly ne 'all') {
1.524     raeburn  1117: 		foreach (sort(keys(%status))) {
1.485     albertel 1118: 		    next if ($_ =~ /^resource.*?submitted_by$/);
                   1119: 		    $gradeTable.='<td align="center">&nbsp;'.&mt($status{$_}).'&nbsp;</td>'."\n";
1.110     ng       1120: 		}
1.41      ng       1121: 	    }
1.126     ng       1122: #	    $gradeTable.='<td></td>' if ($ctr%2 ==1);
1.474     albertel 1123: 	    if ($ctr%2 ==0) {
                   1124: 		$gradeTable.=&Apache::loncommon::end_data_table_row()."\n";
                   1125: 	    }
1.41      ng       1126: 	}
                   1127:     }
1.110     ng       1128:     if ($ctr%2 ==1) {
1.126     ng       1129: 	$gradeTable.='<td>&nbsp;</td><td>&nbsp;</td><td>&nbsp;</td>';
1.301     albertel 1130: 	    if ($env{'form.showgrading'} eq 'yes' 
                   1131: 		&& $submitonly ne 'queued'
                   1132: 		&& $submitonly ne 'all') {
1.110     ng       1133: 		foreach (@$partlist) {
                   1134: 		    $gradeTable.='<td>&nbsp;</td>';
                   1135: 		}
1.301     albertel 1136: 	    } elsif ($submitonly eq 'queued') {
                   1137: 		$gradeTable.='<td>&nbsp;</td>';
1.110     ng       1138: 	    }
1.474     albertel 1139: 	$gradeTable.=&Apache::loncommon::end_data_table_row();
1.110     ng       1140:     }
                   1141: 
1.474     albertel 1142:     $gradeTable.=&Apache::loncommon::end_data_table()."\n".
1.589     bisitz   1143:         '<input type="button" '.
                   1144:         'onclick="javascript:checkSelect(this.form.stuinfo);" '.
                   1145:         'value="'.&mt('Next').' &rarr;" /></form>'."\n";
1.45      ng       1146:     if ($ctr == 0) {
1.96      albertel 1147: 	my $num_students=(scalar(keys(%$fullname)));
                   1148: 	if ($num_students eq 0) {
1.485     albertel 1149: 	    $gradeTable='<br />&nbsp;<span class="LC_warning">'.&mt('There are no students currently enrolled.').'</span>';
1.96      albertel 1150: 	} else {
1.171     albertel 1151: 	    my $submissions='submissions';
                   1152: 	    if ($submitonly eq 'incorrect') { $submissions = 'incorrect submissions'; }
                   1153: 	    if ($submitonly eq 'graded'   ) { $submissions = 'ungraded submissions'; }
1.301     albertel 1154: 	    if ($submitonly eq 'queued'   ) { $submissions = 'queued submissions'; }
1.398     albertel 1155: 	    $gradeTable='<br />&nbsp;<span class="LC_warning">'.
1.485     albertel 1156: 		&mt('No '.$submissions.' found for this resource for any students. ([_1] students checked for '.$submissions.')',
                   1157: 		    $num_students).
                   1158: 		'</span><br />';
1.96      albertel 1159: 	}
1.46      ng       1160:     } elsif ($ctr == 1) {
1.474     albertel 1161: 	$gradeTable =~ s/type="checkbox"/type="checkbox" checked="checked"/;
1.45      ng       1162:     }
1.324     albertel 1163:     $gradeTable.=&show_grading_menu_form($symb);
1.45      ng       1164:     $request->print($gradeTable);
1.44      ng       1165:     return '';
1.10      ng       1166: }
                   1167: 
1.44      ng       1168: #---- Called from the listStudents routine
1.249     albertel 1169: 
                   1170: sub check_script {
                   1171:     my ($form, $type)=@_;
                   1172:     my $chkallscript='<script type="text/javascript">
                   1173:     function checkall() {
                   1174:         for (i=0; i<document.forms.'.$form.'.elements.length; i++) {
                   1175:             ele = document.forms.'.$form.'.elements[i];
                   1176:             if (ele.name == "'.$type.'") {
                   1177:             document.forms.'.$form.'.elements[i].checked=true;
                   1178:                                        }
                   1179:         }
                   1180:     }
                   1181: 
                   1182:     function checksec() {
                   1183:         for (i=0; i<document.forms.'.$form.'.elements.length; i++) {
                   1184:             ele = document.forms.'.$form.'.elements[i];
                   1185:            string = document.forms.'.$form.'.chksec.value;
                   1186:            if
                   1187:           (ele.value.indexOf(":::SECTION"+string)>0) {
                   1188:               document.forms.'.$form.'.elements[i].checked=true;
                   1189:             }
                   1190:         }
                   1191:     }
                   1192: 
                   1193: 
                   1194:     function uncheckall() {
                   1195:         for (i=0; i<document.forms.'.$form.'.elements.length; i++) {
                   1196:             ele = document.forms.'.$form.'.elements[i];
                   1197:             if (ele.name == "'.$type.'") {
                   1198:             document.forms.'.$form.'.elements[i].checked=false;
                   1199:                                        }
                   1200:         }
                   1201:     }
                   1202: 
                   1203: </script>'."\n";
                   1204:     return $chkallscript;
                   1205: }
                   1206: 
                   1207: sub check_buttons {
1.485     albertel 1208:     my $buttons.='<input type="button" onclick="checkall()" value="'.&mt('Check All').'" />';
                   1209:     $buttons.='<input type="button" onclick="uncheckall()" value="'.&mt('Uncheck All').'" />&nbsp;';
                   1210:     $buttons.='<input type="button" onclick="checksec()" value="'.&mt('Check Section/Group').'" />';
1.249     albertel 1211:     $buttons.='<input type="text" size="5" name="chksec" />&nbsp;';
                   1212:     return $buttons;
                   1213: }
                   1214: 
1.44      ng       1215: #     Displays the submissions for one student or a group of students
1.34      ng       1216: sub processGroup {
1.41      ng       1217:     my ($request)  = shift;
                   1218:     my $ctr        = 0;
1.155     albertel 1219:     my @stuchecked = &Apache::loncommon::get_env_multiple('form.stuinfo');
1.41      ng       1220:     my $total      = scalar(@stuchecked)-1;
1.45      ng       1221: 
1.396     banghart 1222:     foreach my $student (@stuchecked) {
                   1223: 	my ($uname,$udom,$fullname) = split(/:/,$student);
1.257     albertel 1224: 	$env{'form.student'}        = $uname;
                   1225: 	$env{'form.userdom'}        = $udom;
                   1226: 	$env{'form.fullname'}       = $fullname;
1.41      ng       1227: 	&submission($request,$ctr,$total);
                   1228: 	$ctr++;
                   1229:     }
                   1230:     return '';
1.35      ng       1231: }
1.34      ng       1232: 
1.44      ng       1233: #------------------------------------------------------------------------------------
                   1234: #
                   1235: #-------------------------- Next few routines handles grading by student, essentially
                   1236: #                           handles essay response type problem/part
                   1237: #
                   1238: #--- Javascript to handle the submission page functionality ---
                   1239: sub sub_page_js {
                   1240:     my $request = shift;
1.539     riegler  1241: 	    my $alertmsg = &mt('A number equal or greater than 0 is expected. Entered value = ');
1.44      ng       1242:     $request->print(<<SUBJAVASCRIPT);
                   1243: <script type="text/javascript" language="javascript">
1.71      ng       1244:     function updateRadio(formname,id,weight) {
1.125     ng       1245: 	var gradeBox = formname["GD_BOX"+id];
                   1246: 	var radioButton = formname["RADVAL"+id];
                   1247: 	var oldpts = formname["oldpts"+id].value;
1.72      ng       1248: 	var pts = checkSolved(formname,id) == 'update' ? gradeBox.value : oldpts;
1.71      ng       1249: 	gradeBox.value = pts;
                   1250: 	var resetbox = false;
                   1251: 	if (isNaN(pts) || pts < 0) {
1.539     riegler  1252: 	    alert("$alertmsg"+pts);
1.71      ng       1253: 	    for (var i=0; i<radioButton.length; i++) {
                   1254: 		if (radioButton[i].checked) {
                   1255: 		    gradeBox.value = i;
                   1256: 		    resetbox = true;
                   1257: 		}
                   1258: 	    }
                   1259: 	    if (!resetbox) {
                   1260: 		formtextbox.value = "";
                   1261: 	    }
                   1262: 	    return;
1.44      ng       1263: 	}
1.71      ng       1264: 
                   1265: 	if (pts > weight) {
                   1266: 	    var resp = confirm("You entered a value ("+pts+
                   1267: 			       ") greater than the weight for the part. Accept?");
                   1268: 	    if (resp == false) {
1.125     ng       1269: 		gradeBox.value = oldpts;
1.71      ng       1270: 		return;
                   1271: 	    }
1.44      ng       1272: 	}
1.13      albertel 1273: 
1.71      ng       1274: 	for (var i=0; i<radioButton.length; i++) {
                   1275: 	    radioButton[i].checked=false;
                   1276: 	    if (pts == i && pts != "") {
                   1277: 		radioButton[i].checked=true;
                   1278: 	    }
                   1279: 	}
                   1280: 	updateSelect(formname,id);
1.125     ng       1281: 	formname["stores"+id].value = "0";
1.41      ng       1282:     }
1.5       albertel 1283: 
1.72      ng       1284:     function writeBox(formname,id,pts) {
1.125     ng       1285: 	var gradeBox = formname["GD_BOX"+id];
1.71      ng       1286: 	if (checkSolved(formname,id) == 'update') {
                   1287: 	    gradeBox.value = pts;
                   1288: 	} else {
1.125     ng       1289: 	    var oldpts = formname["oldpts"+id].value;
1.72      ng       1290: 	    gradeBox.value = oldpts;
1.125     ng       1291: 	    var radioButton = formname["RADVAL"+id];
1.71      ng       1292: 	    for (var i=0; i<radioButton.length; i++) {
                   1293: 		radioButton[i].checked=false;
1.72      ng       1294: 		if (i == oldpts) {
1.71      ng       1295: 		    radioButton[i].checked=true;
                   1296: 		}
                   1297: 	    }
1.41      ng       1298: 	}
1.125     ng       1299: 	formname["stores"+id].value = "0";
1.71      ng       1300: 	updateSelect(formname,id);
                   1301: 	return;
1.41      ng       1302:     }
1.44      ng       1303: 
1.71      ng       1304:     function clearRadBox(formname,id) {
                   1305: 	if (checkSolved(formname,id) == 'noupdate') {
                   1306: 	    updateSelect(formname,id);
                   1307: 	    return;
                   1308: 	}
1.125     ng       1309: 	gradeSelect = formname["GD_SEL"+id];
1.71      ng       1310: 	for (var i=0; i<gradeSelect.length; i++) {
                   1311: 	    if (gradeSelect[i].selected) {
                   1312: 		var selectx=i;
                   1313: 	    }
                   1314: 	}
1.125     ng       1315: 	var stores = formname["stores"+id];
1.71      ng       1316: 	if (selectx == stores.value) { return };
1.125     ng       1317: 	var gradeBox = formname["GD_BOX"+id];
1.71      ng       1318: 	gradeBox.value = "";
1.125     ng       1319: 	var radioButton = formname["RADVAL"+id];
1.71      ng       1320: 	for (var i=0; i<radioButton.length; i++) {
                   1321: 	    radioButton[i].checked=false;
                   1322: 	}
                   1323: 	stores.value = selectx;
                   1324:     }
1.5       albertel 1325: 
1.71      ng       1326:     function checkSolved(formname,id) {
1.125     ng       1327: 	if (formname["solved"+id].value == "correct_by_student" && formname.overRideScore.value == 'no') {
1.118     ng       1328: 	    var reply = confirm("This problem has been graded correct by the computer. Do you want to change the score?");
                   1329: 	    if (!reply) {return "noupdate";}
1.120     ng       1330: 	    formname.overRideScore.value = 'yes';
1.41      ng       1331: 	}
1.71      ng       1332: 	return "update";
1.13      albertel 1333:     }
1.71      ng       1334: 
                   1335:     function updateSelect(formname,id) {
1.125     ng       1336: 	formname["GD_SEL"+id][0].selected = true;
1.71      ng       1337: 	return;
1.41      ng       1338:     }
1.33      ng       1339: 
1.121     ng       1340: //=========== Check that a point is assigned for all the parts  ============
1.71      ng       1341:     function checksubmit(formname,val,total,parttot) {
1.121     ng       1342: 	formname.gradeOpt.value = val;
1.71      ng       1343: 	if (val == "Save & Next") {
                   1344: 	    for (i=0;i<=total;i++) {
                   1345: 		for (j=0;j<parttot;j++) {
1.125     ng       1346: 		    var partid = formname["partid"+i+"_"+j].value;
1.127     ng       1347: 		    if (formname["GD_SEL"+i+"_"+partid][0].selected) {
1.125     ng       1348: 			var points = formname["GD_BOX"+i+"_"+partid].value;
1.71      ng       1349: 			if (points == "") {
1.125     ng       1350: 			    var name = formname["name"+i].value;
1.129     ng       1351: 			    var studentID = (name != '' ? name : formname["unamedom"+i].value);
                   1352: 			    var resp = confirm("You did not assign a score for "+studentID+
                   1353: 					       ", part "+partid+". Continue?");
1.71      ng       1354: 			    if (resp == false) {
1.125     ng       1355: 				formname["GD_BOX"+i+"_"+partid].focus();
1.71      ng       1356: 				return false;
                   1357: 			    }
                   1358: 			}
                   1359: 		    }
                   1360: 		    
                   1361: 		}
                   1362: 	    }
                   1363: 	    
                   1364: 	}
1.121     ng       1365: 	if (val == "Grade Student") {
                   1366: 	    formname.showgrading.value = "yes";
                   1367: 	    if (formname.Status.value == "") {
                   1368: 		formname.Status.value = "Active";
                   1369: 	    }
                   1370: 	    formname.studentNo.value = total;
                   1371: 	}
1.120     ng       1372: 	formname.submit();
                   1373:     }
                   1374: 
1.71      ng       1375: //======= Check that a score is assigned for all the problems (page/sequence grading only) =========
                   1376:     function checkSubmitPage(formname,total) {
                   1377: 	noscore = new Array(100);
                   1378: 	var ptr = 0;
                   1379: 	for (i=1;i<total;i++) {
1.125     ng       1380: 	    var partid = formname["q_"+i].value;
1.127     ng       1381: 	    if (formname["GD_SEL"+i+"_"+partid][0].selected) {
1.125     ng       1382: 		var points = formname["GD_BOX"+i+"_"+partid].value;
                   1383: 		var status = formname["solved"+i+"_"+partid].value;
1.71      ng       1384: 		if (points == "" && status != "correct_by_student") {
                   1385: 		    noscore[ptr] = i;
                   1386: 		    ptr++;
                   1387: 		}
                   1388: 	    }
                   1389: 	}
                   1390: 	if (ptr != 0) {
                   1391: 	    var sense = ptr == 1 ? ": " : "s: ";
                   1392: 	    var prolist = "";
                   1393: 	    if (ptr == 1) {
                   1394: 		prolist = noscore[0];
                   1395: 	    } else {
                   1396: 		var i = 0;
                   1397: 		while (i < ptr-1) {
                   1398: 		    prolist += noscore[i]+", ";
                   1399: 		    i++;
                   1400: 		}
                   1401: 		prolist += "and "+noscore[i];
                   1402: 	    }
                   1403: 	    var resp = confirm("You did not assign any score for the following problem"+sense+prolist+". Continue?");
                   1404: 	    if (resp == false) {
                   1405: 		return false;
                   1406: 	    }
                   1407: 	}
1.45      ng       1408: 
1.71      ng       1409: 	formname.submit();
                   1410:     }
                   1411: </script>
                   1412: SUBJAVASCRIPT
                   1413: }
1.45      ng       1414: 
1.71      ng       1415: #--- javascript for essay type problem --
                   1416: sub sub_page_kw_js {
                   1417:     my $request = shift;
1.80      ng       1418:     my $iconpath = $request->dir_config('lonIconsURL');
1.118     ng       1419:     &commonJSfunctions($request);
1.350     albertel 1420: 
1.351     albertel 1421:     my $inner_js_msg_central=<<INNERJS;
1.350     albertel 1422:     <script text="text/javascript">
                   1423:     function checkInput() {
                   1424:       opener.document.SCORE.msgsub.value = opener.checkEntities(document.msgcenter.msgsub.value);
                   1425:       var nmsg   = opener.document.SCORE.savemsgN.value;
                   1426:       var usrctr = document.msgcenter.usrctr.value;
                   1427:       var newval = opener.document.SCORE["newmsg"+usrctr];
                   1428:       newval.value = opener.checkEntities(document.msgcenter.newmsg.value);
                   1429: 
                   1430:       var msgchk = "";
                   1431:       if (document.msgcenter.subchk.checked) {
                   1432:          msgchk = "msgsub,";
                   1433:       }
                   1434:       var includemsg = 0;
                   1435:       for (var i=1; i<=nmsg; i++) {
                   1436:           var opnmsg = opener.document.SCORE["savemsg"+i];
                   1437:           var frmmsg = document.msgcenter["msg"+i];
                   1438:           opnmsg.value = opener.checkEntities(frmmsg.value);
                   1439:           var showflg = opener.document.SCORE["shownOnce"+i];
                   1440:           showflg.value = "1";
                   1441:           var chkbox = document.msgcenter["msgn"+i];
                   1442:           if (chkbox.checked) {
                   1443:              msgchk += "savemsg"+i+",";
                   1444:              includemsg = 1;
                   1445:           }
                   1446:       }
                   1447:       if (document.msgcenter.newmsgchk.checked) {
                   1448:          msgchk += "newmsg"+usrctr;
                   1449:          includemsg = 1;
                   1450:       }
                   1451:       imgformname = opener.document.SCORE["mailicon"+usrctr];
                   1452:       imgformname.src = "$iconpath/"+((includemsg) ? "mailto.gif" : "mailbkgrd.gif");
                   1453:       var includemsg = opener.document.SCORE["includemsg"+usrctr];
                   1454:       includemsg.value = msgchk;
                   1455: 
                   1456:       self.close()
                   1457: 
                   1458:     }
                   1459:     </script>
                   1460: INNERJS
                   1461: 
1.351     albertel 1462:     my $inner_js_highlight_central=<<INNERJS;
                   1463:  <script type="text/javascript">
                   1464:     function updateChoice(flag) {
                   1465:       opener.document.SCORE.kwclr.value = opener.radioSelection(document.hlCenter.kwdclr);
                   1466:       opener.document.SCORE.kwsize.value = opener.radioSelection(document.hlCenter.kwdsize);
                   1467:       opener.document.SCORE.kwstyle.value = opener.radioSelection(document.hlCenter.kwdstyle);
                   1468:       opener.document.SCORE.refresh.value = "on";
                   1469:       if (opener.document.SCORE.keywords.value!=""){
                   1470:          opener.document.SCORE.submit();
                   1471:       }
                   1472:       self.close()
                   1473:     }
                   1474: </script>
                   1475: INNERJS
                   1476: 
                   1477:     my $start_page_msg_central = 
                   1478:         &Apache::loncommon::start_page('Message Central',$inner_js_msg_central,
                   1479: 				       {'js_ready'  => 1,
                   1480: 					'only_body' => 1,
                   1481: 					'bgcolor'   =>'#FFFFFF',});
                   1482:     my $end_page_msg_central = 
                   1483: 	&Apache::loncommon::end_page({'js_ready' => 1});
                   1484: 
                   1485: 
                   1486:     my $start_page_highlight_central = 
                   1487:         &Apache::loncommon::start_page('Highlight Central',
                   1488: 				       $inner_js_highlight_central,
1.350     albertel 1489: 				       {'js_ready'  => 1,
                   1490: 					'only_body' => 1,
                   1491: 					'bgcolor'   =>'#FFFFFF',});
1.351     albertel 1492:     my $end_page_highlight_central = 
1.350     albertel 1493: 	&Apache::loncommon::end_page({'js_ready' => 1});
                   1494: 
1.219     www      1495:     my $docopen=&Apache::lonhtmlcommon::javascript_docopen();
1.236     albertel 1496:     $docopen=~s/^document\.//;
1.596.2.4  raeburn  1497:     my %lt = &Apache::lonlocal::texthash(
                   1498:                 keyw => 'Keywords list, separated by a space. Add/delete to list if desired.',
                   1499:                 plse => 'Please select a word or group of words from document and then click this link.',
                   1500:                 adds => 'Add selection to keyword list? Edit if desired.',
                   1501:                 comp => 'Compose Message for: ',
                   1502:                 incl => 'Include',
                   1503:                 type => 'Type',
                   1504:                 subj => 'Subject',
                   1505:                 mesa => 'Message',
                   1506:                 new  => 'New',
                   1507:                 save => 'Save',
                   1508:                 canc => 'Cancel',
                   1509:                 kehi => 'Keyword Highlight Options',
                   1510:                 txtc => 'Text Color',
                   1511:                 font => 'Font Size',
                   1512:                 fnst => 'Font Style',
                   1513:              );
1.71      ng       1514:     $request->print(<<SUBJAVASCRIPT);
                   1515: <script type="text/javascript" language="javascript">
1.45      ng       1516: 
1.44      ng       1517: //===================== Show list of keywords ====================
1.122     ng       1518:   function keywords(formname) {
1.596.2.4  raeburn  1519:     var nret = prompt("$lt{'keyw'}",formname.keywords.value);
1.44      ng       1520:     if (nret==null) return;
1.122     ng       1521:     formname.keywords.value = nret;
1.44      ng       1522: 
1.122     ng       1523:     if (formname.keywords.value != "") {
1.128     ng       1524: 	formname.refresh.value = "on";
1.122     ng       1525: 	formname.submit();
1.44      ng       1526:     }
                   1527:     return;
                   1528:   }
                   1529: 
                   1530: //===================== Script to view submitted by ==================
                   1531:   function viewSubmitter(submitter) {
                   1532:     document.SCORE.refresh.value = "on";
                   1533:     document.SCORE.NCT.value = "1";
                   1534:     document.SCORE.unamedom0.value = submitter;
                   1535:     document.SCORE.submit();
                   1536:     return;
                   1537:   }
                   1538: 
                   1539: //===================== Script to add keyword(s) ==================
                   1540:   function getSel() {
                   1541:     if (document.getSelection) txt = document.getSelection();
                   1542:     else if (document.selection) txt = document.selection.createRange().text;
                   1543:     else return;
                   1544:     var cleantxt = txt.replace(new RegExp('([\\f\\n\\r\\t\\v ])+', 'g')," ");
                   1545:     if (cleantxt=="") {
1.596.2.4  raeburn  1546: 	alert("$lt{'plse'}");
1.44      ng       1547: 	return;
                   1548:     }
1.596.2.4  raeburn  1549:     var nret = prompt("$lt{'adds'}",cleantxt);
1.44      ng       1550:     if (nret==null) return;
1.127     ng       1551:     document.SCORE.keywords.value = document.SCORE.keywords.value+" "+nret;
1.44      ng       1552:     if (document.SCORE.keywords.value != "") {
1.127     ng       1553: 	document.SCORE.refresh.value = "on";
1.44      ng       1554: 	document.SCORE.submit();
                   1555:     }
                   1556:     return;
                   1557:   }
                   1558: 
                   1559: //====================== Script for composing message ==============
1.80      ng       1560:    // preload images
                   1561:    img1 = new Image();
                   1562:    img1.src = "$iconpath/mailbkgrd.gif";
                   1563:    img2 = new Image();
                   1564:    img2.src = "$iconpath/mailto.gif";
                   1565: 
1.44      ng       1566:   function msgCenter(msgform,usrctr,fullname) {
                   1567:     var Nmsg  = msgform.savemsgN.value;
                   1568:     savedMsgHeader(Nmsg,usrctr,fullname);
                   1569:     var subject = msgform.msgsub.value;
1.127     ng       1570:     var msgchk = document.SCORE["includemsg"+usrctr].value;
1.44      ng       1571:     re = /msgsub/;
                   1572:     var shwsel = "";
                   1573:     if (re.test(msgchk)) { shwsel = "checked" }
1.123     ng       1574:     subject = (document.SCORE.shownSub.value == 0 ? checkEntities(subject) : subject);
                   1575:     displaySubject(checkEntities(subject),shwsel);
1.44      ng       1576:     for (var i=1; i<=Nmsg; i++) {
1.123     ng       1577: 	var testmsg = "savemsg"+i+",";
                   1578: 	re = new RegExp(testmsg,"g");
1.44      ng       1579: 	shwsel = "";
                   1580: 	if (re.test(msgchk)) { shwsel = "checked" }
1.125     ng       1581: 	var message = document.SCORE["savemsg"+i].value;
1.126     ng       1582: 	message = (document.SCORE["shownOnce"+i].value == 0 ? checkEntities(message) : message);
1.123     ng       1583: 	displaySavedMsg(i,message,shwsel); //I do not get it. w/o checkEntities on saved messages,
                   1584: 	                                   //any &lt; is already converted to <, etc. However, only once!!
1.44      ng       1585:     }
1.125     ng       1586:     newmsg = document.SCORE["newmsg"+usrctr].value;
1.44      ng       1587:     shwsel = "";
                   1588:     re = /newmsg/;
                   1589:     if (re.test(msgchk)) { shwsel = "checked" }
                   1590:     newMsg(newmsg,shwsel);
                   1591:     msgTail(); 
                   1592:     return;
                   1593:   }
                   1594: 
1.123     ng       1595:   function checkEntities(strx) {
                   1596:     if (strx.length == 0) return strx;
                   1597:     var orgStr = ["&", "<", ">", '"']; 
                   1598:     var newStr = ["&amp;", "&lt;", "&gt;", "&quot;"];
                   1599:     var counter = 0;
                   1600:     while (counter < 4) {
                   1601: 	strx = strReplace(strx,orgStr[counter],newStr[counter]);
                   1602: 	counter++;
                   1603:     }
                   1604:     return strx;
                   1605:   }
                   1606: 
                   1607:   function strReplace(strx, orgStr, newStr) {
                   1608:     return strx.split(orgStr).join(newStr);
                   1609:   }
                   1610: 
1.44      ng       1611:   function savedMsgHeader(Nmsg,usrctr,fullname) {
1.76      ng       1612:     var height = 70*Nmsg+250;
1.44      ng       1613:     var scrollbar = "no";
                   1614:     if (height > 600) {
                   1615: 	height = 600;
                   1616: 	scrollbar = "yes";
                   1617:     }
1.118     ng       1618:     var xpos = (screen.width-600)/2;
                   1619:     xpos = (xpos < 0) ? '0' : xpos;
                   1620:     var ypos = (screen.height-height)/2-30;
                   1621:     ypos = (ypos < 0) ? '0' : ypos;
                   1622: 
1.596.2.4  raeburn  1623:     pWin = window.open('', 'MessageCenter', 'resizable=yes,toolbar=no,location=no,scrollbars='+scrollbar+',screenx='+xpos+',screeny='+ypos+',width=700,height='+height);
1.76      ng       1624:     pWin.focus();
                   1625:     pDoc = pWin.document;
1.219     www      1626:     pDoc.$docopen;
1.351     albertel 1627:     pDoc.write('$start_page_msg_central');
1.76      ng       1628: 
                   1629:     pDoc.write("<form action=\\"inactive\\" name=\\"msgcenter\\">");
                   1630:     pDoc.write("<input value=\\""+usrctr+"\\" name=\\"usrctr\\" type=\\"hidden\\">");
1.596.2.4  raeburn  1631:     pDoc.write("<h3><span class=\\"LC_info\\">&nbsp;$lt{'comp'}\"+fullname+\"<\\/span><\\/h3><br /><br />");
1.76      ng       1632: 
1.564     bisitz   1633:     pDoc.write('<table border="0" width="100%"><tr><td bgcolor="#777777">');
                   1634:     pDoc.write('<table border="0" width="100%"><tr bgcolor="#DDFFFF">');
1.596.2.4  raeburn  1635:     pDoc.write("<td><b>$lt{'type'}<\\/b><\\/td><td><b>$lt{'incl'}<\\/b><\\/td><td><b>$lt{'mesa'}<\\/td><\\/tr>");
1.44      ng       1636: }
                   1637:     function displaySubject(msg,shwsel) {
1.76      ng       1638:     pDoc = pWin.document;
                   1639:     pDoc.write("<tr bgcolor=\\"#ffffdd\\">");
1.596.2.4  raeburn  1640:     pDoc.write("<td>$lt{'subj'}<\\/td>");
1.465     albertel 1641:     pDoc.write("<td align=\\"center\\"><input name=\\"subchk\\" type=\\"checkbox\\"" +shwsel+"><\\/td>");
                   1642:     pDoc.write("<td><input name=\\"msgsub\\" type=\\"text\\" value=\\""+msg+"\\"size=\\"60\\" maxlength=\\"80\\"><\\/td><\\/tr>");
1.44      ng       1643: }
                   1644: 
1.72      ng       1645:   function displaySavedMsg(ctr,msg,shwsel) {
1.76      ng       1646:     pDoc = pWin.document;
                   1647:     pDoc.write("<tr bgcolor=\\"#ffffdd\\">");
1.465     albertel 1648:     pDoc.write("<td align=\\"center\\">"+ctr+"<\\/td>");
                   1649:     pDoc.write("<td align=\\"center\\"><input name=\\"msgn"+ctr+"\\" type=\\"checkbox\\"" +shwsel+"><\\/td>");
                   1650:     pDoc.write("<td><textarea name=\\"msg"+ctr+"\\" cols=\\"60\\" rows=\\"3\\">"+msg+"<\\/textarea><\\/td><\\/tr>");
1.44      ng       1651: }
                   1652: 
                   1653:   function newMsg(newmsg,shwsel) {
1.76      ng       1654:     pDoc = pWin.document;
                   1655:     pDoc.write("<tr bgcolor=\\"#ffffdd\\">");
1.596.2.4  raeburn  1656:     pDoc.write("<td align=\\"center\\">$lt{'new'}<\\/td>");
1.465     albertel 1657:     pDoc.write("<td align=\\"center\\"><input name=\\"newmsgchk\\" type=\\"checkbox\\"" +shwsel+"><\\/td>");
                   1658:     pDoc.write("<td><textarea name=\\"newmsg\\" cols=\\"60\\" rows=\\"3\\" onchange=\\"javascript:this.form.newmsgchk.checked=true\\" >"+newmsg+"<\\/textarea><\\/td><\\/tr>");
1.44      ng       1659: }
                   1660: 
                   1661:   function msgTail() {
1.76      ng       1662:     pDoc = pWin.document;
1.465     albertel 1663:     pDoc.write("<\\/table>");
                   1664:     pDoc.write("<\\/td><\\/tr><\\/table>&nbsp;");
1.596.2.4  raeburn  1665:     pDoc.write("<input type=\\"button\\" value=\\"$lt{'save'}\\" onclick=\\"javascript:checkInput()\\">&nbsp;&nbsp;");
                   1666:     pDoc.write("<input type=\\"button\\" value=\\"$lt{'canc'}\\" onclick=\\"self.close()\\"><br /><br />");
1.465     albertel 1667:     pDoc.write("<\\/form>");
1.351     albertel 1668:     pDoc.write('$end_page_msg_central');
1.128     ng       1669:     pDoc.close();
1.44      ng       1670: }
                   1671: 
                   1672: //====================== Script for keyword highlight options ==============
                   1673:   function kwhighlight() {
                   1674:     var kwclr    = document.SCORE.kwclr.value;
                   1675:     var kwsize   = document.SCORE.kwsize.value;
                   1676:     var kwstyle  = document.SCORE.kwstyle.value;
                   1677:     var redsel = "";
                   1678:     var grnsel = "";
                   1679:     var blusel = "";
                   1680:     if (kwclr=="red")   {var redsel="checked"};
                   1681:     if (kwclr=="green") {var grnsel="checked"};
                   1682:     if (kwclr=="blue")  {var blusel="checked"};
                   1683:     var sznsel = "";
                   1684:     var sz1sel = "";
                   1685:     var sz2sel = "";
                   1686:     if (kwsize=="0")  {var sznsel="checked"};
                   1687:     if (kwsize=="+1") {var sz1sel="checked"};
                   1688:     if (kwsize=="+2") {var sz2sel="checked"};
                   1689:     var synsel = "";
                   1690:     var syisel = "";
                   1691:     var sybsel = "";
                   1692:     if (kwstyle=="")    {var synsel="checked"};
                   1693:     if (kwstyle=="<i>") {var syisel="checked"};
                   1694:     if (kwstyle=="<b>") {var sybsel="checked"};
                   1695:     highlightCentral();
                   1696:     highlightbody('red','red',redsel,'0','normal',sznsel,'','normal',synsel);
                   1697:     highlightbody('green','green',grnsel,'+1','+1',sz1sel,'<i>','italic',syisel);
                   1698:     highlightbody('blue','blue',blusel,'+2','+2',sz2sel,'<b>','bold',sybsel);
                   1699:     highlightend();
                   1700:     return;
                   1701:   }
                   1702: 
                   1703:   function highlightCentral() {
1.76      ng       1704: //    if (window.hwdWin) window.hwdWin.close();
1.118     ng       1705:     var xpos = (screen.width-400)/2;
                   1706:     xpos = (xpos < 0) ? '0' : xpos;
                   1707:     var ypos = (screen.height-330)/2-30;
                   1708:     ypos = (ypos < 0) ? '0' : ypos;
                   1709: 
1.206     albertel 1710:     hwdWin = window.open('', 'KeywordHighlightCentral', 'resizeable=yes,toolbar=no,location=no,scrollbars=no,width=400,height=300,screenx='+xpos+',screeny='+ypos);
1.76      ng       1711:     hwdWin.focus();
                   1712:     var hDoc = hwdWin.document;
1.219     www      1713:     hDoc.$docopen;
1.351     albertel 1714:     hDoc.write('$start_page_highlight_central');
1.76      ng       1715:     hDoc.write("<form action=\\"inactive\\" name=\\"hlCenter\\">");
1.596.2.4  raeburn  1716:     hDoc.write("<h3><span class=\\"LC_info\\">&nbsp;$lt{'kehi'}<\\/span><\\/h3><br /><br />");
1.76      ng       1717: 
1.564     bisitz   1718:     hDoc.write('<table border="0" width="100%"><tr><td bgcolor="#777777">');
                   1719:     hDoc.write('<table border="0" width="100%"><tr bgcolor="#DDFFFF">');
1.596.2.4  raeburn  1720:     hDoc.write("<td><b>$lt{'txtc'}<\\/b><\\/td><td><b>$lt{'font'}<\\/b><\\/td><td><b>$lt{'fnst'}<\\/td><\\/tr>");
1.44      ng       1721:   }
                   1722: 
                   1723:   function highlightbody(clrval,clrtxt,clrsel,szval,sztxt,szsel,syval,sytxt,sysel) { 
1.76      ng       1724:     var hDoc = hwdWin.document;
                   1725:     hDoc.write("<tr bgcolor=\\"#ffffdd\\">");
                   1726:     hDoc.write("<td align=\\"left\\">");
1.465     albertel 1727:     hDoc.write("<input name=\\"kwdclr\\" type=\\"radio\\" value=\\""+clrval+"\\" "+clrsel+">&nbsp;"+clrtxt+"<\\/td>");
1.76      ng       1728:     hDoc.write("<td align=\\"left\\">");
1.465     albertel 1729:     hDoc.write("<input name=\\"kwdsize\\" type=\\"radio\\" value=\\""+szval+"\\" "+szsel+">&nbsp;"+sztxt+"<\\/td>");
1.76      ng       1730:     hDoc.write("<td align=\\"left\\">");
1.465     albertel 1731:     hDoc.write("<input name=\\"kwdstyle\\" type=\\"radio\\" value=\\""+syval+"\\" "+sysel+">&nbsp;"+sytxt+"<\\/td>");
                   1732:     hDoc.write("<\\/tr>");
1.44      ng       1733:   }
                   1734: 
                   1735:   function highlightend() { 
1.76      ng       1736:     var hDoc = hwdWin.document;
1.465     albertel 1737:     hDoc.write("<\\/table>");
                   1738:     hDoc.write("<\\/td><\\/tr><\\/table>&nbsp;");
1.596.2.4  raeburn  1739:     hDoc.write("<input type=\\"button\\" value=\\"$lt{'save'}\\" onclick=\\"javascript:updateChoice(1)\\">&nbsp;&nbsp;");
                   1740:     hDoc.write("<input type=\\"button\\" value=\\"$lt{'canc'}\\" onclick=\\"self.close()\\"><br /><br />");
1.465     albertel 1741:     hDoc.write("<\\/form>");
1.351     albertel 1742:     hDoc.write('$end_page_highlight_central');
1.128     ng       1743:     hDoc.close();
1.44      ng       1744:   }
                   1745: 
                   1746: </script>
                   1747: SUBJAVASCRIPT
                   1748: }
                   1749: 
1.349     albertel 1750: sub get_increment {
1.348     bowersj2 1751:     my $increment = $env{'form.increment'};
                   1752:     if ($increment != 1 && $increment != .5 && $increment != .25 &&
                   1753:         $increment != .1) {
                   1754:         $increment = 1;
                   1755:     }
                   1756:     return $increment;
                   1757: }
                   1758: 
1.585     bisitz   1759: sub gradeBox_start {
                   1760:     return (
                   1761:         &Apache::loncommon::start_data_table()
                   1762:        .&Apache::loncommon::start_data_table_header_row()
                   1763:        .'<th>'.&mt('Part').'</th>'
                   1764:        .'<th>'.&mt('Points').'</th>'
                   1765:        .'<th>&nbsp;</th>'
                   1766:        .'<th>'.&mt('Assign Grade').'</th>'
                   1767:        .'<th>'.&mt('Weight').'</th>'
                   1768:        .'<th>'.&mt('Grade Status').'</th>'
                   1769:        .&Apache::loncommon::end_data_table_header_row()
                   1770:     );
                   1771: }
                   1772: 
                   1773: sub gradeBox_end {
                   1774:     return (
                   1775:         &Apache::loncommon::end_data_table()
                   1776:     );
                   1777: }
1.71      ng       1778: #--- displays the grading box, used in essay type problem and grading by page/sequence
                   1779: sub gradeBox {
1.322     albertel 1780:     my ($request,$symb,$uname,$udom,$counter,$partid,$record) = @_;
1.381     albertel 1781:     my $checkIcon = '<img alt="'.&mt('Check Mark').
1.485     albertel 1782: 	'" src="'.&Apache::loncommon::lonhttpdurl($request->dir_config('lonIconsURL').'/check.gif').'" height="16" border="0" />';
1.71      ng       1783:     my $wgt    = &Apache::lonnet::EXT('resource.'.$partid.'.weight',$symb,$udom,$uname);
1.466     albertel 1784:     my $wgtmsg = ($wgt > 0) ? &mt('(problem weight)') 
                   1785:                            : '<span class="LC_info">'.&mt('problem weight assigned by computer').'</span>';
1.71      ng       1786:     $wgt       = ($wgt > 0 ? $wgt : '1');
                   1787:     my $score  = ($$record{'resource.'.$partid.'.awarded'} eq '' ?
1.320     albertel 1788: 		  '' : &compute_points($$record{'resource.'.$partid.'.awarded'},$wgt));
1.71      ng       1789:     my $result='<input type="hidden" name="WGT'.$counter.'_'.$partid.'" value="'.$wgt.'" />'."\n";
1.466     albertel 1790:     my $display_part= &get_display_part($partid,$symb);
1.270     albertel 1791:     my %last_resets = &get_last_resets($symb,$env{'request.course.id'},
                   1792: 				       [$partid]);
                   1793:     my $aggtries = $$record{'resource.'.$partid.'.tries'};
1.269     raeburn  1794:     if ($last_resets{$partid}) {
                   1795:         $aggtries = &get_num_tries($record,$last_resets{$partid},$partid);
                   1796:     }
1.585     bisitz   1797:     $result.=&Apache::loncommon::start_data_table_row();
1.71      ng       1798:     my $ctr = 0;
1.348     bowersj2 1799:     my $thisweight = 0;
1.349     albertel 1800:     my $increment = &get_increment();
1.485     albertel 1801: 
                   1802:     my $radio.='<table border="0"><tr>'."\n";  # display radio buttons in a nice table 10 across
1.348     bowersj2 1803:     while ($thisweight<=$wgt) {
1.532     bisitz   1804: 	$radio.= '<td><span class="LC_nobreak"><label><input type="radio" name="RADVAL'.$counter.'_'.$partid.'" '.
1.589     bisitz   1805:         'onclick="javascript:writeBox(this.form,\''.$counter.'_'.$partid.'\','.
1.348     bowersj2 1806: 	    $thisweight.')" value="'.$thisweight.'" '.
1.401     albertel 1807: 	    ($score eq $thisweight ? 'checked="checked"':'').' /> '.$thisweight."</label></span></td>\n";
1.485     albertel 1808: 	$radio.=(($ctr+1)%10 == 0 ? '</tr><tr>' : '');
1.348     bowersj2 1809:         $thisweight += $increment;
1.71      ng       1810: 	$ctr++;
                   1811:     }
1.485     albertel 1812:     $radio.='</tr></table>';
                   1813: 
                   1814:     my $line.='<input type="text" name="GD_BOX'.$counter.'_'.$partid.'"'.
1.71      ng       1815: 	($score ne ''? ' value = "'.$score.'"':'').' size="4" '.
1.589     bisitz   1816: 	'onchange="javascript:updateRadio(this.form,\''.$counter.'_'.$partid.'\','.
1.71      ng       1817: 	$wgt.')" /></td>'."\n";
1.485     albertel 1818:     $line.='<td>/'.$wgt.' '.$wgtmsg.
1.71      ng       1819: 	($$record{'resource.'.$partid.'.solved'} eq 'correct_by_student' ? '&nbsp;'.$checkIcon : '').
1.585     bisitz   1820: 	' </td>'."\n";
                   1821:     $line.='<td><select name="GD_SEL'.$counter.'_'.$partid.'" '.
1.589     bisitz   1822: 	'onchange="javascript:clearRadBox(this.form,\''.$counter.'_'.$partid.'\')" >'."\n";
1.71      ng       1823:     if ($$record{'resource.'.$partid.'.solved'} eq 'excused') {
1.485     albertel 1824: 	$line.='<option></option>'.
                   1825: 	    '<option value="excused" selected="selected">'.&mt('excused').'</option>';
1.71      ng       1826:     } else {
1.485     albertel 1827: 	$line.='<option selected="selected"></option>'.
                   1828: 	    '<option value="excused" >'.&mt('excused').'</option>';
1.71      ng       1829:     }
1.485     albertel 1830:     $line.='<option value="reset status">'.&mt('reset status').'</option></select>'."\n";
                   1831: 
                   1832: 
                   1833:     $result .= 
1.585     bisitz   1834: 	    '<td>'.$display_part.'</td><td>'.$radio.'</td><td>'.&mt('or').'</td><td>'.$line.'</td>';
                   1835:     $result.=&Apache::loncommon::end_data_table_row();
1.71      ng       1836:     $result.='<input type="hidden" name="stores'.$counter.'_'.$partid.'" value="" />'."\n".
                   1837: 	'<input type="hidden" name="oldpts'.$counter.'_'.$partid.'" value="'.$score.'" />'."\n".
                   1838: 	'<input type="hidden" name="solved'.$counter.'_'.$partid.'" value="'.
1.269     raeburn  1839: 	$$record{'resource.'.$partid.'.solved'}.'" />'."\n".
                   1840:         '<input type="hidden" name="totaltries'.$counter.'_'.$partid.'" value="'.
                   1841:         $$record{'resource.'.$partid.'.tries'}.'" />'."\n".
                   1842:         '<input type="hidden" name="aggtries'.$counter.'_'.$partid.'" value="'.
                   1843:         $aggtries.'" />'."\n";
1.582     raeburn  1844:     my $res_error;
                   1845:     $result.=&handback_box($symb,$uname,$udom,$counter,$partid,$record,\$res_error);
                   1846:     if ($res_error) {
                   1847:         return &navmap_errormsg();
                   1848:     }
1.318     banghart 1849:     return $result;
                   1850: }
1.322     albertel 1851: 
                   1852: sub handback_box {
1.582     raeburn  1853:     my ($symb,$uname,$udom,$counter,$partid,$record,$res_error) = @_;
                   1854:     my ($partlist,$handgrade,$responseType) = &response_type($symb,$res_error);
1.323     banghart 1855:     my (@respids);
1.596.2.4  raeburn  1856:     my @part_response_id = &flatten_responseType($responseType);
1.375     albertel 1857:     foreach my $part_response_id (@part_response_id) {
                   1858:     	my ($part,$resp) = @{ $part_response_id };
1.323     banghart 1859:         if ($part eq $partid) {
1.375     albertel 1860:             push(@respids,$resp);
1.323     banghart 1861:         }
                   1862:     }
1.318     banghart 1863:     my $result;
1.323     banghart 1864:     foreach my $respid (@respids) {
1.322     albertel 1865: 	my $prefix = $counter.'_'.$partid.'_'.$respid.'_';
                   1866: 	my $files=&get_submitted_files($udom,$uname,$partid,$respid,$record);
                   1867: 	next if (!@$files);
1.596.2.4  raeburn  1868: 	my $file_counter = 0;
1.313     banghart 1869: 	foreach my $file (@$files) {
1.368     banghart 1870: 	    if ($file =~ /\/portfolio\//) {
1.596.2.4  raeburn  1871:                 $file_counter++;
1.368     banghart 1872:     	        my ($file_path, $file_disp) = ($file =~ m|(.+/)(.+)$|);
                   1873:     	        my ($name,$version,$ext) = &file_name_version_ext($file_disp);
                   1874:     	        $file_disp = "$name.$ext";
                   1875:     	        $file = $file_path.$file_disp;
                   1876:     	        $result.=&mt('Return commented version of [_1] to student.',
                   1877:     			 '<span class="LC_filename">'.$file_disp.'</span>');
                   1878:     	        $result.='<input type="file"   name="'.$prefix.'returndoc'.$file_counter.'" />'."\n";
1.596.2.4  raeburn  1879:     	        $result.='<input type="hidden" name="'.$prefix.'origdoc'.$file_counter.'" value="'.$file.'" /><br />'."\n";
1.368     banghart 1880: 	    }
1.322     albertel 1881: 	}
1.596.2.4  raeburn  1882:         if ($file_counter) {
                   1883:             $result .= '<input type="hidden" name="'.$prefix.'countreturndoc" value="'.$file_counter.'" />'."\n".
                   1884:                        '<span class="LC_info">'.
                   1885:                        '('.&mt('File(s) will be uploaded when you click on Save &amp; Next below.',$file_counter).')</span><br /><br />';
                   1886:         }
1.313     banghart 1887:     }
1.318     banghart 1888:     return $result;    
1.71      ng       1889: }
1.44      ng       1890: 
1.58      albertel 1891: sub show_problem {
1.382     albertel 1892:     my ($request,$symb,$uname,$udom,$removeform,$viewon,$mode,$form) = @_;
1.144     albertel 1893:     my $rendered;
1.382     albertel 1894:     my %form = ((ref($form) eq 'HASH')? %{$form} : ());
1.329     albertel 1895:     &Apache::lonxml::remember_problem_counter();
1.144     albertel 1896:     if ($mode eq 'both' or $mode eq 'text') {
                   1897: 	$rendered=&Apache::loncommon::get_student_view($symb,$uname,$udom,
1.382     albertel 1898: 						       $env{'request.course.id'},
                   1899: 						       undef,\%form);
1.144     albertel 1900:     }
1.58      albertel 1901:     if ($removeform) {
                   1902: 	$rendered=~s|<form(.*?)>||g;
                   1903: 	$rendered=~s|</form>||g;
1.374     albertel 1904: 	$rendered=~s|(<input[^>]*name\s*=\s*"?)(\w+)("?)|$1would_have_been_$2$3|g;
1.58      albertel 1905:     }
1.144     albertel 1906:     my $companswer;
                   1907:     if ($mode eq 'both' or $mode eq 'answer') {
1.329     albertel 1908: 	&Apache::lonxml::restore_problem_counter();
1.382     albertel 1909: 	$companswer=
                   1910: 	    &Apache::loncommon::get_student_answers($symb,$uname,$udom,
                   1911: 						    $env{'request.course.id'},
                   1912: 						    %form);
1.144     albertel 1913:     }
1.58      albertel 1914:     if ($removeform) {
                   1915: 	$companswer=~s|<form(.*?)>||g;
                   1916: 	$companswer=~s|</form>||g;
1.144     albertel 1917: 	$companswer=~s|name="submit"|name="would_have_been_submit"|g;
1.58      albertel 1918:     }
1.468     albertel 1919:     $rendered=
1.588     bisitz   1920:         '<div class="LC_Box">'
                   1921:        .'<h3 class="LC_hcell">'.&mt('View of the problem').'</h3>'
                   1922:        .$rendered
                   1923:        .'</div>';
1.468     albertel 1924:     $companswer=
1.588     bisitz   1925:         '<div class="LC_Box">'
                   1926:        .'<h3 class="LC_hcell">'.&mt('Correct answer').'</h3>'
                   1927:        .$companswer
                   1928:        .'</div>';
1.468     albertel 1929:     my $result;
1.144     albertel 1930:     if ($mode eq 'both') {
1.588     bisitz   1931:         $result=$rendered.$companswer;
1.144     albertel 1932:     } elsif ($mode eq 'text') {
1.588     bisitz   1933:         $result=$rendered;
1.144     albertel 1934:     } elsif ($mode eq 'answer') {
1.588     bisitz   1935:         $result=$companswer;
1.144     albertel 1936:     }
1.71      ng       1937:     return $result;
1.58      albertel 1938: }
1.397     albertel 1939: 
1.396     banghart 1940: sub files_exist {
                   1941:     my ($r, $symb) = @_;
                   1942:     my @students = &Apache::loncommon::get_env_multiple('form.stuinfo');
1.397     albertel 1943: 
1.396     banghart 1944:     foreach my $student (@students) {
                   1945:         my ($uname,$udom,$fullname) = split(/:/,$student);
1.397     albertel 1946:         my %record = &Apache::lonnet::restore($symb,$env{'request.course.id'},
                   1947: 					      $udom,$uname);
1.396     banghart 1948:         my ($string,$timestamp)= &get_last_submission(\%record);
1.397     albertel 1949:         foreach my $submission (@$string) {
                   1950:             my ($partid,$respid) =
                   1951: 		($submission =~ /^resource\.([^\.]*)\.([^\.]*)\.submission/);
                   1952:             my $files=&get_submitted_files($udom,$uname,$partid,$respid,
                   1953: 					   \%record);
                   1954:             return 1 if (@$files);
1.396     banghart 1955:         }
                   1956:     }
1.397     albertel 1957:     return 0;
1.396     banghart 1958: }
1.397     albertel 1959: 
1.394     banghart 1960: sub download_all_link {
                   1961:     my ($r,$symb) = @_;
1.395     albertel 1962:     my $all_students = 
                   1963: 	join("\n", &Apache::loncommon::get_env_multiple('form.stuinfo'));
                   1964: 
                   1965:     my $parts =
                   1966: 	join("\n",&Apache::loncommon::get_env_multiple('form.vPart'));
                   1967: 
1.394     banghart 1968:     my $identifier = &Apache::loncommon::get_cgi_id();
1.514     raeburn  1969:     &Apache::lonnet::appenv({'cgi.'.$identifier.'.students' => $all_students,
                   1970:                              'cgi.'.$identifier.'.symb' => $symb,
                   1971:                              'cgi.'.$identifier.'.parts' => $parts,});
1.395     albertel 1972:     $r->print('<a href="/cgi-bin/multidownload.pl?'.$identifier.'">'.
                   1973: 	      &mt('Download All Submitted Documents').'</a>');
1.394     banghart 1974:     return
                   1975: }
1.395     albertel 1976: 
1.432     banghart 1977: sub build_section_inputs {
                   1978:     my $section_inputs;
                   1979:     if ($env{'form.section'} eq '') {
                   1980:         $section_inputs .= '<input type="hidden" name="section" value="all" />'."\n";
                   1981:     } else {
                   1982:         my @sections = &Apache::loncommon::get_env_multiple('form.section');
1.434     albertel 1983:         foreach my $section (@sections) {
1.432     banghart 1984:             $section_inputs .= '<input type="hidden" name="section" value="'.$section.'" />'."\n";
                   1985:         }
                   1986:     }
                   1987:     return $section_inputs;
                   1988: }
                   1989: 
1.44      ng       1990: # --------------------------- show submissions of a student, option to grade 
                   1991: sub submission {
                   1992:     my ($request,$counter,$total) = @_;
1.257     albertel 1993:     my ($uname,$udom)     = ($env{'form.student'},$env{'form.userdom'});
                   1994:     $udom = ($udom eq '' ? $env{'user.domain'} : $udom); #has form.userdom changed for a student?
                   1995:     my $usec = &Apache::lonnet::getsection($udom,$uname,$env{'request.course.id'});
                   1996:     $env{'form.fullname'} = &Apache::loncommon::plainname($uname,$udom,'lastname') if $env{'form.fullname'} eq '';
1.324     albertel 1997:     my $symb = &get_symb($request); 
                   1998:     if ($symb eq '') { $request->print("Unable to handle ambiguous references:."); return ''; }
1.104     albertel 1999: 
                   2000:     if (!&canview($usec)) {
1.398     albertel 2001: 	$request->print('<span class="LC_warning">Unable to view requested student.('.
                   2002: 			$uname.':'.$udom.' in section '.$usec.' in course id '.
                   2003: 			$env{'request.course.id'}.')</span>');
1.324     albertel 2004: 	$request->print(&show_grading_menu_form($symb));
1.104     albertel 2005: 	return;
                   2006:     }
                   2007: 
1.257     albertel 2008:     if (!$env{'form.lastSub'}) { $env{'form.lastSub'} = 'datesub'; }
                   2009:     if (!$env{'form.vProb'}) { $env{'form.vProb'} = 'yes'; }
                   2010:     if (!$env{'form.vAns'}) { $env{'form.vAns'} = 'yes'; }
                   2011:     my $last = ($env{'form.lastSub'} eq 'last' ? 'last' : '');
1.381     albertel 2012:     my $checkIcon = '<img alt="'.&mt('Check Mark').
                   2013: 	'" src="'.$request->dir_config('lonIconsURL').
1.122     ng       2014: 	'/check.gif" height="16" border="0" />';
1.41      ng       2015: 
1.426     albertel 2016:     my %old_essays;
1.41      ng       2017:     # header info
                   2018:     if ($counter == 0) {
                   2019: 	&sub_page_js($request);
1.257     albertel 2020: 	&sub_page_kw_js($request) if ($env{'form.handgrade'} eq 'yes');
                   2021: 	$env{'form.probTitle'} = $env{'form.probTitle'} eq '' ? 
                   2022: 	    &Apache::lonnet::gettitle($symb) : $env{'form.probTitle'};
1.397     albertel 2023: 	if ($env{'form.handgrade'} eq 'yes' && &files_exist($request, $symb)) {
1.396     banghart 2024: 	    &download_all_link($request, $symb);
                   2025: 	}
1.485     albertel 2026: 	$request->print('<h3>&nbsp;<span class="LC_info">'.&mt('Submission Record').'</span></h3>'."\n".
                   2027: 			'<h4>&nbsp;'.&mt('<b>Resource: </b> [_1]',$env{'form.probTitle'}).'</h4>'."\n");
1.118     ng       2028: 
1.44      ng       2029: 	# option to display problem, only once else it cause problems 
                   2030:         # with the form later since the problem has a form.
1.257     albertel 2031: 	if ($env{'form.vProb'} eq 'yes' or $env{'form.vAns'} eq 'yes') {
1.144     albertel 2032: 	    my $mode;
1.257     albertel 2033: 	    if ($env{'form.vProb'} eq 'yes' && $env{'form.vAns'} eq 'yes') {
1.144     albertel 2034: 		$mode='both';
1.257     albertel 2035: 	    } elsif ($env{'form.vProb'} eq 'yes') {
1.144     albertel 2036: 		$mode='text';
1.257     albertel 2037: 	    } elsif ($env{'form.vAns'} eq 'yes') {
1.144     albertel 2038: 		$mode='answer';
                   2039: 	    }
1.329     albertel 2040: 	    &Apache::lonxml::clear_problem_counter();
1.144     albertel 2041: 	    $request->print(&show_problem($request,$symb,$uname,$udom,0,1,$mode));
1.41      ng       2042: 	}
1.441     www      2043: 
1.44      ng       2044: 	# kwclr is the only variable that is guaranteed to be non blank 
                   2045:         # if this subroutine has been called once.
1.41      ng       2046: 	my %keyhash = ();
1.257     albertel 2047: 	if ($env{'form.kwclr'} eq '' && $env{'form.handgrade'} eq 'yes') {
1.41      ng       2048: 	    %keyhash = &Apache::lonnet::dump('nohist_handgrade',
1.257     albertel 2049: 					     $env{'course.'.$env{'request.course.id'}.'.domain'},
                   2050: 					     $env{'course.'.$env{'request.course.id'}.'.num'});
1.41      ng       2051: 
1.257     albertel 2052: 	    my $loginuser = $env{'user.name'}.':'.$env{'user.domain'};
                   2053: 	    $env{'form.keywords'} = $keyhash{$symb.'_keywords'} ne '' ? $keyhash{$symb.'_keywords'} : '';
                   2054: 	    $env{'form.kwclr'}    = $keyhash{$loginuser.'_kwclr'} ne '' ? $keyhash{$loginuser.'_kwclr'} : 'red';
                   2055: 	    $env{'form.kwsize'}   = $keyhash{$loginuser.'_kwsize'} ne '' ? $keyhash{$loginuser.'_kwsize'} : '0';
                   2056: 	    $env{'form.kwstyle'}  = $keyhash{$loginuser.'_kwstyle'} ne '' ? $keyhash{$loginuser.'_kwstyle'} : '';
                   2057: 	    $env{'form.msgsub'}   = $keyhash{$symb.'_subject'} ne '' ? 
                   2058: 		$keyhash{$symb.'_subject'} : $env{'form.probTitle'};
                   2059: 	    $env{'form.savemsgN'} = $keyhash{$symb.'_savemsgN'} ne '' ? $keyhash{$symb.'_savemsgN'} : '0';
1.41      ng       2060: 	}
1.257     albertel 2061: 	my $overRideScore = $env{'form.overRideScore'} eq '' ? 'no' : $env{'form.overRideScore'};
1.442     banghart 2062: 	my $stu_status = join(':',&Apache::loncommon::get_env_multiple('form.Status'));
1.303     banghart 2063: 	$request->print('<form action="/adm/grades" method="post" name="SCORE" enctype="multipart/form-data">'."\n".
1.41      ng       2064: 			'<input type="hidden" name="command"    value="handgrade" />'."\n".
1.257     albertel 2065: 			'<input type="hidden" name="saveState"  value="'.$env{'form.saveState'}.'" />'."\n".
1.442     banghart 2066: 			'<input type="hidden" name="Status"     value="'.$stu_status.'" />'."\n".
1.120     ng       2067: 			'<input type="hidden" name="overRideScore" value="'.$overRideScore.'" />'."\n".
1.257     albertel 2068: 			'<input type="hidden" name="probTitle"  value="'.$env{'form.probTitle'}.'" />'."\n".
1.41      ng       2069: 			'<input type="hidden" name="refresh"    value="off" />'."\n".
1.120     ng       2070: 			'<input type="hidden" name="studentNo"  value="" />'."\n".
                   2071: 			'<input type="hidden" name="gradeOpt"   value="" />'."\n".
1.418     albertel 2072: 			'<input type="hidden" name="symb"       value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
1.257     albertel 2073: 			'<input type="hidden" name="showgrading" value="'.$env{'form.showgrading'}.'" />'."\n".
                   2074: 			'<input type="hidden" name="vProb"      value="'.$env{'form.vProb'}.'" />'."\n".
                   2075: 			'<input type="hidden" name="vAns"       value="'.$env{'form.vAns'}.'" />'."\n".
                   2076: 			'<input type="hidden" name="lastSub"    value="'.$env{'form.lastSub'}.'" />'."\n".
1.432     banghart 2077: 			&build_section_inputs().
1.326     albertel 2078: 			'<input type="hidden" name="submitonly" value="'.$env{'form.submitonly'}.'" />'."\n".
                   2079: 			'<input type="hidden" name="handgrade"  value="'.$env{'form.handgrade'}.'" />'."\n".
1.41      ng       2080: 			'<input type="hidden" name="NCT"'.
1.257     albertel 2081: 			' value="'.($env{'form.NTSTU'} ne '' ? $env{'form.NTSTU'} : $total+1).'" />'."\n");
                   2082: 	if ($env{'form.handgrade'} eq 'yes') {
                   2083: 	    $request->print('<input type="hidden" name="keywords" value="'.$env{'form.keywords'}.'" />'."\n".
                   2084: 			    '<input type="hidden" name="kwclr"    value="'.$env{'form.kwclr'}.'" />'."\n".
                   2085: 			    '<input type="hidden" name="kwsize"   value="'.$env{'form.kwsize'}.'" />'."\n".
                   2086: 			    '<input type="hidden" name="kwstyle"  value="'.$env{'form.kwstyle'}.'" />'."\n".
                   2087: 			    '<input type="hidden" name="msgsub"   value="'.$env{'form.msgsub'}.'" />'."\n".
1.123     ng       2088: 			    '<input type="hidden" name="shownSub" value="0" />'."\n".
1.257     albertel 2089: 			    '<input type="hidden" name="savemsgN" value="'.$env{'form.savemsgN'}.'" />'."\n");
1.154     albertel 2090: 	    foreach my $partid (&Apache::loncommon::get_env_multiple('form.vPart')) {
                   2091: 		$request->print('<input type="hidden" name="vPart" value="'.$partid.'" />'."\n");
                   2092: 	    }
1.123     ng       2093: 	}
1.41      ng       2094: 	
                   2095: 	my ($cts,$prnmsg) = (1,'');
1.257     albertel 2096: 	while ($cts <= $env{'form.savemsgN'}) {
1.41      ng       2097: 	    $prnmsg.='<input type="hidden" name="savemsg'.$cts.'" value="'.
1.123     ng       2098: 		(!exists($keyhash{$symb.'_savemsg'.$cts}) ? 
1.257     albertel 2099: 		 &Apache::lonfeedback::clear_out_html($env{'form.savemsg'.$cts}) :
1.80      ng       2100: 		 &Apache::lonfeedback::clear_out_html($keyhash{$symb.'_savemsg'.$cts})).
1.123     ng       2101: 		'" />'."\n".
                   2102: 		'<input type="hidden" name="shownOnce'.$cts.'" value="0" />'."\n";
1.41      ng       2103: 	    $cts++;
                   2104: 	}
                   2105: 	$request->print($prnmsg);
1.32      ng       2106: 
1.257     albertel 2107: 	if ($env{'form.handgrade'} eq 'yes' && $env{'form.showgrading'} eq 'yes') {
1.596.2.4  raeburn  2108: 
                   2109:             my %lt = &Apache::lonlocal::texthash(
                   2110:                           keyw => 'Keyword Options',
                   2111:                           list => 'List',
                   2112:                           past => 'Paste Selection to List',
1.596.2.9  raeburn  2113:                           high => 'Highlight Attribute',
1.596.2.4  raeburn  2114:                      );
1.88      www      2115: #
                   2116: # Print out the keyword options line
                   2117: #
1.41      ng       2118: 	    $request->print(<<KEYWORDS);
1.596.2.4  raeburn  2119: &nbsp;<b>$lt{'keyw'}:</b>&nbsp;
                   2120: <a href="javascript:keywords(document.SCORE);" target="_self">$lt{'list'}</a>&nbsp; &nbsp;
1.589     bisitz   2121: <a href="#" onmousedown="javascript:getSel(); return false"
1.596.2.4  raeburn  2122:  CLASS="page">$lt{'past'}</a>&nbsp; &nbsp;
                   2123: <a href="javascript:kwhighlight();" target="_self">$lt{'high'}</a><br /><br />
1.38      ng       2124: KEYWORDS
1.88      www      2125: #
                   2126: # Load the other essays for similarity check
                   2127: #
1.324     albertel 2128:             my (undef,undef,$essayurl) = &Apache::lonnet::decode_symb($symb);
1.384     albertel 2129: 	    my ($adom,$aname,$apath)=($essayurl=~/^($LONCAPA::domain_re)\/($LONCAPA::username_re)\/(.*)$/);
1.359     www      2130: 	    $apath=&escape($apath);
1.88      www      2131: 	    $apath=~s/\W/\_/gs;
1.426     albertel 2132: 	    %old_essays=&Apache::lonnet::dump('nohist_essay_'.$apath,$adom,$aname);
1.41      ng       2133:         }
                   2134:     }
1.44      ng       2135: 
1.441     www      2136: # This is where output for one specific student would start
1.592     bisitz   2137:     my $add_class = ($counter%2) ? ' LC_grade_show_user_odd_row' : '';
                   2138:     $request->print(
                   2139:         "\n\n"
                   2140:        .'<div class="LC_grade_show_user'.$add_class.'">'
                   2141:        .'<h2>'.&nameUserString(undef,$env{'form.fullname'},$uname,$udom).'</h2>'
                   2142:        ."\n"
                   2143:     );
1.441     www      2144: 
1.592     bisitz   2145:     # Show additional functions if allowed
                   2146:     if ($perm{'vgr'}) {
                   2147:         $request->print(
                   2148:             &Apache::loncommon::track_student_link(
                   2149:                 &mt('View recent activity'),
                   2150:                 $uname,$udom,'check')
                   2151:            .' '
                   2152:         );
                   2153:     }
                   2154:     if ($perm{'opa'}) {
                   2155:         $request->print(
                   2156:             &Apache::loncommon::pprmlink(
                   2157:                 &mt('Set/Change parameters'),
                   2158:                 $uname,$udom,$symb,'check'));
                   2159:     }
                   2160: 
                   2161:     # Show Problem
1.257     albertel 2162:     if ($env{'form.vProb'} eq 'all' or $env{'form.vAns'} eq 'all') {
1.144     albertel 2163: 	my $mode;
1.257     albertel 2164: 	if ($env{'form.vProb'} eq 'all' && $env{'form.vAns'} eq 'all') {
1.144     albertel 2165: 	    $mode='both';
1.257     albertel 2166: 	} elsif ($env{'form.vProb'} eq 'all' ) {
1.144     albertel 2167: 	    $mode='text';
1.257     albertel 2168: 	} elsif ($env{'form.vAns'} eq 'all') {
1.144     albertel 2169: 	    $mode='answer';
                   2170: 	}
1.329     albertel 2171: 	&Apache::lonxml::clear_problem_counter();
1.475     albertel 2172: 	$request->print(&show_problem($request,$symb,$uname,$udom,1,1,$mode,{'request.prefix' => 'ctr'.$counter}));
1.58      albertel 2173:     }
1.144     albertel 2174: 
1.257     albertel 2175:     my %record = &Apache::lonnet::restore($symb,$env{'request.course.id'},$udom,$uname);
1.582     raeburn  2176:     my $res_error;
                   2177:     my ($partlist,$handgrade,$responseType) = &response_type($symb,\$res_error);
                   2178:     if ($res_error) {
                   2179:         $request->print(&navmap_errormsg());
                   2180:         return;
                   2181:     }
1.41      ng       2182: 
1.44      ng       2183:     # Display student info
1.41      ng       2184:     $request->print(($counter == 0 ? '' : '<br />'));
1.590     bisitz   2185: 
                   2186:     my $result='<div class="LC_Box">'
                   2187:               .'<h3 class="LC_hcell">'.&mt('Submissions').'</h3>';
1.45      ng       2188:     $result.='<input type="hidden" name="name'.$counter.
1.588     bisitz   2189:              '" value="'.$env{'form.fullname'}.'" />'."\n";
1.469     albertel 2190:     if ($env{'form.handgrade'} eq 'no') {
1.588     bisitz   2191:         $result.='<p class="LC_info">'
                   2192:                 .&mt('Part(s) graded correct by the computer is marked with a [_1] symbol.',$checkIcon)
                   2193:                 ."</p>\n";
1.469     albertel 2194:     }
                   2195: 
1.118     ng       2196:     # If any part of the problem is an essay-response (handgraded), then check for collaborators
1.464     albertel 2197:     my $fullname;
                   2198:     my $col_fullnames = [];
1.257     albertel 2199:     if ($env{'form.handgrade'} eq 'yes') {
1.464     albertel 2200: 	(my $sub_result,$fullname,$col_fullnames)=
                   2201: 	    &check_collaborators($symb,$uname,$udom,\%record,$handgrade,
                   2202: 				 $counter);
                   2203: 	$result.=$sub_result;
1.41      ng       2204:     }
1.44      ng       2205:     $request->print($result."\n");
1.588     bisitz   2206: 
1.44      ng       2207:     # print student answer/submission
1.588     bisitz   2208:     # Options are (1) Handgraded submission only
1.44      ng       2209:     #             (2) Last submission, includes submission that is not handgraded 
                   2210:     #                  (for multi-response type part)
                   2211:     #             (3) Last submission plus the parts info
                   2212:     #             (4) The whole record for this student
1.257     albertel 2213:     if ($env{'form.lastSub'} =~ /^(lastonly|hdgrade)$/) {
1.151     albertel 2214: 	my ($string,$timestamp)= &get_last_submission(\%record);
1.468     albertel 2215: 	
                   2216: 	my $lastsubonly;
                   2217: 
1.588     bisitz   2218:         if ($$timestamp eq '') {
                   2219:             $lastsubonly.='<div class="LC_grade_submissions_body">'.$$string[0].'</div>'; 
                   2220:         } else {
1.592     bisitz   2221:             $lastsubonly =
                   2222:                 '<div class="LC_grade_submissions_body">'
                   2223:                .'<b>'.&mt('Date Submitted:').'</b> '.$$timestamp."\n";
1.468     albertel 2224: 
1.151     albertel 2225: 	    my %seenparts;
1.375     albertel 2226: 	    my @part_response_id = &flatten_responseType($responseType);
                   2227: 	    foreach my $part (@part_response_id) {
1.393     albertel 2228: 		next if ($env{'form.lastSub'} eq 'hdgrade' 
                   2229: 			 && $$handgrade{$$part[0].'_'.$$part[1]} ne 'yes');
                   2230: 
1.375     albertel 2231: 		my ($partid,$respid) = @{ $part };
1.324     albertel 2232: 		my $display_part=&get_display_part($partid,$symb);
1.257     albertel 2233: 		if ($env{"form.$uname:$udom:$partid:submitted_by"}) {
1.151     albertel 2234: 		    if (exists($seenparts{$partid})) { next; }
                   2235: 		    $seenparts{$partid}=1;
1.207     albertel 2236: 		    my $submitby='<b>Part:</b> '.$display_part.
                   2237: 			' <b>Collaborative submission by:</b> '.
1.151     albertel 2238: 			'<a href="javascript:viewSubmitter(\''.
1.257     albertel 2239: 			$env{"form.$uname:$udom:$partid:submitted_by"}.
1.417     albertel 2240: 			'\');" target="_self">'.
1.257     albertel 2241: 			$$fullname{$env{"form.$uname:$udom:$partid:submitted_by"}}.'</a><br />';
1.151     albertel 2242: 		    $request->print($submitby);
                   2243: 		    next;
                   2244: 		}
                   2245: 		my $responsetype = $responseType->{$partid}->{$respid};
                   2246: 		if (!exists($record{"resource.$partid.$respid.submission"})) {
1.577     bisitz   2247:                     $lastsubonly.="\n".'<div class="LC_grade_submission_part">'.
                   2248:                         '<b>'.&mt('Part: [_1]',$display_part).'</b>'.
                   2249:                         ' <span class="LC_internal_info">'.
1.596.2.4  raeburn  2250:                         '('.&mt('Response ID: [_1]',$respid).')'.
1.577     bisitz   2251:                         '</span>&nbsp; &nbsp;'.
1.539     riegler  2252: 			'<span class="LC_warning">'.&mt('Nothing submitted - no attempts.').'</span><br /><br /></div>';
1.151     albertel 2253: 		    next;
                   2254: 		}
1.468     albertel 2255: 		foreach my $submission (@$string) {
                   2256: 		    my ($partid,$respid) = ($submission =~ /^resource\.([^\.]*)\.([^\.]*)\.submission/);
1.375     albertel 2257: 		    if (join('_',@{$part}) ne ($partid.'_'.$respid)) { next; }
1.596     raeburn  2258: 		    my ($ressub,$hide,$subval) = split(/:/,$submission,3);
1.151     albertel 2259: 		    # Similarity check
                   2260: 		    my $similar='';
1.596.2.2  raeburn  2261:                     my ($type,$trial,$rndseed);
                   2262:                     if ($hide eq 'rand') {
                   2263:                         $type = 'randomizetry';
                   2264:                         $trial = $record{"resource.$partid.tries"};
                   2265:                         $rndseed = $record{"resource.$partid.rndseed"};
                   2266:                     }
1.257     albertel 2267: 		    if($env{'form.checkPlag'}){
1.151     albertel 2268: 			my ($oname,$odom,$ocrsid,$oessay,$osim)=
1.426     albertel 2269: 			    &most_similar($uname,$udom,$subval,\%old_essays);
1.151     albertel 2270: 			if ($osim) {
                   2271: 			    $osim=int($osim*100.0);
1.426     albertel 2272: 			    my %old_course_desc = 
                   2273: 				&Apache::lonnet::coursedescription($ocrsid,
                   2274: 								   {'one_time' => 1});
                   2275: 
1.596.2.2  raeburn  2276:                             if ($hide eq 'anon') {
1.596     raeburn  2277:                                 $similar='<hr /><span class="LC_warning">'.&mt("Essay was found to be similar to another essay submitted for this assignment.").'<br />'.
                   2278:                                          &mt('As the current submission is for an anonymous survey, no other details are available.').'</span><hr />';
                   2279:                             } else {
                   2280: 			        $similar="<hr /><h3><span class=\"LC_warning\">".
                   2281: 				    &mt('Essay is [_1]% similar to an essay by [_2] in course [_3] (course id [_4]:[_5])',
                   2282: 				        $osim,
                   2283: 				        &Apache::loncommon::plainname($oname,$odom).' ('.$oname.':'.$odom.')',
                   2284: 				        $old_course_desc{'description'},
                   2285: 				        $old_course_desc{'num'},
                   2286: 				        $old_course_desc{'domain'}).
                   2287: 				    '</span></h3><blockquote><i>'.
                   2288: 				    &keywords_highlight($oessay).
                   2289: 				    '</i></blockquote><hr />';
                   2290:                             }
1.151     albertel 2291: 			}
1.150     albertel 2292: 		    }
1.596.2.2  raeburn  2293: 		    my $order=&get_order($partid,$respid,$symb,$uname,$udom,
                   2294:                                          undef,$type,$trial,$rndseed);
1.257     albertel 2295: 		    if ($env{'form.lastSub'} eq 'lastonly' || 
                   2296: 			($env{'form.lastSub'} eq 'hdgrade' && 
1.377     albertel 2297: 			 $$handgrade{$$part[0].'_'.$$part[1]} eq 'yes')) {
1.324     albertel 2298: 			my $display_part=&get_display_part($partid,$symb);
1.577     bisitz   2299:                         $lastsubonly.='<div class="LC_grade_submission_part">'.
                   2300:                             '<b>'.&mt('Part: [_1]',$display_part).'</b>'.
                   2301:                             ' <span class="LC_internal_info">'.
1.596.2.4  raeburn  2302:                             '('.&mt('Response ID: [_1]',$respid).')'.
                   2303:                             '</span>&nbsp; &nbsp;';
1.313     banghart 2304: 			my $files=&get_submitted_files($udom,$uname,$partid,$respid,\%record);
                   2305: 			if (@$files) {
1.596.2.2  raeburn  2306:                             if ($hide eq 'anon') {
1.596     raeburn  2307:                                 $lastsubonly.='<br />'.&mt('[quant,_1,file] uploaded to this anonymous survey',scalar(@{$files}));
                   2308:                             } else {
                   2309:                                 $lastsubonly.='<br /><span class="LC_warning">'.&mt('Like all files provided by users, this file may contain viruses').'</span><br />';
                   2310:                                 foreach my $file (@$files) {
                   2311:                                     &Apache::lonnet::allowuploaded('/adm/grades',$file);
                   2312:                                     $lastsubonly.='<br /><a href="'.$file.'?rawmode=1" target="lonGRDs"><img src="'.&Apache::loncommon::icon($file).'" border="0" /> '.$file.'</a>';
                   2313:                                 }
                   2314:                             }
1.236     albertel 2315: 			    $lastsubonly.='<br />';
1.41      ng       2316: 			}
1.596.2.2  raeburn  2317:                         if ($hide eq 'anon') {
1.596     raeburn  2318:                             $lastsubonly.='<b>'.&mt('Anonymous Survey').'</b>'; 
                   2319:                         } else {
                   2320: 			    $lastsubonly.='<b>'.&mt('Submitted Answer:').' </b>'.
                   2321: 			        &cleanRecord($subval,$responsetype,$symb,$partid,
1.596.2.2  raeburn  2322: 					     $respid,\%record,$order,undef,$uname,$udom,$type,$trial,$rndseed);
1.596     raeburn  2323:                         }
1.151     albertel 2324: 			if ($similar) {$lastsubonly.="<br /><br />$similar\n";}
1.468     albertel 2325: 			$lastsubonly.='</div>';
1.41      ng       2326: 		    }
                   2327: 		}
                   2328: 	    }
1.588     bisitz   2329: 	    $lastsubonly.='</div>'."\n"; # End: LC_grade_submissions_body
1.151     albertel 2330: 	}
                   2331: 	$request->print($lastsubonly);
1.468     albertel 2332:    } elsif ($env{'form.lastSub'} eq 'datesub') {
1.324     albertel 2333: 	my (undef,$responseType,undef,$parts) = &showResourceInfo($symb);
1.148     albertel 2334: 	$request->print(&displaySubByDates($symb,\%record,$parts,$responseType,$checkIcon,$uname,$udom));
1.257     albertel 2335:     } elsif ($env{'form.lastSub'} =~ /^(last|all)$/) {
1.41      ng       2336: 	$request->print(&Apache::loncommon::get_previous_attempt($symb,$uname,$udom,
1.257     albertel 2337: 								 $env{'request.course.id'},
1.44      ng       2338: 								 $last,'.submission',
                   2339: 								 'Apache::grades::keywords_highlight'));
1.41      ng       2340:     }
1.120     ng       2341: 
1.121     ng       2342:     $request->print('<input type="hidden" name="unamedom'.$counter.'" value="'.$uname.':'
                   2343: 	.$udom.'" />'."\n");
1.44      ng       2344:     # return if view submission with no grading option
1.257     albertel 2345:     if ($env{'form.showgrading'} eq '' || (!&canmodify($usec))) {
1.120     ng       2346: 	my $toGrade.='<input type="button" value="Grade Student" '.
1.589     bisitz   2347: 	    'onclick="javascript:checksubmit(this.form,\'Grade Student\',\''
1.417     albertel 2348: 	    .$counter.'\');" target="_self" /> &nbsp;'."\n" if (&canmodify($usec));
1.468     albertel 2349: 	$toGrade.='</div>'."\n";
1.257     albertel 2350: 	if (($env{'form.command'} eq 'submission') || 
                   2351: 	    ($env{'form.command'} eq 'processGroup' && $counter == $total)) {
1.324     albertel 2352: 	    $toGrade.='</form>'.&show_grading_menu_form($symb); 
1.169     albertel 2353: 	}
1.180     albertel 2354: 	$request->print($toGrade);
1.41      ng       2355: 	return;
1.180     albertel 2356:     } else {
1.468     albertel 2357: 	$request->print('</div>'."\n");
1.41      ng       2358:     }
1.33      ng       2359: 
1.121     ng       2360:     # essay grading message center
1.257     albertel 2361:     if ($env{'form.handgrade'} eq 'yes') {
1.468     albertel 2362: 	my $result='<div class="LC_grade_message_center">';
                   2363:     
                   2364: 	$result.='<div class="LC_grade_message_center_header">'.
                   2365: 	    &mt('Send Message').'</div><div class="LC_grade_message_center_body">';
1.257     albertel 2366: 	my ($lastname,$givenn) = split(/,/,$env{'form.fullname'});
1.118     ng       2367: 	my $msgfor = $givenn.' '.$lastname;
1.464     albertel 2368: 	if (scalar(@$col_fullnames) > 0) {
                   2369: 	    my $lastone = pop(@$col_fullnames);
                   2370: 	    $msgfor .= ', '.(join ', ',@$col_fullnames).' and '.$lastone.'.';
1.118     ng       2371: 	}
                   2372: 	$msgfor =~ s/\'/\\'/g; #' stupid emacs - no! javascript
1.468     albertel 2373: 	$result.='<input type="hidden" name="includemsg'.$counter.'" value="" />'."\n".
1.121     ng       2374: 	    '<input type="hidden" name="newmsg'.$counter.'" value="" />'."\n";
                   2375: 	$result.='&nbsp;<a href="javascript:msgCenter(document.SCORE,'.$counter.
1.417     albertel 2376: 	    ',\''.$msgfor.'\');" target="_self">'.
1.464     albertel 2377: 	    &mt('Compose message to student').(scalar(@$col_fullnames) >= 1 ? 's' : '').'</a><label> ('.
1.350     albertel 2378: 	    &mt('incl. grades').' <input type="checkbox" name="withgrades'.$counter.'" /></label>)'.
1.118     ng       2379: 	    '<img src="'.$request->dir_config('lonIconsURL').
                   2380: 	    '/mailbkgrd.gif" width="14" height="10" name="mailicon'.$counter.'" />'."\n".
1.298     www      2381: 	    '<br />&nbsp;('.
1.468     albertel 2382: 	    &mt('Message will be sent when you click on Save &amp; Next below.').")\n";
                   2383: 	$result.='</div></div>';
1.121     ng       2384: 	$request->print($result);
1.118     ng       2385:     }
1.41      ng       2386: 
                   2387:     my %seen = ();
                   2388:     my @partlist;
1.129     ng       2389:     my @gradePartRespid;
1.375     albertel 2390:     my @part_response_id = &flatten_responseType($responseType);
1.585     bisitz   2391:     $request->print(
1.588     bisitz   2392:         '<div class="LC_Box">'
                   2393:        .'<h3 class="LC_hcell">'.&mt('Assign Grades').'</h3>'
1.585     bisitz   2394:     );
1.592     bisitz   2395:     $request->print(&gradeBox_start());
1.375     albertel 2396:     foreach my $part_response_id (@part_response_id) {
                   2397:     	my ($partid,$respid) = @{ $part_response_id };
                   2398: 	my $part_resp = join('_',@{ $part_response_id });
1.322     albertel 2399: 	next if ($seen{$partid} > 0);
1.41      ng       2400: 	$seen{$partid}++;
1.393     albertel 2401: 	next if ($$handgrade{$part_resp} ne 'yes' 
                   2402: 		 && $env{'form.lastSub'} eq 'hdgrade');
1.524     raeburn  2403: 	push(@partlist,$partid);
                   2404: 	push(@gradePartRespid,$partid.'.'.$respid);
1.322     albertel 2405: 	$request->print(&gradeBox($request,$symb,$uname,$udom,$counter,$partid,\%record));
1.41      ng       2406:     }
1.585     bisitz   2407:     $request->print(&gradeBox_end()); # </div>
                   2408:     $request->print('</div>');
1.468     albertel 2409: 
                   2410:     $request->print('<div class="LC_grade_info_links">');
                   2411:     $request->print('</div>');
                   2412: 
1.45      ng       2413:     $result='<input type="hidden" name="partlist'.$counter.
                   2414: 	'" value="'.(join ":",@partlist).'" />'."\n";
1.129     ng       2415:     $result.='<input type="hidden" name="gradePartRespid'.
                   2416: 	'" value="'.(join ":",@gradePartRespid).'" />'."\n" if ($counter == 0);
1.45      ng       2417:     my $ctr = 0;
                   2418:     while ($ctr < scalar(@partlist)) {
                   2419: 	$result.='<input type="hidden" name="partid'.$counter.'_'.$ctr.'" value="'.
                   2420: 	    $partlist[$ctr].'" />'."\n";
                   2421: 	$ctr++;
                   2422:     }
1.468     albertel 2423:     $request->print($result.''."\n");
1.41      ng       2424: 
1.441     www      2425: # Done with printing info for one student
                   2426: 
1.468     albertel 2427:     $request->print('</div>');#LC_grade_show_user
1.441     www      2428: 
                   2429: 
1.41      ng       2430:     # print end of form
                   2431:     if ($counter == $total) {
1.592     bisitz   2432:         my $endform='<br /><hr /><table border="0"><tr><td>'."\n";
1.485     albertel 2433: 	$endform.='<input type="button" value="'.&mt('Save &amp; Next').'" '.
1.589     bisitz   2434: 	    'onclick="javascript:checksubmit(this.form,\'Save & Next\','.
1.417     albertel 2435: 	    $total.','.scalar(@partlist).');" target="_self" /> &nbsp;'."\n";
1.119     ng       2436: 	my $ntstu ='<select name="NTSTU">'.
                   2437: 	    '<option>1</option><option>2</option>'.
                   2438: 	    '<option>3</option><option>5</option>'.
                   2439: 	    '<option>7</option><option>10</option></select>'."\n";
1.257     albertel 2440: 	my $nsel = ($env{'form.NTSTU'} ne '' ? $env{'form.NTSTU'} : '1');
1.401     albertel 2441: 	$ntstu =~ s/<option>$nsel</<option selected="selected">$nsel</;
1.578     raeburn  2442:         $endform.=&mt('[_1]student(s)',$ntstu);
1.485     albertel 2443: 	$endform.='&nbsp;&nbsp;<input type="button" value="'.&mt('Previous').'" '.
1.589     bisitz   2444: 	    'onclick="javascript:checksubmit(this.form,\'Previous\');" target="_self" /> &nbsp;'."\n".
1.485     albertel 2445: 	    '<input type="button" value="'.&mt('Next').'" '.
1.589     bisitz   2446: 	    'onclick="javascript:checksubmit(this.form,\'Next\');" target="_self" /> &nbsp;';
1.592     bisitz   2447:         $endform.='<span class="LC_warning">'.
                   2448:                   &mt('(Next and Previous (student) do not save the scores.)').
                   2449:                   '</span>'."\n" ;
1.349     albertel 2450:         $endform.="<input type='hidden' value='".&get_increment().
1.348     bowersj2 2451:             "' name='increment' />";
1.485     albertel 2452: 	$endform.='</td></tr></table></form>';
1.324     albertel 2453: 	$endform.=&show_grading_menu_form($symb);
1.41      ng       2454: 	$request->print($endform);
                   2455:     }
                   2456:     return '';
1.38      ng       2457: }
                   2458: 
1.464     albertel 2459: sub check_collaborators {
                   2460:     my ($symb,$uname,$udom,$record,$handgrade,$counter) = @_;
                   2461:     my ($result,@col_fullnames);
                   2462:     my ($classlist,undef,$fullname) = &getclasslist('all','0');
                   2463:     foreach my $part (keys(%$handgrade)) {
                   2464: 	my $ncol = &Apache::lonnet::EXT('resource.'.$part.
                   2465: 					'.maxcollaborators',
                   2466: 					$symb,$udom,$uname);
                   2467: 	next if ($ncol <= 0);
                   2468: 	$part =~ s/\_/\./g;
                   2469: 	next if ($record->{'resource.'.$part.'.collaborators'} eq '');
                   2470: 	my (@good_collaborators, @bad_collaborators);
                   2471: 	foreach my $possible_collaborator
1.596.2.4  raeburn  2472: 	    (split(/[,;\s]+/,$record->{'resource.'.$part.'.collaborators'})) { 
1.464     albertel 2473: 	    $possible_collaborator =~ s/[\$\^\(\)]//g;
                   2474: 	    next if ($possible_collaborator eq '');
1.596.2.8  raeburn  2475: 	    my ($co_name,$co_dom) = split(/:/,$possible_collaborator);
1.464     albertel 2476: 	    $co_dom = $udom if (! defined($co_dom) || $co_dom =~ /^domain$/i);
                   2477: 	    next if ($co_name eq $uname && $co_dom eq $udom);
                   2478: 	    # Doing this grep allows 'fuzzy' specification
                   2479: 	    my @matches = grep(/^\Q$co_name\E:\Q$co_dom\E$/i, 
                   2480: 			       keys(%$classlist));
                   2481: 	    if (! scalar(@matches)) {
                   2482: 		push(@bad_collaborators, $possible_collaborator);
                   2483: 	    } else {
                   2484: 		push(@good_collaborators, @matches);
                   2485: 	    }
                   2486: 	}
                   2487: 	if (scalar(@good_collaborators) != 0) {
1.596.2.8  raeburn  2488: 	    $result.='<br />'.&mt('Collaborators:').'<ol>';
1.464     albertel 2489: 	    foreach my $name (@good_collaborators) {
                   2490: 		my ($lastname,$givenn) = split(/,/,$$fullname{$name});
                   2491: 		push(@col_fullnames, $givenn.' '.$lastname);
1.596.2.4  raeburn  2492: 		$result.='<li>'.$fullname->{$name}.'</li>';
1.464     albertel 2493: 	    }
1.596.2.4  raeburn  2494: 	    $result.='</ol><br />'."\n";
1.466     albertel 2495: 	    my ($part)=split(/\./,$part);
1.464     albertel 2496: 	    $result.='<input type="hidden" name="collaborator'.$counter.
                   2497: 		'" value="'.$part.':'.(join ':',@good_collaborators).'" />'.
                   2498: 		"\n";
                   2499: 	}
                   2500: 	if (scalar(@bad_collaborators) > 0) {
1.466     albertel 2501: 	    $result.='<div class="LC_warning">';
1.464     albertel 2502: 	    $result.=&mt('This student has submitted [quant,_1,invalid collaborator]: [_2]',scalar(@bad_collaborators),join(', ',@bad_collaborators));
                   2503: 	    $result .= '</div>';
                   2504: 	}         
                   2505: 	if (scalar(@bad_collaborators > $ncol)) {
1.466     albertel 2506: 	    $result .= '<div class="LC_warning">';
1.464     albertel 2507: 	    $result .= &mt('This student has submitted too many '.
                   2508: 		'collaborators.  Maximum is [_1].',$ncol);
                   2509: 	    $result .= '</div>';
                   2510: 	}
                   2511:     }
                   2512:     return ($result,$fullname,\@col_fullnames);
                   2513: }
                   2514: 
1.44      ng       2515: #--- Retrieve the last submission for all the parts
1.38      ng       2516: sub get_last_submission {
1.119     ng       2517:     my ($returnhash)=@_;
1.596     raeburn  2518:     my (@string,$timestamp,%lasthidden);
1.119     ng       2519:     if ($$returnhash{'version'}) {
1.46      ng       2520: 	my %lasthash=();
                   2521: 	my ($version);
1.119     ng       2522: 	for ($version=1;$version<=$$returnhash{'version'};$version++) {
1.397     albertel 2523: 	    foreach my $key (sort(split(/\:/,
                   2524: 					$$returnhash{$version.':keys'}))) {
                   2525: 		$lasthash{$key}=$$returnhash{$version.':'.$key};
                   2526: 		$timestamp = 
1.545     raeburn  2527: 		    &Apache::lonlocal::locallocaltime($$returnhash{$version.':timestamp'});
1.46      ng       2528: 	    }
                   2529: 	}
1.596.2.2  raeburn  2530:         my (%typeparts,%randombytry);
1.596     raeburn  2531:         my $showsurv = 
                   2532:             &Apache::lonnet::allowed('vas',$env{'request.course.id'});
                   2533:         foreach my $key (sort(keys(%lasthash))) {
                   2534:             if ($key =~ /\.type$/) {
                   2535:                 if (($lasthash{$key} eq 'anonsurvey') || 
1.596.2.2  raeburn  2536:                     ($lasthash{$key} eq 'anonsurveycred') ||
                   2537:                     ($lasthash{$key} eq 'randomizetry')) {
1.596     raeburn  2538:                     my ($ign,@parts) = split(/\./,$key);
                   2539:                     pop(@parts);
1.596.2.3  raeburn  2540:                     my $id = join('.',@parts);
1.596.2.2  raeburn  2541:                     if ($lasthash{$key} eq 'randomizetry') {
                   2542:                         $randombytry{$ign.'.'.$id} = $lasthash{$key};
                   2543:                     } else {
                   2544:                         unless ($showsurv) {
                   2545:                             $typeparts{$ign.'.'.$id} = $lasthash{$key};
                   2546:                         }
1.596     raeburn  2547:                     }
                   2548:                     delete($lasthash{$key});
                   2549:                 }
                   2550:             }
                   2551:         }
                   2552:         my @hidden = keys(%typeparts);
1.596.2.2  raeburn  2553:         my @randomize = keys(%randombytry);
1.397     albertel 2554: 	foreach my $key (keys(%lasthash)) {
                   2555: 	    next if ($key !~ /\.submission$/);
1.596     raeburn  2556:             my $hide;
                   2557:             if (@hidden) {
                   2558:                 foreach my $id (@hidden) {
                   2559:                     if ($key =~ /^\Q$id\E/) {
1.596.2.2  raeburn  2560:                         $hide = 'anon';
1.596     raeburn  2561:                         last;
                   2562:                     }
                   2563:                 }
                   2564:             }
1.596.2.2  raeburn  2565:             unless ($hide) {
                   2566:                 if (@randomize) {
                   2567:                     foreach my $id (@hidden) {
                   2568:                         if ($key =~ /^\Q$id\E/) {
                   2569:                             $hide = 'rand';
                   2570:                             last;
                   2571:                         }
                   2572:                     }
                   2573:                 }
                   2574:             }
1.397     albertel 2575: 	    my ($partid,$foo) = split(/submission$/,$key);
                   2576: 	    my $draft  = $lasthash{$partid.'awarddetail'} eq 'DRAFT' ?
1.398     albertel 2577: 		'<span class="LC_warning">Draft Copy</span> ' : '';
1.596     raeburn  2578: 	    push(@string, join(':', $key, $hide, $draft.$lasthash{$key}));
1.41      ng       2579: 	}
                   2580:     }
1.397     albertel 2581:     if (!@string) {
                   2582: 	$string[0] =
1.539     riegler  2583: 	    '<span class="LC_warning">'.&mt('Nothing submitted - no attempts.').'</span>';
1.397     albertel 2584:     }
                   2585:     return (\@string,\$timestamp);
1.38      ng       2586: }
1.35      ng       2587: 
1.44      ng       2588: #--- High light keywords, with style choosen by user.
1.38      ng       2589: sub keywords_highlight {
1.44      ng       2590:     my $string    = shift;
1.257     albertel 2591:     my $size      = $env{'form.kwsize'} eq '0' ? '' : 'size='.$env{'form.kwsize'};
                   2592:     my $styleon   = $env{'form.kwstyle'} eq ''  ? '' : $env{'form.kwstyle'};
1.41      ng       2593:     (my $styleoff = $styleon) =~ s/\</\<\//;
1.257     albertel 2594:     my @keylist   = split(/[,\s+]/,$env{'form.keywords'});
1.398     albertel 2595:     foreach my $keyword (@keylist) {
                   2596: 	$string =~ s/\b\Q$keyword\E(\b|\.)/<font color\=$env{'form.kwclr'} $size\>$styleon$keyword$styleoff<\/font>/gi;
1.41      ng       2597:     }
                   2598:     return $string;
1.38      ng       2599: }
1.36      ng       2600: 
1.44      ng       2601: #--- Called from submission routine
1.38      ng       2602: sub processHandGrade {
1.41      ng       2603:     my ($request) = shift;
1.324     albertel 2604:     my $symb   = &get_symb($request);
                   2605:     my (undef,undef,$url) = &Apache::lonnet::decode_symb($symb);
1.257     albertel 2606:     my $button = $env{'form.gradeOpt'};
                   2607:     my $ngrade = $env{'form.NCT'};
                   2608:     my $ntstu  = $env{'form.NTSTU'};
1.301     albertel 2609:     my $cdom   = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   2610:     my $cnum   = $env{'course.'.$env{'request.course.id'}.'.num'};
                   2611: 
1.44      ng       2612:     if ($button eq 'Save & Next') {
                   2613: 	my $ctr = 0;
                   2614: 	while ($ctr < $ngrade) {
1.257     albertel 2615: 	    my ($uname,$udom) = split(/:/,$env{'form.unamedom'.$ctr});
1.324     albertel 2616: 	    my ($errorflag,$pts,$wgt) = &saveHandGrade($request,$symb,$uname,$udom,$ctr);
1.71      ng       2617: 	    if ($errorflag eq 'no_score') {
                   2618: 		$ctr++;
                   2619: 		next;
                   2620: 	    }
1.104     albertel 2621: 	    if ($errorflag eq 'not_allowed') {
1.398     albertel 2622: 		$request->print("<span class=\"LC_warning\">Not allowed to modify grades for $uname:$udom</span>");
1.104     albertel 2623: 		$ctr++;
                   2624: 		next;
                   2625: 	    }
1.257     albertel 2626: 	    my $includemsg = $env{'form.includemsg'.$ctr};
1.44      ng       2627: 	    my ($subject,$message,$msgstatus) = ('','','');
1.418     albertel 2628: 	    my $restitle = &Apache::lonnet::gettitle($symb);
                   2629:             my ($feedurl,$showsymb) =
                   2630: 		&get_feedurl_and_symb($symb,$uname,$udom);
                   2631: 	    my $messagetail;
1.62      albertel 2632: 	    if ($includemsg =~ /savemsg|newmsg\Q$ctr\E/) {
1.298     www      2633: 		$subject = $env{'form.msgsub'} if ($includemsg =~ /msgsub/);
1.295     www      2634: 		unless ($subject=~/\w/) { $subject=&mt('Grading Feedback'); }
1.386     raeburn  2635: 		$subject.=' ['.$restitle.']';
1.44      ng       2636: 		my (@msgnum) = split(/,/,$includemsg);
                   2637: 		foreach (@msgnum) {
1.257     albertel 2638: 		    $message.=$env{'form.'.$_} if ($_ =~ /savemsg|newmsg/ && $_ ne '');
1.44      ng       2639: 		}
1.80      ng       2640: 		$message =&Apache::lonfeedback::clear_out_html($message);
1.298     www      2641: 		if ($env{'form.withgrades'.$ctr}) {
                   2642: 		    $message.="\n\nPoint".($pts > 1 ? 's':'').' awarded = '.$pts.' out of '.$wgt;
1.386     raeburn  2643: 		    $messagetail = " for <a href=\"".
1.418     albertel 2644: 		                   $feedurl."?symb=$showsymb\">$env{'form.probTitle'}</a>";
1.386     raeburn  2645: 		}
                   2646: 		$msgstatus = 
                   2647:                     &Apache::lonmsg::user_normal_msg($uname,$udom,$subject,
                   2648: 						     $message.$messagetail,
1.418     albertel 2649:                                                      undef,$feedurl,undef,
1.386     raeburn  2650:                                                      undef,undef,$showsymb,
                   2651:                                                      $restitle);
1.574     bisitz   2652: 		$request->print('<br />'.&mt('Sending message to [_1]',$uname.':'.$udom).': '.
1.596.2.4  raeburn  2653: 				$msgstatus.'<br />');
1.44      ng       2654: 	    }
1.257     albertel 2655: 	    if ($env{'form.collaborator'.$ctr}) {
1.155     albertel 2656: 		my @collabstrs=&Apache::loncommon::get_env_multiple("form.collaborator$ctr");
1.150     albertel 2657: 		foreach my $collabstr (@collabstrs) {
                   2658: 		    my ($part,@collaborators) = split(/:/,$collabstr);
1.310     banghart 2659: 		    foreach my $collaborator (@collaborators) {
1.150     albertel 2660: 			my ($errorflag,$pts,$wgt) = 
1.324     albertel 2661: 			    &saveHandGrade($request,$symb,$collaborator,$udom,$ctr,
1.257     albertel 2662: 					   $env{'form.unamedom'.$ctr},$part);
1.150     albertel 2663: 			if ($errorflag eq 'not_allowed') {
1.362     albertel 2664: 			    $request->print("<span class=\"LC_error\">".&mt('Not allowed to modify grades for [_1]',"$collaborator:$udom")."</span>");
1.150     albertel 2665: 			    next;
1.418     albertel 2666: 			} elsif ($message ne '') {
                   2667: 			    my ($baseurl,$showsymb) = 
                   2668: 				&get_feedurl_and_symb($symb,$collaborator,
                   2669: 						      $udom);
                   2670: 			    if ($env{'form.withgrades'.$ctr}) {
                   2671: 				$messagetail = " for <a href=\"".
1.386     raeburn  2672:                                     $baseurl."?symb=$showsymb\">$env{'form.probTitle'}</a>";
1.150     albertel 2673: 			    }
1.418     albertel 2674: 			    $msgstatus = 
                   2675: 				&Apache::lonmsg::user_normal_msg($collaborator,$udom,$subject,$message.$messagetail,undef,$baseurl,undef,undef,undef,$showsymb,$restitle);
1.104     albertel 2676: 			}
1.44      ng       2677: 		    }
                   2678: 		}
                   2679: 	    }
                   2680: 	    $ctr++;
                   2681: 	}
                   2682:     }
                   2683: 
1.257     albertel 2684:     if ($env{'form.handgrade'} eq 'yes') {
1.119     ng       2685: 	# Keywords sorted in alphabatical order
1.257     albertel 2686: 	my $loginuser = $env{'user.name'}.':'.$env{'user.domain'};
1.119     ng       2687: 	my %keyhash = ();
1.257     albertel 2688: 	$env{'form.keywords'}           =~ s/,\s{0,}|\s+/ /g;
                   2689: 	$env{'form.keywords'}           =~ s/^\s+|\s+$//;
                   2690: 	my (@keywords) = sort(split(/\s+/,$env{'form.keywords'}));
                   2691: 	$env{'form.keywords'} = join(' ',@keywords);
                   2692: 	$keyhash{$symb.'_keywords'}     = $env{'form.keywords'};
                   2693: 	$keyhash{$symb.'_subject'}      = $env{'form.msgsub'};
                   2694: 	$keyhash{$loginuser.'_kwclr'}   = $env{'form.kwclr'};
                   2695: 	$keyhash{$loginuser.'_kwsize'}  = $env{'form.kwsize'};
                   2696: 	$keyhash{$loginuser.'_kwstyle'} = $env{'form.kwstyle'};
1.119     ng       2697: 
                   2698: 	# message center - Order of message gets changed. Blank line is eliminated.
1.257     albertel 2699: 	# New messages are saved in env for the next student.
1.119     ng       2700: 	# All messages are saved in nohist_handgrade.db
                   2701: 	my ($ctr,$idx) = (1,1);
1.257     albertel 2702: 	while ($ctr <= $env{'form.savemsgN'}) {
                   2703: 	    if ($env{'form.savemsg'.$ctr} ne '') {
                   2704: 		$keyhash{$symb.'_savemsg'.$idx} = $env{'form.savemsg'.$ctr};
1.119     ng       2705: 		$idx++;
                   2706: 	    }
                   2707: 	    $ctr++;
1.41      ng       2708: 	}
1.119     ng       2709: 	$ctr = 0;
                   2710: 	while ($ctr < $ngrade) {
1.257     albertel 2711: 	    if ($env{'form.newmsg'.$ctr} ne '') {
                   2712: 		$keyhash{$symb.'_savemsg'.$idx} = $env{'form.newmsg'.$ctr};
                   2713: 		$env{'form.savemsg'.$idx} = $env{'form.newmsg'.$ctr};
1.119     ng       2714: 		$idx++;
                   2715: 	    }
                   2716: 	    $ctr++;
1.41      ng       2717: 	}
1.257     albertel 2718: 	$env{'form.savemsgN'} = --$idx;
                   2719: 	$keyhash{$symb.'_savemsgN'} = $env{'form.savemsgN'};
1.119     ng       2720: 	my $putresult = &Apache::lonnet::put
1.301     albertel 2721: 	    ('nohist_handgrade',\%keyhash,$cdom,$cnum);
1.41      ng       2722:     }
1.44      ng       2723:     # Called by Save & Refresh from Highlight Attribute Window
1.257     albertel 2724:     my (undef,undef,$fullname) = &getclasslist($env{'form.section'},'1');
                   2725:     if ($env{'form.refresh'} eq 'on') {
1.86      ng       2726: 	my ($ctr,$total) = (0,0);
                   2727: 	while ($ctr < $ngrade) {
1.257     albertel 2728: 	    $total++ if  $env{'form.unamedom'.$ctr} ne '';
1.86      ng       2729: 	    $ctr++;
                   2730: 	}
1.257     albertel 2731: 	$env{'form.NTSTU'}=$ngrade;
1.86      ng       2732: 	$ctr = 0;
                   2733: 	while ($ctr < $total) {
1.257     albertel 2734: 	    my $processUser = $env{'form.unamedom'.$ctr};
                   2735: 	    ($env{'form.student'},$env{'form.userdom'}) = split(/:/,$processUser);
                   2736: 	    $env{'form.fullname'} = $$fullname{$processUser};
1.86      ng       2737: 	    &submission($request,$ctr,$total-1);
1.41      ng       2738: 	    $ctr++;
                   2739: 	}
                   2740: 	return '';
                   2741:     }
1.36      ng       2742: 
1.121     ng       2743: # Go directly to grade student - from submission or link from chart page
1.120     ng       2744:     if ($button eq 'Grade Student') {
1.324     albertel 2745: 	(undef,undef,$env{'form.handgrade'},undef,undef) = &showResourceInfo($symb);
1.257     albertel 2746: 	my $processUser = $env{'form.unamedom'.$env{'form.studentNo'}};
                   2747: 	($env{'form.student'},$env{'form.userdom'}) = split(/:/,$processUser);
                   2748: 	$env{'form.fullname'} = $$fullname{$processUser};
1.120     ng       2749: 	&submission($request,0,0);
                   2750: 	return '';
                   2751:     }
                   2752: 
1.44      ng       2753:     # Get the next/previous one or group of students
1.257     albertel 2754:     my $firststu = $env{'form.unamedom0'};
                   2755:     my $laststu = $env{'form.unamedom'.($ngrade-1)};
1.119     ng       2756:     my $ctr = 2;
1.41      ng       2757:     while ($laststu eq '') {
1.257     albertel 2758: 	$laststu  = $env{'form.unamedom'.($ngrade-$ctr)};
1.41      ng       2759: 	$ctr++;
                   2760: 	$laststu = $firststu if ($ctr > $ngrade);
                   2761:     }
1.44      ng       2762: 
1.41      ng       2763:     my (@parsedlist,@nextlist);
                   2764:     my ($nextflg) = 0;
1.524     raeburn  2765:     foreach my $item (sort 
1.294     albertel 2766: 	     {
                   2767: 		 if (lc($$fullname{$a}) ne lc($$fullname{$b})) {
                   2768: 		     return (lc($$fullname{$a}) cmp lc($$fullname{$b}));
                   2769: 		 }
                   2770: 		 return $a cmp $b;
                   2771: 	     } (keys(%$fullname))) {
1.41      ng       2772: 	if ($nextflg == 1 && $button =~ /Next$/) {
1.524     raeburn  2773: 	    push(@parsedlist,$item);
1.41      ng       2774: 	}
1.524     raeburn  2775: 	$nextflg = 1 if ($item eq $laststu);
1.41      ng       2776: 	if ($button eq 'Previous') {
1.524     raeburn  2777: 	    last if ($item eq $firststu);
                   2778: 	    push(@parsedlist,$item);
1.41      ng       2779: 	}
                   2780:     }
                   2781:     $ctr = 0;
                   2782:     @parsedlist = reverse @parsedlist if ($button eq 'Previous');
1.582     raeburn  2783:     my $res_error;
                   2784:     my ($partlist) = &response_type($symb,\$res_error);
                   2785:     if ($res_error) {
                   2786:         $request->print(&navmap_errormsg());
                   2787:         return;
                   2788:     }
1.41      ng       2789:     foreach my $student (@parsedlist) {
1.257     albertel 2790: 	my $submitonly=$env{'form.submitonly'};
1.41      ng       2791: 	my ($uname,$udom) = split(/:/,$student);
1.301     albertel 2792: 	
                   2793: 	if ($submitonly eq 'queued') {
                   2794: 	    my %queue_status = 
                   2795: 		&Apache::bridgetask::get_student_status($symb,$cdom,$cnum,
                   2796: 							$udom,$uname);
                   2797: 	    next if (!defined($queue_status{'gradingqueue'}));
                   2798: 	}
                   2799: 
1.156     albertel 2800: 	if ($submitonly =~ /^(yes|graded|incorrect)$/) {
1.257     albertel 2801: #	    my %record = &Apache::lonnet::restore($symb,$env{'request.course.id'},$udom,$uname);
1.324     albertel 2802: 	    my %status=&student_gradeStatus($symb,$udom,$uname,$partlist);
1.145     albertel 2803: 	    my $submitted = 0;
1.248     albertel 2804: 	    my $ungraded = 0;
                   2805: 	    my $incorrect = 0;
1.524     raeburn  2806: 	    foreach my $item (keys(%status)) {
                   2807: 		$submitted = 1 if ($status{$item} ne 'nothing');
                   2808: 		$ungraded = 1 if ($status{$item} =~ /^ungraded/);
                   2809: 		$incorrect = 1 if ($status{$item} =~ /^incorrect/);
                   2810: 		my ($foo,$partid,$foo1) = split(/\./,$item);
1.145     albertel 2811: 		if ($status{'resource.'.$partid.'.submitted_by'} ne '') {
                   2812: 		    $submitted = 0;
                   2813: 		}
1.41      ng       2814: 	    }
1.156     albertel 2815: 	    next if (!$submitted && ($submitonly eq 'yes' ||
                   2816: 				     $submitonly eq 'incorrect' ||
                   2817: 				     $submitonly eq 'graded'));
1.248     albertel 2818: 	    next if (!$ungraded && ($submitonly eq 'graded'));
                   2819: 	    next if (!$incorrect && $submitonly eq 'incorrect');
1.41      ng       2820: 	}
1.524     raeburn  2821: 	push(@nextlist,$student) if ($ctr < $ntstu);
1.129     ng       2822: 	last if ($ctr == $ntstu);
1.41      ng       2823: 	$ctr++;
                   2824:     }
1.36      ng       2825: 
1.41      ng       2826:     $ctr = 0;
                   2827:     my $total = scalar(@nextlist)-1;
1.39      ng       2828: 
1.524     raeburn  2829:     foreach (sort(@nextlist)) {
1.41      ng       2830: 	my ($uname,$udom,$submitter) = split(/:/);
1.257     albertel 2831: 	$env{'form.student'}  = $uname;
                   2832: 	$env{'form.userdom'}  = $udom;
                   2833: 	$env{'form.fullname'} = $$fullname{$_};
1.41      ng       2834: 	&submission($request,$ctr,$total);
                   2835: 	$ctr++;
                   2836:     }
                   2837:     if ($total < 0) {
1.485     albertel 2838: 	my $the_end = '<h3><span class="LC_info">'.&mt('LON-CAPA User Message').'</span></h3><br />'."\n";
1.596.2.4  raeburn  2839: 	$the_end.='<p>'.&mt('[_1]Message:[_2] No more students for this section or class.','<b>','</b>').'</p>'."\n";
1.485     albertel 2840: 	$the_end.=&mt('Click on the button below to return to the grading menu.').'<br /><br />'."\n";
1.324     albertel 2841: 	$the_end.=&show_grading_menu_form($symb);
1.41      ng       2842: 	$request->print($the_end);
                   2843:     }
                   2844:     return '';
1.38      ng       2845: }
1.36      ng       2846: 
1.44      ng       2847: #---- Save the score and award for each student, if changed
1.38      ng       2848: sub saveHandGrade {
1.324     albertel 2849:     my ($request,$symb,$stuname,$domain,$newflg,$submitter,$part) = @_;
1.342     banghart 2850:     my @version_parts;
1.104     albertel 2851:     my $usec = &Apache::lonnet::getsection($domain,$stuname,
1.257     albertel 2852: 					   $env{'request.course.id'});
1.104     albertel 2853:     if (!&canmodify($usec)) { return('not_allowed'); }
1.337     banghart 2854:     my %record = &Apache::lonnet::restore($symb,$env{'request.course.id'},$domain,$stuname);
1.251     banghart 2855:     my @parts_graded;
1.77      ng       2856:     my %newrecord  = ();
                   2857:     my ($pts,$wgt) = ('','');
1.269     raeburn  2858:     my %aggregate = ();
                   2859:     my $aggregateflag = 0;
1.301     albertel 2860:     my @parts = split(/:/,$env{'form.partlist'.$newflg});
                   2861:     foreach my $new_part (@parts) {
1.337     banghart 2862: 	#collaborator ($submi may vary for different parts
1.259     banghart 2863: 	if ($submitter && $new_part ne $part) { next; }
                   2864: 	my $dropMenu = $env{'form.GD_SEL'.$newflg.'_'.$new_part};
1.125     ng       2865: 	if ($dropMenu eq 'excused') {
1.259     banghart 2866: 	    if ($record{'resource.'.$new_part.'.solved'} ne 'excused') {
                   2867: 		$newrecord{'resource.'.$new_part.'.solved'} = 'excused';
                   2868: 		if (exists($record{'resource.'.$new_part.'.awarded'})) {
                   2869: 		    $newrecord{'resource.'.$new_part.'.awarded'} = '';
1.58      albertel 2870: 		}
1.364     banghart 2871: 	        $newrecord{'resource.'.$new_part.'.regrader'}="$env{'user.name'}:$env{'user.domain'}";
1.58      albertel 2872: 	    }
1.125     ng       2873: 	} elsif ($dropMenu eq 'reset status'
1.259     banghart 2874: 		 && exists($record{'resource.'.$new_part.'.solved'})) { #don't bother if no old records -> no attempts
1.524     raeburn  2875: 	    foreach my $key (keys(%record)) {
1.259     banghart 2876: 		if ($key=~/^resource\.\Q$new_part\E\./) { $newrecord{$key} = ''; }
1.197     albertel 2877: 	    }
1.259     banghart 2878: 	    $newrecord{'resource.'.$new_part.'.regrader'}=
1.257     albertel 2879: 		"$env{'user.name'}:$env{'user.domain'}";
1.270     albertel 2880:             my $totaltries = $record{'resource.'.$part.'.tries'};
                   2881: 
                   2882:             my %last_resets = &get_last_resets($symb,$env{'request.course.id'},
                   2883: 					       [$new_part]);
                   2884:             my $aggtries =$totaltries;
1.269     raeburn  2885:             if ($last_resets{$new_part}) {
1.270     albertel 2886:                 $aggtries = &get_num_tries(\%record,$last_resets{$new_part},
                   2887: 					   $new_part);
1.269     raeburn  2888:             }
1.270     albertel 2889: 
                   2890:             my $solvedstatus = $record{'resource.'.$new_part.'.solved'};
1.269     raeburn  2891:             if ($aggtries > 0) {
1.327     albertel 2892:                 &decrement_aggs($symb,$new_part,\%aggregate,$aggtries,$totaltries,$solvedstatus);
1.269     raeburn  2893:                 $aggregateflag = 1;
                   2894:             }
1.125     ng       2895: 	} elsif ($dropMenu eq '') {
1.259     banghart 2896: 	    $pts = ($env{'form.GD_BOX'.$newflg.'_'.$new_part} ne '' ? 
                   2897: 		    $env{'form.GD_BOX'.$newflg.'_'.$new_part} : 
                   2898: 		    $env{'form.RADVAL'.$newflg.'_'.$new_part});
                   2899: 	    if ($pts eq '' && $env{'form.GD_SEL'.$newflg.'_'.$new_part} eq '') {
1.153     albertel 2900: 		next;
                   2901: 	    }
1.259     banghart 2902: 	    $wgt = $env{'form.WGT'.$newflg.'_'.$new_part} eq '' ? 1 : 
                   2903: 		$env{'form.WGT'.$newflg.'_'.$new_part};
1.41      ng       2904: 	    my $partial= $pts/$wgt;
1.259     banghart 2905: 	    if ($partial eq $record{'resource.'.$new_part.'.awarded'}) {
1.153     albertel 2906: 		#do not update score for part if not changed.
1.346     banghart 2907:                 &handback_files($request,$symb,$stuname,$domain,$newflg,$new_part,\%newrecord);
1.153     albertel 2908: 		next;
1.251     banghart 2909: 	    } else {
1.524     raeburn  2910: 	        push(@parts_graded,$new_part);
1.153     albertel 2911: 	    }
1.259     banghart 2912: 	    if ($record{'resource.'.$new_part.'.awarded'} ne $partial) {
                   2913: 		$newrecord{'resource.'.$new_part.'.awarded'}  = $partial;
1.153     albertel 2914: 	    }
1.259     banghart 2915: 	    my $reckey = 'resource.'.$new_part.'.solved';
1.41      ng       2916: 	    if ($partial == 0) {
1.153     albertel 2917: 		if ($record{$reckey} ne 'incorrect_by_override') {
                   2918: 		    $newrecord{$reckey} = 'incorrect_by_override';
                   2919: 		}
1.41      ng       2920: 	    } else {
1.153     albertel 2921: 		if ($record{$reckey} ne 'correct_by_override') {
                   2922: 		    $newrecord{$reckey} = 'correct_by_override';
                   2923: 		}
                   2924: 	    }	    
                   2925: 	    if ($submitter && 
1.259     banghart 2926: 		($record{'resource.'.$new_part.'.submitted_by'} ne $submitter)) {
                   2927: 		$newrecord{'resource.'.$new_part.'.submitted_by'} = $submitter;
1.41      ng       2928: 	    }
1.259     banghart 2929: 	    $newrecord{'resource.'.$new_part.'.regrader'}=
1.257     albertel 2930: 		"$env{'user.name'}:$env{'user.domain'}";
1.41      ng       2931: 	}
1.259     banghart 2932: 	# unless problem has been graded, set flag to version the submitted files
1.305     banghart 2933: 	unless ($record{'resource.'.$new_part.'.solved'} =~ /^correct_/  || 
                   2934: 	        $record{'resource.'.$new_part.'.solved'} eq 'incorrect_by_override' ||
                   2935: 	        $dropMenu eq 'reset status')
                   2936: 	   {
1.524     raeburn  2937: 	    push(@version_parts,$new_part);
1.259     banghart 2938: 	}
1.41      ng       2939:     }
1.301     albertel 2940:     my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   2941:     my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   2942: 
1.344     albertel 2943:     if (%newrecord) {
                   2944:         if (@version_parts) {
1.364     banghart 2945:             my @changed_keys = &version_portfiles(\%record, \@parts_graded, 
                   2946:                                 $env{'request.course.id'}, $symb, $domain, $stuname, \@version_parts);
1.344     albertel 2947: 	    @newrecord{@changed_keys} = @record{@changed_keys};
1.367     albertel 2948: 	    foreach my $new_part (@version_parts) {
                   2949: 		&handback_files($request,$symb,$stuname,$domain,$newflg,
                   2950: 				$new_part,\%newrecord);
                   2951: 	    }
1.259     banghart 2952:         }
1.44      ng       2953: 	&Apache::lonnet::cstore(\%newrecord,$symb,
1.257     albertel 2954: 				$env{'request.course.id'},$domain,$stuname);
1.380     albertel 2955: 	&check_and_remove_from_queue(\@parts,\%record,\%newrecord,$symb,
                   2956: 				     $cdom,$cnum,$domain,$stuname);
1.41      ng       2957:     }
1.269     raeburn  2958:     if ($aggregateflag) {
                   2959:         &Apache::lonnet::cinc('nohist_resourcetracker',\%aggregate,
1.301     albertel 2960: 			      $cdom,$cnum);
1.269     raeburn  2961:     }
1.301     albertel 2962:     return ('',$pts,$wgt);
1.36      ng       2963: }
1.322     albertel 2964: 
1.380     albertel 2965: sub check_and_remove_from_queue {
                   2966:     my ($parts,$record,$newrecord,$symb,$cdom,$cnum,$domain,$stuname) = @_;
                   2967:     my @ungraded_parts;
                   2968:     foreach my $part (@{$parts}) {
                   2969: 	if (    $record->{   'resource.'.$part.'.awarded'} eq ''
                   2970: 	     && $record->{   'resource.'.$part.'.solved' } ne 'excused'
                   2971: 	     && $newrecord->{'resource.'.$part.'.awarded'} eq ''
                   2972: 	     && $newrecord->{'resource.'.$part.'.solved' } ne 'excused'
                   2973: 		) {
                   2974: 	    push(@ungraded_parts, $part);
                   2975: 	}
                   2976:     }
                   2977:     if ( !@ungraded_parts ) {
                   2978: 	&Apache::bridgetask::remove_from_queue('gradingqueue',$symb,$cdom,
                   2979: 					       $cnum,$domain,$stuname);
                   2980:     }
                   2981: }
                   2982: 
1.337     banghart 2983: sub handback_files {
                   2984:     my ($request,$symb,$stuname,$domain,$newflg,$new_part,$newrecord) = @_;
1.517     raeburn  2985:     my $portfolio_root = '/userfiles/portfolio';
1.582     raeburn  2986:     my $res_error;
                   2987:     my ($partlist,$handgrade,$responseType) = &response_type($symb,\$res_error);
                   2988:     if ($res_error) {
                   2989:         $request->print('<br />'.&navmap_errormsg().'<br />');
                   2990:         return;
                   2991:     }
1.596.2.4  raeburn  2992:     my @handedback;
                   2993:     my $file_msg;
1.375     albertel 2994:     my @part_response_id = &flatten_responseType($responseType);
                   2995:     foreach my $part_response_id (@part_response_id) {
                   2996:     	my ($part_id,$resp_id) = @{ $part_response_id };
                   2997: 	my $part_resp = join('_',@{ $part_response_id });
1.596.2.4  raeburn  2998:         if (($env{'form.'.$newflg.'_'.$part_resp.'_countreturndoc'} =~ /^\d+$/) & ($new_part eq $part_id)) {
                   2999:             for (my $counter=1; $counter<=$env{'form.'.$newflg.'_'.$part_resp.'_countreturndoc'}; $counter++) {
1.337     banghart 3000:                 # if multiple files are uploaded names will be 'returndoc2','returndoc3'
1.596.2.4  raeburn  3001: 		if ($env{'form.'.$newflg.'_'.$part_resp.'_returndoc'.$counter}) {
                   3002:                     my $fname=$env{'form.'.$newflg.'_'.$part_resp.'_returndoc'.$counter.'.filename'};
1.338     banghart 3003:                     my ($directory,$answer_file) = 
1.596.2.4  raeburn  3004:                         ($env{'form.'.$newflg.'_'.$part_resp.'_origdoc'.$counter} =~ /^(.*?)([^\/]*)$/);
1.338     banghart 3005:                     my ($answer_name,$answer_ver,$answer_ext) =
                   3006: 		        &file_name_version_ext($answer_file);
1.355     banghart 3007: 		    my ($portfolio_path) = ($directory =~ /^.+$stuname\/portfolio(.*)/);
1.517     raeburn  3008:                     my $getpropath = 1;
1.596.2.12.2.  (raeburn 3009:):                     my ($dir_list,$listerror) =
                   3010:):                         &Apache::lonnet::dirlist($portfolio_root.$portfolio_path,
                   3011:):                                                  $domain,$stuname,$getpropath);
                   3012:): 		    my $version = &get_next_version($answer_name,$answer_ext,$dir_list);
1.355     banghart 3013:                     # fix file name
                   3014:                     my ($save_file_name) = (($directory.$answer_name.".$version.".$answer_ext) =~ /^.+\/${stuname}\/(.*)/);
                   3015:                     my $result=&Apache::lonnet::finishuserfileupload($stuname,$domain,
1.596.2.4  raeburn  3016:             	                                $newflg.'_'.$part_resp.'_returndoc'.$counter,
1.355     banghart 3017:             	                                $save_file_name);
1.337     banghart 3018:                     if ($result !~ m|^/uploaded/|) {
1.536     raeburn  3019:                         $request->print('<br /><span class="LC_error">'.
                   3020:                             &mt('An error occurred ([_1]) while trying to upload [_2].',
1.596.2.4  raeburn  3021:                                 $result,$newflg.'_'.$part_resp.'_returndoc'.$counter).
1.536     raeburn  3022:                                         '</span>');
1.356     banghart 3023:                     } else {
1.360     banghart 3024:                         # mark the file as read only
1.596.2.4  raeburn  3025:                         push(@handedback,$save_file_name);
1.367     albertel 3026: 			if (exists($$newrecord{"resource.$new_part.$resp_id.handback"})) {
                   3027: 			    $$newrecord{"resource.$new_part.$resp_id.handback"}.=',';
                   3028: 			}
                   3029:                         $$newrecord{"resource.$new_part.$resp_id.handback"} .= $save_file_name;
1.596.2.4  raeburn  3030: 			$file_msg.='<span class="LC_filename"><a href="/uploaded/'."$domain/$stuname/".$save_file_name.'">'.$save_file_name."</a></span> <br />";
1.367     albertel 3031: 
1.337     banghart 3032:                     }
1.596.2.4  raeburn  3033:                     $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 3034:                 }
                   3035:             }
                   3036:         }
1.596.2.4  raeburn  3037:     }
                   3038:     if (@handedback > 0) {
                   3039:         $request->print('<br />');
                   3040:         my @what = ($symb,$env{'request.course.id'},'handback');
                   3041:         &Apache::lonnet::mark_as_readonly($domain,$stuname,\@handedback,\@what);
                   3042:         my $user_lh = &Apache::loncommon::user_lang($stuname,$domain,$env{'request.course.id'});
                   3043:         my ($subject,$message);
                   3044:         if (scalar(@handedback) == 1) {
                   3045:             $subject = &mt_user($user_lh,'File Handed Back by Instructor');
                   3046:         } else {
                   3047:             $subject = &mt_user($user_lh,'Files Handed Back by Instructor');
                   3048:             $message = &mt_user($user_lh,'Files have been returned that were originally submitted in response to: ');
                   3049:         }
                   3050:         $message .= "<p><strong>".&Apache::lonnet::gettitle($symb)." </strong></p>";
                   3051:         $message .= &mt_user($user_lh,'The returned file(s) are named: [_1]',"<br />$file_msg <br />").
                   3052:                     &mt_user($user_lh,'The file(s) can be found in your [_1]portfolio[_2].','<a href="/adm/portfolio">','</a>');
                   3053:         my ($feedurl,$showsymb) =
                   3054:             &get_feedurl_and_symb($symb,$domain,$stuname);
                   3055:         my $restitle = &Apache::lonnet::gettitle($symb);
                   3056:         $subject .= ' '.&mt_user($user_lh,'(File Returned)').' ['.$restitle.']';
                   3057:         my $msgstatus =
                   3058:              &Apache::lonmsg::user_normal_msg($stuname,$domain,$subject,
                   3059:                  $message,undef,$feedurl,undef,undef,undef,$showsymb,
                   3060:                  $restitle);
                   3061:         if ($msgstatus) {
                   3062:             $request->print(&mt('Notification message status: [_1]','<span class="LC_info">'.$msgstatus.'</span>').'<br />');
                   3063:         }
                   3064:     }
1.338     banghart 3065:     return;
1.337     banghart 3066: }
                   3067: 
1.418     albertel 3068: sub get_feedurl_and_symb {
                   3069:     my ($symb,$uname,$udom) = @_;
                   3070:     my (undef,undef,$url) = &Apache::lonnet::decode_symb($symb);
                   3071:     $url = &Apache::lonnet::clutter($url);
                   3072:     my $encrypturl=&Apache::lonnet::EXT('resource.0.encrypturl',
                   3073: 					$symb,$udom,$uname);
                   3074:     if ($encrypturl =~ /^yes$/i) {
                   3075: 	&Apache::lonenc::encrypted(\$url,1);
                   3076: 	&Apache::lonenc::encrypted(\$symb,1);
                   3077:     }
                   3078:     return ($url,$symb);
                   3079: }
                   3080: 
1.313     banghart 3081: sub get_submitted_files {
                   3082:     my ($udom,$uname,$partid,$respid,$record) = @_;
                   3083:     my @files;
                   3084:     if ($$record{"resource.$partid.$respid.portfiles"}) {
                   3085:         my $file_url = '/uploaded/'.$udom.'/'.$uname.'/portfolio';
                   3086:         foreach my $file (split(',',$$record{"resource.$partid.$respid.portfiles"})) {
                   3087:     	    push(@files,$file_url.$file);
                   3088:         }
                   3089:     }
                   3090:     if ($$record{"resource.$partid.$respid.uploadedurl"}) {
                   3091:         push(@files,$$record{"resource.$partid.$respid.uploadedurl"});
                   3092:     }
                   3093:     return (\@files);
                   3094: }
1.322     albertel 3095: 
1.269     raeburn  3096: # ----------- Provides number of tries since last reset.
                   3097: sub get_num_tries {
                   3098:     my ($record,$last_reset,$part) = @_;
                   3099:     my $timestamp = '';
                   3100:     my $num_tries = 0;
                   3101:     if ($$record{'version'}) {
                   3102:         for (my $version=$$record{'version'};$version>=1;$version--) {
                   3103:             if (exists($$record{$version.':resource.'.$part.'.solved'})) {
                   3104:                 $timestamp = $$record{$version.':timestamp'};
                   3105:                 if ($timestamp > $last_reset) {
                   3106:                     $num_tries ++;
                   3107:                 } else {
                   3108:                     last;
                   3109:                 }
                   3110:             }
                   3111:         }
                   3112:     }
                   3113:     return $num_tries;
                   3114: }
                   3115: 
                   3116: # ----------- Determine decrements required in aggregate totals 
                   3117: sub decrement_aggs {
                   3118:     my ($symb,$part,$aggregate,$aggtries,$totaltries,$solvedstatus) = @_;
                   3119:     my %decrement = (
                   3120:                         attempts => 0,
                   3121:                         users => 0,
                   3122:                         correct => 0
                   3123:                     );
                   3124:     $decrement{'attempts'} = $aggtries;
                   3125:     if ($solvedstatus =~ /^correct/) {
                   3126:         $decrement{'correct'} = 1;
                   3127:     }
                   3128:     if ($aggtries == $totaltries) {
                   3129:         $decrement{'users'} = 1;
                   3130:     }
1.524     raeburn  3131:     foreach my $type (keys(%decrement)) {
1.269     raeburn  3132:         $$aggregate{$symb."\0".$part."\0".$type} = -$decrement{$type};
                   3133:     }
                   3134:     return;
                   3135: }
                   3136: 
                   3137: # ----------- Determine timestamps for last reset of aggregate totals for parts  
                   3138: sub get_last_resets {
1.270     albertel 3139:     my ($symb,$courseid,$partids) =@_;
                   3140:     my %last_resets;
1.269     raeburn  3141:     my $cdom = $env{'course.'.$courseid.'.domain'};
                   3142:     my $cname = $env{'course.'.$courseid.'.num'};
1.271     albertel 3143:     my @keys;
                   3144:     foreach my $part (@{$partids}) {
                   3145: 	push(@keys,"$symb\0$part\0resettime");
                   3146:     }
                   3147:     my %results=&Apache::lonnet::get('nohist_resourcetracker',\@keys,
                   3148: 				     $cdom,$cname);
                   3149:     foreach my $part (@{$partids}) {
                   3150: 	$last_resets{$part}=$results{"$symb\0$part\0resettime"};
1.269     raeburn  3151:     }
1.270     albertel 3152:     return %last_resets;
1.269     raeburn  3153: }
                   3154: 
1.251     banghart 3155: # ----------- Handles creating versions for portfolio files as answers
                   3156: sub version_portfiles {
1.343     banghart 3157:     my ($record, $parts_graded, $courseid, $symb, $domain, $stu_name, $v_flag) = @_;
1.263     banghart 3158:     my $version_parts = join('|',@$v_flag);
1.343     banghart 3159:     my @returned_keys;
1.255     banghart 3160:     my $parts = join('|', @$parts_graded);
1.517     raeburn  3161:     my $portfolio_root = '/userfiles/portfolio';
1.277     albertel 3162:     foreach my $key (keys(%$record)) {
1.259     banghart 3163:         my $new_portfiles;
1.263     banghart 3164:         if ($key =~ /^resource\.($version_parts)\./ && $key =~ /\.portfiles$/ ) {
1.342     banghart 3165:             my @versioned_portfiles;
1.367     albertel 3166:             my @portfiles = split(/\s*,\s*/,$$record{$key});
1.252     banghart 3167:             foreach my $file (@portfiles) {
1.306     banghart 3168:                 &Apache::lonnet::unmark_as_readonly($domain,$stu_name,[$symb,$env{'request.course.id'}],$file);
1.304     albertel 3169:                 my ($directory,$answer_file) =($file =~ /^(.*?)([^\/]*)$/);
                   3170: 		my ($answer_name,$answer_ver,$answer_ext) =
                   3171: 		    &file_name_version_ext($answer_file);
1.596.2.12.2.  (raeburn 3172:):                 my $getpropath = 1;
                   3173:):                 my ($dir_list,$listerror) =
                   3174:):                     &Apache::lonnet::dirlist($portfolio_root.$directory,$domain,
                   3175:):                                              $stu_name,$getpropath);
                   3176:):                 my $version = &get_next_version($answer_name,$answer_ext,$dir_list);
1.306     banghart 3177:                 my $new_answer = &version_selected_portfile($domain, $stu_name, $directory, $answer_file, $version);
                   3178:                 if ($new_answer ne 'problem getting file') {
1.342     banghart 3179:                     push(@versioned_portfiles, $directory.$new_answer);
1.306     banghart 3180:                     &Apache::lonnet::mark_as_readonly($domain,$stu_name,
1.367     albertel 3181:                         [$directory.$new_answer],
1.306     banghart 3182:                         [$symb,$env{'request.course.id'},'graded']);
1.259     banghart 3183:                 }
1.252     banghart 3184:             }
1.343     banghart 3185:             $$record{$key} = join(',',@versioned_portfiles);
                   3186:             push(@returned_keys,$key);
1.251     banghart 3187:         }
                   3188:     } 
1.343     banghart 3189:     return (@returned_keys);   
1.305     banghart 3190: }
                   3191: 
1.307     banghart 3192: sub get_next_version {
1.341     banghart 3193:     my ($answer_name, $answer_ext, $dir_list) = @_;
1.307     banghart 3194:     my $version;
1.596.2.12.2.  (raeburn 3195:):     if (ref($dir_list) eq 'ARRAY') {
                   3196:):         foreach my $row (@{$dir_list}) {
                   3197:):             my ($file) = split(/\&/,$row,2);
                   3198:):             my ($file_name,$file_version,$file_ext) =
                   3199:): 	        &file_name_version_ext($file);
                   3200:):             if (($file_name eq $answer_name) && 
                   3201:): 	        ($file_ext eq $answer_ext)) {
                   3202:):                 # gets here if filename and extension match, 
                   3203:):                 # regardless of version
1.307     banghart 3204:                 if ($file_version ne '') {
1.596.2.12.2.  (raeburn 3205:):                     # a versioned file is found  so save it for later
                   3206:):                     if ($file_version > $version) {
                   3207:): 		        $version = $file_version;
                   3208:):                     }
1.307     banghart 3209: 	        }
                   3210:             }
                   3211:         }
1.596.2.12.2.  (raeburn 3212:):     }
1.307     banghart 3213:     $version ++;
                   3214:     return($version);
                   3215: }
                   3216: 
1.305     banghart 3217: sub version_selected_portfile {
1.306     banghart 3218:     my ($domain,$stu_name,$directory,$file_name,$version) = @_;
                   3219:     my ($answer_name,$answer_ver,$answer_ext) =
                   3220:         &file_name_version_ext($file_name);
                   3221:     my $new_answer;
                   3222:     $env{'form.copy'} = &Apache::lonnet::getfile("/uploaded/$domain/$stu_name/portfolio$directory$file_name");
                   3223:     if($env{'form.copy'} eq '-1') {
                   3224:         $new_answer = 'problem getting file';
                   3225:     } else {
                   3226:         $new_answer = $answer_name.'.'.$version.'.'.$answer_ext;
                   3227:         my $copy_result = &Apache::lonnet::finishuserfileupload(
                   3228:                             $stu_name,$domain,'copy',
                   3229: 		        '/portfolio'.$directory.$new_answer);
                   3230:     }    
                   3231:     return ($new_answer);
1.251     banghart 3232: }
                   3233: 
1.304     albertel 3234: sub file_name_version_ext {
                   3235:     my ($file)=@_;
                   3236:     my @file_parts = split(/\./, $file);
                   3237:     my ($name,$version,$ext);
                   3238:     if (@file_parts > 1) {
                   3239: 	$ext=pop(@file_parts);
                   3240: 	if (@file_parts > 1 && $file_parts[-1] =~ /^\d+$/) {
                   3241: 	    $version=pop(@file_parts);
                   3242: 	}
                   3243: 	$name=join('.',@file_parts);
                   3244:     } else {
                   3245: 	$name=join('.',@file_parts);
                   3246:     }
                   3247:     return($name,$version,$ext);
                   3248: }
                   3249: 
1.44      ng       3250: #--------------------------------------------------------------------------------------
                   3251: #
                   3252: #-------------------------- Next few routines handles grading by section or whole class
                   3253: #
                   3254: #--- Javascript to handle grading by section or whole class
1.42      ng       3255: sub viewgrades_js {
                   3256:     my ($request) = shift;
                   3257: 
1.539     riegler  3258:     my $alertmsg = &mt('A number equal or greater than 0 is expected. Entered value = ');
1.41      ng       3259:     $request->print(<<VIEWJAVASCRIPT);
                   3260: <script type="text/javascript" language="javascript">
1.45      ng       3261:    function writePoint(partid,weight,point) {
1.125     ng       3262: 	var radioButton = document.classgrade["RADVAL_"+partid];
                   3263: 	var textbox = document.classgrade["TEXTVAL_"+partid];
1.42      ng       3264: 	if (point == "textval") {
1.125     ng       3265: 	    point = document.classgrade["TEXTVAL_"+partid].value;
1.109     matthew  3266: 	    if (isNaN(point) || parseFloat(point) < 0) {
1.539     riegler  3267: 		alert("$alertmsg"+parseFloat(point));
1.42      ng       3268: 		var resetbox = false;
                   3269: 		for (var i=0; i<radioButton.length; i++) {
                   3270: 		    if (radioButton[i].checked) {
                   3271: 			textbox.value = i;
                   3272: 			resetbox = true;
                   3273: 		    }
                   3274: 		}
                   3275: 		if (!resetbox) {
                   3276: 		    textbox.value = "";
                   3277: 		}
                   3278: 		return;
                   3279: 	    }
1.109     matthew  3280: 	    if (parseFloat(point) > parseFloat(weight)) {
                   3281: 		var resp = confirm("You entered a value ("+parseFloat(point)+
1.44      ng       3282: 				   ") greater than the weight for the part. Accept?");
                   3283: 		if (resp == false) {
                   3284: 		    textbox.value = "";
                   3285: 		    return;
                   3286: 		}
                   3287: 	    }
1.42      ng       3288: 	    for (var i=0; i<radioButton.length; i++) {
                   3289: 		radioButton[i].checked=false;
1.109     matthew  3290: 		if (parseFloat(point) == i) {
1.42      ng       3291: 		    radioButton[i].checked=true;
                   3292: 		}
                   3293: 	    }
1.41      ng       3294: 
1.42      ng       3295: 	} else {
1.125     ng       3296: 	    textbox.value = parseFloat(point);
1.42      ng       3297: 	}
1.41      ng       3298: 	for (i=0;i<document.classgrade.total.value;i++) {
1.125     ng       3299: 	    var user = document.classgrade["ctr"+i].value;
1.289     albertel 3300: 	    user = user.replace(new RegExp(':', 'g'),"_");
1.125     ng       3301: 	    var scorename = document.classgrade["GD_"+user+"_"+partid+"_awarded"];
                   3302: 	    var saveval   = document.classgrade["GD_"+user+"_"+partid+"_solved_s"].value;
                   3303: 	    var selname   = document.classgrade["GD_"+user+"_"+partid+"_solved"];
1.42      ng       3304: 	    if (saveval != "correct") {
                   3305: 		scorename.value = point;
1.43      ng       3306: 		if (selname[0].selected != true) {
                   3307: 		    selname[0].selected = true;
                   3308: 		}
1.42      ng       3309: 	    }
                   3310: 	}
1.125     ng       3311: 	document.classgrade["SELVAL_"+partid][0].selected = true;
1.42      ng       3312:     }
                   3313: 
                   3314:     function writeRadText(partid,weight) {
1.125     ng       3315: 	var selval   = document.classgrade["SELVAL_"+partid];
                   3316: 	var radioButton = document.classgrade["RADVAL_"+partid];
1.265     www      3317:         var override = document.classgrade["FORCE_"+partid].checked;
1.125     ng       3318: 	var textbox = document.classgrade["TEXTVAL_"+partid];
                   3319: 	if (selval[1].selected || selval[2].selected) {
1.42      ng       3320: 	    for (var i=0; i<radioButton.length; i++) {
                   3321: 		radioButton[i].checked=false;
                   3322: 
                   3323: 	    }
                   3324: 	    textbox.value = "";
                   3325: 
                   3326: 	    for (i=0;i<document.classgrade.total.value;i++) {
1.125     ng       3327: 		var user = document.classgrade["ctr"+i].value;
1.289     albertel 3328: 		user = user.replace(new RegExp(':', 'g'),"_");
1.125     ng       3329: 		var scorename = document.classgrade["GD_"+user+"_"+partid+"_awarded"];
                   3330: 		var saveval   = document.classgrade["GD_"+user+"_"+partid+"_solved_s"].value;
                   3331: 		var selname   = document.classgrade["GD_"+user+"_"+partid+"_solved"];
1.265     www      3332: 		if ((saveval != "correct") || override) {
1.42      ng       3333: 		    scorename.value = "";
1.125     ng       3334: 		    if (selval[1].selected) {
                   3335: 			selname[1].selected = true;
                   3336: 		    } else {
                   3337: 			selname[2].selected = true;
                   3338: 			if (Number(document.classgrade["GD_"+user+"_"+partid+"_tries"].value)) 
                   3339: 			{document.classgrade["GD_"+user+"_"+partid+"_tries"].value = '0';}
                   3340: 		    }
1.42      ng       3341: 		}
                   3342: 	    }
1.43      ng       3343: 	} else {
                   3344: 	    for (i=0;i<document.classgrade.total.value;i++) {
1.125     ng       3345: 		var user = document.classgrade["ctr"+i].value;
1.289     albertel 3346: 		user = user.replace(new RegExp(':', 'g'),"_");
1.125     ng       3347: 		var scorename = document.classgrade["GD_"+user+"_"+partid+"_awarded"];
                   3348: 		var saveval   = document.classgrade["GD_"+user+"_"+partid+"_solved_s"].value;
                   3349: 		var selname   = document.classgrade["GD_"+user+"_"+partid+"_solved"];
1.265     www      3350: 		if ((saveval != "correct") || override) {
1.125     ng       3351: 		    scorename.value = document.classgrade["GD_"+user+"_"+partid+"_awarded_s"].value;
1.43      ng       3352: 		    selname[0].selected = true;
                   3353: 		}
                   3354: 	    }
                   3355: 	}	    
1.42      ng       3356:     }
                   3357: 
                   3358:     function changeSelect(partid,user) {
1.125     ng       3359: 	var selval = document.classgrade["GD_"+user+'_'+partid+"_solved"];
                   3360: 	var textbox = document.classgrade["GD_"+user+'_'+partid+"_awarded"];
1.44      ng       3361: 	var point  = textbox.value;
1.125     ng       3362: 	var weight = document.classgrade["weight_"+partid].value;
1.44      ng       3363: 
1.109     matthew  3364: 	if (isNaN(point) || parseFloat(point) < 0) {
1.539     riegler  3365: 	    alert("$alertmsg"+parseFloat(point));
1.44      ng       3366: 	    textbox.value = "";
                   3367: 	    return;
                   3368: 	}
1.109     matthew  3369: 	if (parseFloat(point) > parseFloat(weight)) {
                   3370: 	    var resp = confirm("You entered a value ("+parseFloat(point)+
1.44      ng       3371: 			       ") greater than the weight of the part. Accept?");
                   3372: 	    if (resp == false) {
                   3373: 		textbox.value = "";
                   3374: 		return;
                   3375: 	    }
                   3376: 	}
1.42      ng       3377: 	selval[0].selected = true;
                   3378:     }
                   3379: 
                   3380:     function changeOneScore(partid,user) {
1.125     ng       3381: 	var selval = document.classgrade["GD_"+user+'_'+partid+"_solved"];
                   3382: 	if (selval[1].selected || selval[2].selected) {
                   3383: 	    document.classgrade["GD_"+user+'_'+partid+"_awarded"].value = "";
                   3384: 	    if (selval[2].selected) {
                   3385: 		document.classgrade["GD_"+user+'_'+partid+"_tries"].value = "0";
                   3386: 	    }
1.269     raeburn  3387:         }
1.42      ng       3388:     }
                   3389: 
                   3390:     function resetEntry(numpart) {
                   3391: 	for (ctpart=0;ctpart<numpart;ctpart++) {
1.125     ng       3392: 	    var partid = document.classgrade["partid_"+ctpart].value;
                   3393: 	    var radioButton = document.classgrade["RADVAL_"+partid];
                   3394: 	    var textbox = document.classgrade["TEXTVAL_"+partid];
                   3395: 	    var selval  = document.classgrade["SELVAL_"+partid];
1.42      ng       3396: 	    for (var i=0; i<radioButton.length; i++) {
                   3397: 		radioButton[i].checked=false;
                   3398: 
                   3399: 	    }
                   3400: 	    textbox.value = "";
                   3401: 	    selval[0].selected = true;
                   3402: 
                   3403: 	    for (i=0;i<document.classgrade.total.value;i++) {
1.125     ng       3404: 		var user = document.classgrade["ctr"+i].value;
1.289     albertel 3405: 		user = user.replace(new RegExp(':', 'g'),"_");
1.125     ng       3406: 		var resetscore = document.classgrade["GD_"+user+"_"+partid+"_awarded"];
                   3407: 		resetscore.value = document.classgrade["GD_"+user+"_"+partid+"_awarded_s"].value;
                   3408: 		var resettries = document.classgrade["GD_"+user+"_"+partid+"_tries"];
                   3409: 		resettries.value = document.classgrade["GD_"+user+"_"+partid+"_tries_s"].value;
                   3410: 		var saveselval   = document.classgrade["GD_"+user+"_"+partid+"_solved_s"].value;
                   3411: 		var selname   = document.classgrade["GD_"+user+"_"+partid+"_solved"];
1.42      ng       3412: 		if (saveselval == "excused") {
1.43      ng       3413: 		    if (selname[1].selected == false) { selname[1].selected = true;}
1.42      ng       3414: 		} else {
1.43      ng       3415: 		    if (selname[0].selected == false) {selname[0].selected = true};
1.42      ng       3416: 		}
                   3417: 	    }
1.41      ng       3418: 	}
1.42      ng       3419:     }
                   3420: 
1.41      ng       3421: </script>
                   3422: VIEWJAVASCRIPT
1.42      ng       3423: }
                   3424: 
1.44      ng       3425: #--- show scores for a section or whole class w/ option to change/update a score
1.42      ng       3426: sub viewgrades {
                   3427:     my ($request) = shift;
                   3428:     &viewgrades_js($request);
1.41      ng       3429: 
1.324     albertel 3430:     my ($symb) = &get_symb($request);
1.168     albertel 3431:     #need to make sure we have the correct data for later EXT calls, 
                   3432:     #thus invalidate the cache
                   3433:     &Apache::lonnet::devalidatecourseresdata(
1.257     albertel 3434:                  $env{'course.'.$env{'request.course.id'}.'.num'},
                   3435:                  $env{'course.'.$env{'request.course.id'}.'.domain'});
1.168     albertel 3436:     &Apache::lonnet::clear_EXT_cache_status();
                   3437: 
1.398     albertel 3438:     my $result='<h3><span class="LC_info">'.&mt('Manual Grading').'</span></h3>';
1.485     albertel 3439:     $result.='<h4>'.&mt('<b>Current Resource: </b>[_1]',$env{'form.probTitle'}).'</h4>'."\n";
1.41      ng       3440: 
                   3441:     #view individual student submission form - called using Javascript viewOneStudent
1.324     albertel 3442:     $result.=&jscriptNform($symb);
1.41      ng       3443: 
1.44      ng       3444:     #beginning of class grading form
1.442     banghart 3445:     my $stu_status = join(':',&Apache::loncommon::get_env_multiple('form.Status'));
1.41      ng       3446:     $result.= '<form action="/adm/grades" method="post" name="classgrade">'."\n".
1.418     albertel 3447: 	'<input type="hidden" name="symb"    value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
1.38      ng       3448: 	'<input type="hidden" name="command" value="editgrades" />'."\n".
1.432     banghart 3449: 	&build_section_inputs().
1.257     albertel 3450: 	'<input type="hidden" name="saveState" value="'.$env{'form.saveState'}.'" />'."\n".
1.442     banghart 3451: 	'<input type="hidden" name="Status" value="'.$env{'stu_status'}.'" />'."\n".
1.257     albertel 3452: 	'<input type="hidden" name="probTitle" value="'.$env{'form.probTitle'}.'" />'."\n";
1.72      ng       3453: 
1.560     raeburn  3454:     my ($common_header,$specific_header);
1.257     albertel 3455:     if ($env{'form.section'} eq 'all') {
1.560     raeburn  3456: 	$common_header = &mt('Assign Common Grade to Class');
                   3457:         $specific_header = &mt('Assign Grade to Specific Students in Class');
1.257     albertel 3458:     } elsif ($env{'form.section'} eq 'none') {
1.560     raeburn  3459:         $common_header = &mt('Assign Common Grade to Students in no Section');
                   3460: 	$specific_header = &mt('Assign Grade to Specific Students in no Section');
1.52      albertel 3461:     } else {
1.560     raeburn  3462:         my $section_display = join (", ",&Apache::loncommon::get_env_multiple('form.section'));
                   3463:         $common_header = &mt('Assign Common Grade to Students in Section(s) [_1]',$section_display);
                   3464: 	$specific_header = &mt('Assign Grade to Specific Students in Section(s) [_1]',$section_display);
1.52      albertel 3465:     }
1.560     raeburn  3466:     $result.= '<h3>'.$common_header.'</h3>'.&Apache::loncommon::start_data_table();
1.44      ng       3467:     #radio buttons/text box for assigning points for a section or class.
                   3468:     #handles different parts of a problem
1.582     raeburn  3469:     my $res_error;
                   3470:     my ($partlist,$handgrade,$responseType) = &response_type($symb,\$res_error);
                   3471:     if ($res_error) {
                   3472:         return &navmap_errormsg();
                   3473:     }
1.42      ng       3474:     my %weight = ();
                   3475:     my $ctsparts = 0;
1.45      ng       3476:     my %seen = ();
1.375     albertel 3477:     my @part_response_id = &flatten_responseType($responseType);
                   3478:     foreach my $part_response_id (@part_response_id) {
                   3479:     	my ($partid,$respid) = @{ $part_response_id };
                   3480: 	my $part_resp = join('_',@{ $part_response_id });
1.45      ng       3481: 	next if $seen{$partid};
                   3482: 	$seen{$partid}++;
1.375     albertel 3483: 	my $handgrade=$$handgrade{$part_resp};
1.42      ng       3484: 	my $wgt = &Apache::lonnet::EXT('resource.'.$partid.'.weight',$symb);
                   3485: 	$weight{$partid} = $wgt eq '' ? '1' : $wgt;
                   3486: 
1.324     albertel 3487: 	my $display_part=&get_display_part($partid,$symb);
1.485     albertel 3488: 	my $radio.='<table border="0"><tr>';  
1.41      ng       3489: 	my $ctr = 0;
1.42      ng       3490: 	while ($ctr<=$weight{$partid}) { # display radio buttons in a nice table 10 across
1.485     albertel 3491: 	    $radio.= '<td><label><input type="radio" name="RADVAL_'.$partid.'" '.
1.54      albertel 3492: 		'onclick="javascript:writePoint(\''.$partid.'\','.$weight{$partid}.
1.288     albertel 3493: 		','.$ctr.')" />'.$ctr."</label></td>\n";
1.41      ng       3494: 	    $result.=(($ctr+1)%10 == 0 ? '</tr><tr>' : '');
                   3495: 	    $ctr++;
                   3496: 	}
1.485     albertel 3497: 	$radio.='</tr></table>';
                   3498: 	my $line = '<input type="text" name="TEXTVAL_'.
1.589     bisitz   3499: 	    $partid.'" size="4" '.'onchange="javascript:writePoint(\''.
1.54      albertel 3500: 		$partid.'\','.$weight{$partid}.',\'textval\')" /> /'.
1.539     riegler  3501: 	    $weight{$partid}.' '.&mt('(problem weight)').'</td>'."\n";
                   3502: 	$line.= '<td><b>'.&mt('Grade Status').':</b><select name="SELVAL_'.$partid.'"'.
1.589     bisitz   3503: 	    'onchange="javascript:writeRadText(\''.$partid.'\','.
1.59      albertel 3504: 		$weight{$partid}.')"> '.
1.401     albertel 3505: 	    '<option selected="selected"> </option>'.
1.485     albertel 3506: 	    '<option value="excused">'.&mt('excused').'</option>'.
                   3507: 	    '<option value="reset status">'.&mt('reset status').'</option>'.
                   3508: 	    '</select></td>'.
                   3509:             '<td><label><input type="checkbox" name="FORCE_'.$partid.'" />'.&mt('Override "Correct"').'</label>';
                   3510: 	$line.='<input type="hidden" name="partid_'.
                   3511: 	    $ctsparts.'" value="'.$partid.'" />'."\n";
                   3512: 	$line.='<input type="hidden" name="weight_'.
                   3513: 	    $partid.'" value="'.$weight{$partid}.'" />'."\n";
                   3514: 
                   3515: 	$result.=
                   3516: 	    &Apache::loncommon::start_data_table_row()."\n".
1.577     bisitz   3517: 	    '<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 3518: 	    &Apache::loncommon::end_data_table_row()."\n";
1.42      ng       3519: 	$ctsparts++;
1.41      ng       3520:     }
1.474     albertel 3521:     $result.=&Apache::loncommon::end_data_table()."\n".
1.52      albertel 3522: 	'<input type="hidden" name="totalparts" value="'.$ctsparts.'" />';
1.485     albertel 3523:     $result.='<input type="button" value="'.&mt('Revert to Default').'" '.
1.589     bisitz   3524: 	'onclick="javascript:resetEntry('.$ctsparts.');" />';
1.41      ng       3525: 
1.44      ng       3526:     #table listing all the students in a section/class
                   3527:     #header of table
1.560     raeburn  3528:     $result.= '<h3>'.$specific_header.'</h3>'.
                   3529:               &Apache::loncommon::start_data_table().
                   3530: 	      &Apache::loncommon::start_data_table_header_row().
                   3531: 	      '<th>'.&mt('No.').'</th>'.
                   3532: 	      '<th>'.&nameUserString('header')."</th>\n";
1.582     raeburn  3533:     my $partserror;
                   3534:     my (@parts) = sort(&getpartlist($symb,\$partserror));
                   3535:     if ($partserror) {
                   3536:         return &navmap_errormsg();
                   3537:     }
1.324     albertel 3538:     my (undef,undef,$url)=&Apache::lonnet::decode_symb($symb);
1.269     raeburn  3539:     my @partids = ();
1.41      ng       3540:     foreach my $part (@parts) {
                   3541: 	my $display=&Apache::lonnet::metadata($url,$part.'.display');
1.539     riegler  3542:         my $narrowtext = &mt('Tries');
                   3543: 	$display =~ s|^Number of Attempts|$narrowtext <br />|; # makes the column narrower
1.41      ng       3544: 	if  (!$display) { $display = &Apache::lonnet::metadata($url,$part.'.name'); }
1.207     albertel 3545: 	my ($partid) = &split_part_type($part);
1.524     raeburn  3546:         push(@partids,$partid);
1.324     albertel 3547: 	my $display_part=&get_display_part($partid,$symb);
1.41      ng       3548: 	if ($display =~ /^Partial Credit Factor/) {
1.485     albertel 3549: 	    $result.='<th>'.
                   3550: 		&mt('Score Part: [_1]<br /> (weight = [_2])',
                   3551: 		    $display_part,$weight{$partid}).'</th>'."\n";
1.41      ng       3552: 	    next;
1.485     albertel 3553: 	    
1.207     albertel 3554: 	} else {
1.485     albertel 3555: 	    if ($display =~ /Problem Status/) {
                   3556: 		my $grade_status_mt = &mt('Grade Status');
                   3557: 		$display =~ s{Problem Status}{$grade_status_mt<br />};
                   3558: 	    }
                   3559: 	    my $part_mt = &mt('Part:');
                   3560: 	    $display =~s{\[Part: \Q$partid\E\]}{$part_mt $display_part};
1.41      ng       3561: 	}
1.485     albertel 3562: 
1.474     albertel 3563: 	$result.='<th>'.$display.'</th>'."\n";
1.41      ng       3564:     }
1.474     albertel 3565:     $result.=&Apache::loncommon::end_data_table_header_row();
1.44      ng       3566: 
1.270     albertel 3567:     my %last_resets = 
                   3568: 	&get_last_resets($symb,$env{'request.course.id'},\@partids);
1.269     raeburn  3569: 
1.41      ng       3570:     #get info for each student
1.44      ng       3571:     #list all the students - with points and grade status
1.257     albertel 3572:     my (undef,undef,$fullname) = &getclasslist($env{'form.section'},'1');
1.41      ng       3573:     my $ctr = 0;
1.294     albertel 3574:     foreach (sort 
                   3575: 	     {
                   3576: 		 if (lc($$fullname{$a}) ne lc($$fullname{$b})) {
                   3577: 		     return (lc($$fullname{$a}) cmp lc($$fullname{$b}));
                   3578: 		 }
                   3579: 		 return $a cmp $b;
                   3580: 	     } (keys(%$fullname))) {
1.126     ng       3581: 	$ctr++;
1.324     albertel 3582: 	$result.=&viewstudentgrade($symb,$env{'request.course.id'},
1.269     raeburn  3583: 				   $_,$$fullname{$_},\@parts,\%weight,$ctr,\%last_resets);
1.41      ng       3584:     }
1.474     albertel 3585:     $result.=&Apache::loncommon::end_data_table();
1.41      ng       3586:     $result.='<input type="hidden" name="total" value="'.$ctr.'" />'."\n";
1.485     albertel 3587:     $result.='<input type="button" value="'.&mt('Save').'" '.
1.589     bisitz   3588: 	'onclick="javascript:submit();" target="_self" /></form>'."\n";
1.96      albertel 3589:     if (scalar(%$fullname) eq 0) {
                   3590: 	my $colspan=3+scalar(@parts);
1.433     banghart 3591: 	my $section_display = join (", ",&Apache::loncommon::get_env_multiple('form.section'));
1.442     banghart 3592:         my $stu_status = join(' or ',&Apache::loncommon::get_env_multiple('form.Status'));
1.433     banghart 3593: 	$result='<span class="LC_warning">'.
1.485     albertel 3594: 	    &mt('There are no students in section(s) [_1] with enrollment status [_2] to modify or grade.',
1.442     banghart 3595: 	        $section_display, $stu_status).
1.433     banghart 3596: 	    '</span>';
1.96      albertel 3597:     }
1.324     albertel 3598:     $result.=&show_grading_menu_form($symb);
1.41      ng       3599:     return $result;
                   3600: }
                   3601: 
1.44      ng       3602: #--- call by previous routine to display each student
1.41      ng       3603: sub viewstudentgrade {
1.324     albertel 3604:     my ($symb,$courseid,$student,$fullname,$parts,$weight,$ctr,$last_resets) = @_;
1.44      ng       3605:     my ($uname,$udom) = split(/:/,$student);
                   3606:     my %record=&Apache::lonnet::restore($symb,$courseid,$udom,$uname);
1.269     raeburn  3607:     my %aggregates = (); 
1.474     albertel 3608:     my $result=&Apache::loncommon::start_data_table_row().'<td align="right">'.
1.233     albertel 3609: 	'<input type="hidden" name="ctr'.($ctr-1).'" value="'.$student.'" />'.
                   3610: 	"\n".$ctr.'&nbsp;</td><td>&nbsp;'.
1.44      ng       3611: 	'<a href="javascript:viewOneStudent(\''.$uname.'\',\''.$udom.
1.417     albertel 3612: 	'\');" target="_self">'.$fullname.'</a> '.
1.398     albertel 3613: 	'<span class="LC_internal_info">('.$uname.($env{'user.domain'} eq $udom ? '' : ':'.$udom).')</span></td>'."\n";
1.281     albertel 3614:     $student=~s/:/_/; # colon doen't work in javascript for names
1.63      albertel 3615:     foreach my $apart (@$parts) {
                   3616: 	my ($part,$type) = &split_part_type($apart);
1.41      ng       3617: 	my $score=$record{"resource.$part.$type"};
1.276     albertel 3618:         $result.='<td align="center">';
1.269     raeburn  3619:         my ($aggtries,$totaltries);
                   3620:         unless (exists($aggregates{$part})) {
1.270     albertel 3621: 	    $totaltries = $record{'resource.'.$part.'.tries'};
                   3622: 
                   3623: 	    $aggtries = $totaltries;
1.269     raeburn  3624:             if ($$last_resets{$part}) {  
1.270     albertel 3625:                 $aggtries = &get_num_tries(\%record,$$last_resets{$part},
                   3626: 					   $part);
                   3627:             }
1.269     raeburn  3628:             $result.='<input type="hidden" name="'.
                   3629:                 'GD_'.$student.'_'.$part.'_aggtries" value="'.$aggtries.'" />'."\n";
                   3630:             $result.='<input type="hidden" name="'.
                   3631:                 'GD_'.$student.'_'.$part.'_totaltries" value="'.$totaltries.'" />'."\n";
                   3632:             $aggregates{$part} = 1;
                   3633:         }
1.41      ng       3634: 	if ($type eq 'awarded') {
1.320     albertel 3635: 	    my $pts = $score eq '' ? '' : &compute_points($score,$$weight{$part});
1.42      ng       3636: 	    $result.='<input type="hidden" name="'.
1.89      albertel 3637: 		'GD_'.$student.'_'.$part.'_awarded_s" value="'.$pts.'" />'."\n";
1.233     albertel 3638: 	    $result.='<input type="text" name="'.
1.89      albertel 3639: 		'GD_'.$student.'_'.$part.'_awarded" '.
1.589     bisitz   3640:                 'onchange="javascript:changeSelect(\''.$part.'\',\''.$student.
1.44      ng       3641: 		'\')" value="'.$pts.'" size="4" /></td>'."\n";
1.41      ng       3642: 	} elsif ($type eq 'solved') {
                   3643: 	    my ($status,$foo)=split(/_/,$score,2);
                   3644: 	    $status = 'nothing' if ($status eq '');
1.89      albertel 3645: 	    $result.='<input type="hidden" name="'.'GD_'.$student.'_'.
1.54      albertel 3646: 		$part.'_solved_s" value="'.$status.'" />'."\n";
1.233     albertel 3647: 	    $result.='&nbsp;<select name="'.
1.89      albertel 3648: 		'GD_'.$student.'_'.$part.'_solved" '.
1.589     bisitz   3649:                 'onchange="javascript:changeOneScore(\''.$part.'\',\''.$student.'\')" >'."\n";
1.485     albertel 3650: 	    $result.= (($status eq 'excused') ? '<option> </option><option selected="selected" value="excused">'.&mt('excused').'</option>' 
                   3651: 		: '<option selected="selected"> </option><option value="excused">'.&mt('excused').'</option>')."\n";
                   3652: 	    $result.='<option value="reset status">'.&mt('reset status').'</option>';
1.126     ng       3653: 	    $result.="</select>&nbsp;</td>\n";
1.122     ng       3654: 	} else {
                   3655: 	    $result.='<input type="hidden" name="'.
                   3656: 		'GD_'.$student.'_'.$part.'_'.$type.'_s" value="'.$score.'" />'.
                   3657: 		    "\n";
1.233     albertel 3658: 	    $result.='<input type="text" name="'.
1.122     ng       3659: 		'GD_'.$student.'_'.$part.'_'.$type.'" '.
                   3660: 		'value="'.$score.'" size="4" /></td>'."\n";
1.41      ng       3661: 	}
                   3662:     }
1.474     albertel 3663:     $result.=&Apache::loncommon::end_data_table_row();
1.41      ng       3664:     return $result;
1.38      ng       3665: }
                   3666: 
1.44      ng       3667: #--- change scores for all the students in a section/class
                   3668: #    record does not get update if unchanged
1.38      ng       3669: sub editgrades {
1.41      ng       3670:     my ($request) = @_;
                   3671: 
1.324     albertel 3672:     my $symb=&get_symb($request);
1.433     banghart 3673:     my $section_display = join (", ",&Apache::loncommon::get_env_multiple('form.section'));
1.477     albertel 3674:     my $title='<h2>'.&mt('Current Grade Status').'</h2>';
                   3675:     $title.='<h4>'.&mt('<b>Current Resource: </b>[_1]',$env{'form.probTitle'}).'</h4>'."\n";
1.433     banghart 3676:     $title.='<h4>'.&mt('<b>Section: </b>[_1]',$section_display).'</h4>'."\n";
1.126     ng       3677: 
1.477     albertel 3678:     my $result= &Apache::loncommon::start_data_table().
                   3679: 	&Apache::loncommon::start_data_table_header_row().
                   3680: 	'<th rowspan="2" valign="middle">'.&mt('No.').'</th>'.
                   3681: 	'<th rowspan="2" valign="middle">'.&nameUserString('header')."</th>\n";
1.43      ng       3682:     my %scoreptr = (
                   3683: 		    'correct'  =>'correct_by_override',
                   3684: 		    'incorrect'=>'incorrect_by_override',
                   3685: 		    'excused'  =>'excused',
                   3686: 		    'ungraded' =>'ungraded_attempted',
1.596     raeburn  3687:                     'credited' =>'credit_attempted',
1.43      ng       3688: 		    'nothing'  => '',
                   3689: 		    );
1.257     albertel 3690:     my ($classlist,undef,$fullname) = &getclasslist($env{'form.section'},'0');
1.34      ng       3691: 
1.44      ng       3692:     my (@partid);
                   3693:     my %weight = ();
1.54      albertel 3694:     my %columns = ();
1.44      ng       3695:     my ($i,$ctr,$count,$rec_update) = (0,0,0,0);
1.54      albertel 3696: 
1.582     raeburn  3697:     my $partserror;
                   3698:     my (@parts) = sort(&getpartlist($symb,\$partserror));
                   3699:     if ($partserror) {
                   3700:         return &navmap_errormsg();
                   3701:     }
1.54      albertel 3702:     my $header;
1.257     albertel 3703:     while ($ctr < $env{'form.totalparts'}) {
                   3704: 	my $partid = $env{'form.partid_'.$ctr};
1.524     raeburn  3705: 	push(@partid,$partid);
1.257     albertel 3706: 	$weight{$partid} = $env{'form.weight_'.$partid};
1.44      ng       3707: 	$ctr++;
1.54      albertel 3708:     }
1.324     albertel 3709:     my (undef,undef,$url) = &Apache::lonnet::decode_symb($symb);
1.54      albertel 3710:     foreach my $partid (@partid) {
1.478     albertel 3711: 	$header .= '<th align="center">'.&mt('Old Score').'</th>'.
                   3712: 	    '<th align="center">'.&mt('New Score').'</th>';
1.54      albertel 3713: 	$columns{$partid}=2;
                   3714: 	foreach my $stores (@parts) {
                   3715: 	    my ($part,$type) = &split_part_type($stores);
                   3716: 	    if ($part !~ m/^\Q$partid\E/) { next;}
                   3717: 	    if ($type eq 'awarded' || $type eq 'solved') { next; }
                   3718: 	    my $display=&Apache::lonnet::metadata($url,$stores.'.display');
1.551     raeburn  3719: 	    $display =~ s/\[Part: \Q$part\E\]//;
1.539     riegler  3720:             my $narrowtext = &mt('Tries');
                   3721: 	    $display =~ s/Number of Attempts/$narrowtext/;
                   3722: 	    $header .= '<th align="center">'.&mt('Old').' '.$display.'</th>'.
                   3723: 		'<th align="center">'.&mt('New').' '.$display.'</th>';
1.54      albertel 3724: 	    $columns{$partid}+=2;
                   3725: 	}
                   3726:     }
                   3727:     foreach my $partid (@partid) {
1.324     albertel 3728: 	my $display_part=&get_display_part($partid,$symb);
1.478     albertel 3729: 	$result .= '<th colspan="'.$columns{$partid}.'" align="center">'.
                   3730: 	    &mt('Part: [_1] (Weight = [_2])',$display_part,$weight{$partid}).
                   3731: 	    '</th>';
1.54      albertel 3732: 
1.44      ng       3733:     }
1.477     albertel 3734:     $result .= &Apache::loncommon::end_data_table_header_row().
                   3735: 	&Apache::loncommon::start_data_table_header_row().
                   3736: 	$header.
                   3737: 	&Apache::loncommon::end_data_table_header_row();
                   3738:     my @noupdate;
1.126     ng       3739:     my ($updateCtr,$noupdateCtr) = (1,1);
1.257     albertel 3740:     for ($i=0; $i<$env{'form.total'}; $i++) {
1.93      albertel 3741: 	my $line;
1.257     albertel 3742: 	my $user = $env{'form.ctr'.$i};
1.281     albertel 3743: 	my ($uname,$udom)=split(/:/,$user);
1.44      ng       3744: 	my %newrecord;
                   3745: 	my $updateflag = 0;
1.281     albertel 3746: 	$line .= '<td>'.&nameUserString(undef,$$fullname{$user},$uname,$udom).'</td>';
1.108     albertel 3747: 	my $usec=$classlist->{"$uname:$udom"}[5];
1.105     albertel 3748: 	if (!&canmodify($usec)) {
1.126     ng       3749: 	    my $numcols=scalar(@partid)*4+2;
1.477     albertel 3750: 	    push(@noupdate,
1.478     albertel 3751: 		 $line."<td colspan=\"$numcols\"><span class=\"LC_warning\">".
                   3752: 		 &mt('Not allowed to modify student')."</span></td></tr>");
1.105     albertel 3753: 	    next;
                   3754: 	}
1.269     raeburn  3755:         my %aggregate = ();
                   3756:         my $aggregateflag = 0;
1.281     albertel 3757: 	$user=~s/:/_/; # colon doen't work in javascript for names
1.44      ng       3758: 	foreach (@partid) {
1.257     albertel 3759: 	    my $old_aw    = $env{'form.GD_'.$user.'_'.$_.'_awarded_s'};
1.54      albertel 3760: 	    my $old_part_pcr = $old_aw/($weight{$_} ne '0' ? $weight{$_}:1);
                   3761: 	    my $old_part  = $old_aw eq '' ? '' : $old_part_pcr;
1.257     albertel 3762: 	    my $old_score = $scoreptr{$env{'form.GD_'.$user.'_'.$_.'_solved_s'}};
                   3763: 	    my $awarded   = $env{'form.GD_'.$user.'_'.$_.'_awarded'};
1.54      albertel 3764: 	    my $pcr       = $awarded/($weight{$_} ne '0' ? $weight{$_} : 1);
                   3765: 	    my $partial   = $awarded eq '' ? '' : $pcr;
1.44      ng       3766: 	    my $score;
                   3767: 	    if ($partial eq '') {
1.257     albertel 3768: 		$score = $scoreptr{$env{'form.GD_'.$user.'_'.$_.'_solved_s'}};
1.44      ng       3769: 	    } elsif ($partial > 0) {
                   3770: 		$score = 'correct_by_override';
                   3771: 	    } elsif ($partial == 0) {
                   3772: 		$score = 'incorrect_by_override';
                   3773: 	    }
1.257     albertel 3774: 	    my $dropMenu = $env{'form.GD_'.$user.'_'.$_.'_solved'};
1.125     ng       3775: 	    $score = 'excused' if (($dropMenu eq 'excused') && ($score ne 'excused'));
                   3776: 
1.292     albertel 3777: 	    $newrecord{'resource.'.$_.'.regrader'}=
                   3778: 		"$env{'user.name'}:$env{'user.domain'}";
1.125     ng       3779: 	    if ($dropMenu eq 'reset status' &&
                   3780: 		$old_score ne '') { # ignore if no previous attempts => nothing to reset
1.299     albertel 3781: 		$newrecord{'resource.'.$_.'.tries'} = '';
1.125     ng       3782: 		$newrecord{'resource.'.$_.'.solved'} = '';
                   3783: 		$newrecord{'resource.'.$_.'.award'} = '';
1.299     albertel 3784: 		$newrecord{'resource.'.$_.'.awarded'} = '';
1.125     ng       3785: 		$updateflag = 1;
1.269     raeburn  3786:                 if ($env{'form.GD_'.$user.'_'.$_.'_aggtries'} > 0) {
                   3787:                     my $aggtries = $env{'form.GD_'.$user.'_'.$_.'_aggtries'};
                   3788:                     my $totaltries = $env{'form.GD_'.$user.'_'.$_.'_totaltries'};
                   3789:                     my $solvedstatus = $env{'form.GD_'.$user.'_'.$_.'_solved_s'};
                   3790:                     &decrement_aggs($symb,$_,\%aggregate,$aggtries,$totaltries,$solvedstatus);
                   3791:                     $aggregateflag = 1;
                   3792:                 }
1.139     albertel 3793: 	    } elsif (!($old_part eq $partial && $old_score eq $score)) {
                   3794: 		$updateflag = 1;
                   3795: 		$newrecord{'resource.'.$_.'.awarded'}  = $partial if $partial ne '';
                   3796: 		$newrecord{'resource.'.$_.'.solved'}   = $score;
                   3797: 		$rec_update++;
1.125     ng       3798: 	    }
                   3799: 
1.93      albertel 3800: 	    $line .= '<td align="center">'.$old_aw.'&nbsp;</td>'.
1.44      ng       3801: 		'<td align="center">'.$awarded.
                   3802: 		($score eq 'excused' ? $score : '').'&nbsp;</td>';
1.5       albertel 3803: 
1.54      albertel 3804: 
                   3805: 	    my $partid=$_;
                   3806: 	    foreach my $stores (@parts) {
                   3807: 		my ($part,$type) = &split_part_type($stores);
                   3808: 		if ($part !~ m/^\Q$partid\E/) { next;}
                   3809: 		if ($type eq 'awarded' || $type eq 'solved') { next; }
1.257     albertel 3810: 		my $old_aw    = $env{'form.GD_'.$user.'_'.$part.'_'.$type.'_s'};
                   3811: 		my $awarded   = $env{'form.GD_'.$user.'_'.$part.'_'.$type};
1.54      albertel 3812: 		if ($awarded ne '' && $awarded ne $old_aw) {
                   3813: 		    $newrecord{'resource.'.$part.'.'.$type}= $awarded;
1.257     albertel 3814: 		    $newrecord{'resource.'.$part.'.regrader'}="$env{'user.name'}:$env{'user.domain'}";
1.54      albertel 3815: 		    $updateflag=1;
                   3816: 		}
1.93      albertel 3817: 		$line .= '<td align="center">'.$old_aw.'&nbsp;</td>'.
1.54      albertel 3818: 		    '<td align="center">'.$awarded.'&nbsp;</td>';
                   3819: 	    }
1.44      ng       3820: 	}
1.477     albertel 3821: 	$line.="\n";
1.301     albertel 3822: 
                   3823: 	my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   3824: 	my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   3825: 
1.44      ng       3826: 	if ($updateflag) {
                   3827: 	    $count++;
1.257     albertel 3828: 	    &Apache::lonnet::cstore(\%newrecord,$symb,$env{'request.course.id'},
1.89      albertel 3829: 				    $udom,$uname);
1.301     albertel 3830: 
                   3831: 	    if (&Apache::bridgetask::in_queue('gradingqueue',$symb,$cdom,
                   3832: 					      $cnum,$udom,$uname)) {
                   3833: 		# need to figure out if should be in queue.
                   3834: 		my %record =  
                   3835: 		    &Apache::lonnet::restore($symb,$env{'request.course.id'},
                   3836: 					     $udom,$uname);
                   3837: 		my $all_graded = 1;
                   3838: 		my $none_graded = 1;
                   3839: 		foreach my $part (@parts) {
                   3840: 		    if ( $record{'resource.'.$part.'.awarded'} eq '' ) {
                   3841: 			$all_graded = 0;
                   3842: 		    } else {
                   3843: 			$none_graded = 0;
                   3844: 		    }
                   3845: 		}
                   3846: 
                   3847: 		if ($all_graded || $none_graded) {
                   3848: 		    &Apache::bridgetask::remove_from_queue('gradingqueue',
                   3849: 							   $symb,$cdom,$cnum,
                   3850: 							   $udom,$uname);
                   3851: 		}
                   3852: 	    }
                   3853: 
1.477     albertel 3854: 	    $result.=&Apache::loncommon::start_data_table_row().
                   3855: 		'<td align="right">&nbsp;'.$updateCtr.'&nbsp;</td>'.$line.
                   3856: 		&Apache::loncommon::end_data_table_row();
1.126     ng       3857: 	    $updateCtr++;
1.93      albertel 3858: 	} else {
1.477     albertel 3859: 	    push(@noupdate,
                   3860: 		 '<td align="right">&nbsp;'.$noupdateCtr.'&nbsp;</td>'.$line);
1.126     ng       3861: 	    $noupdateCtr++;
1.44      ng       3862: 	}
1.269     raeburn  3863:         if ($aggregateflag) {
                   3864:             &Apache::lonnet::cinc('nohist_resourcetracker',\%aggregate,
1.301     albertel 3865: 				  $cdom,$cnum);
1.269     raeburn  3866:         }
1.93      albertel 3867:     }
1.477     albertel 3868:     if (@noupdate) {
1.126     ng       3869: #	my $numcols=(scalar(@partid)*(scalar(@parts)-1)*2)+3;
                   3870: 	my $numcols=scalar(@partid)*4+2;
1.477     albertel 3871: 	$result .= &Apache::loncommon::start_data_table_row('LC_empty_row').
1.478     albertel 3872: 	    '<td align="center" colspan="'.$numcols.'">'.
                   3873: 	    &mt('No Changes Occurred For the Students Below').
                   3874: 	    '</td>'.
1.477     albertel 3875: 	    &Apache::loncommon::end_data_table_row();
                   3876: 	foreach my $line (@noupdate) {
                   3877: 	    $result.=
                   3878: 		&Apache::loncommon::start_data_table_row().
                   3879: 		$line.
                   3880: 		&Apache::loncommon::end_data_table_row();
                   3881: 	}
1.44      ng       3882:     }
1.477     albertel 3883:     $result .= &Apache::loncommon::end_data_table().
                   3884: 	&show_grading_menu_form($symb);
1.478     albertel 3885:     my $msg = '<p><b>'.
                   3886: 	&mt('Number of records updated = [_1] for [quant,_2,student].',
                   3887: 	    $rec_update,$count).'</b><br />'.
                   3888: 	'<b>'.&mt('Total number of students = [_1]',$env{'form.total'}).
                   3889: 	'</b></p>';
1.44      ng       3890:     return $title.$msg.$result;
1.5       albertel 3891: }
1.54      albertel 3892: 
                   3893: sub split_part_type {
                   3894:     my ($partstr) = @_;
                   3895:     my ($temp,@allparts)=split(/_/,$partstr);
                   3896:     my $type=pop(@allparts);
1.439     albertel 3897:     my $part=join('_',@allparts);
1.54      albertel 3898:     return ($part,$type);
                   3899: }
                   3900: 
1.44      ng       3901: #------------- end of section for handling grading by section/class ---------
                   3902: #
                   3903: #----------------------------------------------------------------------------
                   3904: 
1.5       albertel 3905: 
1.44      ng       3906: #----------------------------------------------------------------------------
                   3907: #
                   3908: #-------------------------- Next few routines handles grading by csv upload
                   3909: #
                   3910: #--- Javascript to handle csv upload
1.27      albertel 3911: sub csvupload_javascript_reverse_associate {
1.573     bisitz   3912:     my $error1=&mt('You need to specify the username or the student/employee ID');
1.246     albertel 3913:     my $error2=&mt('You need to specify at least one grading field');
1.27      albertel 3914:   return(<<ENDPICK);
                   3915:   function verify(vf) {
                   3916:     var foundsomething=0;
                   3917:     var founduname=0;
1.243     albertel 3918:     var foundID=0;
1.27      albertel 3919:     for (i=0;i<=vf.nfields.value;i++) {
                   3920:       tw=eval('vf.f'+i+'.selectedIndex');
1.243     albertel 3921:       if (i==0 && tw!=0) { foundID=1; }
                   3922:       if (i==1 && tw!=0) { founduname=1; }
                   3923:       if (i!=0 && i!=1 && i!=2 && tw!=0) { foundsomething=1; }
1.27      albertel 3924:     }
1.246     albertel 3925:     if (founduname==0 && foundID==0) {
                   3926: 	alert('$error1');
                   3927: 	return;
1.27      albertel 3928:     }
                   3929:     if (foundsomething==0) {
1.246     albertel 3930: 	alert('$error2');
                   3931: 	return;
1.27      albertel 3932:     }
                   3933:     vf.submit();
                   3934:   }
                   3935:   function flip(vf,tf) {
                   3936:     var nw=eval('vf.f'+tf+'.selectedIndex');
                   3937:     var i;
                   3938:     for (i=0;i<=vf.nfields.value;i++) {
                   3939:       //can not pick the same destination field for both name and domain
                   3940:       if (((i ==0)||(i ==1)) && 
                   3941:           ((tf==0)||(tf==1)) && 
                   3942:           (i!=tf) &&
                   3943:           (eval('vf.f'+i+'.selectedIndex')==nw)) {
                   3944:         eval('vf.f'+i+'.selectedIndex=0;')
                   3945:       }
                   3946:     }
                   3947:   }
                   3948: ENDPICK
                   3949: }
                   3950: 
                   3951: sub csvupload_javascript_forward_associate {
1.573     bisitz   3952:     my $error1=&mt('You need to specify the username or the student/employee ID');
1.246     albertel 3953:     my $error2=&mt('You need to specify at least one grading field');
1.27      albertel 3954:   return(<<ENDPICK);
                   3955:   function verify(vf) {
                   3956:     var foundsomething=0;
                   3957:     var founduname=0;
1.243     albertel 3958:     var foundID=0;
1.27      albertel 3959:     for (i=0;i<=vf.nfields.value;i++) {
                   3960:       tw=eval('vf.f'+i+'.selectedIndex');
1.243     albertel 3961:       if (tw==1) { foundID=1; }
                   3962:       if (tw==2) { founduname=1; }
                   3963:       if (tw>3) { foundsomething=1; }
1.27      albertel 3964:     }
1.246     albertel 3965:     if (founduname==0 && foundID==0) {
                   3966: 	alert('$error1');
                   3967: 	return;
1.27      albertel 3968:     }
                   3969:     if (foundsomething==0) {
1.246     albertel 3970: 	alert('$error2');
                   3971: 	return;
1.27      albertel 3972:     }
                   3973:     vf.submit();
                   3974:   }
                   3975:   function flip(vf,tf) {
                   3976:     var nw=eval('vf.f'+tf+'.selectedIndex');
                   3977:     var i;
                   3978:     //can not pick the same destination field twice
                   3979:     for (i=0;i<=vf.nfields.value;i++) {
                   3980:       if ((i!=tf) && (eval('vf.f'+i+'.selectedIndex')==nw)) {
                   3981:         eval('vf.f'+i+'.selectedIndex=0;')
                   3982:       }
                   3983:     }
                   3984:   }
                   3985: ENDPICK
                   3986: }
                   3987: 
1.26      albertel 3988: sub csvuploadmap_header {
1.324     albertel 3989:     my ($request,$symb,$datatoken,$distotal)= @_;
1.41      ng       3990:     my $javascript;
1.257     albertel 3991:     if ($env{'form.upfile_associate'} eq 'reverse') {
1.41      ng       3992: 	$javascript=&csvupload_javascript_reverse_associate();
                   3993:     } else {
                   3994: 	$javascript=&csvupload_javascript_forward_associate();
                   3995:     }
1.45      ng       3996: 
1.324     albertel 3997:     my ($result) = &showResourceInfo($symb,$env{'form.probTitle'});
1.257     albertel 3998:     my $checked=(($env{'form.noFirstLine'})?' checked="checked"':'');
1.245     albertel 3999:     my $ignore=&mt('Ignore First Line');
1.418     albertel 4000:     $symb = &Apache::lonenc::check_encrypt($symb);
1.41      ng       4001:     $request->print(<<ENDPICK);
1.26      albertel 4002: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="gradesupload">
1.398     albertel 4003: <h3><span class="LC_info">Uploading Class Grades</span></h3>
1.45      ng       4004: $result
1.326     albertel 4005: <hr />
1.26      albertel 4006: <h3>Identify fields</h3>
                   4007: Total number of records found in file: $distotal <hr />
                   4008: Enter as many fields as you can. The system will inform you and bring you back
                   4009: to this page if the data selected is insufficient to run your class.<hr />
1.589     bisitz   4010: <input type="button" value="Reverse Association" onclick="javascript:this.form.associate.value='Reverse Association';submit(this.form);" />
1.245     albertel 4011: <label><input type="checkbox" name="noFirstLine" $checked />$ignore</label>
1.26      albertel 4012: <input type="hidden" name="associate"  value="" />
                   4013: <input type="hidden" name="phase"      value="three" />
                   4014: <input type="hidden" name="datatoken"  value="$datatoken" />
1.257     albertel 4015: <input type="hidden" name="fileupload" value="$env{'form.fileupload'}" />
                   4016: <input type="hidden" name="upfiletype" value="$env{'form.upfiletype'}" />
1.26      albertel 4017: <input type="hidden" name="upfile_associate" 
1.257     albertel 4018:                                        value="$env{'form.upfile_associate'}" />
1.26      albertel 4019: <input type="hidden" name="symb"       value="$symb" />
1.257     albertel 4020: <input type="hidden" name="saveState"  value="$env{'form.saveState'}" />
                   4021: <input type="hidden" name="probTitle"  value="$env{'form.probTitle'}" />
1.246     albertel 4022: <input type="hidden" name="command"    value="csvuploadoptions" />
1.26      albertel 4023: <hr />
                   4024: <script type="text/javascript" language="Javascript">
                   4025: $javascript
                   4026: </script>
                   4027: ENDPICK
1.118     ng       4028:     return '';
1.26      albertel 4029: 
                   4030: }
                   4031: 
                   4032: sub csvupload_fields {
1.582     raeburn  4033:     my ($symb,$errorref) = @_;
                   4034:     my (@parts) = &getpartlist($symb,$errorref);
                   4035:     if (ref($errorref)) {
                   4036:         if ($$errorref) {
                   4037:             return;
                   4038:         }
                   4039:     }
                   4040: 
1.556     weissno  4041:     my @fields=(['ID','Student/Employee ID'],
1.243     albertel 4042: 		['username','Student Username'],
                   4043: 		['domain','Student Domain']);
1.324     albertel 4044:     my (undef,undef,$url) = &Apache::lonnet::decode_symb($symb);
1.41      ng       4045:     foreach my $part (sort(@parts)) {
                   4046: 	my @datum;
                   4047: 	my $display=&Apache::lonnet::metadata($url,$part.'.display');
                   4048: 	my $name=$part;
                   4049: 	if  (!$display) { $display = $name; }
                   4050: 	@datum=($name,$display);
1.244     albertel 4051: 	if ($name=~/^stores_(.*)_awarded/) {
                   4052: 	    push(@fields,['stores_'.$1.'_points',"Points [Part: $1]"]);
                   4053: 	}
1.41      ng       4054: 	push(@fields,\@datum);
                   4055:     }
                   4056:     return (@fields);
1.26      albertel 4057: }
                   4058: 
                   4059: sub csvuploadmap_footer {
1.41      ng       4060:     my ($request,$i,$keyfields) =@_;
                   4061:     $request->print(<<ENDPICK);
1.26      albertel 4062: </table>
                   4063: <input type="hidden" name="nfields" value="$i" />
                   4064: <input type="hidden" name="keyfields" value="$keyfields" />
1.589     bisitz   4065: <input type="button" onclick="javascript:verify(this.form)" value="Assign Grades" /><br />
1.26      albertel 4066: </form>
                   4067: ENDPICK
                   4068: }
                   4069: 
1.283     albertel 4070: sub checkforfile_js {
1.539     riegler  4071:     my $alertmsg = &mt('Please use the browse button to select a file from your local directory.');
1.86      ng       4072:     my $result =<<CSVFORMJS;
                   4073: <script type="text/javascript" language="javascript">
                   4074:     function checkUpload(formname) {
                   4075: 	if (formname.upfile.value == "") {
1.539     riegler  4076: 	    alert("$alertmsg");
1.86      ng       4077: 	    return false;
                   4078: 	}
                   4079: 	formname.submit();
                   4080:     }
                   4081:     </script>
                   4082: CSVFORMJS
1.283     albertel 4083:     return $result;
                   4084: }
                   4085: 
                   4086: sub upcsvScores_form {
                   4087:     my ($request) = shift;
1.324     albertel 4088:     my ($symb)=&get_symb($request);
1.283     albertel 4089:     if (!$symb) {return '';}
                   4090:     my $result=&checkforfile_js();
1.257     albertel 4091:     $env{'form.probTitle'} = &Apache::lonnet::gettitle($symb);
1.324     albertel 4092:     my ($table) = &showResourceInfo($symb,$env{'form.probTitle'});
1.118     ng       4093:     $result.=$table;
1.326     albertel 4094:     $result.='<br /><table width="100%" border="0"><tr><td bgcolor="#777777">'."\n";
                   4095:     $result.='<table width="100%" border="0"><tr bgcolor="#e6ffff"><td>'."\n";
1.538     schulted 4096:     $result.='&nbsp;<b>'.&mt('Specify a file containing the class scores for current resource.').
                   4097: 	'</b></td></tr>'."\n";
1.596.2.4  raeburn  4098:     $result.='<tr bgcolor="#ffffe6"><td>'."\n";
1.370     www      4099:     my $upload=&mt("Upload Scores");
1.86      ng       4100:     my $upfile_select=&Apache::loncommon::upfile_select_html();
1.245     albertel 4101:     my $ignore=&mt('Ignore First Line');
1.418     albertel 4102:     $symb = &Apache::lonenc::check_encrypt($symb);
1.86      ng       4103:     $result.=<<ENDUPFORM;
1.106     albertel 4104: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="gradesupload">
1.86      ng       4105: <input type="hidden" name="symb" value="$symb" />
                   4106: <input type="hidden" name="command" value="csvuploadmap" />
1.257     albertel 4107: <input type="hidden" name="probTitle" value="$env{'form.probTitle'}" />
                   4108: <input type="hidden" name="saveState"  value="$env{'form.saveState'}" />
1.86      ng       4109: $upfile_select
1.589     bisitz   4110: <br /><input type="button" onclick="javascript:checkUpload(this.form);" value="$upload" />
1.283     albertel 4111: <label><input type="checkbox" name="noFirstLine" />$ignore</label>
1.86      ng       4112: </form>
                   4113: ENDUPFORM
1.370     www      4114:     $result.=&Apache::loncommon::help_open_topic("Course_Convert_To_CSV",
                   4115:                            &mt("How do I create a CSV file from a spreadsheet"))
                   4116:     .'</td></tr></table>'."\n";
1.86      ng       4117:     $result.='</td></tr></table><br /><br />'."\n";
1.324     albertel 4118:     $result.=&show_grading_menu_form($symb);
1.86      ng       4119:     return $result;
                   4120: }
                   4121: 
                   4122: 
1.26      albertel 4123: sub csvuploadmap {
1.41      ng       4124:     my ($request)= @_;
1.324     albertel 4125:     my ($symb)=&get_symb($request);
1.41      ng       4126:     if (!$symb) {return '';}
1.72      ng       4127: 
1.41      ng       4128:     my $datatoken;
1.257     albertel 4129:     if (!$env{'form.datatoken'}) {
1.41      ng       4130: 	$datatoken=&Apache::loncommon::upfile_store($request);
1.26      albertel 4131:     } else {
1.257     albertel 4132: 	$datatoken=$env{'form.datatoken'};
1.41      ng       4133: 	&Apache::loncommon::load_tmp_file($request);
1.26      albertel 4134:     }
1.41      ng       4135:     my @records=&Apache::loncommon::upfile_record_sep();
1.257     albertel 4136:     if ($env{'form.noFirstLine'}) { shift(@records); }
1.324     albertel 4137:     &csvuploadmap_header($request,$symb,$datatoken,$#records+1);
1.41      ng       4138:     my ($i,$keyfields);
                   4139:     if (@records) {
1.582     raeburn  4140:         my $fieldserror;
                   4141: 	my @fields=&csvupload_fields($symb,\$fieldserror);
                   4142:         if ($fieldserror) {
                   4143:             $request->print(&navmap_errormsg());
                   4144:             return;
                   4145:         }
1.257     albertel 4146: 	if ($env{'form.upfile_associate'} eq 'reverse') {	
1.41      ng       4147: 	    &Apache::loncommon::csv_print_samples($request,\@records);
                   4148: 	    $i=&Apache::loncommon::csv_print_select_table($request,\@records,
                   4149: 							  \@fields);
                   4150: 	    foreach (@fields) { $keyfields.=$_->[0].','; }
                   4151: 	    chop($keyfields);
                   4152: 	} else {
                   4153: 	    unshift(@fields,['none','']);
                   4154: 	    $i=&Apache::loncommon::csv_samples_select_table($request,\@records,
                   4155: 							    \@fields);
1.311     banghart 4156:             foreach my $rec (@records) {
                   4157:                 my %temp = &Apache::loncommon::record_sep($rec);
                   4158:                 if (%temp) {
                   4159:                     $keyfields=join(',',sort(keys(%temp)));
                   4160:                     last;
                   4161:                 }
                   4162:             }
1.41      ng       4163: 	}
                   4164:     }
                   4165:     &csvuploadmap_footer($request,$i,$keyfields);
1.324     albertel 4166:     $request->print(&show_grading_menu_form($symb));
1.72      ng       4167: 
1.41      ng       4168:     return '';
1.27      albertel 4169: }
                   4170: 
1.246     albertel 4171: sub csvuploadoptions {
1.41      ng       4172:     my ($request)= @_;
1.324     albertel 4173:     my ($symb)=&get_symb($request);
1.257     albertel 4174:     my $checked=(($env{'form.noFirstLine'})?'1':'0');
1.246     albertel 4175:     my $ignore=&mt('Ignore First Line');
                   4176:     $request->print(<<ENDPICK);
                   4177: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="gradesupload">
1.398     albertel 4178: <h3><span class="LC_info">Uploading Class Grade Options</span></h3>
1.246     albertel 4179: <input type="hidden" name="command"    value="csvuploadassign" />
1.302     albertel 4180: <!--
1.246     albertel 4181: <p>
                   4182: <label>
                   4183:    <input type="checkbox" name="show_full_results" />
                   4184:    Show a table of all changes
                   4185: </label>
                   4186: </p>
1.302     albertel 4187: -->
1.246     albertel 4188: <p>
                   4189: <label>
                   4190:    <input type="checkbox" name="overwite_scores" checked="checked" />
                   4191:    Overwrite any existing score
                   4192: </label>
                   4193: </p>
                   4194: ENDPICK
                   4195:     my %fields=&get_fields();
                   4196:     if (!defined($fields{'domain'})) {
1.257     albertel 4197: 	my $domform = &Apache::loncommon::select_dom_form($env{'request.role.domain'},'default_domain');
1.246     albertel 4198: 	$request->print("\n<p> Users are in domain: ".$domform."</p>\n");
                   4199:     }
1.257     albertel 4200:     foreach my $key (sort(keys(%env))) {
1.246     albertel 4201: 	if ($key !~ /^form\.(.*)$/) { next; }
                   4202: 	my $cleankey=$1;
                   4203: 	if ($cleankey eq 'command') { next; }
                   4204: 	$request->print('<input type="hidden" name="'.$cleankey.
1.257     albertel 4205: 			'"  value="'.$env{$key}.'" />'."\n");
1.246     albertel 4206:     }
                   4207:     # FIXME do a check for any duplicated user ids...
                   4208:     # FIXME do a check for any invalid user ids?...
1.290     albertel 4209:     $request->print('<input type="submit" value="Assign Grades" /><br />
                   4210: <hr /></form>'."\n");
1.324     albertel 4211:     $request->print(&show_grading_menu_form($symb));
1.246     albertel 4212:     return '';
                   4213: }
                   4214: 
                   4215: sub get_fields {
                   4216:     my %fields;
1.257     albertel 4217:     my @keyfields = split(/\,/,$env{'form.keyfields'});
                   4218:     for (my $i=0; $i<=$env{'form.nfields'}; $i++) {
                   4219: 	if ($env{'form.upfile_associate'} eq 'reverse') {
                   4220: 	    if ($env{'form.f'.$i} ne 'none') {
                   4221: 		$fields{$keyfields[$i]}=$env{'form.f'.$i};
1.41      ng       4222: 	    }
                   4223: 	} else {
1.257     albertel 4224: 	    if ($env{'form.f'.$i} ne 'none') {
                   4225: 		$fields{$env{'form.f'.$i}}=$keyfields[$i];
1.41      ng       4226: 	    }
                   4227: 	}
1.27      albertel 4228:     }
1.246     albertel 4229:     return %fields;
                   4230: }
                   4231: 
                   4232: sub csvuploadassign {
                   4233:     my ($request)= @_;
1.324     albertel 4234:     my ($symb)=&get_symb($request);
1.246     albertel 4235:     if (!$symb) {return '';}
1.345     bowersj2 4236:     my $error_msg = '';
1.246     albertel 4237:     &Apache::loncommon::load_tmp_file($request);
                   4238:     my @gradedata = &Apache::loncommon::upfile_record_sep();
1.257     albertel 4239:     if ($env{'form.noFirstLine'}) { shift(@gradedata); }
1.246     albertel 4240:     my %fields=&get_fields();
1.41      ng       4241:     $request->print('<h3>Assigning Grades</h3>');
1.257     albertel 4242:     my $courseid=$env{'request.course.id'};
1.97      albertel 4243:     my ($classlist) = &getclasslist('all',0);
1.106     albertel 4244:     my @notallowed;
1.41      ng       4245:     my @skipped;
1.596.2.4  raeburn  4246:     my @warnings;
1.41      ng       4247:     my $countdone=0;
                   4248:     foreach my $grade (@gradedata) {
                   4249: 	my %entries=&Apache::loncommon::record_sep($grade);
1.246     albertel 4250: 	my $domain;
                   4251: 	if ($entries{$fields{'domain'}}) {
                   4252: 	    $domain=$entries{$fields{'domain'}};
                   4253: 	} else {
1.257     albertel 4254: 	    $domain=$env{'form.default_domain'};
1.246     albertel 4255: 	}
1.243     albertel 4256: 	$domain=~s/\s//g;
1.41      ng       4257: 	my $username=$entries{$fields{'username'}};
1.160     albertel 4258: 	$username=~s/\s//g;
1.243     albertel 4259: 	if (!$username) {
                   4260: 	    my $id=$entries{$fields{'ID'}};
1.247     albertel 4261: 	    $id=~s/\s//g;
1.243     albertel 4262: 	    my %ids=&Apache::lonnet::idget($domain,$id);
                   4263: 	    $username=$ids{$id};
                   4264: 	}
1.41      ng       4265: 	if (!exists($$classlist{"$username:$domain"})) {
1.247     albertel 4266: 	    my $id=$entries{$fields{'ID'}};
                   4267: 	    $id=~s/\s//g;
                   4268: 	    if ($id) {
                   4269: 		push(@skipped,"$id:$domain");
                   4270: 	    } else {
                   4271: 		push(@skipped,"$username:$domain");
                   4272: 	    }
1.41      ng       4273: 	    next;
                   4274: 	}
1.108     albertel 4275: 	my $usec=$classlist->{"$username:$domain"}[5];
1.106     albertel 4276: 	if (!&canmodify($usec)) {
                   4277: 	    push(@notallowed,"$username:$domain");
                   4278: 	    next;
                   4279: 	}
1.244     albertel 4280: 	my %points;
1.41      ng       4281: 	my %grades;
                   4282: 	foreach my $dest (keys(%fields)) {
1.244     albertel 4283: 	    if ($dest eq 'ID' || $dest eq 'username' ||
                   4284: 		$dest eq 'domain') { next; }
                   4285: 	    if ($entries{$fields{$dest}} =~ /^\s*$/) { next; }
                   4286: 	    if ($dest=~/stores_(.*)_points/) {
                   4287: 		my $part=$1;
                   4288: 		my $wgt =&Apache::lonnet::EXT('resource.'.$part.'.weight',
                   4289: 					      $symb,$domain,$username);
1.345     bowersj2 4290:                 if ($wgt) {
                   4291:                     $entries{$fields{$dest}}=~s/\s//g;
                   4292:                     my $pcr=$entries{$fields{$dest}} / $wgt;
1.463     albertel 4293:                     my $award=($pcr == 0) ? 'incorrect_by_override'
                   4294:                                           : 'correct_by_override';
1.596.2.4  raeburn  4295:                     if ($pcr>1) {
                   4296:                         push(@warnings,&mt("[_1]: point value larger than weight","$username:$domain"));
                   4297:                     }
1.345     bowersj2 4298:                     $grades{"resource.$part.awarded"}=$pcr;
                   4299:                     $grades{"resource.$part.solved"}=$award;
                   4300:                     $points{$part}=1;
                   4301:                 } else {
                   4302:                     $error_msg = "<br />" .
                   4303:                         &mt("Some point values were assigned"
                   4304:                             ." for problems with a weight "
                   4305:                             ."of zero. These values were "
                   4306:                             ."ignored.");
                   4307:                 }
1.244     albertel 4308: 	    } else {
                   4309: 		if ($dest=~/stores_(.*)_awarded/) { if ($points{$1}) {next;} }
                   4310: 		if ($dest=~/stores_(.*)_solved/)  { if ($points{$1}) {next;} }
                   4311: 		my $store_key=$dest;
                   4312: 		$store_key=~s/^stores/resource/;
                   4313: 		$store_key=~s/_/\./g;
                   4314: 		$grades{$store_key}=$entries{$fields{$dest}};
                   4315: 	    }
1.41      ng       4316: 	}
1.508     www      4317: 	if (! %grades) { 
                   4318:            push(@skipped,&mt("[_1]: no data to save","$username:$domain")); 
                   4319:         } else {
                   4320: 	   $grades{"resource.regrader"}="$env{'user.name'}:$env{'user.domain'}";
                   4321: 	   my $result=&Apache::lonnet::cstore(\%grades,$symb,
1.302     albertel 4322: 					   $env{'request.course.id'},
                   4323: 					   $domain,$username);
1.508     www      4324: 	   if ($result eq 'ok') {
                   4325: 	      $request->print('.');
1.596.2.4  raeburn  4326: # Remove from grading queue
                   4327:               &Apache::bridgetask::remove_from_queue('gradingqueue',$symb,
                   4328:                                              $env{'course.'.$env{'request.course.id'}.'.domain'},
                   4329:                                              $env{'course.'.$env{'request.course.id'}.'.num'},
                   4330:                                              $domain,$username);
1.508     www      4331: 	   } else {
                   4332: 	      $request->print("<p><span class=\"LC_error\">".
                   4333:                               &mt("Failed to save data for student [_1]. Message when trying to save was: [_2]",
                   4334:                                   "$username:$domain",$result)."</span></p>");
                   4335: 	   }
                   4336: 	   $request->rflush();
                   4337: 	   $countdone++;
                   4338:         }
1.41      ng       4339:     }
1.570     www      4340:     $request->print('<br />'.&Apache::lonhtmlcommon::confirm_success(&mt("Saved scores for [quant,_1,student]",$countdone),$countdone==0));
1.596.2.4  raeburn  4341:     if (@warnings) {
                   4342:         $request->print('<br />'.&Apache::lonhtmlcommon::confirm_success(&mt('Warnings generated for the following saved scores:'),1).'<br />');
                   4343:         $request->print(join(', ',@warnings));
                   4344:     }
1.41      ng       4345:     if (@skipped) {
1.571     www      4346: 	$request->print('<br />'.&Apache::lonhtmlcommon::confirm_success(&mt('No scores stored for the following username(s):'),1).'<br />');
                   4347:         $request->print(join(', ',@skipped));
1.106     albertel 4348:     }
                   4349:     if (@notallowed) {
1.571     www      4350: 	$request->print('<br />'.&Apache::lonhtmlcommon::confirm_success(&mt('Modification of scores not allowed for the following username(s):'),1).'<br />');
                   4351: 	$request->print(join(', ',@notallowed));
1.41      ng       4352:     }
1.106     albertel 4353:     $request->print("<br />\n");
1.324     albertel 4354:     $request->print(&show_grading_menu_form($symb));
1.345     bowersj2 4355:     return $error_msg;
1.26      albertel 4356: }
1.44      ng       4357: #------------- end of section for handling csv file upload ---------
                   4358: #
                   4359: #-------------------------------------------------------------------
                   4360: #
1.122     ng       4361: #-------------- Next few routines handle grading by page/sequence
1.72      ng       4362: #
                   4363: #--- Select a page/sequence and a student to grade
1.68      ng       4364: sub pickStudentPage {
                   4365:     my ($request) = shift;
                   4366: 
1.539     riegler  4367:     my $alertmsg = &mt('Please select the student you wish to grade.');
1.68      ng       4368:     $request->print(<<LISTJAVASCRIPT);
                   4369: <script type="text/javascript" language="javascript">
                   4370: 
                   4371: function checkPickOne(formname) {
1.76      ng       4372:     if (radioSelection(formname.student) == null) {
1.539     riegler  4373: 	alert("$alertmsg");
1.68      ng       4374: 	return;
                   4375:     }
1.125     ng       4376:     ptr = pullDownSelection(formname.selectpage);
                   4377:     formname.page.value = formname["page"+ptr].value;
                   4378:     formname.title.value = formname["title"+ptr].value;
1.68      ng       4379:     formname.submit();
                   4380: }
                   4381: 
                   4382: </script>
                   4383: LISTJAVASCRIPT
1.118     ng       4384:     &commonJSfunctions($request);
1.324     albertel 4385:     my ($symb) = &get_symb($request);
1.257     albertel 4386:     my $cdom      = $env{"course.$env{'request.course.id'}.domain"};
                   4387:     my $cnum      = $env{"course.$env{'request.course.id'}.num"};
                   4388:     my $getsec    = $env{'form.section'} eq '' ? 'all' : $env{'form.section'};
1.68      ng       4389: 
1.398     albertel 4390:     my $result='<h3><span class="LC_info">&nbsp;'.
1.485     albertel 4391: 	&mt('Manual Grading by Page or Sequence').'</span></h3>';
1.68      ng       4392: 
1.80      ng       4393:     $result.='<form action="/adm/grades" method="post" name="displayPage">'."\n";
1.582     raeburn  4394:     my $map_error;
                   4395:     my ($titles,$symbx) = &getSymbMap($map_error);
                   4396:     if ($map_error) {
                   4397:         $request->print(&navmap_errormsg());
                   4398:         return; 
                   4399:     }
1.137     albertel 4400:     my ($curpage) =&Apache::lonnet::decode_symb($symb); 
                   4401: #    my ($curpage,$mapId) =&Apache::lonnet::decode_symb($symb); 
                   4402: #    my $type=($curpage =~ /\.(page|sequence)/);
1.485     albertel 4403:     my $select = '<select name="selectpage">'."\n";
1.70      ng       4404:     my $ctr=0;
1.68      ng       4405:     foreach (@$titles) {
                   4406: 	my ($minder,$showtitle) = ($_ =~ /(\d+)\.(.*)/);
1.485     albertel 4407: 	$select.='<option value="'.$ctr.'" '.
1.401     albertel 4408: 	    ($$symbx{$_} =~ /$curpage$/ ? 'selected="selected"' : '').
1.71      ng       4409: 	    '>'.$showtitle.'</option>'."\n";
1.70      ng       4410: 	$ctr++;
1.68      ng       4411:     }
1.485     albertel 4412:     $select.= '</select>';
1.539     riegler  4413:     $result.='&nbsp;<b>'.&mt('Problems from').':</b> '.$select."<br />\n";
1.485     albertel 4414: 
1.70      ng       4415:     $ctr=0;
                   4416:     foreach (@$titles) {
                   4417: 	my ($minder,$showtitle) = ($_ =~ /(\d+)\.(.*)/);
                   4418: 	$result.='<input type="hidden" name="page'.$ctr.'" value="'.$$symbx{$_}.'" />'."\n";
                   4419: 	$result.='<input type="hidden" name="title'.$ctr.'" value="'.$showtitle.'" />'."\n";
                   4420: 	$ctr++;
                   4421:     }
1.72      ng       4422:     $result.='<input type="hidden" name="page" />'."\n".
                   4423: 	'<input type="hidden" name="title" />'."\n";
1.68      ng       4424: 
1.485     albertel 4425:     my $options =
                   4426: 	'<label><input type="radio" name="vProb" value="no" checked="checked" /> '.&mt('no').' </label>'."\n".
                   4427: 	'<label><input type="radio" name="vProb" value="yes" /> '.&mt('yes').' </label>'."<br />\n";
1.539     riegler  4428:     $result.='&nbsp;<b>'.&mt('View Problem Text').': </b>'.$options;
1.485     albertel 4429: 
                   4430:     $options =
                   4431: 	'<label><input type="radio" name="lastSub" value="none" /> '.&mt('none').' </label>'."\n".
                   4432: 	'<label><input type="radio" name="lastSub" value="datesub" checked="checked" /> '.&mt('by dates and submissions').'</label>'."\n".
                   4433: 	'<label><input type="radio" name="lastSub" value="all" /> '.&mt('all details').' </label>'."\n";
1.539     riegler  4434:     $result.='&nbsp;<b>'.&mt('Submissions').': </b>'.$options;
1.432     banghart 4435:     
                   4436:     $result.=&build_section_inputs();
1.442     banghart 4437:     my $stu_status = join(':',&Apache::loncommon::get_env_multiple('form.Status'));
                   4438:     $result.='<input type="hidden" name="Status"  value="'.$stu_status.'" />'."\n".
1.72      ng       4439: 	'<input type="hidden" name="command" value="displayPage" />'."\n".
1.418     albertel 4440: 	'<input type="hidden" name="symb"    value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
1.257     albertel 4441: 	'<input type="hidden" name="saveState" value="'.$env{'form.saveState'}.'" />'."<br />\n";
1.72      ng       4442: 
1.539     riegler  4443:     $result.='&nbsp;<b>'.&mt('Use CODE').': </b> <input type="text" name="CODE" value="" /> <br />'."\n";
1.382     albertel 4444: 
1.80      ng       4445:     $result.='&nbsp;<input type="button" '.
1.589     bisitz   4446:              'onclick="javascript:checkPickOne(this.form);" value="'.&mt('Next').' &rarr;" /><br />'."\n";
1.72      ng       4447: 
1.68      ng       4448:     $request->print($result);
                   4449: 
1.485     albertel 4450:     my $studentTable.='&nbsp;<b>'.&mt('Select a student you wish to grade and then click on the Next button.').'</b><br />'.
1.484     albertel 4451: 	&Apache::loncommon::start_data_table().
                   4452: 	&Apache::loncommon::start_data_table_header_row().
1.485     albertel 4453: 	'<th align="right">&nbsp;'.&mt('No.').'</th>'.
1.484     albertel 4454: 	'<th>'.&nameUserString('header').'</th>'.
1.485     albertel 4455: 	'<th align="right">&nbsp;'.&mt('No.').'</th>'.
1.484     albertel 4456: 	'<th>'.&nameUserString('header').'</th>'.
                   4457: 	&Apache::loncommon::end_data_table_header_row();
1.68      ng       4458:  
1.76      ng       4459:     my (undef,undef,$fullname) = &getclasslist($getsec,'1');
1.68      ng       4460:     my $ptr = 1;
1.294     albertel 4461:     foreach my $student (sort 
                   4462: 			 {
                   4463: 			     if (lc($$fullname{$a}) ne lc($$fullname{$b})) {
                   4464: 				 return (lc($$fullname{$a}) cmp lc($$fullname{$b}));
                   4465: 			     }
                   4466: 			     return $a cmp $b;
                   4467: 			 } (keys(%$fullname))) {
1.68      ng       4468: 	my ($uname,$udom) = split(/:/,$student);
1.484     albertel 4469: 	$studentTable.=($ptr%2==1 ? &Apache::loncommon::start_data_table_row()
                   4470:                                   : '</td>');
1.126     ng       4471: 	$studentTable.='<td align="right">'.$ptr.'&nbsp;</td>';
1.288     albertel 4472: 	$studentTable.='<td>&nbsp;<label><input type="radio" name="student" value="'.$student.'" /> '
                   4473: 	    .&nameUserString(undef,$$fullname{$student},$uname,$udom)."</label>\n";
1.484     albertel 4474: 	$studentTable.=
                   4475: 	    ($ptr%2 == 0 ? '</td>'.&Apache::loncommon::end_data_table_row() 
                   4476:                          : '');
1.68      ng       4477: 	$ptr++;
                   4478:     }
1.484     albertel 4479:     if ($ptr%2 == 0) {
                   4480: 	$studentTable.='</td><td>&nbsp;</td><td>&nbsp;</td>'.
                   4481: 	    &Apache::loncommon::end_data_table_row();
                   4482:     }
                   4483:     $studentTable.=&Apache::loncommon::end_data_table()."\n";
1.126     ng       4484:     $studentTable.='<input type="button" '.
1.589     bisitz   4485:                    'onclick="javascript:checkPickOne(this.form);" value="'.&mt('Next').' &rarr;" /></form>'."\n";
1.68      ng       4486: 
1.324     albertel 4487:     $studentTable.=&show_grading_menu_form($symb);
1.68      ng       4488:     $request->print($studentTable);
                   4489: 
                   4490:     return '';
                   4491: }
                   4492: 
                   4493: sub getSymbMap {
1.582     raeburn  4494:     my ($map_error) = @_;
1.132     bowersj2 4495:     my $navmap = Apache::lonnavmaps::navmap->new();
1.582     raeburn  4496:     unless (ref($navmap)) {
                   4497:         if (ref($map_error)) {
                   4498:             $$map_error = 'navmap';
                   4499:         }
                   4500:         return;
                   4501:     }
1.68      ng       4502:     my %symbx = ();
                   4503:     my @titles = ();
1.117     bowersj2 4504:     my $minder = 0;
                   4505: 
                   4506:     # Gather every sequence that has problems.
1.240     albertel 4507:     my @sequences = $navmap->retrieveResources(undef, sub { shift->is_map(); },
                   4508: 					       1,0,1);
1.117     bowersj2 4509:     for my $sequence ($navmap->getById('0.0'), @sequences) {
1.241     albertel 4510: 	if ($navmap->hasResource($sequence, sub { shift->is_problem(); }, 0) ) {
1.381     albertel 4511: 	    my $title = $minder.'.'.
                   4512: 		&HTML::Entities::encode($sequence->compTitle(),'"\'&');
                   4513: 	    push(@titles, $title); # minder in case two titles are identical
                   4514: 	    $symbx{$title} = &HTML::Entities::encode($sequence->symb(),'"\'&');
1.117     bowersj2 4515: 	    $minder++;
1.241     albertel 4516: 	}
1.68      ng       4517:     }
                   4518:     return \@titles,\%symbx;
                   4519: }
                   4520: 
1.72      ng       4521: #
                   4522: #--- Displays a page/sequence w/wo problems, w/wo submissions
1.68      ng       4523: sub displayPage {
                   4524:     my ($request) = shift;
                   4525: 
1.324     albertel 4526:     my ($symb) = &get_symb($request);
1.257     albertel 4527:     my $cdom      = $env{"course.$env{'request.course.id'}.domain"};
                   4528:     my $cnum      = $env{"course.$env{'request.course.id'}.num"};
                   4529:     my $getsec    = $env{'form.section'} eq '' ? 'all' : $env{'form.section'};
                   4530:     my $pageTitle = $env{'form.page'};
1.103     albertel 4531:     my ($classlist,undef,$fullname) = &getclasslist($getsec,'1');
1.257     albertel 4532:     my ($uname,$udom) = split(/:/,$env{'form.student'});
                   4533:     my $usec=$classlist->{$env{'form.student'}}[5];
1.168     albertel 4534: 
                   4535:     #need to make sure we have the correct data for later EXT calls, 
                   4536:     #thus invalidate the cache
                   4537:     &Apache::lonnet::devalidatecourseresdata(
1.257     albertel 4538:                  $env{'course.'.$env{'request.course.id'}.'.num'},
                   4539:                  $env{'course.'.$env{'request.course.id'}.'.domain'});
1.168     albertel 4540:     &Apache::lonnet::clear_EXT_cache_status();
                   4541: 
1.103     albertel 4542:     if (!&canview($usec)) {
1.485     albertel 4543: 	$request->print('<span class="LC_warning">'.&mt('Unable to view requested student. ([_1])',$env{'form.student'}).'</span>');
1.324     albertel 4544: 	$request->print(&show_grading_menu_form($symb));
1.103     albertel 4545: 	return;
                   4546:     }
1.398     albertel 4547:     my $result='<h3><span class="LC_info">&nbsp;'.$env{'form.title'}.'</span></h3>';
1.485     albertel 4548:     $result.='<h3>&nbsp;'.&mt('Student: [_1]',&nameUserString(undef,$$fullname{$env{'form.student'}},$uname,$udom)).
1.129     ng       4549: 	'</h3>'."\n";
1.500     albertel 4550:     $env{'form.CODE'} = uc($env{'form.CODE'});
1.501     foxr     4551:     if (&Apache::lonnet::validCODE(uc($env{'form.CODE'}))) {
1.485     albertel 4552: 	$result.='<h3>&nbsp;'.&mt('CODE: [_1]',$env{'form.CODE'}).'</h3>'."\n";
1.382     albertel 4553:     } else {
                   4554: 	delete($env{'form.CODE'});
                   4555:     }
1.71      ng       4556:     &sub_page_js($request);
                   4557:     $request->print($result);
                   4558: 
1.132     bowersj2 4559:     my $navmap = Apache::lonnavmaps::navmap->new();
1.582     raeburn  4560:     unless (ref($navmap)) {
                   4561:         $request->print(&navmap_errormsg());
                   4562:         $request->print(&show_grading_menu_form($symb));
                   4563:         return;
                   4564:     }
1.257     albertel 4565:     my ($mapUrl, $id, $resUrl)=&Apache::lonnet::decode_symb($env{'form.page'});
1.68      ng       4566:     my $map = $navmap->getResourceByUrl($resUrl); # add to navmaps
1.288     albertel 4567:     if (!$map) {
1.485     albertel 4568: 	$request->print('<span class="LC_warning">'.&mt('Unable to view requested sequence. ([_1])',$resUrl).'</span>');
1.324     albertel 4569: 	$request->print(&show_grading_menu_form($symb));
1.288     albertel 4570: 	return; 
                   4571:     }
1.68      ng       4572:     my $iterator = $navmap->getIterator($map->map_start(),
                   4573: 					$map->map_finish());
                   4574: 
1.71      ng       4575:     my $studentTable='<form action="/adm/grades" method="post" name="gradePage">'."\n".
1.72      ng       4576: 	'<input type="hidden" name="command" value="gradeByPage" />'."\n".
1.257     albertel 4577: 	'<input type="hidden" name="fullname" value="'.$$fullname{$env{'form.student'}}.'" />'."\n".
                   4578: 	'<input type="hidden" name="student" value="'.$env{'form.student'}.'" />'."\n".
1.72      ng       4579: 	'<input type="hidden" name="page"    value="'.$pageTitle.'" />'."\n".
1.257     albertel 4580: 	'<input type="hidden" name="title"   value="'.$env{'form.title'}.'" />'."\n".
1.418     albertel 4581: 	'<input type="hidden" name="symb"    value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
1.125     ng       4582: 	'<input type="hidden" name="overRideScore" value="no" />'."\n".
1.257     albertel 4583: 	'<input type="hidden" name="saveState" value="'.$env{'form.saveState'}.'" />'."\n";
1.71      ng       4584: 
1.382     albertel 4585:     if (defined($env{'form.CODE'})) {
                   4586: 	$studentTable.=
                   4587: 	    '<input type="hidden" name="CODE" value="'.$env{'form.CODE'}.'" />'."\n";
                   4588:     }
1.381     albertel 4589:     my $checkIcon = '<img alt="'.&mt('Check Mark').
1.485     albertel 4590: 	'" src="'.&Apache::loncommon::lonhttpdurl($request->dir_config('lonIconsURL').'/check.gif').'" height="16" border="0" />';
1.71      ng       4591: 
1.594     bisitz   4592:     $studentTable.='&nbsp;<span class="LC_info">'.
                   4593:         &mt('Problems graded correct by the computer are marked with a [_1] symbol.',$checkIcon).
                   4594:         '</span>'."\n".
1.484     albertel 4595: 	&Apache::loncommon::start_data_table().
                   4596: 	&Apache::loncommon::start_data_table_header_row().
                   4597: 	'<th align="center">&nbsp;Prob.&nbsp;</th>'.
1.485     albertel 4598: 	'<th>&nbsp;'.($env{'form.vProb'} eq 'no' ? &mt('Title') : &mt('Problem Text')).'/'.&mt('Grade').'</th>'.
1.484     albertel 4599: 	&Apache::loncommon::end_data_table_header_row();
1.71      ng       4600: 
1.329     albertel 4601:     &Apache::lonxml::clear_problem_counter();
1.196     albertel 4602:     my ($depth,$question,$prob) = (1,1,1);
1.68      ng       4603:     $iterator->next(); # skip the first BEGIN_MAP
                   4604:     my $curRes = $iterator->next(); # for "current resource"
1.101     albertel 4605:     while ($depth > 0) {
1.68      ng       4606:         if($curRes == $iterator->BEGIN_MAP) { $depth++; }
1.100     bowersj2 4607:         if($curRes == $iterator->END_MAP) { $depth--; }
1.68      ng       4608: 
1.385     albertel 4609:         if (ref($curRes) && $curRes->is_problem()) {
1.91      albertel 4610: 	    my $parts = $curRes->parts();
1.68      ng       4611:             my $title = $curRes->compTitle();
1.71      ng       4612: 	    my $symbx = $curRes->symb();
1.484     albertel 4613: 	    $studentTable.=
                   4614: 		&Apache::loncommon::start_data_table_row().
                   4615: 		'<td align="center" valign="top" >'.$prob.
1.485     albertel 4616: 		(scalar(@{$parts}) == 1 ? '' 
1.596.2.2  raeburn  4617: 		                        : '<br />('.&mt('[_1]parts)',
                   4618: 							scalar(@{$parts}).'&nbsp;')
1.485     albertel 4619: 		 ).
                   4620: 		 '</td>';
1.71      ng       4621: 	    $studentTable.='<td valign="top">';
1.382     albertel 4622: 	    my %form = ('CODE' => $env{'form.CODE'},);
1.257     albertel 4623: 	    if ($env{'form.vProb'} eq 'yes' ) {
1.144     albertel 4624: 		$studentTable.=&show_problem($request,$symbx,$uname,$udom,1,
1.383     albertel 4625: 					     undef,'both',\%form);
1.71      ng       4626: 	    } else {
1.382     albertel 4627: 		my $companswer = &Apache::loncommon::get_student_answers($symbx,$uname,$udom,$env{'request.course.id'},%form);
1.80      ng       4628: 		$companswer =~ s|<form(.*?)>||g;
                   4629: 		$companswer =~ s|</form>||g;
1.71      ng       4630: #		while ($companswer =~ /(<a href\=\"javascript:newWindow.*?Script Vars<\/a>)/s) { #<a href="javascript:newWindow</a>
1.116     ng       4631: #		    $companswer =~ s/$1/ /ms;
1.326     albertel 4632: #		    $request->print('match='.$1."<br />\n");
1.71      ng       4633: #		}
1.116     ng       4634: #		$companswer =~ s|<table border=\"1\">|<table border=\"0\">|g;
1.539     riegler  4635: 		$studentTable.='&nbsp;<b>'.$title.'</b>&nbsp;<br />&nbsp;<b>'.&mt('Correct answer').':</b><br />'.$companswer;
1.71      ng       4636: 	    }
                   4637: 
1.257     albertel 4638: 	    my %record = &Apache::lonnet::restore($symbx,$env{'request.course.id'},$udom,$uname);
1.125     ng       4639: 
1.257     albertel 4640: 	    if ($env{'form.lastSub'} eq 'datesub') {
1.71      ng       4641: 		if ($record{'version'} eq '') {
1.485     albertel 4642: 		    $studentTable.='<br />&nbsp;<span class="LC_warning">'.&mt('No recorded submission for this problem.').'</span><br />';
1.71      ng       4643: 		} else {
1.116     ng       4644: 		    my %responseType = ();
                   4645: 		    foreach my $partid (@{$parts}) {
1.147     albertel 4646: 			my @responseIds =$curRes->responseIds($partid);
                   4647: 			my @responseType =$curRes->responseType($partid);
                   4648: 			my %responseIds;
                   4649: 			for (my $i=0;$i<=$#responseIds;$i++) {
                   4650: 			    $responseIds{$responseIds[$i]}=$responseType[$i];
                   4651: 			}
                   4652: 			$responseType{$partid} = \%responseIds;
1.116     ng       4653: 		    }
1.148     albertel 4654: 		    $studentTable.= &displaySubByDates($symbx,\%record,$parts,\%responseType,$checkIcon,$uname,$udom);
1.147     albertel 4655: 
1.71      ng       4656: 		}
1.257     albertel 4657: 	    } elsif ($env{'form.lastSub'} eq 'all') {
                   4658: 		my $last = ($env{'form.lastSub'} eq 'last' ? 'last' : '');
1.71      ng       4659: 		$studentTable.=&Apache::loncommon::get_previous_attempt($symbx,$uname,$udom,
1.257     albertel 4660: 									$env{'request.course.id'},
1.71      ng       4661: 									'','.submission');
                   4662:  
                   4663: 	    }
1.103     albertel 4664: 	    if (&canmodify($usec)) {
1.585     bisitz   4665:             $studentTable.=&gradeBox_start();
1.103     albertel 4666: 		foreach my $partid (@{$parts}) {
                   4667: 		    $studentTable.=&gradeBox($request,$symbx,$uname,$udom,$question,$partid,\%record);
                   4668: 		    $studentTable.='<input type="hidden" name="q_'.$question.'" value="'.$partid.'" />'."\n";
                   4669: 		    $question++;
                   4670: 		}
1.585     bisitz   4671:             $studentTable.=&gradeBox_end();
1.196     albertel 4672: 		$prob++;
1.71      ng       4673: 	    }
                   4674: 	    $studentTable.='</td></tr>';
1.68      ng       4675: 
1.103     albertel 4676: 	}
1.68      ng       4677:         $curRes = $iterator->next();
                   4678:     }
                   4679: 
1.589     bisitz   4680:     $studentTable.=
                   4681:         '</table>'."\n".
                   4682:         '<input type="button" value="'.&mt('Save').'" '.
                   4683:         'onclick="javascript:checkSubmitPage(this.form,'.$question.');" />'.
                   4684:         '</form>'."\n";
1.324     albertel 4685:     $studentTable.=&show_grading_menu_form($symb);
1.71      ng       4686:     $request->print($studentTable);
                   4687: 
                   4688:     return '';
1.119     ng       4689: }
                   4690: 
                   4691: sub displaySubByDates {
1.148     albertel 4692:     my ($symb,$record,$parts,$responseType,$checkIcon,$uname,$udom) = @_;
1.224     albertel 4693:     my $isCODE=0;
1.335     albertel 4694:     my $isTask = ($symb =~/\.task$/);
1.224     albertel 4695:     if (exists($record->{'resource.CODE'})) { $isCODE=1; }
1.467     albertel 4696:     my $studentTable=&Apache::loncommon::start_data_table().
                   4697: 	&Apache::loncommon::start_data_table_header_row().
                   4698: 	'<th>'.&mt('Date/Time').'</th>'.
                   4699: 	($isCODE?'<th>'.&mt('CODE').'</th>':'').
                   4700: 	'<th>'.&mt('Submission').'</th>'.
                   4701: 	'<th>'.&mt('Status').'</th>'.
                   4702: 	&Apache::loncommon::end_data_table_header_row();
1.119     ng       4703:     my ($version);
                   4704:     my %mark;
1.148     albertel 4705:     my %orders;
1.119     ng       4706:     $mark{'correct_by_student'} = $checkIcon;
1.147     albertel 4707:     if (!exists($$record{'1:timestamp'})) {
1.539     riegler  4708: 	return '<br />&nbsp;<span class="LC_warning">'.&mt('Nothing submitted - no attempts.').'</span><br />';
1.147     albertel 4709:     }
1.335     albertel 4710: 
                   4711:     my $interaction;
1.525     raeburn  4712:     my $no_increment = 1;
1.596.2.2  raeburn  4713:     my %lastrndseed;
1.119     ng       4714:     for ($version=1;$version<=$$record{'version'};$version++) {
1.467     albertel 4715: 	my $timestamp = 
                   4716: 	    &Apache::lonlocal::locallocaltime($$record{$version.':timestamp'});
1.335     albertel 4717: 	if (exists($$record{$version.':resource.0.version'})) {
                   4718: 	    $interaction = $$record{$version.':resource.0.version'};
                   4719: 	}
                   4720: 
                   4721: 	my $where = ($isTask ? "$version:resource.$interaction"
                   4722: 		             : "$version:resource");
1.467     albertel 4723: 	$studentTable.=&Apache::loncommon::start_data_table_row().
                   4724: 	    '<td>'.$timestamp.'</td>';
1.224     albertel 4725: 	if ($isCODE) {
                   4726: 	    $studentTable.='<td>'.$record->{$version.':resource.CODE'}.'</td>';
                   4727: 	}
1.119     ng       4728: 	my @versionKeys = split(/\:/,$$record{$version.':keys'});
                   4729: 	my @displaySub = ();
                   4730: 	foreach my $partid (@{$parts}) {
1.596.2.2  raeburn  4731:             my ($hidden,$type);
                   4732:             $type = $$record{$version.':resource.'.$partid.'.type'};
                   4733:             if (($type eq 'anonsurvey') || ($type eq 'anonsurveycred')) {
1.596     raeburn  4734:                 $hidden = 1;
                   4735:             }
1.335     albertel 4736: 	    my @matchKey = ($isTask ? sort(grep /^resource\.\d+\.\Q$partid\E\.award$/,@versionKeys)
                   4737: 			            : sort(grep /^resource\.\Q$partid\E\..*?\.submission$/,@versionKeys));
                   4738: 	    
1.122     ng       4739: #	    next if ($$record{"$version:resource.$partid.solved"} eq '');
1.324     albertel 4740: 	    my $display_part=&get_display_part($partid,$symb);
1.147     albertel 4741: 	    foreach my $matchKey (@matchKey) {
1.198     albertel 4742: 		if (exists($$record{$version.':'.$matchKey}) &&
                   4743: 		    $$record{$version.':'.$matchKey} ne '') {
1.596     raeburn  4744:                     
1.335     albertel 4745: 		    my ($responseId)= ($isTask ? ($matchKey=~ /^resource\.(.*?)\.\Q$partid\E\.award$/)
                   4746: 				               : ($matchKey=~ /^resource\.\Q$partid\E\.(.*?)\.submission$/));
1.577     bisitz   4747:                     $displaySub[0].='<span class="LC_nobreak"';
                   4748:                     $displaySub[0].='<b>'.&mt('Part: [_1]',$display_part).'</b>'
                   4749:                                    .' <span class="LC_internal_info">'
1.596.2.4  raeburn  4750:                                    .'('.&mt('Response ID: [_1]',$responseId).')'
1.577     bisitz   4751:                                    .'</span>'
                   4752:                                    .' <b>';
1.596     raeburn  4753:                     if ($hidden) {
                   4754:                         $displaySub[0].= &mt('Anonymous Survey').'</b>';
                   4755:                     } else {
1.596.2.2  raeburn  4756:                         my ($trial,$rndseed,$newvariation);
                   4757:                         if ($type eq 'randomizetry') {
                   4758:                             $trial = $$record{"$where.$partid.tries"};
                   4759:                             $rndseed = $$record{"$where.$partid.rndseed"};
                   4760:                         }
1.596     raeburn  4761: 		        if ($$record{"$where.$partid.tries"} eq '') {
                   4762: 			    $displaySub[0].=&mt('Trial not counted');
                   4763: 		        } else {
                   4764: 			    $displaySub[0].=&mt('Trial: [_1]',
1.467     albertel 4765: 					    $$record{"$where.$partid.tries"});
1.596.2.2  raeburn  4766:                             if ($rndseed || $lastrndseed{$partid}) {
                   4767:                                 if ($rndseed ne $lastrndseed{$partid}) {
                   4768:                                     $newvariation = '&nbsp;('.&mt('New variation this try').')';
                   4769:                                 }
                   4770:                             }
1.596     raeburn  4771: 		        }
                   4772: 		        my $responseType=($isTask ? 'Task'
1.335     albertel 4773:                                               : $responseType->{$partid}->{$responseId});
1.596     raeburn  4774: 		        if (!exists($orders{$partid})) { $orders{$partid}={}; }
1.596.2.2  raeburn  4775: 		        if ((!exists($orders{$partid}->{$responseId})) || ($trial)) {
1.596     raeburn  4776: 			    $orders{$partid}->{$responseId}=
                   4777: 			        &get_order($partid,$responseId,$symb,$uname,$udom,
1.596.2.2  raeburn  4778:                                            $no_increment,$type,$trial,$rndseed);
1.596     raeburn  4779: 		        }
1.596.2.2  raeburn  4780: 		        $displaySub[0].='</b>'.$newvariation.'</span>'; # /nobreak
1.596     raeburn  4781: 		        $displaySub[0].='&nbsp; '.
1.596.2.2  raeburn  4782: 			    &cleanRecord($$record{$version.':'.$matchKey},$responseType,$symb,$partid,$responseId,$record,$orders{$partid}->{$responseId},"$version:",$uname,$udom,$type,$trial,$rndseed).'<br />';
1.596     raeburn  4783:                     }
1.147     albertel 4784: 		}
                   4785: 	    }
1.335     albertel 4786: 	    if (exists($$record{"$where.$partid.checkedin"})) {
1.485     albertel 4787: 		$displaySub[1].=&mt('Checked in by [_1] into slot [_2]',
                   4788: 				    $$record{"$where.$partid.checkedin"},
                   4789: 				    $$record{"$where.$partid.checkedin.slot"}).
                   4790: 					'<br />';
1.335     albertel 4791: 	    }
                   4792: 	    if (exists $$record{"$where.$partid.award"}) {
1.485     albertel 4793: 		$displaySub[1].='<b>'.&mt('Part:').'</b>&nbsp;'.$display_part.' &nbsp;'.
1.335     albertel 4794: 		    lc($$record{"$where.$partid.award"}).' '.
                   4795: 		    $mark{$$record{"$where.$partid.solved"}}.
1.147     albertel 4796: 		    '<br />';
                   4797: 	    }
1.335     albertel 4798: 	    if (exists $$record{"$where.$partid.regrader"}) {
                   4799: 		$displaySub[2].=$$record{"$where.$partid.regrader"}.
                   4800: 		    ' (<b>'.&mt('Part').':</b> '.$display_part.')';
                   4801: 	    } elsif ($$record{"$version:resource.$partid.regrader"} =~ /\S/) {
                   4802: 		$displaySub[2].=
                   4803: 		    $$record{"$version:resource.$partid.regrader"}.
1.207     albertel 4804: 		    ' (<b>'.&mt('Part').':</b> '.$display_part.')';
1.147     albertel 4805: 	    }
                   4806: 	}
                   4807: 	# needed because old essay regrader has not parts info
                   4808: 	if (exists $$record{"$version:resource.regrader"}) {
                   4809: 	    $displaySub[2].=$$record{"$version:resource.regrader"};
                   4810: 	}
                   4811: 	$studentTable.='<td>'.$displaySub[0].'&nbsp;</td><td>'.$displaySub[1];
                   4812: 	if ($displaySub[2]) {
1.467     albertel 4813: 	    $studentTable.=&mt('Manually graded by [_1]',$displaySub[2]);
1.147     albertel 4814: 	}
1.467     albertel 4815: 	$studentTable.='&nbsp;</td>'.
                   4816: 	    &Apache::loncommon::end_data_table_row();
1.119     ng       4817:     }
1.467     albertel 4818:     $studentTable.=&Apache::loncommon::end_data_table();
1.119     ng       4819:     return $studentTable;
1.71      ng       4820: }
                   4821: 
                   4822: sub updateGradeByPage {
                   4823:     my ($request) = shift;
                   4824: 
1.257     albertel 4825:     my $cdom      = $env{"course.$env{'request.course.id'}.domain"};
                   4826:     my $cnum      = $env{"course.$env{'request.course.id'}.num"};
                   4827:     my $getsec    = $env{'form.section'} eq '' ? 'all' : $env{'form.section'};
                   4828:     my $pageTitle = $env{'form.page'};
1.103     albertel 4829:     my ($classlist,undef,$fullname) = &getclasslist($getsec,'1');
1.257     albertel 4830:     my ($uname,$udom) = split(/:/,$env{'form.student'});
                   4831:     my $usec=$classlist->{$env{'form.student'}}[5];
1.103     albertel 4832:     if (!&canmodify($usec)) {
1.526     raeburn  4833: 	$request->print('<span class="LC_warning">'.&mt('Unable to modify requested student ([_1])',$env{'form.student'}).'</span>');
1.324     albertel 4834: 	$request->print(&show_grading_menu_form($env{'form.symb'}));
1.103     albertel 4835: 	return;
                   4836:     }
1.398     albertel 4837:     my $result='<h3><span class="LC_info">&nbsp;'.$env{'form.title'}.'</span></h3>';
1.526     raeburn  4838:     $result.='<h3>&nbsp;'.&mt('Student: ').&nameUserString(undef,$env{'form.fullname'},$uname,$udom).
1.129     ng       4839: 	'</h3>'."\n";
1.70      ng       4840: 
1.68      ng       4841:     $request->print($result);
                   4842: 
1.582     raeburn  4843: 
1.132     bowersj2 4844:     my $navmap = Apache::lonnavmaps::navmap->new();
1.582     raeburn  4845:     unless (ref($navmap)) {
                   4846:         $request->print(&navmap_errormsg());
                   4847:         return;
                   4848:     }
1.257     albertel 4849:     my ($mapUrl, $id, $resUrl) = &Apache::lonnet::decode_symb( $env{'form.page'});
1.71      ng       4850:     my $map = $navmap->getResourceByUrl($resUrl); # add to navmaps
1.288     albertel 4851:     if (!$map) {
1.527     raeburn  4852: 	$request->print('<span class="LC_warning">'.&mt('Unable to grade requested sequence ([_1]).',$resUrl).'</span>');
1.324     albertel 4853: 	my ($symb)=&get_symb($request);
                   4854: 	$request->print(&show_grading_menu_form($symb));
1.288     albertel 4855: 	return; 
                   4856:     }
1.71      ng       4857:     my $iterator = $navmap->getIterator($map->map_start(),
                   4858: 					$map->map_finish());
1.70      ng       4859: 
1.484     albertel 4860:     my $studentTable=
                   4861: 	&Apache::loncommon::start_data_table().
                   4862: 	&Apache::loncommon::start_data_table_header_row().
1.485     albertel 4863: 	'<th align="center">&nbsp;'.&mt('Prob.').'&nbsp;</th>'.
                   4864: 	'<th>&nbsp;'.&mt('Title').'&nbsp;</th>'.
                   4865: 	'<th>&nbsp;'.&mt('Previous Score').'&nbsp;</th>'.
                   4866: 	'<th>&nbsp;'.&mt('New Score').'&nbsp;</th>'.
1.484     albertel 4867: 	&Apache::loncommon::end_data_table_header_row();
1.71      ng       4868: 
                   4869:     $iterator->next(); # skip the first BEGIN_MAP
                   4870:     my $curRes = $iterator->next(); # for "current resource"
1.196     albertel 4871:     my ($depth,$question,$prob,$changeflag)= (1,1,1,0);
1.101     albertel 4872:     while ($depth > 0) {
1.71      ng       4873:         if($curRes == $iterator->BEGIN_MAP) { $depth++; }
1.100     bowersj2 4874:         if($curRes == $iterator->END_MAP) { $depth--; }
1.71      ng       4875: 
1.385     albertel 4876:         if (ref($curRes) && $curRes->is_problem()) {
1.91      albertel 4877: 	    my $parts = $curRes->parts();
1.71      ng       4878:             my $title = $curRes->compTitle();
                   4879: 	    my $symbx = $curRes->symb();
1.484     albertel 4880: 	    $studentTable.=
                   4881: 		&Apache::loncommon::start_data_table_row().
                   4882: 		'<td align="center" valign="top" >'.$prob.
1.485     albertel 4883: 		(scalar(@{$parts}) == 1 ? '' 
1.596.2.2  raeburn  4884:                                         : '<br />('.&mt('[quant,_1,part]',scalar(@{$parts}))
1.526     raeburn  4885: 		.')').'</td>';
1.71      ng       4886: 	    $studentTable.='<td valign="top">&nbsp;<b>'.$title.'</b>&nbsp;</td>';
                   4887: 
                   4888: 	    my %newrecord=();
                   4889: 	    my @displayPts=();
1.269     raeburn  4890:             my %aggregate = ();
                   4891:             my $aggregateflag = 0;
1.71      ng       4892: 	    foreach my $partid (@{$parts}) {
1.257     albertel 4893: 		my $newpts = $env{'form.GD_BOX'.$question.'_'.$partid};
                   4894: 		my $oldpts = $env{'form.oldpts'.$question.'_'.$partid};
1.71      ng       4895: 
1.257     albertel 4896: 		my $wgt = $env{'form.WGT'.$question.'_'.$partid} != 0 ? 
                   4897: 		    $env{'form.WGT'.$question.'_'.$partid} : 1;
1.71      ng       4898: 		my $partial = $newpts/$wgt;
                   4899: 		my $score;
                   4900: 		if ($partial > 0) {
                   4901: 		    $score = 'correct_by_override';
1.125     ng       4902: 		} elsif ($newpts ne '') { #empty is taken as 0
1.71      ng       4903: 		    $score = 'incorrect_by_override';
                   4904: 		}
1.257     albertel 4905: 		my $dropMenu = $env{'form.GD_SEL'.$question.'_'.$partid};
1.125     ng       4906: 		if ($dropMenu eq 'excused') {
1.71      ng       4907: 		    $partial = '';
                   4908: 		    $score = 'excused';
1.125     ng       4909: 		} elsif ($dropMenu eq 'reset status'
1.257     albertel 4910: 			 && $env{'form.solved'.$question.'_'.$partid} ne '') { #update only if previous record exists
1.125     ng       4911: 		    $newrecord{'resource.'.$partid.'.tries'} = 0;
                   4912: 		    $newrecord{'resource.'.$partid.'.solved'} = '';
                   4913: 		    $newrecord{'resource.'.$partid.'.award'} = '';
                   4914: 		    $newrecord{'resource.'.$partid.'.awarded'} = 0;
1.257     albertel 4915: 		    $newrecord{'resource.'.$partid.'.regrader'} = "$env{'user.name'}:$env{'user.domain'}";
1.125     ng       4916: 		    $changeflag++;
                   4917: 		    $newpts = '';
1.269     raeburn  4918:                     
                   4919:                     my $aggtries =  $env{'form.aggtries'.$question.'_'.$partid};
                   4920:                     my $totaltries = $env{'form.totaltries'.$question.'_'.$partid};
                   4921:                     my $solvedstatus = $env{'form.solved'.$question.'_'.$partid};
                   4922:                     if ($aggtries > 0) {
                   4923:                         &decrement_aggs($symbx,$partid,\%aggregate,$aggtries,$totaltries,$solvedstatus);
                   4924:                         $aggregateflag = 1;
                   4925:                     }
1.71      ng       4926: 		}
1.324     albertel 4927: 		my $display_part=&get_display_part($partid,$curRes->symb());
1.257     albertel 4928: 		my $oldstatus = $env{'form.solved'.$question.'_'.$partid};
1.526     raeburn  4929: 		$displayPts[0].='&nbsp;<b>'.&mt('Part').':</b> '.$display_part.' = '.
1.71      ng       4930: 		    (($oldstatus eq 'excused') ? 'excused' : $oldpts).
1.326     albertel 4931: 		    '&nbsp;<br />';
1.526     raeburn  4932: 		$displayPts[1].='&nbsp;<b>'.&mt('Part').':</b> '.$display_part.' = '.
1.125     ng       4933: 		     (($score eq 'excused') ? 'excused' : $newpts).
1.326     albertel 4934: 		    '&nbsp;<br />';
1.71      ng       4935: 		$question++;
1.380     albertel 4936: 		next if ($dropMenu eq 'reset status' || ($newpts eq $oldpts && $score ne 'excused'));
1.125     ng       4937: 
1.71      ng       4938: 		$newrecord{'resource.'.$partid.'.awarded'}  = $partial if $partial ne '';
1.125     ng       4939: 		$newrecord{'resource.'.$partid.'.solved'}   = $score if $score ne '';
1.257     albertel 4940: 		$newrecord{'resource.'.$partid.'.regrader'} = "$env{'user.name'}:$env{'user.domain'}"
1.125     ng       4941: 		    if (scalar(keys(%newrecord)) > 0);
1.71      ng       4942: 
                   4943: 		$changeflag++;
                   4944: 	    }
                   4945: 	    if (scalar(keys(%newrecord)) > 0) {
1.382     albertel 4946: 		my %record = 
                   4947: 		    &Apache::lonnet::restore($symbx,$env{'request.course.id'},
                   4948: 					     $udom,$uname);
                   4949: 
                   4950: 		if (&Apache::lonnet::validCODE($env{'form.CODE'})) {
                   4951: 		    $newrecord{'resource.CODE'} = $env{'form.CODE'};
                   4952: 		} elsif (&Apache::lonnet::validCODE($record{'resource.CODE'})) {
                   4953: 		    $newrecord{'resource.CODE'} = '';
                   4954: 		}
1.257     albertel 4955: 		&Apache::lonnet::cstore(\%newrecord,$symbx,$env{'request.course.id'},
1.71      ng       4956: 					$udom,$uname);
1.382     albertel 4957: 		%record = &Apache::lonnet::restore($symbx,
                   4958: 						   $env{'request.course.id'},
                   4959: 						   $udom,$uname);
1.380     albertel 4960: 		&check_and_remove_from_queue($parts,\%record,undef,$symbx,
                   4961: 					     $cdom,$cnum,$udom,$uname);
1.71      ng       4962: 	    }
1.380     albertel 4963: 	    
1.269     raeburn  4964:             if ($aggregateflag) {
                   4965:                 &Apache::lonnet::cinc('nohist_resourcetracker',\%aggregate,
                   4966:                       $env{'course.'.$env{'request.course.id'}.'.domain'},
                   4967:                       $env{'course.'.$env{'request.course.id'}.'.num'});
                   4968:             }
1.125     ng       4969: 
1.71      ng       4970: 	    $studentTable.='<td valign="top">'.$displayPts[0].'</td>'.
                   4971: 		'<td valign="top">'.$displayPts[1].'</td>'.
1.484     albertel 4972: 		&Apache::loncommon::end_data_table_row();
1.68      ng       4973: 
1.196     albertel 4974: 	    $prob++;
1.68      ng       4975: 	}
1.71      ng       4976:         $curRes = $iterator->next();
1.68      ng       4977:     }
1.98      albertel 4978: 
1.484     albertel 4979:     $studentTable.=&Apache::loncommon::end_data_table();
1.324     albertel 4980:     $studentTable.=&show_grading_menu_form($env{'form.symb'});
1.526     raeburn  4981:     my $grademsg=($changeflag == 0 ? &mt('No score was changed or updated.') :
                   4982: 		  &mt('The scores were changed for [quant,_1,problem].',
                   4983: 		  $changeflag));
1.76      ng       4984:     $request->print($grademsg.$studentTable);
1.68      ng       4985: 
1.70      ng       4986:     return '';
                   4987: }
                   4988: 
1.72      ng       4989: #-------- end of section for handling grading by page/sequence ---------
                   4990: #
                   4991: #-------------------------------------------------------------------
                   4992: 
1.581     www      4993: #-------------------- Bubblesheet (Scantron) Grading -------------------
1.75      albertel 4994: #
                   4995: #------ start of section for handling grading by page/sequence ---------
                   4996: 
1.423     albertel 4997: =pod
                   4998: 
                   4999: =head1 Bubble sheet grading routines
                   5000: 
1.424     albertel 5001:   For this documentation:
                   5002: 
                   5003:    'scanline' refers to the full line of characters
                   5004:    from the file that we are parsing that represents one entire sheet
                   5005: 
                   5006:    'bubble line' refers to the data
1.596.2.6  raeburn  5007:    representing the line of bubbles that are on the physical bubblesheet
1.424     albertel 5008: 
                   5009: 
1.596.2.6  raeburn  5010: The overall process is that a scanned in bubblesheet data is uploaded
1.424     albertel 5011: into a course. When a user wants to grade, they select a
1.596.2.6  raeburn  5012: sequence/folder of resources, a file of bubblesheet info, and pick
1.424     albertel 5013: one of the predefined configurations for what each scanline looks
                   5014: like.
                   5015: 
                   5016: Next each scanline is checked for any errors of either 'missing
1.435     foxr     5017: bubbles' (it's an error because it may have been mis-scanned
1.424     albertel 5018: because too light bubbling), 'double bubble' (each bubble line should
                   5019: have no more that one letter picked), invalid or duplicated CODE,
1.556     weissno  5020: invalid student/employee ID
1.424     albertel 5021: 
                   5022: If the CODE option is used that determines the randomization of the
1.556     weissno  5023: homework problems, either way the student/employee ID is looked up into a
1.424     albertel 5024: username:domain.
                   5025: 
                   5026: During the validation phase the instructor can choose to skip scanlines. 
                   5027: 
1.596.2.6  raeburn  5028: After the validation phase, there are now 3 bubblesheet files
1.424     albertel 5029: 
                   5030:   scantron_original_filename (unmodified original file)
                   5031:   scantron_corrected_filename (file where the corrected information has replaced the original information)
                   5032:   scantron_skipped_filename (contains the exact text of scanlines that where skipped)
                   5033: 
                   5034: Also there is a separate hash nohist_scantrondata that contains extra
1.596.2.6  raeburn  5035: correction information that isn't representable in the bubblesheet
1.424     albertel 5036: file (see &scantron_getfile() for more information)
                   5037: 
                   5038: After all scanlines are either valid, marked as valid or skipped, then
                   5039: foreach line foreach problem in the picked sequence, an ssi request is
                   5040: made that simulates a user submitting their selected letter(s) against
                   5041: the homework problem.
1.423     albertel 5042: 
                   5043: =over 4
                   5044: 
                   5045: 
                   5046: 
                   5047: =item defaultFormData
                   5048: 
                   5049:   Returns html hidden inputs used to hold context/default values.
                   5050: 
                   5051:  Arguments:
                   5052:   $symb - $symb of the current resource 
                   5053: 
                   5054: =cut
1.422     foxr     5055: 
1.81      albertel 5056: sub defaultFormData {
1.324     albertel 5057:     my ($symb)=@_;
1.447     foxr     5058:     return '<input type="hidden" name="symb"    value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
1.257     albertel 5059:      '<input type="hidden" name="saveState" value="'.$env{'form.saveState'}.'" />'."\n".
                   5060:      '<input type="hidden" name="probTitle" value="'.$env{'form.probTitle'}.'" />'."\n";
1.81      albertel 5061: }
                   5062: 
1.447     foxr     5063: 
1.423     albertel 5064: =pod 
                   5065: 
                   5066: =item getSequenceDropDown
                   5067: 
                   5068:    Return html dropdown of possible sequences to grade
                   5069:  
                   5070:  Arguments:
1.582     raeburn  5071:    $symb - $symb of the current resource
                   5072:    $map_error - ref to scalar which will container error if
                   5073:                 $navmap object is unavailable in &getSymbMap().
1.423     albertel 5074: 
                   5075: =cut
1.422     foxr     5076: 
1.75      albertel 5077: sub getSequenceDropDown {
1.582     raeburn  5078:     my ($symb,$map_error)=@_;
1.75      albertel 5079:     my $result='<select name="selectpage">'."\n";
1.582     raeburn  5080:     my ($titles,$symbx) = &getSymbMap($map_error);
                   5081:     if (ref($map_error)) {
                   5082:         return if ($$map_error);
                   5083:     }
1.137     albertel 5084:     my ($curpage)=&Apache::lonnet::decode_symb($symb); 
1.75      albertel 5085:     my $ctr=0;
                   5086:     foreach (@$titles) {
                   5087: 	my ($minder,$showtitle) = ($_ =~ /(\d+)\.(.*)/);
                   5088: 	$result.='<option value="'.$$symbx{$_}.'" '.
1.401     albertel 5089: 	    ($$symbx{$_} =~ /$curpage$/ ? 'selected="selected"' : '').
1.75      albertel 5090: 	    '>'.$showtitle.'</option>'."\n";
                   5091: 	$ctr++;
                   5092:     }
                   5093:     $result.= '</select>';
                   5094:     return $result;
                   5095: }
                   5096: 
1.495     albertel 5097: my %bubble_lines_per_response;     # no. bubble lines for each response.
1.554     raeburn  5098:                                    # key is zero-based index - 0, 1, 2 ...
1.495     albertel 5099: 
                   5100: my %first_bubble_line;             # First bubble line no. for each bubble.
                   5101: 
1.509     raeburn  5102: my %subdivided_bubble_lines;       # no. bubble lines for optionresponse, 
                   5103:                                    # matchresponse or rankresponse, where 
                   5104:                                    # an individual response can have multiple 
                   5105:                                    # lines
1.503     raeburn  5106: 
                   5107: my %responsetype_per_response;     # responsetype for each response
                   5108: 
1.495     albertel 5109: # Save and restore the bubble lines array to the form env.
                   5110: 
                   5111: 
                   5112: sub save_bubble_lines {
                   5113:     foreach my $line (keys(%bubble_lines_per_response)) {
                   5114: 	$env{"form.scantron.bubblelines.$line"}  = $bubble_lines_per_response{$line};
                   5115: 	$env{"form.scantron.first_bubble_line.$line"} =
                   5116: 	    $first_bubble_line{$line};
1.503     raeburn  5117:         $env{"form.scantron.sub_bubblelines.$line"} = 
                   5118:             $subdivided_bubble_lines{$line};
                   5119:         $env{"form.scantron.responsetype.$line"} =
                   5120:             $responsetype_per_response{$line};
1.495     albertel 5121:     }
                   5122: }
                   5123: 
                   5124: 
                   5125: sub restore_bubble_lines {
                   5126:     my $line = 0;
                   5127:     %bubble_lines_per_response = ();
                   5128:     while ($env{"form.scantron.bubblelines.$line"}) {
                   5129: 	my $value = $env{"form.scantron.bubblelines.$line"};
                   5130: 	$bubble_lines_per_response{$line} = $value;
                   5131: 	$first_bubble_line{$line}  =
                   5132: 	    $env{"form.scantron.first_bubble_line.$line"};
1.503     raeburn  5133:         $subdivided_bubble_lines{$line} =
                   5134:             $env{"form.scantron.sub_bubblelines.$line"};
                   5135:         $responsetype_per_response{$line} =
                   5136:             $env{"form.scantron.responsetype.$line"};
1.495     albertel 5137: 	$line++;
                   5138:     }
                   5139: }
                   5140: 
                   5141: #  Given the parsed scanline, get the response for 
                   5142: #  'answer' number n:
                   5143: 
                   5144: sub get_response_bubbles {
                   5145:     my ($parsed_line, $response)  = @_;
                   5146: 
                   5147:     my $bubble_line = $first_bubble_line{$response-1} +1;
                   5148:     my $bubble_lines= $bubble_lines_per_response{$response-1};
                   5149:     
                   5150:     my $selected = "";
                   5151: 
                   5152:     for (my $bline = 0; $bline < $bubble_lines; $bline++) {
                   5153: 	$selected .= $$parsed_line{"scantron.$bubble_line.answer"}.":";
                   5154: 	$bubble_line++;
                   5155:     }
                   5156:     return $selected;
                   5157: }
1.423     albertel 5158: 
                   5159: =pod 
                   5160: 
                   5161: =item scantron_filenames
                   5162: 
                   5163:    Returns a list of the scantron files in the current course 
                   5164: 
                   5165: =cut
1.422     foxr     5166: 
1.202     albertel 5167: sub scantron_filenames {
1.257     albertel 5168:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
                   5169:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
1.517     raeburn  5170:     my $getpropath = 1;
1.596.2.12.2.  (raeburn 5171:):     my ($dirlist,$listerror) = &Apache::lonnet::dirlist('userfiles',$cdom,
                   5172:):                                                         $cname,$getpropath);
1.202     albertel 5173:     my @possiblenames;
1.596.2.12.2.  (raeburn 5174:):     if (ref($dirlist) eq 'ARRAY') {
                   5175:):         foreach my $filename (sort(@{$dirlist})) {
                   5176:): 	    ($filename)=split(/&/,$filename);
                   5177:): 	    if ($filename!~/^scantron_orig_/) { next ; }
                   5178:): 	    $filename=~s/^scantron_orig_//;
                   5179:): 	    push(@possiblenames,$filename);
                   5180:):         }
1.202     albertel 5181:     }
                   5182:     return @possiblenames;
                   5183: }
                   5184: 
1.423     albertel 5185: =pod 
                   5186: 
                   5187: =item scantron_uploads
                   5188: 
                   5189:    Returns  html drop-down list of scantron files in current course.
                   5190: 
                   5191:  Arguments:
                   5192:    $file2grade - filename to set as selected in the dropdown
                   5193: 
                   5194: =cut
1.422     foxr     5195: 
1.202     albertel 5196: sub scantron_uploads {
1.209     ng       5197:     my ($file2grade) = @_;
1.202     albertel 5198:     my $result=	'<select name="scantron_selectfile">';
                   5199:     $result.="<option></option>";
                   5200:     foreach my $filename (sort(&scantron_filenames())) {
1.401     albertel 5201: 	$result.="<option".($filename eq $file2grade ? ' selected="selected"':'').">$filename</option>\n";
1.81      albertel 5202:     }
                   5203:     $result.="</select>";
                   5204:     return $result;
                   5205: }
                   5206: 
1.423     albertel 5207: =pod 
                   5208: 
                   5209: =item scantron_scantab
                   5210: 
                   5211:   Returns html drop down of the scantron formats in the scantronformat.tab
                   5212:   file.
                   5213: 
                   5214: =cut
1.422     foxr     5215: 
1.82      albertel 5216: sub scantron_scantab {
                   5217:     my $result='<select name="scantron_format">'."\n";
1.191     albertel 5218:     $result.='<option></option>'."\n";
1.518     raeburn  5219:     my @lines = &get_scantronformat_file();
                   5220:     if (@lines > 0) {
                   5221:         foreach my $line (@lines) {
                   5222:             next if (($line =~ /^\#/) || ($line eq ''));
                   5223: 	    my ($name,$descrip)=split(/:/,$line);
                   5224: 	    $result.='<option value="'.$name.'">'.$descrip.'</option>'."\n";
                   5225:         }
1.82      albertel 5226:     }
                   5227:     $result.='</select>'."\n";
1.518     raeburn  5228:     return $result;
                   5229: }
                   5230: 
                   5231: =pod
                   5232: 
                   5233: =item get_scantronformat_file
                   5234: 
                   5235:   Returns an array containing lines from the scantron format file for
                   5236:   the domain of the course.
                   5237: 
                   5238:   If a url for a custom.tab file is listed in domain's configuration.db, 
                   5239:   lines are from this file.
                   5240: 
                   5241:   Otherwise, if a default.tab has been published in RES space by the 
                   5242:   domainconfig user, lines are from this file.
                   5243: 
                   5244:   Otherwise, fall back to getting lines from the legacy file on the
1.519     raeburn  5245:   local server:  /home/httpd/lonTabs/default_scantronformat.tab    
1.82      albertel 5246: 
1.518     raeburn  5247: =cut
                   5248: 
                   5249: sub get_scantronformat_file {
                   5250:     my $cdom= $env{'course.'.$env{'request.course.id'}.'.domain'};
                   5251:     my %domconfig = &Apache::lonnet::get_dom('configuration',['scantron'],$cdom);
                   5252:     my $gottab = 0;
                   5253:     my @lines;
                   5254:     if (ref($domconfig{'scantron'}) eq 'HASH') {
                   5255:         if ($domconfig{'scantron'}{'scantronformat'} ne '') {
                   5256:             my $formatfile = &Apache::lonnet::getfile($Apache::lonnet::perlvar{'lonDocRoot'}.$domconfig{'scantron'}{'scantronformat'});
                   5257:             if ($formatfile ne '-1') {
                   5258:                 @lines = split("\n",$formatfile,-1);
                   5259:                 $gottab = 1;
                   5260:             }
                   5261:         }
                   5262:     }
                   5263:     if (!$gottab) {
                   5264:         my $confname = $cdom.'-domainconfig';
                   5265:         my $default = $Apache::lonnet::perlvar{'lonDocRoot'}.'/res/'.$cdom.'/'.$confname.'/default.tab';
                   5266:         my $formatfile =  &Apache::lonnet::getfile($default);
                   5267:         if ($formatfile ne '-1') {
                   5268:             @lines = split("\n",$formatfile,-1);
                   5269:             $gottab = 1;
                   5270:         }
                   5271:     }
                   5272:     if (!$gottab) {
1.519     raeburn  5273:         my @domains = &Apache::lonnet::current_machine_domains();
                   5274:         if (grep(/^\Q$cdom\E$/,@domains)) {
                   5275:             my $fh=Apache::File->new($Apache::lonnet::perlvar{'lonTabDir'}.'/scantronformat.tab');
                   5276:             @lines = <$fh>;
                   5277:             close($fh);
                   5278:         } else {
                   5279:             my $fh=Apache::File->new($Apache::lonnet::perlvar{'lonTabDir'}.'/default_scantronformat.tab');
                   5280:             @lines = <$fh>;
                   5281:             close($fh);
                   5282:         }
1.518     raeburn  5283:     }
                   5284:     return @lines;
1.82      albertel 5285: }
                   5286: 
1.423     albertel 5287: =pod 
                   5288: 
                   5289: =item scantron_CODElist
                   5290: 
                   5291:   Returns html drop down of the saved CODE lists from current course,
                   5292:   generated from earlier printings.
                   5293: 
                   5294: =cut
1.422     foxr     5295: 
1.186     albertel 5296: sub scantron_CODElist {
1.257     albertel 5297:     my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   5298:     my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
1.186     albertel 5299:     my @names=&Apache::lonnet::getkeys('CODEs',$cdom,$cnum);
                   5300:     my $namechoice='<option></option>';
1.225     albertel 5301:     foreach my $name (sort {uc($a) cmp uc($b)} @names) {
1.191     albertel 5302: 	if ($name =~ /^error: 2 /) { next; }
1.278     albertel 5303: 	if ($name =~ /^type\0/) { next; }
1.186     albertel 5304: 	$namechoice.='<option value="'.$name.'">'.$name.'</option>';
                   5305:     }
                   5306:     $namechoice='<select name="scantron_CODElist">'.$namechoice.'</select>';
                   5307:     return $namechoice;
                   5308: }
                   5309: 
1.423     albertel 5310: =pod 
                   5311: 
                   5312: =item scantron_CODEunique
                   5313: 
                   5314:   Returns the html for "Each CODE to be used once" radio.
                   5315: 
                   5316: =cut
1.422     foxr     5317: 
1.186     albertel 5318: sub scantron_CODEunique {
1.532     bisitz   5319:     my $result='<span class="LC_nobreak">
1.272     albertel 5320:                  <label><input type="radio" name="scantron_CODEunique"
1.423     albertel 5321:                         value="yes" checked="checked" />'.&mt('Yes').' </label>
1.381     albertel 5322:                 </span>
1.532     bisitz   5323:                 <span class="LC_nobreak">
1.272     albertel 5324:                  <label><input type="radio" name="scantron_CODEunique"
1.423     albertel 5325:                         value="no" />'.&mt('No').' </label>
1.381     albertel 5326:                 </span>';
1.186     albertel 5327:     return $result;
                   5328: }
1.423     albertel 5329: 
                   5330: =pod 
                   5331: 
                   5332: =item scantron_selectphase
                   5333: 
1.596.2.6  raeburn  5334:   Generates the initial screen to start the bubblesheet process.
1.423     albertel 5335:   Allows for - starting a grading run.
1.424     albertel 5336:              - downloading existing scan data (original, corrected
1.423     albertel 5337:                                                 or skipped info)
                   5338: 
                   5339:              - uploading new scan data
                   5340: 
                   5341:  Arguments:
                   5342:   $r          - The Apache request object
                   5343:   $file2grade - name of the file that contain the scanned data to score
                   5344: 
                   5345: =cut
1.186     albertel 5346: 
1.75      albertel 5347: sub scantron_selectphase {
1.209     ng       5348:     my ($r,$file2grade) = @_;
1.324     albertel 5349:     my ($symb)=&get_symb($r);
1.75      albertel 5350:     if (!$symb) {return '';}
1.582     raeburn  5351:     my $map_error;
                   5352:     my $sequence_selector=&getSequenceDropDown($symb,\$map_error);
                   5353:     if ($map_error) {
                   5354:         $r->print('<br />'.&navmap_errormsg().'<br />');
                   5355:         return;
                   5356:     }
1.324     albertel 5357:     my $default_form_data=&defaultFormData($symb);
                   5358:     my $grading_menu_button=&show_grading_menu_form($symb);
1.209     ng       5359:     my $file_selector=&scantron_uploads($file2grade);
1.82      albertel 5360:     my $format_selector=&scantron_scantab();
1.186     albertel 5361:     my $CODE_selector=&scantron_CODElist();
                   5362:     my $CODE_unique=&scantron_CODEunique();
1.75      albertel 5363:     my $result;
1.422     foxr     5364: 
1.513     foxr     5365:     $ssi_error = 0;
                   5366: 
1.596.2.4  raeburn  5367:     if (&Apache::lonnet::allowed('usc',$env{'request.role.domain'}) ||
                   5368:         &Apache::lonnet::allowed('usc',$env{'request.course.id'})) {
                   5369: 
                   5370:         # Chunk of form to prompt for a scantron file upload.
                   5371: 
                   5372:         $r->print('
                   5373:     <br />
                   5374:     '.&Apache::loncommon::start_data_table('LC_scantron_action').'
                   5375:        '.&Apache::loncommon::start_data_table_header_row().'
                   5376:             <th>
                   5377:               &nbsp;'.&mt('Specify a bubblesheet data file to upload.').'
                   5378:             </th>
                   5379:        '.&Apache::loncommon::end_data_table_header_row().'
                   5380:        '.&Apache::loncommon::start_data_table_row().'
                   5381:             <td>
                   5382: ');
                   5383:     my $default_form_data=&defaultFormData(&get_symb($r,1));
                   5384:     my $cdom= $env{'course.'.$env{'request.course.id'}.'.domain'};
                   5385:     my $cnum= $env{'course.'.$env{'request.course.id'}.'.num'};
                   5386:     $r->print('
                   5387:               <script type="text/javascript" language="javascript">
                   5388:     function checkUpload(formname) {
                   5389:         if (formname.upfile.value == "") {
                   5390:             alert("'.&mt('Please use the browse button to select a file from your local directory.').'");
                   5391:             return false;
                   5392:         }
                   5393:         formname.submit();
                   5394:     }
                   5395:               </script>
                   5396: 
                   5397:               <form enctype="multipart/form-data" action="/adm/grades" name="rules" method="post">
                   5398:                 '.$default_form_data.'
                   5399:                 <input name="courseid" type="hidden" value="'.$cnum.'" />
                   5400:                 <input name="domainid" type="hidden" value="'.$cdom.'" />
                   5401:                 <input name="command" value="scantronupload_save" type="hidden" />
                   5402:                 '.&mt('File to upload: [_1]','<input type="file" name="upfile" size="50" />').'
                   5403:                 <br />
                   5404:                 <input type="button" onclick="javascript:checkUpload(this.form);" value="'.&mt('Upload Bubblesheet Data').'" />
                   5405:               </form>
                   5406: ');
                   5407: 
                   5408:         $r->print('
                   5409:             </td>
                   5410:        '.&Apache::loncommon::end_data_table_row().'
                   5411:        '.&Apache::loncommon::end_data_table().'
                   5412: ');
                   5413:     }
                   5414: 
1.422     foxr     5415:     # Chunk of form to prompt for a file to grade and how:
                   5416: 
1.489     albertel 5417:     $result.= '
                   5418:     <br />
                   5419:     <form method="post" enctype="multipart/form-data" action="/adm/grades" name="scantron_process">
                   5420:     <input type="hidden" name="command" value="scantron_warning" />
                   5421:     '.$default_form_data.'
                   5422:     '.&Apache::loncommon::start_data_table('LC_scantron_action').'
                   5423:        '.&Apache::loncommon::start_data_table_header_row().'
                   5424:             <th colspan="2">
1.492     albertel 5425:               &nbsp;'.&mt('Specify file and which Folder/Sequence to grade').'
1.489     albertel 5426:             </th>
                   5427:        '.&Apache::loncommon::end_data_table_header_row().'
                   5428:        '.&Apache::loncommon::start_data_table_row().'
1.492     albertel 5429:             <td> '.&mt('Sequence to grade:').' </td><td> '.$sequence_selector.' </td>
1.489     albertel 5430:        '.&Apache::loncommon::end_data_table_row().'
                   5431:        '.&Apache::loncommon::start_data_table_row().'
1.572     www      5432:             <td> '.&mt('Filename of bubblesheet data file:').' </td><td> '.$file_selector.' </td>
1.489     albertel 5433:        '.&Apache::loncommon::end_data_table_row().'
                   5434:        '.&Apache::loncommon::start_data_table_row().'
1.572     www      5435:             <td> '.&mt('Format of bubblesheet data file:').' </td><td> '.$format_selector.' </td>
1.489     albertel 5436:        '.&Apache::loncommon::end_data_table_row().'
                   5437:        '.&Apache::loncommon::start_data_table_row().'
1.492     albertel 5438:             <td> '.&mt('Saved CODEs to validate against:').' </td><td> '.$CODE_selector.' </td>
1.489     albertel 5439:        '.&Apache::loncommon::end_data_table_row().'
                   5440:        '.&Apache::loncommon::start_data_table_row().'
1.492     albertel 5441:             <td> '.&mt('Each CODE is only to be used once:').'</td><td> '.$CODE_unique.' </td>
1.489     albertel 5442:        '.&Apache::loncommon::end_data_table_row().'
                   5443:        '.&Apache::loncommon::start_data_table_row().'
1.492     albertel 5444: 	    <td> '.&mt('Options:').' </td>
1.187     albertel 5445:             <td>
1.492     albertel 5446: 	       <label><input type="checkbox" name="scantron_options_redo" value="redo_skipped"/> '.&mt('Do only previously skipped records').'</label> <br />
                   5447:                <label><input type="checkbox" name="scantron_options_ignore" value="ignore_corrections"/> '.&mt('Remove all existing corrections').'</label> <br />
                   5448:                <label><input type="checkbox" name="scantron_options_hidden" value="ignore_hidden"/> '.&mt('Skip hidden resources when grading').'</label>
1.187     albertel 5449: 	    </td>
1.489     albertel 5450:        '.&Apache::loncommon::end_data_table_row().'
                   5451:        '.&Apache::loncommon::start_data_table_row().'
1.174     albertel 5452:             <td colspan="2">
1.572     www      5453:               <input type="submit" value="'.&mt('Grading: Validate Bubblesheet Records').'" />
1.162     albertel 5454:             </td>
1.489     albertel 5455:        '.&Apache::loncommon::end_data_table_row().'
                   5456:     '.&Apache::loncommon::end_data_table().'
                   5457:     </form>
                   5458: ';
1.162     albertel 5459:    
                   5460:     $r->print($result);
                   5461: 
1.422     foxr     5462:     # Chunk of the form that prompts to view a scoring office file,
                   5463:     # corrected file, skipped records in a file.
                   5464: 
1.489     albertel 5465:     $r->print('
                   5466:    <br />
                   5467:    <form action="/adm/grades" name="scantron_download">
                   5468:      '.$default_form_data.'
                   5469:      <input type="hidden" name="command" value="scantron_download" />
                   5470:      '.&Apache::loncommon::start_data_table('LC_scantron_action').'
                   5471:        '.&Apache::loncommon::start_data_table_header_row().'
                   5472:               <th>
1.492     albertel 5473:                 &nbsp;'.&mt('Download a scoring office file').'
1.489     albertel 5474:               </th>
                   5475:        '.&Apache::loncommon::end_data_table_header_row().'
                   5476:        '.&Apache::loncommon::start_data_table_row().'
1.492     albertel 5477:               <td> '.&mt('Filename of scoring office file: [_1]',$file_selector).' 
1.489     albertel 5478:                 <br />
1.492     albertel 5479:                 <input type="submit" value="'.&mt('Download: Show List of Associated Files').'" />
1.489     albertel 5480:        '.&Apache::loncommon::end_data_table_row().'
                   5481:      '.&Apache::loncommon::end_data_table().'
                   5482:    </form>
                   5483:    <br />
                   5484: ');
1.162     albertel 5485: 
1.457     banghart 5486:     &Apache::lonpickcode::code_list($r,2);
1.523     raeburn  5487: 
1.528     raeburn  5488:     $r->print('<br /><form method="post" name="checkscantron">'.
1.523     raeburn  5489:              $default_form_data."\n".
                   5490:              &Apache::loncommon::start_data_table('LC_scantron_action')."\n".
                   5491:              &Apache::loncommon::start_data_table_header_row()."\n".
                   5492:              '<th colspan="2">
1.572     www      5493:               &nbsp;'.&mt('Review bubblesheet data and submissions for a previously graded folder/sequence')."\n".
1.523     raeburn  5494:              '</th>'."\n".
                   5495:               &Apache::loncommon::end_data_table_header_row()."\n".
                   5496:               &Apache::loncommon::start_data_table_row()."\n".
                   5497:               '<td> '.&mt('Graded folder/sequence:').' </td>'."\n".
                   5498:               '<td> '.$sequence_selector.' </td>'.
                   5499:               &Apache::loncommon::end_data_table_row()."\n".
                   5500:               &Apache::loncommon::start_data_table_row()."\n".
                   5501:               '<td> '.&mt('Filename of scoring office file:').' </td>'."\n".
                   5502:               '<td> '.$file_selector.' </td>'."\n".
                   5503:               &Apache::loncommon::end_data_table_row()."\n".
                   5504:               &Apache::loncommon::start_data_table_row()."\n".
                   5505:               '<td> '.&mt('Format of data file:').' </td>'."\n".
                   5506:               '<td> '.$format_selector.' </td>'."\n".
                   5507:               &Apache::loncommon::end_data_table_row()."\n".
                   5508:               &Apache::loncommon::start_data_table_row()."\n".
1.557     raeburn  5509:               '<td> '.&mt('Options').' </td>'."\n".
                   5510:               '<td> <label><input type="checkbox" name="scantron_options_hidden" value="ignore_hidden"/> '.&mt('Skip hidden resources').'</label></td>'.
                   5511:               &Apache::loncommon::end_data_table_row()."\n".
                   5512:               &Apache::loncommon::start_data_table_row()."\n".
1.523     raeburn  5513:               '<td colspan="2">'."\n".
                   5514:               '<input type="hidden" name="command" value="checksubmissions" />'."\n".
1.575     www      5515:               '<input type="submit" value="'.&mt('Review Bubblesheet Data and Submission Records').'" />'."\n".
1.523     raeburn  5516:               '</td>'."\n".
                   5517:               &Apache::loncommon::end_data_table_row()."\n".
                   5518:               &Apache::loncommon::end_data_table()."\n".
                   5519:               '</form><br />');
1.457     banghart 5520:     $r->print($grading_menu_button);
1.523     raeburn  5521:     return;
1.75      albertel 5522: }
                   5523: 
1.423     albertel 5524: =pod
                   5525: 
                   5526: =item get_scantron_config
                   5527: 
                   5528:    Parse and return the scantron configuration line selected as a
                   5529:    hash of configuration file fields.
                   5530: 
                   5531:  Arguments:
                   5532:     which - the name of the configuration to parse from the file.
                   5533: 
                   5534: 
                   5535:  Returns:
                   5536:             If the named configuration is not in the file, an empty
                   5537:             hash is returned.
                   5538:     a hash with the fields
                   5539:       name         - internal name for the this configuration setup
                   5540:       description  - text to display to operator that describes this config
                   5541:       CODElocation - if 0 or the string 'none'
                   5542:                           - no CODE exists for this config
                   5543:                      if -1 || the string 'letter'
                   5544:                           - a CODE exists for this config and is
                   5545:                             a string of letters
                   5546:                      Unsupported value (but planned for future support)
                   5547:                           if a positive integer
                   5548:                                - The CODE exists as the first n items from
                   5549:                                  the question section of the form
                   5550:                           if the string 'number'
                   5551:                                - The CODE exists for this config and is
                   5552:                                  a string of numbers
                   5553:       CODEstart   - (only matter if a CODE exists) column in the line where
                   5554:                      the CODE starts
                   5555:       CODElength  - length of the CODE
1.573     bisitz   5556:       IDstart     - column where the student/employee ID starts
1.556     weissno  5557:       IDlength    - length of the student/employee ID info
1.423     albertel 5558:       Qstart      - column where the information from the bubbled
                   5559:                     'questions' start
                   5560:       Qlength     - number of columns comprising a single bubble line from
                   5561:                     the sheet. (usually either 1 or 10)
1.424     albertel 5562:       Qon         - either a single character representing the character used
1.423     albertel 5563:                     to signal a bubble was chosen in the positional setup, or
                   5564:                     the string 'letter' if the letter of the chosen bubble is
                   5565:                     in the final, or 'number' if a number representing the
                   5566:                     chosen bubble is in the file (1->A 0->J)
1.424     albertel 5567:       Qoff        - the character used to represent that a bubble was
                   5568:                     left blank
1.423     albertel 5569:       PaperID     - if the scanning process generates a unique number for each
                   5570:                     sheet scanned the column that this ID number starts in
                   5571:       PaperIDlength - number of columns that comprise the unique ID number
                   5572:                       for the sheet of paper
1.424     albertel 5573:       FirstName   - column that the first name starts in
1.423     albertel 5574:       FirstNameLength - number of columns that the first name spans
                   5575:  
                   5576:       LastName    - column that the last name starts in
                   5577:       LastNameLength - number of columns that the last name spans
1.596.2.12.2.  (raeburn 5578:):       BubblesPerRow - number of bubbles available in each row used to
                   5579:):                       bubble an answer. (If not specified, 10 assumed).
1.423     albertel 5580: 
                   5581: =cut
1.422     foxr     5582: 
1.82      albertel 5583: sub get_scantron_config {
                   5584:     my ($which) = @_;
1.518     raeburn  5585:     my @lines = &get_scantronformat_file();
1.82      albertel 5586:     my %config;
1.157     albertel 5587:     #FIXME probably should move to XML it has already gotten a bit much now
1.518     raeburn  5588:     foreach my $line (@lines) {
1.82      albertel 5589: 	my ($name,$descrip)=split(/:/,$line);
                   5590: 	if ($name ne $which ) { next; }
                   5591: 	chomp($line);
                   5592: 	my @config=split(/:/,$line);
                   5593: 	$config{'name'}=$config[0];
                   5594: 	$config{'description'}=$config[1];
                   5595: 	$config{'CODElocation'}=$config[2];
                   5596: 	$config{'CODEstart'}=$config[3];
                   5597: 	$config{'CODElength'}=$config[4];
                   5598: 	$config{'IDstart'}=$config[5];
                   5599: 	$config{'IDlength'}=$config[6];
                   5600: 	$config{'Qstart'}=$config[7];
1.497     foxr     5601:  	$config{'Qlength'}=$config[8];
1.82      albertel 5602: 	$config{'Qoff'}=$config[9];
                   5603: 	$config{'Qon'}=$config[10];
1.157     albertel 5604: 	$config{'PaperID'}=$config[11];
                   5605: 	$config{'PaperIDlength'}=$config[12];
                   5606: 	$config{'FirstName'}=$config[13];
                   5607: 	$config{'FirstNamelength'}=$config[14];
                   5608: 	$config{'LastName'}=$config[15];
                   5609: 	$config{'LastNamelength'}=$config[16];
1.596.2.12.2.  (raeburn 5610:):         $config{'BubblesPerRow'}=$config[17];
1.82      albertel 5611: 	last;
                   5612:     }
                   5613:     return %config;
                   5614: }
                   5615: 
1.423     albertel 5616: =pod 
                   5617: 
                   5618: =item username_to_idmap
                   5619: 
1.556     weissno  5620:     creates a hash keyed by student/employee ID with values of the corresponding
1.423     albertel 5621:     student username:domain.
                   5622: 
                   5623:   Arguments:
                   5624: 
                   5625:     $classlist - reference to the class list hash. This is a hash
                   5626:                  keyed by student name:domain  whose elements are references
1.424     albertel 5627:                  to arrays containing various chunks of information
1.423     albertel 5628:                  about the student. (See loncoursedata for more info).
                   5629: 
                   5630:   Returns
                   5631:     %idmap - the constructed hash
                   5632: 
                   5633: =cut
                   5634: 
1.82      albertel 5635: sub username_to_idmap {
                   5636:     my ($classlist)= @_;
                   5637:     my %idmap;
                   5638:     foreach my $student (keys(%$classlist)) {
                   5639: 	$idmap{$classlist->{$student}->[&Apache::loncoursedata::CL_ID]}=
                   5640: 	    $student;
                   5641:     }
                   5642:     return %idmap;
                   5643: }
1.423     albertel 5644: 
                   5645: =pod
                   5646: 
1.424     albertel 5647: =item scantron_fixup_scanline
1.423     albertel 5648: 
                   5649:    Process a requested correction to a scanline.
                   5650: 
                   5651:   Arguments:
                   5652:     $scantron_config   - hash from &get_scantron_config()
                   5653:     $scan_data         - hash of correction information 
                   5654:                           (see &scantron_getfile())
                   5655:     $line              - existing scanline
                   5656:     $whichline         - line number of the passed in scanline
                   5657:     $field             - type of change to process 
                   5658:                          (either 
1.573     bisitz   5659:                           'ID'     -> correct the student/employee ID
1.423     albertel 5660:                           'CODE'   -> correct the CODE
                   5661:                           'answer' -> fixup the submitted answers)
                   5662:     
                   5663:    $args               - hash of additional info,
                   5664:                           - 'ID' 
                   5665:                                'newid' -> studentID to use in replacement
1.424     albertel 5666:                                           of existing one
1.423     albertel 5667:                           - 'CODE' 
                   5668:                                'CODE_ignore_dup' - set to true if duplicates
                   5669:                                                    should be ignored.
                   5670: 	                       'CODE' - is new code or 'use_unfound'
1.424     albertel 5671:                                         if the existing unfound code should
1.423     albertel 5672:                                         be used as is
                   5673:                           - 'answer'
                   5674:                                'response' - new answer or 'none' if blank
                   5675:                                'question' - the bubble line to change
1.503     raeburn  5676:                                'questionnum' - the question identifier,
                   5677:                                                may include subquestion. 
1.423     albertel 5678: 
                   5679:   Returns:
                   5680:     $line - the modified scanline
                   5681: 
                   5682:   Side effects: 
                   5683:     $scan_data - may be updated
                   5684: 
                   5685: =cut
                   5686: 
1.82      albertel 5687: 
1.157     albertel 5688: sub scantron_fixup_scanline {
                   5689:     my ($scantron_config,$scan_data,$line,$whichline,$field,$args)=@_;
                   5690:     if ($field eq 'ID') {
                   5691: 	if (length($args->{'newid'}) > $$scantron_config{'IDlength'}) {
1.186     albertel 5692: 	    return ($line,1,'New value too large');
1.157     albertel 5693: 	}
                   5694: 	if (length($args->{'newid'}) < $$scantron_config{'IDlength'}) {
                   5695: 	    $args->{'newid'}=sprintf('%-'.$$scantron_config{'IDlength'}.'s',
                   5696: 				     $args->{'newid'});
                   5697: 	}
                   5698: 	substr($line,$$scantron_config{'IDstart'}-1,
                   5699: 	       $$scantron_config{'IDlength'})=$args->{'newid'};
                   5700: 	if ($args->{'newid'}=~/^\s*$/) {
                   5701: 	    &scan_data($scan_data,"$whichline.user",
                   5702: 		       $args->{'username'}.':'.$args->{'domain'});
                   5703: 	}
1.186     albertel 5704:     } elsif ($field eq 'CODE') {
1.192     albertel 5705: 	if ($args->{'CODE_ignore_dup'}) {
                   5706: 	    &scan_data($scan_data,"$whichline.CODE_ignore_dup",'1');
                   5707: 	}
                   5708: 	&scan_data($scan_data,"$whichline.useCODE",'1');
                   5709: 	if ($args->{'CODE'} ne 'use_unfound') {
1.191     albertel 5710: 	    if (length($args->{'CODE'}) > $$scantron_config{'CODElength'}) {
                   5711: 		return ($line,1,'New CODE value too large');
                   5712: 	    }
                   5713: 	    if (length($args->{'CODE'}) < $$scantron_config{'CODElength'}) {
                   5714: 		$args->{'CODE'}=sprintf('%-'.$$scantron_config{'CODElength'}.'s',$args->{'CODE'});
                   5715: 	    }
                   5716: 	    substr($line,$$scantron_config{'CODEstart'}-1,
                   5717: 		   $$scantron_config{'CODElength'})=$args->{'CODE'};
1.186     albertel 5718: 	}
1.157     albertel 5719:     } elsif ($field eq 'answer') {
1.497     foxr     5720: 	my $length=$scantron_config->{'Qlength'};
1.157     albertel 5721: 	my $off=$scantron_config->{'Qoff'};
                   5722: 	my $on=$scantron_config->{'Qon'};
1.497     foxr     5723: 	my $answer=${off}x$length;
                   5724: 	if ($args->{'response'} eq 'none') {
                   5725: 	    &scan_data($scan_data,
1.503     raeburn  5726: 		       "$whichline.no_bubble.".$args->{'questionnum'},'1');
1.497     foxr     5727: 	} else {
                   5728: 	    if ($on eq 'letter') {
                   5729: 		my @alphabet=('A'..'Z');
                   5730: 		$answer=$alphabet[$args->{'response'}];
                   5731: 	    } elsif ($on eq 'number') {
                   5732: 		$answer=$args->{'response'}+1;
                   5733: 		if ($answer == 10) { $answer = '0'; }
1.274     albertel 5734: 	    } else {
1.497     foxr     5735: 		substr($answer,$args->{'response'},1)=$on;
1.274     albertel 5736: 	    }
1.497     foxr     5737: 	    &scan_data($scan_data,
1.503     raeburn  5738: 		       "$whichline.no_bubble.".$args->{'questionnum'},undef,'1');
1.157     albertel 5739: 	}
1.497     foxr     5740: 	my $where=$length*($args->{'question'}-1)+$scantron_config->{'Qstart'};
                   5741: 	substr($line,$where-1,$length)=$answer;
1.157     albertel 5742:     }
                   5743:     return $line;
                   5744: }
1.423     albertel 5745: 
                   5746: =pod
                   5747: 
                   5748: =item scan_data
                   5749: 
                   5750:     Edit or look up  an item in the scan_data hash.
                   5751: 
                   5752:   Arguments:
                   5753:     $scan_data  - The hash (see scantron_getfile)
                   5754:     $key        - shorthand of the key to edit (actual key is
1.424     albertel 5755:                   scantronfilename_key).
1.423     albertel 5756:     $data        - New value of the hash entry.
                   5757:     $delete      - If true, the entry is removed from the hash.
                   5758: 
                   5759:   Returns:
                   5760:     The new value of the hash table field (undefined if deleted).
                   5761: 
                   5762: =cut
                   5763: 
                   5764: 
1.157     albertel 5765: sub scan_data {
                   5766:     my ($scan_data,$key,$value,$delete)=@_;
1.257     albertel 5767:     my $filename=$env{'form.scantron_selectfile'};
1.157     albertel 5768:     if (defined($value)) {
                   5769: 	$scan_data->{$filename.'_'.$key} = $value;
                   5770:     }
                   5771:     if ($delete) { delete($scan_data->{$filename.'_'.$key}); }
                   5772:     return $scan_data->{$filename.'_'.$key};
                   5773: }
1.423     albertel 5774: 
1.495     albertel 5775: # ----- These first few routines are general use routines.----
                   5776: 
                   5777: # Return the number of occurences of a pattern in a string.
                   5778: 
                   5779: sub occurence_count {
                   5780:     my ($string, $pattern) = @_;
                   5781: 
                   5782:     my @matches = ($string =~ /$pattern/g);
                   5783: 
                   5784:     return scalar(@matches);
                   5785: }
                   5786: 
                   5787: 
                   5788: # Take a string known to have digits and convert all the
                   5789: # digits into letters in the range J,A..I.
                   5790: 
                   5791: sub digits_to_letters {
                   5792:     my ($input) = @_;
                   5793: 
                   5794:     my @alphabet = ('J', 'A'..'I');
                   5795: 
                   5796:     my @input    = split(//, $input);
                   5797:     my $output ='';
                   5798:     for (my $i = 0; $i < scalar(@input); $i++) {
                   5799: 	if ($input[$i] =~ /\d/) {
                   5800: 	    $output .= $alphabet[$input[$i]];
                   5801: 	} else {
                   5802: 	    $output .= $input[$i];
                   5803: 	}
                   5804:     }
                   5805:     return $output;
                   5806: }
                   5807: 
1.423     albertel 5808: =pod 
                   5809: 
                   5810: =item scantron_parse_scanline
                   5811: 
                   5812:   Decodes a scanline from the selected scantron file
                   5813: 
                   5814:  Arguments:
                   5815:     line             - The text of the scantron file line to process
                   5816:     whichline        - Line number
                   5817:     scantron_config  - Hash describing the format of the scantron lines.
                   5818:     scan_data        - Hash of extra information about the scanline
                   5819:                        (see scantron_getfile for more information)
                   5820:     just_header      - True if should not process question answers but only
                   5821:                        the stuff to the left of the answers.
                   5822:  Returns:
                   5823:    Hash containing the result of parsing the scanline
                   5824: 
                   5825:    Keys are all proceeded by the string 'scantron.'
                   5826: 
                   5827:        CODE    - the CODE in use for this scanline
                   5828:        useCODE - 1 if the CODE is invalid but it usage has been forced
                   5829:                  by the operator
                   5830:        CODE_ignore_dup - 1 if the CODE is a duplicated use when unique
                   5831:                             CODEs were selected, but the usage has been
                   5832:                             forced by the operator
1.556     weissno  5833:        ID  - student/employee ID
1.423     albertel 5834:        PaperID - if used, the ID number printed on the sheet when the 
                   5835:                  paper was scanned
                   5836:        FirstName - first name from the sheet
                   5837:        LastName  - last name from the sheet
                   5838: 
                   5839:      if just_header was not true these key may also exist
                   5840: 
1.447     foxr     5841:        missingerror - a list of bubble ranges that are considered to be answers
                   5842:                       to a single question that don't have any bubbles filled in.
                   5843:                       Of the form questionnumber:firstbubblenumber:count.
                   5844:        doubleerror  - a list of bubble ranges that are considered to be answers
                   5845:                       to a single question that have more than one bubble filled in.
                   5846:                       Of the form questionnumber::firstbubblenumber:count
                   5847:    
                   5848:                 In the above, count is the number of bubble responses in the
                   5849:                 input line needed to represent the possible answers to the question.
                   5850:                 e.g. a radioresponse with 15 choices in an answer sheet with 10 choices
                   5851:                 per line would have count = 2.
                   5852: 
1.423     albertel 5853:        maxquest     - the number of the last bubble line that was parsed
                   5854: 
                   5855:        (<number> starts at 1)
                   5856:        <number>.answer - zero or more letters representing the selected
                   5857:                          letters from the scanline for the bubble line 
                   5858:                          <number>.
                   5859:                          if blank there was either no bubble or there where
                   5860:                          multiple bubbles, (consult the keys missingerror and
                   5861:                          doubleerror if this is an error condition)
                   5862: 
                   5863: =cut
                   5864: 
1.82      albertel 5865: sub scantron_parse_scanline {
1.423     albertel 5866:     my ($line,$whichline,$scantron_config,$scan_data,$just_header)=@_;
1.470     foxr     5867: 
1.82      albertel 5868:     my %record;
1.550     raeburn  5869:     my $lastpos = $env{'form.scantron_maxbubble'}*$$scantron_config{'Qlength'};
                   5870:     my $questions=substr($line,$$scantron_config{'Qstart'}-1,$lastpos);  # Answers
1.422     foxr     5871:     my $data=substr($line,0,$$scantron_config{'Qstart'}-1);     # earlier stuff
1.278     albertel 5872:     if (!($$scantron_config{'CODElocation'} eq 0 ||
                   5873: 	  $$scantron_config{'CODElocation'} eq 'none')) {
                   5874: 	if ($$scantron_config{'CODElocation'} < 0 ||
                   5875: 	    $$scantron_config{'CODElocation'} eq 'letter' ||
                   5876: 	    $$scantron_config{'CODElocation'} eq 'number') {
1.191     albertel 5877: 	    $record{'scantron.CODE'}=substr($data,
                   5878: 					    $$scantron_config{'CODEstart'}-1,
1.83      albertel 5879: 					    $$scantron_config{'CODElength'});
1.191     albertel 5880: 	    if (&scan_data($scan_data,"$whichline.useCODE")) {
                   5881: 		$record{'scantron.useCODE'}=1;
                   5882: 	    }
1.192     albertel 5883: 	    if (&scan_data($scan_data,"$whichline.CODE_ignore_dup")) {
                   5884: 		$record{'scantron.CODE_ignore_dup'}=1;
                   5885: 	    }
1.82      albertel 5886: 	} else {
                   5887: 	    #FIXME interpret first N questions
                   5888: 	}
                   5889:     }
1.83      albertel 5890:     $record{'scantron.ID'}=substr($data,$$scantron_config{'IDstart'}-1,
                   5891: 				  $$scantron_config{'IDlength'});
1.157     albertel 5892:     $record{'scantron.PaperID'}=
                   5893: 	substr($data,$$scantron_config{'PaperID'}-1,
                   5894: 	       $$scantron_config{'PaperIDlength'});
                   5895:     $record{'scantron.FirstName'}=
                   5896: 	substr($data,$$scantron_config{'FirstName'}-1,
                   5897: 	       $$scantron_config{'FirstNamelength'});
                   5898:     $record{'scantron.LastName'}=
                   5899: 	substr($data,$$scantron_config{'LastName'}-1,
                   5900: 	       $$scantron_config{'LastNamelength'});
1.423     albertel 5901:     if ($just_header) { return \%record; }
1.194     albertel 5902: 
1.82      albertel 5903:     my @alphabet=('A'..'Z');
                   5904:     my $questnum=0;
1.447     foxr     5905:     my $ansnum  =1;		# Multiple 'answer lines'/question.
                   5906: 
1.470     foxr     5907:     chomp($questions);		# Get rid of any trailing \n.
                   5908:     $questions =~ s/\r$//;      # Get rid of trailing \r too (MAC or Win uploads).
                   5909:     while (length($questions)) {
1.447     foxr     5910: 	my $answers_needed = $bubble_lines_per_response{$questnum};
1.503     raeburn  5911:         my $answer_length  = ($$scantron_config{'Qlength'} * $answers_needed)
                   5912:                              || 1;
                   5913:         $questnum++;
                   5914:         my $quest_id = $questnum;
                   5915:         my $currentquest = substr($questions,0,$answer_length);
                   5916:         $questions       = substr($questions,$answer_length);
                   5917:         if (length($currentquest) < $answer_length) { next; }
                   5918: 
                   5919:         if ($subdivided_bubble_lines{$questnum-1} =~ /,/) {
                   5920:             my $subquestnum = 1;
                   5921:             my $subquestions = $currentquest;
                   5922:             my @subanswers_needed = 
                   5923:                 split(/,/,$subdivided_bubble_lines{$questnum-1});  
                   5924:             foreach my $subans (@subanswers_needed) {
                   5925:                 my $subans_length =
                   5926:                     ($$scantron_config{'Qlength'} * $subans)  || 1;
                   5927:                 my $currsubquest = substr($subquestions,0,$subans_length);
                   5928:                 $subquestions   = substr($subquestions,$subans_length);
                   5929:                 $quest_id = "$questnum.$subquestnum";
                   5930:                 if (($$scantron_config{'Qon'} eq 'letter') ||
                   5931:                     ($$scantron_config{'Qon'} eq 'number')) {
                   5932:                     $ansnum = &scantron_validator_lettnum($ansnum, 
                   5933:                         $questnum,$quest_id,$subans,$currsubquest,$whichline,
                   5934:                         \@alphabet,\%record,$scantron_config,$scan_data);
                   5935:                 } else {
                   5936:                     $ansnum = &scantron_validator_positional($ansnum,
                   5937:                         $questnum,$quest_id,$subans,$currsubquest,$whichline,                        \@alphabet,\%record,$scantron_config,$scan_data);
                   5938:                 }
                   5939:                 $subquestnum ++;
                   5940:             }
                   5941:         } else {
                   5942:             if (($$scantron_config{'Qon'} eq 'letter') ||
                   5943:                 ($$scantron_config{'Qon'} eq 'number')) {
                   5944:                 $ansnum = &scantron_validator_lettnum($ansnum,$questnum,
                   5945:                     $quest_id,$answers_needed,$currentquest,$whichline,
                   5946:                     \@alphabet,\%record,$scantron_config,$scan_data);
                   5947:             } else {
                   5948:                 $ansnum = &scantron_validator_positional($ansnum,$questnum,
                   5949:                     $quest_id,$answers_needed,$currentquest,$whichline,
                   5950:                     \@alphabet,\%record,$scantron_config,$scan_data);
                   5951:             }
                   5952:         }
                   5953:     }
                   5954:     $record{'scantron.maxquest'}=$questnum;
                   5955:     return \%record;
                   5956: }
1.447     foxr     5957: 
1.503     raeburn  5958: sub scantron_validator_lettnum {
                   5959:     my ($ansnum,$questnum,$quest_id,$answers_needed,$currquest,$whichline,
                   5960:         $alphabet,$record,$scantron_config,$scan_data) = @_;
                   5961: 
                   5962:     # Qon 'letter' implies for each slot in currquest we have:
                   5963:     #    ? or * for doubles, a letter in A-Z for a bubble, and
                   5964:     #    about anything else (esp. a value of Qoff) for missing
                   5965:     #    bubbles.
                   5966:     #
                   5967:     # Qon 'number' implies each slot gives a digit that indexes the
                   5968:     #    bubbles filled, or Qoff, or a non-number for unbubbled lines,
                   5969:     #    and * or ? for double bubbles on a single line.
                   5970:     #
1.447     foxr     5971: 
1.503     raeburn  5972:     my $matchon;
                   5973:     if ($$scantron_config{'Qon'} eq 'letter') {
                   5974:         $matchon = '[A-Z]';
                   5975:     } elsif ($$scantron_config{'Qon'} eq 'number') {
                   5976:         $matchon = '\d';
                   5977:     }
                   5978:     my $occurrences = 0;
                   5979:     if (($responsetype_per_response{$questnum-1} eq 'essayresponse') ||
                   5980:         ($responsetype_per_response{$questnum-1} eq 'formularesponse') ||
1.510     raeburn  5981:         ($responsetype_per_response{$questnum-1} eq 'stringresponse') ||
                   5982:         ($responsetype_per_response{$questnum-1} eq 'imageresponse') ||
                   5983:         ($responsetype_per_response{$questnum-1} eq 'reactionresponse') ||
                   5984:         ($responsetype_per_response{$questnum-1} eq 'organicresponse')) {
1.503     raeburn  5985:         my @singlelines = split('',$currquest);
                   5986:         foreach my $entry (@singlelines) {
                   5987:             $occurrences = &occurence_count($entry,$matchon);
                   5988:             if ($occurrences > 1) {
                   5989:                 last;
                   5990:             }
                   5991:         } 
                   5992:     } else {
                   5993:         $occurrences = &occurence_count($currquest,$matchon); 
                   5994:     }
                   5995:     if (($currquest =~ /\?/ || $currquest =~ /\*/) || ($occurrences > 1)) {
                   5996:         push(@{$record->{'scantron.doubleerror'}},$quest_id);
                   5997:         for (my $ans=0; $ans<$answers_needed; $ans++) {
                   5998:             my $bubble = substr($currquest,$ans,1);
                   5999:             if ($bubble =~ /$matchon/ ) {
                   6000:                 if ($$scantron_config{'Qon'} eq 'number') {
                   6001:                     if ($bubble == 0) {
                   6002:                         $bubble = 10; 
                   6003:                     }
                   6004:                     $record->{"scantron.$ansnum.answer"} = 
                   6005:                         $alphabet->[$bubble-1];
                   6006:                 } else {
                   6007:                     $record->{"scantron.$ansnum.answer"} = $bubble;
                   6008:                 }
                   6009:             } else {
                   6010:                 $record->{"scantron.$ansnum.answer"}='';
                   6011:             }
                   6012:             $ansnum++;
                   6013:         }
                   6014:     } elsif (!defined($currquest)
                   6015:             || (&occurence_count($currquest, $$scantron_config{'Qoff'}) == length($currquest))
                   6016:             || (&occurence_count($currquest,$matchon) == 0)) {
                   6017:         for (my $ans=0; $ans<$answers_needed; $ans++ ) {
                   6018:             $record->{"scantron.$ansnum.answer"}='';
                   6019:             $ansnum++;
                   6020:         }
                   6021:         if (!&scan_data($scan_data,"$whichline.no_bubble.$quest_id")) {
                   6022:             push(@{$record->{'scantron.missingerror'}},$quest_id);
                   6023:         }
                   6024:     } else {
                   6025:         if ($$scantron_config{'Qon'} eq 'number') {
                   6026:             $currquest = &digits_to_letters($currquest);            
                   6027:         }
                   6028:         for (my $ans=0; $ans<$answers_needed; $ans++) {
                   6029:             my $bubble = substr($currquest,$ans,1);
                   6030:             $record->{"scantron.$ansnum.answer"} = $bubble;
                   6031:             $ansnum++;
                   6032:         }
                   6033:     }
                   6034:     return $ansnum;
                   6035: }
1.447     foxr     6036: 
1.503     raeburn  6037: sub scantron_validator_positional {
                   6038:     my ($ansnum,$questnum,$quest_id,$answers_needed,$currquest,
                   6039:         $whichline,$alphabet,$record,$scantron_config,$scan_data) = @_;
1.447     foxr     6040: 
1.503     raeburn  6041:     # Otherwise there's a positional notation;
                   6042:     # each bubble line requires Qlength items, and there are filled in
                   6043:     # bubbles for each case where there 'Qon' characters.
                   6044:     #
1.447     foxr     6045: 
1.503     raeburn  6046:     my @array=split($$scantron_config{'Qon'},$currquest,-1);
1.447     foxr     6047: 
1.503     raeburn  6048:     # If the split only gives us one element.. the full length of the
                   6049:     # answer string, no bubbles are filled in:
1.447     foxr     6050: 
1.507     raeburn  6051:     if ($answers_needed eq '') {
                   6052:         return;
                   6053:     }
                   6054: 
1.503     raeburn  6055:     if (length($array[0]) eq $$scantron_config{'Qlength'}*$answers_needed) {
                   6056:         for (my $ans=0; $ans<$answers_needed; $ans++ ) {
                   6057:             $record->{"scantron.$ansnum.answer"}='';
                   6058:             $ansnum++;
                   6059:         }
                   6060:         if (!&scan_data($scan_data,"$whichline.no_bubble.$quest_id")) {
                   6061:             push(@{$record->{"scantron.missingerror"}},$quest_id);
                   6062:         }
                   6063:     } elsif (scalar(@array) == 2) {
                   6064:         my $location = length($array[0]);
                   6065:         my $line_num = int($location / $$scantron_config{'Qlength'});
                   6066:         my $bubble   = $alphabet->[$location % $$scantron_config{'Qlength'}];
                   6067:         for (my $ans=0; $ans<$answers_needed; $ans++) {
                   6068:             if ($ans eq $line_num) {
                   6069:                 $record->{"scantron.$ansnum.answer"} = $bubble;
                   6070:             } else {
                   6071:                 $record->{"scantron.$ansnum.answer"} = ' ';
                   6072:             }
                   6073:             $ansnum++;
                   6074:          }
                   6075:     } else {
                   6076:         #  If there's more than one instance of a bubble character
                   6077:         #  That's a double bubble; with positional notation we can
                   6078:         #  record all the bubbles filled in as well as the
                   6079:         #  fact this response consists of multiple bubbles.
                   6080:         #
                   6081:         if (($responsetype_per_response{$questnum-1} eq 'essayresponse') ||
                   6082:             ($responsetype_per_response{$questnum-1} eq 'formularesponse') ||
1.510     raeburn  6083:             ($responsetype_per_response{$questnum-1} eq 'stringresponse') ||
                   6084:             ($responsetype_per_response{$questnum-1} eq 'imageresponse') ||
                   6085:             ($responsetype_per_response{$questnum-1} eq 'reactionresponse') ||
                   6086:             ($responsetype_per_response{$questnum-1} eq 'organicresponse')) {
1.503     raeburn  6087:             my $doubleerror = 0;
                   6088:             while (($currquest >= $$scantron_config{'Qlength'}) && 
                   6089:                    (!$doubleerror)) {
                   6090:                my $currline = substr($currquest,0,$$scantron_config{'Qlength'});
                   6091:                $currquest = substr($currquest,$$scantron_config{'Qlength'});
                   6092:                my @currarray = split($$scantron_config{'Qon'},$currline,-1);
                   6093:                if (length(@currarray) > 2) {
                   6094:                    $doubleerror = 1;
                   6095:                } 
                   6096:             }
                   6097:             if ($doubleerror) {
                   6098:                 push(@{$record->{'scantron.doubleerror'}},$quest_id);
                   6099:             }
                   6100:         } else {
                   6101:             push(@{$record->{'scantron.doubleerror'}},$quest_id);
                   6102:         }
                   6103:         my $item = $ansnum;
                   6104:         for (my $ans=0; $ans<$answers_needed; $ans++) {
                   6105:             $record->{"scantron.$item.answer"} = '';
                   6106:             $item ++;
                   6107:         }
1.447     foxr     6108: 
1.503     raeburn  6109:         my @ans=@array;
                   6110:         my $i=0;
                   6111:         my $increment = 0;
                   6112:         while ($#ans) {
                   6113:             $i+=length($ans[0]) + $increment;
                   6114:             my $line   = int($i/$$scantron_config{'Qlength'} + $ansnum);
                   6115:             my $bubble = $i%$$scantron_config{'Qlength'};
                   6116:             $record->{"scantron.$line.answer"}.=$alphabet->[$bubble];
                   6117:             shift(@ans);
                   6118:             $increment = 1;
                   6119:         }
                   6120:         $ansnum += $answers_needed;
1.82      albertel 6121:     }
1.503     raeburn  6122:     return $ansnum;
1.82      albertel 6123: }
                   6124: 
1.423     albertel 6125: =pod
                   6126: 
                   6127: =item scantron_add_delay
                   6128: 
                   6129:    Adds an error message that occurred during the grading phase to a
                   6130:    queue of messages to be shown after grading pass is complete
                   6131: 
                   6132:  Arguments:
1.424     albertel 6133:    $delayqueue  - arrary ref of hash ref of error messages
1.423     albertel 6134:    $scanline    - the scanline that caused the error
                   6135:    $errormesage - the error message
                   6136:    $errorcode   - a numeric code for the error
                   6137: 
                   6138:  Side Effects:
1.424     albertel 6139:    updates the $delayqueue to have a new hash ref of the error
1.423     albertel 6140: 
                   6141: =cut
                   6142: 
1.82      albertel 6143: sub scantron_add_delay {
1.140     albertel 6144:     my ($delayqueue,$scanline,$errormessage,$errorcode)=@_;
                   6145:     push(@$delayqueue,
                   6146: 	 {'line' => $scanline, 'emsg' => $errormessage,
                   6147: 	  'ecode' => $errorcode }
                   6148: 	 );
1.82      albertel 6149: }
                   6150: 
1.423     albertel 6151: =pod
                   6152: 
                   6153: =item scantron_find_student
                   6154: 
1.424     albertel 6155:    Finds the username for the current scanline
                   6156: 
                   6157:   Arguments:
                   6158:    $scantron_record - hash result from scantron_parse_scanline
                   6159:    $scan_data       - hash of correction information 
                   6160:                       (see &scantron_getfile() form more information)
                   6161:    $idmap           - hash from &username_to_idmap()
                   6162:    $line            - number of current scanline
                   6163:  
                   6164:   Returns:
                   6165:    Either 'username:domain' or undef if unknown
                   6166: 
1.423     albertel 6167: =cut
                   6168: 
1.82      albertel 6169: sub scantron_find_student {
1.157     albertel 6170:     my ($scantron_record,$scan_data,$idmap,$line)=@_;
1.83      albertel 6171:     my $scanID=$$scantron_record{'scantron.ID'};
1.157     albertel 6172:     if ($scanID =~ /^\s*$/) {
                   6173:  	return &scan_data($scan_data,"$line.user");
                   6174:     }
1.83      albertel 6175:     foreach my $id (keys(%$idmap)) {
1.157     albertel 6176:  	if (lc($id) eq lc($scanID)) {
                   6177:  	    return $$idmap{$id};
                   6178:  	}
1.83      albertel 6179:     }
                   6180:     return undef;
                   6181: }
                   6182: 
1.423     albertel 6183: =pod
                   6184: 
                   6185: =item scantron_filter
                   6186: 
1.424     albertel 6187:    Filter sub for lonnavmaps, filters out hidden resources if ignore
                   6188:    hidden resources was selected
                   6189: 
1.423     albertel 6190: =cut
                   6191: 
1.83      albertel 6192: sub scantron_filter {
                   6193:     my ($curres)=@_;
1.331     albertel 6194: 
                   6195:     if (ref($curres) && $curres->is_problem()) {
                   6196: 	# if the user has asked to not have either hidden
                   6197: 	# or 'randomout' controlled resources to be graded
                   6198: 	# don't include them
                   6199: 	if ($env{'form.scantron_options_hidden'} eq 'ignore_hidden'
                   6200: 	    && $curres->randomout) {
                   6201: 	    return 0;
                   6202: 	}
1.83      albertel 6203: 	return 1;
                   6204:     }
                   6205:     return 0;
1.82      albertel 6206: }
                   6207: 
1.423     albertel 6208: =pod
                   6209: 
                   6210: =item scantron_process_corrections
                   6211: 
1.424     albertel 6212:    Gets correction information out of submitted form data and corrects
                   6213:    the scanline
                   6214: 
1.423     albertel 6215: =cut
                   6216: 
1.157     albertel 6217: sub scantron_process_corrections {
                   6218:     my ($r) = @_;
1.257     albertel 6219:     my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
1.157     albertel 6220:     my ($scanlines,$scan_data)=&scantron_getfile();
                   6221:     my $classlist=&Apache::loncoursedata::get_classlist();
1.257     albertel 6222:     my $which=$env{'form.scantron_line'};
1.200     albertel 6223:     my $line=&scantron_get_line($scanlines,$scan_data,$which);
1.157     albertel 6224:     my ($skip,$err,$errmsg);
1.257     albertel 6225:     if ($env{'form.scantron_skip_record'}) {
1.157     albertel 6226: 	$skip=1;
1.257     albertel 6227:     } elsif ($env{'form.scantron_corrections'} =~ /^(duplicate|incorrect)ID$/) {
                   6228: 	my $newstudent=$env{'form.scantron_username'}.':'.
                   6229: 	    $env{'form.scantron_domain'};
1.157     albertel 6230: 	my $newid=$classlist->{$newstudent}->[&Apache::loncoursedata::CL_ID];
                   6231: 	($line,$err,$errmsg)=
                   6232: 	    &scantron_fixup_scanline(\%scantron_config,$scan_data,$line,$which,
                   6233: 				     'ID',{'newid'=>$newid,
1.257     albertel 6234: 				    'username'=>$env{'form.scantron_username'},
                   6235: 				    'domain'=>$env{'form.scantron_domain'}});
                   6236:     } elsif ($env{'form.scantron_corrections'} =~ /^(duplicate|incorrect)CODE$/) {
                   6237: 	my $resolution=$env{'form.scantron_CODE_resolution'};
1.190     albertel 6238: 	my $newCODE;
1.192     albertel 6239: 	my %args;
1.190     albertel 6240: 	if      ($resolution eq 'use_unfound') {
1.191     albertel 6241: 	    $newCODE='use_unfound';
1.190     albertel 6242: 	} elsif ($resolution eq 'use_found') {
1.257     albertel 6243: 	    $newCODE=$env{'form.scantron_CODE_selectedvalue'};
1.190     albertel 6244: 	} elsif ($resolution eq 'use_typed') {
1.257     albertel 6245: 	    $newCODE=$env{'form.scantron_CODE_newvalue'};
1.194     albertel 6246: 	} elsif ($resolution =~ /^use_closest_(\d+)/) {
1.257     albertel 6247: 	    $newCODE=$env{"form.scantron_CODE_closest_$1"};
1.190     albertel 6248: 	}
1.257     albertel 6249: 	if ($env{'form.scantron_corrections'} eq 'duplicateCODE') {
1.192     albertel 6250: 	    $args{'CODE_ignore_dup'}=1;
                   6251: 	}
                   6252: 	$args{'CODE'}=$newCODE;
1.186     albertel 6253: 	($line,$err,$errmsg)=
                   6254: 	    &scantron_fixup_scanline(\%scantron_config,$scan_data,$line,$which,
1.192     albertel 6255: 				     'CODE',\%args);
1.257     albertel 6256:     } elsif ($env{'form.scantron_corrections'} =~ /^(missing|double)bubble$/) {
                   6257: 	foreach my $question (split(',',$env{'form.scantron_questions'})) {
1.157     albertel 6258: 	    ($line,$err,$errmsg)=
                   6259: 		&scantron_fixup_scanline(\%scantron_config,$scan_data,$line,
                   6260: 					 $which,'answer',
                   6261: 					 { 'question'=>$question,
1.503     raeburn  6262: 		      		   'response'=>$env{"form.scantron_correct_Q_$question"},
                   6263:                                    'questionnum'=>$env{"form.scantron_questionnum_Q_$question"}});
1.157     albertel 6264: 	    if ($err) { last; }
                   6265: 	}
                   6266:     }
                   6267:     if ($err) {
1.398     albertel 6268: 	$r->print("<span class=\"LC_warning\">Unable to accept last correction, an error occurred :$errmsg:</span>");
1.157     albertel 6269:     } else {
1.200     albertel 6270: 	&scantron_put_line($scanlines,$scan_data,$which,$line,$skip);
1.157     albertel 6271: 	&scantron_putfile($scanlines,$scan_data);
                   6272:     }
                   6273: }
                   6274: 
1.423     albertel 6275: =pod
                   6276: 
                   6277: =item reset_skipping_status
                   6278: 
1.424     albertel 6279:    Forgets the current set of remember skipped scanlines (and thus
                   6280:    reverts back to considering all lines in the
                   6281:    scantron_skipped_<filename> file)
                   6282: 
1.423     albertel 6283: =cut
                   6284: 
1.200     albertel 6285: sub reset_skipping_status {
                   6286:     my ($scanlines,$scan_data)=&scantron_getfile();
                   6287:     &scan_data($scan_data,'remember_skipping',undef,1);
                   6288:     &scantron_putfile(undef,$scan_data);
                   6289: }
                   6290: 
1.423     albertel 6291: =pod
                   6292: 
                   6293: =item start_skipping
                   6294: 
1.424     albertel 6295:    Marks a scanline to be skipped. 
                   6296: 
1.423     albertel 6297: =cut
                   6298: 
1.376     albertel 6299: sub start_skipping {
1.200     albertel 6300:     my ($scan_data,$i)=@_;
                   6301:     my %remembered=split(':',&scan_data($scan_data,'remember_skipping'));
1.376     albertel 6302:     if ($env{'form.scantron_options_redo'} =~ /^redo_/) {
                   6303: 	$remembered{$i}=2;
                   6304:     } else {
                   6305: 	$remembered{$i}=1;
                   6306:     }
1.200     albertel 6307:     &scan_data($scan_data,'remember_skipping',join(':',%remembered));
                   6308: }
                   6309: 
1.423     albertel 6310: =pod
                   6311: 
                   6312: =item should_be_skipped
                   6313: 
1.424     albertel 6314:    Checks whether a scanline should be skipped.
                   6315: 
1.423     albertel 6316: =cut
                   6317: 
1.200     albertel 6318: sub should_be_skipped {
1.376     albertel 6319:     my ($scanlines,$scan_data,$i)=@_;
1.257     albertel 6320:     if ($env{'form.scantron_options_redo'} !~ /^redo_/) {
1.200     albertel 6321: 	# not redoing old skips
1.376     albertel 6322: 	if ($scanlines->{'skipped'}[$i]) { return 1; }
1.200     albertel 6323: 	return 0;
                   6324:     }
                   6325:     my %remembered=split(':',&scan_data($scan_data,'remember_skipping'));
1.376     albertel 6326: 
                   6327:     if (exists($remembered{$i}) && $remembered{$i} != 2 ) {
                   6328: 	return 0;
                   6329:     }
1.200     albertel 6330:     return 1;
                   6331: }
                   6332: 
1.423     albertel 6333: =pod
                   6334: 
                   6335: =item remember_current_skipped
                   6336: 
1.424     albertel 6337:    Discovers what scanlines are in the scantron_skipped_<filename>
                   6338:    file and remembers them into scan_data for later use.
                   6339: 
1.423     albertel 6340: =cut
                   6341: 
1.200     albertel 6342: sub remember_current_skipped {
                   6343:     my ($scanlines,$scan_data)=&scantron_getfile();
                   6344:     my %to_remember;
                   6345:     for (my $i=0;$i<=$scanlines->{'count'};$i++) {
                   6346: 	if ($scanlines->{'skipped'}[$i]) {
                   6347: 	    $to_remember{$i}=1;
                   6348: 	}
                   6349:     }
1.376     albertel 6350: 
1.200     albertel 6351:     &scan_data($scan_data,'remember_skipping',join(':',%to_remember));
                   6352:     &scantron_putfile(undef,$scan_data);
                   6353: }
                   6354: 
1.423     albertel 6355: =pod
                   6356: 
                   6357: =item check_for_error
                   6358: 
1.424     albertel 6359:     Checks if there was an error when attempting to remove a specific
1.596.2.6  raeburn  6360:     scantron_.. bubblesheet data file. Prints out an error if
1.424     albertel 6361:     something went wrong.
                   6362: 
1.423     albertel 6363: =cut
                   6364: 
1.200     albertel 6365: sub check_for_error {
                   6366:     my ($r,$result)=@_;
                   6367:     if ($result ne 'ok' && $result ne 'not_found' ) {
1.492     albertel 6368: 	$r->print(&mt("An error occurred ([_1]) when trying to remove the existing corrections.",$result));
1.200     albertel 6369:     }
                   6370: }
1.157     albertel 6371: 
1.423     albertel 6372: =pod
                   6373: 
                   6374: =item scantron_warning_screen
                   6375: 
1.424     albertel 6376:    Interstitial screen to make sure the operator has selected the
                   6377:    correct options before we start the validation phase.
                   6378: 
1.423     albertel 6379: =cut
                   6380: 
1.203     albertel 6381: sub scantron_warning_screen {
                   6382:     my ($button_text)=@_;
1.257     albertel 6383:     my $title=&Apache::lonnet::gettitle($env{'form.selectpage'});
1.284     albertel 6384:     my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
1.373     albertel 6385:     my $CODElist;
1.284     albertel 6386:     if ($scantron_config{'CODElocation'} &&
                   6387: 	$scantron_config{'CODEstart'} &&
                   6388: 	$scantron_config{'CODElength'}) {
                   6389: 	$CODElist=$env{'form.scantron_CODElist'};
1.398     albertel 6390: 	if ($env{'form.scantron_CODElist'} eq '') { $CODElist='<span class="LC_warning">None</span>'; }
1.284     albertel 6391: 	$CODElist=
1.492     albertel 6392: 	    '<tr><td><b>'.&mt('List of CODES to validate against:').'</b></td><td><tt>'.
1.373     albertel 6393: 	    $env{'form.scantron_CODElist'}.'</tt></td></tr>';
1.284     albertel 6394:     }
1.596.2.12.2.  (raeburn 6395:):     my $lastbubblepoints;
                   6396:):     if ($env{'form.scantron_lastbubblepoints'} ne '') {
                   6397:):         $lastbubblepoints =
                   6398:):             '<tr><td><b>'.&mt('Hand-graded items: points from last bubble in row').'</b></td><td><tt>'.
                   6399:):             $env{'form.scantron_lastbubblepoints'}.'</tt></td></tr>';
                   6400:):     }
1.492     albertel 6401:     return ('
1.203     albertel 6402: <p>
1.492     albertel 6403: <span class="LC_warning">
                   6404: '.&mt('Please double check the information below before clicking on \'[_1]\'',&mt($button_text)).'</span>
1.203     albertel 6405: </p>
                   6406: <table>
1.492     albertel 6407: <tr><td><b>'.&mt('Sequence to be Graded:').'</b></td><td>'.$title.'</td></tr>
                   6408: <tr><td><b>'.&mt('Data File that will be used:').'</b></td><td><tt>'.$env{'form.scantron_selectfile'}.'</tt></td></tr>
1.596.2.12.2.  (raeburn 6409:): '.$CODElist.$lastbubblepoints.'
1.203     albertel 6410: </table>
                   6411: <br />
1.492     albertel 6412: <p> '.&mt('If this information is correct, please click on \'[_1]\'.',&mt($button_text)).'</p>
                   6413: <p> '.&mt('If something is incorrect, please click the \'Grading Menu\' button to start over.').'</p>
1.203     albertel 6414: 
                   6415: <br />
1.492     albertel 6416: ');
1.203     albertel 6417: }
                   6418: 
1.423     albertel 6419: =pod
                   6420: 
                   6421: =item scantron_do_warning
                   6422: 
1.424     albertel 6423:    Check if the operator has picked something for all required
                   6424:    fields. Error out if something is missing.
                   6425: 
1.423     albertel 6426: =cut
                   6427: 
1.203     albertel 6428: sub scantron_do_warning {
                   6429:     my ($r)=@_;
1.324     albertel 6430:     my ($symb)=&get_symb($r);
1.203     albertel 6431:     if (!$symb) {return '';}
1.324     albertel 6432:     my $default_form_data=&defaultFormData($symb);
1.203     albertel 6433:     $r->print(&scantron_form_start().$default_form_data);
1.257     albertel 6434:     if ( $env{'form.selectpage'} eq '' ||
                   6435: 	 $env{'form.scantron_selectfile'} eq '' ||
                   6436: 	 $env{'form.scantron_format'} eq '' ) {
1.596.2.4  raeburn  6437: 	$r->print("<p>".&mt('You have forgotten to specify some information. Please go Back and try again.')."</p>");
1.257     albertel 6438: 	if ( $env{'form.selectpage'} eq '') {
1.492     albertel 6439: 	    $r->print('<p><span class="LC_error">'.&mt('You have not selected a Sequence to grade').'</span></p>');
1.237     albertel 6440: 	} 
1.257     albertel 6441: 	if ( $env{'form.scantron_selectfile'} eq '') {
1.596.2.4  raeburn  6442: 	    $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 6443: 	} 
1.257     albertel 6444: 	if ( $env{'form.scantron_format'} eq '') {
1.596.2.5  raeburn  6445: 	    $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 6446: 	} 
                   6447:     } else {
1.265     www      6448: 	my $warning=&scantron_warning_screen('Grading: Validate Records');
1.596.2.12.2.  (raeburn 6449:):         my $bubbledbyhand=&hand_bubble_option();
1.492     albertel 6450: 	$r->print('
1.596.2.12.2.  (raeburn 6451:): '.$warning.$bubbledbyhand.'
1.492     albertel 6452: <input type="submit" name="submit" value="'.&mt('Grading: Validate Records').'" />
1.203     albertel 6453: <input type="hidden" name="command" value="scantron_validate" />
1.492     albertel 6454: ');
1.237     albertel 6455:     }
1.352     albertel 6456:     $r->print("</form><br />".&show_grading_menu_form($symb));
1.203     albertel 6457:     return '';
                   6458: }
                   6459: 
1.423     albertel 6460: =pod
                   6461: 
                   6462: =item scantron_form_start
                   6463: 
1.424     albertel 6464:     html hidden input for remembering all selected grading options
                   6465: 
1.423     albertel 6466: =cut
                   6467: 
1.203     albertel 6468: sub scantron_form_start {
                   6469:     my ($max_bubble)=@_;
                   6470:     my $result= <<SCANTRONFORM;
                   6471: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="scantronupload">
1.257     albertel 6472:   <input type="hidden" name="selectpage" value="$env{'form.selectpage'}" />
                   6473:   <input type="hidden" name="scantron_format" value="$env{'form.scantron_format'}" />
                   6474:   <input type="hidden" name="scantron_selectfile" value="$env{'form.scantron_selectfile'}" />
1.218     albertel 6475:   <input type="hidden" name="scantron_maxbubble" value="$max_bubble" />
1.257     albertel 6476:   <input type="hidden" name="scantron_CODElist" value="$env{'form.scantron_CODElist'}" />
                   6477:   <input type="hidden" name="scantron_CODEunique" value="$env{'form.scantron_CODEunique'}" />
                   6478:   <input type="hidden" name="scantron_options_redo" value="$env{'form.scantron_options_redo'}" />
                   6479:   <input type="hidden" name="scantron_options_ignore" value="$env{'form.scantron_options_ignore'}" />
1.331     albertel 6480:   <input type="hidden" name="scantron_options_hidden" value="$env{'form.scantron_options_hidden'}" />
1.203     albertel 6481: SCANTRONFORM
1.447     foxr     6482: 
                   6483:   my $line = 0;
                   6484:     while (defined($env{"form.scantron.bubblelines.$line"})) {
                   6485:        my $chunk =
                   6486: 	   '<input type="hidden" name="scantron.bubblelines.'.$line.'" value="'.$env{"form.scantron.bubblelines.$line"}.'" />'."\n";
1.448     foxr     6487:        $chunk .=
                   6488: 	   '<input type="hidden" name="scantron.first_bubble_line.'.$line.'" value="'.$env{"form.scantron.first_bubble_line.$line"}.'" />'."\n";
1.503     raeburn  6489:        $chunk .= 
                   6490:            '<input type="hidden" name="scantron.sub_bubblelines.'.$line.'" value="'.$env{"form.scantron.sub_bubblelines.$line"}.'" />'."\n";
1.504     raeburn  6491:        $chunk .=
                   6492:            '<input type="hidden" name="scantron.responsetype.'.$line.'" value="'.$env{"form.scantron.responsetype.$line"}.'" />'."\n";
1.447     foxr     6493:        $result .= $chunk;
                   6494:        $line++;
                   6495:    }
1.203     albertel 6496:     return $result;
                   6497: }
                   6498: 
1.423     albertel 6499: =pod
                   6500: 
                   6501: =item scantron_validate_file
                   6502: 
1.596.2.6  raeburn  6503:     Dispatch routine for doing validation of a bubblesheet data file.
1.424     albertel 6504: 
                   6505:     Also processes any necessary information resets that need to
                   6506:     occur before validation begins (ignore previous corrections,
                   6507:     restarting the skipped records processing)
                   6508: 
1.423     albertel 6509: =cut
                   6510: 
1.157     albertel 6511: sub scantron_validate_file {
                   6512:     my ($r) = @_;
1.324     albertel 6513:     my ($symb)=&get_symb($r);
1.157     albertel 6514:     if (!$symb) {return '';}
1.324     albertel 6515:     my $default_form_data=&defaultFormData($symb);
1.200     albertel 6516:     
                   6517:     # do the detection of only doing skipped records first befroe we delete
1.424     albertel 6518:     # them when doing the corrections reset
1.257     albertel 6519:     if ($env{'form.scantron_options_redo'} ne 'redo_skipped_ready') {
1.200     albertel 6520: 	&reset_skipping_status();
                   6521:     }
1.257     albertel 6522:     if ($env{'form.scantron_options_redo'} eq 'redo_skipped') {
1.200     albertel 6523: 	&remember_current_skipped();
1.257     albertel 6524: 	$env{'form.scantron_options_redo'}='redo_skipped_ready';
1.200     albertel 6525:     }
                   6526: 
1.257     albertel 6527:     if ($env{'form.scantron_options_ignore'} eq 'ignore_corrections') {
1.200     albertel 6528: 	&check_for_error($r,&scantron_remove_file('corrected'));
                   6529: 	&check_for_error($r,&scantron_remove_file('skipped'));
                   6530: 	&check_for_error($r,&scantron_remove_scan_data());
1.257     albertel 6531: 	$env{'form.scantron_options_ignore'}='done';
1.192     albertel 6532:     }
1.200     albertel 6533: 
1.257     albertel 6534:     if ($env{'form.scantron_corrections'}) {
1.157     albertel 6535: 	&scantron_process_corrections($r);
                   6536:     }
1.503     raeburn  6537:     $r->print('<p>'.&mt('Gathering necessary information.').'</p>');$r->rflush();
1.157     albertel 6538:     #get the student pick code ready
                   6539:     $r->print(&Apache::loncommon::studentbrowser_javascript());
1.582     raeburn  6540:     my $nav_error;
1.596.2.12.2.  (raeburn 6541:):     my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
                   6542:):     my $max_bubble=&scantron_get_maxbubble(\$nav_error,\%scantron_config);
1.582     raeburn  6543:     if ($nav_error) {
                   6544:         $r->print(&navmap_errormsg());
                   6545:         return '';
                   6546:     }
1.203     albertel 6547:     my $result=&scantron_form_start($max_bubble).$default_form_data;
1.596.2.12.2.  (raeburn 6548:):     if ($env{'form.scantron_lastbubblepoints'} ne '') {
                   6549:):         $result .= '<input type="hidden" name="scantron_lastbubblepoints" value="'.$env{'form.scantron_lastbubblepoints'}.'" />';
                   6550:):     }
1.157     albertel 6551:     $r->print($result);
                   6552:     
1.334     albertel 6553:     my @validate_phases=( 'sequence',
                   6554: 			  'ID',
1.157     albertel 6555: 			  'CODE',
                   6556: 			  'doublebubble',
                   6557: 			  'missingbubbles');
1.257     albertel 6558:     if (!$env{'form.validatepass'}) {
                   6559: 	$env{'form.validatepass'} = 0;
1.157     albertel 6560:     }
1.257     albertel 6561:     my $currentphase=$env{'form.validatepass'};
1.157     albertel 6562: 
1.448     foxr     6563: 
1.157     albertel 6564:     my $stop=0;
                   6565:     while (!$stop && $currentphase < scalar(@validate_phases)) {
1.503     raeburn  6566: 	$r->print(&mt('Validating '.$validate_phases[$currentphase]).'<br />');
1.157     albertel 6567: 	$r->rflush();
                   6568: 	my $which="scantron_validate_".$validate_phases[$currentphase];
                   6569: 	{
                   6570: 	    no strict 'refs';
                   6571: 	    ($stop,$currentphase)=&$which($r,$currentphase);
                   6572: 	}
                   6573:     }
                   6574:     if (!$stop) {
1.203     albertel 6575: 	my $warning=&scantron_warning_screen('Start Grading');
1.542     raeburn  6576: 	$r->print(&mt('Validation process complete.').'<br />'.
                   6577:                   $warning.
                   6578:                   &mt('Perform verification for each student after storage of submissions?').
                   6579:                   '&nbsp;<span class="LC_nobreak"><label>'.
                   6580:                   '<input type="radio" name="verifyrecord" value="1" />'.&mt('Yes').'</label>'.
                   6581:                   ('&nbsp;'x3).'<label>'.
                   6582:                   '<input type="radio" name="verifyrecord" value="0" checked="checked" />'.&mt('No').
                   6583:                   '</label></span><br />'.
                   6584:                   &mt('Grading will take longer if you use verification.').'<br />'.
1.572     www      6585:                   &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  6586:                   '<input type="submit" name="submit" value="'.&mt('Start Grading').'" />'.
                   6587:                   '<input type="hidden" name="command" value="scantron_process" />'."\n");
1.157     albertel 6588:     } else {
                   6589: 	$r->print('<input type="hidden" name="command" value="scantron_validate" />');
                   6590: 	$r->print("<input type='hidden' name='validatepass' value='".$currentphase."' />");
                   6591:     }
                   6592:     if ($stop) {
1.334     albertel 6593: 	if ($validate_phases[$currentphase] eq 'sequence') {
1.539     riegler  6594: 	    $r->print('<input type="submit" name="submit" value="'.&mt('Ignore').' &rarr; " />');
1.492     albertel 6595: 	    $r->print(' '.&mt('this error').' <br />');
1.334     albertel 6596: 
1.492     albertel 6597: 	    $r->print(" <p>".&mt("Or click the 'Grading Menu' button to start over.")."</p>");
1.334     albertel 6598: 	} else {
1.503     raeburn  6599:             if ($validate_phases[$currentphase] eq 'doublebubble' || $validate_phases[$currentphase] eq 'missingbubbles') {
1.539     riegler  6600: 	        $r->print('<input type="button" name="submitbutton" value="'.&mt('Continue').' &rarr;" onclick="javascript:verify_bubble_radio(this.form)" />');
1.503     raeburn  6601:             } else {
1.539     riegler  6602:                 $r->print('<input type="submit" name="submit" value="'.&mt('Continue').' &rarr;" />');
1.503     raeburn  6603:             }
1.492     albertel 6604: 	    $r->print(' '.&mt('using corrected info').' <br />');
                   6605: 	    $r->print("<input type='submit' value='".&mt("Skip")."' name='scantron_skip_record' />");
                   6606: 	    $r->print(" ".&mt("this scanline saving it for later."));
1.334     albertel 6607: 	}
1.157     albertel 6608:     }
1.352     albertel 6609:     $r->print(" </form><br />".&show_grading_menu_form($symb));
1.157     albertel 6610:     return '';
                   6611: }
                   6612: 
1.423     albertel 6613: 
                   6614: =pod
                   6615: 
                   6616: =item scantron_remove_file
                   6617: 
1.596.2.6  raeburn  6618:    Removes the requested bubblesheet data file, makes sure that
1.424     albertel 6619:    scantron_original_<filename> is never removed
                   6620: 
                   6621: 
1.423     albertel 6622: =cut
                   6623: 
1.200     albertel 6624: sub scantron_remove_file {
1.192     albertel 6625:     my ($which)=@_;
1.257     albertel 6626:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   6627:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1.192     albertel 6628:     my $file='scantron_';
1.200     albertel 6629:     if ($which eq 'corrected' || $which eq 'skipped') {
                   6630: 	$file.=$which.'_';
1.192     albertel 6631:     } else {
                   6632: 	return 'refused';
                   6633:     }
1.257     albertel 6634:     $file.=$env{'form.scantron_selectfile'};
1.200     albertel 6635:     return &Apache::lonnet::removeuserfile($cname,$cdom,$file);
                   6636: }
                   6637: 
1.423     albertel 6638: 
                   6639: =pod
                   6640: 
                   6641: =item scantron_remove_scan_data
                   6642: 
1.596.2.6  raeburn  6643:    Removes all scan_data correction for the requested bubblesheet
1.424     albertel 6644:    data file.  (In the case that both the are doing skipped records we need
                   6645:    to remember the old skipped lines for the time being so that element
                   6646:    persists for a while.)
                   6647: 
1.423     albertel 6648: =cut
                   6649: 
1.200     albertel 6650: sub scantron_remove_scan_data {
1.257     albertel 6651:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   6652:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1.192     albertel 6653:     my @keys=&Apache::lonnet::getkeys('nohist_scantrondata',$cdom,$cname);
                   6654:     my @todelete;
1.257     albertel 6655:     my $filename=$env{'form.scantron_selectfile'};
1.192     albertel 6656:     foreach my $key (@keys) {
                   6657: 	if ($key=~/^\Q$filename\E_/) {
1.257     albertel 6658: 	    if ($env{'form.scantron_options_redo'} eq 'redo_skipped_ready' &&
1.200     albertel 6659: 		$key=~/remember_skipping/) {
                   6660: 		next;
                   6661: 	    }
1.192     albertel 6662: 	    push(@todelete,$key);
                   6663: 	}
                   6664:     }
1.200     albertel 6665:     my $result;
1.192     albertel 6666:     if (@todelete) {
1.491     albertel 6667: 	$result = &Apache::lonnet::del('nohist_scantrondata',
                   6668: 				       \@todelete,$cdom,$cname);
                   6669:     } else {
                   6670: 	$result = 'ok';
1.192     albertel 6671:     }
                   6672:     return $result;
                   6673: }
                   6674: 
1.423     albertel 6675: 
                   6676: =pod
                   6677: 
                   6678: =item scantron_getfile
                   6679: 
1.596.2.6  raeburn  6680:     Fetches the requested bubblesheet data file (all 3 versions), and
1.424     albertel 6681:     the scan_data hash
                   6682:   
                   6683:   Arguments:
                   6684:     None
                   6685: 
                   6686:   Returns:
                   6687:     2 hash references
                   6688: 
                   6689:      - first one has 
                   6690:          orig      -
                   6691:          corrected -
                   6692:          skipped   -  each of which points to an array ref of the specified
                   6693:                       file broken up into individual lines
                   6694:          count     - number of scanlines
                   6695:  
                   6696:      - second is the scan_data hash possible keys are
1.425     albertel 6697:        ($number refers to scanline numbered $number and thus the key affects
                   6698:         only that scanline
                   6699:         $bubline refers to the specific bubble line element and the aspects
                   6700:         refers to that specific bubble line element)
                   6701: 
                   6702:        $number.user - username:domain to use
                   6703:        $number.CODE_ignore_dup 
                   6704:                     - ignore the duplicate CODE error 
                   6705:        $number.useCODE
                   6706:                     - use the CODE in the scanline as is
                   6707:        $number.no_bubble.$bubline
                   6708:                     - it is valid that there is no bubbled in bubble
                   6709:                       at $number $bubline
                   6710:        remember_skipping
                   6711:                     - a frozen hash containing keys of $number and values
                   6712:                       of either 
                   6713:                         1 - we are on a 'do skipped records pass' and plan
                   6714:                             on processing this line
                   6715:                         2 - we are on a 'do skipped records pass' and this
                   6716:                             scanline has been marked to skip yet again
1.424     albertel 6717: 
1.423     albertel 6718: =cut
                   6719: 
1.157     albertel 6720: sub scantron_getfile {
1.200     albertel 6721:     #FIXME really would prefer a scantron directory
1.257     albertel 6722:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   6723:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1.157     albertel 6724:     my $lines;
                   6725:     $lines=&Apache::lonnet::getfile('/uploaded/'.$cdom.'/'.$cname.'/'.
1.257     albertel 6726: 		       'scantron_orig_'.$env{'form.scantron_selectfile'});
1.157     albertel 6727:     my %scanlines;
                   6728:     $scanlines{'orig'}=[(split("\n",$lines,-1))];
                   6729:     my $temp=$scanlines{'orig'};
                   6730:     $scanlines{'count'}=$#$temp;
                   6731: 
                   6732:     $lines=&Apache::lonnet::getfile('/uploaded/'.$cdom.'/'.$cname.'/'.
1.257     albertel 6733: 		       'scantron_corrected_'.$env{'form.scantron_selectfile'});
1.157     albertel 6734:     if ($lines eq '-1') {
                   6735: 	$scanlines{'corrected'}=[];
                   6736:     } else {
                   6737: 	$scanlines{'corrected'}=[(split("\n",$lines,-1))];
                   6738:     }
                   6739:     $lines=&Apache::lonnet::getfile('/uploaded/'.$cdom.'/'.$cname.'/'.
1.257     albertel 6740: 		       'scantron_skipped_'.$env{'form.scantron_selectfile'});
1.157     albertel 6741:     if ($lines eq '-1') {
                   6742: 	$scanlines{'skipped'}=[];
                   6743:     } else {
                   6744: 	$scanlines{'skipped'}=[(split("\n",$lines,-1))];
                   6745:     }
1.175     albertel 6746:     my @tmp=&Apache::lonnet::dump('nohist_scantrondata',$cdom,$cname);
1.157     albertel 6747:     if ($tmp[0] =~ /^(error:|no_such_host)/) { @tmp=(); }
                   6748:     my %scan_data = @tmp;
                   6749:     return (\%scanlines,\%scan_data);
                   6750: }
                   6751: 
1.423     albertel 6752: =pod
                   6753: 
                   6754: =item lonnet_putfile
                   6755: 
1.424     albertel 6756:    Wrapper routine to call &Apache::lonnet::finishuserfileupload
                   6757: 
                   6758:  Arguments:
                   6759:    $contents - data to store
                   6760:    $filename - filename to store $contents into
                   6761: 
                   6762:  Returns:
                   6763:    result value from &Apache::lonnet::finishuserfileupload
                   6764: 
1.423     albertel 6765: =cut
                   6766: 
1.157     albertel 6767: sub lonnet_putfile {
                   6768:     my ($contents,$filename)=@_;
1.257     albertel 6769:     my $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   6770:     my $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
                   6771:     $env{'form.sillywaytopassafilearound'}=$contents;
1.275     albertel 6772:     &Apache::lonnet::finishuserfileupload($docuname,$docudom,'sillywaytopassafilearound',$filename);
1.157     albertel 6773: 
                   6774: }
                   6775: 
1.423     albertel 6776: =pod
                   6777: 
                   6778: =item scantron_putfile
                   6779: 
1.596.2.6  raeburn  6780:     Stores the current version of the bubblesheet data files, and the
1.424     albertel 6781:     scan_data hash. (Does not modify the original version only the
                   6782:     corrected and skipped versions.
                   6783: 
                   6784:  Arguments:
                   6785:     $scanlines - hash ref that looks like the first return value from
                   6786:                  &scantron_getfile()
                   6787:     $scan_data - hash ref that looks like the second return value from
                   6788:                  &scantron_getfile()
                   6789: 
1.423     albertel 6790: =cut
                   6791: 
1.157     albertel 6792: sub scantron_putfile {
                   6793:     my ($scanlines,$scan_data) = @_;
1.200     albertel 6794:     #FIXME really would prefer a scantron directory
1.257     albertel 6795:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   6796:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1.200     albertel 6797:     if ($scanlines) {
                   6798: 	my $prefix='scantron_';
1.157     albertel 6799: # no need to update orig, shouldn't change
                   6800: #   &lonnet_putfile(join("\n",@{$scanlines->{'orig'}}),$prefix.'orig_'.
1.257     albertel 6801: #		    $env{'form.scantron_selectfile'});
1.200     albertel 6802: 	&lonnet_putfile(join("\n",@{$scanlines->{'corrected'}}),
                   6803: 			$prefix.'corrected_'.
1.257     albertel 6804: 			$env{'form.scantron_selectfile'});
1.200     albertel 6805: 	&lonnet_putfile(join("\n",@{$scanlines->{'skipped'}}),
                   6806: 			$prefix.'skipped_'.
1.257     albertel 6807: 			$env{'form.scantron_selectfile'});
1.200     albertel 6808:     }
1.175     albertel 6809:     &Apache::lonnet::put('nohist_scantrondata',$scan_data,$cdom,$cname);
1.157     albertel 6810: }
                   6811: 
1.423     albertel 6812: =pod
                   6813: 
                   6814: =item scantron_get_line
                   6815: 
1.424     albertel 6816:    Returns the correct version of the scanline
                   6817: 
                   6818:  Arguments:
                   6819:     $scanlines - hash ref that looks like the first return value from
                   6820:                  &scantron_getfile()
                   6821:     $scan_data - hash ref that looks like the second return value from
                   6822:                  &scantron_getfile()
                   6823:     $i         - number of the requested line (starts at 0)
                   6824: 
                   6825:  Returns:
                   6826:    A scanline, (either the original or the corrected one if it
                   6827:    exists), or undef if the requested scanline should be
                   6828:    skipped. (Either because it's an skipped scanline, or it's an
                   6829:    unskipped scanline and we are not doing a 'do skipped scanlines'
                   6830:    pass.
                   6831: 
1.423     albertel 6832: =cut
                   6833: 
1.157     albertel 6834: sub scantron_get_line {
1.200     albertel 6835:     my ($scanlines,$scan_data,$i)=@_;
1.376     albertel 6836:     if (&should_be_skipped($scanlines,$scan_data,$i)) { return undef; }
                   6837:     #if ($scanlines->{'skipped'}[$i]) { return undef; }
1.157     albertel 6838:     if ($scanlines->{'corrected'}[$i]) {return $scanlines->{'corrected'}[$i];}
                   6839:     return $scanlines->{'orig'}[$i]; 
                   6840: }
                   6841: 
1.423     albertel 6842: =pod
                   6843: 
                   6844: =item scantron_todo_count
                   6845: 
1.424     albertel 6846:     Counts the number of scanlines that need processing.
                   6847: 
                   6848:  Arguments:
                   6849:     $scanlines - hash ref that looks like the first return value from
                   6850:                  &scantron_getfile()
                   6851:     $scan_data - hash ref that looks like the second return value from
                   6852:                  &scantron_getfile()
                   6853: 
                   6854:  Returns:
                   6855:     $count - number of scanlines to process
                   6856: 
1.423     albertel 6857: =cut
                   6858: 
1.200     albertel 6859: sub get_todo_count {
                   6860:     my ($scanlines,$scan_data)=@_;
                   6861:     my $count=0;
                   6862:     for (my $i=0;$i<=$scanlines->{'count'};$i++) {
                   6863: 	my $line=&scantron_get_line($scanlines,$scan_data,$i);
                   6864: 	if ($line=~/^[\s\cz]*$/) { next; }
                   6865: 	$count++;
                   6866:     }
                   6867:     return $count;
                   6868: }
                   6869: 
1.423     albertel 6870: =pod
                   6871: 
                   6872: =item scantron_put_line
                   6873: 
1.596.2.6  raeburn  6874:     Updates the 'corrected' or 'skipped' versions of the bubblesheet
1.424     albertel 6875:     data file.
                   6876: 
                   6877:  Arguments:
                   6878:     $scanlines - hash ref that looks like the first return value from
                   6879:                  &scantron_getfile()
                   6880:     $scan_data - hash ref that looks like the second return value from
                   6881:                  &scantron_getfile()
                   6882:     $i         - line number to update
                   6883:     $newline   - contents of the updated scanline
                   6884:     $skip      - if true make the line for skipping and update the
                   6885:                  'skipped' file
                   6886: 
1.423     albertel 6887: =cut
                   6888: 
1.157     albertel 6889: sub scantron_put_line {
1.200     albertel 6890:     my ($scanlines,$scan_data,$i,$newline,$skip)=@_;
1.157     albertel 6891:     if ($skip) {
                   6892: 	$scanlines->{'skipped'}[$i]=$newline;
1.376     albertel 6893: 	&start_skipping($scan_data,$i);
1.157     albertel 6894: 	return;
                   6895:     }
                   6896:     $scanlines->{'corrected'}[$i]=$newline;
                   6897: }
                   6898: 
1.423     albertel 6899: =pod
                   6900: 
                   6901: =item scantron_clear_skip
                   6902: 
1.424     albertel 6903:    Remove a line from the 'skipped' file
                   6904: 
                   6905:  Arguments:
                   6906:     $scanlines - hash ref that looks like the first return value from
                   6907:                  &scantron_getfile()
                   6908:     $scan_data - hash ref that looks like the second return value from
                   6909:                  &scantron_getfile()
                   6910:     $i         - line number to update
                   6911: 
1.423     albertel 6912: =cut
                   6913: 
1.376     albertel 6914: sub scantron_clear_skip {
                   6915:     my ($scanlines,$scan_data,$i)=@_;
                   6916:     if (exists($scanlines->{'skipped'}[$i])) {
                   6917: 	undef($scanlines->{'skipped'}[$i]);
                   6918: 	return 1;
                   6919:     }
                   6920:     return 0;
                   6921: }
                   6922: 
1.423     albertel 6923: =pod
                   6924: 
                   6925: =item scantron_filter_not_exam
                   6926: 
1.424     albertel 6927:    Filter routine used by &Apache::lonnavmaps::retrieveResources(), to
                   6928:    filter out resources that are not marked as 'exam' mode
                   6929: 
1.423     albertel 6930: =cut
                   6931: 
1.334     albertel 6932: sub scantron_filter_not_exam {
                   6933:     my ($curres)=@_;
                   6934:     
                   6935:     if (ref($curres) && $curres->is_problem() && !$curres->is_exam()) {
                   6936: 	# if the user has asked to not have either hidden
                   6937: 	# or 'randomout' controlled resources to be graded
                   6938: 	# don't include them
                   6939: 	if ($env{'form.scantron_options_hidden'} eq 'ignore_hidden'
                   6940: 	    && $curres->randomout) {
                   6941: 	    return 0;
                   6942: 	}
                   6943: 	return 1;
                   6944:     }
                   6945:     return 0;
                   6946: }
                   6947: 
1.423     albertel 6948: =pod
                   6949: 
                   6950: =item scantron_validate_sequence
                   6951: 
1.424     albertel 6952:     Validates the selected sequence, checking for resource that are
                   6953:     not set to exam mode.
                   6954: 
1.423     albertel 6955: =cut
                   6956: 
1.334     albertel 6957: sub scantron_validate_sequence {
                   6958:     my ($r,$currentphase) = @_;
                   6959: 
                   6960:     my $navmap=Apache::lonnavmaps::navmap->new();
1.582     raeburn  6961:     unless (ref($navmap)) {
                   6962:         $r->print(&navmap_errormsg());
                   6963:         return (1,$currentphase);
                   6964:     }
1.334     albertel 6965:     my (undef,undef,$sequence)=
                   6966: 	&Apache::lonnet::decode_symb($env{'form.selectpage'});
                   6967: 
                   6968:     my $map=$navmap->getResourceByUrl($sequence);
                   6969: 
                   6970:     $r->print('<input type="hidden" name="validate_sequence_exam"
                   6971:                                     value="ignore" />');
                   6972:     if ($env{'form.validate_sequence_exam'} ne 'ignore') {
                   6973: 	my @resources=
                   6974: 	    $navmap->retrieveResources($map,\&scantron_filter_not_exam,1,0);
                   6975: 	if (@resources) {
1.357     banghart 6976: 	    $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 6977: 	    return (1,$currentphase);
                   6978: 	}
                   6979:     }
                   6980: 
                   6981:     return (0,$currentphase+1);
                   6982: }
                   6983: 
1.423     albertel 6984: 
                   6985: 
1.157     albertel 6986: sub scantron_validate_ID {
                   6987:     my ($r,$currentphase) = @_;
                   6988:     
                   6989:     #get student info
                   6990:     my $classlist=&Apache::loncoursedata::get_classlist();
                   6991:     my %idmap=&username_to_idmap($classlist);
                   6992: 
                   6993:     #get scantron line setup
1.257     albertel 6994:     my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
1.157     albertel 6995:     my ($scanlines,$scan_data)=&scantron_getfile();
1.582     raeburn  6996: 
                   6997:     my $nav_error;
1.596.2.12.2.  (raeburn 6998:):     &scantron_get_maxbubble(\$nav_error,\%scantron_config); # parse needs the bubble_lines.. array.
1.582     raeburn  6999:     if ($nav_error) {
                   7000:         $r->print(&navmap_errormsg());
                   7001:         return(1,$currentphase);
                   7002:     }
1.157     albertel 7003: 
                   7004:     my %found=('ids'=>{},'usernames'=>{});
                   7005:     for (my $i=0;$i<=$scanlines->{'count'};$i++) {
1.200     albertel 7006: 	my $line=&scantron_get_line($scanlines,$scan_data,$i);
1.157     albertel 7007: 	if ($line=~/^[\s\cz]*$/) { next; }
                   7008: 	my $scan_record=&scantron_parse_scanline($line,$i,\%scantron_config,
                   7009: 						 $scan_data);
                   7010: 	my $id=$$scan_record{'scantron.ID'};
                   7011: 	my $found;
                   7012: 	foreach my $checkid (keys(%idmap)) {
                   7013: 	    if (lc($checkid) eq lc($id)) { $found=$checkid;last; }
                   7014: 	}
                   7015: 	if ($found) {
                   7016: 	    my $username=$idmap{$found};
                   7017: 	    if ($found{'ids'}{$found}) {
                   7018: 		&scantron_get_correction($r,$i,$scan_record,\%scantron_config,
                   7019: 					 $line,'duplicateID',$found);
1.194     albertel 7020: 		return(1,$currentphase);
1.157     albertel 7021: 	    } elsif ($found{'usernames'}{$username}) {
                   7022: 		&scantron_get_correction($r,$i,$scan_record,\%scantron_config,
                   7023: 					 $line,'duplicateID',$username);
1.194     albertel 7024: 		return(1,$currentphase);
1.157     albertel 7025: 	    }
1.186     albertel 7026: 	    #FIXME store away line we previously saw the ID on to use above
1.157     albertel 7027: 	    $found{'ids'}{$found}++;
                   7028: 	    $found{'usernames'}{$username}++;
                   7029: 	} else {
                   7030: 	    if ($id =~ /^\s*$/) {
1.158     albertel 7031: 		my $username=&scan_data($scan_data,"$i.user");
1.157     albertel 7032: 		if (defined($username) && $found{'usernames'}{$username}) {
                   7033: 		    &scantron_get_correction($r,$i,$scan_record,
                   7034: 					     \%scantron_config,
                   7035: 					     $line,'duplicateID',$username);
1.194     albertel 7036: 		    return(1,$currentphase);
1.157     albertel 7037: 		} elsif (!defined($username)) {
                   7038: 		    &scantron_get_correction($r,$i,$scan_record,
                   7039: 					     \%scantron_config,
                   7040: 					     $line,'incorrectID');
1.194     albertel 7041: 		    return(1,$currentphase);
1.157     albertel 7042: 		}
                   7043: 		$found{'usernames'}{$username}++;
                   7044: 	    } else {
                   7045: 		&scantron_get_correction($r,$i,$scan_record,\%scantron_config,
                   7046: 					 $line,'incorrectID');
1.194     albertel 7047: 		return(1,$currentphase);
1.157     albertel 7048: 	    }
                   7049: 	}
                   7050:     }
                   7051: 
                   7052:     return (0,$currentphase+1);
                   7053: }
                   7054: 
1.423     albertel 7055: 
1.157     albertel 7056: sub scantron_get_correction {
                   7057:     my ($r,$i,$scan_record,$scan_config,$line,$error,$arg)=@_;
1.454     banghart 7058: #FIXME in the case of a duplicated ID the previous line, probably need
1.157     albertel 7059: #to show both the current line and the previous one and allow skipping
                   7060: #the previous one or the current one
                   7061: 
1.333     albertel 7062:     if ( $$scan_record{'scantron.PaperID'} =~ /\S/) {
1.596.2.6  raeburn  7063:         $r->print(
                   7064:             '<p class="LC_warning">'
                   7065:            .&mt('An error was detected ([_1]) for PaperID [_2]',
                   7066:                 "<b>$error</b>",
                   7067:                 '<tt>'.$$scan_record{'scantron.PaperID'}.'</tt>')
                   7068:            ."</p> \n");
1.157     albertel 7069:     } else {
1.596.2.6  raeburn  7070:         $r->print(
                   7071:             '<p class="LC_warning">'
                   7072:            .&mt('An error was detected ([_1]) in scanline [_2] [_3]',
                   7073:                 "<b>$error</b>", $i, "<pre>$line</pre>")
                   7074:            ."</p> \n");
                   7075:     }
                   7076:     my $message =
                   7077:         '<p>'
                   7078:        .&mt('The ID on the form is [_1]',
                   7079:             "<tt>$$scan_record{'scantron.ID'}</tt>")
                   7080:        .'<br />'
1.596.2.12  raeburn  7081:        .&mt('The name on the paper is [_1], [_2]',
1.596.2.6  raeburn  7082:             $$scan_record{'scantron.LastName'},
                   7083:             $$scan_record{'scantron.FirstName'})
                   7084:        .'</p>';
1.242     albertel 7085: 
1.157     albertel 7086:     $r->print('<input type="hidden" name="scantron_corrections" value="'.$error.'" />'."\n");
                   7087:     $r->print('<input type="hidden" name="scantron_line" value="'.$i.'" />'."\n");
1.503     raeburn  7088:                            # Array populated for doublebubble or
                   7089:     my @lines_to_correct;  # missingbubble errors to build javascript
                   7090:                            # to validate radio button checking   
                   7091: 
1.157     albertel 7092:     if ($error =~ /ID$/) {
1.186     albertel 7093: 	if ($error eq 'incorrectID') {
1.596.2.6  raeburn  7094: 	    $r->print('<p class="LC_warning">'.&mt("The encoded ID is not in the classlist").
1.492     albertel 7095: 		      "</p>\n");
1.157     albertel 7096: 	} elsif ($error eq 'duplicateID') {
1.596.2.6  raeburn  7097: 	    $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 7098: 	}
1.242     albertel 7099: 	$r->print($message);
1.492     albertel 7100: 	$r->print("<p>".&mt("How should I handle this?")." <br /> \n");
1.157     albertel 7101: 	$r->print("\n<ul><li> ");
                   7102: 	#FIXME it would be nice if this sent back the user ID and
                   7103: 	#could do partial userID matches
                   7104: 	$r->print(&Apache::loncommon::selectstudent_link('scantronupload',
                   7105: 				       'scantron_username','scantron_domain'));
                   7106: 	$r->print(": <input type='text' name='scantron_username' value='' />");
                   7107: 	$r->print("\n@".
1.257     albertel 7108: 		 &Apache::loncommon::select_dom_form($env{'request.role.domain'},'scantron_domain'));
1.157     albertel 7109: 
                   7110: 	$r->print('</li>');
1.186     albertel 7111:     } elsif ($error =~ /CODE$/) {
                   7112: 	if ($error eq 'incorrectCODE') {
1.596.2.6  raeburn  7113: 	    $r->print('<p class="LC_warning">'.&mt("The encoded CODE is not in the list of possible CODEs.")."</p>\n");
1.186     albertel 7114: 	} elsif ($error eq 'duplicateCODE') {
1.596.2.6  raeburn  7115: 	    $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 7116: 	}
1.596.2.6  raeburn  7117:         $r->print("<p>".&mt('The CODE on the form is [_1]',
                   7118:                             "<tt>'$$scan_record{'scantron.CODE'}'</tt>")
                   7119:                  ."</p>\n");
1.242     albertel 7120: 	$r->print($message);
1.596.2.6  raeburn  7121: 	$r->print("<p>".&mt("How should I handle this?")."</p>\n");
1.187     albertel 7122: 	$r->print("\n<br /> ");
1.194     albertel 7123: 	my $i=0;
1.273     albertel 7124: 	if ($error eq 'incorrectCODE' 
                   7125: 	    && $$scan_record{'scantron.CODE'}=~/\S/ ) {
1.194     albertel 7126: 	    my ($max,$closest)=&scantron_get_closely_matching_CODEs($arg,$$scan_record{'scantron.CODE'});
1.278     albertel 7127: 	    if ($closest > 0) {
                   7128: 		foreach my $testcode (@{$closest}) {
                   7129: 		    my $checked='';
1.569     bisitz   7130: 		    if (!$i) { $checked=' checked="checked"'; }
1.492     albertel 7131: 		    $r->print("
                   7132:    <label>
1.569     bisitz   7133:        <input type='radio' name='scantron_CODE_resolution' value='use_closest_$i'$checked />
1.492     albertel 7134:        ".&mt("Use the similar CODE [_1] instead.",
                   7135: 	    "<b><tt>".$testcode."</tt></b>")."
                   7136:     </label>
                   7137:     <input type='hidden' name='scantron_CODE_closest_$i' value='$testcode' />");
1.278     albertel 7138: 		    $r->print("\n<br />");
                   7139: 		    $i++;
                   7140: 		}
1.194     albertel 7141: 	    }
                   7142: 	}
1.273     albertel 7143: 	if ($$scan_record{'scantron.CODE'}=~/\S/ ) {
1.569     bisitz   7144: 	    my $checked; if (!$i) { $checked=' checked="checked"'; }
1.492     albertel 7145: 	    $r->print("
                   7146:     <label>
1.569     bisitz   7147:         <input type='radio' name='scantron_CODE_resolution' value='use_unfound'$checked />
1.596.2.6  raeburn  7148:        ".&mt("Use the CODE [_1] that was on the paper, ignoring the error.",
1.492     albertel 7149: 	     "<b><tt>".$$scan_record{'scantron.CODE'}."</tt></b>")."
                   7150:     </label>");
1.273     albertel 7151: 	    $r->print("\n<br />");
                   7152: 	}
1.194     albertel 7153: 
1.188     albertel 7154: 	$r->print(<<ENDSCRIPT);
                   7155: <script type="text/javascript">
                   7156: function change_radio(field) {
1.190     albertel 7157:     var slct=document.scantronupload.scantron_CODE_resolution;
1.188     albertel 7158:     var i;
                   7159:     for (i=0;i<slct.length;i++) {
                   7160:         if (slct[i].value==field) { slct[i].checked=true; }
                   7161:     }
                   7162: }
                   7163: </script>
                   7164: ENDSCRIPT
1.187     albertel 7165: 	my $href="/adm/pickcode?".
1.359     www      7166: 	   "form=".&escape("scantronupload").
                   7167: 	   "&scantron_format=".&escape($env{'form.scantron_format'}).
                   7168: 	   "&scantron_CODElist=".&escape($env{'form.scantron_CODElist'}).
                   7169: 	   "&curCODE=".&escape($$scan_record{'scantron.CODE'}).
                   7170: 	   "&scantron_selectfile=".&escape($env{'form.scantron_selectfile'});
1.332     albertel 7171: 	if ($env{'form.scantron_CODElist'} =~ /\S/) { 
1.492     albertel 7172: 	    $r->print("
                   7173:     <label>
                   7174:        <input type='radio' name='scantron_CODE_resolution' value='use_found' />
                   7175:        ".&mt("[_1]Select[_2] a CODE from the list of all CODEs and use it.",
                   7176: 	     "<a target='_blank' href='$href'>","</a>")."
                   7177:     </label> 
1.558     bisitz   7178:     ".&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 7179: 	    $r->print("\n<br />");
                   7180: 	}
1.492     albertel 7181: 	$r->print("
                   7182:     <label>
                   7183:        <input type='radio' name='scantron_CODE_resolution' value='use_typed' />
                   7184:        ".&mt("Use [_1] as the CODE.",
                   7185: 	     "</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 7186: 	$r->print("\n<br /><br />");
1.157     albertel 7187:     } elsif ($error eq 'doublebubble') {
1.596.2.6  raeburn  7188: 	$r->print('<p class="LC_warning">'.&mt("There have been multiple bubbles scanned for some question(s)")."</p>\n");
1.497     foxr     7189: 
                   7190: 	# The form field scantron_questions is acutally a list of line numbers.
                   7191: 	# represented by this form so:
                   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.242     albertel 7197: 	$r->print($message);
1.492     albertel 7198: 	$r->print("<p>".&mt("Please indicate which bubble should be used for grading")."</p>");
1.157     albertel 7199: 	foreach my $question (@{$arg}) {
1.503     raeburn  7200: 	    my @linenums = &prompt_for_corrections($r,$question,$scan_config,
                   7201:                                                    $scan_record, $error);
1.524     raeburn  7202:             push(@lines_to_correct,@linenums);
1.157     albertel 7203: 	}
1.503     raeburn  7204:         $r->print(&verify_bubbles_checked(@lines_to_correct));
1.157     albertel 7205:     } elsif ($error eq 'missingbubble') {
1.596.2.9  raeburn  7206: 	$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 7207: 	$r->print($message);
1.492     albertel 7208: 	$r->print("<p>".&mt("Please indicate which bubble should be used for grading.")."</p>");
1.503     raeburn  7209: 	$r->print(&mt("Some questions have no scanned bubbles.")."\n");
1.497     foxr     7210: 
1.503     raeburn  7211: 	# The form field scantron_questions is actually a list of line numbers not
1.497     foxr     7212: 	# a list of question numbers. Therefore:
                   7213: 	#
                   7214: 	
                   7215: 	my $line_list = &questions_to_line_list($arg);
                   7216: 
1.157     albertel 7217: 	$r->print('<input type="hidden" name="scantron_questions" value="'.
1.497     foxr     7218: 		  $line_list.'" />');
1.157     albertel 7219: 	foreach my $question (@{$arg}) {
1.503     raeburn  7220: 	    my @linenums = &prompt_for_corrections($r,$question,$scan_config,
                   7221:                                                    $scan_record, $error);
1.524     raeburn  7222:             push(@lines_to_correct,@linenums);
1.157     albertel 7223: 	}
1.503     raeburn  7224:         $r->print(&verify_bubbles_checked(@lines_to_correct));
1.157     albertel 7225:     } else {
                   7226: 	$r->print("\n<ul>");
                   7227:     }
                   7228:     $r->print("\n</li></ul>");
1.497     foxr     7229: }
                   7230: 
1.503     raeburn  7231: sub verify_bubbles_checked {
                   7232:     my (@ansnums) = @_;
                   7233:     my $ansnumstr = join('","',@ansnums);
                   7234:     my $warning = &mt("A bubble or 'No bubble' selection has not been made for one or more lines.");
                   7235:     my $output = (<<ENDSCRIPT);
                   7236: <script type="text/javascript">
                   7237: function verify_bubble_radio(form) {
                   7238:     var ansnumArray = new Array ("$ansnumstr");
                   7239:     var need_bubble_count = 0;
                   7240:     for (var i=0; i<ansnumArray.length; i++) {
                   7241:         if (form.elements["scantron_correct_Q_"+ansnumArray[i]].length > 1) {
                   7242:             var bubble_picked = 0; 
                   7243:             for (var j=0; j<form.elements["scantron_correct_Q_"+ansnumArray[i]].length; j++) {
                   7244:                 if (form.elements["scantron_correct_Q_"+ansnumArray[i]][j].checked == true) {
                   7245:                     bubble_picked = 1;
                   7246:                 }
                   7247:             }
                   7248:             if (bubble_picked == 0) {
                   7249:                 need_bubble_count ++;
                   7250:             }
                   7251:         }
                   7252:     }
                   7253:     if (need_bubble_count) {
                   7254:         alert("$warning");
                   7255:         return;
                   7256:     }
                   7257:     form.submit(); 
                   7258: }
                   7259: </script>
                   7260: ENDSCRIPT
                   7261:     return $output;
                   7262: }
                   7263: 
1.497     foxr     7264: =pod
                   7265: 
                   7266: =item  questions_to_line_list
1.157     albertel 7267: 
1.497     foxr     7268: Converts a list of questions into a string of comma separated
                   7269: line numbers in the answer sheet used by the questions.  This is
                   7270: used to fill in the scantron_questions form field.
                   7271: 
                   7272:   Arguments:
                   7273:      questions    - Reference to an array of questions.
                   7274: 
                   7275: =cut
                   7276: 
                   7277: 
                   7278: sub questions_to_line_list {
                   7279:     my ($questions) = @_;
                   7280:     my @lines;
                   7281: 
1.503     raeburn  7282:     foreach my $item (@{$questions}) {
                   7283:         my $question = $item;
                   7284:         my ($first,$count,$last);
                   7285:         if ($item =~ /^(\d+)\.(\d+)$/) {
                   7286:             $question = $1;
                   7287:             my $subquestion = $2;
                   7288:             $first = $first_bubble_line{$question-1} + 1;
                   7289:             my @subans = split(/,/,$subdivided_bubble_lines{$question-1});
                   7290:             my $subcount = 1;
                   7291:             while ($subcount<$subquestion) {
                   7292:                 $first += $subans[$subcount-1];
                   7293:                 $subcount ++;
                   7294:             }
                   7295:             $count = $subans[$subquestion-1];
                   7296:         } else {
                   7297: 	    $first   = $first_bubble_line{$question-1} + 1;
                   7298: 	    $count   = $bubble_lines_per_response{$question-1};
                   7299:         }
1.506     raeburn  7300:         $last = $first+$count-1;
1.503     raeburn  7301:         push(@lines, ($first..$last));
1.497     foxr     7302:     }
                   7303:     return join(',', @lines);
                   7304: }
                   7305: 
                   7306: =pod 
                   7307: 
                   7308: =item prompt_for_corrections
                   7309: 
                   7310: Prompts for a potentially multiline correction to the
                   7311: user's bubbling (factors out common code from scantron_get_correction
                   7312: for multi and missing bubble cases).
                   7313: 
                   7314:  Arguments:
                   7315:    $r           - Apache request object.
                   7316:    $question    - The question number to prompt for.
                   7317:    $scan_config - The scantron file configuration hash.
                   7318:    $scan_record - Reference to the hash that has the the parsed scanlines.
1.503     raeburn  7319:    $error       - Type of error
1.497     foxr     7320: 
                   7321:  Implicit inputs:
                   7322:    %bubble_lines_per_response   - Starting line numbers for each question.
                   7323:                                   Numbered from 0 (but question numbers are from
                   7324:                                   1.
                   7325:    %first_bubble_line           - Starting bubble line for each question.
1.509     raeburn  7326:    %subdivided_bubble_lines     - optionresponse, matchresponse and rankresponse 
                   7327:                                   type problems render as separate sub-questions, 
1.503     raeburn  7328:                                   in exam mode. This hash contains a 
                   7329:                                   comma-separated list of the lines per 
                   7330:                                   sub-question.
1.510     raeburn  7331:    %responsetype_per_response   - essayresponse, formularesponse,
                   7332:                                   stringresponse, imageresponse, reactionresponse,
                   7333:                                   and organicresponse type problem parts can have
1.503     raeburn  7334:                                   multiple lines per response if the weight
                   7335:                                   assigned exceeds 10.  In this case, only
                   7336:                                   one bubble per line is permitted, but more 
                   7337:                                   than one line might contain bubbles, e.g.
                   7338:                                   bubbling of: line 1 - J, line 2 - J, 
                   7339:                                   line 3 - B would assign 22 points.  
1.497     foxr     7340: 
                   7341: =cut
                   7342: 
                   7343: sub prompt_for_corrections {
1.503     raeburn  7344:     my ($r, $question, $scan_config, $scan_record, $error) = @_;
                   7345:     my ($current_line,$lines);
                   7346:     my @linenums;
                   7347:     my $questionnum = $question;
                   7348:     if ($question =~ /^(\d+)\.(\d+)$/) {
                   7349:         $question = $1;
                   7350:         $current_line = $first_bubble_line{$question-1} + 1 ;
                   7351:         my $subquestion = $2;
                   7352:         my @subans = split(/,/,$subdivided_bubble_lines{$question-1});
                   7353:         my $subcount = 1;
                   7354:         while ($subcount<$subquestion) {
                   7355:             $current_line += $subans[$subcount-1];
                   7356:             $subcount ++;
                   7357:         }
                   7358:         $lines = $subans[$subquestion-1];
                   7359:     } else {
                   7360:         $current_line = $first_bubble_line{$question-1} + 1 ;
                   7361:         $lines        = $bubble_lines_per_response{$question-1};
                   7362:     }
1.497     foxr     7363:     if ($lines > 1) {
1.503     raeburn  7364:         $r->print(&mt('The group of bubble lines below responds to a single question.').'<br />');
                   7365:         if (($responsetype_per_response{$question-1} eq 'essayresponse') ||
                   7366:             ($responsetype_per_response{$question-1} eq 'formularesponse') ||
1.510     raeburn  7367:             ($responsetype_per_response{$question-1} eq 'stringresponse') ||
                   7368:             ($responsetype_per_response{$question-1} eq 'imageresponse') ||
                   7369:             ($responsetype_per_response{$question-1} eq 'reactionresponse') ||
                   7370:             ($responsetype_per_response{$question-1} eq 'organicresponse')) {
1.572     www      7371:             $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  7372:         } else {
                   7373:             $r->print(&mt("Select at most one bubble in a single line and select 'No Bubble' in all the other lines. ")."<br />");
                   7374:         }
1.497     foxr     7375:     }
                   7376:     for (my $i =0; $i < $lines; $i++) {
1.503     raeburn  7377:         my $selected = $$scan_record{"scantron.$current_line.answer"};
                   7378: 	&scantron_bubble_selector($r,$scan_config,$current_line, 
                   7379: 	        		  $questionnum,$error,split('', $selected));
1.524     raeburn  7380:         push(@linenums,$current_line);
1.497     foxr     7381: 	$current_line++;
                   7382:     }
                   7383:     if ($lines > 1) {
                   7384: 	$r->print("<hr /><br />");
                   7385:     }
1.503     raeburn  7386:     return @linenums;
1.157     albertel 7387: }
1.423     albertel 7388: 
                   7389: =pod
                   7390: 
                   7391: =item scantron_bubble_selector
                   7392:   
                   7393:    Generates the html radiobuttons to correct a single bubble line
1.424     albertel 7394:    possibly showing the existing the selected bubbles if known
1.423     albertel 7395: 
                   7396:  Arguments:
                   7397:     $r           - Apache request object
                   7398:     $scan_config - hash from &get_scantron_config()
1.497     foxr     7399:     $line        - Number of the line being displayed.
1.503     raeburn  7400:     $questionnum - Question number (may include subquestion)
                   7401:     $error       - Type of error.
1.497     foxr     7402:     @selected    - Array of bubbles picked on this line.
1.423     albertel 7403: 
                   7404: =cut
                   7405: 
1.157     albertel 7406: sub scantron_bubble_selector {
1.503     raeburn  7407:     my ($r,$scan_config,$line,$questionnum,$error,@selected)=@_;
1.157     albertel 7408:     my $max=$$scan_config{'Qlength'};
1.274     albertel 7409: 
                   7410:     my $scmode=$$scan_config{'Qon'};
1.596.2.12.2.  (raeburn 7411:):     if ($scmode eq 'number' || $scmode eq 'letter') {
                   7412:):         if (($$scan_config{'BubblesPerRow'} =~ /^\d+$/) &&
                   7413:):             ($$scan_config{'BubblesPerRow'} > 0)) {
                   7414:):             $max=$$scan_config{'BubblesPerRow'};
                   7415:):             if (($scmode eq 'number') && ($max > 10)) {
                   7416:):                 $max = 10;
                   7417:):             } elsif (($scmode eq 'letter') && $max > 26) {
                   7418:):                 $max = 26;
                   7419:):             }
                   7420:):         } else {
                   7421:):             $max = 10;
                   7422:):         }
                   7423:):     }
1.274     albertel 7424: 
1.157     albertel 7425:     my @alphabet=('A'..'Z');
1.503     raeburn  7426:     $r->print(&Apache::loncommon::start_data_table().
                   7427:               &Apache::loncommon::start_data_table_row());
                   7428:     $r->print('<td rowspan="2" class="LC_leftcol_header">'.$line.'</td>');
1.497     foxr     7429:     for (my $i=0;$i<$max+1;$i++) {
                   7430: 	$r->print("\n".'<td align="center">');
                   7431: 	if ($selected[0] eq $alphabet[$i]) { $r->print('X'); shift(@selected) }
                   7432: 	else { $r->print('&nbsp;'); }
                   7433: 	$r->print('</td>');
                   7434:     }
1.503     raeburn  7435:     $r->print(&Apache::loncommon::end_data_table_row().
                   7436:               &Apache::loncommon::start_data_table_row());
1.497     foxr     7437:     for (my $i=0;$i<$max;$i++) {
                   7438: 	$r->print("\n".
                   7439: 		  '<td><label><input type="radio" name="scantron_correct_Q_'.
                   7440: 		  $line.'" value="'.$i.'" />'.$alphabet[$i]."</label></td>");
                   7441:     }
1.503     raeburn  7442:     my $nobub_checked = ' ';
                   7443:     if ($error eq 'missingbubble') {
                   7444:         $nobub_checked = ' checked = "checked" ';
                   7445:     }
                   7446:     $r->print("\n".'<td><label><input type="radio" name="scantron_correct_Q_'.
                   7447: 	      $line.'" value="none"'.$nobub_checked.'/>'.&mt('No bubble').
                   7448:               '</label>'."\n".'<input type="hidden" name="scantron_questionnum_Q_'.
                   7449:               $line.'" value="'.$questionnum.'" /></td>');
                   7450:     $r->print(&Apache::loncommon::end_data_table_row().
                   7451:               &Apache::loncommon::end_data_table());
1.157     albertel 7452: }
                   7453: 
1.423     albertel 7454: =pod
                   7455: 
                   7456: =item num_matches
                   7457: 
1.424     albertel 7458:    Counts the number of characters that are the same between the two arguments.
                   7459: 
                   7460:  Arguments:
                   7461:    $orig - CODE from the scanline
                   7462:    $code - CODE to match against
                   7463: 
                   7464:  Returns:
                   7465:    $count - integer count of the number of same characters between the
                   7466:             two arguments
                   7467: 
1.423     albertel 7468: =cut
                   7469: 
1.194     albertel 7470: sub num_matches {
                   7471:     my ($orig,$code) = @_;
                   7472:     my @code=split(//,$code);
                   7473:     my @orig=split(//,$orig);
                   7474:     my $same=0;
                   7475:     for (my $i=0;$i<scalar(@code);$i++) {
                   7476: 	if ($code[$i] eq $orig[$i]) { $same++; }
                   7477:     }
                   7478:     return $same;
                   7479: }
                   7480: 
1.423     albertel 7481: =pod
                   7482: 
                   7483: =item scantron_get_closely_matching_CODEs
                   7484: 
1.424     albertel 7485:    Cycles through all CODEs and finds the set that has the greatest
                   7486:    number of same characters as the provided CODE
                   7487: 
                   7488:  Arguments:
                   7489:    $allcodes - hash ref returned by &get_codes()
                   7490:    $CODE     - CODE from the current scanline
                   7491: 
                   7492:  Returns:
                   7493:    2 element list
                   7494:     - first elements is number of how closely matching the best fit is 
                   7495:       (5 means best set has 5 matching characters)
                   7496:     - second element is an arrary ref containing the set of valid CODEs
                   7497:       that best fit the passed in CODE
                   7498: 
1.423     albertel 7499: =cut
                   7500: 
1.194     albertel 7501: sub scantron_get_closely_matching_CODEs {
                   7502:     my ($allcodes,$CODE)=@_;
                   7503:     my @CODEs;
                   7504:     foreach my $testcode (sort(keys(%{$allcodes}))) {
                   7505: 	push(@{$CODEs[&num_matches($CODE,$testcode)]},$testcode);
                   7506:     }
                   7507: 
                   7508:     return ($#CODEs,$CODEs[-1]);
                   7509: }
                   7510: 
1.423     albertel 7511: =pod
                   7512: 
                   7513: =item get_codes
                   7514: 
1.424     albertel 7515:    Builds a hash which has keys of all of the valid CODEs from the selected
                   7516:    set of remembered CODEs.
                   7517: 
                   7518:  Arguments:
                   7519:   $old_name - name of the set of remembered CODEs
                   7520:   $cdom     - domain of the course
                   7521:   $cnum     - internal course name
                   7522: 
                   7523:  Returns:
                   7524:   %allcodes - keys are the valid CODEs, values are all 1
                   7525: 
1.423     albertel 7526: =cut
                   7527: 
1.194     albertel 7528: sub get_codes {
1.280     foxr     7529:     my ($old_name, $cdom, $cnum) = @_;
                   7530:     if (!$old_name) {
                   7531: 	$old_name=$env{'form.scantron_CODElist'};
                   7532:     }
                   7533:     if (!$cdom) {
                   7534: 	$cdom =$env{'course.'.$env{'request.course.id'}.'.domain'};
                   7535:     }
                   7536:     if (!$cnum) {
                   7537: 	$cnum =$env{'course.'.$env{'request.course.id'}.'.num'};
                   7538:     }
1.278     albertel 7539:     my %result=&Apache::lonnet::get('CODEs',[$old_name,"type\0$old_name"],
                   7540: 				    $cdom,$cnum);
                   7541:     my %allcodes;
                   7542:     if ($result{"type\0$old_name"} eq 'number') {
                   7543: 	%allcodes=map {($_,1)} split(',',$result{$old_name});
                   7544:     } else {
                   7545: 	%allcodes=map {(&Apache::lonprintout::num_to_letters($_),1)} split(',',$result{$old_name});
                   7546:     }
1.194     albertel 7547:     return %allcodes;
                   7548: }
                   7549: 
1.423     albertel 7550: =pod
                   7551: 
                   7552: =item scantron_validate_CODE
                   7553: 
1.424     albertel 7554:    Validates all scanlines in the selected file to not have any
                   7555:    invalid or underspecified CODEs and that none of the codes are
                   7556:    duplicated if this was requested.
                   7557: 
1.423     albertel 7558: =cut
                   7559: 
1.157     albertel 7560: sub scantron_validate_CODE {
                   7561:     my ($r,$currentphase) = @_;
1.257     albertel 7562:     my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
1.186     albertel 7563:     if ($scantron_config{'CODElocation'} &&
                   7564: 	$scantron_config{'CODEstart'} &&
                   7565: 	$scantron_config{'CODElength'}) {
1.257     albertel 7566: 	if (!defined($env{'form.scantron_CODElist'})) {
1.186     albertel 7567: 	    &FIXME_blow_up()
                   7568: 	}
                   7569:     } else {
                   7570: 	return (0,$currentphase+1);
                   7571:     }
                   7572:     
                   7573:     my %usedCODEs;
                   7574: 
1.194     albertel 7575:     my %allcodes=&get_codes();
1.186     albertel 7576: 
1.582     raeburn  7577:     my $nav_error;
1.596.2.12.2.  (raeburn 7578:):     &scantron_get_maxbubble(\$nav_error,\%scantron_config); # parse needs the lines per response array.
1.582     raeburn  7579:     if ($nav_error) {
                   7580:         $r->print(&navmap_errormsg());
                   7581:         return(1,$currentphase);
                   7582:     }
1.447     foxr     7583: 
1.186     albertel 7584:     my ($scanlines,$scan_data)=&scantron_getfile();
                   7585:     for (my $i=0;$i<=$scanlines->{'count'};$i++) {
1.200     albertel 7586: 	my $line=&scantron_get_line($scanlines,$scan_data,$i);
1.186     albertel 7587: 	if ($line=~/^[\s\cz]*$/) { next; }
                   7588: 	my $scan_record=&scantron_parse_scanline($line,$i,\%scantron_config,
                   7589: 						 $scan_data);
                   7590: 	my $CODE=$$scan_record{'scantron.CODE'};
                   7591: 	my $error=0;
1.224     albertel 7592: 	if (!&Apache::lonnet::validCODE($CODE)) {
                   7593: 	    &scantron_get_correction($r,$i,$scan_record,
                   7594: 				     \%scantron_config,
                   7595: 				     $line,'incorrectCODE',\%allcodes);
                   7596: 	    return(1,$currentphase);
                   7597: 	}
1.221     albertel 7598: 	if (%allcodes && !exists($allcodes{$CODE}) 
                   7599: 	    && !$$scan_record{'scantron.useCODE'}) {
1.186     albertel 7600: 	    &scantron_get_correction($r,$i,$scan_record,
                   7601: 				     \%scantron_config,
1.194     albertel 7602: 				     $line,'incorrectCODE',\%allcodes);
                   7603: 	    return(1,$currentphase);
1.186     albertel 7604: 	}
1.214     albertel 7605: 	if (exists($usedCODEs{$CODE}) 
1.257     albertel 7606: 	    && $env{'form.scantron_CODEunique'} eq 'yes'
1.192     albertel 7607: 	    && !$$scan_record{'scantron.CODE_ignore_dup'}) {
1.186     albertel 7608: 	    &scantron_get_correction($r,$i,$scan_record,
                   7609: 				     \%scantron_config,
1.194     albertel 7610: 				     $line,'duplicateCODE',$usedCODEs{$CODE});
                   7611: 	    return(1,$currentphase);
1.186     albertel 7612: 	}
1.524     raeburn  7613: 	push(@{$usedCODEs{$CODE}},$$scan_record{'scantron.PaperID'});
1.186     albertel 7614:     }
1.157     albertel 7615:     return (0,$currentphase+1);
                   7616: }
                   7617: 
1.423     albertel 7618: =pod
                   7619: 
                   7620: =item scantron_validate_doublebubble
                   7621: 
1.424     albertel 7622:    Validates all scanlines in the selected file to not have any
                   7623:    bubble lines with multiple bubbles marked.
                   7624: 
1.423     albertel 7625: =cut
                   7626: 
1.157     albertel 7627: sub scantron_validate_doublebubble {
                   7628:     my ($r,$currentphase) = @_;
                   7629:     #get student info
                   7630:     my $classlist=&Apache::loncoursedata::get_classlist();
                   7631:     my %idmap=&username_to_idmap($classlist);
                   7632: 
                   7633:     #get scantron line setup
1.257     albertel 7634:     my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
1.157     albertel 7635:     my ($scanlines,$scan_data)=&scantron_getfile();
1.583     raeburn  7636:     my $nav_error;
1.596.2.12.2.  (raeburn 7637:):     &scantron_get_maxbubble(\$nav_error,\%scantron_config); # parse needs the bubble line array.
1.583     raeburn  7638:     if ($nav_error) {
                   7639:         $r->print(&navmap_errormsg());
                   7640:         return(1,$currentphase);
                   7641:     }
1.447     foxr     7642: 
1.157     albertel 7643:     for (my $i=0;$i<=$scanlines->{'count'};$i++) {
1.200     albertel 7644: 	my $line=&scantron_get_line($scanlines,$scan_data,$i);
1.157     albertel 7645: 	if ($line=~/^[\s\cz]*$/) { next; }
                   7646: 	my $scan_record=&scantron_parse_scanline($line,$i,\%scantron_config,
                   7647: 						 $scan_data);
                   7648: 	if (!defined($$scan_record{'scantron.doubleerror'})) { next; }
                   7649: 	&scantron_get_correction($r,$i,$scan_record,\%scantron_config,$line,
                   7650: 				 'doublebubble',
                   7651: 				 $$scan_record{'scantron.doubleerror'});
                   7652:     	return (1,$currentphase);
                   7653:     }
                   7654:     return (0,$currentphase+1);
                   7655: }
                   7656: 
1.423     albertel 7657: 
1.503     raeburn  7658: sub scantron_get_maxbubble {
1.596.2.12.2.  (raeburn 7659:):     my ($nav_error,$scantron_config) = @_;
1.257     albertel 7660:     if (defined($env{'form.scantron_maxbubble'}) &&
                   7661: 	$env{'form.scantron_maxbubble'}) {
1.447     foxr     7662: 	&restore_bubble_lines();
1.257     albertel 7663: 	return $env{'form.scantron_maxbubble'};
1.191     albertel 7664:     }
1.330     albertel 7665: 
1.447     foxr     7666:     my (undef, undef, $sequence) =
1.257     albertel 7667: 	&Apache::lonnet::decode_symb($env{'form.selectpage'});
1.330     albertel 7668: 
1.447     foxr     7669:     my $navmap=Apache::lonnavmaps::navmap->new();
1.582     raeburn  7670:     unless (ref($navmap)) {
                   7671:         if (ref($nav_error)) {
                   7672:             $$nav_error = 1;
                   7673:         }
1.591     raeburn  7674:         return;
1.582     raeburn  7675:     }
1.191     albertel 7676:     my $map=$navmap->getResourceByUrl($sequence);
                   7677:     my @resources=$navmap->retrieveResources($map,\&scantron_filter,1,0);
1.596.2.12.2.  (raeburn 7678:):     my $bubbles_per_row = &bubblesheet_bubbles_per_row($scantron_config);
1.330     albertel 7679: 
                   7680:     &Apache::lonxml::clear_problem_counter();
                   7681: 
1.557     raeburn  7682:     my $uname       = $env{'user.name'};
                   7683:     my $udom        = $env{'user.domain'};
1.435     foxr     7684:     my $cid         = $env{'request.course.id'};
                   7685:     my $total_lines = 0;
                   7686:     %bubble_lines_per_response = ();
1.447     foxr     7687:     %first_bubble_line         = ();
1.503     raeburn  7688:     %subdivided_bubble_lines   = ();
                   7689:     %responsetype_per_response = ();
1.554     raeburn  7690: 
1.447     foxr     7691:     my $response_number = 0;
                   7692:     my $bubble_line     = 0;
1.191     albertel 7693:     foreach my $resource (@resources) {
1.596.2.12.2.  (raeburn 7694:):         my ($analysis,$parts) = &scantron_partids_tograde($resource,$cid,$uname,
                   7695:):                                                           $udom,$bubbles_per_row);
1.542     raeburn  7696:         if ((ref($analysis) eq 'HASH') && (ref($parts) eq 'ARRAY')) {
                   7697: 	    foreach my $part_id (@{$parts}) {
                   7698:                 my $lines;
                   7699: 
                   7700: 	        # TODO - make this a persistent hash not an array.
                   7701: 
                   7702:                 # optionresponse, matchresponse and rankresponse type items 
                   7703:                 # render as separate sub-questions in exam mode.
                   7704:                 if (($analysis->{$part_id.'.type'} eq 'optionresponse') ||
                   7705:                     ($analysis->{$part_id.'.type'} eq 'matchresponse') ||
                   7706:                     ($analysis->{$part_id.'.type'} eq 'rankresponse')) {
                   7707:                     my ($numbub,$numshown);
                   7708:                     if ($analysis->{$part_id.'.type'} eq 'optionresponse') {
                   7709:                         if (ref($analysis->{$part_id.'.options'}) eq 'ARRAY') {
                   7710:                             $numbub = scalar(@{$analysis->{$part_id.'.options'}});
                   7711:                         }
                   7712:                     } elsif ($analysis->{$part_id.'.type'} eq 'matchresponse') {
                   7713:                         if (ref($analysis->{$part_id.'.items'}) eq 'ARRAY') {
                   7714:                             $numbub = scalar(@{$analysis->{$part_id.'.items'}});
                   7715:                         }
                   7716:                     } elsif ($analysis->{$part_id.'.type'} eq 'rankresponse') {
                   7717:                         if (ref($analysis->{$part_id.'.foils'}) eq 'ARRAY') {
                   7718:                             $numbub = scalar(@{$analysis->{$part_id.'.foils'}});
                   7719:                         }
                   7720:                     }
                   7721:                     if (ref($analysis->{$part_id.'.shown'}) eq 'ARRAY') {
                   7722:                         $numshown = scalar(@{$analysis->{$part_id.'.shown'}});
                   7723:                     }
1.596.2.12.2.  (raeburn 7724:):                     my $bubbles_per_row =
                   7725:):                         &bubblesheet_bubbles_per_row($scantron_config);
                   7726:):                     my $inner_bubble_lines = int($numbub/$bubbles_per_row);
                   7727:):                     if (($numbub % $bubbles_per_row) != 0) {
1.542     raeburn  7728:                         $inner_bubble_lines++;
                   7729:                     }
                   7730:                     for (my $i=0; $i<$numshown; $i++) {
                   7731:                         $subdivided_bubble_lines{$response_number} .= 
                   7732:                             $inner_bubble_lines.',';
                   7733:                     }
                   7734:                     $subdivided_bubble_lines{$response_number} =~ s/,$//;
                   7735:                     $lines = $numshown * $inner_bubble_lines;
                   7736:                 } else {
                   7737:                     $lines = $analysis->{"$part_id.bubble_lines"};
1.596.2.12.2.  (raeburn 7738:):                 }
1.542     raeburn  7739: 
                   7740:                 $first_bubble_line{$response_number} = $bubble_line;
                   7741: 	        $bubble_lines_per_response{$response_number} = $lines;
                   7742:                 $responsetype_per_response{$response_number} = 
                   7743:                     $analysis->{$part_id.'.type'};
                   7744: 	        $response_number++;
                   7745: 
                   7746: 	        $bubble_line +=  $lines;
                   7747: 	        $total_lines +=  $lines;
                   7748: 	    }
                   7749:         }
                   7750:     }
1.552     raeburn  7751:     &Apache::lonnet::delenv('scantron.');
1.542     raeburn  7752: 
                   7753:     &save_bubble_lines();
                   7754:     $env{'form.scantron_maxbubble'} =
                   7755: 	$total_lines;
                   7756:     return $env{'form.scantron_maxbubble'};
                   7757: }
1.523     raeburn  7758: 
1.596.2.12.2.  (raeburn 7759:): sub bubblesheet_bubbles_per_row {
                   7760:):     my ($scantron_config) = @_;
                   7761:):     my $bubbles_per_row;
                   7762:):     if (ref($scantron_config) eq 'HASH') {
                   7763:):         $bubbles_per_row = $scantron_config->{'BubblesPerRow'};
                   7764:):     }
                   7765:):     if ((!$bubbles_per_row) || ($bubbles_per_row < 1)) {
                   7766:):         $bubbles_per_row = 10;
                   7767:):     }
                   7768:):     return $bubbles_per_row;
                   7769:): }
                   7770:): 
1.157     albertel 7771: sub scantron_validate_missingbubbles {
                   7772:     my ($r,$currentphase) = @_;
                   7773:     #get student info
                   7774:     my $classlist=&Apache::loncoursedata::get_classlist();
                   7775:     my %idmap=&username_to_idmap($classlist);
                   7776: 
                   7777:     #get scantron line setup
1.257     albertel 7778:     my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
1.157     albertel 7779:     my ($scanlines,$scan_data)=&scantron_getfile();
1.582     raeburn  7780:     my $nav_error;
1.596.2.12.2.  (raeburn 7781:):     my $max_bubble=&scantron_get_maxbubble(\$nav_error,\%scantron_config);
1.582     raeburn  7782:     if ($nav_error) {
                   7783:         return(1,$currentphase);
                   7784:     }
1.157     albertel 7785:     if (!$max_bubble) { $max_bubble=2**31; }
                   7786:     for (my $i=0;$i<=$scanlines->{'count'};$i++) {
1.200     albertel 7787: 	my $line=&scantron_get_line($scanlines,$scan_data,$i);
1.157     albertel 7788: 	if ($line=~/^[\s\cz]*$/) { next; }
                   7789: 	my $scan_record=&scantron_parse_scanline($line,$i,\%scantron_config,
                   7790: 						 $scan_data);
                   7791: 	if (!defined($$scan_record{'scantron.missingerror'})) { next; }
                   7792: 	my @to_correct;
1.470     foxr     7793: 	
                   7794: 	# Probably here's where the error is...
                   7795: 
1.157     albertel 7796: 	foreach my $missing (@{$$scan_record{'scantron.missingerror'}}) {
1.505     raeburn  7797:             my $lastbubble;
                   7798:             if ($missing =~ /^(\d+)\.(\d+)$/) {
                   7799:                my $question = $1;
                   7800:                my $subquestion = $2;
                   7801:                if (!defined($first_bubble_line{$question -1})) { next; }
                   7802:                my $first = $first_bubble_line{$question-1};
                   7803:                my @subans = split(/,/,$subdivided_bubble_lines{$question-1});
                   7804:                my $subcount = 1;
                   7805:                while ($subcount<$subquestion) {
                   7806:                    $first += $subans[$subcount-1];
                   7807:                    $subcount ++;
                   7808:                }
                   7809:                my $count = $subans[$subquestion-1];
                   7810:                $lastbubble = $first + $count;
                   7811:             } else {
                   7812:                 if (!defined($first_bubble_line{$missing - 1})) { next; }
                   7813:                 $lastbubble = $first_bubble_line{$missing - 1} + $bubble_lines_per_response{$missing - 1};
                   7814:             }
                   7815:             if ($lastbubble > $max_bubble) { next; }
1.157     albertel 7816: 	    push(@to_correct,$missing);
                   7817: 	}
                   7818: 	if (@to_correct) {
                   7819: 	    &scantron_get_correction($r,$i,$scan_record,\%scantron_config,
                   7820: 				     $line,'missingbubble',\@to_correct);
                   7821: 	    return (1,$currentphase);
                   7822: 	}
                   7823: 
                   7824:     }
                   7825:     return (0,$currentphase+1);
                   7826: }
                   7827: 
1.596.2.12.2.  (raeburn 7828:): sub hand_bubble_option {
                   7829:):     my (undef, undef, $sequence) =
                   7830:):         &Apache::lonnet::decode_symb($env{'form.selectpage'});
                   7831:):     return if ($sequence eq '');
                   7832:):     my $navmap = Apache::lonnavmaps::navmap->new();
                   7833:):     unless (ref($navmap)) {
                   7834:):         return;
                   7835:):     }
                   7836:):     my $needs_hand_bubbles;
                   7837:):     my $map=$navmap->getResourceByUrl($sequence);
                   7838:):     my @resources=$navmap->retrieveResources($map,\&scantron_filter,1,0);
                   7839:):     foreach my $res (@resources) {
                   7840:):         if (ref($res)) {
                   7841:):             if ($res->is_problem()) {
                   7842:):                 my $partlist = $res->parts();
                   7843:):                 foreach my $part (@{ $partlist }) {
                   7844:):                     my @types = $res->responseType($part);
                   7845:):                     if (grep(/^(chem|essay|image|formula|math|string|functionplot)$/,@types)) {
                   7846:):                         $needs_hand_bubbles = 1;
                   7847:):                         last;
                   7848:):                     }
                   7849:):                 }
                   7850:):             }
                   7851:):         }
                   7852:):     }
                   7853:):     if ($needs_hand_bubbles) {
                   7854:):         my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
                   7855:):         my $bubbles_per_row = &bubblesheet_bubbles_per_row(\%scantron_config);
                   7856:):         return &mt('The sequence to be graded contains response types which are handgraded.').'<p>'.
                   7857:):                &mt('If you have already graded these by bubbling sheets to indicate points awarded, [_1]what point value is assigned to a filled last bubble in each row?','<br />').
                   7858:):                '<label><input type="radio" name="scantron_lastbubblepoints" value="'.$bubbles_per_row.'" checked="checked" />'.&mt('[quant,_1,point]',$bubbles_per_row).'</label>&nbsp;'.&mt('or').'&nbsp;'.
                   7859:):                '<label><input type="radio" name="scantron_lastbubblepoints" value="0"/>0 points</label></p>';
                   7860:):     }
                   7861:):     return;
                   7862:): }
1.423     albertel 7863: 
1.82      albertel 7864: sub scantron_process_students {
1.75      albertel 7865:     my ($r) = @_;
1.513     foxr     7866: 
1.257     albertel 7867:     my (undef,undef,$sequence)=&Apache::lonnet::decode_symb($env{'form.selectpage'});
1.324     albertel 7868:     my ($symb)=&get_symb($r);
1.513     foxr     7869:     if (!$symb) {
                   7870: 	return '';
                   7871:     }
1.324     albertel 7872:     my $default_form_data=&defaultFormData($symb);
1.82      albertel 7873: 
1.257     albertel 7874:     my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
1.157     albertel 7875:     my ($scanlines,$scan_data)=&scantron_getfile();
1.82      albertel 7876:     my $classlist=&Apache::loncoursedata::get_classlist();
                   7877:     my %idmap=&username_to_idmap($classlist);
1.132     bowersj2 7878:     my $navmap=Apache::lonnavmaps::navmap->new();
1.582     raeburn  7879:     unless (ref($navmap)) {
                   7880:         $r->print(&navmap_errormsg());
                   7881:         return '';
                   7882:     }  
1.83      albertel 7883:     my $map=$navmap->getResourceByUrl($sequence);
                   7884:     my @resources=$navmap->retrieveResources($map,\&scantron_filter,1,0);
1.557     raeburn  7885:     my (%grader_partids_by_symb,%grader_randomlists_by_symb);
                   7886:     &graders_resources_pass(\@resources,\%grader_partids_by_symb,
                   7887:                             \%grader_randomlists_by_symb);
1.586     raeburn  7888:     my $resource_error;
1.557     raeburn  7889:     foreach my $resource (@resources) {
1.586     raeburn  7890:         my $ressymb;
                   7891:         if (ref($resource)) {
                   7892:             $ressymb = $resource->symb();
                   7893:         } else {
                   7894:             $resource_error = 1;
                   7895:             last;
                   7896:         }
1.557     raeburn  7897:         my ($analysis,$parts) =
                   7898:             &scantron_partids_tograde($resource,$env{'request.course.id'},
1.596.2.12.2.  (raeburn 7899:):                                       $env{'user.name'},$env{'user.domain'},
                   7900:):                                       1,$bubbles_per_row);
1.557     raeburn  7901:         $grader_partids_by_symb{$ressymb} = $parts;
                   7902:         if (ref($analysis) eq 'HASH') {
                   7903:             if (ref($analysis->{'parts_withrandomlist'}) eq 'ARRAY') {
                   7904:                 $grader_randomlists_by_symb{$ressymb} = 
                   7905:                     $analysis->{'parts_withrandomlist'};
                   7906:             }
                   7907:         }
                   7908:     }
1.586     raeburn  7909:     if ($resource_error) {
                   7910:         $r->print(&navmap_errormsg());
                   7911:         return '';
                   7912:     }
1.557     raeburn  7913: 
1.554     raeburn  7914:     my ($uname,$udom);
1.82      albertel 7915:     my $result= <<SCANTRONFORM;
1.81      albertel 7916: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="scantronupload">
                   7917:   <input type="hidden" name="command" value="scantron_configphase" />
                   7918:   $default_form_data
                   7919: SCANTRONFORM
1.82      albertel 7920:     $r->print($result);
                   7921: 
                   7922:     my @delayqueue;
1.542     raeburn  7923:     my (%completedstudents,%scandata);
1.140     albertel 7924:     
1.520     www      7925:     my $lock=&Apache::lonnet::set_lock(&mt('Grading bubblesheet exam'));
1.200     albertel 7926:     my $count=&get_todo_count($scanlines,$scan_data);
1.575     www      7927:     my %prog_state=&Apache::lonhtmlcommon::Create_PrgWin($r,'Bubblesheet Status',
                   7928:  				    'Bubblesheet Progress',$count,
1.195     albertel 7929: 				    'inline',undef,'scantronupload');
1.140     albertel 7930:     &Apache::lonhtmlcommon::Update_PrgWin($r,\%prog_state,
                   7931: 					  'Processing first student');
1.542     raeburn  7932:     $r->print('<br />');
1.140     albertel 7933:     my $start=&Time::HiRes::time();
1.158     albertel 7934:     my $i=-1;
1.542     raeburn  7935:     my $started;
1.447     foxr     7936: 
1.582     raeburn  7937:     my $nav_error;
1.596.2.12.2.  (raeburn 7938:):     &scantron_get_maxbubble(\$nav_error,\%scantron_config); # Need the bubble lines array to parse.
1.582     raeburn  7939:     if ($nav_error) {
                   7940:         $r->print(&navmap_errormsg());
                   7941:         return '';
                   7942:     }
                   7943: 
1.513     foxr     7944:     # If an ssi failed in scantron_get_maxbubble, put an error message out to
                   7945:     # the user and return.
                   7946: 
                   7947:     if ($ssi_error) {
                   7948: 	$r->print("</form>");
                   7949: 	&ssi_print_error($r);
                   7950: 	$r->print(&show_grading_menu_form($symb));
1.520     www      7951:         &Apache::lonnet::remove_lock($lock);
1.513     foxr     7952: 	return '';		# Dunno why the other returns return '' rather than just returning.
                   7953:     }
1.447     foxr     7954: 
1.542     raeburn  7955:     my %lettdig = &letter_to_digits();
                   7956:     my $numletts = scalar(keys(%lettdig));
                   7957: 
1.157     albertel 7958:     while ($i<$scanlines->{'count'}) {
                   7959:  	($uname,$udom)=('','');
                   7960:  	$i++;
1.200     albertel 7961:  	my $line=&scantron_get_line($scanlines,$scan_data,$i);
1.157     albertel 7962:  	if ($line=~/^[\s\cz]*$/) { next; }
1.200     albertel 7963: 	if ($started) {
                   7964: 	    &Apache::lonhtmlcommon::Increment_PrgWin($r,\%prog_state,
                   7965: 						     'last student');
                   7966: 	}
                   7967: 	$started=1;
1.157     albertel 7968:  	my $scan_record=&scantron_parse_scanline($line,$i,\%scantron_config,
                   7969:  						 $scan_data);
                   7970:  	unless ($uname=&scantron_find_student($scan_record,$scan_data,
                   7971:  					      \%idmap,$i)) {
                   7972:   	    &scantron_add_delay(\@delayqueue,$line,
                   7973:  				'Unable to find a student that matches',1);
                   7974:  	    next;
                   7975:   	}
                   7976:  	if (exists $completedstudents{$uname}) {
                   7977:  	    &scantron_add_delay(\@delayqueue,$line,
                   7978:  				'Student '.$uname.' has multiple sheets',2);
                   7979:  	    next;
                   7980:  	}
                   7981:   	($uname,$udom)=split(/:/,$uname);
1.330     albertel 7982: 
1.586     raeburn  7983:         my (%partids_by_symb,$res_error);
1.554     raeburn  7984:         foreach my $resource (@resources) {
1.586     raeburn  7985:             my $ressymb;
                   7986:             if (ref($resource)) {
                   7987:                 $ressymb = $resource->symb();
                   7988:             } else {
                   7989:                 $res_error = 1;
                   7990:                 last;
                   7991:             }
1.557     raeburn  7992:             if ((exists($grader_randomlists_by_symb{$ressymb})) ||
                   7993:                 (ref($grader_partids_by_symb{$ressymb}) ne 'ARRAY')) {
                   7994:                 my ($analysis,$parts) =
1.596.2.12.2.  (raeburn 7995:):                     &scantron_partids_tograde($resource,$env{'request.course.id'},
                   7996:):                                               $uname,$udom,undef,$bubbles_per_row);
1.557     raeburn  7997:                 $partids_by_symb{$ressymb} = $parts;
                   7998:             } else {
                   7999:                 $partids_by_symb{$ressymb} = $grader_partids_by_symb{$ressymb};
                   8000:             }
1.554     raeburn  8001:         }
                   8002: 
1.586     raeburn  8003:         if ($res_error) {
                   8004:             &scantron_add_delay(\@delayqueue,$line,
                   8005:                                 'An error occurred while grading student '.$uname,2);
                   8006:             next;
                   8007:         }
                   8008: 
1.330     albertel 8009: 	&Apache::lonxml::clear_problem_counter();
1.514     raeburn  8010:   	&Apache::lonnet::appenv($scan_record);
1.376     albertel 8011: 
                   8012: 	if (&scantron_clear_skip($scanlines,$scan_data,$i)) {
                   8013: 	    &scantron_putfile($scanlines,$scan_data);
                   8014: 	}
1.161     albertel 8015: 	
1.542     raeburn  8016:         my $scancode;
                   8017:         if ((exists($scan_record->{'scantron.CODE'})) &&
                   8018:             (&Apache::lonnet::validCODE($scan_record->{'scantron.CODE'}))) {
                   8019:             $scancode = $scan_record->{'scantron.CODE'};
                   8020:         } else {
                   8021:             $scancode = '';
                   8022:         }
                   8023: 
                   8024:         if (&grade_student_bubbles($r,$uname,$udom,$scan_record,$scancode,
1.596.2.12.2.  (raeburn 8025:):                                    \@resources,\%partids_by_symb,
                   8026:):                                    $bubbles_per_row) eq 'ssi_error') {
1.542     raeburn  8027:             $ssi_error = 0; # So end of handler error message does not trigger.
                   8028:             $r->print("</form>");
                   8029:             &ssi_print_error($r);
                   8030:             $r->print(&show_grading_menu_form($symb));
                   8031:             &Apache::lonnet::remove_lock($lock);
                   8032:             return '';      # Why return ''?  Beats me.
                   8033:         }
1.513     foxr     8034: 
1.140     albertel 8035: 	$completedstudents{$uname}={'line'=>$line};
1.542     raeburn  8036:         if ($env{'form.verifyrecord'}) {
                   8037:             my $lastpos = $env{'form.scantron_maxbubble'}*$scantron_config{'Qlength'};
                   8038:             my $studentdata = substr($line,$scantron_config{'Qstart'}-1,$lastpos);
                   8039:             chomp($studentdata);
                   8040:             $studentdata =~ s/\r$//;
                   8041:             my $studentrecord = '';
                   8042:             my $counter = -1;
                   8043:             foreach my $resource (@resources) {
1.554     raeburn  8044:                 my $ressymb = $resource->symb();
1.542     raeburn  8045:                 ($counter,my $recording) =
                   8046:                     &verify_scantron_grading($resource,$udom,$uname,$env{'request.course.id'},
1.554     raeburn  8047:                                              $counter,$studentdata,$partids_by_symb{$ressymb},
1.542     raeburn  8048:                                              \%scantron_config,\%lettdig,$numletts);
                   8049:                 $studentrecord .= $recording;
                   8050:             }
                   8051:             if ($studentrecord ne $studentdata) {
1.554     raeburn  8052:                 &Apache::lonxml::clear_problem_counter();
                   8053:                 if (&grade_student_bubbles($r,$uname,$udom,$scan_record,$scancode,
1.596.2.12.2.  (raeburn 8054:):                                            \@resources,\%partids_by_symb,
                   8055:):                                            $bubbles_per_row) eq 'ssi_error') {
1.554     raeburn  8056:                     $ssi_error = 0; # So end of handler error message does not trigger.
                   8057:                     $r->print("</form>");
                   8058:                     &ssi_print_error($r);
                   8059:                     $r->print(&show_grading_menu_form($symb));
                   8060:                     &Apache::lonnet::remove_lock($lock);
                   8061:                     delete($completedstudents{$uname});
                   8062:                     return '';
                   8063:                 }
1.542     raeburn  8064:                 $counter = -1;
                   8065:                 $studentrecord = '';
                   8066:                 foreach my $resource (@resources) {
1.554     raeburn  8067:                     my $ressymb = $resource->symb();
1.542     raeburn  8068:                     ($counter,my $recording) =
                   8069:                         &verify_scantron_grading($resource,$udom,$uname,$env{'request.course.id'},
1.554     raeburn  8070:                                                  $counter,$studentdata,$partids_by_symb{$ressymb},
1.542     raeburn  8071:                                                  \%scantron_config,\%lettdig,$numletts);
                   8072:                     $studentrecord .= $recording;
                   8073:                 }
                   8074:                 if ($studentrecord ne $studentdata) {
1.596.2.6  raeburn  8075:                     $r->print('<p><span class="LC_warning">');
1.542     raeburn  8076:                     if ($scancode eq '') {
1.596.2.6  raeburn  8077:                         $r->print(&mt('Mismatch grading bubblesheet for user: [_1] with ID: [_2].',
1.542     raeburn  8078:                                   $uname.':'.$udom,$scan_record->{'scantron.ID'}));
                   8079:                     } else {
1.596.2.6  raeburn  8080:                         $r->print(&mt('Mismatch grading bubblesheet for user: [_1] with ID: [_2] and CODE: [_3].',
1.542     raeburn  8081:                                   $uname.':'.$udom,$scan_record->{'scantron.ID'},$scancode));
                   8082:                     }
                   8083:                     $r->print('</span><br />'.&Apache::loncommon::start_data_table()."\n".
                   8084:                               &Apache::loncommon::start_data_table_header_row()."\n".
                   8085:                               '<th>'.&mt('Source').'</th><th>'.&mt('Bubbled responses').'</th>'.
                   8086:                               &Apache::loncommon::end_data_table_header_row()."\n".
                   8087:                               &Apache::loncommon::start_data_table_row().
1.596.2.6  raeburn  8088:                               '<td>'.&mt('Bubblesheet').'</td>'.
1.542     raeburn  8089:                               '<td><span class="LC_nobreak">'.$studentdata.'</span></td>'.
                   8090:                               &Apache::loncommon::end_data_table_row().
                   8091:                               &Apache::loncommon::start_data_table_row().
1.596.2.6  raeburn  8092:                               '<td>'.&mt('Stored submissions').'</td>'.
1.542     raeburn  8093:                               '<td><span class="LC_nobreak">'.$studentrecord.'</span></td>'."\n".
                   8094:                               &Apache::loncommon::end_data_table_row().
                   8095:                               &Apache::loncommon::end_data_table().'</p>');
                   8096:                 } else {
                   8097:                     $r->print('<br /><span class="LC_warning">'.
                   8098:                              &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 />'.
                   8099:                              &mt("As a consequence, this user's submission history records two tries.").
                   8100:                                  '</span><br />');
                   8101:                 }
                   8102:             }
                   8103:         }
1.543     raeburn  8104:         if (&Apache::loncommon::connection_aborted($r)) { last; }
1.140     albertel 8105:     } continue {
1.330     albertel 8106: 	&Apache::lonxml::clear_problem_counter();
1.552     raeburn  8107: 	&Apache::lonnet::delenv('scantron.');
1.82      albertel 8108:     }
1.140     albertel 8109:     &Apache::lonhtmlcommon::Close_PrgWin($r,\%prog_state);
1.520     www      8110:     &Apache::lonnet::remove_lock($lock);
1.172     albertel 8111: #    my $lasttime = &Time::HiRes::time()-$start;
                   8112: #    $r->print("<p>took $lasttime</p>");
1.140     albertel 8113: 
1.200     albertel 8114:     $r->print("</form>");
1.324     albertel 8115:     $r->print(&show_grading_menu_form($symb));
1.157     albertel 8116:     return '';
1.75      albertel 8117: }
1.157     albertel 8118: 
1.557     raeburn  8119: sub graders_resources_pass {
                   8120:     my ($resources,$grader_partids_by_symb,$grader_randomlists_by_symb) = @_;
                   8121:     if ((ref($resources) eq 'ARRAY') && (ref($grader_partids_by_symb)) && 
                   8122:         (ref($grader_randomlists_by_symb) eq 'HASH')) {
                   8123:         foreach my $resource (@{$resources}) {
                   8124:             my $ressymb = $resource->symb();
                   8125:             my ($analysis,$parts) =
                   8126:                 &scantron_partids_tograde($resource,$env{'request.course.id'},
1.596.2.12.2.  (raeburn 8127:):                                           $env{'user.name'},$env{'user.domain'},
                   8128:):                                           1,$bubbles_per_row);
1.557     raeburn  8129:             $grader_partids_by_symb->{$ressymb} = $parts;
                   8130:             if (ref($analysis) eq 'HASH') {
                   8131:                 if (ref($analysis->{'parts_withrandomlist'}) eq 'ARRAY') {
                   8132:                     $grader_randomlists_by_symb->{$ressymb} =
                   8133:                         $analysis->{'parts_withrandomlist'};
                   8134:                 }
                   8135:             }
                   8136:         }
                   8137:     }
                   8138:     return;
                   8139: }
                   8140: 
1.542     raeburn  8141: sub grade_student_bubbles {
1.596.2.12.2.  (raeburn 8142:):     my ($r,$uname,$udom,$scan_record,$scancode,$resources,$parts,$bubbles_per_row) = @_;
1.554     raeburn  8143:     if (ref($resources) eq 'ARRAY') {
                   8144:         my $count = 0;
                   8145:         foreach my $resource (@{$resources}) {
                   8146:             my $ressymb = $resource->symb();
                   8147:             my %form = ('submitted'      => 'scantron',
                   8148:                         'grade_target'   => 'grade',
                   8149:                         'grade_username' => $uname,
                   8150:                         'grade_domain'   => $udom,
                   8151:                         'grade_courseid' => $env{'request.course.id'},
                   8152:                         'grade_symb'     => $ressymb,
                   8153:                         'CODE'           => $scancode
                   8154:                        );
1.596.2.12.2.  (raeburn 8155:):             if ($bubbles_per_row ne '') {
                   8156:):                 $form{'bubbles_per_row'} = $bubbles_per_row;
                   8157:):             }
                   8158:):             if ($env{'form.scantron_lastbubblepoints'} ne '') {
                   8159:):                 $form{'scantron_lastbubblepoints'} = $env{'form.scantron_lastbubblepoints'};
                   8160:):             }
1.554     raeburn  8161:             if (ref($parts) eq 'HASH') {
                   8162:                 if (ref($parts->{$ressymb}) eq 'ARRAY') {
                   8163:                     foreach my $part (@{$parts->{$ressymb}}) {
                   8164:                         $form{'scantron_questnum_start.'.$part} =
                   8165:                             1+$env{'form.scantron.first_bubble_line.'.$count};
                   8166:                         $count++;
                   8167:                     }
                   8168:                 }
                   8169:             }
                   8170:             my $result=&ssi_with_retries($resource->src(),$ssi_retries,%form);
                   8171:             return 'ssi_error' if ($ssi_error);
                   8172:             last if (&Apache::loncommon::connection_aborted($r));
                   8173:         }
1.542     raeburn  8174:     }
                   8175:     return;
                   8176: }
                   8177: 
1.157     albertel 8178: sub scantron_upload_scantron_data {
                   8179:     my ($r)=@_;
1.565     raeburn  8180:     my $dom = $env{'request.role.domain'};
                   8181:     my $domdesc = &Apache::lonnet::domain($dom,'description');
                   8182:     $r->print(&Apache::loncommon::coursebrowser_javascript($dom));
1.157     albertel 8183:     my $select_link=&Apache::loncommon::selectcourse_link('rules','courseid',
1.181     albertel 8184: 							  'domainid',
1.565     raeburn  8185: 							  'coursename',$dom);
                   8186:     my $syllabuslink = '<a href="javascript:ToSyllabus();">'.&mt('Syllabus').'</a>'.
                   8187:                        ('&nbsp'x2).&mt('(shows course personnel)'); 
1.324     albertel 8188:     my $default_form_data=&defaultFormData(&get_symb($r,1));
1.579     raeburn  8189:     my $nofile_alert = &mt('Please use the browse button to select a file from your local directory.');
                   8190:     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 8191:     $r->print('
1.157     albertel 8192: <script type="text/javascript" language="javascript">
                   8193:     function checkUpload(formname) {
                   8194: 	if (formname.upfile.value == "") {
1.579     raeburn  8195: 	    alert("'.$nofile_alert.'");
1.157     albertel 8196: 	    return false;
                   8197: 	}
1.565     raeburn  8198:         if (formname.courseid.value == "") {
1.579     raeburn  8199:             alert("'.$nocourseid_alert.'");
1.565     raeburn  8200:             return false;
                   8201:         }
1.157     albertel 8202: 	formname.submit();
                   8203:     }
1.565     raeburn  8204: 
                   8205:     function ToSyllabus() {
                   8206:         var cdom = '."'$dom'".';
                   8207:         var cnum = document.rules.courseid.value;
                   8208:         if (cdom == "" || cdom == null) {
                   8209:             return;
                   8210:         }
                   8211:         if (cnum == "" || cnum == null) {
                   8212:            return;
                   8213:         }
                   8214:         syllwin=window.open("/public/"+cdom+"/"+cnum+"/syllabus","LONCAPASyllabus",
                   8215:                             "height=350,width=350,scrollbars=yes,menubar=no");
                   8216:         return;
                   8217:     }
                   8218: 
1.157     albertel 8219: </script>
                   8220: 
1.596.2.4  raeburn  8221: <h3>'.&mt('Send bubblesheet data to a course').'</h3>
1.566     raeburn  8222: 
1.492     albertel 8223: <form enctype="multipart/form-data" action="/adm/grades" name="rules" method="post">
1.565     raeburn  8224: '.$default_form_data.
                   8225:   &Apache::lonhtmlcommon::start_pick_box().
                   8226:   &Apache::lonhtmlcommon::row_title(&mt('Course ID')).
                   8227:   '<input name="courseid" type="text" size="30" />'.$select_link.
                   8228:   &Apache::lonhtmlcommon::row_closure().
                   8229:   &Apache::lonhtmlcommon::row_title(&mt('Course Name')).
                   8230:   '<input name="coursename" type="text" size="30" />'.$syllabuslink.
                   8231:   &Apache::lonhtmlcommon::row_closure().
                   8232:   &Apache::lonhtmlcommon::row_title(&mt('Domain')).
                   8233:   '<input name="domainid" type="hidden" />'.$domdesc.
                   8234:   &Apache::lonhtmlcommon::row_closure().
                   8235:   &Apache::lonhtmlcommon::row_title(&mt('File to upload')).
                   8236:   '<input type="file" name="upfile" size="50" />'.
                   8237:   &Apache::lonhtmlcommon::row_closure(1).
                   8238:   &Apache::lonhtmlcommon::end_pick_box().'<br />
                   8239: 
1.492     albertel 8240: <input name="command" value="scantronupload_save" type="hidden" />
1.589     bisitz   8241: <input type="button" onclick="javascript:checkUpload(this.form);" value="'.&mt('Upload Bubblesheet Data').'" />
1.157     albertel 8242: </form>
1.492     albertel 8243: ');
1.157     albertel 8244:     return '';
                   8245: }
                   8246: 
1.423     albertel 8247: 
1.157     albertel 8248: sub scantron_upload_scantron_data_save {
                   8249:     my($r)=@_;
1.324     albertel 8250:     my ($symb)=&get_symb($r,1);
1.182     albertel 8251:     my $doanotherupload=
                   8252: 	'<br /><form action="/adm/grades" method="post">'."\n".
                   8253: 	'<input type="hidden" name="command" value="scantronupload" />'."\n".
1.492     albertel 8254: 	'<input type="submit" name="submit" value="'.&mt('Do Another Upload').'" />'."\n".
1.182     albertel 8255: 	'</form>'."\n";
1.257     albertel 8256:     if (!&Apache::lonnet::allowed('usc',$env{'form.domainid'}) &&
1.162     albertel 8257: 	!&Apache::lonnet::allowed('usc',
1.257     albertel 8258: 			    $env{'form.domainid'}.'_'.$env{'form.courseid'})) {
1.575     www      8259: 	$r->print(&mt("You are not allowed to upload bubblesheet data to the requested course.")."<br />");
1.182     albertel 8260: 	if ($symb) {
1.324     albertel 8261: 	    $r->print(&show_grading_menu_form($symb));
1.182     albertel 8262: 	} else {
                   8263: 	    $r->print($doanotherupload);
                   8264: 	}
1.162     albertel 8265: 	return '';
                   8266:     }
1.257     albertel 8267:     my %coursedata=&Apache::lonnet::coursedescription($env{'form.domainid'}.'_'.$env{'form.courseid'});
1.568     raeburn  8268:     my $uploadedfile;
1.567     raeburn  8269:     $r->print('<h3>'.&mt("Uploading file to [_1]",$coursedata{'description'}).'</h3>');
1.257     albertel 8270:     if (length($env{'form.upfile'}) < 2) {
1.568     raeburn  8271:         $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 8272:     } else {
1.568     raeburn  8273:         my $result = 
                   8274:             &Apache::lonnet::userfileupload('upfile','','scantron','','','',
                   8275:                                             $env{'form.courseid'},$env{'form.domainid'});
                   8276: 	if ($result =~ m{^/uploaded/}) {
1.567     raeburn  8277: 	    $r->print(&mt('[_1]Success:[_2] Successfully uploaded [_3] bytes of data into location: [_4]',
                   8278:                           '<span class="LC_success">','</span>',(length($env{'form.upfile'})-1),
                   8279: 			  '<span class="LC_filename">'.$result.'</span>'));
1.568     raeburn  8280:             ($uploadedfile) = ($result =~ m{/([^/]+)$});
1.567     raeburn  8281:             $r->print(&validate_uploaded_scantron_file($env{'form.domainid'},
1.568     raeburn  8282:                                                        $env{'form.courseid'},$uploadedfile));
1.210     albertel 8283: 	} else {
1.567     raeburn  8284: 	    $r->print(&mt('[_1]Error:[_2] An error ([_3]) occurred when attempting to upload the file, [_4]',
                   8285:                           '<span class="LC_error">','</span>',$result,
1.568     raeburn  8286: 			  '<span class="LC_filename">'.&HTML::Entities::encode($env{'form.upfile.filename'},'<>&"').'</span>'));
1.183     albertel 8287: 	}
                   8288:     }
1.174     albertel 8289:     if ($symb) {
1.209     ng       8290: 	$r->print(&scantron_selectphase($r,$uploadedfile));
1.174     albertel 8291:     } else {
1.182     albertel 8292: 	$r->print($doanotherupload);
1.174     albertel 8293:     }
1.157     albertel 8294:     return '';
                   8295: }
                   8296: 
1.567     raeburn  8297: sub validate_uploaded_scantron_file {
                   8298:     my ($cdom,$cname,$fname) = @_;
                   8299:     my $scanlines=&Apache::lonnet::getfile('/uploaded/'.$cdom.'/'.$cname.'/'.$fname);
                   8300:     my @lines;
                   8301:     if ($scanlines ne '-1') {
                   8302:         @lines=split("\n",$scanlines,-1);
                   8303:     }
                   8304:     my $output;
                   8305:     if (@lines) {
                   8306:         my (%counts,$max_match_format);
                   8307:         my ($max_match_count,$max_match_pct) = (0,0);
                   8308:         my $classlist = &Apache::loncoursedata::get_classlist($cdom,$cname);
                   8309:         my %idmap = &username_to_idmap($classlist);
                   8310:         foreach my $key (keys(%idmap)) {
                   8311:             my $lckey = lc($key);
                   8312:             $idmap{$lckey} = $idmap{$key};
                   8313:         }
                   8314:         my %unique_formats;
                   8315:         my @formatlines = &get_scantronformat_file();
                   8316:         foreach my $line (@formatlines) {
                   8317:             chomp($line);
                   8318:             my @config = split(/:/,$line);
                   8319:             my $idstart = $config[5];
                   8320:             my $idlength = $config[6];
                   8321:             if (($idstart ne '') && ($idlength > 0)) {
                   8322:                 if (ref($unique_formats{$idstart.':'.$idlength}) eq 'ARRAY') {
                   8323:                     push(@{$unique_formats{$idstart.':'.$idlength}},$config[0].':'.$config[1]); 
                   8324:                 } else {
                   8325:                     $unique_formats{$idstart.':'.$idlength} = [$config[0].':'.$config[1]];
                   8326:                 }
                   8327:             }
                   8328:         }
                   8329:         foreach my $key (keys(%unique_formats)) {
                   8330:             my ($idstart,$idlength) = split(':',$key);
                   8331:             %{$counts{$key}} = (
                   8332:                                'found'   => 0,
                   8333:                                'total'   => 0,
                   8334:                               );
                   8335:             foreach my $line (@lines) {
                   8336:                 next if ($line =~ /^#/);
                   8337:                 next if ($line =~ /^[\s\cz]*$/);
                   8338:                 my $id = substr($line,$idstart-1,$idlength);
                   8339:                 $id = lc($id);
                   8340:                 if (exists($idmap{$id})) {
                   8341:                     $counts{$key}{'found'} ++;
                   8342:                 }
                   8343:                 $counts{$key}{'total'} ++;
                   8344:             }
                   8345:             if ($counts{$key}{'total'}) {
                   8346:                 my $percent_match = (100*$counts{$key}{'found'})/($counts{$key}{'total'});
                   8347:                 if (($max_match_format eq '') || ($percent_match > $max_match_pct)) {
                   8348:                     $max_match_pct = $percent_match;
                   8349:                     $max_match_format = $key;
                   8350:                     $max_match_count = $counts{$key}{'total'};
                   8351:                 }
                   8352:             }
                   8353:         }
                   8354:         if (ref($unique_formats{$max_match_format}) eq 'ARRAY') {
                   8355:             my $format_descs;
                   8356:             my $numwithformat = @{$unique_formats{$max_match_format}};
                   8357:             for (my $i=0; $i<$numwithformat; $i++) {
                   8358:                 my ($name,$desc) = split(':',$unique_formats{$max_match_format}[$i]);
                   8359:                 if ($i<$numwithformat-2) {
                   8360:                     $format_descs .= '"<i>'.$desc.'</i>", ';
                   8361:                 } elsif ($i==$numwithformat-2) {
                   8362:                     $format_descs .= '"<i>'.$desc.'</i>" '.&mt('and').' ';
                   8363:                 } elsif ($i==$numwithformat-1) {
                   8364:                     $format_descs .= '"<i>'.$desc.'</i>"';
                   8365:                 }
                   8366:             }
                   8367:             my $showpct = sprintf("%.0f",$max_match_pct).'%';
                   8368:             $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).
                   8369:                        '<br />'.&mt('A low percentage of matches results from one of the following:').'<ul>'.
                   8370:                        '<li>'.&mt('The file was uploaded to the wrong course').'</li>'.
                   8371:                        '<li>'.&mt('The data are not in the format expected for the domain: [_1]',
                   8372:                                   '<i>'.$cdom.'</i>').'</li>'.
                   8373:                        '<li>'.&mt('Students did not bubble their IDs, or mis-bubbled them').'</li>'.
                   8374:                        '<li>'.&mt('The course roster is not up to date').'</li>'.
                   8375:                        '</ul>';
                   8376:         }
                   8377:     } else {
                   8378:         $output = '<span class="LC_warning">'.&mt('Uploaded file contained no data').'</span>';
                   8379:     }
                   8380:     return $output;
                   8381: }
                   8382: 
1.202     albertel 8383: sub valid_file {
                   8384:     my ($requested_file)=@_;
                   8385:     foreach my $filename (sort(&scantron_filenames())) {
                   8386: 	if ($requested_file eq $filename) { return 1; }
                   8387:     }
                   8388:     return 0;
                   8389: }
                   8390: 
                   8391: sub scantron_download_scantron_data {
                   8392:     my ($r)=@_;
1.324     albertel 8393:     my $default_form_data=&defaultFormData(&get_symb($r,1));
1.257     albertel 8394:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   8395:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
                   8396:     my $file=$env{'form.scantron_selectfile'};
1.202     albertel 8397:     if (! &valid_file($file)) {
1.492     albertel 8398: 	$r->print('
1.202     albertel 8399: 	<p>
1.492     albertel 8400: 	    '.&mt('The requested file name was invalid.').'
1.202     albertel 8401:         </p>
1.492     albertel 8402: ');
1.324     albertel 8403: 	$r->print(&show_grading_menu_form(&get_symb($r,1)));
1.202     albertel 8404: 	return;
                   8405:     }
                   8406:     my $orig='/uploaded/'.$cdom.'/'.$cname.'/scantron_orig_'.$file;
                   8407:     my $corrected='/uploaded/'.$cdom.'/'.$cname.'/scantron_corrected_'.$file;
                   8408:     my $skipped='/uploaded/'.$cdom.'/'.$cname.'/scantron_skipped_'.$file;
                   8409:     &Apache::lonnet::allowuploaded('/adm/grades',$orig);
                   8410:     &Apache::lonnet::allowuploaded('/adm/grades',$corrected);
                   8411:     &Apache::lonnet::allowuploaded('/adm/grades',$skipped);
1.492     albertel 8412:     $r->print('
1.202     albertel 8413:     <p>
1.492     albertel 8414: 	'.&mt('[_1]Original[_2] file as uploaded by the scantron office.',
                   8415: 	      '<a href="'.$orig.'">','</a>').'
1.202     albertel 8416:     </p>
                   8417:     <p>
1.492     albertel 8418: 	'.&mt('[_1]Corrections[_2], a file of corrected records that were used in grading.',
                   8419: 	      '<a href="'.$corrected.'">','</a>').'
1.202     albertel 8420:     </p>
                   8421:     <p>
1.492     albertel 8422: 	'.&mt('[_1]Skipped[_2], a file of records that were skipped.',
                   8423: 	      '<a href="'.$skipped.'">','</a>').'
1.202     albertel 8424:     </p>
1.492     albertel 8425: ');
1.324     albertel 8426:     $r->print(&show_grading_menu_form(&get_symb($r,1)));
1.202     albertel 8427:     return '';
                   8428: }
1.157     albertel 8429: 
1.523     raeburn  8430: sub checkscantron_results {
                   8431:     my ($r) = @_;
                   8432:     my ($symb)=&get_symb($r);
                   8433:     if (!$symb) {return '';}
                   8434:     my $grading_menu_button=&show_grading_menu_form($symb);
                   8435:     my $cid = $env{'request.course.id'};
1.542     raeburn  8436:     my %lettdig = &letter_to_digits();
1.523     raeburn  8437:     my $numletts = scalar(keys(%lettdig));
                   8438:     my $cnum = $env{'course.'.$cid.'.num'};
                   8439:     my $cdom = $env{'course.'.$cid.'.domain'};
                   8440:     my (undef, undef, $sequence) = &Apache::lonnet::decode_symb($env{'form.selectpage'});
                   8441:     my %record;
                   8442:     my %scantron_config =
                   8443:         &Apache::grades::get_scantron_config($env{'form.scantron_format'});
                   8444:     my ($scanlines,$scan_data)=&Apache::grades::scantron_getfile();
                   8445:     my $classlist=&Apache::loncoursedata::get_classlist();
                   8446:     my %idmap=&Apache::grades::username_to_idmap($classlist);
                   8447:     my $navmap=Apache::lonnavmaps::navmap->new();
1.582     raeburn  8448:     unless (ref($navmap)) {
                   8449:         $r->print(&navmap_errormsg());
                   8450:         return '';
                   8451:     }
1.523     raeburn  8452:     my $map=$navmap->getResourceByUrl($sequence);
1.557     raeburn  8453:     my @resources=$navmap->retrieveResources($map,\&scantron_filter,1,0);
                   8454:     my (%grader_partids_by_symb,%grader_randomlists_by_symb);
                   8455:     &graders_resources_pass(\@resources,\%grader_partids_by_symb,                             \%grader_randomlists_by_symb);
                   8456: 
1.554     raeburn  8457:     my ($uname,$udom);
1.523     raeburn  8458:     my (%scandata,%lastname,%bylast);
                   8459:     $r->print('
                   8460: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="checkscantron">'."\n");
                   8461: 
                   8462:     my @delayqueue;
                   8463:     my %completedstudents;
                   8464: 
                   8465:     my $count=&Apache::grades::get_todo_count($scanlines,$scan_data);
1.581     www      8466:     my %prog_state=&Apache::lonhtmlcommon::Create_PrgWin($r,'Bubblesheet/Submissions Comparison Status',
                   8467:                                     'Progress of Bubblesheet Data/Submission Records Comparison',$count,
1.523     raeburn  8468:                                     'inline',undef,'checkscantron');
1.546     raeburn  8469:     my ($username,$domain,$started);
1.582     raeburn  8470:     my $nav_error;
1.596.2.12.2.  (raeburn 8471:):     &scantron_get_maxbubble(\$nav_error,\%scantron_config); # Need the bubble lines array to parse.
1.582     raeburn  8472:     if ($nav_error) {
                   8473:         $r->print(&navmap_errormsg());
                   8474:         return '';
                   8475:     }
1.523     raeburn  8476: 
                   8477:     &Apache::lonhtmlcommon::Update_PrgWin($r,\%prog_state,
                   8478:                                           'Processing first student');
                   8479:     my $start=&Time::HiRes::time();
                   8480:     my $i=-1;
                   8481: 
                   8482:     while ($i<$scanlines->{'count'}) {
                   8483:         ($username,$domain,$uname)=('','','');
                   8484:         $i++;
                   8485:         my $line=&Apache::grades::scantron_get_line($scanlines,$scan_data,$i);
                   8486:         if ($line=~/^[\s\cz]*$/) { next; }
                   8487:         if ($started) {
                   8488:             &Apache::lonhtmlcommon::Increment_PrgWin($r,\%prog_state,
                   8489:                                                      'last student');
                   8490:         }
                   8491:         $started=1;
                   8492:         my $scan_record=
                   8493:             &Apache::grades::scantron_parse_scanline($line,$i,\%scantron_config,
                   8494:                                                      $scan_data);
                   8495:         unless ($uname=&Apache::grades::scantron_find_student($scan_record,$scan_data,
                   8496:                                                               \%idmap,$i)) {
                   8497:             &Apache::grades::scantron_add_delay(\@delayqueue,$line,
                   8498:                                 'Unable to find a student that matches',1);
                   8499:             next;
                   8500:         }
                   8501:         if (exists $completedstudents{$uname}) {
                   8502:             &Apache::grades::scantron_add_delay(\@delayqueue,$line,
                   8503:                                 'Student '.$uname.' has multiple sheets',2);
                   8504:             next;
                   8505:         }
                   8506:         my $pid = $scan_record->{'scantron.ID'};
                   8507:         $lastname{$pid} = $scan_record->{'scantron.LastName'};
                   8508:         push(@{$bylast{$lastname{$pid}}},$pid);
                   8509:         my $lastpos = $env{'form.scantron_maxbubble'}*$scantron_config{'Qlength'};
                   8510:         $scandata{$pid} = substr($line,$scantron_config{'Qstart'}-1,$lastpos);
                   8511:         chomp($scandata{$pid});
                   8512:         $scandata{$pid} =~ s/\r$//;
                   8513:         ($username,$domain)=split(/:/,$uname);
                   8514:         my $counter = -1;
                   8515:         foreach my $resource (@resources) {
1.557     raeburn  8516:             my $parts;
1.554     raeburn  8517:             my $ressymb = $resource->symb();
1.557     raeburn  8518:             if ((exists($grader_randomlists_by_symb{$ressymb})) ||
                   8519:                 (ref($grader_partids_by_symb{$ressymb}) ne 'ARRAY')) {
                   8520:                 (my $analysis,$parts) =
1.596.2.12.2.  (raeburn 8521:):                     &scantron_partids_tograde($resource,$env{'request.course.id'},
                   8522:):                                               $username,$domain,undef,
                   8523:):                                               $bubbles_per_row);
1.557     raeburn  8524:             } else {
                   8525:                 $parts = $grader_partids_by_symb{$ressymb};
                   8526:             }
1.542     raeburn  8527:             ($counter,my $recording) =
                   8528:                 &verify_scantron_grading($resource,$domain,$username,$cid,$counter,
1.554     raeburn  8529:                                          $scandata{$pid},$parts,
1.542     raeburn  8530:                                          \%scantron_config,\%lettdig,$numletts);
                   8531:             $record{$pid} .= $recording;
1.523     raeburn  8532:         }
                   8533:     }
                   8534:     &Apache::lonhtmlcommon::Close_PrgWin($r,\%prog_state);
                   8535:     $r->print('<br />');
                   8536:     my ($okstudents,$badstudents,$numstudents,$passed,$failed);
                   8537:     $passed = 0;
                   8538:     $failed = 0;
                   8539:     $numstudents = 0;
                   8540:     foreach my $last (sort(keys(%bylast))) {
                   8541:         if (ref($bylast{$last}) eq 'ARRAY') {
                   8542:             foreach my $pid (sort(@{$bylast{$last}})) {
                   8543:                 my $showscandata = $scandata{$pid};
                   8544:                 my $showrecord = $record{$pid};
                   8545:                 $showscandata =~ s/\s/&nbsp;/g;
                   8546:                 $showrecord =~ s/\s/&nbsp;/g;
                   8547:                 if ($scandata{$pid} eq $record{$pid}) {
                   8548:                     my $css_class = ($passed % 2)?'LC_odd_row':'LC_even_row';
                   8549:                     $okstudents .= '<tr class="'.$css_class.'">'.
1.581     www      8550: '<td>'.&mt('Bubblesheet').'</td><td>'.$showscandata.'</td><td rowspan="2">'.$last.'</td><td rowspan="2">'.$pid.'</td>'."\n".
1.523     raeburn  8551: '</tr>'."\n".
                   8552: '<tr class="'.$css_class.'">'."\n".
                   8553: '<td>Submissions</td><td>'.$showrecord.'</td></tr>'."\n";
                   8554:                     $passed ++;
                   8555:                 } else {
                   8556:                     my $css_class = ($failed % 2)?'LC_odd_row':'LC_even_row';
1.581     www      8557:                     $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  8558: '</tr>'."\n".
                   8559: '<tr class="'.$css_class.'">'."\n".
                   8560: '<td>Submissions</td><td><span class="LC_nobreak">'.$record{$pid}.'</span></td>'."\n".
                   8561: '</tr>'."\n";
                   8562:                     $failed ++;
                   8563:                 }
                   8564:                 $numstudents ++;
                   8565:             }
                   8566:         }
                   8567:     }
1.596.2.4  raeburn  8568:     $r->print('<p>'.
1.596.2.8  raeburn  8569:               &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  8570:                   '<b>',
                   8571:                   $numstudents,
                   8572:                   '</b>',
                   8573:                   $env{'form.scantron_maxbubble'}).
                   8574:               '</p>'
                   8575:     );
1.523     raeburn  8576:     $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>');
                   8577:     if ($passed) {
1.572     www      8578:         $r->print(&mt('Students with exact correspondence between bubblesheet data and submissions are as follows:').'<br /><br />');
1.523     raeburn  8579:         $r->print(&Apache::loncommon::start_data_table()."\n".
                   8580:                  &Apache::loncommon::start_data_table_header_row()."\n".
                   8581:                  '<th>'.&mt('Source').'</th><th>'.&mt('Bubble records').'</th><th>'.&mt('Name').'</th><th>'.&mt('ID').'</th>'.
                   8582:                  &Apache::loncommon::end_data_table_header_row()."\n".
                   8583:                  $okstudents."\n".
                   8584:                  &Apache::loncommon::end_data_table().'<br />');
                   8585:     }
                   8586:     if ($failed) {
1.572     www      8587:         $r->print(&mt('Students with differences between bubblesheet data and submissions are as follows:').'<br /><br />');
1.523     raeburn  8588:         $r->print(&Apache::loncommon::start_data_table()."\n".
                   8589:                  &Apache::loncommon::start_data_table_header_row()."\n".
                   8590:                  '<th>'.&mt('Source').'</th><th>'.&mt('Bubble records').'</th><th>'.&mt('Name').'</th><th>'.&mt('ID').'</th>'.
                   8591:                  &Apache::loncommon::end_data_table_header_row()."\n".
                   8592:                  $badstudents."\n".
                   8593:                  &Apache::loncommon::end_data_table()).'<br />'.
1.572     www      8594:                  &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  8595:     }
                   8596:     $r->print('</form><br />'.$grading_menu_button);
                   8597:     return;
                   8598: }
                   8599: 
1.542     raeburn  8600: sub verify_scantron_grading {
1.554     raeburn  8601:     my ($resource,$domain,$username,$cid,$counter,$scandata,$partids,
1.542     raeburn  8602:         $scantron_config,$lettdig,$numletts) = @_;
                   8603:     my ($record,%expected,%startpos);
                   8604:     return ($counter,$record) if (!ref($resource));
                   8605:     return ($counter,$record) if (!$resource->is_problem());
                   8606:     my $symb = $resource->symb();
1.554     raeburn  8607:     return ($counter,$record) if (ref($partids) ne 'ARRAY');
                   8608:     foreach my $part_id (@{$partids}) {
1.542     raeburn  8609:         $counter ++;
                   8610:         $expected{$part_id} = 0;
                   8611:         if ($env{"form.scantron.sub_bubblelines.$counter"}) {
                   8612:             my @sub_lines = split(/,/,$env{"form.scantron.sub_bubblelines.$counter"});
                   8613:             foreach my $item (@sub_lines) {
                   8614:                 $expected{$part_id} += $item;
                   8615:             }
                   8616:         } else {
                   8617:             $expected{$part_id} = $env{"form.scantron.bubblelines.$counter"};
                   8618:         }
                   8619:         $startpos{$part_id} = $env{"form.scantron.first_bubble_line.$counter"};
                   8620:     }
                   8621:     if ($symb) {
                   8622:         my %recorded;
                   8623:         my (%returnhash) = &Apache::lonnet::restore($symb,$cid,$domain,$username);
                   8624:         if ($returnhash{'version'}) {
                   8625:             my %lasthash=();
                   8626:             my $version;
                   8627:             for ($version=1;$version<=$returnhash{'version'};$version++) {
                   8628:                 foreach my $key (sort(split(/\:/,$returnhash{$version.':keys'}))) {
                   8629:                     $lasthash{$key}=$returnhash{$version.':'.$key};
                   8630:                 }
                   8631:             }
                   8632:             foreach my $key (keys(%lasthash)) {
                   8633:                 if ($key =~ /\.scantron$/) {
                   8634:                     my $value = &unescape($lasthash{$key});
                   8635:                     my ($part_id) = ($key =~ /^resource\.(.+)\.scantron$/);
                   8636:                     if ($value eq '') {
                   8637:                         for (my $i=0; $i<$expected{$part_id}; $i++) {
                   8638:                             for (my $j=0; $j<$scantron_config->{'length'}; $j++) {
                   8639:                                 $recorded{$part_id} .= $scantron_config->{'Qoff'};
                   8640:                             }
                   8641:                         }
                   8642:                     } else {
                   8643:                         my @tocheck;
                   8644:                         my @items = split(//,$value);
                   8645:                         if (($scantron_config->{'Qon'} eq 'letter') ||
                   8646:                             ($scantron_config->{'Qon'} eq 'number')) {
                   8647:                             if (@items < $expected{$part_id}) {
                   8648:                                 my $fragment = substr($scandata,$startpos{$part_id},$expected{$part_id});
                   8649:                                 my @singles = split(//,$fragment);
                   8650:                                 foreach my $pos (@singles) {
                   8651:                                     if ($pos eq ' ') {
                   8652:                                         push(@tocheck,$pos);
                   8653:                                     } else {
                   8654:                                         my $next = shift(@items);
                   8655:                                         push(@tocheck,$next);
                   8656:                                     }
                   8657:                                 }
                   8658:                             } else {
                   8659:                                 @tocheck = @items;
                   8660:                             }
                   8661:                             foreach my $letter (@tocheck) {
                   8662:                                 if ($scantron_config->{'Qon'} eq 'letter') {
                   8663:                                     if ($letter !~ /^[A-J]$/) {
                   8664:                                         $letter = $scantron_config->{'Qoff'};
                   8665:                                     }
                   8666:                                     $recorded{$part_id} .= $letter;
                   8667:                                 } elsif ($scantron_config->{'Qon'} eq 'number') {
                   8668:                                     my $digit;
                   8669:                                     if ($letter !~ /^[A-J]$/) {
                   8670:                                         $digit = $scantron_config->{'Qoff'};
                   8671:                                     } else {
                   8672:                                         $digit = $lettdig->{$letter};
                   8673:                                     }
                   8674:                                     $recorded{$part_id} .= $digit;
                   8675:                                 }
                   8676:                             }
                   8677:                         } else {
                   8678:                             @tocheck = @items;
                   8679:                             for (my $i=0; $i<$expected{$part_id}; $i++) {
                   8680:                                 my $curr_sub = shift(@tocheck);
                   8681:                                 my $digit;
                   8682:                                 if ($curr_sub =~ /^[A-J]$/) {
                   8683:                                     $digit = $lettdig->{$curr_sub}-1;
                   8684:                                 }
                   8685:                                 if ($curr_sub eq 'J') {
                   8686:                                     $digit += scalar($numletts);
                   8687:                                 }
                   8688:                                 for (my $j=0; $j<$scantron_config->{'Qlength'}; $j++) {
                   8689:                                     if ($j == $digit) {
                   8690:                                         $recorded{$part_id} .= $scantron_config->{'Qon'};
                   8691:                                     } else {
                   8692:                                         $recorded{$part_id} .= $scantron_config->{'Qoff'};
                   8693:                                     }
                   8694:                                 }
                   8695:                             }
                   8696:                         }
                   8697:                     }
                   8698:                 }
                   8699:             }
                   8700:         }
1.554     raeburn  8701:         foreach my $part_id (@{$partids}) {
1.542     raeburn  8702:             if ($recorded{$part_id} eq '') {
                   8703:                 for (my $i=0; $i<$expected{$part_id}; $i++) {
                   8704:                     for (my $j=0; $j<$scantron_config->{'Qlength'}; $j++) {
                   8705:                         $recorded{$part_id} .= $scantron_config->{'Qoff'};
                   8706:                     }
                   8707:                 }
                   8708:             }
                   8709:             $record .= $recorded{$part_id};
                   8710:         }
                   8711:     }
                   8712:     return ($counter,$record);
                   8713: }
                   8714: 
                   8715: sub letter_to_digits { 
                   8716:     my %lettdig = (
                   8717:                     A => 1,
                   8718:                     B => 2,
                   8719:                     C => 3,
                   8720:                     D => 4,
                   8721:                     E => 5,
                   8722:                     F => 6,
                   8723:                     G => 7,
                   8724:                     H => 8,
                   8725:                     I => 9,
                   8726:                     J => 0,
                   8727:                   );
                   8728:     return %lettdig;
                   8729: }
                   8730: 
1.423     albertel 8731: 
1.75      albertel 8732: #-------- end of section for handling grading scantron forms -------
                   8733: #
                   8734: #-------------------------------------------------------------------
                   8735: 
1.72      ng       8736: #-------------------------- Menu interface -------------------------
                   8737: #
                   8738: #--- Show a Grading Menu button - Calls the next routine ---
                   8739: sub show_grading_menu_form {
1.324     albertel 8740:     my ($symb)=@_;
1.125     ng       8741:     my $result.='<br /><form action="/adm/grades" method="post">'."\n".
1.418     albertel 8742: 	'<input type="hidden" name="symb" value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
1.257     albertel 8743: 	'<input type="hidden" name="saveState"  value="'.$env{'form.saveState'}.'" />'."\n".
1.72      ng       8744: 	'<input type="hidden" name="command" value="gradingmenu" />'."\n".
1.478     albertel 8745: 	'<input type="submit" name="submit" value="'.&mt('Grading Menu').'" />'."\n".
1.72      ng       8746: 	'</form>'."\n";
                   8747:     return $result;
                   8748: }
                   8749: 
1.77      ng       8750: # -- Retrieve choices for grading form
                   8751: sub savedState {
                   8752:     my %savedState = ();
1.257     albertel 8753:     if ($env{'form.saveState'}) {
                   8754: 	foreach (split(/:/,$env{'form.saveState'})) {
1.77      ng       8755: 	    my ($key,$value) = split(/=/,$_,2);
                   8756: 	    $savedState{$key} = $value;
                   8757: 	}
                   8758:     }
                   8759:     return \%savedState;
                   8760: }
1.76      ng       8761: 
1.443     banghart 8762: sub grading_menu {
                   8763:     my ($request) = @_;
                   8764:     my ($symb)=&get_symb($request);
                   8765:     if (!$symb) {return '';}
                   8766:     my $probTitle = &Apache::lonnet::gettitle($symb);
                   8767:     my ($table,undef,$hdgrade) = &showResourceInfo($symb,$probTitle);
                   8768: 
1.444     banghart 8769:     $request->print($table);
1.443     banghart 8770:     my %fields = ('symb'=>&Apache::lonenc::check_encrypt($symb),
                   8771:                   'handgrade'=>$hdgrade,
                   8772:                   'probTitle'=>$probTitle,
                   8773:                   'command'=>'submit_options',
                   8774:                   'saveState'=>"",
                   8775:                   'gradingMenu'=>1,
                   8776:                   'showgrading'=>"yes");
1.538     schulted 8777:     
                   8778:     my $url1 = &Apache::lonhtmlcommon::build_url('grades/',\%fields);
                   8779:     
1.443     banghart 8780:     $fields{'command'} = 'csvform';
1.538     schulted 8781:     my $url2 = &Apache::lonhtmlcommon::build_url('grades/',\%fields);
                   8782:     
1.443     banghart 8783:     $fields{'command'} = 'processclicker';
1.538     schulted 8784:     my $url3 = &Apache::lonhtmlcommon::build_url('grades/',\%fields);
                   8785:     
1.443     banghart 8786:     $fields{'command'} = 'scantron_selectphase';
1.538     schulted 8787:     my $url4 = &Apache::lonhtmlcommon::build_url('grades/',\%fields);
                   8788:     
                   8789:     my @menu = ({	categorytitle=>'Course Grading',
                   8790:             items =>[
                   8791:                         {	linktext => 'Manual Grading/View Submissions',
                   8792:                     		url => $url1,
                   8793:                     		permission => 'F',
                   8794:                     		icon => 'edit-find-replace.png',
                   8795:                     		linktitle => 'Start the process of hand grading submissions.'
                   8796:                         },
                   8797:                 	    {	linktext => 'Upload Scores',
                   8798:                     		url => $url2,
                   8799:                     		permission => 'F',
                   8800:                     		icon => 'uploadscores.png',
                   8801:                     		linktitle => 'Specify a file containing the class scores for current resource.'
                   8802:                 	    },
                   8803:                 	    {	linktext => 'Process Clicker',
                   8804:                     		url => $url3,
                   8805:                     		permission => 'F',
                   8806:                     		icon => 'addClickerInfoFile.png',
                   8807:                     		linktitle => 'Specify a file containing the clicker information for this resource.'
                   8808:                 	    },
1.587     raeburn  8809:                 	    {	linktext => 'Grade/Manage/Review Bubblesheets',
1.538     schulted 8810:                     		url => $url4,
                   8811:                     		permission => 'F',
                   8812:                     		icon => 'stat.png',
1.596.2.4  raeburn  8813:                     		linktitle => 'Grade bubblesheet exams, upload/download bubblesheet data files, and review previously graded bubblesheet exams.'
1.538     schulted 8814:                 	    }
                   8815:                     ]
                   8816:             });
                   8817: 
                   8818:     #$fields{'command'} = 'verify';
                   8819:     #$url = &Apache::lonhtmlcommon::build_url('grades/',\%fields);
1.443     banghart 8820:     #
                   8821:     # Create the menu
                   8822:     my $Str;
1.444     banghart 8823:     # $Str .= '<h2>'.&mt('Please select a grading task').'</h2>';
1.445     banghart 8824:     $Str .= '<form method="post" action="" name="gradingMenu">';
                   8825:     $Str .= '<input type="hidden" name="command" value="" />'.
                   8826:     	'<input type="hidden" name="symb"        value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
                   8827: 	'<input type="hidden" name="handgrade"   value="'.$hdgrade.'" />'."\n".
1.476     albertel 8828: 	'<input type="hidden" name="probTitle"   value="'.$probTitle.'" />'."\n".
1.445     banghart 8829: 	'<input type="hidden" name="saveState"   value="" />'."\n".
                   8830: 	'<input type="hidden" name="gradingMenu" value="1" />'."\n".
                   8831: 	'<input type="hidden" name="showgrading" value="yes" />'."\n";
                   8832: 
1.538     schulted 8833:     $Str .= Apache::lonhtmlcommon::generate_menu(@menu);
                   8834:     #$menudata->{'jscript'}
1.584     bisitz   8835:     $Str .='<hr /><input type="button" value="'.&mt('Verify Receipt No.').'" '.
1.589     bisitz   8836:         ' onclick="javascript:checkChoice(document.forms.gradingMenu,\'5\',\'verify\')" '.
1.538     schulted 8837:         ' /> '.
                   8838:         &Apache::lonnet::recprefix($env{'request.course.id'}).
1.589     bisitz   8839:         '-<input type="text" name="receipt" size="4" onchange="javascript:checkReceiptNo(this.form,\'OK\')" />';
1.538     schulted 8840: 
1.444     banghart 8841:     $Str .="</form>\n";
1.539     riegler  8842:     my $receiptalert = &mt("Please enter a receipt number given by a student in the receipt box.");
1.443     banghart 8843:     $request->print(<<GRADINGMENUJS);
                   8844: <script type="text/javascript" language="javascript">
                   8845:     function checkChoice(formname,val,cmdx) {
                   8846: 	if (val <= 2) {
                   8847: 	    var cmd = radioSelection(formname.radioChoice);
                   8848: 	    var cmdsave = cmd;
                   8849: 	} else {
                   8850: 	    cmd = cmdx;
                   8851: 	    cmdsave = 'submission';
                   8852: 	}
                   8853: 	formname.command.value = cmd;
                   8854: 	if (val < 5) formname.submit();
                   8855: 	if (val == 5) {
1.458     banghart 8856: 	    if (!checkReceiptNo(formname,'notOK')) { 
                   8857: 	        return false;
                   8858: 	    } else {
                   8859: 	        formname.submit();
                   8860: 	    }
1.445     banghart 8861: 	}
                   8862:     }
1.443     banghart 8863: 
                   8864:     function checkReceiptNo(formname,nospace) {
                   8865: 	var receiptNo = formname.receipt.value;
                   8866: 	var checkOpt = false;
                   8867: 	if (nospace == "OK" && isNaN(receiptNo)) {checkOpt = true;}
                   8868: 	if (nospace == "notOK" && (isNaN(receiptNo) || receiptNo == "")) {checkOpt = true;}
                   8869: 	if (checkOpt) {
1.539     riegler  8870: 	    alert("$receiptalert");
1.443     banghart 8871: 	    formname.receipt.value = "";
                   8872: 	    formname.receipt.focus();
                   8873: 	    return false;
                   8874: 	}
                   8875: 	return true;
                   8876:     }
                   8877: </script>
                   8878: GRADINGMENUJS
                   8879:     &commonJSfunctions($request);
                   8880:     return $Str;    
                   8881: }
                   8882: 
                   8883: 
                   8884: #--- Displays the submissions first page -------
                   8885: sub submit_options {
1.72      ng       8886:     my ($request) = @_;
1.324     albertel 8887:     my ($symb)=&get_symb($request);
1.72      ng       8888:     if (!$symb) {return '';}
1.76      ng       8889:     my $probTitle = &Apache::lonnet::gettitle($symb);
1.72      ng       8890: 
1.539     riegler  8891:     my $receiptalert = &mt("Please enter a receipt number given by a student in the receipt box."); 
1.72      ng       8892:     $request->print(<<GRADINGMENUJS);
                   8893: <script type="text/javascript" language="javascript">
1.116     ng       8894:     function checkChoice(formname,val,cmdx) {
                   8895: 	if (val <= 2) {
                   8896: 	    var cmd = radioSelection(formname.radioChoice);
1.118     ng       8897: 	    var cmdsave = cmd;
1.116     ng       8898: 	} else {
                   8899: 	    cmd = cmdx;
1.118     ng       8900: 	    cmdsave = 'submission';
1.116     ng       8901: 	}
                   8902: 	formname.command.value = cmd;
1.118     ng       8903: 	formname.saveState.value = "saveCmd="+cmdsave+":saveSec="+pullDownSelection(formname.section)+
1.145     albertel 8904: 	    ":saveSub="+pullDownSelection(formname.submitonly)+":saveStatus="+pullDownSelection(formname.Status);
1.116     ng       8905: 	if (val < 5) formname.submit();
                   8906: 	if (val == 5) {
1.72      ng       8907: 	    if (!checkReceiptNo(formname,'notOK')) { return false;}
                   8908: 	    formname.submit();
                   8909: 	}
1.238     albertel 8910: 	if (val < 7) formname.submit();
1.72      ng       8911:     }
                   8912: 
                   8913:     function checkReceiptNo(formname,nospace) {
                   8914: 	var receiptNo = formname.receipt.value;
                   8915: 	var checkOpt = false;
                   8916: 	if (nospace == "OK" && isNaN(receiptNo)) {checkOpt = true;}
                   8917: 	if (nospace == "notOK" && (isNaN(receiptNo) || receiptNo == "")) {checkOpt = true;}
                   8918: 	if (checkOpt) {
1.539     riegler  8919: 	    alert("$receiptalert");
1.72      ng       8920: 	    formname.receipt.value = "";
                   8921: 	    formname.receipt.focus();
                   8922: 	    return false;
                   8923: 	}
                   8924: 	return true;
                   8925:     }
                   8926: </script>
                   8927: GRADINGMENUJS
1.118     ng       8928:     &commonJSfunctions($request);
1.324     albertel 8929:     my ($table,undef,$hdgrade) = &showResourceInfo($symb,$probTitle);
1.473     albertel 8930:     my $result;
1.76      ng       8931:     my (undef,$sections) = &getclasslist('all','0');
1.77      ng       8932:     my $savedState = &savedState();
1.118     ng       8933:     my $saveCmd = ($$savedState{'saveCmd'} eq '' ? 'submission' : $$savedState{'saveCmd'});
1.77      ng       8934:     my $saveSec = ($$savedState{'saveSec'} eq '' ? 'all' : $$savedState{'saveSec'});
1.118     ng       8935:     my $saveSub = ($$savedState{'saveSub'} eq '' ? 'all' : $$savedState{'saveSub'});
1.77      ng       8936:     my $saveStatus = ($$savedState{'saveStatus'} eq '' ? 'Active' : $$savedState{'saveStatus'});
1.72      ng       8937: 
1.533     bisitz   8938:     # Preselect sections
                   8939:     my $selsec="";
                   8940:     if (ref($sections)) {
                   8941:         foreach my $section (sort(@$sections)) {
                   8942:             $selsec.='<option value="'.$section.'" '.
                   8943:                 ($saveSec eq $section ? 'selected="selected"':'').'>'.$section.'</option>'."\n";
                   8944:         }
                   8945:     }
                   8946: 
1.72      ng       8947:     $result.='<form action="/adm/grades" method="post" name="gradingMenu">'."\n".
1.418     albertel 8948: 	'<input type="hidden" name="symb"        value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
1.72      ng       8949: 	'<input type="hidden" name="handgrade"   value="'.$hdgrade.'" />'."\n".
                   8950: 	'<input type="hidden" name="probTitle"   value="'.$probTitle.'" />'."\n".
1.116     ng       8951: 	'<input type="hidden" name="command"     value="" />'."\n".
1.77      ng       8952: 	'<input type="hidden" name="saveState"   value="" />'."\n".
1.124     ng       8953: 	'<input type="hidden" name="gradingMenu" value="1" />'."\n".
1.72      ng       8954: 	'<input type="hidden" name="showgrading" value="yes" />'."\n";
                   8955: 
1.472     albertel 8956:     $result.='
1.533     bisitz   8957: <h2>
                   8958:   '.&mt('Grade Current Resource').'
                   8959: </h2>
                   8960: <div>
                   8961:   '.$table.'
                   8962: </div>
                   8963: 
1.537     harmsja  8964: <div class="LC_columnSection">
                   8965:   
1.533     bisitz   8966:     <fieldset>
                   8967:       <legend>
                   8968:        '.&mt('Sections').'
                   8969:       </legend>
                   8970:       <select name="section" multiple="multiple" size="5">'."\n";
                   8971:     $result.= $selsec;
1.401     albertel 8972:     $result.= '<option value="all" '.($saveSec eq 'all' ? 'selected="selected"' : ''). '>all</option></select> &nbsp; ';
1.472     albertel 8973:     $result.='
1.533     bisitz   8974:     </fieldset>
1.537     harmsja  8975:   
1.533     bisitz   8976:     <fieldset>
                   8977:       <legend>
                   8978:         '.&mt('Groups').'
                   8979:       </legend>
                   8980:       '.&Apache::lonstatistics::GroupSelect('group','multiple',5).'
                   8981:     </fieldset>
1.537     harmsja  8982:   
1.533     bisitz   8983:     <fieldset>
                   8984:       <legend>
                   8985:         '.&mt('Access Status').'
                   8986:       </legend>
                   8987:       '.&Apache::lonhtmlcommon::StatusOptions($saveStatus,undef,5,undef,'mult').'
                   8988:     </fieldset>
1.537     harmsja  8989:   
1.533     bisitz   8990:     <fieldset>
                   8991:       <legend>
                   8992:         '.&mt('Submission Status').'
                   8993:       </legend>
                   8994:       <select name="submitonly" size="5">
1.473     albertel 8995: 	         <option value="yes" '.      ($saveSub eq 'yes'       ? 'selected="selected"' : '').'>'.&mt('with submissions').'</option>
                   8996: 	         <option value="queued" '.   ($saveSub eq 'queued'    ? 'selected="selected"' : '').'>'.&mt('in grading queue').'</option>
                   8997: 	         <option value="graded" '.   ($saveSub eq 'graded'    ? 'selected="selected"' : '').'>'.&mt('with ungraded submissions').'</option>
                   8998: 	         <option value="incorrect" '.($saveSub eq 'incorrect' ? 'selected="selected"' : '').'>'.&mt('with incorrect submissions').'</option>
                   8999:                  <option value="all" '.      ($saveSub eq 'all'       ? 'selected="selected"' : '').'>'.&mt('with any status').'</option>
1.533     bisitz   9000:       </select>
                   9001:     </fieldset>
1.537     harmsja  9002:   
1.533     bisitz   9003: </div>
                   9004: 
                   9005: <br />
                   9006:           <div>
                   9007:             <div>
1.473     albertel 9008:               <label>
                   9009:                 <input type="radio" name="radioChoice" value="submission" '.
                   9010:                   ($saveCmd eq 'submission' ? 'checked="checked"' : '').' /> '.
                   9011:              &mt('Select individual students to grade and view submissions.').'
                   9012: 	      </label> 
                   9013:             </div>
1.533     bisitz   9014:             <div>
1.473     albertel 9015: 	      <label>
                   9016:                 <input type="radio" name="radioChoice" value="viewgrades" '.
                   9017:                   ($saveCmd eq 'viewgrades' ? 'checked="checked"' : '').' /> '.
                   9018:                     &mt('Grade all selected students in a grading table.').'
                   9019:               </label>
                   9020:             </div>
1.533     bisitz   9021:             <div>
1.589     bisitz   9022: 	      <input type="button" onclick="javascript:checkChoice(this.form,\'2\');" value="'.&mt('Next').' &rarr;" />
1.473     albertel 9023:             </div>
1.472     albertel 9024:           </div>
1.533     bisitz   9025: 
                   9026: 
1.473     albertel 9027:         <h2>
                   9028:          '.&mt('Grade Complete Folder for One Student').'
                   9029:         </h2>
1.533     bisitz   9030:         <div>
                   9031:             <div>
1.473     albertel 9032:               <label>
                   9033:                 <input type="radio" name="radioChoice" value="pickStudentPage" '.
                   9034: 	  ($saveCmd eq 'pickStudentPage' ? 'checked="checked"' : '').' /> '.
                   9035:   &mt('The <b>complete</b> page/sequence/folder: For one student').'
                   9036:               </label>
                   9037:             </div>
1.533     bisitz   9038:             <div>
1.589     bisitz   9039: 	      <input type="button" onclick="javascript:checkChoice(this.form,\'2\');" value="'.&mt('Next').' &rarr;" />
1.473     albertel 9040:             </div>
1.472     albertel 9041:         </div>
                   9042:   </form>';
1.499     albertel 9043:     $result .= &show_grading_menu_form($symb);
1.44      ng       9044:     return $result;
1.2       albertel 9045: }
                   9046: 
1.285     albertel 9047: sub reset_perm {
                   9048:     undef(%perm);
                   9049: }
                   9050: 
                   9051: sub init_perm {
                   9052:     &reset_perm();
1.300     albertel 9053:     foreach my $test_perm ('vgr','mgr','opa') {
                   9054: 
                   9055: 	my $scope = $env{'request.course.id'};
                   9056: 	if (!($perm{$test_perm}=&Apache::lonnet::allowed($test_perm,$scope))) {
                   9057: 
                   9058: 	    $scope .= '/'.$env{'request.course.sec'};
                   9059: 	    if ( $perm{$test_perm}=
                   9060: 		 &Apache::lonnet::allowed($test_perm,$scope)) {
                   9061: 		$perm{$test_perm.'_section'}=$env{'request.course.sec'};
                   9062: 	    } else {
                   9063: 		delete($perm{$test_perm});
                   9064: 	    }
1.285     albertel 9065: 	}
                   9066:     }
                   9067: }
                   9068: 
1.400     www      9069: sub gather_clicker_ids {
1.408     albertel 9070:     my %clicker_ids;
1.400     www      9071: 
                   9072:     my $classlist = &Apache::loncoursedata::get_classlist();
                   9073: 
                   9074:     # Set up a couple variables.
1.407     albertel 9075:     my $username_idx = &Apache::loncoursedata::CL_SNAME();
                   9076:     my $domain_idx   = &Apache::loncoursedata::CL_SDOM();
1.438     www      9077:     my $status_idx   = &Apache::loncoursedata::CL_STATUS();
1.400     www      9078: 
1.407     albertel 9079:     foreach my $student (keys(%$classlist)) {
1.438     www      9080:         if ($classlist->{$student}->[$status_idx] ne 'Active') { next; }
1.407     albertel 9081:         my $username = $classlist->{$student}->[$username_idx];
                   9082:         my $domain   = $classlist->{$student}->[$domain_idx];
1.400     www      9083:         my $clickers =
1.408     albertel 9084: 	    (&Apache::lonnet::userenvironment($domain,$username,'clickers'))[1];
1.400     www      9085:         foreach my $id (split(/\,/,$clickers)) {
1.414     www      9086:             $id=~s/^[\#0]+//;
1.421     www      9087:             $id=~s/[\-\:]//g;
1.407     albertel 9088:             if (exists($clicker_ids{$id})) {
1.408     albertel 9089: 		$clicker_ids{$id}.=','.$username.':'.$domain;
1.400     www      9090:             } else {
1.408     albertel 9091: 		$clicker_ids{$id}=$username.':'.$domain;
1.400     www      9092:             }
                   9093:         }
                   9094:     }
1.407     albertel 9095:     return %clicker_ids;
1.400     www      9096: }
                   9097: 
1.402     www      9098: sub gather_adv_clicker_ids {
1.408     albertel 9099:     my %clicker_ids;
1.402     www      9100:     my $cnum=$env{'course.'.$env{'request.course.id'}.'.num'};
                   9101:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
                   9102:     my %coursepersonnel=&Apache::lonnet::get_course_adv_roles($cdom.'/'.$cnum);
1.409     albertel 9103:     foreach my $element (sort(keys(%coursepersonnel))) {
1.402     www      9104:         foreach my $person (split(/\,/,$coursepersonnel{$element})) {
                   9105:             my ($puname,$pudom)=split(/\:/,$person);
                   9106:             my $clickers =
1.408     albertel 9107: 		(&Apache::lonnet::userenvironment($pudom,$puname,'clickers'))[1];
1.405     www      9108:             foreach my $id (split(/\,/,$clickers)) {
1.414     www      9109: 		$id=~s/^[\#0]+//;
1.421     www      9110:                 $id=~s/[\-\:]//g;
1.408     albertel 9111: 		if (exists($clicker_ids{$id})) {
                   9112: 		    $clicker_ids{$id}.=','.$puname.':'.$pudom;
                   9113: 		} else {
                   9114: 		    $clicker_ids{$id}=$puname.':'.$pudom;
                   9115: 		}
1.405     www      9116:             }
1.402     www      9117:         }
                   9118:     }
1.407     albertel 9119:     return %clicker_ids;
1.402     www      9120: }
                   9121: 
1.413     www      9122: sub clicker_grading_parameters {
                   9123:     return ('gradingmechanism' => 'scalar',
                   9124:             'upfiletype' => 'scalar',
                   9125:             'specificid' => 'scalar',
                   9126:             'pcorrect' => 'scalar',
                   9127:             'pincorrect' => 'scalar');
                   9128: }
                   9129: 
1.400     www      9130: sub process_clicker {
                   9131:     my ($r)=@_;
                   9132:     my ($symb)=&get_symb($r);
                   9133:     if (!$symb) {return '';}
                   9134:     my $result=&checkforfile_js();
                   9135:     $env{'form.probTitle'} = &Apache::lonnet::gettitle($symb);
                   9136:     my ($table) = &showResourceInfo($symb,$env{'form.probTitle'});
                   9137:     $result.=$table;
                   9138:     $result.='<br /><table width="100%" border="0"><tr><td bgcolor="#777777">'."\n";
                   9139:     $result.='<table width="100%" border="0"><tr bgcolor="#e6ffff"><td>'."\n";
1.538     schulted 9140:     $result.='&nbsp;<b>'.&mt('Specify a file containing the clicker information for this resource.').
                   9141:         '</b></td></tr>'."\n";
1.596.2.4  raeburn  9142:     $result.='<tr bgcolor="#ffffe6"><td>'."\n";
1.413     www      9143: # Attempt to restore parameters from last session, set defaults if not present
                   9144:     my %Saveable_Parameters=&clicker_grading_parameters();
                   9145:     &Apache::loncommon::restore_course_settings('grades_clicker',
                   9146:                                                  \%Saveable_Parameters);
                   9147:     if (!$env{'form.pcorrect'}) { $env{'form.pcorrect'}=100; }
                   9148:     if (!$env{'form.pincorrect'}) { $env{'form.pincorrect'}=100; }
                   9149:     if (!$env{'form.gradingmechanism'}) { $env{'form.gradingmechanism'}='attendance'; }
                   9150:     if (!$env{'form.upfiletype'}) { $env{'form.upfiletype'}='iclicker'; }
                   9151: 
                   9152:     my %checked;
1.521     www      9153:     foreach my $gradingmechanism ('attendance','personnel','specific','given') {
1.413     www      9154:        if ($env{'form.gradingmechanism'} eq $gradingmechanism) {
1.569     bisitz   9155:           $checked{$gradingmechanism}=' checked="checked"';
1.413     www      9156:        }
                   9157:     }
                   9158: 
1.400     www      9159:     my $upload=&mt("Upload File");
                   9160:     my $type=&mt("Type");
1.402     www      9161:     my $attendance=&mt("Award points just for participation");
                   9162:     my $personnel=&mt("Correctness determined from response by course personnel");
1.414     www      9163:     my $specific=&mt("Correctness determined from response with clicker ID(s)"); 
1.521     www      9164:     my $given=&mt("Correctness determined from given list of answers").' '.
                   9165:               '<font size="-2"><tt>('.&mt("Provide comma-separated list. Use '*' for any answer correct, '-' for skip").')</tt></font>';
1.402     www      9166:     my $pcorrect=&mt("Percentage points for correct solution");
                   9167:     my $pincorrect=&mt("Percentage points for incorrect solution");
1.413     www      9168:     my $selectform=&Apache::loncommon::select_form($env{'form.upfiletype'},'upfiletype',
1.596.2.1  raeburn  9169:                                                    {'iclicker' => 'i>clicker',
1.596.2.12.2.  (raeburn 9170:):                                                     'interwrite' => 'interwrite PRS',
                   9171:):                                                     'turning' => 'Turning Technologies'});
1.418     albertel 9172:     $symb = &Apache::lonenc::check_encrypt($symb);
1.400     www      9173:     $result.=<<ENDUPFORM;
1.402     www      9174: <script type="text/javascript">
                   9175: function sanitycheck() {
                   9176: // Accept only integer percentages
                   9177:    document.forms.gradesupload.pcorrect.value=Math.round(document.forms.gradesupload.pcorrect.value);
                   9178:    document.forms.gradesupload.pincorrect.value=Math.round(document.forms.gradesupload.pincorrect.value);
                   9179: // Find out grading choice
                   9180:    for (i=0; i<document.forms.gradesupload.gradingmechanism.length; i++) {
                   9181:       if (document.forms.gradesupload.gradingmechanism[i].checked) {
                   9182:          gradingchoice=document.forms.gradesupload.gradingmechanism[i].value;
                   9183:       }
                   9184:    }
                   9185: // By default, new choice equals user selection
                   9186:    newgradingchoice=gradingchoice;
                   9187: // Not good to give more points for false answers than correct ones
                   9188:    if (Math.round(document.forms.gradesupload.pcorrect.value)<Math.round(document.forms.gradesupload.pincorrect.value)) {
                   9189:       document.forms.gradesupload.pcorrect.value=document.forms.gradesupload.pincorrect.value;
                   9190:    }
                   9191: // If new choice is attendance only, and old choice was correctness-based, restore defaults
                   9192:    if ((gradingchoice=='attendance') && (document.forms.gradesupload.waschecked.value!='attendance')) {
                   9193:       document.forms.gradesupload.pcorrect.value=100;
                   9194:       document.forms.gradesupload.pincorrect.value=100;
                   9195:    }
                   9196: // If the values are different, cannot be attendance only
                   9197:    if ((Math.round(document.forms.gradesupload.pcorrect.value)!=Math.round(document.forms.gradesupload.pincorrect.value)) &&
                   9198:        (gradingchoice=='attendance')) {
                   9199:        newgradingchoice='personnel';
                   9200:    }
                   9201: // Change grading choice to new one
                   9202:    for (i=0; i<document.forms.gradesupload.gradingmechanism.length; i++) {
                   9203:       if (document.forms.gradesupload.gradingmechanism[i].value==newgradingchoice) {
                   9204:          document.forms.gradesupload.gradingmechanism[i].checked=true;
                   9205:       } else {
                   9206:          document.forms.gradesupload.gradingmechanism[i].checked=false;
                   9207:       }
                   9208:    }
                   9209: // Remember the old state
                   9210:    document.forms.gradesupload.waschecked.value=newgradingchoice;
                   9211: }
                   9212: </script>
1.400     www      9213: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="gradesupload">
                   9214: <input type="hidden" name="symb" value="$symb" />
                   9215: <input type="hidden" name="command" value="processclickerfile" />
                   9216: <input type="hidden" name="probTitle" value="$env{'form.probTitle'}" />
                   9217: <input type="hidden" name="saveState"  value="$env{'form.saveState'}" />
                   9218: <input type="file" name="upfile" size="50" />
                   9219: <br /><label>$type: $selectform</label>
1.589     bisitz   9220: <br /><label><input type="radio" name="gradingmechanism" value="attendance"$checked{'attendance'} onclick="sanitycheck()" />$attendance </label>
                   9221: <br /><label><input type="radio" name="gradingmechanism" value="personnel"$checked{'personnel'} onclick="sanitycheck()" />$personnel</label>
                   9222: <br /><label><input type="radio" name="gradingmechanism" value="specific"$checked{'specific'} onclick="sanitycheck()" />$specific </label>
1.414     www      9223: <input type="text" name="specificid" value="$env{'form.specificid'}" size="20" />
1.589     bisitz   9224: <br /><label><input type="radio" name="gradingmechanism" value="given"$checked{'given'} onclick="sanitycheck()" />$given </label>
1.521     www      9225: <br />&nbsp;&nbsp;&nbsp;
                   9226: <input type="text" name="givenanswer" size="50" />
1.413     www      9227: <input type="hidden" name="waschecked" value="$env{'form.gradingmechanism'}" />
1.589     bisitz   9228: <br /><label>$pcorrect: <input type="text" name="pcorrect" size="4" value="$env{'form.pcorrect'}" onchange="sanitycheck()" /></label>
                   9229: <br /><label>$pincorrect: <input type="text" name="pincorrect" size="4" value="$env{'form.pincorrect'}" onchange="sanitycheck()" /></label>
                   9230: <br /><input type="button" onclick="javascript:checkUpload(this.form);" value="$upload" />
1.400     www      9231: </form>
                   9232: ENDUPFORM
                   9233:     $result.='</td></tr></table>'."\n".
                   9234:              '</td></tr></table><br /><br />'."\n";
                   9235:     $result.=&show_grading_menu_form($symb);
                   9236:     return $result;
                   9237: }
                   9238: 
                   9239: sub process_clicker_file {
                   9240:     my ($r)=@_;
                   9241:     my ($symb)=&get_symb($r);
                   9242:     if (!$symb) {return '';}
1.413     www      9243: 
                   9244:     my %Saveable_Parameters=&clicker_grading_parameters();
                   9245:     &Apache::loncommon::store_course_settings('grades_clicker',
                   9246:                                               \%Saveable_Parameters);
                   9247: 
1.400     www      9248:     my ($result) = &showResourceInfo($symb,$env{'form.probTitle'});
1.404     www      9249:     if (($env{'form.gradingmechanism'} eq 'specific') && ($env{'form.specificid'}!~/\w/)) {
1.408     albertel 9250: 	$result.='<span class="LC_error">'.&mt('You need to specify a clicker ID for the correct answer').'</span>';
                   9251: 	return $result.&show_grading_menu_form($symb);
1.404     www      9252:     }
1.522     www      9253:     if (($env{'form.gradingmechanism'} eq 'given') && ($env{'form.givenanswer'}!~/\S/)) {
1.521     www      9254:         $result.='<span class="LC_error">'.&mt('You need to specify the correct answer').'</span>';
                   9255:         return $result.&show_grading_menu_form($symb);
                   9256:     }
1.522     www      9257:     my $foundgiven=0;
1.521     www      9258:     if ($env{'form.gradingmechanism'} eq 'given') {
                   9259:         $env{'form.givenanswer'}=~s/^\s*//gs;
                   9260:         $env{'form.givenanswer'}=~s/\s*$//gs;
1.596.2.4  raeburn  9261:         $env{'form.givenanswer'}=~s/[^a-zA-Z0-9\.\*\-\+]+/\,/g;
1.521     www      9262:         $env{'form.givenanswer'}=uc($env{'form.givenanswer'});
1.522     www      9263:         my @answers=split(/\,/,$env{'form.givenanswer'});
                   9264:         $foundgiven=$#answers+1;
1.521     www      9265:     }
1.407     albertel 9266:     my %clicker_ids=&gather_clicker_ids();
1.408     albertel 9267:     my %correct_ids;
1.404     www      9268:     if ($env{'form.gradingmechanism'} eq 'personnel') {
1.408     albertel 9269: 	%correct_ids=&gather_adv_clicker_ids();
1.404     www      9270:     }
                   9271:     if ($env{'form.gradingmechanism'} eq 'specific') {
1.414     www      9272: 	foreach my $correct_id (split(/[\s\,]/,$env{'form.specificid'})) {;
                   9273: 	   $correct_id=~tr/a-z/A-Z/;
                   9274: 	   $correct_id=~s/\s//gs;
                   9275: 	   $correct_id=~s/^[\#0]+//;
1.421     www      9276:            $correct_id=~s/[\-\:]//g;
1.414     www      9277:            if ($correct_id) {
                   9278: 	      $correct_ids{$correct_id}='specified';
                   9279:            }
                   9280:         }
1.400     www      9281:     }
1.404     www      9282:     if ($env{'form.gradingmechanism'} eq 'attendance') {
1.408     albertel 9283: 	$result.=&mt('Score based on attendance only');
1.521     www      9284:     } elsif ($env{'form.gradingmechanism'} eq 'given') {
1.522     www      9285:         $result.=&mt('Score based on [_1] ([_2] answers)','<tt>'.$env{'form.givenanswer'}.'</tt>',$foundgiven);
1.404     www      9286:     } else {
1.408     albertel 9287: 	my $number=0;
1.411     www      9288: 	$result.='<p><b>'.&mt('Correctness determined by the following IDs').'</b>';
1.408     albertel 9289: 	foreach my $id (sort(keys(%correct_ids))) {
1.411     www      9290: 	    $result.='<br /><tt>'.$id.'</tt> - ';
1.408     albertel 9291: 	    if ($correct_ids{$id} eq 'specified') {
                   9292: 		$result.=&mt('specified');
                   9293: 	    } else {
                   9294: 		my ($uname,$udom)=split(/\:/,$correct_ids{$id});
                   9295: 		$result.=&Apache::loncommon::plainname($uname,$udom);
                   9296: 	    }
                   9297: 	    $number++;
                   9298: 	}
1.411     www      9299:         $result.="</p>\n";
1.408     albertel 9300: 	if ($number==0) {
                   9301: 	    $result.='<span class="LC_error">'.&mt('No IDs found to determine correct answer').'</span>';
                   9302: 	    return $result.&show_grading_menu_form($symb);
                   9303: 	}
1.404     www      9304:     }
1.405     www      9305:     if (length($env{'form.upfile'}) < 2) {
1.407     albertel 9306:         $result.=&mt('[_1] Error: [_2] The file you attempted to upload, [_3] contained no information. Please check that you entered the correct filename.',
                   9307: 		     '<span class="LC_error">',
                   9308: 		     '</span>',
                   9309: 		     '<span class="LC_filename">'.&HTML::Entities::encode($env{'form.upfile.filename'},'<>&"').'</span>');
1.405     www      9310:         return $result.&show_grading_menu_form($symb);
                   9311:     }
1.410     www      9312: 
                   9313: # Were able to get all the info needed, now analyze the file
                   9314: 
1.411     www      9315:     $result.=&Apache::loncommon::studentbrowser_javascript();
1.418     albertel 9316:     $symb = &Apache::lonenc::check_encrypt($symb);
1.410     www      9317:     my $heading=&mt('Scanning clicker file');
                   9318:     $result.=(<<ENDHEADER);
                   9319: <br /><table width="100%" border="0"><tr><td bgcolor="#777777">
                   9320: <table width="100%" border="0"><tr bgcolor="#e6ffff"><td>
1.596.2.4  raeburn  9321: <b>$heading</b></td></tr><tr bgcolor="#ffffe6"><td>
1.410     www      9322: <form method="post" action="/adm/grades" name="clickeranalysis">
                   9323: <input type="hidden" name="symb" value="$symb" />
                   9324: <input type="hidden" name="command" value="assignclickergrades" />
                   9325: <input type="hidden" name="probTitle" value="$env{'form.probTitle'}" />
                   9326: <input type="hidden" name="saveState"  value="$env{'form.saveState'}" />
1.411     www      9327: <input type="hidden" name="gradingmechanism" value="$env{'form.gradingmechanism'}" />
                   9328: <input type="hidden" name="pcorrect" value="$env{'form.pcorrect'}" />
                   9329: <input type="hidden" name="pincorrect" value="$env{'form.pincorrect'}" />
1.410     www      9330: ENDHEADER
1.522     www      9331:     if ($env{'form.gradingmechanism'} eq 'given') {
                   9332:        $result.='<input type="hidden" name="correct:given" value="'.$env{'form.givenanswer'}.'" />';
                   9333:     } 
1.408     albertel 9334:     my %responses;
                   9335:     my @questiontitles;
1.405     www      9336:     my $errormsg='';
                   9337:     my $number=0;
                   9338:     if ($env{'form.upfiletype'} eq 'iclicker') {
1.408     albertel 9339: 	($errormsg,$number)=&iclicker_eval(\@questiontitles,\%responses);
1.406     www      9340:     }
1.419     www      9341:     if ($env{'form.upfiletype'} eq 'interwrite') {
                   9342:         ($errormsg,$number)=&interwrite_eval(\@questiontitles,\%responses);
                   9343:     }
1.596.2.12.2.  (raeburn 9344:):     if ($env{'form.upfiletype'} eq 'turning') {
                   9345:):         ($errormsg,$number)=&turning_eval(\@questiontitles,\%responses);
                   9346:):     }
1.411     www      9347:     $result.='<br />'.&mt('Found [_1] question(s)',$number).'<br />'.
                   9348:              '<input type="hidden" name="number" value="'.$number.'" />'.
                   9349:              &mt('Awarding [_1] percent for correct and [_2] percent for incorrect responses',
                   9350:                  $env{'form.pcorrect'},$env{'form.pincorrect'}).
                   9351:              '<br />';
1.522     www      9352:     if (($env{'form.gradingmechanism'} eq 'given') && ($number!=$foundgiven)) {
                   9353:        $result.='<span class="LC_error">'.&mt('Number of given answers does not agree with number of questions in file.').'</span>';
                   9354:        return $result.&show_grading_menu_form($symb);
                   9355:     } 
1.414     www      9356: # Remember Question Titles
                   9357: # FIXME: Possibly need delimiter other than ":"
                   9358:     for (my $i=0;$i<$number;$i++) {
                   9359:         $result.='<input type="hidden" name="question:'.$i.'" value="'.
                   9360:                  &HTML::Entities::encode($questiontitles[$i],'"&<>').'" />';
                   9361:     }
1.411     www      9362:     my $correct_count=0;
                   9363:     my $student_count=0;
                   9364:     my $unknown_count=0;
1.414     www      9365: # Match answers with usernames
                   9366: # FIXME: Possibly need delimiter other than ":"
1.409     albertel 9367:     foreach my $id (keys(%responses)) {
1.410     www      9368:        if ($correct_ids{$id}) {
1.414     www      9369:           $result.="\n".'<input type="hidden" name="correct:'.$correct_count.':'.$correct_ids{$id}.'" value="'.$responses{$id}.'" />';
1.411     www      9370:           $correct_count++;
1.410     www      9371:        } elsif ($clicker_ids{$id}) {
1.437     www      9372:           if ($clicker_ids{$id}=~/\,/) {
                   9373: # More than one user with the same clicker!
                   9374:              $result.="\n<hr />".&mt('Clicker registered more than once').": <tt>".$id."</tt><br />";
                   9375:              $result.="\n".'<input type="hidden" name="unknown:'.$id.'" value="'.$responses{$id}.'" />'.
                   9376:                            "<select name='multi".$id."'>";
                   9377:              foreach my $reguser (sort(split(/\,/,$clicker_ids{$id}))) {
                   9378:                  $result.="<option value='".$reguser."'>".&Apache::loncommon::plainname(split(/\:/,$reguser)).' ('.$reguser.')</option>';
                   9379:              }
                   9380:              $result.='</select>';
                   9381:              $unknown_count++;
                   9382:           } else {
                   9383: # Good: found one and only one user with the right clicker
                   9384:              $result.="\n".'<input type="hidden" name="student:'.$clicker_ids{$id}.'" value="'.$responses{$id}.'" />';
                   9385:              $student_count++;
                   9386:           }
1.410     www      9387:        } else {
1.411     www      9388:           $result.="\n<hr />".&mt('Unregistered Clicker')." <tt>".$id."</tt><br />";
                   9389:           $result.="\n".'<input type="hidden" name="unknown:'.$id.'" value="'.$responses{$id}.'" />'.
                   9390:                    "\n".&mt("Username").": <input type='text' name='uname".$id."' />&nbsp;".
                   9391:                    "\n".&mt("Domain").": ".
                   9392:                    &Apache::loncommon::select_dom_form($env{'course.'.$env{'request.course.id'}.'.domain'},'udom'.$id).'&nbsp;'.
1.596.2.4  raeburn  9393:                    &Apache::loncommon::selectstudent_link('clickeranalysis','uname'.$id,'udom'.$id,0,$id);
1.411     www      9394:           $unknown_count++;
1.410     www      9395:        }
1.405     www      9396:     }
1.412     www      9397:     $result.='<hr />'.
                   9398:              &mt('Found [_1] registered and [_2] unregistered clickers.',$student_count,$unknown_count);
1.521     www      9399:     if (($env{'form.gradingmechanism'} ne 'attendance') && ($env{'form.gradingmechanism'} ne 'given')) {
1.412     www      9400:        if ($correct_count==0) {
                   9401:           $errormsg.="Found no correct answers answers for grading!";
                   9402:        } elsif ($correct_count>1) {
1.414     www      9403:           $result.='<br /><span class="LC_warning">'.&mt("Found [_1] entries for grading!",$correct_count).'</span>';
1.412     www      9404:        }
                   9405:     }
1.428     www      9406:     if ($number<1) {
                   9407:        $errormsg.="Found no questions.";
                   9408:     }
1.412     www      9409:     if ($errormsg) {
                   9410:        $result.='<br /><span class="LC_error">'.&mt($errormsg).'</span>';
                   9411:     } else {
                   9412:        $result.='<br /><input type="submit" name="finalize" value="'.&mt('Finalize Grading').'" />';
                   9413:     }
                   9414:     $result.='</form></td></tr></table>'."\n".
1.410     www      9415:              '</td></tr></table><br /><br />'."\n";
1.404     www      9416:     return $result.&show_grading_menu_form($symb);
1.400     www      9417: }
                   9418: 
1.405     www      9419: sub iclicker_eval {
1.406     www      9420:     my ($questiontitles,$responses)=@_;
1.405     www      9421:     my $number=0;
                   9422:     my $errormsg='';
                   9423:     foreach my $line (split(/[\n\r]/,$env{'form.upfile'})) {
1.410     www      9424:         my %components=&Apache::loncommon::record_sep($line);
                   9425:         my @entries=map {$components{$_}} (sort(keys(%components)));
1.408     albertel 9426: 	if ($entries[0] eq 'Question') {
                   9427: 	    for (my $i=3;$i<$#entries;$i+=6) {
                   9428: 		$$questiontitles[$number]=$entries[$i];
                   9429: 		$number++;
                   9430: 	    }
                   9431: 	}
                   9432: 	if ($entries[0]=~/^\#/) {
                   9433: 	    my $id=$entries[0];
                   9434: 	    my @idresponses;
                   9435: 	    $id=~s/^[\#0]+//;
                   9436: 	    for (my $i=0;$i<$number;$i++) {
                   9437: 		my $idx=3+$i*6;
1.596.2.4  raeburn  9438:                 $entries[$idx]=~s/[^a-zA-Z0-9\.\*\-\+]+//g;
1.408     albertel 9439: 		push(@idresponses,$entries[$idx]);
                   9440: 	    }
                   9441: 	    $$responses{$id}=join(',',@idresponses);
                   9442: 	}
1.405     www      9443:     }
                   9444:     return ($errormsg,$number);
                   9445: }
                   9446: 
1.419     www      9447: sub interwrite_eval {
                   9448:     my ($questiontitles,$responses)=@_;
                   9449:     my $number=0;
                   9450:     my $errormsg='';
1.420     www      9451:     my $skipline=1;
                   9452:     my $questionnumber=0;
                   9453:     my %idresponses=();
1.419     www      9454:     foreach my $line (split(/[\n\r]/,$env{'form.upfile'})) {
                   9455:         my %components=&Apache::loncommon::record_sep($line);
                   9456:         my @entries=map {$components{$_}} (sort(keys(%components)));
1.420     www      9457:         if ($entries[1] eq 'Time') { $skipline=0; next; }
                   9458:         if ($entries[1] eq 'Response') { $skipline=1; }
                   9459:         next if $skipline;
                   9460:         if ($entries[0]!=$questionnumber) {
                   9461:            $questionnumber=$entries[0];
                   9462:            $$questiontitles[$number]=&mt('Question [_1]',$questionnumber);
                   9463:            $number++;
1.419     www      9464:         }
1.420     www      9465:         my $id=$entries[4];
                   9466:         $id=~s/^[\#0]+//;
1.421     www      9467:         $id=~s/^v\d*\://i;
                   9468:         $id=~s/[\-\:]//g;
1.420     www      9469:         $idresponses{$id}[$number]=$entries[6];
                   9470:     }
1.524     raeburn  9471:     foreach my $id (keys(%idresponses)) {
1.420     www      9472:        $$responses{$id}=join(',',@{$idresponses{$id}});
                   9473:        $$responses{$id}=~s/^\s*\,//;
1.419     www      9474:     }
                   9475:     return ($errormsg,$number);
                   9476: }
                   9477: 
1.596.2.12.2.  (raeburn 9478:): sub turning_eval {
                   9479:):     my ($questiontitles,$responses)=@_;
                   9480:):     my $number=0;
                   9481:):     my $errormsg='';
                   9482:):     foreach my $line (split(/[\n\r]/,$env{'form.upfile'})) {
                   9483:):         my %components=&Apache::loncommon::record_sep($line);
                   9484:):         my @entries=map {$components{$_}} (sort(keys(%components)));
                   9485:):         if ($#entries>$number) { $number=$#entries; }
                   9486:):         my $id=$entries[0];
                   9487:):         my @idresponses;
                   9488:):         $id=~s/^[\#0]+//;
                   9489:):         unless ($id) { next; }
                   9490:):         for (my $idx=1;$idx<=$#entries;$idx++) {
                   9491:):             $entries[$idx]=~s/\,/\;/g;
                   9492:):             $entries[$idx]=~s/[^a-zA-Z0-9\.\*\-\+\;]+//g;
                   9493:):             push(@idresponses,$entries[$idx]);
                   9494:):         }
                   9495:):         $$responses{$id}=join(',',@idresponses);
                   9496:):     }
                   9497:):     for (my $i=1; $i<=$number; $i++) {
                   9498:):         $$questiontitles[$i]=&mt('Question [_1]',$i);
                   9499:):     }
                   9500:):     return ($errormsg,$number);
                   9501:): }
                   9502:): 
1.414     www      9503: sub assign_clicker_grades {
                   9504:     my ($r)=@_;
                   9505:     my ($symb)=&get_symb($r);
                   9506:     if (!$symb) {return '';}
1.416     www      9507: # See which part we are saving to
1.582     raeburn  9508:     my $res_error;
                   9509:     my ($partlist,$handgrade,$responseType) = &response_type($symb,\$res_error);
                   9510:     if ($res_error) {
                   9511:         return &navmap_errormsg();
                   9512:     }
1.416     www      9513: # FIXME: This should probably look for the first handgradeable part
                   9514:     my $part=$$partlist[0];
                   9515: # Start screen output
1.596.2.10  raeburn  9516:     my ($result) = &showResourceInfo($symb,$env{'form.probTitle'});
1.596.2.4  raeburn  9517: 
1.596.2.10  raeburn  9518:     $result .= '<br />'.
                   9519:                &Apache::loncommon::start_data_table().
1.596.2.4  raeburn  9520:                &Apache::loncommon::start_data_table_header_row().
                   9521:                '<th>'.&mt('Assigning grades based on clicker file').'</th>'.
                   9522:                &Apache::loncommon::end_data_table_header_row().
                   9523:                &Apache::loncommon::start_data_table_row().'<td>';
1.416     www      9524: 
1.414     www      9525: # Get correct result
                   9526: # FIXME: Possibly need delimiter other than ":"
                   9527:     my @correct=();
1.415     www      9528:     my $gradingmechanism=$env{'form.gradingmechanism'};
                   9529:     my $number=$env{'form.number'};
                   9530:     if ($gradingmechanism ne 'attendance') {
1.414     www      9531:        foreach my $key (keys(%env)) {
                   9532:           if ($key=~/^form\.correct\:/) {
                   9533:              my @input=split(/\,/,$env{$key});
                   9534:              for (my $i=0;$i<=$#input;$i++) {
                   9535:                  if (($correct[$i]) && ($input[$i]) &&
                   9536:                      ($correct[$i] ne $input[$i])) {
                   9537:                     $result.='<br /><span class="LC_warning">'.
                   9538:                              &mt('More than one correct result given for question "[_1]": [_2] versus [_3].',
                   9539:                                  $env{'form.question:'.$i},$correct[$i],$input[$i]).'</span>';
1.596.2.4  raeburn  9540:                  } elsif (($input[$i]) || ($input[$i] eq '0')) {
1.414     www      9541:                     $correct[$i]=$input[$i];
                   9542:                  }
                   9543:              }
                   9544:           }
                   9545:        }
1.415     www      9546:        for (my $i=0;$i<$number;$i++) {
1.596.2.4  raeburn  9547:           if ((!$correct[$i]) && ($correct[$i] ne '0')) {
1.414     www      9548:              $result.='<br /><span class="LC_error">'.
                   9549:                       &mt('No correct result given for question "[_1]"!',
                   9550:                           $env{'form.question:'.$i}).'</span>';
                   9551:           }
                   9552:        }
1.596.2.4  raeburn  9553:        $result.='<br />'.&mt("Correct answer: [_1]",join(', ',map { ((($_) || ($_ eq '0'))?$_:'-') } @correct));
1.414     www      9554:     }
                   9555: # Start grading
1.415     www      9556:     my $pcorrect=$env{'form.pcorrect'};
                   9557:     my $pincorrect=$env{'form.pincorrect'};
1.416     www      9558:     my $storecount=0;
1.596.2.4  raeburn  9559:     my %users=();
1.415     www      9560:     foreach my $key (keys(%env)) {
1.420     www      9561:        my $user='';
1.415     www      9562:        if ($key=~/^form\.student\:(.*)$/) {
1.420     www      9563:           $user=$1;
                   9564:        }
                   9565:        if ($key=~/^form\.unknown\:(.*)$/) {
                   9566:           my $id=$1;
                   9567:           if (($env{'form.uname'.$id}) && ($env{'form.udom'.$id})) {
                   9568:              $user=$env{'form.uname'.$id}.':'.$env{'form.udom'.$id};
1.437     www      9569:           } elsif ($env{'form.multi'.$id}) {
                   9570:              $user=$env{'form.multi'.$id};
1.420     www      9571:           }
                   9572:        }
1.596.2.4  raeburn  9573:        if ($user) {
                   9574:           if ($users{$user}) {
                   9575:              $result.='<br /><span class="LC_warning">'.
                   9576:                       &mt("More than one entry found for <tt>[_1]</tt>!",$user).
                   9577:                       '</span><br />';
                   9578:           }
                   9579:           $users{$user}=1;
1.415     www      9580:           my @answer=split(/\,/,$env{$key});
                   9581:           my $sum=0;
1.522     www      9582:           my $realnumber=$number;
1.415     www      9583:           for (my $i=0;$i<$number;$i++) {
1.576     www      9584:              if  ($correct[$i] eq '-') {
                   9585:                 $realnumber--;
                   9586:              } elsif ($answer[$i]) {
1.415     www      9587:                 if ($gradingmechanism eq 'attendance') {
                   9588:                    $sum+=$pcorrect;
1.576     www      9589:                 } elsif ($correct[$i] eq '*') {
1.522     www      9590:                    $sum+=$pcorrect;
1.415     www      9591:                 } else {
1.596.2.4  raeburn  9592: # We actually grade if correct or not
                   9593:                    my $increment=$pincorrect;
                   9594: # Special case: numerical answer "0"
                   9595:                    if ($correct[$i] eq '0') {
                   9596:                       if ($answer[$i]=~/^[0\.]+$/) {
                   9597:                          $increment=$pcorrect;
                   9598:                       }
                   9599: # General numerical answer, both evaluate to something non-zero
                   9600:                    } elsif ((1.0*$correct[$i]!=0) && (1.0*$answer[$i]!=0)) {
                   9601:                       if (1.0*$correct[$i]==1.0*$answer[$i]) {
                   9602:                          $increment=$pcorrect;
                   9603:                       }
                   9604: # Must be just alphanumeric
                   9605:                    } elsif ($answer[$i] eq $correct[$i]) {
                   9606:                       $increment=$pcorrect;
1.415     www      9607:                    }
1.596.2.4  raeburn  9608:                    $sum+=$increment;
1.415     www      9609:                 }
                   9610:              }
                   9611:           }
1.522     www      9612:           my $ave=$sum/(100*$realnumber);
1.416     www      9613: # Store
                   9614:           my ($username,$domain)=split(/\:/,$user);
                   9615:           my %grades=();
                   9616:           $grades{"resource.$part.solved"}='correct_by_override';
                   9617:           $grades{"resource.$part.awarded"}=$ave;
                   9618:           $grades{"resource.regrader"}="$env{'user.name'}:$env{'user.domain'}";
                   9619:           my $returncode=&Apache::lonnet::cstore(\%grades,$symb,
                   9620:                                                  $env{'request.course.id'},
                   9621:                                                  $domain,$username);
                   9622:           if ($returncode ne 'ok') {
                   9623:              $result.="<br /><span class=\"LC_error\">Failed to save student $username:$domain. Message when trying to save was ($returncode)</span>";
                   9624:           } else {
                   9625:              $storecount++;
                   9626:           }
1.415     www      9627:        }
                   9628:     }
                   9629: # We are done
1.549     hauer    9630:     $result.='<br />'.&mt('Successfully stored grades for [quant,_1,student].',$storecount).
1.596.2.4  raeburn  9631:              '</td>'.
                   9632:              &Apache::loncommon::end_data_table_row().
                   9633:              &Apache::loncommon::end_data_table()."<br /><br />\n";
1.414     www      9634:     return $result.&show_grading_menu_form($symb);
                   9635: }
                   9636: 
1.582     raeburn  9637: sub navmap_errormsg {
                   9638:     return '<div class="LC_error">'.
                   9639:            &mt('An error occurred retrieving information about resources in the course.').'<br />'.
1.595     raeburn  9640:            &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  9641:            '</div>';
                   9642: }
                   9643: 
1.1       albertel 9644: sub handler {
1.41      ng       9645:     my $request=$_[0];
1.434     albertel 9646:     &reset_caches();
1.596.2.4  raeburn  9647:     if ($request->header_only) {
                   9648:         &Apache::loncommon::content_type($request,'text/html');
                   9649:         $request->send_http_header;
                   9650:         return OK;
1.41      ng       9651:     }
                   9652:     &Apache::loncommon::get_unprocessed_cgi($ENV{'QUERY_STRING'});
1.596.2.4  raeburn  9653: 
1.324     albertel 9654:     my $symb=&get_symb($request,1);
1.160     albertel 9655:     my @commands=&Apache::loncommon::get_env_multiple('form.command');
                   9656:     my $command=$commands[0];
1.447     foxr     9657: 
1.160     albertel 9658:     if ($#commands > 0) {
                   9659: 	&Apache::lonnet::logthis("grades got multiple commands ".join(':',@commands));
                   9660:     }
1.447     foxr     9661: 
1.513     foxr     9662:     $ssi_error = 0;
1.535     raeburn  9663:     my $brcrum = [{href=>"/adm/grades",text=>"Grading"}];
1.596.2.4  raeburn  9664:     my $start_page = &Apache::loncommon::start_page('Grading',undef,
1.596.2.5  raeburn  9665:                                           {'bread_crumbs' => $brcrum});
1.324     albertel 9666:     if ($symb eq '' && $command eq '') {
1.257     albertel 9667: 	if ($env{'user.adv'}) {
1.596.2.4  raeburn  9668:             &Apache::loncommon::content_type($request,'text/html');
                   9669:             $request->send_http_header;
                   9670:             $request->print($start_page);
1.257     albertel 9671: 	    if (($env{'form.codeone'}) && ($env{'form.codetwo'}) &&
                   9672: 		($env{'form.codethree'})) {
                   9673: 		my $token=$env{'form.codeone'}.'*'.$env{'form.codetwo'}.'*'.
                   9674: 		    $env{'form.codethree'};
1.41      ng       9675: 		my ($tsymb,$tuname,$tudom,$tcrsid)=
                   9676: 		    &Apache::lonnet::checkin($token);
                   9677: 		if ($tsymb) {
1.137     albertel 9678: 		    my ($map,$id,$url)=&Apache::lonnet::decode_symb($tsymb);
1.41      ng       9679: 		    if (&Apache::lonnet::allowed('mgr',$tcrsid)) {
1.513     foxr     9680: 			$request->print(&ssi_with_retries('/res/'.$url, $ssi_retries,
1.99      albertel 9681: 					  ('grade_username' => $tuname,
                   9682: 					   'grade_domain' => $tudom,
                   9683: 					   'grade_courseid' => $tcrsid,
                   9684: 					   'grade_symb' => $tsymb)));
1.41      ng       9685: 		    } else {
1.45      ng       9686: 			$request->print('<h3>Not authorized: '.$token.'</h3>');
1.99      albertel 9687: 		    }
1.41      ng       9688: 		} else {
1.45      ng       9689: 		    $request->print('<h3>Not a valid DocID: '.$token.'</h3>');
1.41      ng       9690: 		}
1.14      www      9691: 	    } else {
1.41      ng       9692: 		$request->print(&Apache::lonxml::tokeninputfield());
                   9693: 	    }
1.596.2.4  raeburn  9694:         } elsif ($env{'request.course.id'}) {
                   9695:             &init_perm(); 
                   9696:             if (!%perm) {
                   9697:                 $request->internal_redirect('/adm/quickgrades');
                   9698:             } else {
                   9699:                 &Apache::loncommon::content_type($request,'text/html');
                   9700:                 $request->send_http_header;
                   9701:                 $request->print($start_page);
                   9702:             }
                   9703:         }
1.41      ng       9704:     } else {
1.596.2.4  raeburn  9705:         &init_perm();
                   9706:         if (!$env{'request.course.id'}) {
1.596.2.11  raeburn  9707:             unless ((&Apache::lonnet::allowed('usc',$env{'request.role.domain'})) &&
                   9708:                     ($command =~ /^scantronupload/)) {
                   9709:                 # Not in a course.
                   9710:                 $env{'user.error.msg'}="/adm/grades::vgr:0:0:Cannot display grades page outside course context";
                   9711:                 return HTTP_NOT_ACCEPTABLE;
                   9712:             }
1.596.2.4  raeburn  9713:         } elsif (!%perm) {
                   9714:             $request->internal_redirect('/adm/quickgrades');
                   9715:         }
                   9716:         &Apache::loncommon::content_type($request,'text/html');
                   9717:         $request->send_http_header;
                   9718:         $request->print($start_page);
1.104     albertel 9719: 	if ($command eq 'submission' && $perm{'vgr'}) {
1.257     albertel 9720: 	    ($env{'form.student'} eq '' ? &listStudents($request) : &submission($request,0,0));
1.103     albertel 9721: 	} elsif ($command eq 'pickStudentPage' && $perm{'vgr'}) {
1.68      ng       9722: 	    &pickStudentPage($request);
1.103     albertel 9723: 	} elsif ($command eq 'displayPage' && $perm{'vgr'}) {
1.68      ng       9724: 	    &displayPage($request);
1.104     albertel 9725: 	} elsif ($command eq 'gradeByPage' && $perm{'mgr'}) {
1.71      ng       9726: 	    &updateGradeByPage($request);
1.104     albertel 9727: 	} elsif ($command eq 'processGroup' && $perm{'vgr'}) {
1.41      ng       9728: 	    &processGroup($request);
1.104     albertel 9729: 	} elsif ($command eq 'gradingmenu' && $perm{'vgr'}) {
1.443     banghart 9730: 	    $request->print(&grading_menu($request));
                   9731: 	} elsif ($command eq 'submit_options' && $perm{'vgr'}) {
                   9732: 	    $request->print(&submit_options($request));
1.104     albertel 9733: 	} elsif ($command eq 'viewgrades' && $perm{'vgr'}) {
1.41      ng       9734: 	    $request->print(&viewgrades($request));
1.104     albertel 9735: 	} elsif ($command eq 'handgrade' && $perm{'mgr'}) {
1.41      ng       9736: 	    $request->print(&processHandGrade($request));
1.106     albertel 9737: 	} elsif ($command eq 'editgrades' && $perm{'mgr'}) {
1.41      ng       9738: 	    $request->print(&editgrades($request));
1.106     albertel 9739: 	} elsif ($command eq 'verify' && $perm{'vgr'}) {
1.41      ng       9740: 	    $request->print(&verifyreceipt($request));
1.400     www      9741:         } elsif ($command eq 'processclicker' && $perm{'mgr'}) {
                   9742:             $request->print(&process_clicker($request));
                   9743:         } elsif ($command eq 'processclickerfile' && $perm{'mgr'}) {
                   9744:             $request->print(&process_clicker_file($request));
1.414     www      9745:         } elsif ($command eq 'assignclickergrades' && $perm{'mgr'}) {
                   9746:             $request->print(&assign_clicker_grades($request));
1.106     albertel 9747: 	} elsif ($command eq 'csvform' && $perm{'mgr'}) {
1.72      ng       9748: 	    $request->print(&upcsvScores_form($request));
1.106     albertel 9749: 	} elsif ($command eq 'csvupload' && $perm{'mgr'}) {
1.41      ng       9750: 	    $request->print(&csvupload($request));
1.106     albertel 9751: 	} elsif ($command eq 'csvuploadmap' && $perm{'mgr'} ) {
1.41      ng       9752: 	    $request->print(&csvuploadmap($request));
1.246     albertel 9753: 	} elsif ($command eq 'csvuploadoptions' && $perm{'mgr'}) {
1.257     albertel 9754: 	    if ($env{'form.associate'} ne 'Reverse Association') {
1.246     albertel 9755: 		$request->print(&csvuploadoptions($request));
1.41      ng       9756: 	    } else {
1.257     albertel 9757: 		if ( $env{'form.upfile_associate'} ne 'reverse' ) {
                   9758: 		    $env{'form.upfile_associate'} = 'reverse';
1.41      ng       9759: 		} else {
1.257     albertel 9760: 		    $env{'form.upfile_associate'} = 'forward';
1.41      ng       9761: 		}
                   9762: 		$request->print(&csvuploadmap($request));
                   9763: 	    }
1.246     albertel 9764: 	} elsif ($command eq 'csvuploadassign' && $perm{'mgr'} ) {
                   9765: 	    $request->print(&csvuploadassign($request));
1.106     albertel 9766: 	} elsif ($command eq 'scantron_selectphase' && $perm{'mgr'}) {
1.75      albertel 9767: 	    $request->print(&scantron_selectphase($request));
1.203     albertel 9768:  	} elsif ($command eq 'scantron_warning' && $perm{'mgr'}) {
                   9769:  	    $request->print(&scantron_do_warning($request));
1.142     albertel 9770: 	} elsif ($command eq 'scantron_validate' && $perm{'mgr'}) {
                   9771: 	    $request->print(&scantron_validate_file($request));
1.106     albertel 9772: 	} elsif ($command eq 'scantron_process' && $perm{'mgr'}) {
1.82      albertel 9773: 	    $request->print(&scantron_process_students($request));
1.157     albertel 9774:  	} elsif ($command eq 'scantronupload' && 
1.257     albertel 9775:  		 (&Apache::lonnet::allowed('usc',$env{'request.role.domain'})||
                   9776: 		  &Apache::lonnet::allowed('usc',$env{'request.course.id'}))) {
1.162     albertel 9777:  	    $request->print(&scantron_upload_scantron_data($request)); 
1.157     albertel 9778:  	} elsif ($command eq 'scantronupload_save' &&
1.257     albertel 9779:  		 (&Apache::lonnet::allowed('usc',$env{'request.role.domain'})||
                   9780: 		  &Apache::lonnet::allowed('usc',$env{'request.course.id'}))) {
1.157     albertel 9781:  	    $request->print(&scantron_upload_scantron_data_save($request));
1.202     albertel 9782:  	} elsif ($command eq 'scantron_download' &&
1.257     albertel 9783: 		 &Apache::lonnet::allowed('usc',$env{'request.course.id'})) {
1.162     albertel 9784:  	    $request->print(&scantron_download_scantron_data($request));
1.523     raeburn  9785:         } elsif ($command eq 'checksubmissions' && $perm{'vgr'}) {
                   9786:             $request->print(&checkscantron_results($request));     
1.106     albertel 9787: 	} elsif ($command) {
1.562     bisitz   9788: 	    $request->print('<p class="LC_error">'.&mt('Access Denied ([_1])',$command).'</p>');
1.26      albertel 9789: 	}
1.2       albertel 9790:     }
1.513     foxr     9791:     if ($ssi_error) {
                   9792: 	&ssi_print_error($request);
                   9793:     }
1.353     albertel 9794:     $request->print(&Apache::loncommon::end_page());
1.434     albertel 9795:     &reset_caches();
1.596.2.4  raeburn  9796:     return OK;
1.44      ng       9797: }
                   9798: 
1.1       albertel 9799: 1;
                   9800: 
1.13      albertel 9801: __END__;
1.531     jms      9802: 
                   9803: 
                   9804: =head1 NAME
                   9805: 
                   9806: Apache::grades
                   9807: 
                   9808: =head1 SYNOPSIS
                   9809: 
                   9810: Handles the viewing of grades.
                   9811: 
                   9812: This is part of the LearningOnline Network with CAPA project
                   9813: described at http://www.lon-capa.org.
                   9814: 
                   9815: =head1 OVERVIEW
                   9816: 
                   9817: Do an ssi with retries:
                   9818: While I'd love to factor out this with the vesrion in lonprintout,
                   9819: 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
                   9820: I'm not quite ready to invent (e.g. an ssi_with_retry object).
                   9821: 
                   9822: At least the logic that drives this has been pulled out into loncommon.
                   9823: 
                   9824: 
                   9825: 
                   9826: ssi_with_retries - Does the server side include of a resource.
                   9827:                      if the ssi call returns an error we'll retry it up to
                   9828:                      the number of times requested by the caller.
                   9829:                      If we still have a proble, no text is appended to the
                   9830:                      output and we set some global variables.
                   9831:                      to indicate to the caller an SSI error occurred.  
                   9832:                      All of this is supposed to deal with the issues described
                   9833:                      in LonCAPA BZ 5631 see:
                   9834:                      http://bugs.lon-capa.org/show_bug.cgi?id=5631
                   9835:                      by informing the user that this happened.
                   9836: 
                   9837: Parameters:
                   9838:   resource   - The resource to include.  This is passed directly, without
                   9839:                interpretation to lonnet::ssi.
                   9840:   form       - The form hash parameters that guide the interpretation of the resource
                   9841:                
                   9842:   retries    - Number of retries allowed before giving up completely.
                   9843: Returns:
                   9844:   On success, returns the rendered resource identified by the resource parameter.
                   9845: Side Effects:
                   9846:   The following global variables can be set:
                   9847:    ssi_error                - If an unrecoverable error occurred this becomes true.
                   9848:                               It is up to the caller to initialize this to false
                   9849:                               if desired.
                   9850:    ssi_error_resource  - If an unrecoverable error occurred, this is the value
                   9851:                               of the resource that could not be rendered by the ssi
                   9852:                               call.
                   9853:    ssi_error_message   - The error string fetched from the ssi response
                   9854:                               in the event of an error.
                   9855: 
                   9856: 
                   9857: =head1 HANDLER SUBROUTINE
                   9858: 
                   9859: ssi_with_retries()
                   9860: 
                   9861: =head1 SUBROUTINES
                   9862: 
                   9863: =over
                   9864: 
                   9865: =item scantron_get_correction() : 
                   9866: 
                   9867:    Builds the interface screen to interact with the operator to fix a
                   9868:    specific error condition in a specific scanline
                   9869: 
                   9870:  Arguments:
                   9871:     $r           - Apache request object
                   9872:     $i           - number of the current scanline
                   9873:     $scan_record - hash ref as returned from &scantron_parse_scanline()
                   9874:     $scan_config - hash ref as returned from &get_scantron_config()
                   9875:     $line        - full contents of the current scanline
                   9876:     $error       - error condition, valid values are
                   9877:                    'incorrectCODE', 'duplicateCODE',
                   9878:                    'doublebubble', 'missingbubble',
                   9879:                    'duplicateID', 'incorrectID'
                   9880:     $arg         - extra information needed
                   9881:        For errors:
                   9882:          - duplicateID   - paper number that this studentID was seen before on
                   9883:          - duplicateCODE - array ref of the paper numbers this CODE was
                   9884:                            seen on before
                   9885:          - incorrectCODE - current incorrect CODE 
                   9886:          - doublebubble  - array ref of the bubble lines that have double
                   9887:                            bubble errors
                   9888:          - missingbubble - array ref of the bubble lines that have missing
                   9889:                            bubble errors
                   9890: 
                   9891: =item  scantron_get_maxbubble() : 
                   9892: 
1.582     raeburn  9893:    Arguments:
                   9894:        $nav_error  - Reference to scalar which is a flag to indicate a
                   9895:                       failure to retrieve a navmap object.
                   9896:        if $nav_error is set to 1 by scantron_get_maxbubble(), the 
                   9897:        calling routine should trap the error condition and display the warning
                   9898:        found in &navmap_errormsg().
                   9899: 
1.596.2.12.2.  (raeburn 9900:):        $scantron_config - Reference to bubblesheet format configuration hash.
                   9901:): 
1.531     jms      9902:    Returns the maximum number of bubble lines that are expected to
                   9903:    occur. Does this by walking the selected sequence rendering the
                   9904:    resource and then checking &Apache::lonxml::get_problem_counter()
                   9905:    for what the current value of the problem counter is.
                   9906: 
                   9907:    Caches the results to $env{'form.scantron_maxbubble'},
                   9908:    $env{'form.scantron.bubble_lines.n'}, 
                   9909:    $env{'form.scantron.first_bubble_line.n'} and
                   9910:    $env{"form.scantron.sub_bubblelines.n"}
                   9911:    which are the total number of bubble, lines, the number of bubble
                   9912:    lines for response n and number of the first bubble line for response n,
                   9913:    and a comma separated list of numbers of bubble lines for sub-questions
                   9914:    (for optionresponse, matchresponse, and rankresponse items), for response n.  
                   9915: 
                   9916: 
                   9917: =item  scantron_validate_missingbubbles() : 
                   9918: 
                   9919:    Validates all scanlines in the selected file to not have any
                   9920:     answers that don't have bubbles that have not been verified
                   9921:     to be bubble free.
                   9922: 
                   9923: =item  scantron_process_students() : 
                   9924: 
1.596.2.6  raeburn  9925:    Routine that does the actual grading of the bubblesheet information.
1.531     jms      9926: 
                   9927:    The parsed scanline hash is added to %env 
                   9928: 
                   9929:    Then foreach unskipped scanline it does an &Apache::lonnet::ssi()
                   9930:    foreach resource , with the form data of
                   9931: 
                   9932: 	'submitted'     =>'scantron' 
                   9933: 	'grade_target'  =>'grade',
                   9934: 	'grade_username'=> username of student
                   9935: 	'grade_domain'  => domain of student
                   9936: 	'grade_courseid'=> of course
                   9937: 	'grade_symb'    => symb of resource to grade
                   9938: 
                   9939:     This triggers a grading pass. The problem grading code takes care
                   9940:     of converting the bubbled letter information (now in %env) into a
                   9941:     valid submission.
                   9942: 
                   9943: =item  scantron_upload_scantron_data() :
                   9944: 
1.596.2.6  raeburn  9945:     Creates the screen for adding a new bubblesheet data file to a course.
1.531     jms      9946: 
                   9947: =item  scantron_upload_scantron_data_save() : 
                   9948: 
                   9949:    Adds a provided bubble information data file to the course if user
                   9950:    has the correct privileges to do so. 
                   9951: 
                   9952: =item  valid_file() :
                   9953: 
                   9954:    Validates that the requested bubble data file exists in the course.
                   9955: 
                   9956: =item  scantron_download_scantron_data() : 
                   9957: 
                   9958:    Shows a list of the three internal files (original, corrected,
1.596.2.6  raeburn  9959:    skipped) for a specific bubblesheet data file that exists in the
1.531     jms      9960:    course.
                   9961: 
                   9962: =item  scantron_validate_ID() : 
                   9963: 
                   9964:    Validates all scanlines in the selected file to not have any
1.556     weissno  9965:    invalid or underspecified student/employee IDs
1.531     jms      9966: 
1.582     raeburn  9967: =item navmap_errormsg() :
                   9968: 
                   9969:    Returns HTML mark-up inside a <div></div> with a link to re-initialize the course.
                   9970:    Should be called whenever the request to instantiate a navmap object fails.  
                   9971: 
1.531     jms      9972: =back
                   9973: 
                   9974: =cut

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