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

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.  0.2.1(ra    4:ct-18): # $Id: grades.pm,v 1.596.2.12.2.40 2017/05/19 20:08:33 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.596.2.12.2.  0.2.1(ra   47:ct-18): use Apache::lontexconvert();
1.170     albertel   48: use String::Similarity;
1.359     www        49: use LONCAPA;
                     50: 
1.315     bowersj2   51: use POSIX qw(floor);
1.87      www        52: 
1.435     foxr       53: 
1.513     foxr       54: 
1.435     foxr       55: my %perm=();
1.596.2.12.2.  (raeburn   56:): my %old_essays=();
1.447     foxr       57: 
1.513     foxr       58: #  These variables are used to recover from ssi errors
                     59: 
                     60: my $ssi_retries = 5;
                     61: my $ssi_error;
                     62: my $ssi_error_resource;
                     63: my $ssi_error_message;
                     64: 
                     65: 
                     66: sub ssi_with_retries {
                     67:     my ($resource, $retries, %form) = @_;
                     68:     my ($content, $response) = &Apache::loncommon::ssi_with_retries($resource, $retries, %form);
                     69:     if ($response->is_error) {
                     70: 	$ssi_error          = 1;
                     71: 	$ssi_error_resource = $resource;
                     72: 	$ssi_error_message  = $response->code . " " . $response->message;
                     73:     }
                     74: 
                     75:     return $content;
                     76: 
                     77: }
                     78: #
                     79: #  Prodcuces an ssi retry failure error message to the user:
                     80: #
                     81: 
                     82: sub ssi_print_error {
                     83:     my ($r) = @_;
1.516     raeburn    84:     my $helpurl = &Apache::loncommon::top_nav_help('Helpdesk');
                     85:     $r->print('
                     86: <br />
                     87: <h2>'.&mt('An unrecoverable network error occurred:').'</h2>
                     88: <p>
                     89: '.&mt('Unable to retrieve a resource from a server:').'<br />
                     90: '.&mt('Resource:').' '.$ssi_error_resource.'<br />
                     91: '.&mt('Error:').' '.$ssi_error_message.'
                     92: </p>
                     93: <p>'.
                     94: &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 />'.
                     95: &mt('If the error persists, please contact the [_1] for assistance.',$helpurl).
                     96: '</p>');
                     97:     return;
1.513     foxr       98: }
                     99: 
1.44      ng        100: #
1.146     albertel  101: # --- Retrieve the parts from the metadata file.---
1.44      ng        102: sub getpartlist {
1.582     raeburn   103:     my ($symb,$errorref) = @_;
1.439     albertel  104: 
                    105:     my $navmap   = Apache::lonnavmaps::navmap->new();
1.582     raeburn   106:     unless (ref($navmap)) {
                    107:         if (ref($errorref)) { 
                    108:             $$errorref = 'navmap';
                    109:             return;
                    110:         }
                    111:     }
1.439     albertel  112:     my $res      = $navmap->getBySymb($symb);
                    113:     my $partlist = $res->parts();
                    114:     my $url      = $res->src();
                    115:     my @metakeys = split(/,/,&Apache::lonnet::metadata($url,'keys'));
                    116: 
1.146     albertel  117:     my @stores;
1.439     albertel  118:     foreach my $part (@{ $partlist }) {
1.146     albertel  119: 	foreach my $key (@metakeys) {
                    120: 	    if ($key =~ m/^stores_\Q$part\E_/) { push(@stores,$key); }
                    121: 	}
                    122:     }
                    123:     return @stores;
1.2       albertel  124: }
                    125: 
1.44      ng        126: # --- Get the symbolic name of a problem and the url
1.324     albertel  127: sub get_symb {
1.173     albertel  128:     my ($request,$silent) = @_;
1.596.2.12.2.  (raeburn  129:):     my $symb=$env{'form.symb'};
                    130:):     unless ($symb) {
                    131:):         (my $url=$env{'form.url'}) =~ s-^http://($ENV{'SERVER_NAME'}|$ENV{'HTTP_HOST'})--;
                    132:):         $symb = &Apache::lonnet::symbread($url);
                    133:):         if ($symb eq '') { 
                    134:): 	    if (!$silent) {
                    135:):                 $request->print(&mt("Unable to handle ambiguous references: [_1].",$url));
                    136:): 	        return ();
                    137:): 	    }
                    138:):         }
1.173     albertel  139:     }
1.418     albertel  140:     &Apache::lonenc::check_decrypt(\$symb);
1.324     albertel  141:     return ($symb);
1.32      ng        142: }
                    143: 
1.129     ng        144: #--- Format fullname, username:domain if different for display
                    145: #--- Use anywhere where the student names are listed
                    146: sub nameUserString {
                    147:     my ($type,$fullname,$uname,$udom) = @_;
                    148:     if ($type eq 'header') {
1.485     albertel  149: 	return '<b>&nbsp;'.&mt('Fullname').'&nbsp;</b><span class="LC_internal_info">('.&mt('Username').')</span>';
1.129     ng        150:     } else {
1.398     albertel  151: 	return '&nbsp;'.$fullname.'<span class="LC_internal_info">&nbsp;('.$uname.
                    152: 	    ($env{'user.domain'} eq $udom ? '' : ' ('.$udom.')').')</span>';
1.129     ng        153:     }
                    154: }
                    155: 
1.44      ng        156: #--- Get the partlist and the response type for a given problem. ---
                    157: #--- Indicate if a response type is coded handgraded or not. ---
1.39      ng        158: sub response_type {
1.582     raeburn   159:     my ($symb,$response_error) = @_;
1.377     albertel  160: 
                    161:     my $navmap = Apache::lonnavmaps::navmap->new();
1.582     raeburn   162:     unless (ref($navmap)) {
                    163:         if (ref($response_error)) {
                    164:             $$response_error = 1;
                    165:         }
                    166:         return;
                    167:     }
1.377     albertel  168:     my $res = $navmap->getBySymb($symb);
1.593     raeburn   169:     unless (ref($res)) {
                    170:         $$response_error = 1;
                    171:         return;
                    172:     }
1.377     albertel  173:     my $partlist = $res->parts();
1.392     albertel  174:     my %vPart = 
                    175: 	map { $_ => 1 } (&Apache::loncommon::get_env_multiple('form.vPart'));
1.377     albertel  176:     my (%response_types,%handgrade);
                    177:     foreach my $part (@{ $partlist }) {
1.392     albertel  178: 	next if (%vPart && !exists($vPart{$part}));
                    179: 
1.377     albertel  180: 	my @types = $res->responseType($part);
                    181: 	my @ids = $res->responseIds($part);
                    182: 	for (my $i=0; $i < scalar(@ids); $i++) {
                    183: 	    $response_types{$part}{$ids[$i]} = $types[$i];
                    184: 	    $handgrade{$part.'_'.$ids[$i]} = 
                    185: 		&Apache::lonnet::EXT('resource.'.$part.'_'.$ids[$i].
                    186: 				     '.handgrade',$symb);
1.41      ng        187: 	}
                    188:     }
1.377     albertel  189:     return ($partlist,\%handgrade,\%response_types);
1.39      ng        190: }
                    191: 
1.375     albertel  192: sub flatten_responseType {
                    193:     my ($responseType) = @_;
                    194:     my @part_response_id =
                    195: 	map { 
                    196: 	    my $part = $_;
                    197: 	    map {
                    198: 		[$part,$_]
                    199: 		} sort(keys(%{ $responseType->{$part} }));
                    200: 	} sort(keys(%$responseType));
                    201:     return @part_response_id;
                    202: }
                    203: 
1.207     albertel  204: sub get_display_part {
1.324     albertel  205:     my ($partID,$symb)=@_;
1.207     albertel  206:     my $display=&Apache::lonnet::EXT('resource.'.$partID.'.display',$symb);
                    207:     if (defined($display) and $display ne '') {
1.577     bisitz    208:         $display.= ' (<span class="LC_internal_info">'
                    209:                   .&mt('Part ID: [_1]',$partID).'</span>)';
1.207     albertel  210:     } else {
                    211: 	$display=$partID;
                    212:     }
                    213:     return $display;
                    214: }
1.269     raeburn   215: 
1.118     ng        216: #--- Show resource title
                    217: #--- and parts and response type
                    218: sub showResourceInfo {
1.582     raeburn   219:     my ($symb,$probTitle,$checkboxes,$res_error) = @_;
1.398     albertel  220:     my $result = '<h3>'.&mt('Current Resource').': '.$probTitle.'</h3>'."\n";
1.582     raeburn   221:     my ($partlist,$handgrade,$responseType) = &response_type($symb,$res_error);
                    222:     if (ref($res_error)) {
                    223:         if ($$res_error) {
                    224:             return;
                    225:         }
                    226:     }
1.584     bisitz    227:     $result.=&Apache::loncommon::start_data_table()
                    228:             .&Apache::loncommon::start_data_table_header_row();
                    229:     if ($checkboxes) {
                    230:         $result.='<th>&nbsp;</th>';
                    231:     }
                    232:     $result.='<th>'.&mt('Problem Part').'</th>'
                    233:             .'<th>'.&mt('Res. ID').'</th>'
                    234:             .'<th>'.&mt('Type').'</th>'
                    235:             .&Apache::loncommon::end_data_table_header_row();
1.126     ng        236:     my %resptype = ();
1.122     ng        237:     my $hdgrade='no';
1.154     albertel  238:     my %partsseen;
1.524     raeburn   239:     foreach my $partID (sort(keys(%$responseType))) {
1.584     bisitz    240:         foreach my $resID (sort(keys(%{ $responseType->{$partID} }))) {
                    241:             my $handgrade=$$handgrade{$partID.'_'.$resID};
                    242:             my $responsetype = $responseType->{$partID}->{$resID};
                    243:             $hdgrade = $handgrade if ($handgrade eq 'yes');
                    244:             $result.=&Apache::loncommon::start_data_table_row();
                    245:             if ($checkboxes) {
                    246:                 if (exists($partsseen{$partID})) {
                    247:                     $result.="<td>&nbsp;</td>";
                    248:                 } else {
                    249:                     $result.="<td><input type='checkbox' name='vPart' value='$partID' checked='checked' /></td>";
                    250:                 }
                    251:                 $partsseen{$partID}=1;
                    252:             }
                    253:             my $display_part=&get_display_part($partID,$symb);
                    254:             $result.='<td>'.$display_part.'</td>'
                    255:                     .'<td>'.'<span class="LC_internal_info">'.$resID.'</span></td>'
                    256:                     .'<td>'.&mt($responsetype).'</td>'
1.596.2.12.2.  2(raebur  257:2): #                   .'<td><b>'.&mt('Handgrade: [_1]',$handgrade).'</b></td>'
1.584     bisitz    258:                     .&Apache::loncommon::end_data_table_row();
                    259:         }
1.118     ng        260:     }
1.584     bisitz    261:     $result.=&Apache::loncommon::end_data_table();
1.147     albertel  262:     return $result,$responseType,$hdgrade,$partlist,$handgrade;
1.118     ng        263: }
                    264: 
1.434     albertel  265: sub reset_caches {
                    266:     &reset_analyze_cache();
                    267:     &reset_perm();
1.596.2.12.2.  (raeburn  268:):     &reset_old_essays();
1.434     albertel  269: }
                    270: 
                    271: {
                    272:     my %analyze_cache;
1.557     raeburn   273:     my %analyze_cache_formkeys;
1.148     albertel  274: 
1.434     albertel  275:     sub reset_analyze_cache {
                    276: 	undef(%analyze_cache);
1.557     raeburn   277:         undef(%analyze_cache_formkeys);
1.434     albertel  278:     }
                    279: 
                    280:     sub get_analyze {
1.596.2.12.2.  (raeburn  281:): 	my ($symb,$uname,$udom,$no_increment,$add_to_hash,$type,$trial,$rndseed,$bubbles_per_row)=@_;
1.434     albertel  282: 	my $key = "$symb\0$uname\0$udom";
1.596.2.2  raeburn   283:         if ($type eq 'randomizetry') {
                    284:             if ($trial ne '') {
                    285:                 $key .= "\0".$trial;
                    286:             }
                    287:         }
1.557     raeburn   288: 	if (exists($analyze_cache{$key})) {
                    289:             my $getupdate = 0;
                    290:             if (ref($add_to_hash) eq 'HASH') {
                    291:                 foreach my $item (keys(%{$add_to_hash})) {
                    292:                     if (ref($analyze_cache_formkeys{$key}) eq 'HASH') {
                    293:                         if (!exists($analyze_cache_formkeys{$key}{$item})) {
                    294:                             $getupdate = 1;
                    295:                             last;
                    296:                         }
                    297:                     } else {
                    298:                         $getupdate = 1;
                    299:                     }
                    300:                 }
                    301:             }
                    302:             if (!$getupdate) {
                    303:                 return $analyze_cache{$key};
                    304:             }
                    305:         }
1.434     albertel  306: 
                    307: 	my (undef,undef,$url)=&Apache::lonnet::decode_symb($symb);
                    308: 	$url=&Apache::lonnet::clutter($url);
1.557     raeburn   309:         my %form = ('grade_target'      => 'analyze',
                    310:                     'grade_domain'      => $udom,
                    311:                     'grade_symb'        => $symb,
                    312:                     'grade_courseid'    =>  $env{'request.course.id'},
                    313:                     'grade_username'    => $uname,
                    314:                     'grade_noincrement' => $no_increment);
1.596.2.12.2.  (raeburn  315:):         if ($bubbles_per_row ne '') {
                    316:):             $form{'bubbles_per_row'} = $bubbles_per_row;
                    317:):         }
1.596.2.2  raeburn   318:         if ($type eq 'randomizetry') {
                    319:             $form{'grade_questiontype'} = $type;
                    320:             if ($rndseed ne '') {
                    321:                 $form{'grade_rndseed'} = $rndseed;
                    322:             }
                    323:         }
1.557     raeburn   324:         if (ref($add_to_hash)) {
                    325:             %form = (%form,%{$add_to_hash});
1.596.2.2  raeburn   326:         }
1.557     raeburn   327: 	my $subresult=&ssi_with_retries($url, $ssi_retries,%form);
1.434     albertel  328: 	(undef,$subresult)=split(/_HASH_REF__/,$subresult,2);
                    329: 	my %analyze=&Apache::lonnet::str2hash($subresult);
1.557     raeburn   330:         if (ref($add_to_hash) eq 'HASH') {
                    331:             $analyze_cache_formkeys{$key} = $add_to_hash;
                    332:         } else {
                    333:             $analyze_cache_formkeys{$key} = {};
                    334:         }
1.434     albertel  335: 	return $analyze_cache{$key} = \%analyze;
                    336:     }
                    337: 
                    338:     sub get_order {
1.596.2.2  raeburn   339: 	my ($partid,$respid,$symb,$uname,$udom,$no_increment,$type,$trial,$rndseed)=@_;
                    340: 	my $analyze = &get_analyze($symb,$uname,$udom,$no_increment,undef,$type,$trial,$rndseed);
1.434     albertel  341: 	return $analyze->{"$partid.$respid.shown"};
                    342:     }
                    343: 
                    344:     sub get_radiobutton_correct_foil {
1.596.2.2  raeburn   345: 	my ($partid,$respid,$symb,$uname,$udom,$type,$trial,$rndseed)=@_;
                    346: 	my $analyze = &get_analyze($symb,$uname,$udom,undef,undef,$type,$trial,$rndseed);
                    347:         my $foils = &get_order($partid,$respid,$symb,$uname,$udom,undef,$type,$trial,$rndseed);
1.555     raeburn   348:         if (ref($foils) eq 'ARRAY') {
                    349: 	    foreach my $foil (@{$foils}) {
                    350: 	        if ($analyze->{"$partid.$respid.foil.value.$foil"} eq 'true') {
                    351: 		    return $foil;
                    352: 	        }
1.434     albertel  353: 	    }
                    354: 	}
                    355:     }
1.554     raeburn   356: 
                    357:     sub scantron_partids_tograde {
1.596.2.12.2.  (raeburn  358:):         my ($resource,$cid,$uname,$udom,$check_for_randomlist,$bubbles_per_row) = @_;
1.554     raeburn   359:         my (%analysis,@parts);
                    360:         if (ref($resource)) {
                    361:             my $symb = $resource->symb();
1.557     raeburn   362:             my $add_to_form;
                    363:             if ($check_for_randomlist) {
                    364:                 $add_to_form = { 'check_parts_withrandomlist' => 1,};
                    365:             }
1.596.2.12.2.  (raeburn  366:):             my $analyze =
                    367:):                 &get_analyze($symb,$uname,$udom,undef,$add_to_form,
                    368:):                              undef,undef,undef,$bubbles_per_row);
1.554     raeburn   369:             if (ref($analyze) eq 'HASH') {
                    370:                 %analysis = %{$analyze};
                    371:             }
                    372:             if (ref($analysis{'parts'}) eq 'ARRAY') {
                    373:                 foreach my $part (@{$analysis{'parts'}}) {
                    374:                     my ($id,$respid) = split(/\./,$part);
                    375:                     if (!&Apache::loncommon::check_if_partid_hidden($id,$symb,$udom,$uname)) {
                    376:                         push(@parts,$part);
                    377:                     }
                    378:                 }
                    379:             }
                    380:         }
                    381:         return (\%analysis,\@parts);
                    382:     }
                    383: 
1.148     albertel  384: }
1.434     albertel  385: 
1.118     ng        386: #--- Clean response type for display
1.335     albertel  387: #--- Currently filters option/rank/radiobutton/match/essay/Task
                    388: #        response types only.
1.118     ng        389: sub cleanRecord {
1.336     albertel  390:     my ($answer,$response,$symb,$partid,$respid,$record,$order,$version,
1.596.2.2  raeburn   391: 	$uname,$udom,$type,$trial,$rndseed) = @_;
1.398     albertel  392:     my $grayFont = '<span class="LC_internal_info">';
1.148     albertel  393:     if ($response =~ /^(option|rank)$/) {
                    394: 	my %answer=&Apache::lonnet::str2hash($answer);
1.596.2.12.2.  8(raebur  395:4):         my @answer = %answer;
                    396:4):         %answer = map {&HTML::Entities::encode($_, '"<>&')} @answer;
1.148     albertel  397: 	my %grading=&Apache::lonnet::str2hash($record->{$version."resource.$partid.$respid.submissiongrading"});
                    398: 	my ($toprow,$bottomrow);
                    399: 	foreach my $foil (@$order) {
                    400: 	    if ($grading{$foil} == 1) {
                    401: 		$toprow.='<td><b>'.$answer{$foil}.'&nbsp;</b></td>';
                    402: 	    } else {
                    403: 		$toprow.='<td><i>'.$answer{$foil}.'&nbsp;</i></td>';
                    404: 	    }
1.398     albertel  405: 	    $bottomrow.='<td>'.$grayFont.$foil.'</span>&nbsp;</td>';
1.148     albertel  406: 	}
                    407: 	return '<blockquote><table border="1">'.
1.466     albertel  408: 	    '<tr valign="top"><td>'.&mt('Answer').'</td>'.$toprow.'</tr>'.
                    409: 	    '<tr valign="top"><td>'.$grayFont.&mt('Option ID').'</span></td>'.
1.596.2.1  raeburn   410: 	    $bottomrow.'</tr></table></blockquote>';
1.148     albertel  411:     } elsif ($response eq 'match') {
                    412: 	my %answer=&Apache::lonnet::str2hash($answer);
1.596.2.12.2.  8(raebur  413:4):         my @answer = %answer;
                    414:4):         %answer = map {&HTML::Entities::encode($_, '"<>&')} @answer;
1.148     albertel  415: 	my %grading=&Apache::lonnet::str2hash($record->{$version."resource.$partid.$respid.submissiongrading"});
                    416: 	my @items=&Apache::lonnet::str2array($record->{$version."resource.$partid.$respid.submissionitems"});
                    417: 	my ($toprow,$middlerow,$bottomrow);
                    418: 	foreach my $foil (@$order) {
                    419: 	    my $item=shift(@items);
                    420: 	    if ($grading{$foil} == 1) {
                    421: 		$toprow.='<td><b>'.$item.'&nbsp;</b></td>';
1.398     albertel  422: 		$middlerow.='<td><b>'.$grayFont.$answer{$foil}.'&nbsp;</span></b></td>';
1.148     albertel  423: 	    } else {
                    424: 		$toprow.='<td><i>'.$item.'&nbsp;</i></td>';
1.398     albertel  425: 		$middlerow.='<td><i>'.$grayFont.$answer{$foil}.'&nbsp;</span></i></td>';
1.148     albertel  426: 	    }
1.398     albertel  427: 	    $bottomrow.='<td>'.$grayFont.$foil.'</span>&nbsp;</td>';
1.118     ng        428: 	}
1.126     ng        429: 	return '<blockquote><table border="1">'.
1.466     albertel  430: 	    '<tr valign="top"><td>'.&mt('Answer').'</td>'.$toprow.'</tr>'.
                    431: 	    '<tr valign="top"><td>'.$grayFont.&mt('Item ID').'</span></td>'.
1.148     albertel  432: 	    $middlerow.'</tr>'.
1.466     albertel  433: 	    '<tr valign="top"><td>'.$grayFont.&mt('Option ID').'</span></td>'.
1.596.2.8  raeburn   434: 	    $bottomrow.'</tr></table></blockquote>';
1.148     albertel  435:     } elsif ($response eq 'radiobutton') {
                    436: 	my %answer=&Apache::lonnet::str2hash($answer);
                    437: 	my ($toprow,$bottomrow);
1.434     albertel  438: 	my $correct = 
1.596.2.2  raeburn   439: 	    &get_radiobutton_correct_foil($partid,$respid,$symb,$uname,$udom,$type,$trial,$rndseed);
1.434     albertel  440: 	foreach my $foil (@$order) {
1.148     albertel  441: 	    if (exists($answer{$foil})) {
1.434     albertel  442: 		if ($foil eq $correct) {
1.466     albertel  443: 		    $toprow.='<td><b>'.&mt('true').'</b></td>';
1.148     albertel  444: 		} else {
1.466     albertel  445: 		    $toprow.='<td><i>'.&mt('true').'</i></td>';
1.148     albertel  446: 		}
                    447: 	    } else {
1.466     albertel  448: 		$toprow.='<td>'.&mt('false').'</td>';
1.148     albertel  449: 	    }
1.398     albertel  450: 	    $bottomrow.='<td>'.$grayFont.$foil.'</span>&nbsp;</td>';
1.148     albertel  451: 	}
                    452: 	return '<blockquote><table border="1">'.
1.466     albertel  453: 	    '<tr valign="top"><td>'.&mt('Answer').'</td>'.$toprow.'</tr>'.
                    454: 	    '<tr valign="top"><td>'.$grayFont.&mt('Option ID').'</span></td>'.
1.596.2.4  raeburn   455: 	    $bottomrow.'</tr></table></blockquote>';
1.148     albertel  456:     } elsif ($response eq 'essay') {
1.257     albertel  457: 	if (! exists ($env{'form.'.$symb})) {
1.122     ng        458: 	    my (%keyhash) = &Apache::lonnet::dump('nohist_handgrade',
1.257     albertel  459: 						  $env{'course.'.$env{'request.course.id'}.'.domain'},
                    460: 						  $env{'course.'.$env{'request.course.id'}.'.num'});
1.122     ng        461: 
1.257     albertel  462: 	    my $loginuser = $env{'user.name'}.':'.$env{'user.domain'};
                    463: 	    $env{'form.keywords'} = $keyhash{$symb.'_keywords'} ne '' ? $keyhash{$symb.'_keywords'} : '';
                    464: 	    $env{'form.kwclr'}    = $keyhash{$loginuser.'_kwclr'} ne '' ? $keyhash{$loginuser.'_kwclr'} : 'red';
                    465: 	    $env{'form.kwsize'}   = $keyhash{$loginuser.'_kwsize'} ne '' ? $keyhash{$loginuser.'_kwsize'} : '0';
                    466: 	    $env{'form.kwstyle'}  = $keyhash{$loginuser.'_kwstyle'} ne '' ? $keyhash{$loginuser.'_kwstyle'} : '';
                    467: 	    $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        468: 	}
1.596.2.12.2.  0.2.1(ra  469:ct-18):         $answer = &Apache::lontexconvert::msgtexconverted($answer);
          2(raebur  470:5): 	return '<br /><br /><blockquote><tt>'.&keywords_highlight($answer).'</tt></blockquote>';
1.268     albertel  471:     } elsif ( $response eq 'organic') {
1.596.2.12.2.  8(raebur  472:4):         my $result=&mt('Smile representation: [_1]',
                    473:4):                            '"<tt>'.&HTML::Entities::encode($answer, '"<>&').'</tt>"');
1.268     albertel  474: 	my $jme=$record->{$version."resource.$partid.$respid.molecule"};
                    475: 	$result.=&Apache::chemresponse::jme_img($jme,$answer,400);
                    476: 	return $result;
1.335     albertel  477:     } elsif ( $response eq 'Task') {
                    478: 	if ( $answer eq 'SUBMITTED') {
                    479: 	    my $files = $record->{$version."resource.$respid.$partid.bridgetask.portfiles"};
1.336     albertel  480: 	    my $result = &Apache::bridgetask::file_list($files,$uname,$udom);
1.335     albertel  481: 	    return $result;
                    482: 	} elsif ( grep(/^\Q$version\E.*?\.instance$/, keys(%{$record})) ) {
                    483: 	    my @matches = grep(/^\Q$version\E.*?\.instance$/,
                    484: 			       keys(%{$record}));
                    485: 	    return join('<br />',($version,@matches));
                    486: 			       
                    487: 			       
                    488: 	} else {
                    489: 	    my $result =
                    490: 		'<p>'
                    491: 		.&mt('Overall result: [_1]',
                    492: 		     $record->{$version."resource.$respid.$partid.status"})
                    493: 		.'</p>';
                    494: 	    
                    495: 	    $result .= '<ul>';
                    496: 	    my @grade = grep(/^\Q${version}resource.$respid.$partid.\E[^.]*[.]status$/,
                    497: 			     keys(%{$record}));
                    498: 	    foreach my $grade (sort(@grade)) {
                    499: 		my ($dim) = ($grade =~/[.]([^.]+)[.]status$/);
                    500: 		$result.= '<li>'.&mt("Dimension: [_1], status [_2] ",
                    501: 				     $dim, $record->{$grade}).
                    502: 			  '</li>';
                    503: 	    }
                    504: 	    $result.='</ul>';
                    505: 	    return $result;
                    506: 	}
1.596.2.12.2.  8(raebur  507:4):     } elsif ( $response =~ m/(?:numerical|formula|custom)/) {
                    508:4):         # Respect multiple input fields, see Bug #5409 
1.440     albertel  509: 	$answer = 
                    510: 	    &Apache::loncommon::format_previous_attempt_value('submission',
                    511: 							      $answer);
1.596.2.12.2.  8(raebur  512:4):         return $answer;
1.122     ng        513:     }
1.596.2.12.2.  8(raebur  514:4):     return &HTML::Entities::encode($answer, '"<>&');
1.118     ng        515: }
                    516: 
                    517: #-- A couple of common js functions
                    518: sub commonJSfunctions {
                    519:     my $request = shift;
                    520:     $request->print(<<COMMONJSFUNCTIONS);
                    521: <script type="text/javascript" language="javascript">
                    522:     function radioSelection(radioButton) {
                    523: 	var selection=null;
                    524: 	if (radioButton.length > 1) {
                    525: 	    for (var i=0; i<radioButton.length; i++) {
                    526: 		if (radioButton[i].checked) {
                    527: 		    return radioButton[i].value;
                    528: 		}
                    529: 	    }
                    530: 	} else {
                    531: 	    if (radioButton.checked) return radioButton.value;
                    532: 	}
                    533: 	return selection;
                    534:     }
                    535: 
                    536:     function pullDownSelection(selectOne) {
                    537: 	var selection="";
                    538: 	if (selectOne.length > 1) {
                    539: 	    for (var i=0; i<selectOne.length; i++) {
                    540: 		if (selectOne[i].selected) {
                    541: 		    return selectOne[i].value;
                    542: 		}
                    543: 	    }
                    544: 	} else {
1.138     albertel  545:             // only one value it must be the selected one
                    546: 	    return selectOne.value;
1.118     ng        547: 	}
                    548:     }
                    549: </script>
                    550: COMMONJSFUNCTIONS
                    551: }
                    552: 
1.44      ng        553: #--- Dumps the class list with usernames,list of sections,
                    554: #--- section, ids and fullnames for each user.
                    555: sub getclasslist {
1.449     banghart  556:     my ($getsec,$filterlist,$getgroup) = @_;
1.291     albertel  557:     my @getsec;
1.450     banghart  558:     my @getgroup;
1.442     banghart  559:     my $stu_status = join(':',&Apache::loncommon::get_env_multiple('form.Status'));
1.291     albertel  560:     if (!ref($getsec)) {
                    561: 	if ($getsec ne '' && $getsec ne 'all') {
                    562: 	    @getsec=($getsec);
                    563: 	}
                    564:     } else {
                    565: 	@getsec=@{$getsec};
                    566:     }
                    567:     if (grep(/^all$/,@getsec)) { undef(@getsec); }
1.450     banghart  568:     if (!ref($getgroup)) {
                    569: 	if ($getgroup ne '' && $getgroup ne 'all') {
                    570: 	    @getgroup=($getgroup);
                    571: 	}
                    572:     } else {
                    573: 	@getgroup=@{$getgroup};
                    574:     }
                    575:     if (grep(/^all$/,@getgroup)) { undef(@getgroup); }
1.291     albertel  576: 
1.449     banghart  577:     my ($classlist,$keylist)=&Apache::loncoursedata::get_classlist();
1.49      albertel  578:     # Bail out if we were unable to get the classlist
1.56      matthew   579:     return if (! defined($classlist));
1.449     banghart  580:     &Apache::loncoursedata::get_group_memberships($classlist,$keylist);
1.56      matthew   581:     #
                    582:     my %sections;
                    583:     my %fullnames;
1.205     matthew   584:     foreach my $student (keys(%$classlist)) {
                    585:         my $end      = 
                    586:             $classlist->{$student}->[&Apache::loncoursedata::CL_END()];
                    587:         my $start    = 
                    588:             $classlist->{$student}->[&Apache::loncoursedata::CL_START()];
                    589:         my $id       = 
                    590:             $classlist->{$student}->[&Apache::loncoursedata::CL_ID()];
                    591:         my $section  = 
                    592:             $classlist->{$student}->[&Apache::loncoursedata::CL_SECTION()];
                    593:         my $fullname = 
                    594:             $classlist->{$student}->[&Apache::loncoursedata::CL_FULLNAME()];
                    595:         my $status   = 
                    596:             $classlist->{$student}->[&Apache::loncoursedata::CL_STATUS()];
1.449     banghart  597:         my $group   = 
                    598:             $classlist->{$student}->[&Apache::loncoursedata::CL_GROUP()];
1.76      ng        599: 	# filter students according to status selected
1.442     banghart  600: 	if ($filterlist && (!($stu_status =~ /Any/))) {
                    601: 	    if (!($stu_status =~ $status)) {
1.450     banghart  602: 		delete($classlist->{$student});
1.76      ng        603: 		next;
                    604: 	    }
                    605: 	}
1.450     banghart  606: 	# filter students according to groups selected
1.453     banghart  607: 	my @stu_groups = split(/,/,$group);
1.450     banghart  608: 	if (@getgroup) {
                    609: 	    my $exclude = 1;
1.454     banghart  610: 	    foreach my $grp (@getgroup) {
                    611: 	        foreach my $stu_group (@stu_groups) {
1.453     banghart  612: 	            if ($stu_group eq $grp) {
                    613: 	                $exclude = 0;
                    614:     	            } 
1.450     banghart  615: 	        }
1.453     banghart  616:     	        if (($grp eq 'none') && !$group) {
                    617:         	        $exclude = 0;
                    618:         	}
1.450     banghart  619: 	    }
                    620: 	    if ($exclude) {
                    621: 	        delete($classlist->{$student});
                    622: 	    }
                    623: 	}
1.205     matthew   624: 	$section = ($section ne '' ? $section : 'none');
1.106     albertel  625: 	if (&canview($section)) {
1.291     albertel  626: 	    if (!@getsec || grep(/^\Q$section\E$/,@getsec)) {
1.103     albertel  627: 		$sections{$section}++;
1.450     banghart  628: 		if ($classlist->{$student}) {
                    629: 		    $fullnames{$student}=$fullname;
                    630: 		}
1.103     albertel  631: 	    } else {
1.205     matthew   632: 		delete($classlist->{$student});
1.103     albertel  633: 	    }
                    634: 	} else {
1.205     matthew   635: 	    delete($classlist->{$student});
1.103     albertel  636: 	}
1.44      ng        637:     }
                    638:     my %seen = ();
1.56      matthew   639:     my @sections = sort(keys(%sections));
                    640:     return ($classlist,\@sections,\%fullnames);
1.44      ng        641: }
                    642: 
1.103     albertel  643: sub canmodify {
                    644:     my ($sec)=@_;
                    645:     if ($perm{'mgr'}) {
                    646: 	if (!defined($perm{'mgr_section'})) {
                    647: 	    # can modify whole class
                    648: 	    return 1;
                    649: 	} else {
                    650: 	    if ($sec eq $perm{'mgr_section'}) {
                    651: 		#can modify the requested section
                    652: 		return 1;
                    653: 	    } else {
                    654: 		# can't modify the request section
                    655: 		return 0;
                    656: 	    }
                    657: 	}
                    658:     }
                    659:     #can't modify
                    660:     return 0;
                    661: }
                    662: 
                    663: sub canview {
                    664:     my ($sec)=@_;
                    665:     if ($perm{'vgr'}) {
                    666: 	if (!defined($perm{'vgr_section'})) {
                    667: 	    # can modify whole class
                    668: 	    return 1;
                    669: 	} else {
                    670: 	    if ($sec eq $perm{'vgr_section'}) {
                    671: 		#can modify the requested section
                    672: 		return 1;
                    673: 	    } else {
                    674: 		# can't modify the request section
                    675: 		return 0;
                    676: 	    }
                    677: 	}
                    678:     }
                    679:     #can't modify
                    680:     return 0;
                    681: }
                    682: 
1.44      ng        683: #--- Retrieve the grade status of a student for all the parts
                    684: sub student_gradeStatus {
1.324     albertel  685:     my ($symb,$udom,$uname,$partlist) = @_;
1.257     albertel  686:     my %record     = &Apache::lonnet::restore($symb,$env{'request.course.id'},$udom,$uname);
1.44      ng        687:     my %partstatus = ();
                    688:     foreach (@$partlist) {
1.128     ng        689: 	my ($status,undef)   = split(/_/,$record{"resource.$_.solved"},2);
1.44      ng        690: 	$status              = 'nothing' if ($status eq '');
                    691: 	$partstatus{$_}      = $status;
                    692: 	my $subkey           = "resource.$_.submitted_by";
                    693: 	$partstatus{$subkey} = $record{$subkey} if ($record{$subkey} ne '');
                    694:     }
                    695:     return %partstatus;
                    696: }
                    697: 
1.45      ng        698: # hidden form and javascript that calls the form
                    699: # Use by verifyscript and viewgrades
                    700: # Shows a student's view of problem and submission
                    701: sub jscriptNform {
1.324     albertel  702:     my ($symb) = @_;
1.442     banghart  703:     my $stu_status = join(':',&Apache::loncommon::get_env_multiple('form.Status'));
1.45      ng        704:     my $jscript='<script type="text/javascript" language="javascript">'."\n".
                    705: 	'    function viewOneStudent(user,domain) {'."\n".
                    706: 	'	document.onestudent.student.value = user;'."\n".
                    707: 	'	document.onestudent.userdom.value = domain;'."\n".
                    708: 	'	document.onestudent.submit();'."\n".
                    709: 	'    }'."\n".
                    710: 	'</script>'."\n";
                    711:     $jscript.= '<form action="/adm/grades" method="post" name="onestudent">'."\n".
1.418     albertel  712: 	'<input type="hidden" name="symb"    value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
1.257     albertel  713: 	'<input type="hidden" name="saveState" value="'.$env{'form.saveState'}.'" />'."\n".
                    714: 	'<input type="hidden" name="probTitle" value="'.$env{'form.probTitle'}.'" />'."\n".
1.442     banghart  715: 	'<input type="hidden" name="Status"  value="'.$stu_status.'" />'."\n".
1.45      ng        716: 	'<input type="hidden" name="command" value="submission" />'."\n".
                    717: 	'<input type="hidden" name="student" value="" />'."\n".
                    718: 	'<input type="hidden" name="userdom" value="" />'."\n".
                    719: 	'</form>'."\n";
                    720:     return $jscript;
                    721: }
1.39      ng        722: 
1.447     foxr      723: 
                    724: 
1.315     bowersj2  725: # Given the score (as a number [0-1] and the weight) what is the final
                    726: # point value? This function will round to the nearest tenth, third,
                    727: # or quarter if one of those is within the tolerance of .00001.
1.316     albertel  728: sub compute_points {
1.315     bowersj2  729:     my ($score, $weight) = @_;
                    730:     
                    731:     my $tolerance = .00001;
                    732:     my $points = $score * $weight;
                    733: 
                    734:     # Check for nearness to 1/x.
                    735:     my $check_for_nearness = sub {
                    736:         my ($factor) = @_;
                    737:         my $num = ($points * $factor) + $tolerance;
                    738:         my $floored_num = floor($num);
1.316     albertel  739:         if ($num - $floored_num < 2 * $tolerance * $factor) {
1.315     bowersj2  740:             return $floored_num / $factor;
                    741:         }
                    742:         return $points;
                    743:     };
                    744: 
                    745:     $points = $check_for_nearness->(10);
                    746:     $points = $check_for_nearness->(3);
                    747:     $points = $check_for_nearness->(4);
                    748:     
                    749:     return $points;
                    750: }
                    751: 
1.44      ng        752: #------------------ End of general use routines --------------------
1.87      www       753: 
                    754: #
                    755: # Find most similar essay
                    756: #
                    757: 
                    758: sub most_similar {
1.596.2.12.2.  (raeburn  759:):     my ($uname,$udom,$symb,$uessay)=@_;
                    760:): 
                    761:):     unless ($symb) { return ''; }
                    762:): 
                    763:):     unless (ref($old_essays{$symb}) eq 'HASH') { return ''; }
1.87      www       764: 
                    765: # ignore spaces and punctuation
                    766: 
                    767:     $uessay=~s/\W+/ /gs;
                    768: 
1.282     www       769: # ignore empty submissions (occuring when only files are sent)
                    770: 
1.596.2.4  raeburn   771:     unless ($uessay=~/\w+/s) { return ''; }
1.282     www       772: 
1.87      www       773: # these will be returned. Do not care if not at least 50 percent similar
1.88      www       774:     my $limit=0.6;
1.87      www       775:     my $sname='';
                    776:     my $sdom='';
                    777:     my $scrsid='';
                    778:     my $sessay='';
                    779: # go through all essays ...
1.596.2.12.2.  (raeburn  780:):     foreach my $tkey (keys(%{$old_essays{$symb}})) {
1.426     albertel  781: 	my ($tname,$tdom,$tcrsid)=map {&unescape($_)} (split(/\./,$tkey));
1.87      www       782: # ... except the same student
1.426     albertel  783:         next if (($tname eq $uname) && ($tdom eq $udom));
1.596.2.12.2.  (raeburn  784:): 	my $tessay=$old_essays{$symb}{$tkey};
1.426     albertel  785: 	$tessay=~s/\W+/ /gs;
1.87      www       786: # String similarity gives up if not even limit
1.426     albertel  787: 	my $tsimilar=&String::Similarity::similarity($uessay,$tessay,$limit);
1.87      www       788: # Found one
1.426     albertel  789: 	if ($tsimilar>$limit) {
                    790: 	    $limit=$tsimilar;
                    791: 	    $sname=$tname;
                    792: 	    $sdom=$tdom;
                    793: 	    $scrsid=$tcrsid;
1.596.2.12.2.  (raeburn  794:): 	    $sessay=$old_essays{$symb}{$tkey};
1.426     albertel  795: 	}
1.87      www       796:     }
1.88      www       797:     if ($limit>0.6) {
1.87      www       798:        return ($sname,$sdom,$scrsid,$sessay,$limit);
                    799:     } else {
                    800:        return ('','','','',0);
                    801:     }
                    802: }
                    803: 
1.44      ng        804: #-------------------------------------------------------------------
                    805: 
                    806: #------------------------------------ Receipt Verification Routines
1.45      ng        807: #
1.44      ng        808: #--- Check whether a receipt number is valid.---
                    809: sub verifyreceipt {
                    810:     my $request  = shift;
                    811: 
1.257     albertel  812:     my $courseid = $env{'request.course.id'};
1.184     www       813:     my $receipt  = &Apache::lonnet::recprefix($courseid).'-'.
1.257     albertel  814: 	$env{'form.receipt'};
1.44      ng        815:     $receipt     =~ s/[^\-\d]//g;
1.378     albertel  816:     my ($symb)   = &get_symb($request);
1.44      ng        817: 
1.487     albertel  818:     my $title.=
                    819: 	'<h3><span class="LC_info">'.
1.584     bisitz    820: 	&mt('Verifying Receipt No. [_1]',$receipt).
1.487     albertel  821: 	'</span></h3>'."\n".
1.596.2.12.2.  2(raebur  822:3): 	'<h4>'.&mt('[_1]Resource: [_2]','<b>','</b>'.$env{'form.probTitle'}).
1.487     albertel  823: 	'</h4>'."\n";
1.44      ng        824: 
                    825:     my ($string,$contents,$matches) = ('','',0);
1.56      matthew   826:     my (undef,undef,$fullname) = &getclasslist('all','0');
1.177     albertel  827:     
                    828:     my $receiptparts=0;
1.390     albertel  829:     if ($env{"course.$courseid.receiptalg"} eq 'receipt2' ||
                    830: 	$env{"course.$courseid.receiptalg"} eq 'receipt3') { $receiptparts=1; }
1.177     albertel  831:     my $parts=['0'];
1.582     raeburn   832:     if ($receiptparts) {
                    833:         my $res_error; 
                    834:         ($parts)=&response_type($symb,\$res_error);
                    835:         if ($res_error) {
                    836:             return &navmap_errormsg();
                    837:         } 
                    838:     }
1.486     albertel  839:     
                    840:     my $header = 
                    841: 	&Apache::loncommon::start_data_table().
                    842: 	&Apache::loncommon::start_data_table_header_row().
1.487     albertel  843: 	'<th>&nbsp;'.&mt('Fullname').'&nbsp;</th>'."\n".
                    844: 	'<th>&nbsp;'.&mt('Username').'&nbsp;</th>'."\n".
                    845: 	'<th>&nbsp;'.&mt('Domain').'&nbsp;</th>';
1.486     albertel  846:     if ($receiptparts) {
1.487     albertel  847: 	$header.='<th>&nbsp;'.&mt('Problem Part').'&nbsp;</th>';
1.486     albertel  848:     }
                    849:     $header.=
                    850: 	&Apache::loncommon::end_data_table_header_row();
                    851: 
1.294     albertel  852:     foreach (sort 
                    853: 	     {
                    854: 		 if (lc($$fullname{$a}) ne lc($$fullname{$b})) {
                    855: 		     return (lc($$fullname{$a}) cmp lc($$fullname{$b}));
                    856: 		 }
                    857: 		 return $a cmp $b;
                    858: 	     } (keys(%$fullname))) {
1.44      ng        859: 	my ($uname,$udom)=split(/\:/);
1.177     albertel  860: 	foreach my $part (@$parts) {
                    861: 	    if ($receipt eq &Apache::lonnet::ireceipt($uname,$udom,$courseid,$symb,$part)) {
1.486     albertel  862: 		$contents.=
                    863: 		    &Apache::loncommon::start_data_table_row().
                    864: 		    '<td>&nbsp;'."\n".
1.177     albertel  865: 		    '<a href="javascript:viewOneStudent(\''.$uname.'\',\''.$udom.
1.417     albertel  866: 		    '\');" target="_self">'.$$fullname{$_}.'</a>&nbsp;</td>'."\n".
1.177     albertel  867: 		    '<td>&nbsp;'.$uname.'&nbsp;</td>'.
                    868: 		    '<td>&nbsp;'.$udom.'&nbsp;</td>';
                    869: 		if ($receiptparts) {
                    870: 		    $contents.='<td>&nbsp;'.$part.'&nbsp;</td>';
                    871: 		}
1.486     albertel  872: 		$contents.= 
                    873: 		    &Apache::loncommon::end_data_table_row()."\n";
1.177     albertel  874: 		
                    875: 		$matches++;
                    876: 	    }
1.44      ng        877: 	}
                    878:     }
                    879:     if ($matches == 0) {
1.584     bisitz    880:         $string = $title
                    881:                  .'<p class="LC_warning">'
                    882:                  .&mt('No match found for the above receipt number.')
                    883:                  .'</p>';
1.44      ng        884:     } else {
1.324     albertel  885: 	$string = &jscriptNform($symb).$title.
1.487     albertel  886: 	    '<p>'.
1.584     bisitz    887: 	    &mt('The above receipt number matches the following [quant,_1,student].',$matches).
1.487     albertel  888: 	    '</p>'.
1.486     albertel  889: 	    $header.
                    890: 	    $contents.
                    891: 	    &Apache::loncommon::end_data_table()."\n";
1.44      ng        892:     }
1.324     albertel  893:     return $string.&show_grading_menu_form($symb);
1.44      ng        894: }
                    895: 
                    896: #--- This is called by a number of programs.
                    897: #--- Called from the Grading Menu - View/Grade an individual student
                    898: #--- Also called directly when one clicks on the subm button 
                    899: #    on the problem page.
1.30      ng        900: sub listStudents {
1.41      ng        901:     my ($request) = shift;
1.49      albertel  902: 
1.324     albertel  903:     my ($symb) = &get_symb($request);
1.257     albertel  904:     my $cdom      = $env{"course.$env{'request.course.id'}.domain"};
                    905:     my $cnum      = $env{"course.$env{'request.course.id'}.num"};
                    906:     my $getsec    = $env{'form.section'} eq '' ? 'all' : $env{'form.section'};
1.449     banghart  907:     my $getgroup  = $env{'form.group'} eq '' ? 'all' : $env{'form.group'};
1.257     albertel  908:     my $submitonly= $env{'form.submitonly'} eq '' ? 'all' : $env{'form.submitonly'};
1.548     bisitz    909:     my $viewgrade = $env{'form.showgrading'} eq 'yes' ? 'View/Grade/Regrade' : 'View';
1.257     albertel  910:     $env{'form.probTitle'} = $env{'form.probTitle'} eq '' ? 
                    911: 	&Apache::lonnet::gettitle($symb) : $env{'form.probTitle'};
1.49      albertel  912: 
1.548     bisitz    913:     my $result='<h3><span class="LC_info">&nbsp;'
                    914: 	.&mt("$viewgrade Submissions for a Student or a Group of Students")
1.485     albertel  915: 	.'</span></h3>';
1.118     ng        916: 
1.324     albertel  917:     my ($table,undef,$hdgrade,$partlist,$handgrade) = &showResourceInfo($symb,$env{'form.probTitle'},($env{'form.showgrading'} eq 'yes'));
1.49      albertel  918: 
1.596.2.12.2.  6(raebur  919:6):     my %js_lt = &Apache::lonlocal::texthash (
1.559     raeburn   920: 		'multiple' => 'Please select a student or group of students before clicking on the Next button.',
                    921: 		'single'   => 'Please select the student before clicking on the Next button.',
                    922: 	     );
1.596.2.12.2.  6(raebur  923:6):     &js_escape(\%js_lt);
1.45      ng        924:     $request->print(<<LISTJAVASCRIPT);
                    925: <script type="text/javascript" language="javascript">
1.110     ng        926:     function checkSelect(checkBox) {
                    927: 	var ctr=0;
                    928: 	var sense="";
                    929: 	if (checkBox.length > 1) {
                    930: 	    for (var i=0; i<checkBox.length; i++) {
                    931: 		if (checkBox[i].checked) {
                    932: 		    ctr++;
                    933: 		}
                    934: 	    }
1.596.2.12.2.  6(raebur  935:6): 	    sense = '$js_lt{'multiple'}';
1.110     ng        936: 	} else {
                    937: 	    if (checkBox.checked) {
                    938: 		ctr = 1;
                    939: 	    }
1.596.2.12.2.  6(raebur  940:6): 	    sense = '$js_lt{'single'}';
1.110     ng        941: 	}
                    942: 	if (ctr == 0) {
1.485     albertel  943: 	    alert(sense);
1.110     ng        944: 	    return false;
                    945: 	}
                    946: 	document.gradesub.submit();
                    947:     }
                    948: 
                    949:     function reLoadList(formname) {
1.112     ng        950: 	if (formname.saveStatusOld.value == pullDownSelection(formname.Status)) {return;}
1.110     ng        951: 	formname.command.value = 'submission';
                    952: 	formname.submit();
                    953:     }
1.45      ng        954: </script>
                    955: LISTJAVASCRIPT
                    956: 
1.118     ng        957:     &commonJSfunctions($request);
1.41      ng        958:     $request->print($result);
1.39      ng        959: 
1.401     albertel  960:     my $checkhdgrade = ($env{'form.handgrade'} eq 'yes' && scalar(@$partlist) > 1 ) ? 'checked="checked"' : '';
                    961:     my $checklastsub = $checkhdgrade eq '' ? 'checked="checked"' : '';
1.154     albertel  962:     my $gradeTable='<form action="/adm/grades" method="post" name="gradesub">'.
1.485     albertel  963: 	"\n".$table;
                    964: 	
1.561     bisitz    965:     $gradeTable .= &Apache::lonhtmlcommon::start_pick_box();
                    966:     $gradeTable .= &Apache::lonhtmlcommon::row_title(&mt('View Problem Text'))
                    967:                   .'<label><input type="radio" name="vProb" value="no" checked="checked" /> '.&mt('no').' </label>'."\n"
                    968:                   .'<label><input type="radio" name="vProb" value="yes" /> '.&mt('one student').' </label>'."\n"
                    969:                   .'<label><input type="radio" name="vProb" value="all" /> '.&mt('all students').' </label><br />'."\n"
                    970:                   .&Apache::lonhtmlcommon::row_closure();
                    971:     $gradeTable .= &Apache::lonhtmlcommon::row_title(&mt('View Answer'))
                    972:                   .'<label><input type="radio" name="vAns" value="no"  /> '.&mt('no').' </label>'."\n"
                    973:                   .'<label><input type="radio" name="vAns" value="yes" /> '.&mt('one student').' </label>'."\n"
                    974:                   .'<label><input type="radio" name="vAns" value="all" checked="checked" /> '.&mt('all students').' </label><br />'."\n"
                    975:                   .&Apache::lonhtmlcommon::row_closure();
1.485     albertel  976: 
                    977:     my $submission_options;
1.257     albertel  978:     if ($env{'form.handgrade'} eq 'yes' && scalar(@$partlist) > 1) {
1.485     albertel  979: 	$submission_options.=
                    980: 	    '<label><input type="radio" name="lastSub" value="hdgrade" '.$checkhdgrade.' /> '.&mt('essay part only').' </label>'."\n";
1.49      albertel  981:     }
1.442     banghart  982:     my $stu_status = join(':',&Apache::loncommon::get_env_multiple('form.Status'));
                    983:     my $saveStatus = $stu_status eq '' ? 'Active' : $stu_status;
1.257     albertel  984:     $env{'form.Status'} = $saveStatus;
1.485     albertel  985:     $submission_options.=
1.592     bisitz    986:         '<span class="LC_nobreak">'.
                    987:         '<label><input type="radio" name="lastSub" value="lastonly" '.$checklastsub.' /> '.
                    988:         &mt('last submission only').' </label></span>'."\n".
                    989:         '<span class="LC_nobreak">'.
                    990:         '<label><input type="radio" name="lastSub" value="last" /> '.
                    991:         &mt('last submission &amp; parts info').' </label></span>'."\n".
                    992:         '<span class="LC_nobreak">'.
                    993:         '<label><input type="radio" name="lastSub" value="datesub" /> '.
                    994:         &mt('by dates and submissions').'</label></span>'."\n".
                    995:         '<span class="LC_nobreak">'.
                    996:         '<label><input type="radio" name="lastSub" value="all" /> '.
                    997:         &mt('all details').'</label></span>';
1.561     bisitz    998:     $gradeTable .= &Apache::lonhtmlcommon::row_title(&mt('Submissions'))
                    999:                   .$submission_options
                   1000:                   .&Apache::lonhtmlcommon::row_closure();
                   1001: 
                   1002:     $gradeTable .= &Apache::lonhtmlcommon::row_title(&mt('Grading Increments'))
                   1003:                   .'<select name="increment">'
                   1004:                   .'<option value="1">'.&mt('Whole Points').'</option>'
                   1005:                   .'<option value=".5">'.&mt('Half Points').'</option>'
                   1006:                   .'<option value=".25">'.&mt('Quarter Points').'</option>'
                   1007:                   .'<option value=".1">'.&mt('Tenths of a Point').'</option>'
                   1008:                   .'</select>'
                   1009:                   .&Apache::lonhtmlcommon::row_closure();
1.485     albertel 1010: 
                   1011:     $gradeTable .= 
1.432     banghart 1012:         &build_section_inputs().
1.45      ng       1013: 	'<input type="hidden" name="submitonly"  value="'.$submitonly.'" />'."\n".
1.257     albertel 1014: 	'<input type="hidden" name="handgrade"   value="'.$env{'form.handgrade'}.'" /><br />'."\n".
                   1015: 	'<input type="hidden" name="showgrading" value="'.$env{'form.showgrading'}.'" /><br />'."\n".
                   1016: 	'<input type="hidden" name="saveState"   value="'.$env{'form.saveState'}.'" />'."\n".
                   1017: 	'<input type="hidden" name="probTitle"   value="'.$env{'form.probTitle'}.'" />'."\n".
1.418     albertel 1018: 	'<input type="hidden" name="symb" value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
1.110     ng       1019: 	'<input type="hidden" name="saveStatusOld" value="'.$saveStatus.'" />'."\n";
                   1020: 
1.257     albertel 1021:     if (exists($env{'form.gradingMenu'}) && exists($env{'form.Status'})) {
1.561     bisitz   1022: 	$gradeTable .= '<input type="hidden" name="Status" value="'.$stu_status.'" />'."\n";
1.124     ng       1023:     } else {
1.561     bisitz   1024:         $gradeTable .= &Apache::lonhtmlcommon::row_title(&mt('Student Status'))
                   1025:                       .&Apache::lonhtmlcommon::StatusOptions(
                   1026:                            $saveStatus,undef,1,'javascript:reLoadList(this.form);')
                   1027:                       .&Apache::lonhtmlcommon::row_closure();
1.124     ng       1028:     }
1.112     ng       1029: 
1.561     bisitz   1030:     $gradeTable .= &Apache::lonhtmlcommon::row_title(&mt('Check For Plagiarism'))
                   1031:                   .'<input type="checkbox" name="checkPlag" checked="checked" />'
                   1032:                   .&Apache::lonhtmlcommon::row_closure(1)
                   1033:                   .&Apache::lonhtmlcommon::end_pick_box();
                   1034: 
                   1035:     $gradeTable .= '<p>'
                   1036:                   .&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"
                   1037:                   .'<input type="hidden" name="command" value="processGroup" />'
                   1038:                   .'</p>';
1.249     albertel 1039: 
                   1040: # checkall buttons
                   1041:     $gradeTable.=&check_script('gradesub', 'stuinfo');
1.110     ng       1042:     $gradeTable.='<input type="button" '."\n".
1.589     bisitz   1043:         'onclick="javascript:checkSelect(this.form.stuinfo);" '."\n".
                   1044:         'value="'.&mt('Next').' &rarr;" /> <br />'."\n";
1.249     albertel 1045:     $gradeTable.=&check_buttons();
1.450     banghart 1046:     my ($classlist, undef, $fullname) = &getclasslist($getsec,'1',$getgroup);
1.474     albertel 1047:     $gradeTable.= &Apache::loncommon::start_data_table().
                   1048: 	&Apache::loncommon::start_data_table_header_row();
1.110     ng       1049:     my $loop = 0;
                   1050:     while ($loop < 2) {
1.485     albertel 1051: 	$gradeTable.='<th>'.&mt('No.').'</th><th>'.&mt('Select').'</th>'.
                   1052: 	    '<th>'.&nameUserString('header').'&nbsp;'.&mt('Section/Group').'</th>';
1.301     albertel 1053: 	if ($env{'form.showgrading'} eq 'yes' 
                   1054: 	    && $submitonly ne 'queued'
                   1055: 	    && $submitonly ne 'all') {
1.485     albertel 1056: 	    foreach my $part (sort(@$partlist)) {
                   1057: 		my $display_part=
                   1058: 		    &get_display_part((split(/_/,$part))[0],$symb);
                   1059: 		$gradeTable.=
                   1060: 		    '<th>'.&mt('Part: [_1] Status',$display_part).'</th>';
1.110     ng       1061: 	    }
1.301     albertel 1062: 	} elsif ($submitonly eq 'queued') {
1.474     albertel 1063: 	    $gradeTable.='<th>'.&mt('Queue Status').'&nbsp;</th>';
1.110     ng       1064: 	}
                   1065: 	$loop++;
1.126     ng       1066: #	$gradeTable.='<td></td>' if ($loop%2 ==1);
1.41      ng       1067:     }
1.474     albertel 1068:     $gradeTable.=&Apache::loncommon::end_data_table_header_row()."\n";
1.41      ng       1069: 
1.45      ng       1070:     my $ctr = 0;
1.294     albertel 1071:     foreach my $student (sort 
                   1072: 			 {
                   1073: 			     if (lc($$fullname{$a}) ne lc($$fullname{$b})) {
                   1074: 				 return (lc($$fullname{$a}) cmp lc($$fullname{$b}));
                   1075: 			     }
                   1076: 			     return $a cmp $b;
                   1077: 			 }
                   1078: 			 (keys(%$fullname))) {
1.41      ng       1079: 	my ($uname,$udom) = split(/:/,$student);
1.301     albertel 1080: 
1.110     ng       1081: 	my %status = ();
1.301     albertel 1082: 
                   1083: 	if ($submitonly eq 'queued') {
                   1084: 	    my %queue_status = 
                   1085: 		&Apache::bridgetask::get_student_status($symb,$cdom,$cnum,
                   1086: 							$udom,$uname);
                   1087: 	    next if (!defined($queue_status{'gradingqueue'}));
                   1088: 	    $status{'gradingqueue'} = $queue_status{'gradingqueue'};
                   1089: 	}
                   1090: 
                   1091: 	if ($env{'form.showgrading'} eq 'yes' 
                   1092: 	    && $submitonly ne 'queued'
                   1093: 	    && $submitonly ne 'all') {
1.324     albertel 1094: 	    (%status) =&student_gradeStatus($symb,$udom,$uname,$partlist);
1.145     albertel 1095: 	    my $submitted = 0;
1.164     albertel 1096: 	    my $graded = 0;
1.248     albertel 1097: 	    my $incorrect = 0;
1.110     ng       1098: 	    foreach (keys(%status)) {
1.145     albertel 1099: 		$submitted = 1 if ($status{$_} ne 'nothing');
1.248     albertel 1100: 		$graded = 1 if ($status{$_} =~ /^ungraded/);
                   1101: 		$incorrect = 1 if ($status{$_} =~ /^incorrect/);
                   1102: 		
1.110     ng       1103: 		my ($foo,$partid,$foo1) = split(/\./,$_);
                   1104: 		if ($status{'resource.'.$partid.'.submitted_by'} ne '') {
1.145     albertel 1105: 		    $submitted = 0;
1.150     albertel 1106: 		    my ($part)=split(/\./,$partid);
1.110     ng       1107: 		    $gradeTable.='<input type="hidden" name="'.
1.150     albertel 1108: 			$student.':'.$part.':submitted_by" value="'.
1.110     ng       1109: 			$status{'resource.'.$partid.'.submitted_by'}.'" />';
                   1110: 		}
1.41      ng       1111: 	    }
1.248     albertel 1112: 	    
1.156     albertel 1113: 	    next if (!$submitted && ($submitonly eq 'yes' ||
                   1114: 				     $submitonly eq 'incorrect' ||
                   1115: 				     $submitonly eq 'graded'));
1.248     albertel 1116: 	    next if (!$graded && ($submitonly eq 'graded'));
                   1117: 	    next if (!$incorrect && $submitonly eq 'incorrect');
1.41      ng       1118: 	}
1.34      ng       1119: 
1.45      ng       1120: 	$ctr++;
1.249     albertel 1121: 	my $section = $classlist->{$student}->[&Apache::loncoursedata::CL_SECTION()];
1.452     banghart 1122:         my $group = $classlist->{$student}->[&Apache::loncoursedata::CL_GROUP()];
1.104     albertel 1123: 	if ( $perm{'vgr'} eq 'F' ) {
1.474     albertel 1124: 	    if ($ctr%2 ==1) {
                   1125: 		$gradeTable.= &Apache::loncommon::start_data_table_row();
                   1126: 	    }
1.126     ng       1127: 	    $gradeTable.='<td align="right">'.$ctr.'&nbsp;</td>'.
1.563     bisitz   1128:                '<td align="center"><label><input type="checkbox" name="stuinfo" value="'.
1.249     albertel 1129:                $student.':'.$$fullname{$student}.':::SECTION'.$section.
                   1130: 	       ')&nbsp;" />&nbsp;&nbsp;</label></td>'."\n".'<td>'.
                   1131: 	       &nameUserString(undef,$$fullname{$student},$uname,$udom).
1.474     albertel 1132: 	       '&nbsp;'.$section.($group ne '' ?'/'.$group:'').'</td>'."\n";
1.110     ng       1133: 
1.257     albertel 1134: 	    if ($env{'form.showgrading'} eq 'yes' && $submitonly ne 'all') {
1.524     raeburn  1135: 		foreach (sort(keys(%status))) {
1.485     albertel 1136: 		    next if ($_ =~ /^resource.*?submitted_by$/);
                   1137: 		    $gradeTable.='<td align="center">&nbsp;'.&mt($status{$_}).'&nbsp;</td>'."\n";
1.110     ng       1138: 		}
1.41      ng       1139: 	    }
1.126     ng       1140: #	    $gradeTable.='<td></td>' if ($ctr%2 ==1);
1.474     albertel 1141: 	    if ($ctr%2 ==0) {
                   1142: 		$gradeTable.=&Apache::loncommon::end_data_table_row()."\n";
                   1143: 	    }
1.41      ng       1144: 	}
                   1145:     }
1.110     ng       1146:     if ($ctr%2 ==1) {
1.126     ng       1147: 	$gradeTable.='<td>&nbsp;</td><td>&nbsp;</td><td>&nbsp;</td>';
1.301     albertel 1148: 	    if ($env{'form.showgrading'} eq 'yes' 
                   1149: 		&& $submitonly ne 'queued'
                   1150: 		&& $submitonly ne 'all') {
1.110     ng       1151: 		foreach (@$partlist) {
                   1152: 		    $gradeTable.='<td>&nbsp;</td>';
                   1153: 		}
1.301     albertel 1154: 	    } elsif ($submitonly eq 'queued') {
                   1155: 		$gradeTable.='<td>&nbsp;</td>';
1.110     ng       1156: 	    }
1.474     albertel 1157: 	$gradeTable.=&Apache::loncommon::end_data_table_row();
1.110     ng       1158:     }
                   1159: 
1.474     albertel 1160:     $gradeTable.=&Apache::loncommon::end_data_table()."\n".
1.589     bisitz   1161:         '<input type="button" '.
                   1162:         'onclick="javascript:checkSelect(this.form.stuinfo);" '.
                   1163:         'value="'.&mt('Next').' &rarr;" /></form>'."\n";
1.45      ng       1164:     if ($ctr == 0) {
1.96      albertel 1165: 	my $num_students=(scalar(keys(%$fullname)));
                   1166: 	if ($num_students eq 0) {
1.485     albertel 1167: 	    $gradeTable='<br />&nbsp;<span class="LC_warning">'.&mt('There are no students currently enrolled.').'</span>';
1.96      albertel 1168: 	} else {
1.171     albertel 1169: 	    my $submissions='submissions';
                   1170: 	    if ($submitonly eq 'incorrect') { $submissions = 'incorrect submissions'; }
                   1171: 	    if ($submitonly eq 'graded'   ) { $submissions = 'ungraded submissions'; }
1.301     albertel 1172: 	    if ($submitonly eq 'queued'   ) { $submissions = 'queued submissions'; }
1.398     albertel 1173: 	    $gradeTable='<br />&nbsp;<span class="LC_warning">'.
1.596.2.12.2.  4(raebur 1174:3): 		&mt('No '.$submissions.' found for this resource for any students. ([quant,_1,student] checked for '.$submissions.')',
1.485     albertel 1175: 		    $num_students).
                   1176: 		'</span><br />';
1.96      albertel 1177: 	}
1.46      ng       1178:     } elsif ($ctr == 1) {
1.474     albertel 1179: 	$gradeTable =~ s/type="checkbox"/type="checkbox" checked="checked"/;
1.45      ng       1180:     }
1.324     albertel 1181:     $gradeTable.=&show_grading_menu_form($symb);
1.45      ng       1182:     $request->print($gradeTable);
1.44      ng       1183:     return '';
1.10      ng       1184: }
                   1185: 
1.44      ng       1186: #---- Called from the listStudents routine
1.249     albertel 1187: 
                   1188: sub check_script {
                   1189:     my ($form, $type)=@_;
                   1190:     my $chkallscript='<script type="text/javascript">
                   1191:     function checkall() {
                   1192:         for (i=0; i<document.forms.'.$form.'.elements.length; i++) {
                   1193:             ele = document.forms.'.$form.'.elements[i];
                   1194:             if (ele.name == "'.$type.'") {
                   1195:             document.forms.'.$form.'.elements[i].checked=true;
                   1196:                                        }
                   1197:         }
                   1198:     }
                   1199: 
                   1200:     function checksec() {
                   1201:         for (i=0; i<document.forms.'.$form.'.elements.length; i++) {
                   1202:             ele = document.forms.'.$form.'.elements[i];
                   1203:            string = document.forms.'.$form.'.chksec.value;
                   1204:            if
                   1205:           (ele.value.indexOf(":::SECTION"+string)>0) {
                   1206:               document.forms.'.$form.'.elements[i].checked=true;
                   1207:             }
                   1208:         }
                   1209:     }
                   1210: 
                   1211: 
                   1212:     function uncheckall() {
                   1213:         for (i=0; i<document.forms.'.$form.'.elements.length; i++) {
                   1214:             ele = document.forms.'.$form.'.elements[i];
                   1215:             if (ele.name == "'.$type.'") {
                   1216:             document.forms.'.$form.'.elements[i].checked=false;
                   1217:                                        }
                   1218:         }
                   1219:     }
                   1220: 
                   1221: </script>'."\n";
                   1222:     return $chkallscript;
                   1223: }
                   1224: 
                   1225: sub check_buttons {
1.485     albertel 1226:     my $buttons.='<input type="button" onclick="checkall()" value="'.&mt('Check All').'" />';
                   1227:     $buttons.='<input type="button" onclick="uncheckall()" value="'.&mt('Uncheck All').'" />&nbsp;';
                   1228:     $buttons.='<input type="button" onclick="checksec()" value="'.&mt('Check Section/Group').'" />';
1.249     albertel 1229:     $buttons.='<input type="text" size="5" name="chksec" />&nbsp;';
                   1230:     return $buttons;
                   1231: }
                   1232: 
1.44      ng       1233: #     Displays the submissions for one student or a group of students
1.34      ng       1234: sub processGroup {
1.41      ng       1235:     my ($request)  = shift;
                   1236:     my $ctr        = 0;
1.155     albertel 1237:     my @stuchecked = &Apache::loncommon::get_env_multiple('form.stuinfo');
1.41      ng       1238:     my $total      = scalar(@stuchecked)-1;
1.45      ng       1239: 
1.396     banghart 1240:     foreach my $student (@stuchecked) {
                   1241: 	my ($uname,$udom,$fullname) = split(/:/,$student);
1.257     albertel 1242: 	$env{'form.student'}        = $uname;
                   1243: 	$env{'form.userdom'}        = $udom;
                   1244: 	$env{'form.fullname'}       = $fullname;
1.41      ng       1245: 	&submission($request,$ctr,$total);
                   1246: 	$ctr++;
                   1247:     }
                   1248:     return '';
1.35      ng       1249: }
1.34      ng       1250: 
1.44      ng       1251: #------------------------------------------------------------------------------------
                   1252: #
                   1253: #-------------------------- Next few routines handles grading by student, essentially
                   1254: #                           handles essay response type problem/part
                   1255: #
                   1256: #--- Javascript to handle the submission page functionality ---
                   1257: sub sub_page_js {
                   1258:     my $request = shift;
1.596.2.12.2.  6(raebur 1259:6):     my $alertmsg = &mt('A number equal or greater than 0 is expected. Entered value = ');
          7(raebur 1260:6):     &js_escape(\$alertmsg);
1.44      ng       1261:     $request->print(<<SUBJAVASCRIPT);
                   1262: <script type="text/javascript" language="javascript">
1.71      ng       1263:     function updateRadio(formname,id,weight) {
1.125     ng       1264: 	var gradeBox = formname["GD_BOX"+id];
                   1265: 	var radioButton = formname["RADVAL"+id];
                   1266: 	var oldpts = formname["oldpts"+id].value;
1.72      ng       1267: 	var pts = checkSolved(formname,id) == 'update' ? gradeBox.value : oldpts;
1.71      ng       1268: 	gradeBox.value = pts;
                   1269: 	var resetbox = false;
                   1270: 	if (isNaN(pts) || pts < 0) {
1.539     riegler  1271: 	    alert("$alertmsg"+pts);
1.71      ng       1272: 	    for (var i=0; i<radioButton.length; i++) {
                   1273: 		if (radioButton[i].checked) {
                   1274: 		    gradeBox.value = i;
                   1275: 		    resetbox = true;
                   1276: 		}
                   1277: 	    }
                   1278: 	    if (!resetbox) {
                   1279: 		formtextbox.value = "";
                   1280: 	    }
                   1281: 	    return;
1.44      ng       1282: 	}
1.71      ng       1283: 
                   1284: 	if (pts > weight) {
                   1285: 	    var resp = confirm("You entered a value ("+pts+
                   1286: 			       ") greater than the weight for the part. Accept?");
                   1287: 	    if (resp == false) {
1.125     ng       1288: 		gradeBox.value = oldpts;
1.71      ng       1289: 		return;
                   1290: 	    }
1.44      ng       1291: 	}
1.13      albertel 1292: 
1.71      ng       1293: 	for (var i=0; i<radioButton.length; i++) {
                   1294: 	    radioButton[i].checked=false;
                   1295: 	    if (pts == i && pts != "") {
                   1296: 		radioButton[i].checked=true;
                   1297: 	    }
                   1298: 	}
                   1299: 	updateSelect(formname,id);
1.125     ng       1300: 	formname["stores"+id].value = "0";
1.41      ng       1301:     }
1.5       albertel 1302: 
1.72      ng       1303:     function writeBox(formname,id,pts) {
1.125     ng       1304: 	var gradeBox = formname["GD_BOX"+id];
1.71      ng       1305: 	if (checkSolved(formname,id) == 'update') {
                   1306: 	    gradeBox.value = pts;
                   1307: 	} else {
1.125     ng       1308: 	    var oldpts = formname["oldpts"+id].value;
1.72      ng       1309: 	    gradeBox.value = oldpts;
1.125     ng       1310: 	    var radioButton = formname["RADVAL"+id];
1.71      ng       1311: 	    for (var i=0; i<radioButton.length; i++) {
                   1312: 		radioButton[i].checked=false;
1.72      ng       1313: 		if (i == oldpts) {
1.71      ng       1314: 		    radioButton[i].checked=true;
                   1315: 		}
                   1316: 	    }
1.41      ng       1317: 	}
1.125     ng       1318: 	formname["stores"+id].value = "0";
1.71      ng       1319: 	updateSelect(formname,id);
                   1320: 	return;
1.41      ng       1321:     }
1.44      ng       1322: 
1.71      ng       1323:     function clearRadBox(formname,id) {
                   1324: 	if (checkSolved(formname,id) == 'noupdate') {
                   1325: 	    updateSelect(formname,id);
                   1326: 	    return;
                   1327: 	}
1.125     ng       1328: 	gradeSelect = formname["GD_SEL"+id];
1.71      ng       1329: 	for (var i=0; i<gradeSelect.length; i++) {
                   1330: 	    if (gradeSelect[i].selected) {
                   1331: 		var selectx=i;
                   1332: 	    }
                   1333: 	}
1.125     ng       1334: 	var stores = formname["stores"+id];
1.71      ng       1335: 	if (selectx == stores.value) { return };
1.125     ng       1336: 	var gradeBox = formname["GD_BOX"+id];
1.71      ng       1337: 	gradeBox.value = "";
1.125     ng       1338: 	var radioButton = formname["RADVAL"+id];
1.71      ng       1339: 	for (var i=0; i<radioButton.length; i++) {
                   1340: 	    radioButton[i].checked=false;
                   1341: 	}
                   1342: 	stores.value = selectx;
                   1343:     }
1.5       albertel 1344: 
1.71      ng       1345:     function checkSolved(formname,id) {
1.125     ng       1346: 	if (formname["solved"+id].value == "correct_by_student" && formname.overRideScore.value == 'no') {
1.118     ng       1347: 	    var reply = confirm("This problem has been graded correct by the computer. Do you want to change the score?");
                   1348: 	    if (!reply) {return "noupdate";}
1.120     ng       1349: 	    formname.overRideScore.value = 'yes';
1.41      ng       1350: 	}
1.71      ng       1351: 	return "update";
1.13      albertel 1352:     }
1.71      ng       1353: 
                   1354:     function updateSelect(formname,id) {
1.125     ng       1355: 	formname["GD_SEL"+id][0].selected = true;
1.71      ng       1356: 	return;
1.41      ng       1357:     }
1.33      ng       1358: 
1.121     ng       1359: //=========== Check that a point is assigned for all the parts  ============
1.71      ng       1360:     function checksubmit(formname,val,total,parttot) {
1.121     ng       1361: 	formname.gradeOpt.value = val;
1.71      ng       1362: 	if (val == "Save & Next") {
                   1363: 	    for (i=0;i<=total;i++) {
                   1364: 		for (j=0;j<parttot;j++) {
1.125     ng       1365: 		    var partid = formname["partid"+i+"_"+j].value;
1.127     ng       1366: 		    if (formname["GD_SEL"+i+"_"+partid][0].selected) {
1.125     ng       1367: 			var points = formname["GD_BOX"+i+"_"+partid].value;
1.71      ng       1368: 			if (points == "") {
1.125     ng       1369: 			    var name = formname["name"+i].value;
1.129     ng       1370: 			    var studentID = (name != '' ? name : formname["unamedom"+i].value);
                   1371: 			    var resp = confirm("You did not assign a score for "+studentID+
                   1372: 					       ", part "+partid+". Continue?");
1.71      ng       1373: 			    if (resp == false) {
1.125     ng       1374: 				formname["GD_BOX"+i+"_"+partid].focus();
1.71      ng       1375: 				return false;
                   1376: 			    }
                   1377: 			}
                   1378: 		    }
                   1379: 		}
                   1380: 	    }
                   1381: 	}
1.121     ng       1382: 	if (val == "Grade Student") {
                   1383: 	    formname.showgrading.value = "yes";
                   1384: 	    if (formname.Status.value == "") {
                   1385: 		formname.Status.value = "Active";
                   1386: 	    }
                   1387: 	    formname.studentNo.value = total;
                   1388: 	}
1.120     ng       1389: 	formname.submit();
                   1390:     }
                   1391: 
1.71      ng       1392: //======= Check that a score is assigned for all the problems (page/sequence grading only) =========
                   1393:     function checkSubmitPage(formname,total) {
                   1394: 	noscore = new Array(100);
                   1395: 	var ptr = 0;
                   1396: 	for (i=1;i<total;i++) {
1.125     ng       1397: 	    var partid = formname["q_"+i].value;
1.127     ng       1398: 	    if (formname["GD_SEL"+i+"_"+partid][0].selected) {
1.125     ng       1399: 		var points = formname["GD_BOX"+i+"_"+partid].value;
                   1400: 		var status = formname["solved"+i+"_"+partid].value;
1.71      ng       1401: 		if (points == "" && status != "correct_by_student") {
                   1402: 		    noscore[ptr] = i;
                   1403: 		    ptr++;
                   1404: 		}
                   1405: 	    }
                   1406: 	}
                   1407: 	if (ptr != 0) {
                   1408: 	    var sense = ptr == 1 ? ": " : "s: ";
                   1409: 	    var prolist = "";
                   1410: 	    if (ptr == 1) {
                   1411: 		prolist = noscore[0];
                   1412: 	    } else {
                   1413: 		var i = 0;
                   1414: 		while (i < ptr-1) {
                   1415: 		    prolist += noscore[i]+", ";
                   1416: 		    i++;
                   1417: 		}
                   1418: 		prolist += "and "+noscore[i];
                   1419: 	    }
                   1420: 	    var resp = confirm("You did not assign any score for the following problem"+sense+prolist+". Continue?");
                   1421: 	    if (resp == false) {
                   1422: 		return false;
                   1423: 	    }
                   1424: 	}
1.45      ng       1425: 
1.71      ng       1426: 	formname.submit();
                   1427:     }
                   1428: </script>
                   1429: SUBJAVASCRIPT
                   1430: }
1.45      ng       1431: 
1.71      ng       1432: #--- javascript for essay type problem --
                   1433: sub sub_page_kw_js {
                   1434:     my $request = shift;
1.80      ng       1435:     my $iconpath = $request->dir_config('lonIconsURL');
1.118     ng       1436:     &commonJSfunctions($request);
1.350     albertel 1437: 
1.351     albertel 1438:     my $inner_js_msg_central=<<INNERJS;
1.350     albertel 1439:     <script text="text/javascript">
                   1440:     function checkInput() {
                   1441:       opener.document.SCORE.msgsub.value = opener.checkEntities(document.msgcenter.msgsub.value);
                   1442:       var nmsg   = opener.document.SCORE.savemsgN.value;
                   1443:       var usrctr = document.msgcenter.usrctr.value;
                   1444:       var newval = opener.document.SCORE["newmsg"+usrctr];
                   1445:       newval.value = opener.checkEntities(document.msgcenter.newmsg.value);
                   1446: 
                   1447:       var msgchk = "";
                   1448:       if (document.msgcenter.subchk.checked) {
                   1449:          msgchk = "msgsub,";
                   1450:       }
                   1451:       var includemsg = 0;
                   1452:       for (var i=1; i<=nmsg; i++) {
                   1453:           var opnmsg = opener.document.SCORE["savemsg"+i];
                   1454:           var frmmsg = document.msgcenter["msg"+i];
                   1455:           opnmsg.value = opener.checkEntities(frmmsg.value);
                   1456:           var showflg = opener.document.SCORE["shownOnce"+i];
                   1457:           showflg.value = "1";
                   1458:           var chkbox = document.msgcenter["msgn"+i];
                   1459:           if (chkbox.checked) {
                   1460:              msgchk += "savemsg"+i+",";
                   1461:              includemsg = 1;
                   1462:           }
                   1463:       }
                   1464:       if (document.msgcenter.newmsgchk.checked) {
                   1465:          msgchk += "newmsg"+usrctr;
                   1466:          includemsg = 1;
                   1467:       }
                   1468:       imgformname = opener.document.SCORE["mailicon"+usrctr];
                   1469:       imgformname.src = "$iconpath/"+((includemsg) ? "mailto.gif" : "mailbkgrd.gif");
                   1470:       var includemsg = opener.document.SCORE["includemsg"+usrctr];
                   1471:       includemsg.value = msgchk;
                   1472: 
                   1473:       self.close()
                   1474: 
                   1475:     }
                   1476:     </script>
                   1477: INNERJS
                   1478: 
1.351     albertel 1479:     my $inner_js_highlight_central=<<INNERJS;
                   1480:  <script type="text/javascript">
                   1481:     function updateChoice(flag) {
                   1482:       opener.document.SCORE.kwclr.value = opener.radioSelection(document.hlCenter.kwdclr);
                   1483:       opener.document.SCORE.kwsize.value = opener.radioSelection(document.hlCenter.kwdsize);
                   1484:       opener.document.SCORE.kwstyle.value = opener.radioSelection(document.hlCenter.kwdstyle);
                   1485:       opener.document.SCORE.refresh.value = "on";
                   1486:       if (opener.document.SCORE.keywords.value!=""){
                   1487:          opener.document.SCORE.submit();
                   1488:       }
                   1489:       self.close()
                   1490:     }
                   1491: </script>
                   1492: INNERJS
                   1493: 
                   1494:     my $start_page_msg_central = 
                   1495:         &Apache::loncommon::start_page('Message Central',$inner_js_msg_central,
                   1496: 				       {'js_ready'  => 1,
                   1497: 					'only_body' => 1,
                   1498: 					'bgcolor'   =>'#FFFFFF',});
                   1499:     my $end_page_msg_central = 
                   1500: 	&Apache::loncommon::end_page({'js_ready' => 1});
                   1501: 
                   1502: 
                   1503:     my $start_page_highlight_central = 
                   1504:         &Apache::loncommon::start_page('Highlight Central',
                   1505: 				       $inner_js_highlight_central,
1.350     albertel 1506: 				       {'js_ready'  => 1,
                   1507: 					'only_body' => 1,
                   1508: 					'bgcolor'   =>'#FFFFFF',});
1.351     albertel 1509:     my $end_page_highlight_central = 
1.350     albertel 1510: 	&Apache::loncommon::end_page({'js_ready' => 1});
                   1511: 
1.219     www      1512:     my $docopen=&Apache::lonhtmlcommon::javascript_docopen();
1.236     albertel 1513:     $docopen=~s/^document\.//;
1.596.2.12.2.  6(raebur 1514:6):     my %js_lt = &Apache::lonlocal::texthash(
1.596.2.4  raeburn  1515:                 keyw => 'Keywords list, separated by a space. Add/delete to list if desired.',
                   1516:                 plse => 'Please select a word or group of words from document and then click this link.',
                   1517:                 adds => 'Add selection to keyword list? Edit if desired.',
1.596.2.12.2.  6(raebur 1518:6):                 col1 => 'red',
                   1519:6):                 col2 => 'green',
                   1520:6):                 col3 => 'blue',
                   1521:6):                 siz1 => 'normal',
                   1522:6):                 siz2 => '+1',
                   1523:6):                 siz3 => '+2',
                   1524:6):                 sty1 => 'normal',
                   1525:6):                 sty2 => 'italic',
                   1526:6):                 sty3 => 'bold',
                   1527:6):              );
                   1528:6):     my %html_js_lt = &Apache::lonlocal::texthash(
1.596.2.4  raeburn  1529:                 comp => 'Compose Message for: ',
                   1530:                 incl => 'Include',
                   1531:                 type => 'Type',
                   1532:                 subj => 'Subject',
                   1533:                 mesa => 'Message',
                   1534:                 new  => 'New',
                   1535:                 save => 'Save',
                   1536:                 canc => 'Cancel',
                   1537:                 kehi => 'Keyword Highlight Options',
                   1538:                 txtc => 'Text Color',
                   1539:                 font => 'Font Size',
                   1540:                 fnst => 'Font Style',
                   1541:              );
1.596.2.12.2.  6(raebur 1542:6):     &js_escape(\%js_lt);
                   1543:6):     &html_escape(\%html_js_lt);
                   1544:6):     &js_escape(\%html_js_lt);
1.71      ng       1545:     $request->print(<<SUBJAVASCRIPT);
                   1546: <script type="text/javascript" language="javascript">
1.45      ng       1547: 
1.44      ng       1548: //===================== Show list of keywords ====================
1.122     ng       1549:   function keywords(formname) {
1.596.2.12.2.  6(raebur 1550:6):     var nret = prompt("$js_lt{'keyw'}",formname.keywords.value);
1.44      ng       1551:     if (nret==null) return;
1.122     ng       1552:     formname.keywords.value = nret;
1.44      ng       1553: 
1.122     ng       1554:     if (formname.keywords.value != "") {
1.128     ng       1555: 	formname.refresh.value = "on";
1.122     ng       1556: 	formname.submit();
1.44      ng       1557:     }
                   1558:     return;
                   1559:   }
                   1560: 
                   1561: //===================== Script to view submitted by ==================
                   1562:   function viewSubmitter(submitter) {
                   1563:     document.SCORE.refresh.value = "on";
                   1564:     document.SCORE.NCT.value = "1";
                   1565:     document.SCORE.unamedom0.value = submitter;
                   1566:     document.SCORE.submit();
                   1567:     return;
                   1568:   }
                   1569: 
                   1570: //===================== Script to add keyword(s) ==================
                   1571:   function getSel() {
                   1572:     if (document.getSelection) txt = document.getSelection();
                   1573:     else if (document.selection) txt = document.selection.createRange().text;
                   1574:     else return;
                   1575:     var cleantxt = txt.replace(new RegExp('([\\f\\n\\r\\t\\v ])+', 'g')," ");
                   1576:     if (cleantxt=="") {
1.596.2.12.2.  6(raebur 1577:6): 	alert("$js_lt{'plse'}");
1.44      ng       1578: 	return;
                   1579:     }
1.596.2.12.2.  6(raebur 1580:6):     var nret = prompt("$js_lt{'adds'}",cleantxt);
1.44      ng       1581:     if (nret==null) return;
1.127     ng       1582:     document.SCORE.keywords.value = document.SCORE.keywords.value+" "+nret;
1.44      ng       1583:     if (document.SCORE.keywords.value != "") {
1.127     ng       1584: 	document.SCORE.refresh.value = "on";
1.44      ng       1585: 	document.SCORE.submit();
                   1586:     }
                   1587:     return;
                   1588:   }
                   1589: 
                   1590: //====================== Script for composing message ==============
1.80      ng       1591:    // preload images
                   1592:    img1 = new Image();
                   1593:    img1.src = "$iconpath/mailbkgrd.gif";
                   1594:    img2 = new Image();
                   1595:    img2.src = "$iconpath/mailto.gif";
                   1596: 
1.44      ng       1597:   function msgCenter(msgform,usrctr,fullname) {
                   1598:     var Nmsg  = msgform.savemsgN.value;
                   1599:     savedMsgHeader(Nmsg,usrctr,fullname);
                   1600:     var subject = msgform.msgsub.value;
1.127     ng       1601:     var msgchk = document.SCORE["includemsg"+usrctr].value;
1.44      ng       1602:     re = /msgsub/;
                   1603:     var shwsel = "";
                   1604:     if (re.test(msgchk)) { shwsel = "checked" }
1.123     ng       1605:     subject = (document.SCORE.shownSub.value == 0 ? checkEntities(subject) : subject);
                   1606:     displaySubject(checkEntities(subject),shwsel);
1.44      ng       1607:     for (var i=1; i<=Nmsg; i++) {
1.123     ng       1608: 	var testmsg = "savemsg"+i+",";
                   1609: 	re = new RegExp(testmsg,"g");
1.44      ng       1610: 	shwsel = "";
                   1611: 	if (re.test(msgchk)) { shwsel = "checked" }
1.125     ng       1612: 	var message = document.SCORE["savemsg"+i].value;
1.126     ng       1613: 	message = (document.SCORE["shownOnce"+i].value == 0 ? checkEntities(message) : message);
1.123     ng       1614: 	displaySavedMsg(i,message,shwsel); //I do not get it. w/o checkEntities on saved messages,
                   1615: 	                                   //any &lt; is already converted to <, etc. However, only once!!
1.44      ng       1616:     }
1.125     ng       1617:     newmsg = document.SCORE["newmsg"+usrctr].value;
1.44      ng       1618:     shwsel = "";
                   1619:     re = /newmsg/;
                   1620:     if (re.test(msgchk)) { shwsel = "checked" }
                   1621:     newMsg(newmsg,shwsel);
                   1622:     msgTail(); 
                   1623:     return;
                   1624:   }
                   1625: 
1.123     ng       1626:   function checkEntities(strx) {
                   1627:     if (strx.length == 0) return strx;
                   1628:     var orgStr = ["&", "<", ">", '"']; 
                   1629:     var newStr = ["&amp;", "&lt;", "&gt;", "&quot;"];
                   1630:     var counter = 0;
                   1631:     while (counter < 4) {
                   1632: 	strx = strReplace(strx,orgStr[counter],newStr[counter]);
                   1633: 	counter++;
                   1634:     }
                   1635:     return strx;
                   1636:   }
                   1637: 
                   1638:   function strReplace(strx, orgStr, newStr) {
                   1639:     return strx.split(orgStr).join(newStr);
                   1640:   }
                   1641: 
1.44      ng       1642:   function savedMsgHeader(Nmsg,usrctr,fullname) {
1.76      ng       1643:     var height = 70*Nmsg+250;
1.44      ng       1644:     if (height > 600) {
                   1645: 	height = 600;
                   1646:     }
1.118     ng       1647:     var xpos = (screen.width-600)/2;
                   1648:     xpos = (xpos < 0) ? '0' : xpos;
                   1649:     var ypos = (screen.height-height)/2-30;
                   1650:     ypos = (ypos < 0) ? '0' : ypos;
                   1651: 
1.596.2.12.2.  (raeburn 1652:):     pWin = window.open('', 'MessageCenter', 'resizable=yes,toolbar=no,location=no,scrollbars=yes,screenx='+xpos+',screeny='+ypos+',width=700,height='+height);
1.76      ng       1653:     pWin.focus();
                   1654:     pDoc = pWin.document;
1.219     www      1655:     pDoc.$docopen;
1.351     albertel 1656:     pDoc.write('$start_page_msg_central');
1.76      ng       1657: 
                   1658:     pDoc.write("<form action=\\"inactive\\" name=\\"msgcenter\\">");
                   1659:     pDoc.write("<input value=\\""+usrctr+"\\" name=\\"usrctr\\" type=\\"hidden\\">");
1.596.2.12.2.  6(raebur 1660:6):     pDoc.write("<h3><span class=\\"LC_info\\">&nbsp;$html_js_lt{'comp'}\"+fullname+\"<\\/span><\\/h3><br /><br />");
1.76      ng       1661: 
1.564     bisitz   1662:     pDoc.write('<table border="0" width="100%"><tr><td bgcolor="#777777">');
                   1663:     pDoc.write('<table border="0" width="100%"><tr bgcolor="#DDFFFF">');
1.596.2.12.2.  6(raebur 1664:6):     pDoc.write("<td><b>$html_js_lt{'type'}<\\/b><\\/td><td><b>$html_js_lt{'incl'}<\\/b><\\/td><td><b>$html_js_lt{'mesa'}<\\/td><\\/tr>");
1.44      ng       1665: }
                   1666:     function displaySubject(msg,shwsel) {
1.76      ng       1667:     pDoc = pWin.document;
                   1668:     pDoc.write("<tr bgcolor=\\"#ffffdd\\">");
1.596.2.12.2.  6(raebur 1669:6):     pDoc.write("<td>$html_js_lt{'subj'}<\\/td>");
1.465     albertel 1670:     pDoc.write("<td align=\\"center\\"><input name=\\"subchk\\" type=\\"checkbox\\"" +shwsel+"><\\/td>");
                   1671:     pDoc.write("<td><input name=\\"msgsub\\" type=\\"text\\" value=\\""+msg+"\\"size=\\"60\\" maxlength=\\"80\\"><\\/td><\\/tr>");
1.44      ng       1672: }
                   1673: 
1.72      ng       1674:   function displaySavedMsg(ctr,msg,shwsel) {
1.76      ng       1675:     pDoc = pWin.document;
                   1676:     pDoc.write("<tr bgcolor=\\"#ffffdd\\">");
1.465     albertel 1677:     pDoc.write("<td align=\\"center\\">"+ctr+"<\\/td>");
                   1678:     pDoc.write("<td align=\\"center\\"><input name=\\"msgn"+ctr+"\\" type=\\"checkbox\\"" +shwsel+"><\\/td>");
                   1679:     pDoc.write("<td><textarea name=\\"msg"+ctr+"\\" cols=\\"60\\" rows=\\"3\\">"+msg+"<\\/textarea><\\/td><\\/tr>");
1.44      ng       1680: }
                   1681: 
                   1682:   function newMsg(newmsg,shwsel) {
1.76      ng       1683:     pDoc = pWin.document;
                   1684:     pDoc.write("<tr bgcolor=\\"#ffffdd\\">");
1.596.2.12.2.  6(raebur 1685:6):     pDoc.write("<td align=\\"center\\">$html_js_lt{'new'}<\\/td>");
1.465     albertel 1686:     pDoc.write("<td align=\\"center\\"><input name=\\"newmsgchk\\" type=\\"checkbox\\"" +shwsel+"><\\/td>");
                   1687:     pDoc.write("<td><textarea name=\\"newmsg\\" cols=\\"60\\" rows=\\"3\\" onchange=\\"javascript:this.form.newmsgchk.checked=true\\" >"+newmsg+"<\\/textarea><\\/td><\\/tr>");
1.44      ng       1688: }
                   1689: 
                   1690:   function msgTail() {
1.76      ng       1691:     pDoc = pWin.document;
1.465     albertel 1692:     pDoc.write("<\\/table>");
                   1693:     pDoc.write("<\\/td><\\/tr><\\/table>&nbsp;");
1.596.2.12.2.  6(raebur 1694:6):     pDoc.write("<input type=\\"button\\" value=\\"$html_js_lt{'save'}\\" onclick=\\"javascript:checkInput()\\">&nbsp;&nbsp;");
                   1695:6):     pDoc.write("<input type=\\"button\\" value=\\"$html_js_lt{'canc'}\\" onclick=\\"self.close()\\"><br /><br />");
1.465     albertel 1696:     pDoc.write("<\\/form>");
1.351     albertel 1697:     pDoc.write('$end_page_msg_central');
1.128     ng       1698:     pDoc.close();
1.44      ng       1699: }
                   1700: 
                   1701: //====================== Script for keyword highlight options ==============
                   1702:   function kwhighlight() {
                   1703:     var kwclr    = document.SCORE.kwclr.value;
                   1704:     var kwsize   = document.SCORE.kwsize.value;
                   1705:     var kwstyle  = document.SCORE.kwstyle.value;
                   1706:     var redsel = "";
                   1707:     var grnsel = "";
                   1708:     var blusel = "";
1.596.2.12.2.  6(raebur 1709:6):     var txtcol1 = "$js_lt{'col1'}";
                   1710:6):     var txtcol2 = "$js_lt{'col2'}";
                   1711:6):     var txtcol3 = "$js_lt{'col3'}";
                   1712:6):     var txtsiz1 = "$js_lt{'siz1'}";
                   1713:6):     var txtsiz2 = "$js_lt{'siz2'}";
                   1714:6):     var txtsiz3 = "$js_lt{'siz3'}";
                   1715:6):     var txtsty1 = "$js_lt{'sty1'}";
                   1716:6):     var txtsty2 = "$js_lt{'sty2'}";
                   1717:6):     var txtsty3 = "$js_lt{'sty3'}";
          8(raebur 1718:4):     if (kwclr=="red")   {var redsel="checked='checked'"};
                   1719:4):     if (kwclr=="green") {var grnsel="checked='checked'"};
                   1720:4):     if (kwclr=="blue")  {var blusel="checked='checked'"};
1.44      ng       1721:     var sznsel = "";
                   1722:     var sz1sel = "";
                   1723:     var sz2sel = "";
1.596.2.12.2.  8(raebur 1724:4):     if (kwsize=="0")  {var sznsel="checked='checked'"};
                   1725:4):     if (kwsize=="+1") {var sz1sel="checked='checked'"};
                   1726:4):     if (kwsize=="+2") {var sz2sel="checked='checked'"};
1.44      ng       1727:     var synsel = "";
                   1728:     var syisel = "";
                   1729:     var sybsel = "";
1.596.2.12.2.  8(raebur 1730:4):     if (kwstyle=="")    {var synsel="checked='checked'"};
                   1731:4):     if (kwstyle=="<i>") {var syisel="checked='checked'"};
                   1732:4):     if (kwstyle=="<b>") {var sybsel="checked='checked'"};
1.44      ng       1733:     highlightCentral();
1.596.2.12.2.  8(raebur 1734:4):     highlightbody('red',txtcol1,redsel,'0',txtsiz1,sznsel,'',txtsty1,synsel);
                   1735:4):     highlightbody('green',txtcol2,grnsel,'+1',txtsiz2,sz1sel,'<i>',txtsty2,syisel);
                   1736:4):     highlightbody('blue',txtcol3,blusel,'+2',txtsiz3,sz2sel,'<b>',txtsty3,sybsel);
1.44      ng       1737:     highlightend();
                   1738:     return;
                   1739:   }
                   1740: 
                   1741:   function highlightCentral() {
1.76      ng       1742: //    if (window.hwdWin) window.hwdWin.close();
1.118     ng       1743:     var xpos = (screen.width-400)/2;
                   1744:     xpos = (xpos < 0) ? '0' : xpos;
                   1745:     var ypos = (screen.height-330)/2-30;
                   1746:     ypos = (ypos < 0) ? '0' : ypos;
                   1747: 
1.206     albertel 1748:     hwdWin = window.open('', 'KeywordHighlightCentral', 'resizeable=yes,toolbar=no,location=no,scrollbars=no,width=400,height=300,screenx='+xpos+',screeny='+ypos);
1.76      ng       1749:     hwdWin.focus();
                   1750:     var hDoc = hwdWin.document;
1.219     www      1751:     hDoc.$docopen;
1.351     albertel 1752:     hDoc.write('$start_page_highlight_central');
1.76      ng       1753:     hDoc.write("<form action=\\"inactive\\" name=\\"hlCenter\\">");
1.596.2.12.2.  6(raebur 1754:6):     hDoc.write("<h1>$html_js_lt{'kehi'}<\\/h1>");
1.76      ng       1755: 
1.596.2.12.2.  8(raebur 1756:4):     hDoc.write('<table border="0" width="100%"><tr style="background-color:#A1D676">');
          6(raebur 1757:6):     hDoc.write("<th>$html_js_lt{'txtc'}<\\/th><th>$html_js_lt{'font'}<\\/th><th>$html_js_lt{'fnst'}<\\/th><\\/tr>");
1.44      ng       1758:   }
                   1759: 
                   1760:   function highlightbody(clrval,clrtxt,clrsel,szval,sztxt,szsel,syval,sytxt,sysel) { 
1.76      ng       1761:     var hDoc = hwdWin.document;
1.596.2.12.2.  8(raebur 1762:4):     hDoc.write("<tr>");
1.76      ng       1763:     hDoc.write("<td align=\\"left\\">");
1.596.2.12.2.  8(raebur 1764:4):     hDoc.write("<input name=\\"kwdclr\\" type=\\"radio\\" value=\\""+clrval+"\\" "+clrsel+" \\/>&nbsp;"+clrtxt+"<\\/td>");
1.76      ng       1765:     hDoc.write("<td align=\\"left\\">");
1.596.2.12.2.  8(raebur 1766:4):     hDoc.write("<input name=\\"kwdsize\\" type=\\"radio\\" value=\\""+szval+"\\" "+szsel+" \\/>&nbsp;"+sztxt+"<\\/td>");
1.76      ng       1767:     hDoc.write("<td align=\\"left\\">");
1.596.2.12.2.  8(raebur 1768:4):     hDoc.write("<input name=\\"kwdstyle\\" type=\\"radio\\" value=\\""+syval+"\\" "+sysel+" \\/>&nbsp;"+sytxt+"<\\/td>");
1.465     albertel 1769:     hDoc.write("<\\/tr>");
1.44      ng       1770:   }
                   1771: 
                   1772:   function highlightend() { 
1.76      ng       1773:     var hDoc = hwdWin.document;
1.596.2.12.2.  8(raebur 1774:4):     hDoc.write("<\\/table><br \\/>");
          6(raebur 1775:6):     hDoc.write("<input type=\\"button\\" value=\\"$html_js_lt{'save'}\\" onclick=\\"javascript:updateChoice(1)\\" \\/>&nbsp;&nbsp;");
                   1776:6):     hDoc.write("<input type=\\"button\\" value=\\"$html_js_lt{'canc'}\\" onclick=\\"self.close()\\" \\/><br /><br />");
1.465     albertel 1777:     hDoc.write("<\\/form>");
1.351     albertel 1778:     hDoc.write('$end_page_highlight_central');
1.128     ng       1779:     hDoc.close();
1.44      ng       1780:   }
                   1781: 
                   1782: </script>
                   1783: SUBJAVASCRIPT
                   1784: }
                   1785: 
1.349     albertel 1786: sub get_increment {
1.348     bowersj2 1787:     my $increment = $env{'form.increment'};
                   1788:     if ($increment != 1 && $increment != .5 && $increment != .25 &&
                   1789:         $increment != .1) {
                   1790:         $increment = 1;
                   1791:     }
                   1792:     return $increment;
                   1793: }
                   1794: 
1.585     bisitz   1795: sub gradeBox_start {
                   1796:     return (
                   1797:         &Apache::loncommon::start_data_table()
                   1798:        .&Apache::loncommon::start_data_table_header_row()
                   1799:        .'<th>'.&mt('Part').'</th>'
                   1800:        .'<th>'.&mt('Points').'</th>'
                   1801:        .'<th>&nbsp;</th>'
                   1802:        .'<th>'.&mt('Assign Grade').'</th>'
                   1803:        .'<th>'.&mt('Weight').'</th>'
                   1804:        .'<th>'.&mt('Grade Status').'</th>'
                   1805:        .&Apache::loncommon::end_data_table_header_row()
                   1806:     );
                   1807: }
                   1808: 
                   1809: sub gradeBox_end {
                   1810:     return (
                   1811:         &Apache::loncommon::end_data_table()
                   1812:     );
                   1813: }
1.71      ng       1814: #--- displays the grading box, used in essay type problem and grading by page/sequence
                   1815: sub gradeBox {
1.322     albertel 1816:     my ($request,$symb,$uname,$udom,$counter,$partid,$record) = @_;
1.381     albertel 1817:     my $checkIcon = '<img alt="'.&mt('Check Mark').
1.485     albertel 1818: 	'" src="'.&Apache::loncommon::lonhttpdurl($request->dir_config('lonIconsURL').'/check.gif').'" height="16" border="0" />';
1.71      ng       1819:     my $wgt    = &Apache::lonnet::EXT('resource.'.$partid.'.weight',$symb,$udom,$uname);
1.466     albertel 1820:     my $wgtmsg = ($wgt > 0) ? &mt('(problem weight)') 
                   1821:                            : '<span class="LC_info">'.&mt('problem weight assigned by computer').'</span>';
1.71      ng       1822:     $wgt       = ($wgt > 0 ? $wgt : '1');
                   1823:     my $score  = ($$record{'resource.'.$partid.'.awarded'} eq '' ?
1.320     albertel 1824: 		  '' : &compute_points($$record{'resource.'.$partid.'.awarded'},$wgt));
1.596.2.12.2.  8(raebur 1825:3):     my $data_WGT='<input type="hidden" name="WGT'.$counter.'_'.$partid.'" value="'.$wgt.'" />'."\n";
1.466     albertel 1826:     my $display_part= &get_display_part($partid,$symb);
1.270     albertel 1827:     my %last_resets = &get_last_resets($symb,$env{'request.course.id'},
                   1828: 				       [$partid]);
                   1829:     my $aggtries = $$record{'resource.'.$partid.'.tries'};
1.269     raeburn  1830:     if ($last_resets{$partid}) {
                   1831:         $aggtries = &get_num_tries($record,$last_resets{$partid},$partid);
                   1832:     }
1.596.2.12.2.  8(raebur 1833:3):     my $result=&Apache::loncommon::start_data_table_row();
1.71      ng       1834:     my $ctr = 0;
1.348     bowersj2 1835:     my $thisweight = 0;
1.349     albertel 1836:     my $increment = &get_increment();
1.485     albertel 1837: 
                   1838:     my $radio.='<table border="0"><tr>'."\n";  # display radio buttons in a nice table 10 across
1.348     bowersj2 1839:     while ($thisweight<=$wgt) {
1.532     bisitz   1840: 	$radio.= '<td><span class="LC_nobreak"><label><input type="radio" name="RADVAL'.$counter.'_'.$partid.'" '.
1.589     bisitz   1841:         'onclick="javascript:writeBox(this.form,\''.$counter.'_'.$partid.'\','.
1.348     bowersj2 1842: 	    $thisweight.')" value="'.$thisweight.'" '.
1.401     albertel 1843: 	    ($score eq $thisweight ? 'checked="checked"':'').' /> '.$thisweight."</label></span></td>\n";
1.485     albertel 1844: 	$radio.=(($ctr+1)%10 == 0 ? '</tr><tr>' : '');
1.348     bowersj2 1845:         $thisweight += $increment;
1.71      ng       1846: 	$ctr++;
                   1847:     }
1.485     albertel 1848:     $radio.='</tr></table>';
                   1849: 
                   1850:     my $line.='<input type="text" name="GD_BOX'.$counter.'_'.$partid.'"'.
1.71      ng       1851: 	($score ne ''? ' value = "'.$score.'"':'').' size="4" '.
1.589     bisitz   1852: 	'onchange="javascript:updateRadio(this.form,\''.$counter.'_'.$partid.'\','.
1.71      ng       1853: 	$wgt.')" /></td>'."\n";
1.485     albertel 1854:     $line.='<td>/'.$wgt.' '.$wgtmsg.
1.71      ng       1855: 	($$record{'resource.'.$partid.'.solved'} eq 'correct_by_student' ? '&nbsp;'.$checkIcon : '').
1.585     bisitz   1856: 	' </td>'."\n";
                   1857:     $line.='<td><select name="GD_SEL'.$counter.'_'.$partid.'" '.
1.589     bisitz   1858: 	'onchange="javascript:clearRadBox(this.form,\''.$counter.'_'.$partid.'\')" >'."\n";
1.71      ng       1859:     if ($$record{'resource.'.$partid.'.solved'} eq 'excused') {
1.485     albertel 1860: 	$line.='<option></option>'.
                   1861: 	    '<option value="excused" selected="selected">'.&mt('excused').'</option>';
1.71      ng       1862:     } else {
1.485     albertel 1863: 	$line.='<option selected="selected"></option>'.
                   1864: 	    '<option value="excused" >'.&mt('excused').'</option>';
1.71      ng       1865:     }
1.485     albertel 1866:     $line.='<option value="reset status">'.&mt('reset status').'</option></select>'."\n";
                   1867: 
                   1868: 
                   1869:     $result .= 
1.596.2.12.2.  8(raebur 1870:3): 	    '<td>'.$data_WGT.$display_part.'</td><td>'.$radio.'</td><td>'.&mt('or').'</td><td>'.$line.'</td>';
                   1871:3):     $result.=&Apache::loncommon::end_data_table_row().'<td colspan="6">';
1.71      ng       1872:     $result.='<input type="hidden" name="stores'.$counter.'_'.$partid.'" value="" />'."\n".
                   1873: 	'<input type="hidden" name="oldpts'.$counter.'_'.$partid.'" value="'.$score.'" />'."\n".
                   1874: 	'<input type="hidden" name="solved'.$counter.'_'.$partid.'" value="'.
1.269     raeburn  1875: 	$$record{'resource.'.$partid.'.solved'}.'" />'."\n".
                   1876:         '<input type="hidden" name="totaltries'.$counter.'_'.$partid.'" value="'.
                   1877:         $$record{'resource.'.$partid.'.tries'}.'" />'."\n".
                   1878:         '<input type="hidden" name="aggtries'.$counter.'_'.$partid.'" value="'.
                   1879:         $aggtries.'" />'."\n";
1.582     raeburn  1880:     my $res_error;
                   1881:     $result.=&handback_box($symb,$uname,$udom,$counter,$partid,$record,\$res_error);
1.596.2.12.2.  8(raebur 1882:3):     $result.='</td>'.&Apache::loncommon::end_data_table_row();
1.582     raeburn  1883:     if ($res_error) {
                   1884:         return &navmap_errormsg();
                   1885:     }
1.318     banghart 1886:     return $result;
                   1887: }
1.322     albertel 1888: 
                   1889: sub handback_box {
1.582     raeburn  1890:     my ($symb,$uname,$udom,$counter,$partid,$record,$res_error) = @_;
                   1891:     my ($partlist,$handgrade,$responseType) = &response_type($symb,$res_error);
1.323     banghart 1892:     my (@respids);
1.596.2.4  raeburn  1893:     my @part_response_id = &flatten_responseType($responseType);
1.375     albertel 1894:     foreach my $part_response_id (@part_response_id) {
                   1895:     	my ($part,$resp) = @{ $part_response_id };
1.323     banghart 1896:         if ($part eq $partid) {
1.375     albertel 1897:             push(@respids,$resp);
1.323     banghart 1898:         }
                   1899:     }
1.318     banghart 1900:     my $result;
1.323     banghart 1901:     foreach my $respid (@respids) {
1.322     albertel 1902: 	my $prefix = $counter.'_'.$partid.'_'.$respid.'_';
                   1903: 	my $files=&get_submitted_files($udom,$uname,$partid,$respid,$record);
                   1904: 	next if (!@$files);
1.596.2.4  raeburn  1905: 	my $file_counter = 0;
1.313     banghart 1906: 	foreach my $file (@$files) {
1.368     banghart 1907: 	    if ($file =~ /\/portfolio\//) {
1.596.2.4  raeburn  1908:                 $file_counter++;
1.368     banghart 1909:     	        my ($file_path, $file_disp) = ($file =~ m|(.+/)(.+)$|);
                   1910:     	        my ($name,$version,$ext) = &file_name_version_ext($file_disp);
                   1911:     	        $file_disp = "$name.$ext";
                   1912:     	        $file = $file_path.$file_disp;
                   1913:     	        $result.=&mt('Return commented version of [_1] to student.',
                   1914:     			 '<span class="LC_filename">'.$file_disp.'</span>');
                   1915:     	        $result.='<input type="file"   name="'.$prefix.'returndoc'.$file_counter.'" />'."\n";
1.596.2.4  raeburn  1916:     	        $result.='<input type="hidden" name="'.$prefix.'origdoc'.$file_counter.'" value="'.$file.'" /><br />'."\n";
1.368     banghart 1917: 	    }
1.322     albertel 1918: 	}
1.596.2.4  raeburn  1919:         if ($file_counter) {
                   1920:             $result .= '<input type="hidden" name="'.$prefix.'countreturndoc" value="'.$file_counter.'" />'."\n".
                   1921:                        '<span class="LC_info">'.
                   1922:                        '('.&mt('File(s) will be uploaded when you click on Save &amp; Next below.',$file_counter).')</span><br /><br />';
                   1923:         }
1.313     banghart 1924:     }
1.318     banghart 1925:     return $result;    
1.71      ng       1926: }
1.44      ng       1927: 
1.58      albertel 1928: sub show_problem {
1.382     albertel 1929:     my ($request,$symb,$uname,$udom,$removeform,$viewon,$mode,$form) = @_;
1.144     albertel 1930:     my $rendered;
1.382     albertel 1931:     my %form = ((ref($form) eq 'HASH')? %{$form} : ());
1.329     albertel 1932:     &Apache::lonxml::remember_problem_counter();
1.144     albertel 1933:     if ($mode eq 'both' or $mode eq 'text') {
                   1934: 	$rendered=&Apache::loncommon::get_student_view($symb,$uname,$udom,
1.382     albertel 1935: 						       $env{'request.course.id'},
                   1936: 						       undef,\%form);
1.144     albertel 1937:     }
1.58      albertel 1938:     if ($removeform) {
                   1939: 	$rendered=~s|<form(.*?)>||g;
                   1940: 	$rendered=~s|</form>||g;
1.374     albertel 1941: 	$rendered=~s|(<input[^>]*name\s*=\s*"?)(\w+)("?)|$1would_have_been_$2$3|g;
1.58      albertel 1942:     }
1.144     albertel 1943:     my $companswer;
                   1944:     if ($mode eq 'both' or $mode eq 'answer') {
1.329     albertel 1945: 	&Apache::lonxml::restore_problem_counter();
1.382     albertel 1946: 	$companswer=
                   1947: 	    &Apache::loncommon::get_student_answers($symb,$uname,$udom,
                   1948: 						    $env{'request.course.id'},
                   1949: 						    %form);
1.144     albertel 1950:     }
1.58      albertel 1951:     if ($removeform) {
                   1952: 	$companswer=~s|<form(.*?)>||g;
                   1953: 	$companswer=~s|</form>||g;
1.144     albertel 1954: 	$companswer=~s|name="submit"|name="would_have_been_submit"|g;
1.58      albertel 1955:     }
1.596.2.12.2.  (raeburn 1956:):     my $renderheading = &mt('View of the problem');
                   1957:):     my $answerheading = &mt('Correct answer');
                   1958:):     if (($uname ne $env{'user.name'}) || ($udom ne $env{'user.domain'})) {
                   1959:):         my $stu_fullname = $env{'form.fullname'};
                   1960:):         if ($stu_fullname eq '') {
                   1961:):             $stu_fullname = &Apache::loncommon::plainname($uname,$udom,'lastname');
                   1962:):         }
                   1963:):         my $forwhom = &nameUserString(undef,$stu_fullname,$uname,$udom);
                   1964:):         if ($forwhom ne '') {
                   1965:):             $renderheading = &mt('View of the problem for[_1]',$forwhom);
                   1966:):             $answerheading = &mt('Correct answer for[_1]',$forwhom);
                   1967:):         }
                   1968:):     }
1.468     albertel 1969:     $rendered=
1.588     bisitz   1970:         '<div class="LC_Box">'
1.596.2.12.2.  (raeburn 1971:):        .'<h3 class="LC_hcell">'.$renderheading.'</h3>'
1.588     bisitz   1972:        .$rendered
                   1973:        .'</div>';
1.468     albertel 1974:     $companswer=
1.588     bisitz   1975:         '<div class="LC_Box">'
1.596.2.12.2.  (raeburn 1976:):        .'<h3 class="LC_hcell">'.$answerheading.'</h3>'
1.588     bisitz   1977:        .$companswer
                   1978:        .'</div>';
1.468     albertel 1979:     my $result;
1.144     albertel 1980:     if ($mode eq 'both') {
1.588     bisitz   1981:         $result=$rendered.$companswer;
1.144     albertel 1982:     } elsif ($mode eq 'text') {
1.588     bisitz   1983:         $result=$rendered;
1.144     albertel 1984:     } elsif ($mode eq 'answer') {
1.588     bisitz   1985:         $result=$companswer;
1.144     albertel 1986:     }
1.71      ng       1987:     return $result;
1.58      albertel 1988: }
1.397     albertel 1989: 
1.396     banghart 1990: sub files_exist {
                   1991:     my ($r, $symb) = @_;
                   1992:     my @students = &Apache::loncommon::get_env_multiple('form.stuinfo');
1.397     albertel 1993: 
1.396     banghart 1994:     foreach my $student (@students) {
                   1995:         my ($uname,$udom,$fullname) = split(/:/,$student);
1.397     albertel 1996:         my %record = &Apache::lonnet::restore($symb,$env{'request.course.id'},
                   1997: 					      $udom,$uname);
1.396     banghart 1998:         my ($string,$timestamp)= &get_last_submission(\%record);
1.397     albertel 1999:         foreach my $submission (@$string) {
                   2000:             my ($partid,$respid) =
                   2001: 		($submission =~ /^resource\.([^\.]*)\.([^\.]*)\.submission/);
                   2002:             my $files=&get_submitted_files($udom,$uname,$partid,$respid,
                   2003: 					   \%record);
                   2004:             return 1 if (@$files);
1.396     banghart 2005:         }
                   2006:     }
1.397     albertel 2007:     return 0;
1.396     banghart 2008: }
1.397     albertel 2009: 
1.394     banghart 2010: sub download_all_link {
                   2011:     my ($r,$symb) = @_;
1.395     albertel 2012:     my $all_students = 
                   2013: 	join("\n", &Apache::loncommon::get_env_multiple('form.stuinfo'));
                   2014: 
                   2015:     my $parts =
                   2016: 	join("\n",&Apache::loncommon::get_env_multiple('form.vPart'));
                   2017: 
1.394     banghart 2018:     my $identifier = &Apache::loncommon::get_cgi_id();
1.514     raeburn  2019:     &Apache::lonnet::appenv({'cgi.'.$identifier.'.students' => $all_students,
                   2020:                              'cgi.'.$identifier.'.symb' => $symb,
                   2021:                              'cgi.'.$identifier.'.parts' => $parts,});
1.395     albertel 2022:     $r->print('<a href="/cgi-bin/multidownload.pl?'.$identifier.'">'.
                   2023: 	      &mt('Download All Submitted Documents').'</a>');
1.394     banghart 2024:     return
                   2025: }
1.395     albertel 2026: 
1.432     banghart 2027: sub build_section_inputs {
                   2028:     my $section_inputs;
                   2029:     if ($env{'form.section'} eq '') {
                   2030:         $section_inputs .= '<input type="hidden" name="section" value="all" />'."\n";
                   2031:     } else {
                   2032:         my @sections = &Apache::loncommon::get_env_multiple('form.section');
1.434     albertel 2033:         foreach my $section (@sections) {
1.432     banghart 2034:             $section_inputs .= '<input type="hidden" name="section" value="'.$section.'" />'."\n";
                   2035:         }
                   2036:     }
                   2037:     return $section_inputs;
                   2038: }
                   2039: 
1.44      ng       2040: # --------------------------- show submissions of a student, option to grade 
                   2041: sub submission {
                   2042:     my ($request,$counter,$total) = @_;
1.257     albertel 2043:     my ($uname,$udom)     = ($env{'form.student'},$env{'form.userdom'});
                   2044:     $udom = ($udom eq '' ? $env{'user.domain'} : $udom); #has form.userdom changed for a student?
                   2045:     my $usec = &Apache::lonnet::getsection($udom,$uname,$env{'request.course.id'});
                   2046:     $env{'form.fullname'} = &Apache::loncommon::plainname($uname,$udom,'lastname') if $env{'form.fullname'} eq '';
1.596.2.12.2.  (raeburn 2047:):     my ($symb) = &get_symb($request); 
1.324     albertel 2048:     if ($symb eq '') { $request->print("Unable to handle ambiguous references:."); return ''; }
1.104     albertel 2049: 
                   2050:     if (!&canview($usec)) {
1.596.2.12.2.  8(raebur 2051:4):         $request->print(
                   2052:4):             '<span class="LC_warning">'.
                   2053:4):             &mt('Unable to view requested student.').
                   2054:4):             ' '.&mt('([_1] in section [_2] in course id [_3])',
                   2055:4):                         $uname.':'.$udom,$usec,$env{'request.course.id'}).
                   2056:4):             '</span>');
1.324     albertel 2057: 	$request->print(&show_grading_menu_form($symb));
1.104     albertel 2058: 	return;
                   2059:     }
                   2060: 
1.257     albertel 2061:     if (!$env{'form.lastSub'}) { $env{'form.lastSub'} = 'datesub'; }
                   2062:     if (!$env{'form.vProb'}) { $env{'form.vProb'} = 'yes'; }
                   2063:     if (!$env{'form.vAns'}) { $env{'form.vAns'} = 'yes'; }
                   2064:     my $last = ($env{'form.lastSub'} eq 'last' ? 'last' : '');
1.381     albertel 2065:     my $checkIcon = '<img alt="'.&mt('Check Mark').
                   2066: 	'" src="'.$request->dir_config('lonIconsURL').
1.122     ng       2067: 	'/check.gif" height="16" border="0" />';
1.41      ng       2068: 
                   2069:     # header info
                   2070:     if ($counter == 0) {
                   2071: 	&sub_page_js($request);
1.257     albertel 2072: 	&sub_page_kw_js($request) if ($env{'form.handgrade'} eq 'yes');
                   2073: 	$env{'form.probTitle'} = $env{'form.probTitle'} eq '' ? 
                   2074: 	    &Apache::lonnet::gettitle($symb) : $env{'form.probTitle'};
1.397     albertel 2075: 	if ($env{'form.handgrade'} eq 'yes' && &files_exist($request, $symb)) {
1.396     banghart 2076: 	    &download_all_link($request, $symb);
                   2077: 	}
1.485     albertel 2078: 	$request->print('<h3>&nbsp;<span class="LC_info">'.&mt('Submission Record').'</span></h3>'."\n".
1.596.2.12.2.  2(raebur 2079:3): 			'<h4>&nbsp;'.&mt('[_1]Resource: [_2]','<b>','</b>'.$env{'form.probTitle'}).'</h4>'."\n");
1.118     ng       2080: 
1.44      ng       2081: 	# option to display problem, only once else it cause problems 
                   2082:         # with the form later since the problem has a form.
1.257     albertel 2083: 	if ($env{'form.vProb'} eq 'yes' or $env{'form.vAns'} eq 'yes') {
1.144     albertel 2084: 	    my $mode;
1.257     albertel 2085: 	    if ($env{'form.vProb'} eq 'yes' && $env{'form.vAns'} eq 'yes') {
1.144     albertel 2086: 		$mode='both';
1.257     albertel 2087: 	    } elsif ($env{'form.vProb'} eq 'yes') {
1.144     albertel 2088: 		$mode='text';
1.257     albertel 2089: 	    } elsif ($env{'form.vAns'} eq 'yes') {
1.144     albertel 2090: 		$mode='answer';
                   2091: 	    }
1.329     albertel 2092: 	    &Apache::lonxml::clear_problem_counter();
1.144     albertel 2093: 	    $request->print(&show_problem($request,$symb,$uname,$udom,0,1,$mode));
1.41      ng       2094: 	}
1.441     www      2095: 
1.596.2.12.2.  0(raebur 2096:3): 	# kwclr is the only variable that is guaranteed not to be blank 
1.44      ng       2097:         # if this subroutine has been called once.
1.41      ng       2098: 	my %keyhash = ();
1.257     albertel 2099: 	if ($env{'form.kwclr'} eq '' && $env{'form.handgrade'} eq 'yes') {
1.41      ng       2100: 	    %keyhash = &Apache::lonnet::dump('nohist_handgrade',
1.257     albertel 2101: 					     $env{'course.'.$env{'request.course.id'}.'.domain'},
                   2102: 					     $env{'course.'.$env{'request.course.id'}.'.num'});
1.41      ng       2103: 
1.257     albertel 2104: 	    my $loginuser = $env{'user.name'}.':'.$env{'user.domain'};
                   2105: 	    $env{'form.keywords'} = $keyhash{$symb.'_keywords'} ne '' ? $keyhash{$symb.'_keywords'} : '';
                   2106: 	    $env{'form.kwclr'}    = $keyhash{$loginuser.'_kwclr'} ne '' ? $keyhash{$loginuser.'_kwclr'} : 'red';
                   2107: 	    $env{'form.kwsize'}   = $keyhash{$loginuser.'_kwsize'} ne '' ? $keyhash{$loginuser.'_kwsize'} : '0';
                   2108: 	    $env{'form.kwstyle'}  = $keyhash{$loginuser.'_kwstyle'} ne '' ? $keyhash{$loginuser.'_kwstyle'} : '';
                   2109: 	    $env{'form.msgsub'}   = $keyhash{$symb.'_subject'} ne '' ? 
                   2110: 		$keyhash{$symb.'_subject'} : $env{'form.probTitle'};
                   2111: 	    $env{'form.savemsgN'} = $keyhash{$symb.'_savemsgN'} ne '' ? $keyhash{$symb.'_savemsgN'} : '0';
1.41      ng       2112: 	}
1.257     albertel 2113: 	my $overRideScore = $env{'form.overRideScore'} eq '' ? 'no' : $env{'form.overRideScore'};
1.442     banghart 2114: 	my $stu_status = join(':',&Apache::loncommon::get_env_multiple('form.Status'));
1.303     banghart 2115: 	$request->print('<form action="/adm/grades" method="post" name="SCORE" enctype="multipart/form-data">'."\n".
1.41      ng       2116: 			'<input type="hidden" name="command"    value="handgrade" />'."\n".
1.257     albertel 2117: 			'<input type="hidden" name="saveState"  value="'.$env{'form.saveState'}.'" />'."\n".
1.442     banghart 2118: 			'<input type="hidden" name="Status"     value="'.$stu_status.'" />'."\n".
1.120     ng       2119: 			'<input type="hidden" name="overRideScore" value="'.$overRideScore.'" />'."\n".
1.257     albertel 2120: 			'<input type="hidden" name="probTitle"  value="'.$env{'form.probTitle'}.'" />'."\n".
1.41      ng       2121: 			'<input type="hidden" name="refresh"    value="off" />'."\n".
1.120     ng       2122: 			'<input type="hidden" name="studentNo"  value="" />'."\n".
                   2123: 			'<input type="hidden" name="gradeOpt"   value="" />'."\n".
1.418     albertel 2124: 			'<input type="hidden" name="symb"       value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
1.257     albertel 2125: 			'<input type="hidden" name="showgrading" value="'.$env{'form.showgrading'}.'" />'."\n".
                   2126: 			'<input type="hidden" name="vProb"      value="'.$env{'form.vProb'}.'" />'."\n".
                   2127: 			'<input type="hidden" name="vAns"       value="'.$env{'form.vAns'}.'" />'."\n".
                   2128: 			'<input type="hidden" name="lastSub"    value="'.$env{'form.lastSub'}.'" />'."\n".
1.432     banghart 2129: 			&build_section_inputs().
1.326     albertel 2130: 			'<input type="hidden" name="submitonly" value="'.$env{'form.submitonly'}.'" />'."\n".
                   2131: 			'<input type="hidden" name="handgrade"  value="'.$env{'form.handgrade'}.'" />'."\n".
1.41      ng       2132: 			'<input type="hidden" name="NCT"'.
1.257     albertel 2133: 			' value="'.($env{'form.NTSTU'} ne '' ? $env{'form.NTSTU'} : $total+1).'" />'."\n");
                   2134: 	if ($env{'form.handgrade'} eq 'yes') {
                   2135: 	    $request->print('<input type="hidden" name="keywords" value="'.$env{'form.keywords'}.'" />'."\n".
                   2136: 			    '<input type="hidden" name="kwclr"    value="'.$env{'form.kwclr'}.'" />'."\n".
                   2137: 			    '<input type="hidden" name="kwsize"   value="'.$env{'form.kwsize'}.'" />'."\n".
                   2138: 			    '<input type="hidden" name="kwstyle"  value="'.$env{'form.kwstyle'}.'" />'."\n".
                   2139: 			    '<input type="hidden" name="msgsub"   value="'.$env{'form.msgsub'}.'" />'."\n".
1.123     ng       2140: 			    '<input type="hidden" name="shownSub" value="0" />'."\n".
1.257     albertel 2141: 			    '<input type="hidden" name="savemsgN" value="'.$env{'form.savemsgN'}.'" />'."\n");
1.154     albertel 2142: 	    foreach my $partid (&Apache::loncommon::get_env_multiple('form.vPart')) {
                   2143: 		$request->print('<input type="hidden" name="vPart" value="'.$partid.'" />'."\n");
                   2144: 	    }
1.123     ng       2145: 	}
1.41      ng       2146: 	
                   2147: 	my ($cts,$prnmsg) = (1,'');
1.257     albertel 2148: 	while ($cts <= $env{'form.savemsgN'}) {
1.41      ng       2149: 	    $prnmsg.='<input type="hidden" name="savemsg'.$cts.'" value="'.
1.123     ng       2150: 		(!exists($keyhash{$symb.'_savemsg'.$cts}) ? 
1.257     albertel 2151: 		 &Apache::lonfeedback::clear_out_html($env{'form.savemsg'.$cts}) :
1.80      ng       2152: 		 &Apache::lonfeedback::clear_out_html($keyhash{$symb.'_savemsg'.$cts})).
1.123     ng       2153: 		'" />'."\n".
                   2154: 		'<input type="hidden" name="shownOnce'.$cts.'" value="0" />'."\n";
1.41      ng       2155: 	    $cts++;
                   2156: 	}
                   2157: 	$request->print($prnmsg);
1.32      ng       2158: 
1.257     albertel 2159: 	if ($env{'form.handgrade'} eq 'yes' && $env{'form.showgrading'} eq 'yes') {
1.596.2.4  raeburn  2160: 
                   2161:             my %lt = &Apache::lonlocal::texthash(
1.596.2.12.2.  8(raebur 2162:4):                           keyh => 'Keyword Highlighting for Essays',
1.596.2.4  raeburn  2163:                           keyw => 'Keyword Options',
                   2164:                           list => 'List',
                   2165:                           past => 'Paste Selection to List',
1.596.2.9  raeburn  2166:                           high => 'Highlight Attribute',
1.596.2.4  raeburn  2167:                      );
1.88      www      2168: #
                   2169: # Print out the keyword options line
                   2170: #
1.596.2.12.2.  8(raebur 2171:4):             $request->print(
                   2172:4):                 '<div class="LC_columnSection">'
                   2173:4):                .'<fieldset><legend>'.$lt{'keyh'}.'</legend>'
                   2174:4):                .&Apache::lonhtmlcommon::funclist_from_array(
                   2175:4):                     ['<a href="javascript:keywords(document.SCORE);" target="_self">'.$lt{'list'}.'</a>',
                   2176:4):                      '<a href="#" onmousedown="javascript:getSel(); return false"
                   2177:4):  class="page">'.$lt{'past'}.'</a>',
                   2178:4):                      '<a href="javascript:kwhighlight();" target="_self">'.$lt{'high'}.'</a>'],
                   2179:4):                     {legend => $lt{'keyw'}})
                   2180:4):                .'</fieldset></div>'
                   2181:4):             );
                   2182:4): 
1.88      www      2183: #
                   2184: # Load the other essays for similarity check
                   2185: #
1.324     albertel 2186:             my (undef,undef,$essayurl) = &Apache::lonnet::decode_symb($symb);
1.384     albertel 2187: 	    my ($adom,$aname,$apath)=($essayurl=~/^($LONCAPA::domain_re)\/($LONCAPA::username_re)\/(.*)$/);
1.359     www      2188: 	    $apath=&escape($apath);
1.88      www      2189: 	    $apath=~s/\W/\_/gs;
1.596.2.12.2.  (raeburn 2190:):             &init_old_essays($symb,$apath,$adom,$aname);
1.41      ng       2191:         }
                   2192:     }
1.44      ng       2193: 
1.441     www      2194: # This is where output for one specific student would start
1.592     bisitz   2195:     my $add_class = ($counter%2) ? ' LC_grade_show_user_odd_row' : '';
                   2196:     $request->print(
                   2197:         "\n\n"
                   2198:        .'<div class="LC_grade_show_user'.$add_class.'">'
                   2199:        .'<h2>'.&nameUserString(undef,$env{'form.fullname'},$uname,$udom).'</h2>'
                   2200:        ."\n"
                   2201:     );
1.441     www      2202: 
1.592     bisitz   2203:     # Show additional functions if allowed
                   2204:     if ($perm{'vgr'}) {
                   2205:         $request->print(
                   2206:             &Apache::loncommon::track_student_link(
1.596.2.12.2.  4(raebur 2207:3):                 'View recent activity',
1.592     bisitz   2208:                 $uname,$udom,'check')
                   2209:            .' '
                   2210:         );
                   2211:     }
                   2212:     if ($perm{'opa'}) {
                   2213:         $request->print(
                   2214:             &Apache::loncommon::pprmlink(
                   2215:                 &mt('Set/Change parameters'),
                   2216:                 $uname,$udom,$symb,'check'));
                   2217:     }
                   2218: 
                   2219:     # Show Problem
1.257     albertel 2220:     if ($env{'form.vProb'} eq 'all' or $env{'form.vAns'} eq 'all') {
1.144     albertel 2221: 	my $mode;
1.257     albertel 2222: 	if ($env{'form.vProb'} eq 'all' && $env{'form.vAns'} eq 'all') {
1.144     albertel 2223: 	    $mode='both';
1.257     albertel 2224: 	} elsif ($env{'form.vProb'} eq 'all' ) {
1.144     albertel 2225: 	    $mode='text';
1.257     albertel 2226: 	} elsif ($env{'form.vAns'} eq 'all') {
1.144     albertel 2227: 	    $mode='answer';
                   2228: 	}
1.329     albertel 2229: 	&Apache::lonxml::clear_problem_counter();
1.475     albertel 2230: 	$request->print(&show_problem($request,$symb,$uname,$udom,1,1,$mode,{'request.prefix' => 'ctr'.$counter}));
1.58      albertel 2231:     }
1.144     albertel 2232: 
1.257     albertel 2233:     my %record = &Apache::lonnet::restore($symb,$env{'request.course.id'},$udom,$uname);
1.582     raeburn  2234:     my $res_error;
                   2235:     my ($partlist,$handgrade,$responseType) = &response_type($symb,\$res_error);
                   2236:     if ($res_error) {
                   2237:         $request->print(&navmap_errormsg());
                   2238:         return;
                   2239:     }
1.41      ng       2240: 
1.44      ng       2241:     # Display student info
1.41      ng       2242:     $request->print(($counter == 0 ? '' : '<br />'));
1.590     bisitz   2243: 
                   2244:     my $result='<div class="LC_Box">'
                   2245:               .'<h3 class="LC_hcell">'.&mt('Submissions').'</h3>';
1.45      ng       2246:     $result.='<input type="hidden" name="name'.$counter.
1.588     bisitz   2247:              '" value="'.$env{'form.fullname'}.'" />'."\n";
1.469     albertel 2248:     if ($env{'form.handgrade'} eq 'no') {
1.588     bisitz   2249:         $result.='<p class="LC_info">'
                   2250:                 .&mt('Part(s) graded correct by the computer is marked with a [_1] symbol.',$checkIcon)
                   2251:                 ."</p>\n";
1.469     albertel 2252:     }
                   2253: 
1.118     ng       2254:     # If any part of the problem is an essay-response (handgraded), then check for collaborators
1.464     albertel 2255:     my $fullname;
                   2256:     my $col_fullnames = [];
1.257     albertel 2257:     if ($env{'form.handgrade'} eq 'yes') {
1.464     albertel 2258: 	(my $sub_result,$fullname,$col_fullnames)=
                   2259: 	    &check_collaborators($symb,$uname,$udom,\%record,$handgrade,
                   2260: 				 $counter);
                   2261: 	$result.=$sub_result;
1.41      ng       2262:     }
1.44      ng       2263:     $request->print($result."\n");
1.588     bisitz   2264: 
1.44      ng       2265:     # print student answer/submission
1.588     bisitz   2266:     # Options are (1) Handgraded submission only
1.44      ng       2267:     #             (2) Last submission, includes submission that is not handgraded 
                   2268:     #                  (for multi-response type part)
                   2269:     #             (3) Last submission plus the parts info
                   2270:     #             (4) The whole record for this student
1.596.2.12.2.  1(raebur 2271:3): 
1.151     albertel 2272: 	my ($string,$timestamp)= &get_last_submission(\%record);
1.468     albertel 2273: 	
                   2274: 	my $lastsubonly;
                   2275: 
1.588     bisitz   2276:         if ($$timestamp eq '') {
                   2277:             $lastsubonly.='<div class="LC_grade_submissions_body">'.$$string[0].'</div>'; 
                   2278:         } else {
1.592     bisitz   2279:             $lastsubonly =
                   2280:                 '<div class="LC_grade_submissions_body">'
                   2281:                .'<b>'.&mt('Date Submitted:').'</b> '.$$timestamp."\n";
1.468     albertel 2282: 
1.151     albertel 2283: 	    my %seenparts;
1.375     albertel 2284: 	    my @part_response_id = &flatten_responseType($responseType);
                   2285: 	    foreach my $part (@part_response_id) {
1.393     albertel 2286: 		next if ($env{'form.lastSub'} eq 'hdgrade' 
                   2287: 			 && $$handgrade{$$part[0].'_'.$$part[1]} ne 'yes');
                   2288: 
1.375     albertel 2289: 		my ($partid,$respid) = @{ $part };
1.324     albertel 2290: 		my $display_part=&get_display_part($partid,$symb);
1.257     albertel 2291: 		if ($env{"form.$uname:$udom:$partid:submitted_by"}) {
1.151     albertel 2292: 		    if (exists($seenparts{$partid})) { next; }
                   2293: 		    $seenparts{$partid}=1;
1.596.2.12.2.  8(raebur 2294:3):                     $request->print(
                   2295:3):                         '<b>'.&mt('Part: [_1]',$display_part).'</b>'.
                   2296:3):                         ' <b>'.&mt('Collaborative submission by: [_1]',
                   2297:3):                                    '<a href="javascript:viewSubmitter(\''.
                   2298:3):                                    $env{"form.$uname:$udom:$partid:submitted_by"}.
                   2299:3):                                    '\');" target="_self">'.
                   2300:3):                                    $$fullname{$env{"form.$uname:$udom:$partid:submitted_by"}}.'</a>').
                   2301:3):                         '<br />');
1.151     albertel 2302: 		    next;
                   2303: 		}
                   2304: 		my $responsetype = $responseType->{$partid}->{$respid};
                   2305: 		if (!exists($record{"resource.$partid.$respid.submission"})) {
1.577     bisitz   2306:                     $lastsubonly.="\n".'<div class="LC_grade_submission_part">'.
                   2307:                         '<b>'.&mt('Part: [_1]',$display_part).'</b>'.
                   2308:                         ' <span class="LC_internal_info">'.
1.596.2.4  raeburn  2309:                         '('.&mt('Response ID: [_1]',$respid).')'.
1.577     bisitz   2310:                         '</span>&nbsp; &nbsp;'.
1.539     riegler  2311: 			'<span class="LC_warning">'.&mt('Nothing submitted - no attempts.').'</span><br /><br /></div>';
1.151     albertel 2312: 		    next;
                   2313: 		}
1.468     albertel 2314: 		foreach my $submission (@$string) {
                   2315: 		    my ($partid,$respid) = ($submission =~ /^resource\.([^\.]*)\.([^\.]*)\.submission/);
1.375     albertel 2316: 		    if (join('_',@{$part}) ne ($partid.'_'.$respid)) { next; }
1.596.2.12.2.  0(raebur 2317:4): 		    my ($ressub,$hide,$draft,$subval) = split(/:/,$submission,4);
1.151     albertel 2318: 		    # Similarity check
                   2319: 		    my $similar='';
1.596.2.2  raeburn  2320:                     my ($type,$trial,$rndseed);
                   2321:                     if ($hide eq 'rand') {
                   2322:                         $type = 'randomizetry';
                   2323:                         $trial = $record{"resource.$partid.tries"};
                   2324:                         $rndseed = $record{"resource.$partid.rndseed"};
                   2325:                     }
1.596.2.12.2.  1(raebur 2326:3): 		    if ($env{'form.checkPlag'}) {
1.151     albertel 2327: 			my ($oname,$odom,$ocrsid,$oessay,$osim)=
1.596.2.12.2.  (raeburn 2328:): 			    &most_similar($uname,$udom,$symb,$subval);
1.151     albertel 2329: 			if ($osim) {
                   2330: 			    $osim=int($osim*100.0);
1.426     albertel 2331: 			    my %old_course_desc = 
                   2332: 				&Apache::lonnet::coursedescription($ocrsid,
                   2333: 								   {'one_time' => 1});
                   2334: 
1.596.2.2  raeburn  2335:                             if ($hide eq 'anon') {
1.596     raeburn  2336:                                 $similar='<hr /><span class="LC_warning">'.&mt("Essay was found to be similar to another essay submitted for this assignment.").'<br />'.
                   2337:                                          &mt('As the current submission is for an anonymous survey, no other details are available.').'</span><hr />';
                   2338:                             } else {
                   2339: 			        $similar="<hr /><h3><span class=\"LC_warning\">".
                   2340: 				    &mt('Essay is [_1]% similar to an essay by [_2] in course [_3] (course id [_4]:[_5])',
                   2341: 				        $osim,
                   2342: 				        &Apache::loncommon::plainname($oname,$odom).' ('.$oname.':'.$odom.')',
                   2343: 				        $old_course_desc{'description'},
                   2344: 				        $old_course_desc{'num'},
                   2345: 				        $old_course_desc{'domain'}).
                   2346: 				    '</span></h3><blockquote><i>'.
                   2347: 				    &keywords_highlight($oessay).
                   2348: 				    '</i></blockquote><hr />';
                   2349:                             }
1.151     albertel 2350: 			}
1.150     albertel 2351: 		    }
1.596.2.2  raeburn  2352: 		    my $order=&get_order($partid,$respid,$symb,$uname,$udom,
                   2353:                                          undef,$type,$trial,$rndseed);
1.596.2.12.2.  1(raebur 2354:3):                     if ($env{'form.lastSub'} eq 'lastonly' || $env{'form.lastSub'} eq 'datesub' || $env{'form.lastSub'} =~ /^(last|all)$/ || ($env{'form.lastSub'} eq 'hdgrade' &&
                   2355:3):                          $$handgrade{$$part[0].'_'.$$part[1]} eq 'yes')) {
1.324     albertel 2356: 			my $display_part=&get_display_part($partid,$symb);
1.577     bisitz   2357:                         $lastsubonly.='<div class="LC_grade_submission_part">'.
                   2358:                             '<b>'.&mt('Part: [_1]',$display_part).'</b>'.
                   2359:                             ' <span class="LC_internal_info">'.
1.596.2.4  raeburn  2360:                             '('.&mt('Response ID: [_1]',$respid).')'.
                   2361:                             '</span>&nbsp; &nbsp;';
1.313     banghart 2362: 			my $files=&get_submitted_files($udom,$uname,$partid,$respid,\%record);
                   2363: 			if (@$files) {
1.596.2.2  raeburn  2364:                             if ($hide eq 'anon') {
1.596     raeburn  2365:                                 $lastsubonly.='<br />'.&mt('[quant,_1,file] uploaded to this anonymous survey',scalar(@{$files}));
                   2366:                             } else {
1.596.2.12.2.  8(raebur 2367:3):                                 $lastsubonly.='<br /><br />'.'<b>'.&mt('Submitted Files:').'</b>'
                   2368:3):                                             .'<br /><span class="LC_warning">';
                   2369:3):                                 if(@$files == 1) {
                   2370:3):                                     $lastsubonly .= &mt('Like all files provided by users, this file may contain viruses!');
                   2371:3):                                 } else {
                   2372:3):                                     $lastsubonly .= &mt('Like all files provided by users, these files may contain viruses!');
                   2373:3):                                 }
                   2374:3):                                 $lastsubonly .= '</span>';
                   2375:3): 
1.596     raeburn  2376:                                 foreach my $file (@$files) {
                   2377:                                     &Apache::lonnet::allowuploaded('/adm/grades',$file);
1.596.2.12.2.  8(raebur 2378:3):                                     $lastsubonly.='<br /><a href="'.$file.'?rawmode=1" target="lonGRDs"><img src="'.&Apache::loncommon::icon($file).'" border="0" alt="" /> '.$file.'</a>';
1.596     raeburn  2379:                                 }
                   2380:                             }
1.236     albertel 2381: 			    $lastsubonly.='<br />';
1.41      ng       2382: 			}
1.596.2.2  raeburn  2383:                         if ($hide eq 'anon') {
1.596.2.12.2.  8(raebur 2384:3):                             $lastsubonly.='<br /><b>'.&mt('Anonymous Survey').'</b>'; 
1.596     raeburn  2385:                         } else {
1.596.2.12.2.  0(raebur 2386:4): 			    $lastsubonly.='<br /><b>'.&mt('Submitted Answer:').' </b>';
                   2387:4):                             if ($draft) {
                   2388:4):                                 $lastsubonly.= ' <span class="LC_warning">'.&mt('Draft Copy').'</span>';
                   2389:4):                             }
                   2390:4):                             $subval =
1.596     raeburn  2391: 			        &cleanRecord($subval,$responsetype,$symb,$partid,
1.596.2.2  raeburn  2392: 					     $respid,\%record,$order,undef,$uname,$udom,$type,$trial,$rndseed);
1.596.2.12.2.  0(raebur 2393:4):                             if ($responsetype eq 'essay') {
                   2394:4):                                 $subval =~ s{\n}{<br />}g;
                   2395:4):                             }
                   2396:4):                             $lastsubonly.=$subval."\n";
1.596     raeburn  2397:                         }
1.151     albertel 2398: 			if ($similar) {$lastsubonly.="<br /><br />$similar\n";}
1.468     albertel 2399: 			$lastsubonly.='</div>';
1.41      ng       2400: 		    }
                   2401: 		}
                   2402: 	    }
1.588     bisitz   2403: 	    $lastsubonly.='</div>'."\n"; # End: LC_grade_submissions_body
1.151     albertel 2404: 	}
                   2405: 	$request->print($lastsubonly);
1.596.2.12.2.  1(raebur 2406:3):    if ($env{'form.lastSub'} eq 'datesub') {
1.324     albertel 2407: 	my (undef,$responseType,undef,$parts) = &showResourceInfo($symb);
1.148     albertel 2408: 	$request->print(&displaySubByDates($symb,\%record,$parts,$responseType,$checkIcon,$uname,$udom));
1.596.2.12.2.  1(raebur 2409:3):     }
                   2410:3):     if ($env{'form.lastSub'} =~ /^(last|all)$/) {
                   2411:5):         my $identifier = (&canmodify($usec)? $counter : '');
1.41      ng       2412: 	$request->print(&Apache::loncommon::get_previous_attempt($symb,$uname,$udom,
1.257     albertel 2413: 								 $env{'request.course.id'},
1.44      ng       2414: 								 $last,'.submission',
1.596.2.12.2.  1(raebur 2415:5): 								 'Apache::grades::keywords_highlight',
                   2416:5):                                                                  $usec,$identifier));
1.41      ng       2417:     }
1.120     ng       2418: 
1.121     ng       2419:     $request->print('<input type="hidden" name="unamedom'.$counter.'" value="'.$uname.':'
                   2420: 	.$udom.'" />'."\n");
1.44      ng       2421:     # return if view submission with no grading option
1.257     albertel 2422:     if ($env{'form.showgrading'} eq '' || (!&canmodify($usec))) {
1.120     ng       2423: 	my $toGrade.='<input type="button" value="Grade Student" '.
1.589     bisitz   2424: 	    'onclick="javascript:checksubmit(this.form,\'Grade Student\',\''
1.417     albertel 2425: 	    .$counter.'\');" target="_self" /> &nbsp;'."\n" if (&canmodify($usec));
1.468     albertel 2426: 	$toGrade.='</div>'."\n";
1.257     albertel 2427: 	if (($env{'form.command'} eq 'submission') || 
                   2428: 	    ($env{'form.command'} eq 'processGroup' && $counter == $total)) {
1.324     albertel 2429: 	    $toGrade.='</form>'.&show_grading_menu_form($symb); 
1.169     albertel 2430: 	}
1.180     albertel 2431: 	$request->print($toGrade);
1.41      ng       2432: 	return;
1.180     albertel 2433:     } else {
1.468     albertel 2434: 	$request->print('</div>'."\n");
1.41      ng       2435:     }
1.33      ng       2436: 
1.121     ng       2437:     # essay grading message center
1.257     albertel 2438:     if ($env{'form.handgrade'} eq 'yes') {
1.468     albertel 2439: 	my $result='<div class="LC_grade_message_center">';
                   2440:     
                   2441: 	$result.='<div class="LC_grade_message_center_header">'.
                   2442: 	    &mt('Send Message').'</div><div class="LC_grade_message_center_body">';
1.257     albertel 2443: 	my ($lastname,$givenn) = split(/,/,$env{'form.fullname'});
1.118     ng       2444: 	my $msgfor = $givenn.' '.$lastname;
1.464     albertel 2445: 	if (scalar(@$col_fullnames) > 0) {
                   2446: 	    my $lastone = pop(@$col_fullnames);
                   2447: 	    $msgfor .= ', '.(join ', ',@$col_fullnames).' and '.$lastone.'.';
1.118     ng       2448: 	}
                   2449: 	$msgfor =~ s/\'/\\'/g; #' stupid emacs - no! javascript
1.468     albertel 2450: 	$result.='<input type="hidden" name="includemsg'.$counter.'" value="" />'."\n".
1.121     ng       2451: 	    '<input type="hidden" name="newmsg'.$counter.'" value="" />'."\n";
                   2452: 	$result.='&nbsp;<a href="javascript:msgCenter(document.SCORE,'.$counter.
1.417     albertel 2453: 	    ',\''.$msgfor.'\');" target="_self">'.
1.596.2.12.2.  8(raebur 2454:3): 	    &mt('Compose message to student'.(scalar(@$col_fullnames) >= 1 ? 's' : '')).'</a><label> ('.
1.350     albertel 2455: 	    &mt('incl. grades').' <input type="checkbox" name="withgrades'.$counter.'" /></label>)'.
1.596.2.12.2.  8(raebur 2456:3): 	    ' <img src="'.$request->dir_config('lonIconsURL').
1.118     ng       2457: 	    '/mailbkgrd.gif" width="14" height="10" name="mailicon'.$counter.'" />'."\n".
1.298     www      2458: 	    '<br />&nbsp;('.
1.468     albertel 2459: 	    &mt('Message will be sent when you click on Save &amp; Next below.').")\n";
                   2460: 	$result.='</div></div>';
1.121     ng       2461: 	$request->print($result);
1.118     ng       2462:     }
1.41      ng       2463: 
                   2464:     my %seen = ();
                   2465:     my @partlist;
1.129     ng       2466:     my @gradePartRespid;
1.375     albertel 2467:     my @part_response_id = &flatten_responseType($responseType);
1.585     bisitz   2468:     $request->print(
1.588     bisitz   2469:         '<div class="LC_Box">'
                   2470:        .'<h3 class="LC_hcell">'.&mt('Assign Grades').'</h3>'
1.585     bisitz   2471:     );
1.592     bisitz   2472:     $request->print(&gradeBox_start());
1.375     albertel 2473:     foreach my $part_response_id (@part_response_id) {
                   2474:     	my ($partid,$respid) = @{ $part_response_id };
                   2475: 	my $part_resp = join('_',@{ $part_response_id });
1.322     albertel 2476: 	next if ($seen{$partid} > 0);
1.41      ng       2477: 	$seen{$partid}++;
1.393     albertel 2478: 	next if ($$handgrade{$part_resp} ne 'yes' 
                   2479: 		 && $env{'form.lastSub'} eq 'hdgrade');
1.524     raeburn  2480: 	push(@partlist,$partid);
                   2481: 	push(@gradePartRespid,$partid.'.'.$respid);
1.322     albertel 2482: 	$request->print(&gradeBox($request,$symb,$uname,$udom,$counter,$partid,\%record));
1.41      ng       2483:     }
1.585     bisitz   2484:     $request->print(&gradeBox_end()); # </div>
                   2485:     $request->print('</div>');
1.468     albertel 2486: 
                   2487:     $request->print('<div class="LC_grade_info_links">');
                   2488:     $request->print('</div>');
                   2489: 
1.45      ng       2490:     $result='<input type="hidden" name="partlist'.$counter.
                   2491: 	'" value="'.(join ":",@partlist).'" />'."\n";
1.129     ng       2492:     $result.='<input type="hidden" name="gradePartRespid'.
                   2493: 	'" value="'.(join ":",@gradePartRespid).'" />'."\n" if ($counter == 0);
1.45      ng       2494:     my $ctr = 0;
                   2495:     while ($ctr < scalar(@partlist)) {
                   2496: 	$result.='<input type="hidden" name="partid'.$counter.'_'.$ctr.'" value="'.
                   2497: 	    $partlist[$ctr].'" />'."\n";
                   2498: 	$ctr++;
                   2499:     }
1.468     albertel 2500:     $request->print($result.''."\n");
1.41      ng       2501: 
1.441     www      2502: # Done with printing info for one student
                   2503: 
1.468     albertel 2504:     $request->print('</div>');#LC_grade_show_user
1.441     www      2505: 
                   2506: 
1.41      ng       2507:     # print end of form
                   2508:     if ($counter == $total) {
1.592     bisitz   2509:         my $endform='<br /><hr /><table border="0"><tr><td>'."\n";
1.485     albertel 2510: 	$endform.='<input type="button" value="'.&mt('Save &amp; Next').'" '.
1.589     bisitz   2511: 	    'onclick="javascript:checksubmit(this.form,\'Save & Next\','.
1.417     albertel 2512: 	    $total.','.scalar(@partlist).');" target="_self" /> &nbsp;'."\n";
1.119     ng       2513: 	my $ntstu ='<select name="NTSTU">'.
                   2514: 	    '<option>1</option><option>2</option>'.
                   2515: 	    '<option>3</option><option>5</option>'.
                   2516: 	    '<option>7</option><option>10</option></select>'."\n";
1.257     albertel 2517: 	my $nsel = ($env{'form.NTSTU'} ne '' ? $env{'form.NTSTU'} : '1');
1.401     albertel 2518: 	$ntstu =~ s/<option>$nsel</<option selected="selected">$nsel</;
1.578     raeburn  2519:         $endform.=&mt('[_1]student(s)',$ntstu);
1.485     albertel 2520: 	$endform.='&nbsp;&nbsp;<input type="button" value="'.&mt('Previous').'" '.
1.589     bisitz   2521: 	    'onclick="javascript:checksubmit(this.form,\'Previous\');" target="_self" /> &nbsp;'."\n".
1.485     albertel 2522: 	    '<input type="button" value="'.&mt('Next').'" '.
1.589     bisitz   2523: 	    'onclick="javascript:checksubmit(this.form,\'Next\');" target="_self" /> &nbsp;';
1.592     bisitz   2524:         $endform.='<span class="LC_warning">'.
                   2525:                   &mt('(Next and Previous (student) do not save the scores.)').
                   2526:                   '</span>'."\n" ;
1.349     albertel 2527:         $endform.="<input type='hidden' value='".&get_increment().
1.348     bowersj2 2528:             "' name='increment' />";
1.485     albertel 2529: 	$endform.='</td></tr></table></form>';
1.324     albertel 2530: 	$endform.=&show_grading_menu_form($symb);
1.41      ng       2531: 	$request->print($endform);
                   2532:     }
                   2533:     return '';
1.38      ng       2534: }
                   2535: 
1.464     albertel 2536: sub check_collaborators {
                   2537:     my ($symb,$uname,$udom,$record,$handgrade,$counter) = @_;
                   2538:     my ($result,@col_fullnames);
                   2539:     my ($classlist,undef,$fullname) = &getclasslist('all','0');
                   2540:     foreach my $part (keys(%$handgrade)) {
                   2541: 	my $ncol = &Apache::lonnet::EXT('resource.'.$part.
                   2542: 					'.maxcollaborators',
                   2543: 					$symb,$udom,$uname);
                   2544: 	next if ($ncol <= 0);
                   2545: 	$part =~ s/\_/\./g;
                   2546: 	next if ($record->{'resource.'.$part.'.collaborators'} eq '');
                   2547: 	my (@good_collaborators, @bad_collaborators);
                   2548: 	foreach my $possible_collaborator
1.596.2.4  raeburn  2549: 	    (split(/[,;\s]+/,$record->{'resource.'.$part.'.collaborators'})) { 
1.464     albertel 2550: 	    $possible_collaborator =~ s/[\$\^\(\)]//g;
                   2551: 	    next if ($possible_collaborator eq '');
1.596.2.8  raeburn  2552: 	    my ($co_name,$co_dom) = split(/:/,$possible_collaborator);
1.464     albertel 2553: 	    $co_dom = $udom if (! defined($co_dom) || $co_dom =~ /^domain$/i);
                   2554: 	    next if ($co_name eq $uname && $co_dom eq $udom);
                   2555: 	    # Doing this grep allows 'fuzzy' specification
                   2556: 	    my @matches = grep(/^\Q$co_name\E:\Q$co_dom\E$/i, 
                   2557: 			       keys(%$classlist));
                   2558: 	    if (! scalar(@matches)) {
                   2559: 		push(@bad_collaborators, $possible_collaborator);
                   2560: 	    } else {
                   2561: 		push(@good_collaborators, @matches);
                   2562: 	    }
                   2563: 	}
                   2564: 	if (scalar(@good_collaborators) != 0) {
1.596.2.8  raeburn  2565: 	    $result.='<br />'.&mt('Collaborators:').'<ol>';
1.464     albertel 2566: 	    foreach my $name (@good_collaborators) {
                   2567: 		my ($lastname,$givenn) = split(/,/,$$fullname{$name});
                   2568: 		push(@col_fullnames, $givenn.' '.$lastname);
1.596.2.4  raeburn  2569: 		$result.='<li>'.$fullname->{$name}.'</li>';
1.464     albertel 2570: 	    }
1.596.2.4  raeburn  2571: 	    $result.='</ol><br />'."\n";
1.466     albertel 2572: 	    my ($part)=split(/\./,$part);
1.464     albertel 2573: 	    $result.='<input type="hidden" name="collaborator'.$counter.
                   2574: 		'" value="'.$part.':'.(join ':',@good_collaborators).'" />'.
                   2575: 		"\n";
                   2576: 	}
                   2577: 	if (scalar(@bad_collaborators) > 0) {
1.466     albertel 2578: 	    $result.='<div class="LC_warning">';
1.464     albertel 2579: 	    $result.=&mt('This student has submitted [quant,_1,invalid collaborator]: [_2]',scalar(@bad_collaborators),join(', ',@bad_collaborators));
                   2580: 	    $result .= '</div>';
                   2581: 	}         
                   2582: 	if (scalar(@bad_collaborators > $ncol)) {
1.466     albertel 2583: 	    $result .= '<div class="LC_warning">';
1.464     albertel 2584: 	    $result .= &mt('This student has submitted too many '.
                   2585: 		'collaborators.  Maximum is [_1].',$ncol);
                   2586: 	    $result .= '</div>';
                   2587: 	}
                   2588:     }
                   2589:     return ($result,$fullname,\@col_fullnames);
                   2590: }
                   2591: 
1.44      ng       2592: #--- Retrieve the last submission for all the parts
1.38      ng       2593: sub get_last_submission {
1.119     ng       2594:     my ($returnhash)=@_;
1.596     raeburn  2595:     my (@string,$timestamp,%lasthidden);
1.119     ng       2596:     if ($$returnhash{'version'}) {
1.46      ng       2597: 	my %lasthash=();
                   2598: 	my ($version);
1.119     ng       2599: 	for ($version=1;$version<=$$returnhash{'version'};$version++) {
1.397     albertel 2600: 	    foreach my $key (sort(split(/\:/,
                   2601: 					$$returnhash{$version.':keys'}))) {
                   2602: 		$lasthash{$key}=$$returnhash{$version.':'.$key};
                   2603: 		$timestamp = 
1.545     raeburn  2604: 		    &Apache::lonlocal::locallocaltime($$returnhash{$version.':timestamp'});
1.46      ng       2605: 	    }
                   2606: 	}
1.596.2.2  raeburn  2607:         my (%typeparts,%randombytry);
1.596     raeburn  2608:         my $showsurv = 
                   2609:             &Apache::lonnet::allowed('vas',$env{'request.course.id'});
                   2610:         foreach my $key (sort(keys(%lasthash))) {
                   2611:             if ($key =~ /\.type$/) {
                   2612:                 if (($lasthash{$key} eq 'anonsurvey') || 
1.596.2.2  raeburn  2613:                     ($lasthash{$key} eq 'anonsurveycred') ||
                   2614:                     ($lasthash{$key} eq 'randomizetry')) {
1.596     raeburn  2615:                     my ($ign,@parts) = split(/\./,$key);
                   2616:                     pop(@parts);
1.596.2.3  raeburn  2617:                     my $id = join('.',@parts);
1.596.2.2  raeburn  2618:                     if ($lasthash{$key} eq 'randomizetry') {
                   2619:                         $randombytry{$ign.'.'.$id} = $lasthash{$key};
                   2620:                     } else {
                   2621:                         unless ($showsurv) {
                   2622:                             $typeparts{$ign.'.'.$id} = $lasthash{$key};
                   2623:                         }
1.596     raeburn  2624:                     }
                   2625:                     delete($lasthash{$key});
                   2626:                 }
                   2627:             }
                   2628:         }
                   2629:         my @hidden = keys(%typeparts);
1.596.2.2  raeburn  2630:         my @randomize = keys(%randombytry);
1.397     albertel 2631: 	foreach my $key (keys(%lasthash)) {
                   2632: 	    next if ($key !~ /\.submission$/);
1.596     raeburn  2633:             my $hide;
                   2634:             if (@hidden) {
                   2635:                 foreach my $id (@hidden) {
                   2636:                     if ($key =~ /^\Q$id\E/) {
1.596.2.2  raeburn  2637:                         $hide = 'anon';
1.596     raeburn  2638:                         last;
                   2639:                     }
                   2640:                 }
                   2641:             }
1.596.2.2  raeburn  2642:             unless ($hide) {
                   2643:                 if (@randomize) {
1.596.2.12.2.  3(raebur 2644:5):                     foreach my $id (@randomize) {
1.596.2.2  raeburn  2645:                         if ($key =~ /^\Q$id\E/) {
                   2646:                             $hide = 'rand';
                   2647:                             last;
                   2648:                         }
                   2649:                     }
                   2650:                 }
                   2651:             }
1.397     albertel 2652: 	    my ($partid,$foo) = split(/submission$/,$key);
1.596.2.12.2.  0(raebur 2653:4): 	    my $draft  = $lasthash{$partid.'awarddetail'} eq 'DRAFT' ? 1: 0;
                   2654:4):             push(@string, join(':', $key, $hide, $draft, (
          8(raebur 2655:4):                 ref($lasthash{$key}) eq 'ARRAY' ?
                   2656:4):                     join(',', @{$lasthash{$key}}) : $lasthash{$key}) ));
1.41      ng       2657: 	}
                   2658:     }
1.397     albertel 2659:     if (!@string) {
                   2660: 	$string[0] =
1.539     riegler  2661: 	    '<span class="LC_warning">'.&mt('Nothing submitted - no attempts.').'</span>';
1.397     albertel 2662:     }
                   2663:     return (\@string,\$timestamp);
1.38      ng       2664: }
1.35      ng       2665: 
1.44      ng       2666: #--- High light keywords, with style choosen by user.
1.38      ng       2667: sub keywords_highlight {
1.44      ng       2668:     my $string    = shift;
1.257     albertel 2669:     my $size      = $env{'form.kwsize'} eq '0' ? '' : 'size='.$env{'form.kwsize'};
                   2670:     my $styleon   = $env{'form.kwstyle'} eq ''  ? '' : $env{'form.kwstyle'};
1.41      ng       2671:     (my $styleoff = $styleon) =~ s/\</\<\//;
1.257     albertel 2672:     my @keylist   = split(/[,\s+]/,$env{'form.keywords'});
1.398     albertel 2673:     foreach my $keyword (@keylist) {
                   2674: 	$string =~ s/\b\Q$keyword\E(\b|\.)/<font color\=$env{'form.kwclr'} $size\>$styleon$keyword$styleoff<\/font>/gi;
1.41      ng       2675:     }
                   2676:     return $string;
1.38      ng       2677: }
1.36      ng       2678: 
1.596.2.12.2.  (raeburn 2679:): # For Tasks provide a mechanism to display previous version for one specific student
                   2680:): 
                   2681:): sub show_previous_task_version {
                   2682:):     my ($request,$symb) = @_;
                   2683:):     if ($symb eq '') {
          8(raebur 2684:4):         $request->print(
                   2685:4):             '<span class="LC_error">'.
                   2686:4):             &mt('Unable to handle ambiguous references.').
                   2687:4):             '</span>');
          (raeburn 2688:):         return '';
                   2689:):     }
                   2690:):     my ($uname,$udom) = ($env{'form.student'},$env{'form.userdom'});
                   2691:):     my $usec = &Apache::lonnet::getsection($udom,$uname,$env{'request.course.id'});
                   2692:):     if (!&canview($usec)) {
          8(raebur 2693:4):         $request->print('<span class="LC_warning">'.
                   2694:4):                         &mt('Unable to view previous version for requested student.').
                   2695:4):                         ' '.&mt('([_1] in section [_2] in course id [_3])',
          9(raebur 2696:4):                                 $uname.':'.$udom,$usec,$env{'request.course.id'}).
          8(raebur 2697:4):                         '</span>');
          (raeburn 2698:):         return;
                   2699:):     }
                   2700:):     my $mode = 'both';
                   2701:):     my $isTask = ($symb =~/\.task$/);
                   2702:):     if ($isTask) {
                   2703:):         if ($env{'form.previousversion'} =~ /^\d+$/) {
                   2704:):             if ($env{'form.fullname'} eq '') {
                   2705:):                 $env{'form.fullname'} =
                   2706:):                     &Apache::loncommon::plainname($uname,$udom,'lastname');
                   2707:):             }
                   2708:):             my $probtitle=&Apache::lonnet::gettitle($symb);
                   2709:):             $request->print("\n\n".
                   2710:):                             '<div class="LC_grade_show_user">'.
                   2711:):                             '<h2>'.&nameUserString(undef,$env{'form.fullname'},$uname,$udom).
                   2712:):                             '</h2>'."\n");
                   2713:):             &Apache::lonxml::clear_problem_counter();
                   2714:):             $request->print(&show_problem($request,$symb,$uname,$udom,1,1,$mode,
                   2715:):                             {'previousversion' => $env{'form.previousversion'} }));
                   2716:):             $request->print("\n</div>");
                   2717:):         }
                   2718:):     }
                   2719:):     return;
                   2720:): }
                   2721:): 
                   2722:): sub choose_task_version_form {
                   2723:):     my ($symb,$uname,$udom,$nomenu) = @_;
                   2724:):     my $isTask = ($symb =~/\.task$/);
                   2725:):     my ($current,$version,$result,$js,$displayed,$rowtitle);
                   2726:):     if ($isTask) {
                   2727:):         my %record = &Apache::lonnet::restore($symb,$env{'request.course.id'},
                   2728:):                                               $udom,$uname);
                   2729:):         if (($record{'resource.0.version'} eq '') ||
                   2730:):             ($record{'resource.0.version'} < 2)) {
                   2731:):             return ($record{'resource.0.version'},
                   2732:):                     $record{'resource.0.version'},$result,$js);
                   2733:):         } else {
                   2734:):             $current = $record{'resource.0.version'};
                   2735:):         }
                   2736:):         if ($env{'form.previousversion'}) {
                   2737:):             $displayed = $env{'form.previousversion'};
                   2738:):             $rowtitle = &mt('Choose another version:')
                   2739:):         } else {
                   2740:):             $displayed = $current;
                   2741:):             $rowtitle = &mt('Show earlier version:');
                   2742:):         }
                   2743:):         $result = '<div class="LC_left_float">';
                   2744:):         my $list;
                   2745:):         my $numversions = 0;
                   2746:):         for (my $i=1; $i<=$record{'resource.0.version'}; $i++) {
                   2747:):             if ($i == $current) {
                   2748:):                 if (!$env{'form.previousversion'} || $nomenu) {
                   2749:):                     next;
                   2750:):                 } else {
                   2751:):                     $list .= '<option value="'.$i.'">'.&mt('Current').'</option>'."\n";
                   2752:):                     $numversions ++;
                   2753:):                 }
                   2754:):             } elsif (defined($record{'resource.'.$i.'.0.status'})) {
                   2755:):                 unless ($i == $env{'form.previousversion'}) {
                   2756:):                     $numversions ++;
                   2757:):                 }
                   2758:):                 $list .= '<option value="'.$i.'">'.$i.'</option>'."\n";
                   2759:):             }
                   2760:):         }
                   2761:):         if ($numversions) {
                   2762:):             $symb = &HTML::Entities::encode($symb,'<>"&');
                   2763:):             $result .=
                   2764:):                 '<form name="getprev" method="post" action=""'.
                   2765:):                 ' onsubmit="return previousVersion('."'$uname','$udom','$symb','$displayed'".');">'.
                   2766:):                 &Apache::loncommon::start_data_table().
                   2767:):                 &Apache::loncommon::start_data_table_row().
                   2768:):                 '<th align="left">'.$rowtitle.'</th>'.
                   2769:):                 '<td><select name="version">'.
                   2770:):                 '<option>'.&mt('Select').'</option>'.
                   2771:):                 $list.
                   2772:):                 '</select></td>'.
                   2773:):                 &Apache::loncommon::end_data_table_row();
                   2774:):             unless ($nomenu) {
                   2775:):                 $result .= &Apache::loncommon::start_data_table_row().
                   2776:):                 '<th align="left">'.&mt('Open in new window').'</th>'.
                   2777:):                 '<td><span class="LC_nobreak">'.
                   2778:):                 '<label><input type="radio" name="prevwin" value="1" />'.
                   2779:):                 &mt('Yes').'</label>'.
                   2780:):                 '<label><input type="radio" name="prevwin" value="0" checked="checked" />'.&mt('No').'</label>'.
                   2781:):                 '</span></td>'.
                   2782:):                 &Apache::loncommon::end_data_table_row();
                   2783:):             }
                   2784:):             $result .=
                   2785:):                 &Apache::loncommon::start_data_table_row().
                   2786:):                 '<th align="left">&nbsp;</th>'.
                   2787:):                 '<td>'.
                   2788:):                 '<input type="submit" name="prevsub" value="'.&mt('Display').'" />'.
                   2789:):                 '</td>'.
                   2790:):                 &Apache::loncommon::end_data_table_row().
                   2791:):                 &Apache::loncommon::end_data_table().
                   2792:):                 '</form>';
                   2793:):             $js = &previous_display_javascript($nomenu,$current);
                   2794:):         } elsif ($displayed && $nomenu) {
                   2795:):             $result .= '<a href="javascript:window.close()">'.&mt('Close window').'</a>';
                   2796:):         } else {
                   2797:):             $result .= &mt('No previous versions to show for this student');
                   2798:):         }
                   2799:):         $result .= '</div>';
                   2800:):     }
                   2801:):     return ($current,$displayed,$result,$js);
                   2802:): }
                   2803:): 
                   2804:): sub previous_display_javascript {
                   2805:):     my ($nomenu,$current) = @_;
                   2806:):     my $js = <<"JSONE";
                   2807:): <script type="text/javascript">
                   2808:): // <![CDATA[
                   2809:): function previousVersion(uname,udom,symb) {
                   2810:):     var current = '$current';
                   2811:):     var version = document.getprev.version.options[document.getprev.version.selectedIndex].value;
                   2812:):     var prevstr = new RegExp("^\\\\d+\$");
                   2813:):     if (!prevstr.test(version)) {
                   2814:):         return false;
                   2815:):     }
                   2816:):     var url = '';
                   2817:):     if (version == current) {
                   2818:):         url = '/adm/grades?student='+uname+'&userdom='+udom+'&symb='+symb+'&command=submission';
                   2819:):     } else {
                   2820:):         url = '/adm/grades?student='+uname+'&userdom='+udom+'&symb='+symb+'&command=versionsub&previousversion='+version;
                   2821:):     }
                   2822:): JSONE
                   2823:):     if ($nomenu) {
                   2824:):         $js .= <<"JSTWO";
                   2825:):     document.location.href = url;
                   2826:): JSTWO
                   2827:):     } else {
                   2828:):         $js .= <<"JSTHREE";
                   2829:):     var newwin = 0;
                   2830:):     for (var i=0; i<document.getprev.prevwin.length; i++) {
                   2831:):         if (document.getprev.prevwin[i].checked == true) {
                   2832:):             newwin = document.getprev.prevwin[i].value;
                   2833:):         }
                   2834:):     }
                   2835:):     if (newwin == 1) {
                   2836:):         var options = 'height=600,width=800,resizable=yes,scrollbars=yes,location=no,menubar=no,toolbar=no';
                   2837:):         url = url+'&inhibitmenu=yes';
                   2838:):         if (typeof(previousWin) == 'undefined' || previousWin.closed) {
                   2839:):             previousWin = window.open(url,'',options,1);
                   2840:):         } else {
                   2841:):             previousWin.location.href = url;
                   2842:):         }
                   2843:):         previousWin.focus();
                   2844:):         return false;
                   2845:):     } else {
                   2846:):         document.location.href = url;
                   2847:):         return false;
                   2848:):     }
                   2849:): JSTHREE
                   2850:):     }
                   2851:):     $js .= <<"ENDJS";
                   2852:):     return false;
                   2853:): }
                   2854:): // ]]>
                   2855:): </script>
                   2856:): ENDJS
                   2857:): 
                   2858:): }
                   2859:): 
1.44      ng       2860: #--- Called from submission routine
1.38      ng       2861: sub processHandGrade {
1.41      ng       2862:     my ($request) = shift;
1.596.2.12.2.  (raeburn 2863:):     my ($symb)   = &get_symb($request);
1.324     albertel 2864:     my (undef,undef,$url) = &Apache::lonnet::decode_symb($symb);
1.257     albertel 2865:     my $button = $env{'form.gradeOpt'};
                   2866:     my $ngrade = $env{'form.NCT'};
                   2867:     my $ntstu  = $env{'form.NTSTU'};
1.301     albertel 2868:     my $cdom   = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   2869:     my $cnum   = $env{'course.'.$env{'request.course.id'}.'.num'};
                   2870: 
1.44      ng       2871:     if ($button eq 'Save & Next') {
                   2872: 	my $ctr = 0;
                   2873: 	while ($ctr < $ngrade) {
1.257     albertel 2874: 	    my ($uname,$udom) = split(/:/,$env{'form.unamedom'.$ctr});
1.596.2.12.2.  1(raebur 2875:5): 	    my ($errorflag,$pts,$wgt,$numhidden) = 
                   2876:5):                 &saveHandGrade($request,$symb,$uname,$udom,$ctr);
1.71      ng       2877: 	    if ($errorflag eq 'no_score') {
                   2878: 		$ctr++;
                   2879: 		next;
                   2880: 	    }
1.104     albertel 2881: 	    if ($errorflag eq 'not_allowed') {
1.596.2.12.2.  8(raebur 2882:4):                 $request->print(
                   2883:4):                     '<span class="LC_error">'
                   2884:4):                    .&mt('Not allowed to modify grades for [_1]',"$uname:$udom")
                   2885:4):                    .'</span>');
1.104     albertel 2886: 		$ctr++;
                   2887: 		next;
                   2888: 	    }
1.596.2.12.2.  1(raebur 2889:5):             if ($numhidden) {
                   2890:5):                 $request->print(
                   2891:5):                     '<span class="LC_info">'
                   2892:5):                    .&mt('For [_1]: [quant,_2,transaction] hidden',"$uname:$udom",$numhidden)
                   2893:5):                    .'</span><br />');
                   2894:5):             }
1.257     albertel 2895: 	    my $includemsg = $env{'form.includemsg'.$ctr};
1.44      ng       2896: 	    my ($subject,$message,$msgstatus) = ('','','');
1.418     albertel 2897: 	    my $restitle = &Apache::lonnet::gettitle($symb);
                   2898:             my ($feedurl,$showsymb) =
                   2899: 		&get_feedurl_and_symb($symb,$uname,$udom);
                   2900: 	    my $messagetail;
1.62      albertel 2901: 	    if ($includemsg =~ /savemsg|newmsg\Q$ctr\E/) {
1.298     www      2902: 		$subject = $env{'form.msgsub'} if ($includemsg =~ /msgsub/);
1.295     www      2903: 		unless ($subject=~/\w/) { $subject=&mt('Grading Feedback'); }
1.386     raeburn  2904: 		$subject.=' ['.$restitle.']';
1.44      ng       2905: 		my (@msgnum) = split(/,/,$includemsg);
                   2906: 		foreach (@msgnum) {
1.257     albertel 2907: 		    $message.=$env{'form.'.$_} if ($_ =~ /savemsg|newmsg/ && $_ ne '');
1.44      ng       2908: 		}
1.80      ng       2909: 		$message =&Apache::lonfeedback::clear_out_html($message);
1.298     www      2910: 		if ($env{'form.withgrades'.$ctr}) {
                   2911: 		    $message.="\n\nPoint".($pts > 1 ? 's':'').' awarded = '.$pts.' out of '.$wgt;
1.386     raeburn  2912: 		    $messagetail = " for <a href=\"".
1.418     albertel 2913: 		                   $feedurl."?symb=$showsymb\">$env{'form.probTitle'}</a>";
1.386     raeburn  2914: 		}
                   2915: 		$msgstatus = 
                   2916:                     &Apache::lonmsg::user_normal_msg($uname,$udom,$subject,
                   2917: 						     $message.$messagetail,
1.418     albertel 2918:                                                      undef,$feedurl,undef,
1.386     raeburn  2919:                                                      undef,undef,$showsymb,
                   2920:                                                      $restitle);
1.574     bisitz   2921: 		$request->print('<br />'.&mt('Sending message to [_1]',$uname.':'.$udom).': '.
1.596.2.4  raeburn  2922: 				$msgstatus.'<br />');
1.44      ng       2923: 	    }
1.257     albertel 2924: 	    if ($env{'form.collaborator'.$ctr}) {
1.155     albertel 2925: 		my @collabstrs=&Apache::loncommon::get_env_multiple("form.collaborator$ctr");
1.150     albertel 2926: 		foreach my $collabstr (@collabstrs) {
                   2927: 		    my ($part,@collaborators) = split(/:/,$collabstr);
1.310     banghart 2928: 		    foreach my $collaborator (@collaborators) {
1.150     albertel 2929: 			my ($errorflag,$pts,$wgt) = 
1.324     albertel 2930: 			    &saveHandGrade($request,$symb,$collaborator,$udom,$ctr,
1.257     albertel 2931: 					   $env{'form.unamedom'.$ctr},$part);
1.150     albertel 2932: 			if ($errorflag eq 'not_allowed') {
1.362     albertel 2933: 			    $request->print("<span class=\"LC_error\">".&mt('Not allowed to modify grades for [_1]',"$collaborator:$udom")."</span>");
1.150     albertel 2934: 			    next;
1.418     albertel 2935: 			} elsif ($message ne '') {
                   2936: 			    my ($baseurl,$showsymb) = 
                   2937: 				&get_feedurl_and_symb($symb,$collaborator,
                   2938: 						      $udom);
                   2939: 			    if ($env{'form.withgrades'.$ctr}) {
                   2940: 				$messagetail = " for <a href=\"".
1.386     raeburn  2941:                                     $baseurl."?symb=$showsymb\">$env{'form.probTitle'}</a>";
1.150     albertel 2942: 			    }
1.418     albertel 2943: 			    $msgstatus = 
                   2944: 				&Apache::lonmsg::user_normal_msg($collaborator,$udom,$subject,$message.$messagetail,undef,$baseurl,undef,undef,undef,$showsymb,$restitle);
1.104     albertel 2945: 			}
1.44      ng       2946: 		    }
                   2947: 		}
                   2948: 	    }
                   2949: 	    $ctr++;
                   2950: 	}
                   2951:     }
                   2952: 
1.257     albertel 2953:     if ($env{'form.handgrade'} eq 'yes') {
1.119     ng       2954: 	# Keywords sorted in alphabatical order
1.257     albertel 2955: 	my $loginuser = $env{'user.name'}.':'.$env{'user.domain'};
1.119     ng       2956: 	my %keyhash = ();
1.257     albertel 2957: 	$env{'form.keywords'}           =~ s/,\s{0,}|\s+/ /g;
                   2958: 	$env{'form.keywords'}           =~ s/^\s+|\s+$//;
                   2959: 	my (@keywords) = sort(split(/\s+/,$env{'form.keywords'}));
                   2960: 	$env{'form.keywords'} = join(' ',@keywords);
                   2961: 	$keyhash{$symb.'_keywords'}     = $env{'form.keywords'};
                   2962: 	$keyhash{$symb.'_subject'}      = $env{'form.msgsub'};
                   2963: 	$keyhash{$loginuser.'_kwclr'}   = $env{'form.kwclr'};
                   2964: 	$keyhash{$loginuser.'_kwsize'}  = $env{'form.kwsize'};
                   2965: 	$keyhash{$loginuser.'_kwstyle'} = $env{'form.kwstyle'};
1.119     ng       2966: 
                   2967: 	# message center - Order of message gets changed. Blank line is eliminated.
1.257     albertel 2968: 	# New messages are saved in env for the next student.
1.119     ng       2969: 	# All messages are saved in nohist_handgrade.db
                   2970: 	my ($ctr,$idx) = (1,1);
1.257     albertel 2971: 	while ($ctr <= $env{'form.savemsgN'}) {
                   2972: 	    if ($env{'form.savemsg'.$ctr} ne '') {
                   2973: 		$keyhash{$symb.'_savemsg'.$idx} = $env{'form.savemsg'.$ctr};
1.119     ng       2974: 		$idx++;
                   2975: 	    }
                   2976: 	    $ctr++;
1.41      ng       2977: 	}
1.119     ng       2978: 	$ctr = 0;
                   2979: 	while ($ctr < $ngrade) {
1.257     albertel 2980: 	    if ($env{'form.newmsg'.$ctr} ne '') {
                   2981: 		$keyhash{$symb.'_savemsg'.$idx} = $env{'form.newmsg'.$ctr};
                   2982: 		$env{'form.savemsg'.$idx} = $env{'form.newmsg'.$ctr};
1.119     ng       2983: 		$idx++;
                   2984: 	    }
                   2985: 	    $ctr++;
1.41      ng       2986: 	}
1.257     albertel 2987: 	$env{'form.savemsgN'} = --$idx;
                   2988: 	$keyhash{$symb.'_savemsgN'} = $env{'form.savemsgN'};
1.119     ng       2989: 	my $putresult = &Apache::lonnet::put
1.301     albertel 2990: 	    ('nohist_handgrade',\%keyhash,$cdom,$cnum);
1.41      ng       2991:     }
1.44      ng       2992:     # Called by Save & Refresh from Highlight Attribute Window
1.257     albertel 2993:     my (undef,undef,$fullname) = &getclasslist($env{'form.section'},'1');
                   2994:     if ($env{'form.refresh'} eq 'on') {
1.86      ng       2995: 	my ($ctr,$total) = (0,0);
                   2996: 	while ($ctr < $ngrade) {
1.257     albertel 2997: 	    $total++ if  $env{'form.unamedom'.$ctr} ne '';
1.86      ng       2998: 	    $ctr++;
                   2999: 	}
1.257     albertel 3000: 	$env{'form.NTSTU'}=$ngrade;
1.86      ng       3001: 	$ctr = 0;
                   3002: 	while ($ctr < $total) {
1.257     albertel 3003: 	    my $processUser = $env{'form.unamedom'.$ctr};
                   3004: 	    ($env{'form.student'},$env{'form.userdom'}) = split(/:/,$processUser);
                   3005: 	    $env{'form.fullname'} = $$fullname{$processUser};
1.86      ng       3006: 	    &submission($request,$ctr,$total-1);
1.41      ng       3007: 	    $ctr++;
                   3008: 	}
                   3009: 	return '';
                   3010:     }
1.36      ng       3011: 
1.121     ng       3012: # Go directly to grade student - from submission or link from chart page
1.120     ng       3013:     if ($button eq 'Grade Student') {
1.324     albertel 3014: 	(undef,undef,$env{'form.handgrade'},undef,undef) = &showResourceInfo($symb);
1.257     albertel 3015: 	my $processUser = $env{'form.unamedom'.$env{'form.studentNo'}};
                   3016: 	($env{'form.student'},$env{'form.userdom'}) = split(/:/,$processUser);
                   3017: 	$env{'form.fullname'} = $$fullname{$processUser};
1.120     ng       3018: 	&submission($request,0,0);
                   3019: 	return '';
                   3020:     }
                   3021: 
1.44      ng       3022:     # Get the next/previous one or group of students
1.257     albertel 3023:     my $firststu = $env{'form.unamedom0'};
                   3024:     my $laststu = $env{'form.unamedom'.($ngrade-1)};
1.119     ng       3025:     my $ctr = 2;
1.41      ng       3026:     while ($laststu eq '') {
1.257     albertel 3027: 	$laststu  = $env{'form.unamedom'.($ngrade-$ctr)};
1.41      ng       3028: 	$ctr++;
                   3029: 	$laststu = $firststu if ($ctr > $ngrade);
                   3030:     }
1.44      ng       3031: 
1.41      ng       3032:     my (@parsedlist,@nextlist);
                   3033:     my ($nextflg) = 0;
1.524     raeburn  3034:     foreach my $item (sort 
1.294     albertel 3035: 	     {
                   3036: 		 if (lc($$fullname{$a}) ne lc($$fullname{$b})) {
                   3037: 		     return (lc($$fullname{$a}) cmp lc($$fullname{$b}));
                   3038: 		 }
                   3039: 		 return $a cmp $b;
                   3040: 	     } (keys(%$fullname))) {
1.41      ng       3041: 	if ($nextflg == 1 && $button =~ /Next$/) {
1.524     raeburn  3042: 	    push(@parsedlist,$item);
1.41      ng       3043: 	}
1.524     raeburn  3044: 	$nextflg = 1 if ($item eq $laststu);
1.41      ng       3045: 	if ($button eq 'Previous') {
1.524     raeburn  3046: 	    last if ($item eq $firststu);
                   3047: 	    push(@parsedlist,$item);
1.41      ng       3048: 	}
                   3049:     }
                   3050:     $ctr = 0;
                   3051:     @parsedlist = reverse @parsedlist if ($button eq 'Previous');
1.582     raeburn  3052:     my $res_error;
                   3053:     my ($partlist) = &response_type($symb,\$res_error);
                   3054:     if ($res_error) {
                   3055:         $request->print(&navmap_errormsg());
                   3056:         return;
                   3057:     }
1.41      ng       3058:     foreach my $student (@parsedlist) {
1.257     albertel 3059: 	my $submitonly=$env{'form.submitonly'};
1.41      ng       3060: 	my ($uname,$udom) = split(/:/,$student);
1.301     albertel 3061: 	
                   3062: 	if ($submitonly eq 'queued') {
                   3063: 	    my %queue_status = 
                   3064: 		&Apache::bridgetask::get_student_status($symb,$cdom,$cnum,
                   3065: 							$udom,$uname);
                   3066: 	    next if (!defined($queue_status{'gradingqueue'}));
                   3067: 	}
                   3068: 
1.156     albertel 3069: 	if ($submitonly =~ /^(yes|graded|incorrect)$/) {
1.257     albertel 3070: #	    my %record = &Apache::lonnet::restore($symb,$env{'request.course.id'},$udom,$uname);
1.324     albertel 3071: 	    my %status=&student_gradeStatus($symb,$udom,$uname,$partlist);
1.145     albertel 3072: 	    my $submitted = 0;
1.248     albertel 3073: 	    my $ungraded = 0;
                   3074: 	    my $incorrect = 0;
1.524     raeburn  3075: 	    foreach my $item (keys(%status)) {
                   3076: 		$submitted = 1 if ($status{$item} ne 'nothing');
                   3077: 		$ungraded = 1 if ($status{$item} =~ /^ungraded/);
                   3078: 		$incorrect = 1 if ($status{$item} =~ /^incorrect/);
                   3079: 		my ($foo,$partid,$foo1) = split(/\./,$item);
1.145     albertel 3080: 		if ($status{'resource.'.$partid.'.submitted_by'} ne '') {
                   3081: 		    $submitted = 0;
                   3082: 		}
1.41      ng       3083: 	    }
1.156     albertel 3084: 	    next if (!$submitted && ($submitonly eq 'yes' ||
                   3085: 				     $submitonly eq 'incorrect' ||
                   3086: 				     $submitonly eq 'graded'));
1.248     albertel 3087: 	    next if (!$ungraded && ($submitonly eq 'graded'));
                   3088: 	    next if (!$incorrect && $submitonly eq 'incorrect');
1.41      ng       3089: 	}
1.524     raeburn  3090: 	push(@nextlist,$student) if ($ctr < $ntstu);
1.129     ng       3091: 	last if ($ctr == $ntstu);
1.41      ng       3092: 	$ctr++;
                   3093:     }
1.36      ng       3094: 
1.41      ng       3095:     $ctr = 0;
                   3096:     my $total = scalar(@nextlist)-1;
1.39      ng       3097: 
1.524     raeburn  3098:     foreach (sort(@nextlist)) {
1.41      ng       3099: 	my ($uname,$udom,$submitter) = split(/:/);
1.257     albertel 3100: 	$env{'form.student'}  = $uname;
                   3101: 	$env{'form.userdom'}  = $udom;
                   3102: 	$env{'form.fullname'} = $$fullname{$_};
1.41      ng       3103: 	&submission($request,$ctr,$total);
                   3104: 	$ctr++;
                   3105:     }
                   3106:     if ($total < 0) {
1.485     albertel 3107: 	my $the_end = '<h3><span class="LC_info">'.&mt('LON-CAPA User Message').'</span></h3><br />'."\n";
1.596.2.4  raeburn  3108: 	$the_end.='<p>'.&mt('[_1]Message:[_2] No more students for this section or class.','<b>','</b>').'</p>'."\n";
1.485     albertel 3109: 	$the_end.=&mt('Click on the button below to return to the grading menu.').'<br /><br />'."\n";
1.324     albertel 3110: 	$the_end.=&show_grading_menu_form($symb);
1.41      ng       3111: 	$request->print($the_end);
                   3112:     }
                   3113:     return '';
1.38      ng       3114: }
1.36      ng       3115: 
1.44      ng       3116: #---- Save the score and award for each student, if changed
1.38      ng       3117: sub saveHandGrade {
1.324     albertel 3118:     my ($request,$symb,$stuname,$domain,$newflg,$submitter,$part) = @_;
1.342     banghart 3119:     my @version_parts;
1.104     albertel 3120:     my $usec = &Apache::lonnet::getsection($domain,$stuname,
1.257     albertel 3121: 					   $env{'request.course.id'});
1.104     albertel 3122:     if (!&canmodify($usec)) { return('not_allowed'); }
1.337     banghart 3123:     my %record = &Apache::lonnet::restore($symb,$env{'request.course.id'},$domain,$stuname);
1.251     banghart 3124:     my @parts_graded;
1.77      ng       3125:     my %newrecord  = ();
1.596.2.12.2.  1(raebur 3126:5):     my ($pts,$wgt,$totchg) = ('','',0);
1.269     raeburn  3127:     my %aggregate = ();
                   3128:     my $aggregateflag = 0;
1.596.2.12.2.  1(raebur 3129:5):     if ($env{'form.HIDE'.$newflg}) {
                   3130:5):         my ($version,$parts) = split(/:/,$env{'form.HIDE'.$newflg},2);
                   3131:5):         my $numchgs = &makehidden($version,$parts,\%record,$symb,$domain,$stuname,1);
                   3132:5):         $totchg += $numchgs;
                   3133:5):     }
1.301     albertel 3134:     my @parts = split(/:/,$env{'form.partlist'.$newflg});
                   3135:     foreach my $new_part (@parts) {
1.337     banghart 3136: 	#collaborator ($submi may vary for different parts
1.259     banghart 3137: 	if ($submitter && $new_part ne $part) { next; }
                   3138: 	my $dropMenu = $env{'form.GD_SEL'.$newflg.'_'.$new_part};
1.125     ng       3139: 	if ($dropMenu eq 'excused') {
1.259     banghart 3140: 	    if ($record{'resource.'.$new_part.'.solved'} ne 'excused') {
                   3141: 		$newrecord{'resource.'.$new_part.'.solved'} = 'excused';
                   3142: 		if (exists($record{'resource.'.$new_part.'.awarded'})) {
                   3143: 		    $newrecord{'resource.'.$new_part.'.awarded'} = '';
1.58      albertel 3144: 		}
1.364     banghart 3145: 	        $newrecord{'resource.'.$new_part.'.regrader'}="$env{'user.name'}:$env{'user.domain'}";
1.58      albertel 3146: 	    }
1.125     ng       3147: 	} elsif ($dropMenu eq 'reset status'
1.259     banghart 3148: 		 && exists($record{'resource.'.$new_part.'.solved'})) { #don't bother if no old records -> no attempts
1.524     raeburn  3149: 	    foreach my $key (keys(%record)) {
1.259     banghart 3150: 		if ($key=~/^resource\.\Q$new_part\E\./) { $newrecord{$key} = ''; }
1.197     albertel 3151: 	    }
1.259     banghart 3152: 	    $newrecord{'resource.'.$new_part.'.regrader'}=
1.257     albertel 3153: 		"$env{'user.name'}:$env{'user.domain'}";
1.270     albertel 3154:             my $totaltries = $record{'resource.'.$part.'.tries'};
                   3155: 
                   3156:             my %last_resets = &get_last_resets($symb,$env{'request.course.id'},
                   3157: 					       [$new_part]);
                   3158:             my $aggtries =$totaltries;
1.269     raeburn  3159:             if ($last_resets{$new_part}) {
1.270     albertel 3160:                 $aggtries = &get_num_tries(\%record,$last_resets{$new_part},
                   3161: 					   $new_part);
1.269     raeburn  3162:             }
1.270     albertel 3163: 
                   3164:             my $solvedstatus = $record{'resource.'.$new_part.'.solved'};
1.269     raeburn  3165:             if ($aggtries > 0) {
1.327     albertel 3166:                 &decrement_aggs($symb,$new_part,\%aggregate,$aggtries,$totaltries,$solvedstatus);
1.269     raeburn  3167:                 $aggregateflag = 1;
                   3168:             }
1.125     ng       3169: 	} elsif ($dropMenu eq '') {
1.259     banghart 3170: 	    $pts = ($env{'form.GD_BOX'.$newflg.'_'.$new_part} ne '' ? 
                   3171: 		    $env{'form.GD_BOX'.$newflg.'_'.$new_part} : 
                   3172: 		    $env{'form.RADVAL'.$newflg.'_'.$new_part});
                   3173: 	    if ($pts eq '' && $env{'form.GD_SEL'.$newflg.'_'.$new_part} eq '') {
1.153     albertel 3174: 		next;
                   3175: 	    }
1.259     banghart 3176: 	    $wgt = $env{'form.WGT'.$newflg.'_'.$new_part} eq '' ? 1 : 
                   3177: 		$env{'form.WGT'.$newflg.'_'.$new_part};
1.41      ng       3178: 	    my $partial= $pts/$wgt;
1.259     banghart 3179: 	    if ($partial eq $record{'resource.'.$new_part.'.awarded'}) {
1.153     albertel 3180: 		#do not update score for part if not changed.
1.346     banghart 3181:                 &handback_files($request,$symb,$stuname,$domain,$newflg,$new_part,\%newrecord);
1.153     albertel 3182: 		next;
1.251     banghart 3183: 	    } else {
1.524     raeburn  3184: 	        push(@parts_graded,$new_part);
1.153     albertel 3185: 	    }
1.259     banghart 3186: 	    if ($record{'resource.'.$new_part.'.awarded'} ne $partial) {
                   3187: 		$newrecord{'resource.'.$new_part.'.awarded'}  = $partial;
1.153     albertel 3188: 	    }
1.259     banghart 3189: 	    my $reckey = 'resource.'.$new_part.'.solved';
1.41      ng       3190: 	    if ($partial == 0) {
1.153     albertel 3191: 		if ($record{$reckey} ne 'incorrect_by_override') {
                   3192: 		    $newrecord{$reckey} = 'incorrect_by_override';
                   3193: 		}
1.41      ng       3194: 	    } else {
1.153     albertel 3195: 		if ($record{$reckey} ne 'correct_by_override') {
                   3196: 		    $newrecord{$reckey} = 'correct_by_override';
                   3197: 		}
                   3198: 	    }	    
                   3199: 	    if ($submitter && 
1.259     banghart 3200: 		($record{'resource.'.$new_part.'.submitted_by'} ne $submitter)) {
                   3201: 		$newrecord{'resource.'.$new_part.'.submitted_by'} = $submitter;
1.41      ng       3202: 	    }
1.259     banghart 3203: 	    $newrecord{'resource.'.$new_part.'.regrader'}=
1.257     albertel 3204: 		"$env{'user.name'}:$env{'user.domain'}";
1.41      ng       3205: 	}
1.259     banghart 3206: 	# unless problem has been graded, set flag to version the submitted files
1.305     banghart 3207: 	unless ($record{'resource.'.$new_part.'.solved'} =~ /^correct_/  || 
                   3208: 	        $record{'resource.'.$new_part.'.solved'} eq 'incorrect_by_override' ||
                   3209: 	        $dropMenu eq 'reset status')
                   3210: 	   {
1.524     raeburn  3211: 	    push(@version_parts,$new_part);
1.259     banghart 3212: 	}
1.41      ng       3213:     }
1.301     albertel 3214:     my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   3215:     my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   3216: 
1.344     albertel 3217:     if (%newrecord) {
                   3218:         if (@version_parts) {
1.364     banghart 3219:             my @changed_keys = &version_portfiles(\%record, \@parts_graded, 
                   3220:                                 $env{'request.course.id'}, $symb, $domain, $stuname, \@version_parts);
1.344     albertel 3221: 	    @newrecord{@changed_keys} = @record{@changed_keys};
1.367     albertel 3222: 	    foreach my $new_part (@version_parts) {
                   3223: 		&handback_files($request,$symb,$stuname,$domain,$newflg,
                   3224: 				$new_part,\%newrecord);
                   3225: 	    }
1.259     banghart 3226:         }
1.44      ng       3227: 	&Apache::lonnet::cstore(\%newrecord,$symb,
1.257     albertel 3228: 				$env{'request.course.id'},$domain,$stuname);
1.380     albertel 3229: 	&check_and_remove_from_queue(\@parts,\%record,\%newrecord,$symb,
                   3230: 				     $cdom,$cnum,$domain,$stuname);
1.41      ng       3231:     }
1.269     raeburn  3232:     if ($aggregateflag) {
                   3233:         &Apache::lonnet::cinc('nohist_resourcetracker',\%aggregate,
1.301     albertel 3234: 			      $cdom,$cnum);
1.269     raeburn  3235:     }
1.596.2.12.2.  1(raebur 3236:5):     return ('',$pts,$wgt,$totchg);
                   3237:5): }
                   3238:5): 
                   3239:5): sub makehidden {
                   3240:5):     my ($version,$parts,$record,$symb,$domain,$stuname,$tolog) = @_;
                   3241:5):     return unless (ref($record) eq 'HASH');
                   3242:5):     my %modified;
                   3243:5):     my $numchanged = 0;
                   3244:5):     if (exists($record->{$version.':keys'})) {
                   3245:5):         my $partsregexp = $parts;
                   3246:5):         $partsregexp =~ s/,/|/g;
                   3247:5):         foreach my $key (split(/\:/,$record->{$version.':keys'})) {
                   3248:5):             if ($key =~ /^resource\.(?:$partsregexp)\.([^\.]+)$/) {
                   3249:5):                  my $item = $1;
                   3250:5):                  unless (($item eq 'solved') || ($item =~ /^award(|msg|ed)$/)) {
                   3251:5):                      $modified{$key} = $record->{$version.':'.$key};
                   3252:5):                  }
                   3253:5):             } elsif ($key =~ m{^(resource\.(?:$partsregexp)\.[^\.]+\.)(.+)$}) {
                   3254:5):                 $modified{$1.'hidden'.$2} = $record->{$version.':'.$key};
                   3255:5):             } elsif ($key =~ /^(ip|timestamp|host)$/) {
                   3256:5):                 $modified{$key} = $record->{$version.':'.$key};
                   3257:5):             }
                   3258:5):         }
                   3259:5):         if (keys(%modified)) {
                   3260:5):             if (&Apache::lonnet::putstore($env{'request.course.id'},$symb,$version,\%modified,
                   3261:5):                                           $domain,$stuname,$tolog) eq 'ok') {
                   3262:5):                 $numchanged ++;
                   3263:5):             }
                   3264:5):         }
                   3265:5):     }
                   3266:5):     return $numchanged;
1.36      ng       3267: }
1.322     albertel 3268: 
1.380     albertel 3269: sub check_and_remove_from_queue {
                   3270:     my ($parts,$record,$newrecord,$symb,$cdom,$cnum,$domain,$stuname) = @_;
                   3271:     my @ungraded_parts;
                   3272:     foreach my $part (@{$parts}) {
                   3273: 	if (    $record->{   'resource.'.$part.'.awarded'} eq ''
                   3274: 	     && $record->{   'resource.'.$part.'.solved' } ne 'excused'
                   3275: 	     && $newrecord->{'resource.'.$part.'.awarded'} eq ''
                   3276: 	     && $newrecord->{'resource.'.$part.'.solved' } ne 'excused'
                   3277: 		) {
                   3278: 	    push(@ungraded_parts, $part);
                   3279: 	}
                   3280:     }
                   3281:     if ( !@ungraded_parts ) {
                   3282: 	&Apache::bridgetask::remove_from_queue('gradingqueue',$symb,$cdom,
                   3283: 					       $cnum,$domain,$stuname);
                   3284:     }
                   3285: }
                   3286: 
1.337     banghart 3287: sub handback_files {
                   3288:     my ($request,$symb,$stuname,$domain,$newflg,$new_part,$newrecord) = @_;
1.517     raeburn  3289:     my $portfolio_root = '/userfiles/portfolio';
1.582     raeburn  3290:     my $res_error;
                   3291:     my ($partlist,$handgrade,$responseType) = &response_type($symb,\$res_error);
                   3292:     if ($res_error) {
                   3293:         $request->print('<br />'.&navmap_errormsg().'<br />');
                   3294:         return;
                   3295:     }
1.596.2.4  raeburn  3296:     my @handedback;
                   3297:     my $file_msg;
1.375     albertel 3298:     my @part_response_id = &flatten_responseType($responseType);
                   3299:     foreach my $part_response_id (@part_response_id) {
                   3300:     	my ($part_id,$resp_id) = @{ $part_response_id };
                   3301: 	my $part_resp = join('_',@{ $part_response_id });
1.596.2.4  raeburn  3302:         if (($env{'form.'.$newflg.'_'.$part_resp.'_countreturndoc'} =~ /^\d+$/) & ($new_part eq $part_id)) {
                   3303:             for (my $counter=1; $counter<=$env{'form.'.$newflg.'_'.$part_resp.'_countreturndoc'}; $counter++) {
1.337     banghart 3304:                 # if multiple files are uploaded names will be 'returndoc2','returndoc3'
1.596.2.4  raeburn  3305: 		if ($env{'form.'.$newflg.'_'.$part_resp.'_returndoc'.$counter}) {
                   3306:                     my $fname=$env{'form.'.$newflg.'_'.$part_resp.'_returndoc'.$counter.'.filename'};
1.338     banghart 3307:                     my ($directory,$answer_file) = 
1.596.2.4  raeburn  3308:                         ($env{'form.'.$newflg.'_'.$part_resp.'_origdoc'.$counter} =~ /^(.*?)([^\/]*)$/);
1.338     banghart 3309:                     my ($answer_name,$answer_ver,$answer_ext) =
                   3310: 		        &file_name_version_ext($answer_file);
1.355     banghart 3311: 		    my ($portfolio_path) = ($directory =~ /^.+$stuname\/portfolio(.*)/);
1.517     raeburn  3312:                     my $getpropath = 1;
1.596.2.12.2.  (raeburn 3313:):                     my ($dir_list,$listerror) =
                   3314:):                         &Apache::lonnet::dirlist($portfolio_root.$portfolio_path,
                   3315:):                                                  $domain,$stuname,$getpropath);
                   3316:): 		    my $version = &get_next_version($answer_name,$answer_ext,$dir_list);
          3(raebur 3317:3):                     # fix filename
1.355     banghart 3318:                     my ($save_file_name) = (($directory.$answer_name.".$version.".$answer_ext) =~ /^.+\/${stuname}\/(.*)/);
                   3319:                     my $result=&Apache::lonnet::finishuserfileupload($stuname,$domain,
1.596.2.4  raeburn  3320:             	                                $newflg.'_'.$part_resp.'_returndoc'.$counter,
1.355     banghart 3321:             	                                $save_file_name);
1.337     banghart 3322:                     if ($result !~ m|^/uploaded/|) {
1.536     raeburn  3323:                         $request->print('<br /><span class="LC_error">'.
                   3324:                             &mt('An error occurred ([_1]) while trying to upload [_2].',
1.596.2.4  raeburn  3325:                                 $result,$newflg.'_'.$part_resp.'_returndoc'.$counter).
1.536     raeburn  3326:                                         '</span>');
1.356     banghart 3327:                     } else {
1.360     banghart 3328:                         # mark the file as read only
1.596.2.4  raeburn  3329:                         push(@handedback,$save_file_name);
1.367     albertel 3330: 			if (exists($$newrecord{"resource.$new_part.$resp_id.handback"})) {
                   3331: 			    $$newrecord{"resource.$new_part.$resp_id.handback"}.=',';
                   3332: 			}
                   3333:                         $$newrecord{"resource.$new_part.$resp_id.handback"} .= $save_file_name;
1.596.2.4  raeburn  3334: 			$file_msg.='<span class="LC_filename"><a href="/uploaded/'."$domain/$stuname/".$save_file_name.'">'.$save_file_name."</a></span> <br />";
1.367     albertel 3335: 
1.337     banghart 3336:                     }
1.596.2.12.2.  3(raebur 3337:3):                     $request->print('<br />'.&mt('[_1] will be the uploaded filename [_2]','<span class="LC_info">'.$fname.'</span>','<span class="LC_filename">'.$env{'form.'.$newflg.'_'.$part_resp.'_origdoc'.$counter}.'</span>'));
1.337     banghart 3338:                 }
                   3339:             }
                   3340:         }
1.596.2.4  raeburn  3341:     }
                   3342:     if (@handedback > 0) {
                   3343:         $request->print('<br />');
                   3344:         my @what = ($symb,$env{'request.course.id'},'handback');
                   3345:         &Apache::lonnet::mark_as_readonly($domain,$stuname,\@handedback,\@what);
                   3346:         my $user_lh = &Apache::loncommon::user_lang($stuname,$domain,$env{'request.course.id'});
                   3347:         my ($subject,$message);
                   3348:         if (scalar(@handedback) == 1) {
                   3349:             $subject = &mt_user($user_lh,'File Handed Back by Instructor');
                   3350:         } else {
                   3351:             $subject = &mt_user($user_lh,'Files Handed Back by Instructor');
                   3352:             $message = &mt_user($user_lh,'Files have been returned that were originally submitted in response to: ');
                   3353:         }
                   3354:         $message .= "<p><strong>".&Apache::lonnet::gettitle($symb)." </strong></p>";
                   3355:         $message .= &mt_user($user_lh,'The returned file(s) are named: [_1]',"<br />$file_msg <br />").
                   3356:                     &mt_user($user_lh,'The file(s) can be found in your [_1]portfolio[_2].','<a href="/adm/portfolio">','</a>');
                   3357:         my ($feedurl,$showsymb) =
                   3358:             &get_feedurl_and_symb($symb,$domain,$stuname);
                   3359:         my $restitle = &Apache::lonnet::gettitle($symb);
                   3360:         $subject .= ' '.&mt_user($user_lh,'(File Returned)').' ['.$restitle.']';
                   3361:         my $msgstatus =
                   3362:              &Apache::lonmsg::user_normal_msg($stuname,$domain,$subject,
                   3363:                  $message,undef,$feedurl,undef,undef,undef,$showsymb,
                   3364:                  $restitle);
                   3365:         if ($msgstatus) {
                   3366:             $request->print(&mt('Notification message status: [_1]','<span class="LC_info">'.$msgstatus.'</span>').'<br />');
                   3367:         }
                   3368:     }
1.338     banghart 3369:     return;
1.337     banghart 3370: }
                   3371: 
1.418     albertel 3372: sub get_feedurl_and_symb {
                   3373:     my ($symb,$uname,$udom) = @_;
                   3374:     my (undef,undef,$url) = &Apache::lonnet::decode_symb($symb);
                   3375:     $url = &Apache::lonnet::clutter($url);
                   3376:     my $encrypturl=&Apache::lonnet::EXT('resource.0.encrypturl',
                   3377: 					$symb,$udom,$uname);
                   3378:     if ($encrypturl =~ /^yes$/i) {
                   3379: 	&Apache::lonenc::encrypted(\$url,1);
                   3380: 	&Apache::lonenc::encrypted(\$symb,1);
                   3381:     }
                   3382:     return ($url,$symb);
                   3383: }
                   3384: 
1.313     banghart 3385: sub get_submitted_files {
                   3386:     my ($udom,$uname,$partid,$respid,$record) = @_;
                   3387:     my @files;
                   3388:     if ($$record{"resource.$partid.$respid.portfiles"}) {
                   3389:         my $file_url = '/uploaded/'.$udom.'/'.$uname.'/portfolio';
                   3390:         foreach my $file (split(',',$$record{"resource.$partid.$respid.portfiles"})) {
                   3391:     	    push(@files,$file_url.$file);
                   3392:         }
                   3393:     }
                   3394:     if ($$record{"resource.$partid.$respid.uploadedurl"}) {
                   3395:         push(@files,$$record{"resource.$partid.$respid.uploadedurl"});
                   3396:     }
                   3397:     return (\@files);
                   3398: }
1.322     albertel 3399: 
1.269     raeburn  3400: # ----------- Provides number of tries since last reset.
                   3401: sub get_num_tries {
                   3402:     my ($record,$last_reset,$part) = @_;
                   3403:     my $timestamp = '';
                   3404:     my $num_tries = 0;
                   3405:     if ($$record{'version'}) {
                   3406:         for (my $version=$$record{'version'};$version>=1;$version--) {
                   3407:             if (exists($$record{$version.':resource.'.$part.'.solved'})) {
                   3408:                 $timestamp = $$record{$version.':timestamp'};
                   3409:                 if ($timestamp > $last_reset) {
                   3410:                     $num_tries ++;
                   3411:                 } else {
                   3412:                     last;
                   3413:                 }
                   3414:             }
                   3415:         }
                   3416:     }
                   3417:     return $num_tries;
                   3418: }
                   3419: 
                   3420: # ----------- Determine decrements required in aggregate totals 
                   3421: sub decrement_aggs {
                   3422:     my ($symb,$part,$aggregate,$aggtries,$totaltries,$solvedstatus) = @_;
                   3423:     my %decrement = (
                   3424:                         attempts => 0,
                   3425:                         users => 0,
                   3426:                         correct => 0
                   3427:                     );
                   3428:     $decrement{'attempts'} = $aggtries;
                   3429:     if ($solvedstatus =~ /^correct/) {
                   3430:         $decrement{'correct'} = 1;
                   3431:     }
                   3432:     if ($aggtries == $totaltries) {
                   3433:         $decrement{'users'} = 1;
                   3434:     }
1.524     raeburn  3435:     foreach my $type (keys(%decrement)) {
1.269     raeburn  3436:         $$aggregate{$symb."\0".$part."\0".$type} = -$decrement{$type};
                   3437:     }
                   3438:     return;
                   3439: }
                   3440: 
                   3441: # ----------- Determine timestamps for last reset of aggregate totals for parts  
                   3442: sub get_last_resets {
1.270     albertel 3443:     my ($symb,$courseid,$partids) =@_;
                   3444:     my %last_resets;
1.269     raeburn  3445:     my $cdom = $env{'course.'.$courseid.'.domain'};
                   3446:     my $cname = $env{'course.'.$courseid.'.num'};
1.271     albertel 3447:     my @keys;
                   3448:     foreach my $part (@{$partids}) {
                   3449: 	push(@keys,"$symb\0$part\0resettime");
                   3450:     }
                   3451:     my %results=&Apache::lonnet::get('nohist_resourcetracker',\@keys,
                   3452: 				     $cdom,$cname);
                   3453:     foreach my $part (@{$partids}) {
                   3454: 	$last_resets{$part}=$results{"$symb\0$part\0resettime"};
1.269     raeburn  3455:     }
1.270     albertel 3456:     return %last_resets;
1.269     raeburn  3457: }
                   3458: 
1.251     banghart 3459: # ----------- Handles creating versions for portfolio files as answers
                   3460: sub version_portfiles {
1.343     banghart 3461:     my ($record, $parts_graded, $courseid, $symb, $domain, $stu_name, $v_flag) = @_;
1.263     banghart 3462:     my $version_parts = join('|',@$v_flag);
1.343     banghart 3463:     my @returned_keys;
1.255     banghart 3464:     my $parts = join('|', @$parts_graded);
1.517     raeburn  3465:     my $portfolio_root = '/userfiles/portfolio';
1.277     albertel 3466:     foreach my $key (keys(%$record)) {
1.259     banghart 3467:         my $new_portfiles;
1.263     banghart 3468:         if ($key =~ /^resource\.($version_parts)\./ && $key =~ /\.portfiles$/ ) {
1.342     banghart 3469:             my @versioned_portfiles;
1.367     albertel 3470:             my @portfiles = split(/\s*,\s*/,$$record{$key});
1.252     banghart 3471:             foreach my $file (@portfiles) {
1.306     banghart 3472:                 &Apache::lonnet::unmark_as_readonly($domain,$stu_name,[$symb,$env{'request.course.id'}],$file);
1.304     albertel 3473:                 my ($directory,$answer_file) =($file =~ /^(.*?)([^\/]*)$/);
                   3474: 		my ($answer_name,$answer_ver,$answer_ext) =
                   3475: 		    &file_name_version_ext($answer_file);
1.596.2.12.2.  (raeburn 3476:):                 my $getpropath = 1;
                   3477:):                 my ($dir_list,$listerror) =
                   3478:):                     &Apache::lonnet::dirlist($portfolio_root.$directory,$domain,
                   3479:):                                              $stu_name,$getpropath);
                   3480:):                 my $version = &get_next_version($answer_name,$answer_ext,$dir_list);
1.306     banghart 3481:                 my $new_answer = &version_selected_portfile($domain, $stu_name, $directory, $answer_file, $version);
                   3482:                 if ($new_answer ne 'problem getting file') {
1.342     banghart 3483:                     push(@versioned_portfiles, $directory.$new_answer);
1.306     banghart 3484:                     &Apache::lonnet::mark_as_readonly($domain,$stu_name,
1.367     albertel 3485:                         [$directory.$new_answer],
1.306     banghart 3486:                         [$symb,$env{'request.course.id'},'graded']);
1.259     banghart 3487:                 }
1.252     banghart 3488:             }
1.343     banghart 3489:             $$record{$key} = join(',',@versioned_portfiles);
                   3490:             push(@returned_keys,$key);
1.251     banghart 3491:         }
                   3492:     } 
1.343     banghart 3493:     return (@returned_keys);   
1.305     banghart 3494: }
                   3495: 
1.307     banghart 3496: sub get_next_version {
1.341     banghart 3497:     my ($answer_name, $answer_ext, $dir_list) = @_;
1.307     banghart 3498:     my $version;
1.596.2.12.2.  (raeburn 3499:):     if (ref($dir_list) eq 'ARRAY') {
                   3500:):         foreach my $row (@{$dir_list}) {
                   3501:):             my ($file) = split(/\&/,$row,2);
                   3502:):             my ($file_name,$file_version,$file_ext) =
                   3503:): 	        &file_name_version_ext($file);
                   3504:):             if (($file_name eq $answer_name) && 
                   3505:): 	        ($file_ext eq $answer_ext)) {
                   3506:):                 # gets here if filename and extension match, 
                   3507:):                 # regardless of version
1.307     banghart 3508:                 if ($file_version ne '') {
1.596.2.12.2.  (raeburn 3509:):                     # a versioned file is found  so save it for later
                   3510:):                     if ($file_version > $version) {
                   3511:): 		        $version = $file_version;
                   3512:):                     }
1.307     banghart 3513: 	        }
                   3514:             }
                   3515:         }
1.596.2.12.2.  (raeburn 3516:):     }
1.307     banghart 3517:     $version ++;
                   3518:     return($version);
                   3519: }
                   3520: 
1.305     banghart 3521: sub version_selected_portfile {
1.306     banghart 3522:     my ($domain,$stu_name,$directory,$file_name,$version) = @_;
                   3523:     my ($answer_name,$answer_ver,$answer_ext) =
                   3524:         &file_name_version_ext($file_name);
                   3525:     my $new_answer;
                   3526:     $env{'form.copy'} = &Apache::lonnet::getfile("/uploaded/$domain/$stu_name/portfolio$directory$file_name");
                   3527:     if($env{'form.copy'} eq '-1') {
                   3528:         $new_answer = 'problem getting file';
                   3529:     } else {
                   3530:         $new_answer = $answer_name.'.'.$version.'.'.$answer_ext;
                   3531:         my $copy_result = &Apache::lonnet::finishuserfileupload(
                   3532:                             $stu_name,$domain,'copy',
                   3533: 		        '/portfolio'.$directory.$new_answer);
                   3534:     }    
                   3535:     return ($new_answer);
1.251     banghart 3536: }
                   3537: 
1.304     albertel 3538: sub file_name_version_ext {
                   3539:     my ($file)=@_;
                   3540:     my @file_parts = split(/\./, $file);
                   3541:     my ($name,$version,$ext);
                   3542:     if (@file_parts > 1) {
                   3543: 	$ext=pop(@file_parts);
                   3544: 	if (@file_parts > 1 && $file_parts[-1] =~ /^\d+$/) {
                   3545: 	    $version=pop(@file_parts);
                   3546: 	}
                   3547: 	$name=join('.',@file_parts);
                   3548:     } else {
                   3549: 	$name=join('.',@file_parts);
                   3550:     }
                   3551:     return($name,$version,$ext);
                   3552: }
                   3553: 
1.44      ng       3554: #--------------------------------------------------------------------------------------
                   3555: #
                   3556: #-------------------------- Next few routines handles grading by section or whole class
                   3557: #
                   3558: #--- Javascript to handle grading by section or whole class
1.42      ng       3559: sub viewgrades_js {
                   3560:     my ($request) = shift;
                   3561: 
1.539     riegler  3562:     my $alertmsg = &mt('A number equal or greater than 0 is expected. Entered value = ');
1.596.2.12.2.  6(raebur 3563:6):     &js_escape(\$alertmsg);
1.41      ng       3564:     $request->print(<<VIEWJAVASCRIPT);
                   3565: <script type="text/javascript" language="javascript">
1.45      ng       3566:    function writePoint(partid,weight,point) {
1.125     ng       3567: 	var radioButton = document.classgrade["RADVAL_"+partid];
                   3568: 	var textbox = document.classgrade["TEXTVAL_"+partid];
1.42      ng       3569: 	if (point == "textval") {
1.125     ng       3570: 	    point = document.classgrade["TEXTVAL_"+partid].value;
1.109     matthew  3571: 	    if (isNaN(point) || parseFloat(point) < 0) {
1.539     riegler  3572: 		alert("$alertmsg"+parseFloat(point));
1.42      ng       3573: 		var resetbox = false;
                   3574: 		for (var i=0; i<radioButton.length; i++) {
                   3575: 		    if (radioButton[i].checked) {
                   3576: 			textbox.value = i;
                   3577: 			resetbox = true;
                   3578: 		    }
                   3579: 		}
                   3580: 		if (!resetbox) {
                   3581: 		    textbox.value = "";
                   3582: 		}
                   3583: 		return;
                   3584: 	    }
1.109     matthew  3585: 	    if (parseFloat(point) > parseFloat(weight)) {
                   3586: 		var resp = confirm("You entered a value ("+parseFloat(point)+
1.44      ng       3587: 				   ") greater than the weight for the part. Accept?");
                   3588: 		if (resp == false) {
                   3589: 		    textbox.value = "";
                   3590: 		    return;
                   3591: 		}
                   3592: 	    }
1.42      ng       3593: 	    for (var i=0; i<radioButton.length; i++) {
                   3594: 		radioButton[i].checked=false;
1.109     matthew  3595: 		if (parseFloat(point) == i) {
1.42      ng       3596: 		    radioButton[i].checked=true;
                   3597: 		}
                   3598: 	    }
1.41      ng       3599: 
1.42      ng       3600: 	} else {
1.125     ng       3601: 	    textbox.value = parseFloat(point);
1.42      ng       3602: 	}
1.41      ng       3603: 	for (i=0;i<document.classgrade.total.value;i++) {
1.125     ng       3604: 	    var user = document.classgrade["ctr"+i].value;
1.289     albertel 3605: 	    user = user.replace(new RegExp(':', 'g'),"_");
1.125     ng       3606: 	    var scorename = document.classgrade["GD_"+user+"_"+partid+"_awarded"];
                   3607: 	    var saveval   = document.classgrade["GD_"+user+"_"+partid+"_solved_s"].value;
                   3608: 	    var selname   = document.classgrade["GD_"+user+"_"+partid+"_solved"];
1.42      ng       3609: 	    if (saveval != "correct") {
                   3610: 		scorename.value = point;
1.43      ng       3611: 		if (selname[0].selected != true) {
                   3612: 		    selname[0].selected = true;
                   3613: 		}
1.42      ng       3614: 	    }
                   3615: 	}
1.125     ng       3616: 	document.classgrade["SELVAL_"+partid][0].selected = true;
1.42      ng       3617:     }
                   3618: 
                   3619:     function writeRadText(partid,weight) {
1.125     ng       3620: 	var selval   = document.classgrade["SELVAL_"+partid];
                   3621: 	var radioButton = document.classgrade["RADVAL_"+partid];
1.265     www      3622:         var override = document.classgrade["FORCE_"+partid].checked;
1.125     ng       3623: 	var textbox = document.classgrade["TEXTVAL_"+partid];
                   3624: 	if (selval[1].selected || selval[2].selected) {
1.42      ng       3625: 	    for (var i=0; i<radioButton.length; i++) {
                   3626: 		radioButton[i].checked=false;
                   3627: 
                   3628: 	    }
                   3629: 	    textbox.value = "";
                   3630: 
                   3631: 	    for (i=0;i<document.classgrade.total.value;i++) {
1.125     ng       3632: 		var user = document.classgrade["ctr"+i].value;
1.289     albertel 3633: 		user = user.replace(new RegExp(':', 'g'),"_");
1.125     ng       3634: 		var scorename = document.classgrade["GD_"+user+"_"+partid+"_awarded"];
                   3635: 		var saveval   = document.classgrade["GD_"+user+"_"+partid+"_solved_s"].value;
                   3636: 		var selname   = document.classgrade["GD_"+user+"_"+partid+"_solved"];
1.265     www      3637: 		if ((saveval != "correct") || override) {
1.42      ng       3638: 		    scorename.value = "";
1.125     ng       3639: 		    if (selval[1].selected) {
                   3640: 			selname[1].selected = true;
                   3641: 		    } else {
                   3642: 			selname[2].selected = true;
                   3643: 			if (Number(document.classgrade["GD_"+user+"_"+partid+"_tries"].value)) 
                   3644: 			{document.classgrade["GD_"+user+"_"+partid+"_tries"].value = '0';}
                   3645: 		    }
1.42      ng       3646: 		}
                   3647: 	    }
1.43      ng       3648: 	} else {
                   3649: 	    for (i=0;i<document.classgrade.total.value;i++) {
1.125     ng       3650: 		var user = document.classgrade["ctr"+i].value;
1.289     albertel 3651: 		user = user.replace(new RegExp(':', 'g'),"_");
1.125     ng       3652: 		var scorename = document.classgrade["GD_"+user+"_"+partid+"_awarded"];
                   3653: 		var saveval   = document.classgrade["GD_"+user+"_"+partid+"_solved_s"].value;
                   3654: 		var selname   = document.classgrade["GD_"+user+"_"+partid+"_solved"];
1.265     www      3655: 		if ((saveval != "correct") || override) {
1.125     ng       3656: 		    scorename.value = document.classgrade["GD_"+user+"_"+partid+"_awarded_s"].value;
1.43      ng       3657: 		    selname[0].selected = true;
                   3658: 		}
                   3659: 	    }
                   3660: 	}	    
1.42      ng       3661:     }
                   3662: 
                   3663:     function changeSelect(partid,user) {
1.125     ng       3664: 	var selval = document.classgrade["GD_"+user+'_'+partid+"_solved"];
                   3665: 	var textbox = document.classgrade["GD_"+user+'_'+partid+"_awarded"];
1.44      ng       3666: 	var point  = textbox.value;
1.125     ng       3667: 	var weight = document.classgrade["weight_"+partid].value;
1.44      ng       3668: 
1.109     matthew  3669: 	if (isNaN(point) || parseFloat(point) < 0) {
1.539     riegler  3670: 	    alert("$alertmsg"+parseFloat(point));
1.44      ng       3671: 	    textbox.value = "";
                   3672: 	    return;
                   3673: 	}
1.109     matthew  3674: 	if (parseFloat(point) > parseFloat(weight)) {
                   3675: 	    var resp = confirm("You entered a value ("+parseFloat(point)+
1.44      ng       3676: 			       ") greater than the weight of the part. Accept?");
                   3677: 	    if (resp == false) {
                   3678: 		textbox.value = "";
                   3679: 		return;
                   3680: 	    }
                   3681: 	}
1.42      ng       3682: 	selval[0].selected = true;
                   3683:     }
                   3684: 
                   3685:     function changeOneScore(partid,user) {
1.125     ng       3686: 	var selval = document.classgrade["GD_"+user+'_'+partid+"_solved"];
                   3687: 	if (selval[1].selected || selval[2].selected) {
                   3688: 	    document.classgrade["GD_"+user+'_'+partid+"_awarded"].value = "";
                   3689: 	    if (selval[2].selected) {
                   3690: 		document.classgrade["GD_"+user+'_'+partid+"_tries"].value = "0";
                   3691: 	    }
1.269     raeburn  3692:         }
1.42      ng       3693:     }
                   3694: 
                   3695:     function resetEntry(numpart) {
                   3696: 	for (ctpart=0;ctpart<numpart;ctpart++) {
1.125     ng       3697: 	    var partid = document.classgrade["partid_"+ctpart].value;
                   3698: 	    var radioButton = document.classgrade["RADVAL_"+partid];
                   3699: 	    var textbox = document.classgrade["TEXTVAL_"+partid];
                   3700: 	    var selval  = document.classgrade["SELVAL_"+partid];
1.42      ng       3701: 	    for (var i=0; i<radioButton.length; i++) {
                   3702: 		radioButton[i].checked=false;
                   3703: 
                   3704: 	    }
                   3705: 	    textbox.value = "";
                   3706: 	    selval[0].selected = true;
                   3707: 
                   3708: 	    for (i=0;i<document.classgrade.total.value;i++) {
1.125     ng       3709: 		var user = document.classgrade["ctr"+i].value;
1.289     albertel 3710: 		user = user.replace(new RegExp(':', 'g'),"_");
1.125     ng       3711: 		var resetscore = document.classgrade["GD_"+user+"_"+partid+"_awarded"];
                   3712: 		resetscore.value = document.classgrade["GD_"+user+"_"+partid+"_awarded_s"].value;
                   3713: 		var resettries = document.classgrade["GD_"+user+"_"+partid+"_tries"];
                   3714: 		resettries.value = document.classgrade["GD_"+user+"_"+partid+"_tries_s"].value;
                   3715: 		var saveselval   = document.classgrade["GD_"+user+"_"+partid+"_solved_s"].value;
                   3716: 		var selname   = document.classgrade["GD_"+user+"_"+partid+"_solved"];
1.42      ng       3717: 		if (saveselval == "excused") {
1.43      ng       3718: 		    if (selname[1].selected == false) { selname[1].selected = true;}
1.42      ng       3719: 		} else {
1.43      ng       3720: 		    if (selname[0].selected == false) {selname[0].selected = true};
1.42      ng       3721: 		}
                   3722: 	    }
1.41      ng       3723: 	}
1.42      ng       3724:     }
                   3725: 
1.41      ng       3726: </script>
                   3727: VIEWJAVASCRIPT
1.42      ng       3728: }
                   3729: 
1.44      ng       3730: #--- show scores for a section or whole class w/ option to change/update a score
1.42      ng       3731: sub viewgrades {
                   3732:     my ($request) = shift;
                   3733:     &viewgrades_js($request);
1.41      ng       3734: 
1.324     albertel 3735:     my ($symb) = &get_symb($request);
1.168     albertel 3736:     #need to make sure we have the correct data for later EXT calls, 
                   3737:     #thus invalidate the cache
                   3738:     &Apache::lonnet::devalidatecourseresdata(
1.257     albertel 3739:                  $env{'course.'.$env{'request.course.id'}.'.num'},
                   3740:                  $env{'course.'.$env{'request.course.id'}.'.domain'});
1.168     albertel 3741:     &Apache::lonnet::clear_EXT_cache_status();
                   3742: 
1.398     albertel 3743:     my $result='<h3><span class="LC_info">'.&mt('Manual Grading').'</span></h3>';
1.596.2.12.2.  9(raebur 3744:3):     $result.='<h4><b>'.&mt('Current Resource').':</b> '.$env{'form.probTitle'}.'</h4>'."\n";
1.41      ng       3745: 
                   3746:     #view individual student submission form - called using Javascript viewOneStudent
1.324     albertel 3747:     $result.=&jscriptNform($symb);
1.41      ng       3748: 
1.44      ng       3749:     #beginning of class grading form
1.442     banghart 3750:     my $stu_status = join(':',&Apache::loncommon::get_env_multiple('form.Status'));
1.41      ng       3751:     $result.= '<form action="/adm/grades" method="post" name="classgrade">'."\n".
1.418     albertel 3752: 	'<input type="hidden" name="symb"    value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
1.38      ng       3753: 	'<input type="hidden" name="command" value="editgrades" />'."\n".
1.432     banghart 3754: 	&build_section_inputs().
1.257     albertel 3755: 	'<input type="hidden" name="saveState" value="'.$env{'form.saveState'}.'" />'."\n".
1.442     banghart 3756: 	'<input type="hidden" name="Status" value="'.$env{'stu_status'}.'" />'."\n".
1.257     albertel 3757: 	'<input type="hidden" name="probTitle" value="'.$env{'form.probTitle'}.'" />'."\n";
1.72      ng       3758: 
1.596.2.12.2.  7(raebur 3759:6):     #retrieve selected groups
                   3760:6):     my (@groups,$group_display);
          8(raebur 3761:6):     @groups = &Apache::loncommon::get_env_multiple('form.group');
          7(raebur 3762:6):     if (grep(/^all$/,@groups)) {
                   3763:6):         @groups = ('all');
                   3764:6):     } elsif (grep(/^none$/,@groups)) {
                   3765:6):         @groups = ('none');
                   3766:6):     } elsif (@groups > 0) {
                   3767:6):         $group_display = join(', ',@groups);
                   3768:6):     }
                   3769:6): 
                   3770:6):     my ($common_header,$specific_header,@sections,$section_display);
                   3771:6):     @sections = &Apache::loncommon::get_env_multiple('form.section');
                   3772:6):     if (grep(/^all$/,@sections)) {
                   3773:6):         @sections = ('all');
                   3774:6):         if ($group_display) {
                   3775:6):             $common_header = &mt('Assign Common Grade to Students in Group(s) [_1]',$group_display);
                   3776:6):             $specific_header = &mt('Assign Grade to Specific Students in Group(s) [_1]',$group_display);
                   3777:6):         } elsif (grep(/^none$/,@groups)) {
                   3778:6):             $common_header = &mt('Assign Common Grade to Students not assigned to any groups');
                   3779:6):             $specific_header = &mt('Assign Grade to Specific Students not assigned to any groups');
                   3780:6):         } else {
                   3781:6):             $common_header = &mt('Assign Common Grade to Class');
                   3782:6):             $specific_header = &mt('Assign Grade to Specific Students in Class');
                   3783:6):         }
                   3784:6):     } elsif (grep(/^none$/,@sections)) {
                   3785:6):         @sections = ('none');
                   3786:6):         if ($group_display) {
                   3787:6):             $common_header = &mt('Assign Common Grade to Students in no Section and in Group(s) [_1]',$group_display);
                   3788:6):             $specific_header = &mt('Assign Grade to Specific Students in no Section and in Group(s)',$group_display);
                   3789:6):         } elsif (grep(/^none$/,@groups)) {
                   3790:6):             $common_header = &mt('Assign Common Grade to Students in no Section and in no Group');
                   3791:6):             $specific_header = &mt('Assign Grade to Specific Students in no Section and in no Group');
                   3792:6):         } else {
                   3793:6):             $common_header = &mt('Assign Common Grade to Students in no Section');
                   3794:6):             $specific_header = &mt('Assign Grade to Specific Students in no Section');
                   3795:6):         }
                   3796:6):     } else {
                   3797:6):         $section_display = join (", ",@sections);
                   3798:6):         if ($group_display) {
                   3799:6):             $common_header = &mt('Assign Common Grade to Students in Section(s) [_1], and in Group(s) [_2]',
                   3800:6):                                  $section_display,$group_display);
                   3801:6):             $specific_header = &mt('Assign Grade to Specific Students in Section(s) [_1], and in Group(s) [_2]',
                   3802:6):                                    $section_display,$group_display);
                   3803:6):         } elsif (grep(/^none$/,@groups)) {
                   3804:6):             $common_header = &mt('Assign Common Grade to Students in Section(s) [_1] and no Group',$section_display);
                   3805:6):             $specific_header = &mt('Assign Grade to Specific Students in Section(s) [_1] and no Group',$section_display);
                   3806:6):         } else {
                   3807:6):             $common_header = &mt('Assign Common Grade to Students in Section(s) [_1]',$section_display);
                   3808:6):             $specific_header = &mt('Assign Grade to Specific Students in Section(s) [_1]',$section_display);
                   3809:6):         }
1.52      albertel 3810:     }
1.596.2.12.2.  7(raebur 3811:6):     my %submit_types = &substatus_options();
                   3812:6):     my $submission_status = $submit_types{$env{'form.submitonly'}};
                   3813:6): 
                   3814:6):     if ($env{'form.submitonly'} eq 'all') {
                   3815:6):         $result.= '<h3>'.$common_header.'</h3>';
                   3816:6):     } else {
                   3817:6):         $result.= '<h3>'.$common_header.'&nbsp;'.&mt('(submission status: "[_1]")',$submission_status).'</h3>'; 
                   3818:6):     }
                   3819:6):     $result .= &Apache::loncommon::start_data_table();
1.44      ng       3820:     #radio buttons/text box for assigning points for a section or class.
                   3821:     #handles different parts of a problem
1.582     raeburn  3822:     my $res_error;
                   3823:     my ($partlist,$handgrade,$responseType) = &response_type($symb,\$res_error);
                   3824:     if ($res_error) {
                   3825:         return &navmap_errormsg();
                   3826:     }
1.42      ng       3827:     my %weight = ();
                   3828:     my $ctsparts = 0;
1.45      ng       3829:     my %seen = ();
1.375     albertel 3830:     my @part_response_id = &flatten_responseType($responseType);
                   3831:     foreach my $part_response_id (@part_response_id) {
                   3832:     	my ($partid,$respid) = @{ $part_response_id };
                   3833: 	my $part_resp = join('_',@{ $part_response_id });
1.45      ng       3834: 	next if $seen{$partid};
                   3835: 	$seen{$partid}++;
1.375     albertel 3836: 	my $handgrade=$$handgrade{$part_resp};
1.42      ng       3837: 	my $wgt = &Apache::lonnet::EXT('resource.'.$partid.'.weight',$symb);
                   3838: 	$weight{$partid} = $wgt eq '' ? '1' : $wgt;
                   3839: 
1.324     albertel 3840: 	my $display_part=&get_display_part($partid,$symb);
1.485     albertel 3841: 	my $radio.='<table border="0"><tr>';  
1.41      ng       3842: 	my $ctr = 0;
1.42      ng       3843: 	while ($ctr<=$weight{$partid}) { # display radio buttons in a nice table 10 across
1.485     albertel 3844: 	    $radio.= '<td><label><input type="radio" name="RADVAL_'.$partid.'" '.
1.54      albertel 3845: 		'onclick="javascript:writePoint(\''.$partid.'\','.$weight{$partid}.
1.288     albertel 3846: 		','.$ctr.')" />'.$ctr."</label></td>\n";
1.41      ng       3847: 	    $result.=(($ctr+1)%10 == 0 ? '</tr><tr>' : '');
                   3848: 	    $ctr++;
                   3849: 	}
1.485     albertel 3850: 	$radio.='</tr></table>';
                   3851: 	my $line = '<input type="text" name="TEXTVAL_'.
1.589     bisitz   3852: 	    $partid.'" size="4" '.'onchange="javascript:writePoint(\''.
1.54      albertel 3853: 		$partid.'\','.$weight{$partid}.',\'textval\')" /> /'.
1.539     riegler  3854: 	    $weight{$partid}.' '.&mt('(problem weight)').'</td>'."\n";
1.596.2.12.2.  9(raebur 3855:3): 	$line.= '<td><b>'.&mt('Grade Status').':</b>'.
                   3856:3):                 '<select name="SELVAL_'.$partid.'" '.
                   3857:3): 	        'onchange="javascript:writeRadText(\''.$partid.'\','.
1.59      albertel 3858: 		$weight{$partid}.')"> '.
1.401     albertel 3859: 	    '<option selected="selected"> </option>'.
1.485     albertel 3860: 	    '<option value="excused">'.&mt('excused').'</option>'.
                   3861: 	    '<option value="reset status">'.&mt('reset status').'</option>'.
                   3862: 	    '</select></td>'.
                   3863:             '<td><label><input type="checkbox" name="FORCE_'.$partid.'" />'.&mt('Override "Correct"').'</label>';
                   3864: 	$line.='<input type="hidden" name="partid_'.
                   3865: 	    $ctsparts.'" value="'.$partid.'" />'."\n";
                   3866: 	$line.='<input type="hidden" name="weight_'.
                   3867: 	    $partid.'" value="'.$weight{$partid}.'" />'."\n";
                   3868: 
                   3869: 	$result.=
                   3870: 	    &Apache::loncommon::start_data_table_row()."\n".
1.577     bisitz   3871: 	    '<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 3872: 	    &Apache::loncommon::end_data_table_row()."\n";
1.42      ng       3873: 	$ctsparts++;
1.41      ng       3874:     }
1.474     albertel 3875:     $result.=&Apache::loncommon::end_data_table()."\n".
1.52      albertel 3876: 	'<input type="hidden" name="totalparts" value="'.$ctsparts.'" />';
1.485     albertel 3877:     $result.='<input type="button" value="'.&mt('Revert to Default').'" '.
1.589     bisitz   3878: 	'onclick="javascript:resetEntry('.$ctsparts.');" />';
1.41      ng       3879: 
1.44      ng       3880:     #table listing all the students in a section/class
                   3881:     #header of table
1.596.2.12.2.  7(raebur 3882:6):     if ($env{'form.submitonly'} eq 'all') { 
                   3883:6):         $result.= '<h3>'.$specific_header.'</h3>';
                   3884:6):     } else {
                   3885:6):         $result.= '<h3>'.$specific_header.'&nbsp;'.&mt('(submission status: "[_1]")',$submission_status).'</h3>';
                   3886:6):     }
                   3887:6):     $result.= &Apache::loncommon::start_data_table().
1.560     raeburn  3888: 	      &Apache::loncommon::start_data_table_header_row().
                   3889: 	      '<th>'.&mt('No.').'</th>'.
                   3890: 	      '<th>'.&nameUserString('header')."</th>\n";
1.582     raeburn  3891:     my $partserror;
                   3892:     my (@parts) = sort(&getpartlist($symb,\$partserror));
                   3893:     if ($partserror) {
                   3894:         return &navmap_errormsg();
                   3895:     }
1.324     albertel 3896:     my (undef,undef,$url)=&Apache::lonnet::decode_symb($symb);
1.269     raeburn  3897:     my @partids = ();
1.41      ng       3898:     foreach my $part (@parts) {
                   3899: 	my $display=&Apache::lonnet::metadata($url,$part.'.display');
1.539     riegler  3900:         my $narrowtext = &mt('Tries');
                   3901: 	$display =~ s|^Number of Attempts|$narrowtext <br />|; # makes the column narrower
1.41      ng       3902: 	if  (!$display) { $display = &Apache::lonnet::metadata($url,$part.'.name'); }
1.207     albertel 3903: 	my ($partid) = &split_part_type($part);
1.524     raeburn  3904:         push(@partids,$partid);
1.324     albertel 3905: 	my $display_part=&get_display_part($partid,$symb);
1.41      ng       3906: 	if ($display =~ /^Partial Credit Factor/) {
1.485     albertel 3907: 	    $result.='<th>'.
1.596.2.12.2.  8(raebur 3908:3):                 &mt('Score Part: [_1][_2](weight = [_3])',
                   3909:3):                     $display_part,'<br />',$weight{$partid}).'</th>'."\n";
1.41      ng       3910: 	    next;
1.485     albertel 3911: 	    
1.207     albertel 3912: 	} else {
1.485     albertel 3913: 	    if ($display =~ /Problem Status/) {
                   3914: 		my $grade_status_mt = &mt('Grade Status');
                   3915: 		$display =~ s{Problem Status}{$grade_status_mt<br />};
                   3916: 	    }
                   3917: 	    my $part_mt = &mt('Part:');
                   3918: 	    $display =~s{\[Part: \Q$partid\E\]}{$part_mt $display_part};
1.41      ng       3919: 	}
1.485     albertel 3920: 
1.474     albertel 3921: 	$result.='<th>'.$display.'</th>'."\n";
1.41      ng       3922:     }
1.474     albertel 3923:     $result.=&Apache::loncommon::end_data_table_header_row();
1.44      ng       3924: 
1.270     albertel 3925:     my %last_resets = 
                   3926: 	&get_last_resets($symb,$env{'request.course.id'},\@partids);
1.269     raeburn  3927: 
1.41      ng       3928:     #get info for each student
1.44      ng       3929:     #list all the students - with points and grade status
1.596.2.12.2.  7(raebur 3930:6):     my (undef,undef,$fullname) = &getclasslist(\@sections,'1',\@groups);
1.41      ng       3931:     my $ctr = 0;
1.294     albertel 3932:     foreach (sort 
                   3933: 	     {
                   3934: 		 if (lc($$fullname{$a}) ne lc($$fullname{$b})) {
                   3935: 		     return (lc($$fullname{$a}) cmp lc($$fullname{$b}));
                   3936: 		 }
                   3937: 		 return $a cmp $b;
                   3938: 	     } (keys(%$fullname))) {
1.324     albertel 3939: 	$result.=&viewstudentgrade($symb,$env{'request.course.id'},
1.596.2.12.2.  7(raebur 3940:6): 				   $_,$$fullname{$_},\@parts,\%weight,\$ctr,\%last_resets);
1.41      ng       3941:     }
1.474     albertel 3942:     $result.=&Apache::loncommon::end_data_table();
1.41      ng       3943:     $result.='<input type="hidden" name="total" value="'.$ctr.'" />'."\n";
1.485     albertel 3944:     $result.='<input type="button" value="'.&mt('Save').'" '.
1.589     bisitz   3945: 	'onclick="javascript:submit();" target="_self" /></form>'."\n";
1.596.2.12.2.  7(raebur 3946:6):     if ($ctr == 0) {
1.442     banghart 3947:         my $stu_status = join(' or ',&Apache::loncommon::get_env_multiple('form.Status'));
1.596.2.12.2.  7(raebur 3948:6):         $result='<h3><span class="LC_info">'.&mt('Manual Grading').'</span></h3>'.
                   3949:6):                 '<span class="LC_warning">';
                   3950:6):         if ($env{'form.submitonly'} eq 'all') {
                   3951:6):             if (grep(/^all$/,@sections)) {
                   3952:6):                 if (grep(/^all$/,@groups)) {
                   3953:6):                     $result .= &mt('There are no students with enrollment status [_1] to modify or grade.',
                   3954:6):                                    $stu_status);
                   3955:6):                 } elsif (grep(/^none$/,@groups)) {
                   3956:6):                     $result .= &mt('There are no students with no group assigned and with enrollment status [_1] to modify or grade.',
                   3957:6):                                    $stu_status);
                   3958:6):                 } else {
                   3959:6):                     $result .= &mt('There are no students in group(s) [_1] with enrollment status [_2] to modify or grade.',
                   3960:6):                                    $group_display,$stu_status);
                   3961:6):                 }
                   3962:6):             } elsif (grep(/^none$/,@sections)) {
                   3963:6):                 if (grep(/^all$/,@groups)) {
                   3964:6):                     $result .= &mt('There are no students in no section with enrollment status [_1] to modify or grade.',
                   3965:6):                                    $stu_status);
                   3966:6):                 } elsif (grep(/^none$/,@groups)) {
                   3967:6):                     $result .= &mt('There are no students in no section and no group with enrollment status [_1] to modify or grade.',
                   3968:6):                                    $stu_status);
                   3969:6):                 } else {
                   3970:6):                     $result .= &mt('There are no students in no section in group(s) [_1] with enrollment status [_2] to modify or grade.',
                   3971:6):                                    $group_display,$stu_status);
                   3972:6):                 }
                   3973:6):             } else {
                   3974:6):                 if (grep(/^all$/,@groups)) {
                   3975:6):                     $result .= &mt('There are no students in section(s) [_1] with enrollment status [_2] to modify or grade.',
                   3976:6):                                    $section_display,$stu_status);
                   3977:6):                 } elsif (grep(/^none$/,@groups)) {
          9(raebur 3978:7):                     $result .= &mt('There are no students in section(s) [_1] and no group with enrollment status [_2] to modify or grade.',
          7(raebur 3979:6):                                    $section_display,$stu_status);
                   3980:6):                 } else {
                   3981:6):                     $result .= &mt('There are no students in section(s) [_1] and group(s) [_2] with enrollment status [_3] to modify or grade.',
                   3982:6):                                    $section_display,$group_display,$stu_status);
                   3983:6):                 }
                   3984:6):             }
                   3985:6):         } else {
                   3986:6):             if (grep(/^all$/,@sections)) {
                   3987:6):                 if (grep(/^all$/,@groups)) {
                   3988:6):                     $result .= &mt('There are no students with enrollment status [_1] and submission status "[_2]" to modify or grade.',
                   3989:6):                                    $stu_status,$submission_status);
                   3990:6):                 } elsif (grep(/^none$/,@groups)) {
                   3991:6):                     $result .= &mt('There are no students with no group assigned with enrollment status [_1] and submission status "[_2]" to modify or grade.',
                   3992:6):                                    $stu_status,$submission_status);
                   3993:6):                 } else {
                   3994:6):                     $result .= &mt('There are no students in group(s) [_1] with enrollment status [_2] and submission status "[_3]" to modify or grade.',
                   3995:6):                                    $group_display,$stu_status,$submission_status);
                   3996:6):                 }
                   3997:6):             } elsif (grep(/^none$/,@sections)) {
                   3998:6):                 if (grep(/^all$/,@groups)) {
                   3999:6):                     $result .= &mt('There are no students in no section with enrollment status [_1] and submission status "[_2]" to modify or grade.',
                   4000:6):                                    $stu_status,$submission_status);
                   4001:6):                 } elsif (grep(/^none$/,@groups)) {
                   4002:6):                     $result .= &mt('There are no students in no section and no group with enrollment status [_1] and submission status "[_2]" to modify or grade.',
                   4003:6):                                    $stu_status,$submission_status);
                   4004:6):                 } else {
                   4005:6):                     $result .= &mt('There are no students in no section in group(s) [_1] with enrollment status [_2] and submission status "[_3]" to modify or grade.',
                   4006:6):                                    $group_display,$stu_status,$submission_status);
                   4007:6):                 }
                   4008:6):             } else {
                   4009:6):                 if (grep(/^all$/,@groups)) {
                   4010:6):                     $result .= &mt('There are no students in section(s) [_1] with enrollment status [_2] and submission status "[_3]" to modify or grade.',
                   4011:6):                                    $section_display,$stu_status,$submission_status);
                   4012:6):                 } elsif (grep(/^none$/,@groups)) {
                   4013:6):                     $result .= &mt('There are no students in section(s) [_1] and no group with enrollment status [_2] and submission status "[_3]" to modify or grade.',
                   4014:6):                                    $section_display,$stu_status,$submission_status);
                   4015:6):                 } else {
                   4016:6):                     $result .= &mt('There are no students in section(s) [_1] and group(s) [_2] with enrollment status [_3] and submission status "[_4]" to modify or grade.',
                   4017:6):                                    $section_display,$group_display,$stu_status,$submission_status);
                   4018:6):                 }
                   4019:6):             }
                   4020:6): 	}
                   4021:6): 	$result .= '</span><br />';
1.96      albertel 4022:     }
1.324     albertel 4023:     $result.=&show_grading_menu_form($symb);
1.41      ng       4024:     return $result;
                   4025: }
                   4026: 
1.596.2.12.2.  7(raebur 4027:6): #--- call by previous routine to display each student who satisfies submission filter.
1.41      ng       4028: sub viewstudentgrade {
1.324     albertel 4029:     my ($symb,$courseid,$student,$fullname,$parts,$weight,$ctr,$last_resets) = @_;
1.44      ng       4030:     my ($uname,$udom) = split(/:/,$student);
                   4031:     my %record=&Apache::lonnet::restore($symb,$courseid,$udom,$uname);
1.596.2.12.2.  7(raebur 4032:6):     my $submitonly = $env{'form.submitonly'};
                   4033:6):     unless (($submitonly eq 'all') || ($submitonly eq 'queued')) {
                   4034:6):         my %partstatus = ();
                   4035:6):         if (ref($parts) eq 'ARRAY') {
                   4036:6):             foreach my $apart (@{$parts}) {
                   4037:6):                 my ($part,$type) = &split_part_type($apart);
                   4038:6):                 my ($status,undef) = split(/_/,$record{"resource.$part.solved"},2);
                   4039:6):                 $status = 'nothing' if ($status eq '');
                   4040:6):                 $partstatus{$part}      = $status;
                   4041:6):                 my $subkey = "resource.$part.submitted_by";
                   4042:6):                 $partstatus{$subkey} = $record{$subkey} if ($record{$subkey} ne '');
                   4043:6):             }
                   4044:6):             my $submitted = 0;
                   4045:6):             my $graded = 0;
                   4046:6):             my $incorrect = 0;
                   4047:6):             foreach my $key (keys(%partstatus)) {
                   4048:6):                 $submitted = 1 if ($partstatus{$key} ne 'nothing');
                   4049:6):                 $graded = 1 if ($partstatus{$key} =~ /^ungraded/);
                   4050:6):                 $incorrect = 1 if ($partstatus{$key} =~ /^incorrect/);
                   4051:6): 
                   4052:6):                 my $partid = (split(/\./,$key))[1];
                   4053:6):                 if ($partstatus{'resource.'.$partid.'.'.$key.'.submitted_by'} ne '') {
                   4054:6):                     $submitted = 0;
                   4055:6):                 }
                   4056:6):             }
                   4057:6):             return if (!$submitted && ($submitonly eq 'yes' ||
                   4058:6):                                        $submitonly eq 'incorrect' ||
                   4059:6):                                        $submitonly eq 'graded'));
                   4060:6):             return if (!$graded && ($submitonly eq 'graded'));
                   4061:6):             return if (!$incorrect && $submitonly eq 'incorrect');
                   4062:6):         }
                   4063:6):     }
                   4064:6):     if ($submitonly eq 'queued') {
                   4065:6):         my ($cdom,$cnum) = split(/_/,$courseid);
                   4066:6):         my %queue_status =
                   4067:6):             &Apache::bridgetask::get_student_status($symb,$cdom,$cnum,
                   4068:6):                                                     $udom,$uname);
                   4069:6):         return if (!defined($queue_status{'gradingqueue'}));
                   4070:6):     }
                   4071:6):     $$ctr++;
                   4072:6):     my %aggregates = ();
1.474     albertel 4073:     my $result=&Apache::loncommon::start_data_table_row().'<td align="right">'.
1.596.2.12.2.  7(raebur 4074:6): 	'<input type="hidden" name="ctr'.($$ctr-1).'" value="'.$student.'" />'.
                   4075:6): 	"\n".$$ctr.'&nbsp;</td><td>&nbsp;'.
1.44      ng       4076: 	'<a href="javascript:viewOneStudent(\''.$uname.'\',\''.$udom.
1.417     albertel 4077: 	'\');" target="_self">'.$fullname.'</a> '.
1.398     albertel 4078: 	'<span class="LC_internal_info">('.$uname.($env{'user.domain'} eq $udom ? '' : ':'.$udom).')</span></td>'."\n";
1.281     albertel 4079:     $student=~s/:/_/; # colon doen't work in javascript for names
1.63      albertel 4080:     foreach my $apart (@$parts) {
                   4081: 	my ($part,$type) = &split_part_type($apart);
1.41      ng       4082: 	my $score=$record{"resource.$part.$type"};
1.276     albertel 4083:         $result.='<td align="center">';
1.269     raeburn  4084:         my ($aggtries,$totaltries);
                   4085:         unless (exists($aggregates{$part})) {
1.270     albertel 4086: 	    $totaltries = $record{'resource.'.$part.'.tries'};
                   4087: 
                   4088: 	    $aggtries = $totaltries;
1.269     raeburn  4089:             if ($$last_resets{$part}) {  
1.270     albertel 4090:                 $aggtries = &get_num_tries(\%record,$$last_resets{$part},
                   4091: 					   $part);
                   4092:             }
1.269     raeburn  4093:             $result.='<input type="hidden" name="'.
                   4094:                 'GD_'.$student.'_'.$part.'_aggtries" value="'.$aggtries.'" />'."\n";
                   4095:             $result.='<input type="hidden" name="'.
                   4096:                 'GD_'.$student.'_'.$part.'_totaltries" value="'.$totaltries.'" />'."\n";
                   4097:             $aggregates{$part} = 1;
                   4098:         }
1.41      ng       4099: 	if ($type eq 'awarded') {
1.320     albertel 4100: 	    my $pts = $score eq '' ? '' : &compute_points($score,$$weight{$part});
1.42      ng       4101: 	    $result.='<input type="hidden" name="'.
1.89      albertel 4102: 		'GD_'.$student.'_'.$part.'_awarded_s" value="'.$pts.'" />'."\n";
1.233     albertel 4103: 	    $result.='<input type="text" name="'.
1.89      albertel 4104: 		'GD_'.$student.'_'.$part.'_awarded" '.
1.589     bisitz   4105:                 'onchange="javascript:changeSelect(\''.$part.'\',\''.$student.
1.44      ng       4106: 		'\')" value="'.$pts.'" size="4" /></td>'."\n";
1.41      ng       4107: 	} elsif ($type eq 'solved') {
                   4108: 	    my ($status,$foo)=split(/_/,$score,2);
                   4109: 	    $status = 'nothing' if ($status eq '');
1.89      albertel 4110: 	    $result.='<input type="hidden" name="'.'GD_'.$student.'_'.
1.54      albertel 4111: 		$part.'_solved_s" value="'.$status.'" />'."\n";
1.233     albertel 4112: 	    $result.='&nbsp;<select name="'.
1.89      albertel 4113: 		'GD_'.$student.'_'.$part.'_solved" '.
1.589     bisitz   4114:                 'onchange="javascript:changeOneScore(\''.$part.'\',\''.$student.'\')" >'."\n";
1.485     albertel 4115: 	    $result.= (($status eq 'excused') ? '<option> </option><option selected="selected" value="excused">'.&mt('excused').'</option>' 
                   4116: 		: '<option selected="selected"> </option><option value="excused">'.&mt('excused').'</option>')."\n";
                   4117: 	    $result.='<option value="reset status">'.&mt('reset status').'</option>';
1.126     ng       4118: 	    $result.="</select>&nbsp;</td>\n";
1.122     ng       4119: 	} else {
                   4120: 	    $result.='<input type="hidden" name="'.
                   4121: 		'GD_'.$student.'_'.$part.'_'.$type.'_s" value="'.$score.'" />'.
                   4122: 		    "\n";
1.233     albertel 4123: 	    $result.='<input type="text" name="'.
1.122     ng       4124: 		'GD_'.$student.'_'.$part.'_'.$type.'" '.
                   4125: 		'value="'.$score.'" size="4" /></td>'."\n";
1.41      ng       4126: 	}
                   4127:     }
1.474     albertel 4128:     $result.=&Apache::loncommon::end_data_table_row();
1.41      ng       4129:     return $result;
1.38      ng       4130: }
                   4131: 
1.44      ng       4132: #--- change scores for all the students in a section/class
                   4133: #    record does not get update if unchanged
1.38      ng       4134: sub editgrades {
1.41      ng       4135:     my ($request) = @_;
                   4136: 
1.596.2.12.2.  (raeburn 4137:):     my ($symb)=&get_symb($request);
1.433     banghart 4138:     my $section_display = join (", ",&Apache::loncommon::get_env_multiple('form.section'));
1.477     albertel 4139:     my $title='<h2>'.&mt('Current Grade Status').'</h2>';
1.596.2.12.2.  9(raebur 4140:3):     $title.='<h4><b>'.&mt('Current Resource').':</b> '.$env{'form.probTitle'}.'</h4>'."\n";
                   4141:3):     $title.='<h4><b>'.&mt('Section:').'</b> '.$section_display.'</h4>'."\n";
1.126     ng       4142: 
1.477     albertel 4143:     my $result= &Apache::loncommon::start_data_table().
                   4144: 	&Apache::loncommon::start_data_table_header_row().
                   4145: 	'<th rowspan="2" valign="middle">'.&mt('No.').'</th>'.
                   4146: 	'<th rowspan="2" valign="middle">'.&nameUserString('header')."</th>\n";
1.43      ng       4147:     my %scoreptr = (
                   4148: 		    'correct'  =>'correct_by_override',
                   4149: 		    'incorrect'=>'incorrect_by_override',
                   4150: 		    'excused'  =>'excused',
                   4151: 		    'ungraded' =>'ungraded_attempted',
1.596     raeburn  4152:                     'credited' =>'credit_attempted',
1.43      ng       4153: 		    'nothing'  => '',
                   4154: 		    );
1.257     albertel 4155:     my ($classlist,undef,$fullname) = &getclasslist($env{'form.section'},'0');
1.34      ng       4156: 
1.44      ng       4157:     my (@partid);
                   4158:     my %weight = ();
1.54      albertel 4159:     my %columns = ();
1.44      ng       4160:     my ($i,$ctr,$count,$rec_update) = (0,0,0,0);
1.54      albertel 4161: 
1.582     raeburn  4162:     my $partserror;
                   4163:     my (@parts) = sort(&getpartlist($symb,\$partserror));
                   4164:     if ($partserror) {
                   4165:         return &navmap_errormsg();
                   4166:     }
1.54      albertel 4167:     my $header;
1.257     albertel 4168:     while ($ctr < $env{'form.totalparts'}) {
                   4169: 	my $partid = $env{'form.partid_'.$ctr};
1.524     raeburn  4170: 	push(@partid,$partid);
1.257     albertel 4171: 	$weight{$partid} = $env{'form.weight_'.$partid};
1.44      ng       4172: 	$ctr++;
1.54      albertel 4173:     }
1.324     albertel 4174:     my (undef,undef,$url) = &Apache::lonnet::decode_symb($symb);
1.54      albertel 4175:     foreach my $partid (@partid) {
1.478     albertel 4176: 	$header .= '<th align="center">'.&mt('Old Score').'</th>'.
                   4177: 	    '<th align="center">'.&mt('New Score').'</th>';
1.54      albertel 4178: 	$columns{$partid}=2;
                   4179: 	foreach my $stores (@parts) {
                   4180: 	    my ($part,$type) = &split_part_type($stores);
                   4181: 	    if ($part !~ m/^\Q$partid\E/) { next;}
                   4182: 	    if ($type eq 'awarded' || $type eq 'solved') { next; }
                   4183: 	    my $display=&Apache::lonnet::metadata($url,$stores.'.display');
1.551     raeburn  4184: 	    $display =~ s/\[Part: \Q$part\E\]//;
1.539     riegler  4185:             my $narrowtext = &mt('Tries');
                   4186: 	    $display =~ s/Number of Attempts/$narrowtext/;
                   4187: 	    $header .= '<th align="center">'.&mt('Old').' '.$display.'</th>'.
                   4188: 		'<th align="center">'.&mt('New').' '.$display.'</th>';
1.54      albertel 4189: 	    $columns{$partid}+=2;
                   4190: 	}
                   4191:     }
                   4192:     foreach my $partid (@partid) {
1.324     albertel 4193: 	my $display_part=&get_display_part($partid,$symb);
1.478     albertel 4194: 	$result .= '<th colspan="'.$columns{$partid}.'" align="center">'.
                   4195: 	    &mt('Part: [_1] (Weight = [_2])',$display_part,$weight{$partid}).
                   4196: 	    '</th>';
1.54      albertel 4197: 
1.44      ng       4198:     }
1.477     albertel 4199:     $result .= &Apache::loncommon::end_data_table_header_row().
                   4200: 	&Apache::loncommon::start_data_table_header_row().
                   4201: 	$header.
                   4202: 	&Apache::loncommon::end_data_table_header_row();
                   4203:     my @noupdate;
1.126     ng       4204:     my ($updateCtr,$noupdateCtr) = (1,1);
1.257     albertel 4205:     for ($i=0; $i<$env{'form.total'}; $i++) {
1.93      albertel 4206: 	my $line;
1.257     albertel 4207: 	my $user = $env{'form.ctr'.$i};
1.281     albertel 4208: 	my ($uname,$udom)=split(/:/,$user);
1.44      ng       4209: 	my %newrecord;
                   4210: 	my $updateflag = 0;
1.281     albertel 4211: 	$line .= '<td>'.&nameUserString(undef,$$fullname{$user},$uname,$udom).'</td>';
1.108     albertel 4212: 	my $usec=$classlist->{"$uname:$udom"}[5];
1.105     albertel 4213: 	if (!&canmodify($usec)) {
1.126     ng       4214: 	    my $numcols=scalar(@partid)*4+2;
1.477     albertel 4215: 	    push(@noupdate,
1.478     albertel 4216: 		 $line."<td colspan=\"$numcols\"><span class=\"LC_warning\">".
                   4217: 		 &mt('Not allowed to modify student')."</span></td></tr>");
1.105     albertel 4218: 	    next;
                   4219: 	}
1.269     raeburn  4220:         my %aggregate = ();
                   4221:         my $aggregateflag = 0;
1.281     albertel 4222: 	$user=~s/:/_/; # colon doen't work in javascript for names
1.44      ng       4223: 	foreach (@partid) {
1.257     albertel 4224: 	    my $old_aw    = $env{'form.GD_'.$user.'_'.$_.'_awarded_s'};
1.54      albertel 4225: 	    my $old_part_pcr = $old_aw/($weight{$_} ne '0' ? $weight{$_}:1);
                   4226: 	    my $old_part  = $old_aw eq '' ? '' : $old_part_pcr;
1.257     albertel 4227: 	    my $old_score = $scoreptr{$env{'form.GD_'.$user.'_'.$_.'_solved_s'}};
                   4228: 	    my $awarded   = $env{'form.GD_'.$user.'_'.$_.'_awarded'};
1.54      albertel 4229: 	    my $pcr       = $awarded/($weight{$_} ne '0' ? $weight{$_} : 1);
                   4230: 	    my $partial   = $awarded eq '' ? '' : $pcr;
1.44      ng       4231: 	    my $score;
                   4232: 	    if ($partial eq '') {
1.257     albertel 4233: 		$score = $scoreptr{$env{'form.GD_'.$user.'_'.$_.'_solved_s'}};
1.44      ng       4234: 	    } elsif ($partial > 0) {
                   4235: 		$score = 'correct_by_override';
                   4236: 	    } elsif ($partial == 0) {
                   4237: 		$score = 'incorrect_by_override';
                   4238: 	    }
1.257     albertel 4239: 	    my $dropMenu = $env{'form.GD_'.$user.'_'.$_.'_solved'};
1.125     ng       4240: 	    $score = 'excused' if (($dropMenu eq 'excused') && ($score ne 'excused'));
                   4241: 
1.292     albertel 4242: 	    $newrecord{'resource.'.$_.'.regrader'}=
                   4243: 		"$env{'user.name'}:$env{'user.domain'}";
1.125     ng       4244: 	    if ($dropMenu eq 'reset status' &&
                   4245: 		$old_score ne '') { # ignore if no previous attempts => nothing to reset
1.299     albertel 4246: 		$newrecord{'resource.'.$_.'.tries'} = '';
1.125     ng       4247: 		$newrecord{'resource.'.$_.'.solved'} = '';
                   4248: 		$newrecord{'resource.'.$_.'.award'} = '';
1.299     albertel 4249: 		$newrecord{'resource.'.$_.'.awarded'} = '';
1.125     ng       4250: 		$updateflag = 1;
1.269     raeburn  4251:                 if ($env{'form.GD_'.$user.'_'.$_.'_aggtries'} > 0) {
                   4252:                     my $aggtries = $env{'form.GD_'.$user.'_'.$_.'_aggtries'};
                   4253:                     my $totaltries = $env{'form.GD_'.$user.'_'.$_.'_totaltries'};
                   4254:                     my $solvedstatus = $env{'form.GD_'.$user.'_'.$_.'_solved_s'};
                   4255:                     &decrement_aggs($symb,$_,\%aggregate,$aggtries,$totaltries,$solvedstatus);
                   4256:                     $aggregateflag = 1;
                   4257:                 }
1.139     albertel 4258: 	    } elsif (!($old_part eq $partial && $old_score eq $score)) {
                   4259: 		$updateflag = 1;
                   4260: 		$newrecord{'resource.'.$_.'.awarded'}  = $partial if $partial ne '';
                   4261: 		$newrecord{'resource.'.$_.'.solved'}   = $score;
                   4262: 		$rec_update++;
1.125     ng       4263: 	    }
                   4264: 
1.93      albertel 4265: 	    $line .= '<td align="center">'.$old_aw.'&nbsp;</td>'.
1.44      ng       4266: 		'<td align="center">'.$awarded.
                   4267: 		($score eq 'excused' ? $score : '').'&nbsp;</td>';
1.5       albertel 4268: 
1.54      albertel 4269: 
                   4270: 	    my $partid=$_;
                   4271: 	    foreach my $stores (@parts) {
                   4272: 		my ($part,$type) = &split_part_type($stores);
                   4273: 		if ($part !~ m/^\Q$partid\E/) { next;}
                   4274: 		if ($type eq 'awarded' || $type eq 'solved') { next; }
1.257     albertel 4275: 		my $old_aw    = $env{'form.GD_'.$user.'_'.$part.'_'.$type.'_s'};
                   4276: 		my $awarded   = $env{'form.GD_'.$user.'_'.$part.'_'.$type};
1.54      albertel 4277: 		if ($awarded ne '' && $awarded ne $old_aw) {
                   4278: 		    $newrecord{'resource.'.$part.'.'.$type}= $awarded;
1.257     albertel 4279: 		    $newrecord{'resource.'.$part.'.regrader'}="$env{'user.name'}:$env{'user.domain'}";
1.54      albertel 4280: 		    $updateflag=1;
                   4281: 		}
1.93      albertel 4282: 		$line .= '<td align="center">'.$old_aw.'&nbsp;</td>'.
1.54      albertel 4283: 		    '<td align="center">'.$awarded.'&nbsp;</td>';
                   4284: 	    }
1.44      ng       4285: 	}
1.477     albertel 4286: 	$line.="\n";
1.301     albertel 4287: 
                   4288: 	my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   4289: 	my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   4290: 
1.44      ng       4291: 	if ($updateflag) {
                   4292: 	    $count++;
1.257     albertel 4293: 	    &Apache::lonnet::cstore(\%newrecord,$symb,$env{'request.course.id'},
1.89      albertel 4294: 				    $udom,$uname);
1.301     albertel 4295: 
                   4296: 	    if (&Apache::bridgetask::in_queue('gradingqueue',$symb,$cdom,
                   4297: 					      $cnum,$udom,$uname)) {
                   4298: 		# need to figure out if should be in queue.
                   4299: 		my %record =  
                   4300: 		    &Apache::lonnet::restore($symb,$env{'request.course.id'},
                   4301: 					     $udom,$uname);
                   4302: 		my $all_graded = 1;
                   4303: 		my $none_graded = 1;
                   4304: 		foreach my $part (@parts) {
                   4305: 		    if ( $record{'resource.'.$part.'.awarded'} eq '' ) {
                   4306: 			$all_graded = 0;
                   4307: 		    } else {
                   4308: 			$none_graded = 0;
                   4309: 		    }
                   4310: 		}
                   4311: 
                   4312: 		if ($all_graded || $none_graded) {
                   4313: 		    &Apache::bridgetask::remove_from_queue('gradingqueue',
                   4314: 							   $symb,$cdom,$cnum,
                   4315: 							   $udom,$uname);
                   4316: 		}
                   4317: 	    }
                   4318: 
1.477     albertel 4319: 	    $result.=&Apache::loncommon::start_data_table_row().
                   4320: 		'<td align="right">&nbsp;'.$updateCtr.'&nbsp;</td>'.$line.
                   4321: 		&Apache::loncommon::end_data_table_row();
1.126     ng       4322: 	    $updateCtr++;
1.93      albertel 4323: 	} else {
1.477     albertel 4324: 	    push(@noupdate,
                   4325: 		 '<td align="right">&nbsp;'.$noupdateCtr.'&nbsp;</td>'.$line);
1.126     ng       4326: 	    $noupdateCtr++;
1.44      ng       4327: 	}
1.269     raeburn  4328:         if ($aggregateflag) {
                   4329:             &Apache::lonnet::cinc('nohist_resourcetracker',\%aggregate,
1.301     albertel 4330: 				  $cdom,$cnum);
1.269     raeburn  4331:         }
1.93      albertel 4332:     }
1.477     albertel 4333:     if (@noupdate) {
1.126     ng       4334: #	my $numcols=(scalar(@partid)*(scalar(@parts)-1)*2)+3;
                   4335: 	my $numcols=scalar(@partid)*4+2;
1.477     albertel 4336: 	$result .= &Apache::loncommon::start_data_table_row('LC_empty_row').
1.478     albertel 4337: 	    '<td align="center" colspan="'.$numcols.'">'.
                   4338: 	    &mt('No Changes Occurred For the Students Below').
                   4339: 	    '</td>'.
1.477     albertel 4340: 	    &Apache::loncommon::end_data_table_row();
                   4341: 	foreach my $line (@noupdate) {
                   4342: 	    $result.=
                   4343: 		&Apache::loncommon::start_data_table_row().
                   4344: 		$line.
                   4345: 		&Apache::loncommon::end_data_table_row();
                   4346: 	}
1.44      ng       4347:     }
1.477     albertel 4348:     $result .= &Apache::loncommon::end_data_table().
                   4349: 	&show_grading_menu_form($symb);
1.478     albertel 4350:     my $msg = '<p><b>'.
                   4351: 	&mt('Number of records updated = [_1] for [quant,_2,student].',
                   4352: 	    $rec_update,$count).'</b><br />'.
                   4353: 	'<b>'.&mt('Total number of students = [_1]',$env{'form.total'}).
                   4354: 	'</b></p>';
1.44      ng       4355:     return $title.$msg.$result;
1.5       albertel 4356: }
1.54      albertel 4357: 
                   4358: sub split_part_type {
                   4359:     my ($partstr) = @_;
                   4360:     my ($temp,@allparts)=split(/_/,$partstr);
                   4361:     my $type=pop(@allparts);
1.439     albertel 4362:     my $part=join('_',@allparts);
1.54      albertel 4363:     return ($part,$type);
                   4364: }
                   4365: 
1.44      ng       4366: #------------- end of section for handling grading by section/class ---------
                   4367: #
                   4368: #----------------------------------------------------------------------------
                   4369: 
1.5       albertel 4370: 
1.44      ng       4371: #----------------------------------------------------------------------------
                   4372: #
                   4373: #-------------------------- Next few routines handles grading by csv upload
                   4374: #
                   4375: #--- Javascript to handle csv upload
1.27      albertel 4376: sub csvupload_javascript_reverse_associate {
1.573     bisitz   4377:     my $error1=&mt('You need to specify the username or the student/employee ID');
1.246     albertel 4378:     my $error2=&mt('You need to specify at least one grading field');
1.596.2.12.2.  6(raebur 4379:6):   &js_escape(\$error1);
                   4380:6):   &js_escape(\$error2);
1.27      albertel 4381:   return(<<ENDPICK);
                   4382:   function verify(vf) {
                   4383:     var foundsomething=0;
                   4384:     var founduname=0;
1.243     albertel 4385:     var foundID=0;
1.27      albertel 4386:     for (i=0;i<=vf.nfields.value;i++) {
                   4387:       tw=eval('vf.f'+i+'.selectedIndex');
1.243     albertel 4388:       if (i==0 && tw!=0) { foundID=1; }
                   4389:       if (i==1 && tw!=0) { founduname=1; }
                   4390:       if (i!=0 && i!=1 && i!=2 && tw!=0) { foundsomething=1; }
1.27      albertel 4391:     }
1.246     albertel 4392:     if (founduname==0 && foundID==0) {
                   4393: 	alert('$error1');
                   4394: 	return;
1.27      albertel 4395:     }
                   4396:     if (foundsomething==0) {
1.246     albertel 4397: 	alert('$error2');
                   4398: 	return;
1.27      albertel 4399:     }
                   4400:     vf.submit();
                   4401:   }
                   4402:   function flip(vf,tf) {
                   4403:     var nw=eval('vf.f'+tf+'.selectedIndex');
                   4404:     var i;
                   4405:     for (i=0;i<=vf.nfields.value;i++) {
                   4406:       //can not pick the same destination field for both name and domain
                   4407:       if (((i ==0)||(i ==1)) && 
                   4408:           ((tf==0)||(tf==1)) && 
                   4409:           (i!=tf) &&
                   4410:           (eval('vf.f'+i+'.selectedIndex')==nw)) {
                   4411:         eval('vf.f'+i+'.selectedIndex=0;')
                   4412:       }
                   4413:     }
                   4414:   }
                   4415: ENDPICK
                   4416: }
                   4417: 
                   4418: sub csvupload_javascript_forward_associate {
1.573     bisitz   4419:     my $error1=&mt('You need to specify the username or the student/employee ID');
1.246     albertel 4420:     my $error2=&mt('You need to specify at least one grading field');
1.596.2.12.2.  6(raebur 4421:6):   &js_escape(\$error1);
                   4422:6):   &js_escape(\$error2);
1.27      albertel 4423:   return(<<ENDPICK);
                   4424:   function verify(vf) {
                   4425:     var foundsomething=0;
                   4426:     var founduname=0;
1.243     albertel 4427:     var foundID=0;
1.27      albertel 4428:     for (i=0;i<=vf.nfields.value;i++) {
                   4429:       tw=eval('vf.f'+i+'.selectedIndex');
1.243     albertel 4430:       if (tw==1) { foundID=1; }
                   4431:       if (tw==2) { founduname=1; }
                   4432:       if (tw>3) { foundsomething=1; }
1.27      albertel 4433:     }
1.246     albertel 4434:     if (founduname==0 && foundID==0) {
                   4435: 	alert('$error1');
                   4436: 	return;
1.27      albertel 4437:     }
                   4438:     if (foundsomething==0) {
1.246     albertel 4439: 	alert('$error2');
                   4440: 	return;
1.27      albertel 4441:     }
                   4442:     vf.submit();
                   4443:   }
                   4444:   function flip(vf,tf) {
                   4445:     var nw=eval('vf.f'+tf+'.selectedIndex');
                   4446:     var i;
                   4447:     //can not pick the same destination field twice
                   4448:     for (i=0;i<=vf.nfields.value;i++) {
                   4449:       if ((i!=tf) && (eval('vf.f'+i+'.selectedIndex')==nw)) {
                   4450:         eval('vf.f'+i+'.selectedIndex=0;')
                   4451:       }
                   4452:     }
                   4453:   }
                   4454: ENDPICK
                   4455: }
                   4456: 
1.26      albertel 4457: sub csvuploadmap_header {
1.324     albertel 4458:     my ($request,$symb,$datatoken,$distotal)= @_;
1.41      ng       4459:     my $javascript;
1.257     albertel 4460:     if ($env{'form.upfile_associate'} eq 'reverse') {
1.41      ng       4461: 	$javascript=&csvupload_javascript_reverse_associate();
                   4462:     } else {
                   4463: 	$javascript=&csvupload_javascript_forward_associate();
                   4464:     }
1.45      ng       4465: 
1.324     albertel 4466:     my ($result) = &showResourceInfo($symb,$env{'form.probTitle'});
1.257     albertel 4467:     my $checked=(($env{'form.noFirstLine'})?' checked="checked"':'');
1.245     albertel 4468:     my $ignore=&mt('Ignore First Line');
1.418     albertel 4469:     $symb = &Apache::lonenc::check_encrypt($symb);
1.41      ng       4470:     $request->print(<<ENDPICK);
1.26      albertel 4471: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="gradesupload">
1.398     albertel 4472: <h3><span class="LC_info">Uploading Class Grades</span></h3>
1.45      ng       4473: $result
1.326     albertel 4474: <hr />
1.26      albertel 4475: <h3>Identify fields</h3>
                   4476: Total number of records found in file: $distotal <hr />
                   4477: Enter as many fields as you can. The system will inform you and bring you back
                   4478: to this page if the data selected is insufficient to run your class.<hr />
1.589     bisitz   4479: <input type="button" value="Reverse Association" onclick="javascript:this.form.associate.value='Reverse Association';submit(this.form);" />
1.245     albertel 4480: <label><input type="checkbox" name="noFirstLine" $checked />$ignore</label>
1.26      albertel 4481: <input type="hidden" name="associate"  value="" />
                   4482: <input type="hidden" name="phase"      value="three" />
                   4483: <input type="hidden" name="datatoken"  value="$datatoken" />
1.257     albertel 4484: <input type="hidden" name="fileupload" value="$env{'form.fileupload'}" />
                   4485: <input type="hidden" name="upfiletype" value="$env{'form.upfiletype'}" />
1.26      albertel 4486: <input type="hidden" name="upfile_associate" 
1.257     albertel 4487:                                        value="$env{'form.upfile_associate'}" />
1.26      albertel 4488: <input type="hidden" name="symb"       value="$symb" />
1.257     albertel 4489: <input type="hidden" name="saveState"  value="$env{'form.saveState'}" />
                   4490: <input type="hidden" name="probTitle"  value="$env{'form.probTitle'}" />
1.246     albertel 4491: <input type="hidden" name="command"    value="csvuploadoptions" />
1.26      albertel 4492: <hr />
                   4493: <script type="text/javascript" language="Javascript">
                   4494: $javascript
                   4495: </script>
                   4496: ENDPICK
1.118     ng       4497:     return '';
1.26      albertel 4498: 
                   4499: }
                   4500: 
                   4501: sub csvupload_fields {
1.582     raeburn  4502:     my ($symb,$errorref) = @_;
                   4503:     my (@parts) = &getpartlist($symb,$errorref);
                   4504:     if (ref($errorref)) {
                   4505:         if ($$errorref) {
                   4506:             return;
                   4507:         }
                   4508:     }
                   4509: 
1.556     weissno  4510:     my @fields=(['ID','Student/Employee ID'],
1.243     albertel 4511: 		['username','Student Username'],
                   4512: 		['domain','Student Domain']);
1.324     albertel 4513:     my (undef,undef,$url) = &Apache::lonnet::decode_symb($symb);
1.41      ng       4514:     foreach my $part (sort(@parts)) {
                   4515: 	my @datum;
                   4516: 	my $display=&Apache::lonnet::metadata($url,$part.'.display');
                   4517: 	my $name=$part;
                   4518: 	if  (!$display) { $display = $name; }
                   4519: 	@datum=($name,$display);
1.244     albertel 4520: 	if ($name=~/^stores_(.*)_awarded/) {
                   4521: 	    push(@fields,['stores_'.$1.'_points',"Points [Part: $1]"]);
                   4522: 	}
1.41      ng       4523: 	push(@fields,\@datum);
                   4524:     }
                   4525:     return (@fields);
1.26      albertel 4526: }
                   4527: 
                   4528: sub csvuploadmap_footer {
1.41      ng       4529:     my ($request,$i,$keyfields) =@_;
1.596.2.12.2.  0(raebur 4530:3):     my $buttontext = &mt('Assign Grades');
1.41      ng       4531:     $request->print(<<ENDPICK);
1.26      albertel 4532: </table>
                   4533: <input type="hidden" name="nfields" value="$i" />
                   4534: <input type="hidden" name="keyfields" value="$keyfields" />
1.596.2.12.2.  0(raebur 4535:3): <input type="button" onclick="javascript:verify(this.form)" value="$buttontext" /><br />
1.26      albertel 4536: </form>
                   4537: ENDPICK
                   4538: }
                   4539: 
1.283     albertel 4540: sub checkforfile_js {
1.539     riegler  4541:     my $alertmsg = &mt('Please use the browse button to select a file from your local directory.');
1.596.2.12.2.  6(raebur 4542:6):     &js_escape(\$alertmsg);
1.86      ng       4543:     my $result =<<CSVFORMJS;
                   4544: <script type="text/javascript" language="javascript">
                   4545:     function checkUpload(formname) {
                   4546: 	if (formname.upfile.value == "") {
1.539     riegler  4547: 	    alert("$alertmsg");
1.86      ng       4548: 	    return false;
                   4549: 	}
                   4550: 	formname.submit();
                   4551:     }
                   4552:     </script>
                   4553: CSVFORMJS
1.283     albertel 4554:     return $result;
                   4555: }
                   4556: 
                   4557: sub upcsvScores_form {
                   4558:     my ($request) = shift;
1.324     albertel 4559:     my ($symb)=&get_symb($request);
1.283     albertel 4560:     if (!$symb) {return '';}
                   4561:     my $result=&checkforfile_js();
1.257     albertel 4562:     $env{'form.probTitle'} = &Apache::lonnet::gettitle($symb);
1.324     albertel 4563:     my ($table) = &showResourceInfo($symb,$env{'form.probTitle'});
1.118     ng       4564:     $result.=$table;
1.326     albertel 4565:     $result.='<br /><table width="100%" border="0"><tr><td bgcolor="#777777">'."\n";
                   4566:     $result.='<table width="100%" border="0"><tr bgcolor="#e6ffff"><td>'."\n";
1.538     schulted 4567:     $result.='&nbsp;<b>'.&mt('Specify a file containing the class scores for current resource.').
                   4568: 	'</b></td></tr>'."\n";
1.596.2.4  raeburn  4569:     $result.='<tr bgcolor="#ffffe6"><td>'."\n";
1.370     www      4570:     my $upload=&mt("Upload Scores");
1.86      ng       4571:     my $upfile_select=&Apache::loncommon::upfile_select_html();
1.245     albertel 4572:     my $ignore=&mt('Ignore First Line');
1.418     albertel 4573:     $symb = &Apache::lonenc::check_encrypt($symb);
1.86      ng       4574:     $result.=<<ENDUPFORM;
1.106     albertel 4575: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="gradesupload">
1.86      ng       4576: <input type="hidden" name="symb" value="$symb" />
                   4577: <input type="hidden" name="command" value="csvuploadmap" />
1.257     albertel 4578: <input type="hidden" name="probTitle" value="$env{'form.probTitle'}" />
                   4579: <input type="hidden" name="saveState"  value="$env{'form.saveState'}" />
1.86      ng       4580: $upfile_select
1.589     bisitz   4581: <br /><input type="button" onclick="javascript:checkUpload(this.form);" value="$upload" />
1.283     albertel 4582: <label><input type="checkbox" name="noFirstLine" />$ignore</label>
1.86      ng       4583: </form>
                   4584: ENDUPFORM
1.370     www      4585:     $result.=&Apache::loncommon::help_open_topic("Course_Convert_To_CSV",
                   4586:                            &mt("How do I create a CSV file from a spreadsheet"))
                   4587:     .'</td></tr></table>'."\n";
1.86      ng       4588:     $result.='</td></tr></table><br /><br />'."\n";
1.324     albertel 4589:     $result.=&show_grading_menu_form($symb);
1.86      ng       4590:     return $result;
                   4591: }
                   4592: 
                   4593: 
1.26      albertel 4594: sub csvuploadmap {
1.41      ng       4595:     my ($request)= @_;
1.324     albertel 4596:     my ($symb)=&get_symb($request);
1.41      ng       4597:     if (!$symb) {return '';}
1.72      ng       4598: 
1.41      ng       4599:     my $datatoken;
1.257     albertel 4600:     if (!$env{'form.datatoken'}) {
1.41      ng       4601: 	$datatoken=&Apache::loncommon::upfile_store($request);
1.26      albertel 4602:     } else {
1.257     albertel 4603: 	$datatoken=$env{'form.datatoken'};
1.41      ng       4604: 	&Apache::loncommon::load_tmp_file($request);
1.26      albertel 4605:     }
1.41      ng       4606:     my @records=&Apache::loncommon::upfile_record_sep();
1.257     albertel 4607:     if ($env{'form.noFirstLine'}) { shift(@records); }
1.324     albertel 4608:     &csvuploadmap_header($request,$symb,$datatoken,$#records+1);
1.41      ng       4609:     my ($i,$keyfields);
                   4610:     if (@records) {
1.582     raeburn  4611:         my $fieldserror;
                   4612: 	my @fields=&csvupload_fields($symb,\$fieldserror);
                   4613:         if ($fieldserror) {
                   4614:             $request->print(&navmap_errormsg());
                   4615:             return;
                   4616:         }
1.257     albertel 4617: 	if ($env{'form.upfile_associate'} eq 'reverse') {	
1.41      ng       4618: 	    &Apache::loncommon::csv_print_samples($request,\@records);
                   4619: 	    $i=&Apache::loncommon::csv_print_select_table($request,\@records,
                   4620: 							  \@fields);
                   4621: 	    foreach (@fields) { $keyfields.=$_->[0].','; }
                   4622: 	    chop($keyfields);
                   4623: 	} else {
                   4624: 	    unshift(@fields,['none','']);
                   4625: 	    $i=&Apache::loncommon::csv_samples_select_table($request,\@records,
                   4626: 							    \@fields);
1.311     banghart 4627:             foreach my $rec (@records) {
                   4628:                 my %temp = &Apache::loncommon::record_sep($rec);
                   4629:                 if (%temp) {
                   4630:                     $keyfields=join(',',sort(keys(%temp)));
                   4631:                     last;
                   4632:                 }
                   4633:             }
1.41      ng       4634: 	}
                   4635:     }
                   4636:     &csvuploadmap_footer($request,$i,$keyfields);
1.324     albertel 4637:     $request->print(&show_grading_menu_form($symb));
1.72      ng       4638: 
1.41      ng       4639:     return '';
1.27      albertel 4640: }
                   4641: 
1.246     albertel 4642: sub csvuploadoptions {
1.41      ng       4643:     my ($request)= @_;
1.324     albertel 4644:     my ($symb)=&get_symb($request);
1.257     albertel 4645:     my $checked=(($env{'form.noFirstLine'})?'1':'0');
1.246     albertel 4646:     my $ignore=&mt('Ignore First Line');
                   4647:     $request->print(<<ENDPICK);
                   4648: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="gradesupload">
1.398     albertel 4649: <h3><span class="LC_info">Uploading Class Grade Options</span></h3>
1.246     albertel 4650: <input type="hidden" name="command"    value="csvuploadassign" />
1.302     albertel 4651: <!--
1.246     albertel 4652: <p>
                   4653: <label>
                   4654:    <input type="checkbox" name="show_full_results" />
                   4655:    Show a table of all changes
                   4656: </label>
                   4657: </p>
1.302     albertel 4658: -->
1.246     albertel 4659: <p>
                   4660: <label>
                   4661:    <input type="checkbox" name="overwite_scores" checked="checked" />
                   4662:    Overwrite any existing score
                   4663: </label>
                   4664: </p>
                   4665: ENDPICK
                   4666:     my %fields=&get_fields();
                   4667:     if (!defined($fields{'domain'})) {
1.257     albertel 4668: 	my $domform = &Apache::loncommon::select_dom_form($env{'request.role.domain'},'default_domain');
1.246     albertel 4669: 	$request->print("\n<p> Users are in domain: ".$domform."</p>\n");
                   4670:     }
1.257     albertel 4671:     foreach my $key (sort(keys(%env))) {
1.246     albertel 4672: 	if ($key !~ /^form\.(.*)$/) { next; }
                   4673: 	my $cleankey=$1;
                   4674: 	if ($cleankey eq 'command') { next; }
                   4675: 	$request->print('<input type="hidden" name="'.$cleankey.
1.257     albertel 4676: 			'"  value="'.$env{$key}.'" />'."\n");
1.246     albertel 4677:     }
                   4678:     # FIXME do a check for any duplicated user ids...
                   4679:     # FIXME do a check for any invalid user ids?...
1.596.2.12.2.  0(raebur 4680:3):     $request->print('<input type="submit" value="'.&mt('Assign Grades').'" /><br />
1.290     albertel 4681: <hr /></form>'."\n");
1.324     albertel 4682:     $request->print(&show_grading_menu_form($symb));
1.246     albertel 4683:     return '';
                   4684: }
                   4685: 
                   4686: sub get_fields {
                   4687:     my %fields;
1.257     albertel 4688:     my @keyfields = split(/\,/,$env{'form.keyfields'});
                   4689:     for (my $i=0; $i<=$env{'form.nfields'}; $i++) {
                   4690: 	if ($env{'form.upfile_associate'} eq 'reverse') {
                   4691: 	    if ($env{'form.f'.$i} ne 'none') {
                   4692: 		$fields{$keyfields[$i]}=$env{'form.f'.$i};
1.41      ng       4693: 	    }
                   4694: 	} else {
1.257     albertel 4695: 	    if ($env{'form.f'.$i} ne 'none') {
                   4696: 		$fields{$env{'form.f'.$i}}=$keyfields[$i];
1.41      ng       4697: 	    }
                   4698: 	}
1.27      albertel 4699:     }
1.246     albertel 4700:     return %fields;
                   4701: }
                   4702: 
                   4703: sub csvuploadassign {
                   4704:     my ($request)= @_;
1.324     albertel 4705:     my ($symb)=&get_symb($request);
1.246     albertel 4706:     if (!$symb) {return '';}
1.345     bowersj2 4707:     my $error_msg = '';
1.246     albertel 4708:     &Apache::loncommon::load_tmp_file($request);
                   4709:     my @gradedata = &Apache::loncommon::upfile_record_sep();
1.257     albertel 4710:     if ($env{'form.noFirstLine'}) { shift(@gradedata); }
1.246     albertel 4711:     my %fields=&get_fields();
1.41      ng       4712:     $request->print('<h3>Assigning Grades</h3>');
1.257     albertel 4713:     my $courseid=$env{'request.course.id'};
1.97      albertel 4714:     my ($classlist) = &getclasslist('all',0);
1.106     albertel 4715:     my @notallowed;
1.41      ng       4716:     my @skipped;
1.596.2.4  raeburn  4717:     my @warnings;
1.41      ng       4718:     my $countdone=0;
                   4719:     foreach my $grade (@gradedata) {
                   4720: 	my %entries=&Apache::loncommon::record_sep($grade);
1.246     albertel 4721: 	my $domain;
                   4722: 	if ($entries{$fields{'domain'}}) {
                   4723: 	    $domain=$entries{$fields{'domain'}};
                   4724: 	} else {
1.257     albertel 4725: 	    $domain=$env{'form.default_domain'};
1.246     albertel 4726: 	}
1.243     albertel 4727: 	$domain=~s/\s//g;
1.41      ng       4728: 	my $username=$entries{$fields{'username'}};
1.160     albertel 4729: 	$username=~s/\s//g;
1.243     albertel 4730: 	if (!$username) {
                   4731: 	    my $id=$entries{$fields{'ID'}};
1.247     albertel 4732: 	    $id=~s/\s//g;
1.243     albertel 4733: 	    my %ids=&Apache::lonnet::idget($domain,$id);
                   4734: 	    $username=$ids{$id};
                   4735: 	}
1.41      ng       4736: 	if (!exists($$classlist{"$username:$domain"})) {
1.247     albertel 4737: 	    my $id=$entries{$fields{'ID'}};
                   4738: 	    $id=~s/\s//g;
                   4739: 	    if ($id) {
                   4740: 		push(@skipped,"$id:$domain");
                   4741: 	    } else {
                   4742: 		push(@skipped,"$username:$domain");
                   4743: 	    }
1.41      ng       4744: 	    next;
                   4745: 	}
1.108     albertel 4746: 	my $usec=$classlist->{"$username:$domain"}[5];
1.106     albertel 4747: 	if (!&canmodify($usec)) {
                   4748: 	    push(@notallowed,"$username:$domain");
                   4749: 	    next;
                   4750: 	}
1.244     albertel 4751: 	my %points;
1.41      ng       4752: 	my %grades;
                   4753: 	foreach my $dest (keys(%fields)) {
1.244     albertel 4754: 	    if ($dest eq 'ID' || $dest eq 'username' ||
                   4755: 		$dest eq 'domain') { next; }
                   4756: 	    if ($entries{$fields{$dest}} =~ /^\s*$/) { next; }
                   4757: 	    if ($dest=~/stores_(.*)_points/) {
                   4758: 		my $part=$1;
                   4759: 		my $wgt =&Apache::lonnet::EXT('resource.'.$part.'.weight',
                   4760: 					      $symb,$domain,$username);
1.345     bowersj2 4761:                 if ($wgt) {
                   4762:                     $entries{$fields{$dest}}=~s/\s//g;
                   4763:                     my $pcr=$entries{$fields{$dest}} / $wgt;
1.463     albertel 4764:                     my $award=($pcr == 0) ? 'incorrect_by_override'
                   4765:                                           : 'correct_by_override';
1.596.2.4  raeburn  4766:                     if ($pcr>1) {
                   4767:                         push(@warnings,&mt("[_1]: point value larger than weight","$username:$domain"));
                   4768:                     }
1.345     bowersj2 4769:                     $grades{"resource.$part.awarded"}=$pcr;
                   4770:                     $grades{"resource.$part.solved"}=$award;
                   4771:                     $points{$part}=1;
                   4772:                 } else {
                   4773:                     $error_msg = "<br />" .
                   4774:                         &mt("Some point values were assigned"
                   4775:                             ." for problems with a weight "
                   4776:                             ."of zero. These values were "
                   4777:                             ."ignored.");
                   4778:                 }
1.244     albertel 4779: 	    } else {
                   4780: 		if ($dest=~/stores_(.*)_awarded/) { if ($points{$1}) {next;} }
                   4781: 		if ($dest=~/stores_(.*)_solved/)  { if ($points{$1}) {next;} }
                   4782: 		my $store_key=$dest;
                   4783: 		$store_key=~s/^stores/resource/;
                   4784: 		$store_key=~s/_/\./g;
                   4785: 		$grades{$store_key}=$entries{$fields{$dest}};
                   4786: 	    }
1.41      ng       4787: 	}
1.508     www      4788: 	if (! %grades) { 
                   4789:            push(@skipped,&mt("[_1]: no data to save","$username:$domain")); 
                   4790:         } else {
                   4791: 	   $grades{"resource.regrader"}="$env{'user.name'}:$env{'user.domain'}";
                   4792: 	   my $result=&Apache::lonnet::cstore(\%grades,$symb,
1.302     albertel 4793: 					   $env{'request.course.id'},
                   4794: 					   $domain,$username);
1.508     www      4795: 	   if ($result eq 'ok') {
                   4796: 	      $request->print('.');
1.596.2.4  raeburn  4797: # Remove from grading queue
                   4798:               &Apache::bridgetask::remove_from_queue('gradingqueue',$symb,
                   4799:                                              $env{'course.'.$env{'request.course.id'}.'.domain'},
                   4800:                                              $env{'course.'.$env{'request.course.id'}.'.num'},
                   4801:                                              $domain,$username);
1.508     www      4802: 	   } else {
                   4803: 	      $request->print("<p><span class=\"LC_error\">".
                   4804:                               &mt("Failed to save data for student [_1]. Message when trying to save was: [_2]",
                   4805:                                   "$username:$domain",$result)."</span></p>");
                   4806: 	   }
                   4807: 	   $request->rflush();
                   4808: 	   $countdone++;
                   4809:         }
1.41      ng       4810:     }
1.570     www      4811:     $request->print('<br />'.&Apache::lonhtmlcommon::confirm_success(&mt("Saved scores for [quant,_1,student]",$countdone),$countdone==0));
1.596.2.4  raeburn  4812:     if (@warnings) {
                   4813:         $request->print('<br />'.&Apache::lonhtmlcommon::confirm_success(&mt('Warnings generated for the following saved scores:'),1).'<br />');
                   4814:         $request->print(join(', ',@warnings));
                   4815:     }
1.41      ng       4816:     if (@skipped) {
1.571     www      4817: 	$request->print('<br />'.&Apache::lonhtmlcommon::confirm_success(&mt('No scores stored for the following username(s):'),1).'<br />');
                   4818:         $request->print(join(', ',@skipped));
1.106     albertel 4819:     }
                   4820:     if (@notallowed) {
1.571     www      4821: 	$request->print('<br />'.&Apache::lonhtmlcommon::confirm_success(&mt('Modification of scores not allowed for the following username(s):'),1).'<br />');
                   4822: 	$request->print(join(', ',@notallowed));
1.41      ng       4823:     }
1.106     albertel 4824:     $request->print("<br />\n");
1.324     albertel 4825:     $request->print(&show_grading_menu_form($symb));
1.345     bowersj2 4826:     return $error_msg;
1.26      albertel 4827: }
1.44      ng       4828: #------------- end of section for handling csv file upload ---------
                   4829: #
                   4830: #-------------------------------------------------------------------
                   4831: #
1.122     ng       4832: #-------------- Next few routines handle grading by page/sequence
1.72      ng       4833: #
                   4834: #--- Select a page/sequence and a student to grade
1.68      ng       4835: sub pickStudentPage {
                   4836:     my ($request) = shift;
                   4837: 
1.539     riegler  4838:     my $alertmsg = &mt('Please select the student you wish to grade.');
1.596.2.12.2.  6(raebur 4839:6):     &js_escape(\$alertmsg);
1.68      ng       4840:     $request->print(<<LISTJAVASCRIPT);
                   4841: <script type="text/javascript" language="javascript">
                   4842: 
                   4843: function checkPickOne(formname) {
1.76      ng       4844:     if (radioSelection(formname.student) == null) {
1.539     riegler  4845: 	alert("$alertmsg");
1.68      ng       4846: 	return;
                   4847:     }
1.125     ng       4848:     ptr = pullDownSelection(formname.selectpage);
                   4849:     formname.page.value = formname["page"+ptr].value;
                   4850:     formname.title.value = formname["title"+ptr].value;
1.68      ng       4851:     formname.submit();
                   4852: }
                   4853: 
                   4854: </script>
                   4855: LISTJAVASCRIPT
1.118     ng       4856:     &commonJSfunctions($request);
1.324     albertel 4857:     my ($symb) = &get_symb($request);
1.257     albertel 4858:     my $cdom      = $env{"course.$env{'request.course.id'}.domain"};
                   4859:     my $cnum      = $env{"course.$env{'request.course.id'}.num"};
                   4860:     my $getsec    = $env{'form.section'} eq '' ? 'all' : $env{'form.section'};
1.68      ng       4861: 
1.398     albertel 4862:     my $result='<h3><span class="LC_info">&nbsp;'.
1.485     albertel 4863: 	&mt('Manual Grading by Page or Sequence').'</span></h3>';
1.68      ng       4864: 
1.80      ng       4865:     $result.='<form action="/adm/grades" method="post" name="displayPage">'."\n";
1.582     raeburn  4866:     my $map_error;
                   4867:     my ($titles,$symbx) = &getSymbMap($map_error);
                   4868:     if ($map_error) {
                   4869:         $request->print(&navmap_errormsg());
                   4870:         return; 
                   4871:     }
1.137     albertel 4872:     my ($curpage) =&Apache::lonnet::decode_symb($symb); 
                   4873: #    my ($curpage,$mapId) =&Apache::lonnet::decode_symb($symb); 
                   4874: #    my $type=($curpage =~ /\.(page|sequence)/);
1.485     albertel 4875:     my $select = '<select name="selectpage">'."\n";
1.70      ng       4876:     my $ctr=0;
1.68      ng       4877:     foreach (@$titles) {
                   4878: 	my ($minder,$showtitle) = ($_ =~ /(\d+)\.(.*)/);
1.485     albertel 4879: 	$select.='<option value="'.$ctr.'" '.
1.401     albertel 4880: 	    ($$symbx{$_} =~ /$curpage$/ ? 'selected="selected"' : '').
1.71      ng       4881: 	    '>'.$showtitle.'</option>'."\n";
1.70      ng       4882: 	$ctr++;
1.68      ng       4883:     }
1.485     albertel 4884:     $select.= '</select>';
1.539     riegler  4885:     $result.='&nbsp;<b>'.&mt('Problems from').':</b> '.$select."<br />\n";
1.485     albertel 4886: 
1.70      ng       4887:     $ctr=0;
                   4888:     foreach (@$titles) {
                   4889: 	my ($minder,$showtitle) = ($_ =~ /(\d+)\.(.*)/);
                   4890: 	$result.='<input type="hidden" name="page'.$ctr.'" value="'.$$symbx{$_}.'" />'."\n";
                   4891: 	$result.='<input type="hidden" name="title'.$ctr.'" value="'.$showtitle.'" />'."\n";
                   4892: 	$ctr++;
                   4893:     }
1.72      ng       4894:     $result.='<input type="hidden" name="page" />'."\n".
                   4895: 	'<input type="hidden" name="title" />'."\n";
1.68      ng       4896: 
1.485     albertel 4897:     my $options =
                   4898: 	'<label><input type="radio" name="vProb" value="no" checked="checked" /> '.&mt('no').' </label>'."\n".
                   4899: 	'<label><input type="radio" name="vProb" value="yes" /> '.&mt('yes').' </label>'."<br />\n";
1.539     riegler  4900:     $result.='&nbsp;<b>'.&mt('View Problem Text').': </b>'.$options;
1.485     albertel 4901: 
                   4902:     $options =
                   4903: 	'<label><input type="radio" name="lastSub" value="none" /> '.&mt('none').' </label>'."\n".
                   4904: 	'<label><input type="radio" name="lastSub" value="datesub" checked="checked" /> '.&mt('by dates and submissions').'</label>'."\n".
                   4905: 	'<label><input type="radio" name="lastSub" value="all" /> '.&mt('all details').' </label>'."\n";
1.539     riegler  4906:     $result.='&nbsp;<b>'.&mt('Submissions').': </b>'.$options;
1.432     banghart 4907:     
                   4908:     $result.=&build_section_inputs();
1.442     banghart 4909:     my $stu_status = join(':',&Apache::loncommon::get_env_multiple('form.Status'));
                   4910:     $result.='<input type="hidden" name="Status"  value="'.$stu_status.'" />'."\n".
1.72      ng       4911: 	'<input type="hidden" name="command" value="displayPage" />'."\n".
1.418     albertel 4912: 	'<input type="hidden" name="symb"    value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
1.257     albertel 4913: 	'<input type="hidden" name="saveState" value="'.$env{'form.saveState'}.'" />'."<br />\n";
1.72      ng       4914: 
1.539     riegler  4915:     $result.='&nbsp;<b>'.&mt('Use CODE').': </b> <input type="text" name="CODE" value="" /> <br />'."\n";
1.382     albertel 4916: 
1.80      ng       4917:     $result.='&nbsp;<input type="button" '.
1.589     bisitz   4918:              'onclick="javascript:checkPickOne(this.form);" value="'.&mt('Next').' &rarr;" /><br />'."\n";
1.72      ng       4919: 
1.68      ng       4920:     $request->print($result);
                   4921: 
1.485     albertel 4922:     my $studentTable.='&nbsp;<b>'.&mt('Select a student you wish to grade and then click on the Next button.').'</b><br />'.
1.484     albertel 4923: 	&Apache::loncommon::start_data_table().
                   4924: 	&Apache::loncommon::start_data_table_header_row().
1.485     albertel 4925: 	'<th align="right">&nbsp;'.&mt('No.').'</th>'.
1.484     albertel 4926: 	'<th>'.&nameUserString('header').'</th>'.
1.485     albertel 4927: 	'<th align="right">&nbsp;'.&mt('No.').'</th>'.
1.484     albertel 4928: 	'<th>'.&nameUserString('header').'</th>'.
                   4929: 	&Apache::loncommon::end_data_table_header_row();
1.68      ng       4930:  
1.76      ng       4931:     my (undef,undef,$fullname) = &getclasslist($getsec,'1');
1.68      ng       4932:     my $ptr = 1;
1.294     albertel 4933:     foreach my $student (sort 
                   4934: 			 {
                   4935: 			     if (lc($$fullname{$a}) ne lc($$fullname{$b})) {
                   4936: 				 return (lc($$fullname{$a}) cmp lc($$fullname{$b}));
                   4937: 			     }
                   4938: 			     return $a cmp $b;
                   4939: 			 } (keys(%$fullname))) {
1.68      ng       4940: 	my ($uname,$udom) = split(/:/,$student);
1.484     albertel 4941: 	$studentTable.=($ptr%2==1 ? &Apache::loncommon::start_data_table_row()
                   4942:                                   : '</td>');
1.126     ng       4943: 	$studentTable.='<td align="right">'.$ptr.'&nbsp;</td>';
1.288     albertel 4944: 	$studentTable.='<td>&nbsp;<label><input type="radio" name="student" value="'.$student.'" /> '
                   4945: 	    .&nameUserString(undef,$$fullname{$student},$uname,$udom)."</label>\n";
1.484     albertel 4946: 	$studentTable.=
                   4947: 	    ($ptr%2 == 0 ? '</td>'.&Apache::loncommon::end_data_table_row() 
                   4948:                          : '');
1.68      ng       4949: 	$ptr++;
                   4950:     }
1.484     albertel 4951:     if ($ptr%2 == 0) {
                   4952: 	$studentTable.='</td><td>&nbsp;</td><td>&nbsp;</td>'.
                   4953: 	    &Apache::loncommon::end_data_table_row();
                   4954:     }
                   4955:     $studentTable.=&Apache::loncommon::end_data_table()."\n";
1.126     ng       4956:     $studentTable.='<input type="button" '.
1.589     bisitz   4957:                    'onclick="javascript:checkPickOne(this.form);" value="'.&mt('Next').' &rarr;" /></form>'."\n";
1.68      ng       4958: 
1.324     albertel 4959:     $studentTable.=&show_grading_menu_form($symb);
1.68      ng       4960:     $request->print($studentTable);
                   4961: 
                   4962:     return '';
                   4963: }
                   4964: 
                   4965: sub getSymbMap {
1.582     raeburn  4966:     my ($map_error) = @_;
1.132     bowersj2 4967:     my $navmap = Apache::lonnavmaps::navmap->new();
1.582     raeburn  4968:     unless (ref($navmap)) {
                   4969:         if (ref($map_error)) {
                   4970:             $$map_error = 'navmap';
                   4971:         }
                   4972:         return;
                   4973:     }
1.68      ng       4974:     my %symbx = ();
                   4975:     my @titles = ();
1.117     bowersj2 4976:     my $minder = 0;
                   4977: 
                   4978:     # Gather every sequence that has problems.
1.240     albertel 4979:     my @sequences = $navmap->retrieveResources(undef, sub { shift->is_map(); },
                   4980: 					       1,0,1);
1.117     bowersj2 4981:     for my $sequence ($navmap->getById('0.0'), @sequences) {
1.241     albertel 4982: 	if ($navmap->hasResource($sequence, sub { shift->is_problem(); }, 0) ) {
1.381     albertel 4983: 	    my $title = $minder.'.'.
                   4984: 		&HTML::Entities::encode($sequence->compTitle(),'"\'&');
                   4985: 	    push(@titles, $title); # minder in case two titles are identical
                   4986: 	    $symbx{$title} = &HTML::Entities::encode($sequence->symb(),'"\'&');
1.117     bowersj2 4987: 	    $minder++;
1.241     albertel 4988: 	}
1.68      ng       4989:     }
                   4990:     return \@titles,\%symbx;
                   4991: }
                   4992: 
1.72      ng       4993: #
                   4994: #--- Displays a page/sequence w/wo problems, w/wo submissions
1.68      ng       4995: sub displayPage {
                   4996:     my ($request) = shift;
                   4997: 
1.324     albertel 4998:     my ($symb) = &get_symb($request);
1.257     albertel 4999:     my $cdom      = $env{"course.$env{'request.course.id'}.domain"};
                   5000:     my $cnum      = $env{"course.$env{'request.course.id'}.num"};
                   5001:     my $getsec    = $env{'form.section'} eq '' ? 'all' : $env{'form.section'};
                   5002:     my $pageTitle = $env{'form.page'};
1.103     albertel 5003:     my ($classlist,undef,$fullname) = &getclasslist($getsec,'1');
1.257     albertel 5004:     my ($uname,$udom) = split(/:/,$env{'form.student'});
                   5005:     my $usec=$classlist->{$env{'form.student'}}[5];
1.168     albertel 5006: 
                   5007:     #need to make sure we have the correct data for later EXT calls, 
                   5008:     #thus invalidate the cache
                   5009:     &Apache::lonnet::devalidatecourseresdata(
1.257     albertel 5010:                  $env{'course.'.$env{'request.course.id'}.'.num'},
                   5011:                  $env{'course.'.$env{'request.course.id'}.'.domain'});
1.168     albertel 5012:     &Apache::lonnet::clear_EXT_cache_status();
                   5013: 
1.103     albertel 5014:     if (!&canview($usec)) {
1.596.2.12.2.  8(raebur 5015:4): 	$request->print('<span class="LC_warning">'.
                   5016:4):                         &mt('Unable to view requested student. ([_1])',
                   5017:4):                             $env{'form.student'}).
                   5018:4):                         '</span>');
                   5019:4):         $request->print(&show_grading_menu_form($symb));
                   5020:4):         return;
1.103     albertel 5021:     }
1.398     albertel 5022:     my $result='<h3><span class="LC_info">&nbsp;'.$env{'form.title'}.'</span></h3>';
1.485     albertel 5023:     $result.='<h3>&nbsp;'.&mt('Student: [_1]',&nameUserString(undef,$$fullname{$env{'form.student'}},$uname,$udom)).
1.129     ng       5024: 	'</h3>'."\n";
1.500     albertel 5025:     $env{'form.CODE'} = uc($env{'form.CODE'});
1.501     foxr     5026:     if (&Apache::lonnet::validCODE(uc($env{'form.CODE'}))) {
1.485     albertel 5027: 	$result.='<h3>&nbsp;'.&mt('CODE: [_1]',$env{'form.CODE'}).'</h3>'."\n";
1.382     albertel 5028:     } else {
                   5029: 	delete($env{'form.CODE'});
                   5030:     }
1.71      ng       5031:     &sub_page_js($request);
                   5032:     $request->print($result);
                   5033: 
1.132     bowersj2 5034:     my $navmap = Apache::lonnavmaps::navmap->new();
1.582     raeburn  5035:     unless (ref($navmap)) {
                   5036:         $request->print(&navmap_errormsg());
                   5037:         $request->print(&show_grading_menu_form($symb));
                   5038:         return;
                   5039:     }
1.257     albertel 5040:     my ($mapUrl, $id, $resUrl)=&Apache::lonnet::decode_symb($env{'form.page'});
1.68      ng       5041:     my $map = $navmap->getResourceByUrl($resUrl); # add to navmaps
1.288     albertel 5042:     if (!$map) {
1.485     albertel 5043: 	$request->print('<span class="LC_warning">'.&mt('Unable to view requested sequence. ([_1])',$resUrl).'</span>');
1.324     albertel 5044: 	$request->print(&show_grading_menu_form($symb));
1.288     albertel 5045: 	return; 
                   5046:     }
1.68      ng       5047:     my $iterator = $navmap->getIterator($map->map_start(),
                   5048: 					$map->map_finish());
                   5049: 
1.71      ng       5050:     my $studentTable='<form action="/adm/grades" method="post" name="gradePage">'."\n".
1.72      ng       5051: 	'<input type="hidden" name="command" value="gradeByPage" />'."\n".
1.257     albertel 5052: 	'<input type="hidden" name="fullname" value="'.$$fullname{$env{'form.student'}}.'" />'."\n".
                   5053: 	'<input type="hidden" name="student" value="'.$env{'form.student'}.'" />'."\n".
1.72      ng       5054: 	'<input type="hidden" name="page"    value="'.$pageTitle.'" />'."\n".
1.257     albertel 5055: 	'<input type="hidden" name="title"   value="'.$env{'form.title'}.'" />'."\n".
1.418     albertel 5056: 	'<input type="hidden" name="symb"    value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
1.125     ng       5057: 	'<input type="hidden" name="overRideScore" value="no" />'."\n".
1.257     albertel 5058: 	'<input type="hidden" name="saveState" value="'.$env{'form.saveState'}.'" />'."\n";
1.71      ng       5059: 
1.382     albertel 5060:     if (defined($env{'form.CODE'})) {
                   5061: 	$studentTable.=
                   5062: 	    '<input type="hidden" name="CODE" value="'.$env{'form.CODE'}.'" />'."\n";
                   5063:     }
1.381     albertel 5064:     my $checkIcon = '<img alt="'.&mt('Check Mark').
1.485     albertel 5065: 	'" src="'.&Apache::loncommon::lonhttpdurl($request->dir_config('lonIconsURL').'/check.gif').'" height="16" border="0" />';
1.71      ng       5066: 
1.594     bisitz   5067:     $studentTable.='&nbsp;<span class="LC_info">'.
                   5068:         &mt('Problems graded correct by the computer are marked with a [_1] symbol.',$checkIcon).
                   5069:         '</span>'."\n".
1.484     albertel 5070: 	&Apache::loncommon::start_data_table().
                   5071: 	&Apache::loncommon::start_data_table_header_row().
                   5072: 	'<th align="center">&nbsp;Prob.&nbsp;</th>'.
1.485     albertel 5073: 	'<th>&nbsp;'.($env{'form.vProb'} eq 'no' ? &mt('Title') : &mt('Problem Text')).'/'.&mt('Grade').'</th>'.
1.484     albertel 5074: 	&Apache::loncommon::end_data_table_header_row();
1.71      ng       5075: 
1.329     albertel 5076:     &Apache::lonxml::clear_problem_counter();
1.196     albertel 5077:     my ($depth,$question,$prob) = (1,1,1);
1.68      ng       5078:     $iterator->next(); # skip the first BEGIN_MAP
                   5079:     my $curRes = $iterator->next(); # for "current resource"
1.101     albertel 5080:     while ($depth > 0) {
1.68      ng       5081:         if($curRes == $iterator->BEGIN_MAP) { $depth++; }
1.100     bowersj2 5082:         if($curRes == $iterator->END_MAP) { $depth--; }
1.68      ng       5083: 
1.385     albertel 5084:         if (ref($curRes) && $curRes->is_problem()) {
1.91      albertel 5085: 	    my $parts = $curRes->parts();
1.68      ng       5086:             my $title = $curRes->compTitle();
1.71      ng       5087: 	    my $symbx = $curRes->symb();
1.484     albertel 5088: 	    $studentTable.=
                   5089: 		&Apache::loncommon::start_data_table_row().
                   5090: 		'<td align="center" valign="top" >'.$prob.
1.485     albertel 5091: 		(scalar(@{$parts}) == 1 ? '' 
1.596.2.12.2.  2(raebur 5092:2): 		                        : '<br />('.&mt('[_1]parts',
                   5093:2): 							scalar(@{$parts}).'&nbsp;').')'
1.485     albertel 5094: 		 ).
                   5095: 		 '</td>';
1.71      ng       5096: 	    $studentTable.='<td valign="top">';
1.382     albertel 5097: 	    my %form = ('CODE' => $env{'form.CODE'},);
1.257     albertel 5098: 	    if ($env{'form.vProb'} eq 'yes' ) {
1.144     albertel 5099: 		$studentTable.=&show_problem($request,$symbx,$uname,$udom,1,
1.383     albertel 5100: 					     undef,'both',\%form);
1.71      ng       5101: 	    } else {
1.382     albertel 5102: 		my $companswer = &Apache::loncommon::get_student_answers($symbx,$uname,$udom,$env{'request.course.id'},%form);
1.80      ng       5103: 		$companswer =~ s|<form(.*?)>||g;
                   5104: 		$companswer =~ s|</form>||g;
1.71      ng       5105: #		while ($companswer =~ /(<a href\=\"javascript:newWindow.*?Script Vars<\/a>)/s) { #<a href="javascript:newWindow</a>
1.116     ng       5106: #		    $companswer =~ s/$1/ /ms;
1.326     albertel 5107: #		    $request->print('match='.$1."<br />\n");
1.71      ng       5108: #		}
1.116     ng       5109: #		$companswer =~ s|<table border=\"1\">|<table border=\"0\">|g;
1.539     riegler  5110: 		$studentTable.='&nbsp;<b>'.$title.'</b>&nbsp;<br />&nbsp;<b>'.&mt('Correct answer').':</b><br />'.$companswer;
1.71      ng       5111: 	    }
                   5112: 
1.257     albertel 5113: 	    my %record = &Apache::lonnet::restore($symbx,$env{'request.course.id'},$udom,$uname);
1.125     ng       5114: 
1.257     albertel 5115: 	    if ($env{'form.lastSub'} eq 'datesub') {
1.71      ng       5116: 		if ($record{'version'} eq '') {
1.485     albertel 5117: 		    $studentTable.='<br />&nbsp;<span class="LC_warning">'.&mt('No recorded submission for this problem.').'</span><br />';
1.71      ng       5118: 		} else {
1.116     ng       5119: 		    my %responseType = ();
                   5120: 		    foreach my $partid (@{$parts}) {
1.147     albertel 5121: 			my @responseIds =$curRes->responseIds($partid);
                   5122: 			my @responseType =$curRes->responseType($partid);
                   5123: 			my %responseIds;
                   5124: 			for (my $i=0;$i<=$#responseIds;$i++) {
                   5125: 			    $responseIds{$responseIds[$i]}=$responseType[$i];
                   5126: 			}
                   5127: 			$responseType{$partid} = \%responseIds;
1.116     ng       5128: 		    }
1.148     albertel 5129: 		    $studentTable.= &displaySubByDates($symbx,\%record,$parts,\%responseType,$checkIcon,$uname,$udom);
1.147     albertel 5130: 
1.71      ng       5131: 		}
1.257     albertel 5132: 	    } elsif ($env{'form.lastSub'} eq 'all') {
                   5133: 		my $last = ($env{'form.lastSub'} eq 'last' ? 'last' : '');
1.596.2.12.2.  1(raebur 5134:5):                 my $identifier = (&canmodify($usec)? $prob : '');
1.71      ng       5135: 		$studentTable.=&Apache::loncommon::get_previous_attempt($symbx,$uname,$udom,
1.257     albertel 5136: 									$env{'request.course.id'},
1.596.2.12.2.  1(raebur 5137:5): 									'','.submission',undef,
                   5138:5):                                                                         $usec,$identifier);
1.71      ng       5139:  
                   5140: 	    }
1.103     albertel 5141: 	    if (&canmodify($usec)) {
1.585     bisitz   5142:             $studentTable.=&gradeBox_start();
1.103     albertel 5143: 		foreach my $partid (@{$parts}) {
                   5144: 		    $studentTable.=&gradeBox($request,$symbx,$uname,$udom,$question,$partid,\%record);
                   5145: 		    $studentTable.='<input type="hidden" name="q_'.$question.'" value="'.$partid.'" />'."\n";
                   5146: 		    $question++;
                   5147: 		}
1.585     bisitz   5148:             $studentTable.=&gradeBox_end();
1.196     albertel 5149: 		$prob++;
1.71      ng       5150: 	    }
                   5151: 	    $studentTable.='</td></tr>';
1.68      ng       5152: 
1.103     albertel 5153: 	}
1.68      ng       5154:         $curRes = $iterator->next();
                   5155:     }
                   5156: 
1.589     bisitz   5157:     $studentTable.=
                   5158:         '</table>'."\n".
                   5159:         '<input type="button" value="'.&mt('Save').'" '.
                   5160:         'onclick="javascript:checkSubmitPage(this.form,'.$question.');" />'.
                   5161:         '</form>'."\n";
1.324     albertel 5162:     $studentTable.=&show_grading_menu_form($symb);
1.71      ng       5163:     $request->print($studentTable);
                   5164: 
                   5165:     return '';
1.119     ng       5166: }
                   5167: 
                   5168: sub displaySubByDates {
1.148     albertel 5169:     my ($symb,$record,$parts,$responseType,$checkIcon,$uname,$udom) = @_;
1.224     albertel 5170:     my $isCODE=0;
1.335     albertel 5171:     my $isTask = ($symb =~/\.task$/);
1.224     albertel 5172:     if (exists($record->{'resource.CODE'})) { $isCODE=1; }
1.467     albertel 5173:     my $studentTable=&Apache::loncommon::start_data_table().
                   5174: 	&Apache::loncommon::start_data_table_header_row().
                   5175: 	'<th>'.&mt('Date/Time').'</th>'.
                   5176: 	($isCODE?'<th>'.&mt('CODE').'</th>':'').
1.596.2.12.2.  (raeburn 5177:):         ($isTask?'<th>'.&mt('Version').'</th>':'').
1.467     albertel 5178: 	'<th>'.&mt('Submission').'</th>'.
                   5179: 	'<th>'.&mt('Status').'</th>'.
                   5180: 	&Apache::loncommon::end_data_table_header_row();
1.119     ng       5181:     my ($version);
                   5182:     my %mark;
1.148     albertel 5183:     my %orders;
1.119     ng       5184:     $mark{'correct_by_student'} = $checkIcon;
1.147     albertel 5185:     if (!exists($$record{'1:timestamp'})) {
1.539     riegler  5186: 	return '<br />&nbsp;<span class="LC_warning">'.&mt('Nothing submitted - no attempts.').'</span><br />';
1.147     albertel 5187:     }
1.335     albertel 5188: 
                   5189:     my $interaction;
1.525     raeburn  5190:     my $no_increment = 1;
1.596.2.12.2.  5(raebur 5191:5):     my (%lastrndseed,%lasttype);
1.119     ng       5192:     for ($version=1;$version<=$$record{'version'};$version++) {
1.467     albertel 5193: 	my $timestamp = 
                   5194: 	    &Apache::lonlocal::locallocaltime($$record{$version.':timestamp'});
1.335     albertel 5195: 	if (exists($$record{$version.':resource.0.version'})) {
                   5196: 	    $interaction = $$record{$version.':resource.0.version'};
                   5197: 	}
1.596.2.12.2.  (raeburn 5198:):         if ($isTask && $env{'form.previousversion'}) {
                   5199:):             next unless ($interaction == $env{'form.previousversion'});
                   5200:):         }
1.335     albertel 5201: 	my $where = ($isTask ? "$version:resource.$interaction"
                   5202: 		             : "$version:resource");
1.467     albertel 5203: 	$studentTable.=&Apache::loncommon::start_data_table_row().
                   5204: 	    '<td>'.$timestamp.'</td>';
1.224     albertel 5205: 	if ($isCODE) {
                   5206: 	    $studentTable.='<td>'.$record->{$version.':resource.CODE'}.'</td>';
                   5207: 	}
1.596.2.12.2.  (raeburn 5208:):         if ($isTask) {
                   5209:):             $studentTable.='<td>'.$interaction.'</td>';
                   5210:):         }
1.119     ng       5211: 	my @versionKeys = split(/\:/,$$record{$version.':keys'});
                   5212: 	my @displaySub = ();
                   5213: 	foreach my $partid (@{$parts}) {
1.596.2.2  raeburn  5214:             my ($hidden,$type);
                   5215:             $type = $$record{$version.':resource.'.$partid.'.type'};
                   5216:             if (($type eq 'anonsurvey') || ($type eq 'anonsurveycred')) {
1.596     raeburn  5217:                 $hidden = 1;
                   5218:             }
1.335     albertel 5219: 	    my @matchKey = ($isTask ? sort(grep /^resource\.\d+\.\Q$partid\E\.award$/,@versionKeys)
                   5220: 			            : sort(grep /^resource\.\Q$partid\E\..*?\.submission$/,@versionKeys));
                   5221: 	    
1.122     ng       5222: #	    next if ($$record{"$version:resource.$partid.solved"} eq '');
1.324     albertel 5223: 	    my $display_part=&get_display_part($partid,$symb);
1.147     albertel 5224: 	    foreach my $matchKey (@matchKey) {
1.198     albertel 5225: 		if (exists($$record{$version.':'.$matchKey}) &&
                   5226: 		    $$record{$version.':'.$matchKey} ne '') {
1.596     raeburn  5227:                     
1.335     albertel 5228: 		    my ($responseId)= ($isTask ? ($matchKey=~ /^resource\.(.*?)\.\Q$partid\E\.award$/)
                   5229: 				               : ($matchKey=~ /^resource\.\Q$partid\E\.(.*?)\.submission$/));
1.596.2.12.2.  (raeburn 5230:):                     $displaySub[0].='<span class="LC_nobreak">';
1.577     bisitz   5231:                     $displaySub[0].='<b>'.&mt('Part: [_1]',$display_part).'</b>'
                   5232:                                    .' <span class="LC_internal_info">'
1.596.2.4  raeburn  5233:                                    .'('.&mt('Response ID: [_1]',$responseId).')'
1.577     bisitz   5234:                                    .'</span>'
                   5235:                                    .' <b>';
1.596     raeburn  5236:                     if ($hidden) {
                   5237:                         $displaySub[0].= &mt('Anonymous Survey').'</b>';
                   5238:                     } else {
1.596.2.2  raeburn  5239:                         my ($trial,$rndseed,$newvariation);
                   5240:                         if ($type eq 'randomizetry') {
                   5241:                             $trial = $$record{"$where.$partid.tries"};
                   5242:                             $rndseed = $$record{"$where.$partid.rndseed"};
                   5243:                         }
1.596     raeburn  5244: 		        if ($$record{"$where.$partid.tries"} eq '') {
                   5245: 			    $displaySub[0].=&mt('Trial not counted');
                   5246: 		        } else {
                   5247: 			    $displaySub[0].=&mt('Trial: [_1]',
1.467     albertel 5248: 					    $$record{"$where.$partid.tries"});
1.596.2.12.2.  4(raebur 5249:5):                             if (($rndseed ne '')  && ($lastrndseed{$partid} ne '')) {
          5(raebur 5250:5):                                 if (($rndseed ne $lastrndseed{$partid}) &&
                   5251:5):                                     (($type eq 'randomizetry') || ($lasttype{$partid} eq 'randomizetry'))) {
1.596.2.2  raeburn  5252:                                     $newvariation = '&nbsp;('.&mt('New variation this try').')';
                   5253:                                 }
                   5254:                             }
1.596.2.12.2.  4(raebur 5255:5):                             $lastrndseed{$partid} = $rndseed;
          5(raebur 5256:5):                             $lasttype{$partid} = $type;
1.596     raeburn  5257: 		        }
                   5258: 		        my $responseType=($isTask ? 'Task'
1.335     albertel 5259:                                               : $responseType->{$partid}->{$responseId});
1.596     raeburn  5260: 		        if (!exists($orders{$partid})) { $orders{$partid}={}; }
1.596.2.2  raeburn  5261: 		        if ((!exists($orders{$partid}->{$responseId})) || ($trial)) {
1.596     raeburn  5262: 			    $orders{$partid}->{$responseId}=
                   5263: 			        &get_order($partid,$responseId,$symb,$uname,$udom,
1.596.2.2  raeburn  5264:                                            $no_increment,$type,$trial,$rndseed);
1.596     raeburn  5265: 		        }
1.596.2.2  raeburn  5266: 		        $displaySub[0].='</b>'.$newvariation.'</span>'; # /nobreak
1.596     raeburn  5267: 		        $displaySub[0].='&nbsp; '.
1.596.2.2  raeburn  5268: 			    &cleanRecord($$record{$version.':'.$matchKey},$responseType,$symb,$partid,$responseId,$record,$orders{$partid}->{$responseId},"$version:",$uname,$udom,$type,$trial,$rndseed).'<br />';
1.596     raeburn  5269:                     }
1.147     albertel 5270: 		}
                   5271: 	    }
1.335     albertel 5272: 	    if (exists($$record{"$where.$partid.checkedin"})) {
1.485     albertel 5273: 		$displaySub[1].=&mt('Checked in by [_1] into slot [_2]',
                   5274: 				    $$record{"$where.$partid.checkedin"},
                   5275: 				    $$record{"$where.$partid.checkedin.slot"}).
                   5276: 					'<br />';
1.335     albertel 5277: 	    }
                   5278: 	    if (exists $$record{"$where.$partid.award"}) {
1.485     albertel 5279: 		$displaySub[1].='<b>'.&mt('Part:').'</b>&nbsp;'.$display_part.' &nbsp;'.
1.335     albertel 5280: 		    lc($$record{"$where.$partid.award"}).' '.
                   5281: 		    $mark{$$record{"$where.$partid.solved"}}.
1.147     albertel 5282: 		    '<br />';
                   5283: 	    }
1.335     albertel 5284: 	    if (exists $$record{"$where.$partid.regrader"}) {
                   5285: 		$displaySub[2].=$$record{"$where.$partid.regrader"}.
                   5286: 		    ' (<b>'.&mt('Part').':</b> '.$display_part.')';
                   5287: 	    } elsif ($$record{"$version:resource.$partid.regrader"} =~ /\S/) {
                   5288: 		$displaySub[2].=
                   5289: 		    $$record{"$version:resource.$partid.regrader"}.
1.207     albertel 5290: 		    ' (<b>'.&mt('Part').':</b> '.$display_part.')';
1.147     albertel 5291: 	    }
                   5292: 	}
                   5293: 	# needed because old essay regrader has not parts info
                   5294: 	if (exists $$record{"$version:resource.regrader"}) {
                   5295: 	    $displaySub[2].=$$record{"$version:resource.regrader"};
                   5296: 	}
                   5297: 	$studentTable.='<td>'.$displaySub[0].'&nbsp;</td><td>'.$displaySub[1];
                   5298: 	if ($displaySub[2]) {
1.467     albertel 5299: 	    $studentTable.=&mt('Manually graded by [_1]',$displaySub[2]);
1.147     albertel 5300: 	}
1.467     albertel 5301: 	$studentTable.='&nbsp;</td>'.
                   5302: 	    &Apache::loncommon::end_data_table_row();
1.119     ng       5303:     }
1.467     albertel 5304:     $studentTable.=&Apache::loncommon::end_data_table();
1.119     ng       5305:     return $studentTable;
1.71      ng       5306: }
                   5307: 
                   5308: sub updateGradeByPage {
                   5309:     my ($request) = shift;
                   5310: 
1.257     albertel 5311:     my $cdom      = $env{"course.$env{'request.course.id'}.domain"};
                   5312:     my $cnum      = $env{"course.$env{'request.course.id'}.num"};
                   5313:     my $getsec    = $env{'form.section'} eq '' ? 'all' : $env{'form.section'};
                   5314:     my $pageTitle = $env{'form.page'};
1.103     albertel 5315:     my ($classlist,undef,$fullname) = &getclasslist($getsec,'1');
1.257     albertel 5316:     my ($uname,$udom) = split(/:/,$env{'form.student'});
                   5317:     my $usec=$classlist->{$env{'form.student'}}[5];
1.103     albertel 5318:     if (!&canmodify($usec)) {
1.526     raeburn  5319: 	$request->print('<span class="LC_warning">'.&mt('Unable to modify requested student ([_1])',$env{'form.student'}).'</span>');
1.324     albertel 5320: 	$request->print(&show_grading_menu_form($env{'form.symb'}));
1.103     albertel 5321: 	return;
                   5322:     }
1.398     albertel 5323:     my $result='<h3><span class="LC_info">&nbsp;'.$env{'form.title'}.'</span></h3>';
1.526     raeburn  5324:     $result.='<h3>&nbsp;'.&mt('Student: ').&nameUserString(undef,$env{'form.fullname'},$uname,$udom).
1.129     ng       5325: 	'</h3>'."\n";
1.70      ng       5326: 
1.68      ng       5327:     $request->print($result);
                   5328: 
1.582     raeburn  5329: 
1.132     bowersj2 5330:     my $navmap = Apache::lonnavmaps::navmap->new();
1.582     raeburn  5331:     unless (ref($navmap)) {
                   5332:         $request->print(&navmap_errormsg());
                   5333:         return;
                   5334:     }
1.257     albertel 5335:     my ($mapUrl, $id, $resUrl) = &Apache::lonnet::decode_symb( $env{'form.page'});
1.71      ng       5336:     my $map = $navmap->getResourceByUrl($resUrl); # add to navmaps
1.288     albertel 5337:     if (!$map) {
1.527     raeburn  5338: 	$request->print('<span class="LC_warning">'.&mt('Unable to grade requested sequence ([_1]).',$resUrl).'</span>');
1.324     albertel 5339: 	my ($symb)=&get_symb($request);
                   5340: 	$request->print(&show_grading_menu_form($symb));
1.288     albertel 5341: 	return; 
                   5342:     }
1.71      ng       5343:     my $iterator = $navmap->getIterator($map->map_start(),
                   5344: 					$map->map_finish());
1.70      ng       5345: 
1.484     albertel 5346:     my $studentTable=
                   5347: 	&Apache::loncommon::start_data_table().
                   5348: 	&Apache::loncommon::start_data_table_header_row().
1.485     albertel 5349: 	'<th align="center">&nbsp;'.&mt('Prob.').'&nbsp;</th>'.
                   5350: 	'<th>&nbsp;'.&mt('Title').'&nbsp;</th>'.
                   5351: 	'<th>&nbsp;'.&mt('Previous Score').'&nbsp;</th>'.
                   5352: 	'<th>&nbsp;'.&mt('New Score').'&nbsp;</th>'.
1.484     albertel 5353: 	&Apache::loncommon::end_data_table_header_row();
1.71      ng       5354: 
                   5355:     $iterator->next(); # skip the first BEGIN_MAP
                   5356:     my $curRes = $iterator->next(); # for "current resource"
1.596.2.12.2.  1(raebur 5357:5):     my ($depth,$question,$prob,$changeflag,$hideflag)= (1,1,1,0,0);
1.101     albertel 5358:     while ($depth > 0) {
1.71      ng       5359:         if($curRes == $iterator->BEGIN_MAP) { $depth++; }
1.100     bowersj2 5360:         if($curRes == $iterator->END_MAP) { $depth--; }
1.71      ng       5361: 
1.385     albertel 5362:         if (ref($curRes) && $curRes->is_problem()) {
1.91      albertel 5363: 	    my $parts = $curRes->parts();
1.71      ng       5364:             my $title = $curRes->compTitle();
                   5365: 	    my $symbx = $curRes->symb();
1.484     albertel 5366: 	    $studentTable.=
                   5367: 		&Apache::loncommon::start_data_table_row().
                   5368: 		'<td align="center" valign="top" >'.$prob.
1.485     albertel 5369: 		(scalar(@{$parts}) == 1 ? '' 
1.596.2.2  raeburn  5370:                                         : '<br />('.&mt('[quant,_1,part]',scalar(@{$parts}))
1.526     raeburn  5371: 		.')').'</td>';
1.71      ng       5372: 	    $studentTable.='<td valign="top">&nbsp;<b>'.$title.'</b>&nbsp;</td>';
                   5373: 
                   5374: 	    my %newrecord=();
                   5375: 	    my @displayPts=();
1.269     raeburn  5376:             my %aggregate = ();
                   5377:             my $aggregateflag = 0;
1.596.2.12.2.  1(raebur 5378:5):             if ($env{'form.HIDE'.$prob}) {
                   5379:5):                 my %record = &Apache::lonnet::restore($symbx,$env{'request.course.id'},$udom,$uname);
                   5380:5):                 my ($version,$parts) = split(/:/,$env{'form.HIDE'.$prob},2);
                   5381:5):                 my $numchgs = &makehidden($version,$parts,\%record,$symbx,$udom,$uname,1);
                   5382:5):                 $hideflag += $numchgs;
                   5383:5):             }
1.71      ng       5384: 	    foreach my $partid (@{$parts}) {
1.257     albertel 5385: 		my $newpts = $env{'form.GD_BOX'.$question.'_'.$partid};
                   5386: 		my $oldpts = $env{'form.oldpts'.$question.'_'.$partid};
1.71      ng       5387: 
1.257     albertel 5388: 		my $wgt = $env{'form.WGT'.$question.'_'.$partid} != 0 ? 
                   5389: 		    $env{'form.WGT'.$question.'_'.$partid} : 1;
1.71      ng       5390: 		my $partial = $newpts/$wgt;
                   5391: 		my $score;
                   5392: 		if ($partial > 0) {
                   5393: 		    $score = 'correct_by_override';
1.125     ng       5394: 		} elsif ($newpts ne '') { #empty is taken as 0
1.71      ng       5395: 		    $score = 'incorrect_by_override';
                   5396: 		}
1.257     albertel 5397: 		my $dropMenu = $env{'form.GD_SEL'.$question.'_'.$partid};
1.125     ng       5398: 		if ($dropMenu eq 'excused') {
1.71      ng       5399: 		    $partial = '';
                   5400: 		    $score = 'excused';
1.125     ng       5401: 		} elsif ($dropMenu eq 'reset status'
1.257     albertel 5402: 			 && $env{'form.solved'.$question.'_'.$partid} ne '') { #update only if previous record exists
1.125     ng       5403: 		    $newrecord{'resource.'.$partid.'.tries'} = 0;
                   5404: 		    $newrecord{'resource.'.$partid.'.solved'} = '';
                   5405: 		    $newrecord{'resource.'.$partid.'.award'} = '';
                   5406: 		    $newrecord{'resource.'.$partid.'.awarded'} = 0;
1.257     albertel 5407: 		    $newrecord{'resource.'.$partid.'.regrader'} = "$env{'user.name'}:$env{'user.domain'}";
1.125     ng       5408: 		    $changeflag++;
                   5409: 		    $newpts = '';
1.269     raeburn  5410:                     
                   5411:                     my $aggtries =  $env{'form.aggtries'.$question.'_'.$partid};
                   5412:                     my $totaltries = $env{'form.totaltries'.$question.'_'.$partid};
                   5413:                     my $solvedstatus = $env{'form.solved'.$question.'_'.$partid};
                   5414:                     if ($aggtries > 0) {
                   5415:                         &decrement_aggs($symbx,$partid,\%aggregate,$aggtries,$totaltries,$solvedstatus);
                   5416:                         $aggregateflag = 1;
                   5417:                     }
1.71      ng       5418: 		}
1.324     albertel 5419: 		my $display_part=&get_display_part($partid,$curRes->symb());
1.257     albertel 5420: 		my $oldstatus = $env{'form.solved'.$question.'_'.$partid};
1.526     raeburn  5421: 		$displayPts[0].='&nbsp;<b>'.&mt('Part').':</b> '.$display_part.' = '.
1.71      ng       5422: 		    (($oldstatus eq 'excused') ? 'excused' : $oldpts).
1.326     albertel 5423: 		    '&nbsp;<br />';
1.526     raeburn  5424: 		$displayPts[1].='&nbsp;<b>'.&mt('Part').':</b> '.$display_part.' = '.
1.125     ng       5425: 		     (($score eq 'excused') ? 'excused' : $newpts).
1.326     albertel 5426: 		    '&nbsp;<br />';
1.71      ng       5427: 		$question++;
1.380     albertel 5428: 		next if ($dropMenu eq 'reset status' || ($newpts eq $oldpts && $score ne 'excused'));
1.125     ng       5429: 
1.71      ng       5430: 		$newrecord{'resource.'.$partid.'.awarded'}  = $partial if $partial ne '';
1.125     ng       5431: 		$newrecord{'resource.'.$partid.'.solved'}   = $score if $score ne '';
1.257     albertel 5432: 		$newrecord{'resource.'.$partid.'.regrader'} = "$env{'user.name'}:$env{'user.domain'}"
1.125     ng       5433: 		    if (scalar(keys(%newrecord)) > 0);
1.71      ng       5434: 
                   5435: 		$changeflag++;
                   5436: 	    }
                   5437: 	    if (scalar(keys(%newrecord)) > 0) {
1.382     albertel 5438: 		my %record = 
                   5439: 		    &Apache::lonnet::restore($symbx,$env{'request.course.id'},
                   5440: 					     $udom,$uname);
                   5441: 
                   5442: 		if (&Apache::lonnet::validCODE($env{'form.CODE'})) {
                   5443: 		    $newrecord{'resource.CODE'} = $env{'form.CODE'};
                   5444: 		} elsif (&Apache::lonnet::validCODE($record{'resource.CODE'})) {
                   5445: 		    $newrecord{'resource.CODE'} = '';
                   5446: 		}
1.257     albertel 5447: 		&Apache::lonnet::cstore(\%newrecord,$symbx,$env{'request.course.id'},
1.71      ng       5448: 					$udom,$uname);
1.382     albertel 5449: 		%record = &Apache::lonnet::restore($symbx,
                   5450: 						   $env{'request.course.id'},
                   5451: 						   $udom,$uname);
1.380     albertel 5452: 		&check_and_remove_from_queue($parts,\%record,undef,$symbx,
                   5453: 					     $cdom,$cnum,$udom,$uname);
1.71      ng       5454: 	    }
1.380     albertel 5455: 	    
1.269     raeburn  5456:             if ($aggregateflag) {
                   5457:                 &Apache::lonnet::cinc('nohist_resourcetracker',\%aggregate,
                   5458:                       $env{'course.'.$env{'request.course.id'}.'.domain'},
                   5459:                       $env{'course.'.$env{'request.course.id'}.'.num'});
                   5460:             }
1.125     ng       5461: 
1.71      ng       5462: 	    $studentTable.='<td valign="top">'.$displayPts[0].'</td>'.
                   5463: 		'<td valign="top">'.$displayPts[1].'</td>'.
1.484     albertel 5464: 		&Apache::loncommon::end_data_table_row();
1.68      ng       5465: 
1.196     albertel 5466: 	    $prob++;
1.68      ng       5467: 	}
1.71      ng       5468:         $curRes = $iterator->next();
1.68      ng       5469:     }
1.98      albertel 5470: 
1.484     albertel 5471:     $studentTable.=&Apache::loncommon::end_data_table();
1.324     albertel 5472:     $studentTable.=&show_grading_menu_form($env{'form.symb'});
1.526     raeburn  5473:     my $grademsg=($changeflag == 0 ? &mt('No score was changed or updated.') :
                   5474: 		  &mt('The scores were changed for [quant,_1,problem].',
1.596.2.12.2.  1(raebur 5475:5): 		  $changeflag).'<br />');
                   5476:5):     my $hidemsg=($hideflag == 0 ? '' :
                   5477:5):                  &mt('Submissions were marked "hidden" for [quant,_1,transaction].',
                   5478:5):                      $hideflag).'<br />');
                   5479:5):     $request->print($hidemsg.$grademsg.$studentTable);
1.68      ng       5480: 
1.70      ng       5481:     return '';
                   5482: }
                   5483: 
1.72      ng       5484: #-------- end of section for handling grading by page/sequence ---------
                   5485: #
                   5486: #-------------------------------------------------------------------
                   5487: 
1.581     www      5488: #-------------------- Bubblesheet (Scantron) Grading -------------------
1.75      albertel 5489: #
                   5490: #------ start of section for handling grading by page/sequence ---------
                   5491: 
1.423     albertel 5492: =pod
                   5493: 
                   5494: =head1 Bubble sheet grading routines
                   5495: 
1.424     albertel 5496:   For this documentation:
                   5497: 
                   5498:    'scanline' refers to the full line of characters
                   5499:    from the file that we are parsing that represents one entire sheet
                   5500: 
                   5501:    'bubble line' refers to the data
1.596.2.6  raeburn  5502:    representing the line of bubbles that are on the physical bubblesheet
1.424     albertel 5503: 
                   5504: 
1.596.2.6  raeburn  5505: The overall process is that a scanned in bubblesheet data is uploaded
1.424     albertel 5506: into a course. When a user wants to grade, they select a
1.596.2.6  raeburn  5507: sequence/folder of resources, a file of bubblesheet info, and pick
1.424     albertel 5508: one of the predefined configurations for what each scanline looks
                   5509: like.
                   5510: 
                   5511: Next each scanline is checked for any errors of either 'missing
1.435     foxr     5512: bubbles' (it's an error because it may have been mis-scanned
1.424     albertel 5513: because too light bubbling), 'double bubble' (each bubble line should
1.596.2.12.2.  0(raebur 5514:3): have no more than one letter picked), invalid or duplicated CODE,
1.556     weissno  5515: invalid student/employee ID
1.424     albertel 5516: 
                   5517: If the CODE option is used that determines the randomization of the
1.556     weissno  5518: homework problems, either way the student/employee ID is looked up into a
1.424     albertel 5519: username:domain.
                   5520: 
                   5521: During the validation phase the instructor can choose to skip scanlines. 
                   5522: 
1.596.2.6  raeburn  5523: After the validation phase, there are now 3 bubblesheet files
1.424     albertel 5524: 
                   5525:   scantron_original_filename (unmodified original file)
                   5526:   scantron_corrected_filename (file where the corrected information has replaced the original information)
                   5527:   scantron_skipped_filename (contains the exact text of scanlines that where skipped)
                   5528: 
                   5529: Also there is a separate hash nohist_scantrondata that contains extra
1.596.2.6  raeburn  5530: correction information that isn't representable in the bubblesheet
1.424     albertel 5531: file (see &scantron_getfile() for more information)
                   5532: 
                   5533: After all scanlines are either valid, marked as valid or skipped, then
                   5534: foreach line foreach problem in the picked sequence, an ssi request is
                   5535: made that simulates a user submitting their selected letter(s) against
                   5536: the homework problem.
1.423     albertel 5537: 
                   5538: =over 4
                   5539: 
                   5540: 
                   5541: 
                   5542: =item defaultFormData
                   5543: 
                   5544:   Returns html hidden inputs used to hold context/default values.
                   5545: 
                   5546:  Arguments:
                   5547:   $symb - $symb of the current resource 
                   5548: 
                   5549: =cut
1.422     foxr     5550: 
1.81      albertel 5551: sub defaultFormData {
1.324     albertel 5552:     my ($symb)=@_;
1.447     foxr     5553:     return '<input type="hidden" name="symb"    value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
1.257     albertel 5554:      '<input type="hidden" name="saveState" value="'.$env{'form.saveState'}.'" />'."\n".
                   5555:      '<input type="hidden" name="probTitle" value="'.$env{'form.probTitle'}.'" />'."\n";
1.81      albertel 5556: }
                   5557: 
1.447     foxr     5558: 
1.423     albertel 5559: =pod 
                   5560: 
                   5561: =item getSequenceDropDown
                   5562: 
                   5563:    Return html dropdown of possible sequences to grade
                   5564:  
                   5565:  Arguments:
1.582     raeburn  5566:    $symb - $symb of the current resource
                   5567:    $map_error - ref to scalar which will container error if
                   5568:                 $navmap object is unavailable in &getSymbMap().
1.423     albertel 5569: 
                   5570: =cut
1.422     foxr     5571: 
1.75      albertel 5572: sub getSequenceDropDown {
1.582     raeburn  5573:     my ($symb,$map_error)=@_;
1.75      albertel 5574:     my $result='<select name="selectpage">'."\n";
1.582     raeburn  5575:     my ($titles,$symbx) = &getSymbMap($map_error);
                   5576:     if (ref($map_error)) {
                   5577:         return if ($$map_error);
                   5578:     }
1.137     albertel 5579:     my ($curpage)=&Apache::lonnet::decode_symb($symb); 
1.75      albertel 5580:     my $ctr=0;
                   5581:     foreach (@$titles) {
                   5582: 	my ($minder,$showtitle) = ($_ =~ /(\d+)\.(.*)/);
                   5583: 	$result.='<option value="'.$$symbx{$_}.'" '.
1.401     albertel 5584: 	    ($$symbx{$_} =~ /$curpage$/ ? 'selected="selected"' : '').
1.75      albertel 5585: 	    '>'.$showtitle.'</option>'."\n";
                   5586: 	$ctr++;
                   5587:     }
                   5588:     $result.= '</select>';
                   5589:     return $result;
                   5590: }
                   5591: 
1.495     albertel 5592: my %bubble_lines_per_response;     # no. bubble lines for each response.
1.554     raeburn  5593:                                    # key is zero-based index - 0, 1, 2 ...
1.495     albertel 5594: 
                   5595: my %first_bubble_line;             # First bubble line no. for each bubble.
                   5596: 
1.509     raeburn  5597: my %subdivided_bubble_lines;       # no. bubble lines for optionresponse, 
                   5598:                                    # matchresponse or rankresponse, where 
                   5599:                                    # an individual response can have multiple 
                   5600:                                    # lines
1.503     raeburn  5601: 
                   5602: my %responsetype_per_response;     # responsetype for each response
                   5603: 
1.596.2.12.2.  6(raebur 5604:3): my %masterseq_id_responsenum;      # src_id (e.g., 12.3_0.11 etc.) for each
                   5605:3):                                    # numbered response. Needed when randomorder
                   5606:3):                                    # or randompick are in use. Key is ID, value 
                   5607:3):                                    # is response number.
                   5608:3): 
1.495     albertel 5609: # Save and restore the bubble lines array to the form env.
                   5610: 
                   5611: 
                   5612: sub save_bubble_lines {
                   5613:     foreach my $line (keys(%bubble_lines_per_response)) {
                   5614: 	$env{"form.scantron.bubblelines.$line"}  = $bubble_lines_per_response{$line};
                   5615: 	$env{"form.scantron.first_bubble_line.$line"} =
                   5616: 	    $first_bubble_line{$line};
1.503     raeburn  5617:         $env{"form.scantron.sub_bubblelines.$line"} = 
                   5618:             $subdivided_bubble_lines{$line};
                   5619:         $env{"form.scantron.responsetype.$line"} =
                   5620:             $responsetype_per_response{$line};
1.495     albertel 5621:     }
1.596.2.12.2.  6(raebur 5622:3):     foreach my $resid (keys(%masterseq_id_responsenum)) {
                   5623:3):         my $line = $masterseq_id_responsenum{$resid};
                   5624:3):         $env{"form.scantron.residpart.$line"} = $resid;
                   5625:3):     }
1.495     albertel 5626: }
                   5627: 
                   5628: 
                   5629: sub restore_bubble_lines {
                   5630:     my $line = 0;
                   5631:     %bubble_lines_per_response = ();
1.596.2.12.2.  6(raebur 5632:3):     %masterseq_id_responsenum = ();
1.495     albertel 5633:     while ($env{"form.scantron.bubblelines.$line"}) {
                   5634: 	my $value = $env{"form.scantron.bubblelines.$line"};
                   5635: 	$bubble_lines_per_response{$line} = $value;
                   5636: 	$first_bubble_line{$line}  =
                   5637: 	    $env{"form.scantron.first_bubble_line.$line"};
1.503     raeburn  5638:         $subdivided_bubble_lines{$line} =
                   5639:             $env{"form.scantron.sub_bubblelines.$line"};
                   5640:         $responsetype_per_response{$line} =
                   5641:             $env{"form.scantron.responsetype.$line"};
1.596.2.12.2.  6(raebur 5642:3):         my $id = $env{"form.scantron.residpart.$line"};
                   5643:3):         $masterseq_id_responsenum{$id} = $line;
1.495     albertel 5644: 	$line++;
                   5645:     }
                   5646: }
                   5647: 
1.423     albertel 5648: =pod 
                   5649: 
                   5650: =item scantron_filenames
                   5651: 
                   5652:    Returns a list of the scantron files in the current course 
                   5653: 
                   5654: =cut
1.422     foxr     5655: 
1.202     albertel 5656: sub scantron_filenames {
1.257     albertel 5657:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
                   5658:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
1.517     raeburn  5659:     my $getpropath = 1;
1.596.2.12.2.  (raeburn 5660:):     my ($dirlist,$listerror) = &Apache::lonnet::dirlist('userfiles',$cdom,
                   5661:):                                                         $cname,$getpropath);
1.202     albertel 5662:     my @possiblenames;
1.596.2.12.2.  (raeburn 5663:):     if (ref($dirlist) eq 'ARRAY') {
                   5664:):         foreach my $filename (sort(@{$dirlist})) {
                   5665:): 	    ($filename)=split(/&/,$filename);
                   5666:): 	    if ($filename!~/^scantron_orig_/) { next ; }
                   5667:): 	    $filename=~s/^scantron_orig_//;
                   5668:): 	    push(@possiblenames,$filename);
                   5669:):         }
1.202     albertel 5670:     }
                   5671:     return @possiblenames;
                   5672: }
                   5673: 
1.423     albertel 5674: =pod 
                   5675: 
                   5676: =item scantron_uploads
                   5677: 
                   5678:    Returns  html drop-down list of scantron files in current course.
                   5679: 
                   5680:  Arguments:
                   5681:    $file2grade - filename to set as selected in the dropdown
                   5682: 
                   5683: =cut
1.422     foxr     5684: 
1.202     albertel 5685: sub scantron_uploads {
1.209     ng       5686:     my ($file2grade) = @_;
1.202     albertel 5687:     my $result=	'<select name="scantron_selectfile">';
                   5688:     $result.="<option></option>";
                   5689:     foreach my $filename (sort(&scantron_filenames())) {
1.401     albertel 5690: 	$result.="<option".($filename eq $file2grade ? ' selected="selected"':'').">$filename</option>\n";
1.81      albertel 5691:     }
                   5692:     $result.="</select>";
                   5693:     return $result;
                   5694: }
                   5695: 
1.423     albertel 5696: =pod 
                   5697: 
                   5698: =item scantron_scantab
                   5699: 
                   5700:   Returns html drop down of the scantron formats in the scantronformat.tab
                   5701:   file.
                   5702: 
                   5703: =cut
1.422     foxr     5704: 
1.82      albertel 5705: sub scantron_scantab {
                   5706:     my $result='<select name="scantron_format">'."\n";
1.191     albertel 5707:     $result.='<option></option>'."\n";
1.518     raeburn  5708:     my @lines = &get_scantronformat_file();
                   5709:     if (@lines > 0) {
                   5710:         foreach my $line (@lines) {
                   5711:             next if (($line =~ /^\#/) || ($line eq ''));
                   5712: 	    my ($name,$descrip)=split(/:/,$line);
                   5713: 	    $result.='<option value="'.$name.'">'.$descrip.'</option>'."\n";
                   5714:         }
1.82      albertel 5715:     }
                   5716:     $result.='</select>'."\n";
1.518     raeburn  5717:     return $result;
                   5718: }
                   5719: 
                   5720: =pod
                   5721: 
                   5722: =item get_scantronformat_file
                   5723: 
                   5724:   Returns an array containing lines from the scantron format file for
                   5725:   the domain of the course.
                   5726: 
                   5727:   If a url for a custom.tab file is listed in domain's configuration.db, 
                   5728:   lines are from this file.
                   5729: 
                   5730:   Otherwise, if a default.tab has been published in RES space by the 
                   5731:   domainconfig user, lines are from this file.
                   5732: 
                   5733:   Otherwise, fall back to getting lines from the legacy file on the
1.519     raeburn  5734:   local server:  /home/httpd/lonTabs/default_scantronformat.tab    
1.82      albertel 5735: 
1.518     raeburn  5736: =cut
                   5737: 
                   5738: sub get_scantronformat_file {
                   5739:     my $cdom= $env{'course.'.$env{'request.course.id'}.'.domain'};
                   5740:     my %domconfig = &Apache::lonnet::get_dom('configuration',['scantron'],$cdom);
                   5741:     my $gottab = 0;
                   5742:     my @lines;
                   5743:     if (ref($domconfig{'scantron'}) eq 'HASH') {
                   5744:         if ($domconfig{'scantron'}{'scantronformat'} ne '') {
                   5745:             my $formatfile = &Apache::lonnet::getfile($Apache::lonnet::perlvar{'lonDocRoot'}.$domconfig{'scantron'}{'scantronformat'});
                   5746:             if ($formatfile ne '-1') {
                   5747:                 @lines = split("\n",$formatfile,-1);
                   5748:                 $gottab = 1;
                   5749:             }
                   5750:         }
                   5751:     }
                   5752:     if (!$gottab) {
                   5753:         my $confname = $cdom.'-domainconfig';
                   5754:         my $default = $Apache::lonnet::perlvar{'lonDocRoot'}.'/res/'.$cdom.'/'.$confname.'/default.tab';
                   5755:         my $formatfile =  &Apache::lonnet::getfile($default);
                   5756:         if ($formatfile ne '-1') {
                   5757:             @lines = split("\n",$formatfile,-1);
                   5758:             $gottab = 1;
                   5759:         }
                   5760:     }
                   5761:     if (!$gottab) {
1.519     raeburn  5762:         my @domains = &Apache::lonnet::current_machine_domains();
                   5763:         if (grep(/^\Q$cdom\E$/,@domains)) {
                   5764:             my $fh=Apache::File->new($Apache::lonnet::perlvar{'lonTabDir'}.'/scantronformat.tab');
                   5765:             @lines = <$fh>;
                   5766:             close($fh);
                   5767:         } else {
                   5768:             my $fh=Apache::File->new($Apache::lonnet::perlvar{'lonTabDir'}.'/default_scantronformat.tab');
                   5769:             @lines = <$fh>;
                   5770:             close($fh);
                   5771:         }
1.518     raeburn  5772:     }
                   5773:     return @lines;
1.82      albertel 5774: }
                   5775: 
1.423     albertel 5776: =pod 
                   5777: 
                   5778: =item scantron_CODElist
                   5779: 
                   5780:   Returns html drop down of the saved CODE lists from current course,
                   5781:   generated from earlier printings.
                   5782: 
                   5783: =cut
1.422     foxr     5784: 
1.186     albertel 5785: sub scantron_CODElist {
1.257     albertel 5786:     my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   5787:     my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
1.186     albertel 5788:     my @names=&Apache::lonnet::getkeys('CODEs',$cdom,$cnum);
                   5789:     my $namechoice='<option></option>';
1.225     albertel 5790:     foreach my $name (sort {uc($a) cmp uc($b)} @names) {
1.191     albertel 5791: 	if ($name =~ /^error: 2 /) { next; }
1.278     albertel 5792: 	if ($name =~ /^type\0/) { next; }
1.186     albertel 5793: 	$namechoice.='<option value="'.$name.'">'.$name.'</option>';
                   5794:     }
                   5795:     $namechoice='<select name="scantron_CODElist">'.$namechoice.'</select>';
                   5796:     return $namechoice;
                   5797: }
                   5798: 
1.423     albertel 5799: =pod 
                   5800: 
                   5801: =item scantron_CODEunique
                   5802: 
                   5803:   Returns the html for "Each CODE to be used once" radio.
                   5804: 
                   5805: =cut
1.422     foxr     5806: 
1.186     albertel 5807: sub scantron_CODEunique {
1.532     bisitz   5808:     my $result='<span class="LC_nobreak">
1.272     albertel 5809:                  <label><input type="radio" name="scantron_CODEunique"
1.423     albertel 5810:                         value="yes" checked="checked" />'.&mt('Yes').' </label>
1.381     albertel 5811:                 </span>
1.532     bisitz   5812:                 <span class="LC_nobreak">
1.272     albertel 5813:                  <label><input type="radio" name="scantron_CODEunique"
1.423     albertel 5814:                         value="no" />'.&mt('No').' </label>
1.381     albertel 5815:                 </span>';
1.186     albertel 5816:     return $result;
                   5817: }
1.423     albertel 5818: 
                   5819: =pod 
                   5820: 
                   5821: =item scantron_selectphase
                   5822: 
1.596.2.6  raeburn  5823:   Generates the initial screen to start the bubblesheet process.
1.423     albertel 5824:   Allows for - starting a grading run.
1.424     albertel 5825:              - downloading existing scan data (original, corrected
1.423     albertel 5826:                                                 or skipped info)
                   5827: 
                   5828:              - uploading new scan data
                   5829: 
                   5830:  Arguments:
                   5831:   $r          - The Apache request object
                   5832:   $file2grade - name of the file that contain the scanned data to score
                   5833: 
                   5834: =cut
1.186     albertel 5835: 
1.75      albertel 5836: sub scantron_selectphase {
1.209     ng       5837:     my ($r,$file2grade) = @_;
1.324     albertel 5838:     my ($symb)=&get_symb($r);
1.75      albertel 5839:     if (!$symb) {return '';}
1.582     raeburn  5840:     my $map_error;
                   5841:     my $sequence_selector=&getSequenceDropDown($symb,\$map_error);
                   5842:     if ($map_error) {
                   5843:         $r->print('<br />'.&navmap_errormsg().'<br />');
                   5844:         return;
                   5845:     }
1.324     albertel 5846:     my $default_form_data=&defaultFormData($symb);
                   5847:     my $grading_menu_button=&show_grading_menu_form($symb);
1.209     ng       5848:     my $file_selector=&scantron_uploads($file2grade);
1.82      albertel 5849:     my $format_selector=&scantron_scantab();
1.186     albertel 5850:     my $CODE_selector=&scantron_CODElist();
                   5851:     my $CODE_unique=&scantron_CODEunique();
1.75      albertel 5852:     my $result;
1.422     foxr     5853: 
1.513     foxr     5854:     $ssi_error = 0;
                   5855: 
1.596.2.4  raeburn  5856:     if (&Apache::lonnet::allowed('usc',$env{'request.role.domain'}) ||
                   5857:         &Apache::lonnet::allowed('usc',$env{'request.course.id'})) {
                   5858: 
                   5859:         # Chunk of form to prompt for a scantron file upload.
                   5860: 
                   5861:         $r->print('
                   5862:     <br />
                   5863:     '.&Apache::loncommon::start_data_table('LC_scantron_action').'
                   5864:        '.&Apache::loncommon::start_data_table_header_row().'
                   5865:             <th>
                   5866:               &nbsp;'.&mt('Specify a bubblesheet data file to upload.').'
                   5867:             </th>
                   5868:        '.&Apache::loncommon::end_data_table_header_row().'
                   5869:        '.&Apache::loncommon::start_data_table_row().'
                   5870:             <td>
                   5871: ');
                   5872:     my $default_form_data=&defaultFormData(&get_symb($r,1));
                   5873:     my $cdom= $env{'course.'.$env{'request.course.id'}.'.domain'};
                   5874:     my $cnum= $env{'course.'.$env{'request.course.id'}.'.num'};
1.596.2.12.2.  6(raebur 5875:6):     my $alertmsg = &mt('Please use the browse button to select a file from your local directory.');
                   5876:6):     &js_escape(\$alertmsg);
1.596.2.4  raeburn  5877:     $r->print('
                   5878:               <script type="text/javascript" language="javascript">
                   5879:     function checkUpload(formname) {
                   5880:         if (formname.upfile.value == "") {
1.596.2.12.2.  6(raebur 5881:6):             alert("'.$alertmsg.'");
1.596.2.4  raeburn  5882:             return false;
                   5883:         }
                   5884:         formname.submit();
                   5885:     }
                   5886:               </script>
                   5887: 
                   5888:               <form enctype="multipart/form-data" action="/adm/grades" name="rules" method="post">
                   5889:                 '.$default_form_data.'
                   5890:                 <input name="courseid" type="hidden" value="'.$cnum.'" />
                   5891:                 <input name="domainid" type="hidden" value="'.$cdom.'" />
                   5892:                 <input name="command" value="scantronupload_save" type="hidden" />
                   5893:                 '.&mt('File to upload: [_1]','<input type="file" name="upfile" size="50" />').'
                   5894:                 <br />
                   5895:                 <input type="button" onclick="javascript:checkUpload(this.form);" value="'.&mt('Upload Bubblesheet Data').'" />
                   5896:               </form>
                   5897: ');
                   5898: 
                   5899:         $r->print('
                   5900:             </td>
                   5901:        '.&Apache::loncommon::end_data_table_row().'
                   5902:        '.&Apache::loncommon::end_data_table().'
                   5903: ');
                   5904:     }
                   5905: 
1.422     foxr     5906:     # Chunk of form to prompt for a file to grade and how:
                   5907: 
1.489     albertel 5908:     $result.= '
                   5909:     <br />
                   5910:     <form method="post" enctype="multipart/form-data" action="/adm/grades" name="scantron_process">
                   5911:     <input type="hidden" name="command" value="scantron_warning" />
                   5912:     '.$default_form_data.'
                   5913:     '.&Apache::loncommon::start_data_table('LC_scantron_action').'
                   5914:        '.&Apache::loncommon::start_data_table_header_row().'
                   5915:             <th colspan="2">
1.492     albertel 5916:               &nbsp;'.&mt('Specify file and which Folder/Sequence to grade').'
1.489     albertel 5917:             </th>
                   5918:        '.&Apache::loncommon::end_data_table_header_row().'
                   5919:        '.&Apache::loncommon::start_data_table_row().'
1.492     albertel 5920:             <td> '.&mt('Sequence to grade:').' </td><td> '.$sequence_selector.' </td>
1.489     albertel 5921:        '.&Apache::loncommon::end_data_table_row().'
                   5922:        '.&Apache::loncommon::start_data_table_row().'
1.572     www      5923:             <td> '.&mt('Filename of bubblesheet data file:').' </td><td> '.$file_selector.' </td>
1.489     albertel 5924:        '.&Apache::loncommon::end_data_table_row().'
                   5925:        '.&Apache::loncommon::start_data_table_row().'
1.572     www      5926:             <td> '.&mt('Format of bubblesheet data file:').' </td><td> '.$format_selector.' </td>
1.489     albertel 5927:        '.&Apache::loncommon::end_data_table_row().'
                   5928:        '.&Apache::loncommon::start_data_table_row().'
1.492     albertel 5929:             <td> '.&mt('Saved CODEs to validate against:').' </td><td> '.$CODE_selector.' </td>
1.489     albertel 5930:        '.&Apache::loncommon::end_data_table_row().'
                   5931:        '.&Apache::loncommon::start_data_table_row().'
1.492     albertel 5932:             <td> '.&mt('Each CODE is only to be used once:').'</td><td> '.$CODE_unique.' </td>
1.489     albertel 5933:        '.&Apache::loncommon::end_data_table_row().'
                   5934:        '.&Apache::loncommon::start_data_table_row().'
1.492     albertel 5935: 	    <td> '.&mt('Options:').' </td>
1.187     albertel 5936:             <td>
1.492     albertel 5937: 	       <label><input type="checkbox" name="scantron_options_redo" value="redo_skipped"/> '.&mt('Do only previously skipped records').'</label> <br />
                   5938:                <label><input type="checkbox" name="scantron_options_ignore" value="ignore_corrections"/> '.&mt('Remove all existing corrections').'</label> <br />
                   5939:                <label><input type="checkbox" name="scantron_options_hidden" value="ignore_hidden"/> '.&mt('Skip hidden resources when grading').'</label>
1.187     albertel 5940: 	    </td>
1.489     albertel 5941:        '.&Apache::loncommon::end_data_table_row().'
                   5942:        '.&Apache::loncommon::start_data_table_row().'
1.174     albertel 5943:             <td colspan="2">
1.572     www      5944:               <input type="submit" value="'.&mt('Grading: Validate Bubblesheet Records').'" />
1.162     albertel 5945:             </td>
1.489     albertel 5946:        '.&Apache::loncommon::end_data_table_row().'
                   5947:     '.&Apache::loncommon::end_data_table().'
                   5948:     </form>
                   5949: ';
1.162     albertel 5950:    
                   5951:     $r->print($result);
                   5952: 
1.422     foxr     5953:     # Chunk of the form that prompts to view a scoring office file,
                   5954:     # corrected file, skipped records in a file.
                   5955: 
1.489     albertel 5956:     $r->print('
                   5957:    <br />
                   5958:    <form action="/adm/grades" name="scantron_download">
                   5959:      '.$default_form_data.'
                   5960:      <input type="hidden" name="command" value="scantron_download" />
                   5961:      '.&Apache::loncommon::start_data_table('LC_scantron_action').'
                   5962:        '.&Apache::loncommon::start_data_table_header_row().'
                   5963:               <th>
1.492     albertel 5964:                 &nbsp;'.&mt('Download a scoring office file').'
1.489     albertel 5965:               </th>
                   5966:        '.&Apache::loncommon::end_data_table_header_row().'
                   5967:        '.&Apache::loncommon::start_data_table_row().'
1.492     albertel 5968:               <td> '.&mt('Filename of scoring office file: [_1]',$file_selector).' 
1.489     albertel 5969:                 <br />
1.492     albertel 5970:                 <input type="submit" value="'.&mt('Download: Show List of Associated Files').'" />
1.489     albertel 5971:        '.&Apache::loncommon::end_data_table_row().'
                   5972:      '.&Apache::loncommon::end_data_table().'
                   5973:    </form>
                   5974:    <br />
                   5975: ');
1.162     albertel 5976: 
1.457     banghart 5977:     &Apache::lonpickcode::code_list($r,2);
1.523     raeburn  5978: 
1.596.2.12.2.  8(raebur 5979:3):     $r->print('<br /><form method="post" name="checkscantron" action="">'.
1.523     raeburn  5980:              $default_form_data."\n".
                   5981:              &Apache::loncommon::start_data_table('LC_scantron_action')."\n".
                   5982:              &Apache::loncommon::start_data_table_header_row()."\n".
                   5983:              '<th colspan="2">
1.572     www      5984:               &nbsp;'.&mt('Review bubblesheet data and submissions for a previously graded folder/sequence')."\n".
1.523     raeburn  5985:              '</th>'."\n".
                   5986:               &Apache::loncommon::end_data_table_header_row()."\n".
                   5987:               &Apache::loncommon::start_data_table_row()."\n".
                   5988:               '<td> '.&mt('Graded folder/sequence:').' </td>'."\n".
                   5989:               '<td> '.$sequence_selector.' </td>'.
                   5990:               &Apache::loncommon::end_data_table_row()."\n".
                   5991:               &Apache::loncommon::start_data_table_row()."\n".
                   5992:               '<td> '.&mt('Filename of scoring office file:').' </td>'."\n".
                   5993:               '<td> '.$file_selector.' </td>'."\n".
                   5994:               &Apache::loncommon::end_data_table_row()."\n".
                   5995:               &Apache::loncommon::start_data_table_row()."\n".
                   5996:               '<td> '.&mt('Format of data file:').' </td>'."\n".
                   5997:               '<td> '.$format_selector.' </td>'."\n".
                   5998:               &Apache::loncommon::end_data_table_row()."\n".
                   5999:               &Apache::loncommon::start_data_table_row()."\n".
1.557     raeburn  6000:               '<td> '.&mt('Options').' </td>'."\n".
                   6001:               '<td> <label><input type="checkbox" name="scantron_options_hidden" value="ignore_hidden"/> '.&mt('Skip hidden resources').'</label></td>'.
                   6002:               &Apache::loncommon::end_data_table_row()."\n".
                   6003:               &Apache::loncommon::start_data_table_row()."\n".
1.523     raeburn  6004:               '<td colspan="2">'."\n".
                   6005:               '<input type="hidden" name="command" value="checksubmissions" />'."\n".
1.575     www      6006:               '<input type="submit" value="'.&mt('Review Bubblesheet Data and Submission Records').'" />'."\n".
1.523     raeburn  6007:               '</td>'."\n".
                   6008:               &Apache::loncommon::end_data_table_row()."\n".
                   6009:               &Apache::loncommon::end_data_table()."\n".
                   6010:               '</form><br />');
1.457     banghart 6011:     $r->print($grading_menu_button);
1.523     raeburn  6012:     return;
1.75      albertel 6013: }
                   6014: 
1.423     albertel 6015: =pod
                   6016: 
                   6017: =item get_scantron_config
                   6018: 
                   6019:    Parse and return the scantron configuration line selected as a
                   6020:    hash of configuration file fields.
                   6021: 
                   6022:  Arguments:
                   6023:     which - the name of the configuration to parse from the file.
                   6024: 
                   6025: 
                   6026:  Returns:
                   6027:             If the named configuration is not in the file, an empty
                   6028:             hash is returned.
                   6029:     a hash with the fields
                   6030:       name         - internal name for the this configuration setup
                   6031:       description  - text to display to operator that describes this config
                   6032:       CODElocation - if 0 or the string 'none'
                   6033:                           - no CODE exists for this config
                   6034:                      if -1 || the string 'letter'
                   6035:                           - a CODE exists for this config and is
                   6036:                             a string of letters
                   6037:                      Unsupported value (but planned for future support)
                   6038:                           if a positive integer
                   6039:                                - The CODE exists as the first n items from
                   6040:                                  the question section of the form
                   6041:                           if the string 'number'
                   6042:                                - The CODE exists for this config and is
                   6043:                                  a string of numbers
                   6044:       CODEstart   - (only matter if a CODE exists) column in the line where
                   6045:                      the CODE starts
                   6046:       CODElength  - length of the CODE
1.573     bisitz   6047:       IDstart     - column where the student/employee ID starts
1.556     weissno  6048:       IDlength    - length of the student/employee ID info
1.423     albertel 6049:       Qstart      - column where the information from the bubbled
                   6050:                     'questions' start
                   6051:       Qlength     - number of columns comprising a single bubble line from
                   6052:                     the sheet. (usually either 1 or 10)
1.424     albertel 6053:       Qon         - either a single character representing the character used
1.423     albertel 6054:                     to signal a bubble was chosen in the positional setup, or
                   6055:                     the string 'letter' if the letter of the chosen bubble is
                   6056:                     in the final, or 'number' if a number representing the
                   6057:                     chosen bubble is in the file (1->A 0->J)
1.424     albertel 6058:       Qoff        - the character used to represent that a bubble was
                   6059:                     left blank
1.423     albertel 6060:       PaperID     - if the scanning process generates a unique number for each
                   6061:                     sheet scanned the column that this ID number starts in
                   6062:       PaperIDlength - number of columns that comprise the unique ID number
                   6063:                       for the sheet of paper
1.424     albertel 6064:       FirstName   - column that the first name starts in
1.423     albertel 6065:       FirstNameLength - number of columns that the first name spans
                   6066:  
                   6067:       LastName    - column that the last name starts in
                   6068:       LastNameLength - number of columns that the last name spans
1.596.2.12.2.  (raeburn 6069:):       BubblesPerRow - number of bubbles available in each row used to
                   6070:):                       bubble an answer. (If not specified, 10 assumed).
1.423     albertel 6071: 
                   6072: =cut
1.422     foxr     6073: 
1.82      albertel 6074: sub get_scantron_config {
                   6075:     my ($which) = @_;
1.518     raeburn  6076:     my @lines = &get_scantronformat_file();
1.82      albertel 6077:     my %config;
1.157     albertel 6078:     #FIXME probably should move to XML it has already gotten a bit much now
1.518     raeburn  6079:     foreach my $line (@lines) {
1.82      albertel 6080: 	my ($name,$descrip)=split(/:/,$line);
                   6081: 	if ($name ne $which ) { next; }
                   6082: 	chomp($line);
                   6083: 	my @config=split(/:/,$line);
                   6084: 	$config{'name'}=$config[0];
                   6085: 	$config{'description'}=$config[1];
                   6086: 	$config{'CODElocation'}=$config[2];
                   6087: 	$config{'CODEstart'}=$config[3];
                   6088: 	$config{'CODElength'}=$config[4];
                   6089: 	$config{'IDstart'}=$config[5];
                   6090: 	$config{'IDlength'}=$config[6];
                   6091: 	$config{'Qstart'}=$config[7];
1.497     foxr     6092:  	$config{'Qlength'}=$config[8];
1.82      albertel 6093: 	$config{'Qoff'}=$config[9];
                   6094: 	$config{'Qon'}=$config[10];
1.157     albertel 6095: 	$config{'PaperID'}=$config[11];
                   6096: 	$config{'PaperIDlength'}=$config[12];
                   6097: 	$config{'FirstName'}=$config[13];
                   6098: 	$config{'FirstNamelength'}=$config[14];
                   6099: 	$config{'LastName'}=$config[15];
                   6100: 	$config{'LastNamelength'}=$config[16];
1.596.2.12.2.  (raeburn 6101:):         $config{'BubblesPerRow'}=$config[17];
1.82      albertel 6102: 	last;
                   6103:     }
                   6104:     return %config;
                   6105: }
                   6106: 
1.423     albertel 6107: =pod 
                   6108: 
                   6109: =item username_to_idmap
                   6110: 
1.556     weissno  6111:     creates a hash keyed by student/employee ID with values of the corresponding
1.423     albertel 6112:     student username:domain.
                   6113: 
                   6114:   Arguments:
                   6115: 
                   6116:     $classlist - reference to the class list hash. This is a hash
                   6117:                  keyed by student name:domain  whose elements are references
1.424     albertel 6118:                  to arrays containing various chunks of information
1.423     albertel 6119:                  about the student. (See loncoursedata for more info).
                   6120: 
                   6121:   Returns
                   6122:     %idmap - the constructed hash
                   6123: 
                   6124: =cut
                   6125: 
1.82      albertel 6126: sub username_to_idmap {
                   6127:     my ($classlist)= @_;
                   6128:     my %idmap;
                   6129:     foreach my $student (keys(%$classlist)) {
1.596.2.12.2.  3(raebur 6130:5):         my $id = $classlist->{$student}->[&Apache::loncoursedata::CL_ID];
                   6131:5):         unless ($id eq '') {
                   6132:5):             if (!exists($idmap{$id})) {
                   6133:5):                 $idmap{$id} = $student;
                   6134:5):             } else {
                   6135:5):                 my $status = $classlist->{$student}->[&Apache::loncoursedata::CL_STATUS];
                   6136:5):                 if ($status eq 'Active') {
                   6137:5):                     $idmap{$id} = $student;
                   6138:5):                 }
                   6139:5):             }
                   6140:5):         }
1.82      albertel 6141:     }
                   6142:     return %idmap;
                   6143: }
1.423     albertel 6144: 
                   6145: =pod
                   6146: 
1.424     albertel 6147: =item scantron_fixup_scanline
1.423     albertel 6148: 
                   6149:    Process a requested correction to a scanline.
                   6150: 
                   6151:   Arguments:
                   6152:     $scantron_config   - hash from &get_scantron_config()
                   6153:     $scan_data         - hash of correction information 
                   6154:                           (see &scantron_getfile())
                   6155:     $line              - existing scanline
                   6156:     $whichline         - line number of the passed in scanline
                   6157:     $field             - type of change to process 
                   6158:                          (either 
1.573     bisitz   6159:                           'ID'     -> correct the student/employee ID
1.423     albertel 6160:                           'CODE'   -> correct the CODE
                   6161:                           'answer' -> fixup the submitted answers)
                   6162:     
                   6163:    $args               - hash of additional info,
                   6164:                           - 'ID' 
                   6165:                                'newid' -> studentID to use in replacement
1.424     albertel 6166:                                           of existing one
1.423     albertel 6167:                           - 'CODE' 
                   6168:                                'CODE_ignore_dup' - set to true if duplicates
                   6169:                                                    should be ignored.
                   6170: 	                       'CODE' - is new code or 'use_unfound'
1.424     albertel 6171:                                         if the existing unfound code should
1.423     albertel 6172:                                         be used as is
                   6173:                           - 'answer'
                   6174:                                'response' - new answer or 'none' if blank
                   6175:                                'question' - the bubble line to change
1.503     raeburn  6176:                                'questionnum' - the question identifier,
                   6177:                                                may include subquestion. 
1.423     albertel 6178: 
                   6179:   Returns:
                   6180:     $line - the modified scanline
                   6181: 
                   6182:   Side effects: 
                   6183:     $scan_data - may be updated
                   6184: 
                   6185: =cut
                   6186: 
1.82      albertel 6187: 
1.157     albertel 6188: sub scantron_fixup_scanline {
                   6189:     my ($scantron_config,$scan_data,$line,$whichline,$field,$args)=@_;
                   6190:     if ($field eq 'ID') {
                   6191: 	if (length($args->{'newid'}) > $$scantron_config{'IDlength'}) {
1.186     albertel 6192: 	    return ($line,1,'New value too large');
1.157     albertel 6193: 	}
                   6194: 	if (length($args->{'newid'}) < $$scantron_config{'IDlength'}) {
                   6195: 	    $args->{'newid'}=sprintf('%-'.$$scantron_config{'IDlength'}.'s',
                   6196: 				     $args->{'newid'});
                   6197: 	}
                   6198: 	substr($line,$$scantron_config{'IDstart'}-1,
                   6199: 	       $$scantron_config{'IDlength'})=$args->{'newid'};
                   6200: 	if ($args->{'newid'}=~/^\s*$/) {
                   6201: 	    &scan_data($scan_data,"$whichline.user",
                   6202: 		       $args->{'username'}.':'.$args->{'domain'});
                   6203: 	}
1.186     albertel 6204:     } elsif ($field eq 'CODE') {
1.192     albertel 6205: 	if ($args->{'CODE_ignore_dup'}) {
                   6206: 	    &scan_data($scan_data,"$whichline.CODE_ignore_dup",'1');
                   6207: 	}
                   6208: 	&scan_data($scan_data,"$whichline.useCODE",'1');
                   6209: 	if ($args->{'CODE'} ne 'use_unfound') {
1.191     albertel 6210: 	    if (length($args->{'CODE'}) > $$scantron_config{'CODElength'}) {
                   6211: 		return ($line,1,'New CODE value too large');
                   6212: 	    }
                   6213: 	    if (length($args->{'CODE'}) < $$scantron_config{'CODElength'}) {
                   6214: 		$args->{'CODE'}=sprintf('%-'.$$scantron_config{'CODElength'}.'s',$args->{'CODE'});
                   6215: 	    }
                   6216: 	    substr($line,$$scantron_config{'CODEstart'}-1,
                   6217: 		   $$scantron_config{'CODElength'})=$args->{'CODE'};
1.186     albertel 6218: 	}
1.157     albertel 6219:     } elsif ($field eq 'answer') {
1.497     foxr     6220: 	my $length=$scantron_config->{'Qlength'};
1.157     albertel 6221: 	my $off=$scantron_config->{'Qoff'};
                   6222: 	my $on=$scantron_config->{'Qon'};
1.497     foxr     6223: 	my $answer=${off}x$length;
                   6224: 	if ($args->{'response'} eq 'none') {
                   6225: 	    &scan_data($scan_data,
1.503     raeburn  6226: 		       "$whichline.no_bubble.".$args->{'questionnum'},'1');
1.497     foxr     6227: 	} else {
                   6228: 	    if ($on eq 'letter') {
                   6229: 		my @alphabet=('A'..'Z');
                   6230: 		$answer=$alphabet[$args->{'response'}];
                   6231: 	    } elsif ($on eq 'number') {
                   6232: 		$answer=$args->{'response'}+1;
                   6233: 		if ($answer == 10) { $answer = '0'; }
1.274     albertel 6234: 	    } else {
1.497     foxr     6235: 		substr($answer,$args->{'response'},1)=$on;
1.274     albertel 6236: 	    }
1.497     foxr     6237: 	    &scan_data($scan_data,
1.503     raeburn  6238: 		       "$whichline.no_bubble.".$args->{'questionnum'},undef,'1');
1.157     albertel 6239: 	}
1.497     foxr     6240: 	my $where=$length*($args->{'question'}-1)+$scantron_config->{'Qstart'};
                   6241: 	substr($line,$where-1,$length)=$answer;
1.157     albertel 6242:     }
                   6243:     return $line;
                   6244: }
1.423     albertel 6245: 
                   6246: =pod
                   6247: 
                   6248: =item scan_data
                   6249: 
                   6250:     Edit or look up  an item in the scan_data hash.
                   6251: 
                   6252:   Arguments:
                   6253:     $scan_data  - The hash (see scantron_getfile)
                   6254:     $key        - shorthand of the key to edit (actual key is
1.424     albertel 6255:                   scantronfilename_key).
1.423     albertel 6256:     $data        - New value of the hash entry.
                   6257:     $delete      - If true, the entry is removed from the hash.
                   6258: 
                   6259:   Returns:
                   6260:     The new value of the hash table field (undefined if deleted).
                   6261: 
                   6262: =cut
                   6263: 
                   6264: 
1.157     albertel 6265: sub scan_data {
                   6266:     my ($scan_data,$key,$value,$delete)=@_;
1.257     albertel 6267:     my $filename=$env{'form.scantron_selectfile'};
1.157     albertel 6268:     if (defined($value)) {
                   6269: 	$scan_data->{$filename.'_'.$key} = $value;
                   6270:     }
                   6271:     if ($delete) { delete($scan_data->{$filename.'_'.$key}); }
                   6272:     return $scan_data->{$filename.'_'.$key};
                   6273: }
1.423     albertel 6274: 
1.495     albertel 6275: # ----- These first few routines are general use routines.----
                   6276: 
                   6277: # Return the number of occurences of a pattern in a string.
                   6278: 
                   6279: sub occurence_count {
                   6280:     my ($string, $pattern) = @_;
                   6281: 
                   6282:     my @matches = ($string =~ /$pattern/g);
                   6283: 
                   6284:     return scalar(@matches);
                   6285: }
                   6286: 
                   6287: 
                   6288: # Take a string known to have digits and convert all the
                   6289: # digits into letters in the range J,A..I.
                   6290: 
                   6291: sub digits_to_letters {
                   6292:     my ($input) = @_;
                   6293: 
                   6294:     my @alphabet = ('J', 'A'..'I');
                   6295: 
                   6296:     my @input    = split(//, $input);
                   6297:     my $output ='';
                   6298:     for (my $i = 0; $i < scalar(@input); $i++) {
                   6299: 	if ($input[$i] =~ /\d/) {
                   6300: 	    $output .= $alphabet[$input[$i]];
                   6301: 	} else {
                   6302: 	    $output .= $input[$i];
                   6303: 	}
                   6304:     }
                   6305:     return $output;
                   6306: }
                   6307: 
1.423     albertel 6308: =pod 
                   6309: 
                   6310: =item scantron_parse_scanline
                   6311: 
                   6312:   Decodes a scanline from the selected scantron file
                   6313: 
                   6314:  Arguments:
                   6315:     line             - The text of the scantron file line to process
                   6316:     whichline        - Line number
                   6317:     scantron_config  - Hash describing the format of the scantron lines.
                   6318:     scan_data        - Hash of extra information about the scanline
                   6319:                        (see scantron_getfile for more information)
                   6320:     just_header      - True if should not process question answers but only
                   6321:                        the stuff to the left of the answers.
1.596.2.12.2.  6(raebur 6322:3):     randomorder      - True if randomorder in use
                   6323:3):     randompick       - True if randompick in use
                   6324:3):     sequence         - Exam folder URL
                   6325:3):     master_seq       - Ref to array containing symbs in exam folder
                   6326:3):     symb_to_resource - Ref to hash of symbs for resources in exam folder
                   6327:3):                        (corresponding values are resource objects)
                   6328:3):     partids_by_symb  - Ref to hash of symb -> array ref of partIDs
                   6329:3):     orderedforcode   - Ref to hash of arrays. keys are CODEs and values
                   6330:3):                        are refs to an array of resource objects, ordered
                   6331:3):                        according to order used for CODE, when randomorder
                   6332:3):                        and or randompick are in use.
                   6333:3):     respnumlookup    - Ref to hash mapping question numbers in bubble lines
                   6334:3):                        for current line to question number used for same question
                   6335:3):                         in "Master Sequence" (as seen by Course Coordinator).
                   6336:3):     startline        - Ref to hash where key is question number (0 is first)
                   6337:3):                        and value is number of first bubble line for current 
                   6338:3):                        student or code-based randompick and/or randomorder.
                   6339:3):     totalref         - Ref of scalar used to score total number of bubble
                   6340:3):                        lines needed for responses in a scan line (used when
                   6341:3):                        randompick in use. 
                   6342:3): 
1.423     albertel 6343:  Returns:
                   6344:    Hash containing the result of parsing the scanline
                   6345: 
                   6346:    Keys are all proceeded by the string 'scantron.'
                   6347: 
                   6348:        CODE    - the CODE in use for this scanline
                   6349:        useCODE - 1 if the CODE is invalid but it usage has been forced
                   6350:                  by the operator
                   6351:        CODE_ignore_dup - 1 if the CODE is a duplicated use when unique
                   6352:                             CODEs were selected, but the usage has been
                   6353:                             forced by the operator
1.556     weissno  6354:        ID  - student/employee ID
1.423     albertel 6355:        PaperID - if used, the ID number printed on the sheet when the 
                   6356:                  paper was scanned
                   6357:        FirstName - first name from the sheet
                   6358:        LastName  - last name from the sheet
                   6359: 
                   6360:      if just_header was not true these key may also exist
                   6361: 
1.447     foxr     6362:        missingerror - a list of bubble ranges that are considered to be answers
                   6363:                       to a single question that don't have any bubbles filled in.
                   6364:                       Of the form questionnumber:firstbubblenumber:count.
                   6365:        doubleerror  - a list of bubble ranges that are considered to be answers
                   6366:                       to a single question that have more than one bubble filled in.
                   6367:                       Of the form questionnumber::firstbubblenumber:count
                   6368:    
                   6369:                 In the above, count is the number of bubble responses in the
                   6370:                 input line needed to represent the possible answers to the question.
                   6371:                 e.g. a radioresponse with 15 choices in an answer sheet with 10 choices
                   6372:                 per line would have count = 2.
                   6373: 
1.423     albertel 6374:        maxquest     - the number of the last bubble line that was parsed
                   6375: 
                   6376:        (<number> starts at 1)
                   6377:        <number>.answer - zero or more letters representing the selected
                   6378:                          letters from the scanline for the bubble line 
                   6379:                          <number>.
                   6380:                          if blank there was either no bubble or there where
                   6381:                          multiple bubbles, (consult the keys missingerror and
                   6382:                          doubleerror if this is an error condition)
                   6383: 
                   6384: =cut
                   6385: 
1.82      albertel 6386: sub scantron_parse_scanline {
1.596.2.12.2.  6(raebur 6387:3):     my ($line,$whichline,$scantron_config,$scan_data,$just_header,$idmap,
                   6388:3):         $randomorder,$randompick,$sequence,$master_seq,$symb_to_resource,
                   6389:3):         $partids_by_symb,$orderedforcode,$respnumlookup,$startline,$totalref)=@_;
1.470     foxr     6390: 
1.82      albertel 6391:     my %record;
1.596.2.12.2.  6(raebur 6392:3):     my $data=substr($line,0,$$scantron_config{'Qstart'}-1); # stuff before answers
1.278     albertel 6393:     if (!($$scantron_config{'CODElocation'} eq 0 ||
                   6394: 	  $$scantron_config{'CODElocation'} eq 'none')) {
                   6395: 	if ($$scantron_config{'CODElocation'} < 0 ||
                   6396: 	    $$scantron_config{'CODElocation'} eq 'letter' ||
                   6397: 	    $$scantron_config{'CODElocation'} eq 'number') {
1.191     albertel 6398: 	    $record{'scantron.CODE'}=substr($data,
                   6399: 					    $$scantron_config{'CODEstart'}-1,
1.83      albertel 6400: 					    $$scantron_config{'CODElength'});
1.191     albertel 6401: 	    if (&scan_data($scan_data,"$whichline.useCODE")) {
                   6402: 		$record{'scantron.useCODE'}=1;
                   6403: 	    }
1.192     albertel 6404: 	    if (&scan_data($scan_data,"$whichline.CODE_ignore_dup")) {
                   6405: 		$record{'scantron.CODE_ignore_dup'}=1;
                   6406: 	    }
1.82      albertel 6407: 	} else {
                   6408: 	    #FIXME interpret first N questions
                   6409: 	}
                   6410:     }
1.83      albertel 6411:     $record{'scantron.ID'}=substr($data,$$scantron_config{'IDstart'}-1,
                   6412: 				  $$scantron_config{'IDlength'});
1.157     albertel 6413:     $record{'scantron.PaperID'}=
                   6414: 	substr($data,$$scantron_config{'PaperID'}-1,
                   6415: 	       $$scantron_config{'PaperIDlength'});
                   6416:     $record{'scantron.FirstName'}=
                   6417: 	substr($data,$$scantron_config{'FirstName'}-1,
                   6418: 	       $$scantron_config{'FirstNamelength'});
                   6419:     $record{'scantron.LastName'}=
                   6420: 	substr($data,$$scantron_config{'LastName'}-1,
                   6421: 	       $$scantron_config{'LastNamelength'});
1.423     albertel 6422:     if ($just_header) { return \%record; }
1.194     albertel 6423: 
1.82      albertel 6424:     my @alphabet=('A'..'Z');
                   6425:     my $questnum=0;
1.447     foxr     6426:     my $ansnum  =1;		# Multiple 'answer lines'/question.
                   6427: 
1.596.2.12.2.  6(raebur 6428:3):     my $lastpos = $env{'form.scantron_maxbubble'}*$$scantron_config{'Qlength'};
                   6429:3):     if ($randompick || $randomorder) {
                   6430:3):         my $total = &get_respnum_lookups($sequence,$scan_data,$idmap,$line,\%record,
                   6431:3):                                          $master_seq,$symb_to_resource,
                   6432:3):                                          $partids_by_symb,$orderedforcode,
                   6433:3):                                          $respnumlookup,$startline);
                   6434:3):         if ($total) {
                   6435:3):             $lastpos = $total*$$scantron_config{'Qlength'};
                   6436:3):         }
                   6437:3):         if (ref($totalref)) {
                   6438:3):             $$totalref = $total;
                   6439:3):         }
                   6440:3):     }
                   6441:3):     my $questions=substr($line,$$scantron_config{'Qstart'}-1,$lastpos);  # Answers
1.470     foxr     6442:     chomp($questions);		# Get rid of any trailing \n.
                   6443:     $questions =~ s/\r$//;      # Get rid of trailing \r too (MAC or Win uploads).
                   6444:     while (length($questions)) {
1.596.2.12.2.  6(raebur 6445:3):         my $answers_needed;
                   6446:3):         if (($randompick || $randomorder) && (ref($respnumlookup) eq 'HASH')) {
                   6447:3):             $answers_needed = $bubble_lines_per_response{$respnumlookup->{$questnum}};
                   6448:3):         } else {
                   6449:3):             $answers_needed = $bubble_lines_per_response{$questnum};
                   6450:3):         }
1.503     raeburn  6451:         my $answer_length  = ($$scantron_config{'Qlength'} * $answers_needed)
                   6452:                              || 1;
                   6453:         $questnum++;
                   6454:         my $quest_id = $questnum;
                   6455:         my $currentquest = substr($questions,0,$answer_length);
                   6456:         $questions       = substr($questions,$answer_length);
                   6457:         if (length($currentquest) < $answer_length) { next; }
                   6458: 
1.596.2.12.2.  6(raebur 6459:3):         my $subdivided;
                   6460:3):         if (($randompick || $randomorder) && (ref($respnumlookup) eq 'HASH')) {
                   6461:3):             $subdivided = $subdivided_bubble_lines{$respnumlookup->{$questnum-1}};
                   6462:3):         } else {
                   6463:3):             $subdivided = $subdivided_bubble_lines{$questnum-1};
                   6464:3):         }
                   6465:3):         if ($subdivided =~ /,/) {
1.503     raeburn  6466:             my $subquestnum = 1;
                   6467:             my $subquestions = $currentquest;
1.596.2.12.2.  6(raebur 6468:3):             my @subanswers_needed = split(/,/,$subdivided);
1.503     raeburn  6469:             foreach my $subans (@subanswers_needed) {
                   6470:                 my $subans_length =
                   6471:                     ($$scantron_config{'Qlength'} * $subans)  || 1;
                   6472:                 my $currsubquest = substr($subquestions,0,$subans_length);
                   6473:                 $subquestions   = substr($subquestions,$subans_length);
                   6474:                 $quest_id = "$questnum.$subquestnum";
                   6475:                 if (($$scantron_config{'Qon'} eq 'letter') ||
                   6476:                     ($$scantron_config{'Qon'} eq 'number')) {
                   6477:                     $ansnum = &scantron_validator_lettnum($ansnum, 
                   6478:                         $questnum,$quest_id,$subans,$currsubquest,$whichline,
1.596.2.12.2.  6(raebur 6479:3):                         \@alphabet,\%record,$scantron_config,$scan_data,
                   6480:3):                         $randomorder,$randompick,$respnumlookup);
1.503     raeburn  6481:                 } else {
                   6482:                     $ansnum = &scantron_validator_positional($ansnum,
1.596.2.12.2.  6(raebur 6483:3):                         $questnum,$quest_id,$subans,$currsubquest,$whichline,
                   6484:3):                         \@alphabet,\%record,$scantron_config,$scan_data,
                   6485:3):                         $randomorder,$randompick,$respnumlookup);
1.503     raeburn  6486:                 }
                   6487:                 $subquestnum ++;
                   6488:             }
                   6489:         } else {
                   6490:             if (($$scantron_config{'Qon'} eq 'letter') ||
                   6491:                 ($$scantron_config{'Qon'} eq 'number')) {
                   6492:                 $ansnum = &scantron_validator_lettnum($ansnum,$questnum,
                   6493:                     $quest_id,$answers_needed,$currentquest,$whichline,
1.596.2.12.2.  6(raebur 6494:3):                     \@alphabet,\%record,$scantron_config,$scan_data,
                   6495:3):                     $randomorder,$randompick,$respnumlookup);
1.503     raeburn  6496:             } else {
                   6497:                 $ansnum = &scantron_validator_positional($ansnum,$questnum,
                   6498:                     $quest_id,$answers_needed,$currentquest,$whichline,
1.596.2.12.2.  6(raebur 6499:3):                     \@alphabet,\%record,$scantron_config,$scan_data,
                   6500:3):                     $randomorder,$randompick,$respnumlookup);
1.503     raeburn  6501:             }
                   6502:         }
                   6503:     }
                   6504:     $record{'scantron.maxquest'}=$questnum;
                   6505:     return \%record;
                   6506: }
1.447     foxr     6507: 
1.596.2.12.2.  6(raebur 6508:3): sub get_master_seq {
                   6509:3):     my ($resources,$master_seq,$symb_to_resource) = @_;
                   6510:3):     return unless ((ref($resources) eq 'ARRAY') && (ref($master_seq) eq 'ARRAY') &&
                   6511:3):                    (ref($symb_to_resource) eq 'HASH'));
                   6512:3):     my $resource_error;
                   6513:3):     foreach my $resource (@{$resources}) {
                   6514:3):         my $ressymb;
                   6515:3):         if (ref($resource)) {
                   6516:3):             $ressymb = $resource->symb();
                   6517:3):             push(@{$master_seq},$ressymb);
                   6518:3):             $symb_to_resource->{$ressymb} = $resource;
                   6519:3):         } else {
                   6520:3):             $resource_error = 1;
                   6521:3):             last;
                   6522:3):         }
                   6523:3):     }
                   6524:3):     return $resource_error;
                   6525:3): }
                   6526:3): 
                   6527:3): sub get_respnum_lookups {
                   6528:3):     my ($sequence,$scan_data,$idmap,$line,$record,$master_seq,$symb_to_resource,
                   6529:3):         $partids_by_symb,$orderedforcode,$respnumlookup,$startline) = @_;
                   6530:3):     return unless ((ref($record) eq 'HASH') && (ref($master_seq) eq 'ARRAY') &&
                   6531:3):                    (ref($symb_to_resource) eq 'HASH') && (ref($partids_by_symb) eq 'HASH') &&
                   6532:3):                    (ref($orderedforcode) eq 'HASH') && (ref($respnumlookup) eq 'HASH') &&
                   6533:3):                    (ref($startline) eq 'HASH'));
                   6534:3):     my ($user,$scancode);
                   6535:3):     if ((exists($record->{'scantron.CODE'})) &&
                   6536:3):         (&Apache::lonnet::validCODE($record->{'scantron.CODE'}))) {
                   6537:3):         $scancode = $record->{'scantron.CODE'};
                   6538:3):     } else {
                   6539:3):         $user = &scantron_find_student($record,$scan_data,$idmap,$line);
                   6540:3):     }
                   6541:3):     my @mapresources =
                   6542:3):         &users_order($user,$scancode,$sequence,$master_seq,$symb_to_resource,
                   6543:3):                      $orderedforcode);
                   6544:3):     my $total = 0;
                   6545:3):     my $count = 0;
                   6546:3):     foreach my $resource (@mapresources) {
                   6547:3):         my $id = $resource->id();
                   6548:3):         my $symb = $resource->symb();
                   6549:3):         if (ref($partids_by_symb->{$symb}) eq 'ARRAY') {
                   6550:3):             foreach my $partid (@{$partids_by_symb->{$symb}}) {
                   6551:3):                 my $respnum = $masterseq_id_responsenum{$id.'_'.$partid};
                   6552:3):                 if ($respnum ne '') {
                   6553:3):                     $respnumlookup->{$count} = $respnum;
                   6554:3):                     $startline->{$count} = $total;
                   6555:3):                     $total += $bubble_lines_per_response{$respnum};
                   6556:3):                     $count ++;
                   6557:3):                 }
                   6558:3):             }
                   6559:3):         }
                   6560:3):     }
                   6561:3):     return $total;
                   6562:3): }
                   6563:3): 
1.503     raeburn  6564: sub scantron_validator_lettnum {
                   6565:     my ($ansnum,$questnum,$quest_id,$answers_needed,$currquest,$whichline,
1.596.2.12.2.  6(raebur 6566:3):         $alphabet,$record,$scantron_config,$scan_data,$randomorder,
                   6567:3):         $randompick,$respnumlookup) = @_;
1.503     raeburn  6568: 
                   6569:     # Qon 'letter' implies for each slot in currquest we have:
                   6570:     #    ? or * for doubles, a letter in A-Z for a bubble, and
                   6571:     #    about anything else (esp. a value of Qoff) for missing
                   6572:     #    bubbles.
                   6573:     #
                   6574:     # Qon 'number' implies each slot gives a digit that indexes the
                   6575:     #    bubbles filled, or Qoff, or a non-number for unbubbled lines,
                   6576:     #    and * or ? for double bubbles on a single line.
                   6577:     #
1.447     foxr     6578: 
1.503     raeburn  6579:     my $matchon;
                   6580:     if ($$scantron_config{'Qon'} eq 'letter') {
                   6581:         $matchon = '[A-Z]';
                   6582:     } elsif ($$scantron_config{'Qon'} eq 'number') {
                   6583:         $matchon = '\d';
                   6584:     }
                   6585:     my $occurrences = 0;
1.596.2.12.2.  6(raebur 6586:3):     my $responsenum = $questnum-1;
                   6587:3):     if (($randompick || $randomorder) && (ref($respnumlookup) eq 'HASH')) {
                   6588:3):        $responsenum = $respnumlookup->{$questnum-1}
                   6589:3):     }
                   6590:3):     if (($responsetype_per_response{$responsenum} eq 'essayresponse') ||
                   6591:3):         ($responsetype_per_response{$responsenum} eq 'formularesponse') ||
                   6592:3):         ($responsetype_per_response{$responsenum} eq 'stringresponse') ||
                   6593:3):         ($responsetype_per_response{$responsenum} eq 'imageresponse') ||
                   6594:3):         ($responsetype_per_response{$responsenum} eq 'reactionresponse') ||
                   6595:3):         ($responsetype_per_response{$responsenum} eq 'organicresponse')) {
1.503     raeburn  6596:         my @singlelines = split('',$currquest);
                   6597:         foreach my $entry (@singlelines) {
                   6598:             $occurrences = &occurence_count($entry,$matchon);
                   6599:             if ($occurrences > 1) {
                   6600:                 last;
                   6601:             }
1.596.2.12.2.  6(raebur 6602:3):         }
1.503     raeburn  6603:     } else {
                   6604:         $occurrences = &occurence_count($currquest,$matchon); 
                   6605:     }
                   6606:     if (($currquest =~ /\?/ || $currquest =~ /\*/) || ($occurrences > 1)) {
                   6607:         push(@{$record->{'scantron.doubleerror'}},$quest_id);
                   6608:         for (my $ans=0; $ans<$answers_needed; $ans++) {
                   6609:             my $bubble = substr($currquest,$ans,1);
                   6610:             if ($bubble =~ /$matchon/ ) {
                   6611:                 if ($$scantron_config{'Qon'} eq 'number') {
                   6612:                     if ($bubble == 0) {
                   6613:                         $bubble = 10; 
                   6614:                     }
                   6615:                     $record->{"scantron.$ansnum.answer"} = 
                   6616:                         $alphabet->[$bubble-1];
                   6617:                 } else {
                   6618:                     $record->{"scantron.$ansnum.answer"} = $bubble;
                   6619:                 }
                   6620:             } else {
                   6621:                 $record->{"scantron.$ansnum.answer"}='';
                   6622:             }
                   6623:             $ansnum++;
                   6624:         }
                   6625:     } elsif (!defined($currquest)
                   6626:             || (&occurence_count($currquest, $$scantron_config{'Qoff'}) == length($currquest))
                   6627:             || (&occurence_count($currquest,$matchon) == 0)) {
                   6628:         for (my $ans=0; $ans<$answers_needed; $ans++ ) {
                   6629:             $record->{"scantron.$ansnum.answer"}='';
                   6630:             $ansnum++;
                   6631:         }
                   6632:         if (!&scan_data($scan_data,"$whichline.no_bubble.$quest_id")) {
                   6633:             push(@{$record->{'scantron.missingerror'}},$quest_id);
                   6634:         }
                   6635:     } else {
                   6636:         if ($$scantron_config{'Qon'} eq 'number') {
                   6637:             $currquest = &digits_to_letters($currquest);            
                   6638:         }
                   6639:         for (my $ans=0; $ans<$answers_needed; $ans++) {
                   6640:             my $bubble = substr($currquest,$ans,1);
                   6641:             $record->{"scantron.$ansnum.answer"} = $bubble;
                   6642:             $ansnum++;
                   6643:         }
                   6644:     }
                   6645:     return $ansnum;
                   6646: }
1.447     foxr     6647: 
1.503     raeburn  6648: sub scantron_validator_positional {
                   6649:     my ($ansnum,$questnum,$quest_id,$answers_needed,$currquest,
1.596.2.12.2.  6(raebur 6650:3):         $whichline,$alphabet,$record,$scantron_config,$scan_data,
                   6651:3):         $randomorder,$randompick,$respnumlookup) = @_;
1.447     foxr     6652: 
1.503     raeburn  6653:     # Otherwise there's a positional notation;
                   6654:     # each bubble line requires Qlength items, and there are filled in
                   6655:     # bubbles for each case where there 'Qon' characters.
                   6656:     #
1.447     foxr     6657: 
1.503     raeburn  6658:     my @array=split($$scantron_config{'Qon'},$currquest,-1);
1.447     foxr     6659: 
1.503     raeburn  6660:     # If the split only gives us one element.. the full length of the
                   6661:     # answer string, no bubbles are filled in:
1.447     foxr     6662: 
1.507     raeburn  6663:     if ($answers_needed eq '') {
                   6664:         return;
                   6665:     }
                   6666: 
1.503     raeburn  6667:     if (length($array[0]) eq $$scantron_config{'Qlength'}*$answers_needed) {
                   6668:         for (my $ans=0; $ans<$answers_needed; $ans++ ) {
                   6669:             $record->{"scantron.$ansnum.answer"}='';
                   6670:             $ansnum++;
                   6671:         }
                   6672:         if (!&scan_data($scan_data,"$whichline.no_bubble.$quest_id")) {
                   6673:             push(@{$record->{"scantron.missingerror"}},$quest_id);
                   6674:         }
                   6675:     } elsif (scalar(@array) == 2) {
                   6676:         my $location = length($array[0]);
                   6677:         my $line_num = int($location / $$scantron_config{'Qlength'});
                   6678:         my $bubble   = $alphabet->[$location % $$scantron_config{'Qlength'}];
                   6679:         for (my $ans=0; $ans<$answers_needed; $ans++) {
                   6680:             if ($ans eq $line_num) {
                   6681:                 $record->{"scantron.$ansnum.answer"} = $bubble;
                   6682:             } else {
                   6683:                 $record->{"scantron.$ansnum.answer"} = ' ';
                   6684:             }
                   6685:             $ansnum++;
                   6686:          }
                   6687:     } else {
                   6688:         #  If there's more than one instance of a bubble character
                   6689:         #  That's a double bubble; with positional notation we can
                   6690:         #  record all the bubbles filled in as well as the
                   6691:         #  fact this response consists of multiple bubbles.
                   6692:         #
1.596.2.12.2.  6(raebur 6693:3):         my $responsenum = $questnum-1;
                   6694:3):         if (($randompick || $randomorder) && (ref($respnumlookup) eq 'HASH')) {
                   6695:3):             $responsenum = $respnumlookup->{$questnum-1}
                   6696:3):         }
                   6697:3):         if (($responsetype_per_response{$responsenum} eq 'essayresponse') ||
                   6698:3):             ($responsetype_per_response{$responsenum} eq 'formularesponse') ||
                   6699:3):             ($responsetype_per_response{$responsenum} eq 'stringresponse') ||
                   6700:3):             ($responsetype_per_response{$responsenum} eq 'imageresponse') ||
                   6701:3):             ($responsetype_per_response{$responsenum} eq 'reactionresponse') ||
                   6702:3):             ($responsetype_per_response{$responsenum} eq 'organicresponse')) {
1.503     raeburn  6703:             my $doubleerror = 0;
                   6704:             while (($currquest >= $$scantron_config{'Qlength'}) && 
                   6705:                    (!$doubleerror)) {
                   6706:                my $currline = substr($currquest,0,$$scantron_config{'Qlength'});
                   6707:                $currquest = substr($currquest,$$scantron_config{'Qlength'});
                   6708:                my @currarray = split($$scantron_config{'Qon'},$currline,-1);
                   6709:                if (length(@currarray) > 2) {
                   6710:                    $doubleerror = 1;
                   6711:                } 
                   6712:             }
                   6713:             if ($doubleerror) {
                   6714:                 push(@{$record->{'scantron.doubleerror'}},$quest_id);
                   6715:             }
                   6716:         } else {
                   6717:             push(@{$record->{'scantron.doubleerror'}},$quest_id);
                   6718:         }
                   6719:         my $item = $ansnum;
                   6720:         for (my $ans=0; $ans<$answers_needed; $ans++) {
                   6721:             $record->{"scantron.$item.answer"} = '';
                   6722:             $item ++;
                   6723:         }
1.447     foxr     6724: 
1.503     raeburn  6725:         my @ans=@array;
                   6726:         my $i=0;
                   6727:         my $increment = 0;
                   6728:         while ($#ans) {
                   6729:             $i+=length($ans[0]) + $increment;
                   6730:             my $line   = int($i/$$scantron_config{'Qlength'} + $ansnum);
                   6731:             my $bubble = $i%$$scantron_config{'Qlength'};
                   6732:             $record->{"scantron.$line.answer"}.=$alphabet->[$bubble];
                   6733:             shift(@ans);
                   6734:             $increment = 1;
                   6735:         }
                   6736:         $ansnum += $answers_needed;
1.82      albertel 6737:     }
1.503     raeburn  6738:     return $ansnum;
1.82      albertel 6739: }
                   6740: 
1.423     albertel 6741: =pod
                   6742: 
                   6743: =item scantron_add_delay
                   6744: 
                   6745:    Adds an error message that occurred during the grading phase to a
                   6746:    queue of messages to be shown after grading pass is complete
                   6747: 
                   6748:  Arguments:
1.424     albertel 6749:    $delayqueue  - arrary ref of hash ref of error messages
1.423     albertel 6750:    $scanline    - the scanline that caused the error
                   6751:    $errormesage - the error message
                   6752:    $errorcode   - a numeric code for the error
                   6753: 
                   6754:  Side Effects:
1.424     albertel 6755:    updates the $delayqueue to have a new hash ref of the error
1.423     albertel 6756: 
                   6757: =cut
                   6758: 
1.82      albertel 6759: sub scantron_add_delay {
1.140     albertel 6760:     my ($delayqueue,$scanline,$errormessage,$errorcode)=@_;
                   6761:     push(@$delayqueue,
                   6762: 	 {'line' => $scanline, 'emsg' => $errormessage,
                   6763: 	  'ecode' => $errorcode }
                   6764: 	 );
1.82      albertel 6765: }
                   6766: 
1.423     albertel 6767: =pod
                   6768: 
                   6769: =item scantron_find_student
                   6770: 
1.424     albertel 6771:    Finds the username for the current scanline
                   6772: 
                   6773:   Arguments:
                   6774:    $scantron_record - hash result from scantron_parse_scanline
                   6775:    $scan_data       - hash of correction information 
                   6776:                       (see &scantron_getfile() form more information)
                   6777:    $idmap           - hash from &username_to_idmap()
                   6778:    $line            - number of current scanline
                   6779:  
                   6780:   Returns:
                   6781:    Either 'username:domain' or undef if unknown
                   6782: 
1.423     albertel 6783: =cut
                   6784: 
1.82      albertel 6785: sub scantron_find_student {
1.157     albertel 6786:     my ($scantron_record,$scan_data,$idmap,$line)=@_;
1.83      albertel 6787:     my $scanID=$$scantron_record{'scantron.ID'};
1.157     albertel 6788:     if ($scanID =~ /^\s*$/) {
                   6789:  	return &scan_data($scan_data,"$line.user");
                   6790:     }
1.83      albertel 6791:     foreach my $id (keys(%$idmap)) {
1.157     albertel 6792:  	if (lc($id) eq lc($scanID)) {
                   6793:  	    return $$idmap{$id};
                   6794:  	}
1.83      albertel 6795:     }
                   6796:     return undef;
                   6797: }
                   6798: 
1.423     albertel 6799: =pod
                   6800: 
                   6801: =item scantron_filter
                   6802: 
1.424     albertel 6803:    Filter sub for lonnavmaps, filters out hidden resources if ignore
                   6804:    hidden resources was selected
                   6805: 
1.423     albertel 6806: =cut
                   6807: 
1.83      albertel 6808: sub scantron_filter {
                   6809:     my ($curres)=@_;
1.331     albertel 6810: 
                   6811:     if (ref($curres) && $curres->is_problem()) {
                   6812: 	# if the user has asked to not have either hidden
                   6813: 	# or 'randomout' controlled resources to be graded
                   6814: 	# don't include them
                   6815: 	if ($env{'form.scantron_options_hidden'} eq 'ignore_hidden'
                   6816: 	    && $curres->randomout) {
                   6817: 	    return 0;
                   6818: 	}
1.83      albertel 6819: 	return 1;
                   6820:     }
                   6821:     return 0;
1.82      albertel 6822: }
                   6823: 
1.423     albertel 6824: =pod
                   6825: 
                   6826: =item scantron_process_corrections
                   6827: 
1.424     albertel 6828:    Gets correction information out of submitted form data and corrects
                   6829:    the scanline
                   6830: 
1.423     albertel 6831: =cut
                   6832: 
1.157     albertel 6833: sub scantron_process_corrections {
                   6834:     my ($r) = @_;
1.257     albertel 6835:     my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
1.157     albertel 6836:     my ($scanlines,$scan_data)=&scantron_getfile();
                   6837:     my $classlist=&Apache::loncoursedata::get_classlist();
1.257     albertel 6838:     my $which=$env{'form.scantron_line'};
1.200     albertel 6839:     my $line=&scantron_get_line($scanlines,$scan_data,$which);
1.157     albertel 6840:     my ($skip,$err,$errmsg);
1.257     albertel 6841:     if ($env{'form.scantron_skip_record'}) {
1.157     albertel 6842: 	$skip=1;
1.257     albertel 6843:     } elsif ($env{'form.scantron_corrections'} =~ /^(duplicate|incorrect)ID$/) {
                   6844: 	my $newstudent=$env{'form.scantron_username'}.':'.
                   6845: 	    $env{'form.scantron_domain'};
1.157     albertel 6846: 	my $newid=$classlist->{$newstudent}->[&Apache::loncoursedata::CL_ID];
                   6847: 	($line,$err,$errmsg)=
                   6848: 	    &scantron_fixup_scanline(\%scantron_config,$scan_data,$line,$which,
                   6849: 				     'ID',{'newid'=>$newid,
1.257     albertel 6850: 				    'username'=>$env{'form.scantron_username'},
                   6851: 				    'domain'=>$env{'form.scantron_domain'}});
                   6852:     } elsif ($env{'form.scantron_corrections'} =~ /^(duplicate|incorrect)CODE$/) {
                   6853: 	my $resolution=$env{'form.scantron_CODE_resolution'};
1.190     albertel 6854: 	my $newCODE;
1.192     albertel 6855: 	my %args;
1.190     albertel 6856: 	if      ($resolution eq 'use_unfound') {
1.191     albertel 6857: 	    $newCODE='use_unfound';
1.190     albertel 6858: 	} elsif ($resolution eq 'use_found') {
1.257     albertel 6859: 	    $newCODE=$env{'form.scantron_CODE_selectedvalue'};
1.190     albertel 6860: 	} elsif ($resolution eq 'use_typed') {
1.257     albertel 6861: 	    $newCODE=$env{'form.scantron_CODE_newvalue'};
1.194     albertel 6862: 	} elsif ($resolution =~ /^use_closest_(\d+)/) {
1.257     albertel 6863: 	    $newCODE=$env{"form.scantron_CODE_closest_$1"};
1.190     albertel 6864: 	}
1.257     albertel 6865: 	if ($env{'form.scantron_corrections'} eq 'duplicateCODE') {
1.192     albertel 6866: 	    $args{'CODE_ignore_dup'}=1;
                   6867: 	}
                   6868: 	$args{'CODE'}=$newCODE;
1.186     albertel 6869: 	($line,$err,$errmsg)=
                   6870: 	    &scantron_fixup_scanline(\%scantron_config,$scan_data,$line,$which,
1.192     albertel 6871: 				     'CODE',\%args);
1.257     albertel 6872:     } elsif ($env{'form.scantron_corrections'} =~ /^(missing|double)bubble$/) {
                   6873: 	foreach my $question (split(',',$env{'form.scantron_questions'})) {
1.157     albertel 6874: 	    ($line,$err,$errmsg)=
                   6875: 		&scantron_fixup_scanline(\%scantron_config,$scan_data,$line,
                   6876: 					 $which,'answer',
                   6877: 					 { 'question'=>$question,
1.503     raeburn  6878: 		      		   'response'=>$env{"form.scantron_correct_Q_$question"},
                   6879:                                    'questionnum'=>$env{"form.scantron_questionnum_Q_$question"}});
1.157     albertel 6880: 	    if ($err) { last; }
                   6881: 	}
                   6882:     }
                   6883:     if ($err) {
1.596.2.12.2.  0(raebur 6884:3): 	$r->print(
                   6885:3):             '<p class="LC_error">'
                   6886:3):            .&mt('Unable to accept last correction, an error occurred: [_1]',
                   6887:3):                 $errmsg)
          1(raebur 6888:3):            .'</p>');
1.157     albertel 6889:     } else {
1.200     albertel 6890: 	&scantron_put_line($scanlines,$scan_data,$which,$line,$skip);
1.157     albertel 6891: 	&scantron_putfile($scanlines,$scan_data);
                   6892:     }
                   6893: }
                   6894: 
1.423     albertel 6895: =pod
                   6896: 
                   6897: =item reset_skipping_status
                   6898: 
1.424     albertel 6899:    Forgets the current set of remember skipped scanlines (and thus
                   6900:    reverts back to considering all lines in the
                   6901:    scantron_skipped_<filename> file)
                   6902: 
1.423     albertel 6903: =cut
                   6904: 
1.200     albertel 6905: sub reset_skipping_status {
                   6906:     my ($scanlines,$scan_data)=&scantron_getfile();
                   6907:     &scan_data($scan_data,'remember_skipping',undef,1);
                   6908:     &scantron_putfile(undef,$scan_data);
                   6909: }
                   6910: 
1.423     albertel 6911: =pod
                   6912: 
                   6913: =item start_skipping
                   6914: 
1.424     albertel 6915:    Marks a scanline to be skipped. 
                   6916: 
1.423     albertel 6917: =cut
                   6918: 
1.376     albertel 6919: sub start_skipping {
1.200     albertel 6920:     my ($scan_data,$i)=@_;
                   6921:     my %remembered=split(':',&scan_data($scan_data,'remember_skipping'));
1.376     albertel 6922:     if ($env{'form.scantron_options_redo'} =~ /^redo_/) {
                   6923: 	$remembered{$i}=2;
                   6924:     } else {
                   6925: 	$remembered{$i}=1;
                   6926:     }
1.200     albertel 6927:     &scan_data($scan_data,'remember_skipping',join(':',%remembered));
                   6928: }
                   6929: 
1.423     albertel 6930: =pod
                   6931: 
                   6932: =item should_be_skipped
                   6933: 
1.424     albertel 6934:    Checks whether a scanline should be skipped.
                   6935: 
1.423     albertel 6936: =cut
                   6937: 
1.200     albertel 6938: sub should_be_skipped {
1.376     albertel 6939:     my ($scanlines,$scan_data,$i)=@_;
1.257     albertel 6940:     if ($env{'form.scantron_options_redo'} !~ /^redo_/) {
1.200     albertel 6941: 	# not redoing old skips
1.376     albertel 6942: 	if ($scanlines->{'skipped'}[$i]) { return 1; }
1.200     albertel 6943: 	return 0;
                   6944:     }
                   6945:     my %remembered=split(':',&scan_data($scan_data,'remember_skipping'));
1.376     albertel 6946: 
                   6947:     if (exists($remembered{$i}) && $remembered{$i} != 2 ) {
                   6948: 	return 0;
                   6949:     }
1.200     albertel 6950:     return 1;
                   6951: }
                   6952: 
1.423     albertel 6953: =pod
                   6954: 
                   6955: =item remember_current_skipped
                   6956: 
1.424     albertel 6957:    Discovers what scanlines are in the scantron_skipped_<filename>
                   6958:    file and remembers them into scan_data for later use.
                   6959: 
1.423     albertel 6960: =cut
                   6961: 
1.200     albertel 6962: sub remember_current_skipped {
                   6963:     my ($scanlines,$scan_data)=&scantron_getfile();
                   6964:     my %to_remember;
                   6965:     for (my $i=0;$i<=$scanlines->{'count'};$i++) {
                   6966: 	if ($scanlines->{'skipped'}[$i]) {
                   6967: 	    $to_remember{$i}=1;
                   6968: 	}
                   6969:     }
1.376     albertel 6970: 
1.200     albertel 6971:     &scan_data($scan_data,'remember_skipping',join(':',%to_remember));
                   6972:     &scantron_putfile(undef,$scan_data);
                   6973: }
                   6974: 
1.423     albertel 6975: =pod
                   6976: 
                   6977: =item check_for_error
                   6978: 
1.424     albertel 6979:     Checks if there was an error when attempting to remove a specific
1.596.2.6  raeburn  6980:     scantron_.. bubblesheet data file. Prints out an error if
1.424     albertel 6981:     something went wrong.
                   6982: 
1.423     albertel 6983: =cut
                   6984: 
1.200     albertel 6985: sub check_for_error {
                   6986:     my ($r,$result)=@_;
                   6987:     if ($result ne 'ok' && $result ne 'not_found' ) {
1.492     albertel 6988: 	$r->print(&mt("An error occurred ([_1]) when trying to remove the existing corrections.",$result));
1.200     albertel 6989:     }
                   6990: }
1.157     albertel 6991: 
1.423     albertel 6992: =pod
                   6993: 
                   6994: =item scantron_warning_screen
                   6995: 
1.424     albertel 6996:    Interstitial screen to make sure the operator has selected the
                   6997:    correct options before we start the validation phase.
                   6998: 
1.423     albertel 6999: =cut
                   7000: 
1.203     albertel 7001: sub scantron_warning_screen {
                   7002:     my ($button_text)=@_;
1.257     albertel 7003:     my $title=&Apache::lonnet::gettitle($env{'form.selectpage'});
1.284     albertel 7004:     my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
1.373     albertel 7005:     my $CODElist;
1.284     albertel 7006:     if ($scantron_config{'CODElocation'} &&
                   7007: 	$scantron_config{'CODEstart'} &&
                   7008: 	$scantron_config{'CODElength'}) {
                   7009: 	$CODElist=$env{'form.scantron_CODElist'};
1.596.2.12.2.  8(raebur 7010:4): 	if ($env{'form.scantron_CODElist'} eq '') { $CODElist='<span class="LC_warning">'.&mt('None').'</span>'; }
1.284     albertel 7011: 	$CODElist=
1.492     albertel 7012: 	    '<tr><td><b>'.&mt('List of CODES to validate against:').'</b></td><td><tt>'.
1.373     albertel 7013: 	    $env{'form.scantron_CODElist'}.'</tt></td></tr>';
1.284     albertel 7014:     }
1.596.2.12.2.  (raeburn 7015:):     my $lastbubblepoints;
                   7016:):     if ($env{'form.scantron_lastbubblepoints'} ne '') {
                   7017:):         $lastbubblepoints =
                   7018:):             '<tr><td><b>'.&mt('Hand-graded items: points from last bubble in row').'</b></td><td><tt>'.
                   7019:):             $env{'form.scantron_lastbubblepoints'}.'</tt></td></tr>';
                   7020:):     }
1.492     albertel 7021:     return ('
1.203     albertel 7022: <p>
1.492     albertel 7023: <span class="LC_warning">
1.596.2.12.2.  6(raebur 7024:3): '.&mt("Please double check the information below before clicking on '[_1]'",&mt($button_text)).'</span>
1.203     albertel 7025: </p>
                   7026: <table>
1.492     albertel 7027: <tr><td><b>'.&mt('Sequence to be Graded:').'</b></td><td>'.$title.'</td></tr>
                   7028: <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 7029:): '.$CODElist.$lastbubblepoints.'
1.203     albertel 7030: </table>
                   7031: <br />
1.596.2.12.2.  2(raebur 7032:2): <p> '.&mt("If this information is correct, please click on '[_1]'.",&mt($button_text)).'</p>
                   7033:2): <p> '.&mt("If something is incorrect, please click the 'Grading Menu' button to start over.").'</p>
1.203     albertel 7034: 
                   7035: <br />
1.492     albertel 7036: ');
1.203     albertel 7037: }
                   7038: 
1.423     albertel 7039: =pod
                   7040: 
                   7041: =item scantron_do_warning
                   7042: 
1.424     albertel 7043:    Check if the operator has picked something for all required
                   7044:    fields. Error out if something is missing.
                   7045: 
1.423     albertel 7046: =cut
                   7047: 
1.203     albertel 7048: sub scantron_do_warning {
                   7049:     my ($r)=@_;
1.324     albertel 7050:     my ($symb)=&get_symb($r);
1.203     albertel 7051:     if (!$symb) {return '';}
1.324     albertel 7052:     my $default_form_data=&defaultFormData($symb);
1.203     albertel 7053:     $r->print(&scantron_form_start().$default_form_data);
1.257     albertel 7054:     if ( $env{'form.selectpage'} eq '' ||
                   7055: 	 $env{'form.scantron_selectfile'} eq '' ||
                   7056: 	 $env{'form.scantron_format'} eq '' ) {
1.596.2.4  raeburn  7057: 	$r->print("<p>".&mt('You have forgotten to specify some information. Please go Back and try again.')."</p>");
1.257     albertel 7058: 	if ( $env{'form.selectpage'} eq '') {
1.492     albertel 7059: 	    $r->print('<p><span class="LC_error">'.&mt('You have not selected a Sequence to grade').'</span></p>');
1.237     albertel 7060: 	} 
1.257     albertel 7061: 	if ( $env{'form.scantron_selectfile'} eq '') {
1.596.2.4  raeburn  7062: 	    $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 7063: 	} 
1.257     albertel 7064: 	if ( $env{'form.scantron_format'} eq '') {
1.596.2.5  raeburn  7065: 	    $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 7066: 	} 
                   7067:     } else {
1.265     www      7068: 	my $warning=&scantron_warning_screen('Grading: Validate Records');
1.596.2.12.2.  (raeburn 7069:):         my $bubbledbyhand=&hand_bubble_option();
1.492     albertel 7070: 	$r->print('
1.596.2.12.2.  (raeburn 7071:): '.$warning.$bubbledbyhand.'
1.492     albertel 7072: <input type="submit" name="submit" value="'.&mt('Grading: Validate Records').'" />
1.203     albertel 7073: <input type="hidden" name="command" value="scantron_validate" />
1.492     albertel 7074: ');
1.237     albertel 7075:     }
1.352     albertel 7076:     $r->print("</form><br />".&show_grading_menu_form($symb));
1.203     albertel 7077:     return '';
                   7078: }
                   7079: 
1.423     albertel 7080: =pod
                   7081: 
                   7082: =item scantron_form_start
                   7083: 
1.424     albertel 7084:     html hidden input for remembering all selected grading options
                   7085: 
1.423     albertel 7086: =cut
                   7087: 
1.203     albertel 7088: sub scantron_form_start {
                   7089:     my ($max_bubble)=@_;
                   7090:     my $result= <<SCANTRONFORM;
                   7091: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="scantronupload">
1.257     albertel 7092:   <input type="hidden" name="selectpage" value="$env{'form.selectpage'}" />
                   7093:   <input type="hidden" name="scantron_format" value="$env{'form.scantron_format'}" />
                   7094:   <input type="hidden" name="scantron_selectfile" value="$env{'form.scantron_selectfile'}" />
1.218     albertel 7095:   <input type="hidden" name="scantron_maxbubble" value="$max_bubble" />
1.257     albertel 7096:   <input type="hidden" name="scantron_CODElist" value="$env{'form.scantron_CODElist'}" />
                   7097:   <input type="hidden" name="scantron_CODEunique" value="$env{'form.scantron_CODEunique'}" />
                   7098:   <input type="hidden" name="scantron_options_redo" value="$env{'form.scantron_options_redo'}" />
                   7099:   <input type="hidden" name="scantron_options_ignore" value="$env{'form.scantron_options_ignore'}" />
1.331     albertel 7100:   <input type="hidden" name="scantron_options_hidden" value="$env{'form.scantron_options_hidden'}" />
1.203     albertel 7101: SCANTRONFORM
1.447     foxr     7102: 
                   7103:   my $line = 0;
                   7104:     while (defined($env{"form.scantron.bubblelines.$line"})) {
                   7105:        my $chunk =
                   7106: 	   '<input type="hidden" name="scantron.bubblelines.'.$line.'" value="'.$env{"form.scantron.bubblelines.$line"}.'" />'."\n";
1.448     foxr     7107:        $chunk .=
                   7108: 	   '<input type="hidden" name="scantron.first_bubble_line.'.$line.'" value="'.$env{"form.scantron.first_bubble_line.$line"}.'" />'."\n";
1.503     raeburn  7109:        $chunk .= 
                   7110:            '<input type="hidden" name="scantron.sub_bubblelines.'.$line.'" value="'.$env{"form.scantron.sub_bubblelines.$line"}.'" />'."\n";
1.504     raeburn  7111:        $chunk .=
                   7112:            '<input type="hidden" name="scantron.responsetype.'.$line.'" value="'.$env{"form.scantron.responsetype.$line"}.'" />'."\n";
1.596.2.12.2.  6(raebur 7113:3):        $chunk .=
                   7114:3):            '<input type="hidden" name="scantron.residpart.'.$line.'" value="'.$env{"form.scantron.residpart.$line"}.'" />'."\n";
1.447     foxr     7115:        $result .= $chunk;
                   7116:        $line++;
1.596.2.12.2.  6(raebur 7117:3):     }
1.203     albertel 7118:     return $result;
                   7119: }
                   7120: 
1.423     albertel 7121: =pod
                   7122: 
                   7123: =item scantron_validate_file
                   7124: 
1.596.2.6  raeburn  7125:     Dispatch routine for doing validation of a bubblesheet data file.
1.424     albertel 7126: 
                   7127:     Also processes any necessary information resets that need to
                   7128:     occur before validation begins (ignore previous corrections,
                   7129:     restarting the skipped records processing)
                   7130: 
1.423     albertel 7131: =cut
                   7132: 
1.157     albertel 7133: sub scantron_validate_file {
                   7134:     my ($r) = @_;
1.324     albertel 7135:     my ($symb)=&get_symb($r);
1.157     albertel 7136:     if (!$symb) {return '';}
1.324     albertel 7137:     my $default_form_data=&defaultFormData($symb);
1.200     albertel 7138:     
1.596.2.12.2.  0(raebur 7139:3):     # do the detection of only doing skipped records first before we delete
1.424     albertel 7140:     # them when doing the corrections reset
1.257     albertel 7141:     if ($env{'form.scantron_options_redo'} ne 'redo_skipped_ready') {
1.200     albertel 7142: 	&reset_skipping_status();
                   7143:     }
1.257     albertel 7144:     if ($env{'form.scantron_options_redo'} eq 'redo_skipped') {
1.200     albertel 7145: 	&remember_current_skipped();
1.257     albertel 7146: 	$env{'form.scantron_options_redo'}='redo_skipped_ready';
1.200     albertel 7147:     }
                   7148: 
1.257     albertel 7149:     if ($env{'form.scantron_options_ignore'} eq 'ignore_corrections') {
1.200     albertel 7150: 	&check_for_error($r,&scantron_remove_file('corrected'));
                   7151: 	&check_for_error($r,&scantron_remove_file('skipped'));
                   7152: 	&check_for_error($r,&scantron_remove_scan_data());
1.257     albertel 7153: 	$env{'form.scantron_options_ignore'}='done';
1.192     albertel 7154:     }
1.200     albertel 7155: 
1.257     albertel 7156:     if ($env{'form.scantron_corrections'}) {
1.157     albertel 7157: 	&scantron_process_corrections($r);
                   7158:     }
1.503     raeburn  7159:     $r->print('<p>'.&mt('Gathering necessary information.').'</p>');$r->rflush();
1.157     albertel 7160:     #get the student pick code ready
                   7161:     $r->print(&Apache::loncommon::studentbrowser_javascript());
1.582     raeburn  7162:     my $nav_error;
1.596.2.12.2.  (raeburn 7163:):     my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
                   7164:):     my $max_bubble=&scantron_get_maxbubble(\$nav_error,\%scantron_config);
1.582     raeburn  7165:     if ($nav_error) {
                   7166:         $r->print(&navmap_errormsg());
                   7167:         return '';
                   7168:     }
1.203     albertel 7169:     my $result=&scantron_form_start($max_bubble).$default_form_data;
1.596.2.12.2.  (raeburn 7170:):     if ($env{'form.scantron_lastbubblepoints'} ne '') {
                   7171:):         $result .= '<input type="hidden" name="scantron_lastbubblepoints" value="'.$env{'form.scantron_lastbubblepoints'}.'" />';
                   7172:):     }
1.157     albertel 7173:     $r->print($result);
                   7174:     
1.334     albertel 7175:     my @validate_phases=( 'sequence',
                   7176: 			  'ID',
1.157     albertel 7177: 			  'CODE',
                   7178: 			  'doublebubble',
                   7179: 			  'missingbubbles');
1.257     albertel 7180:     if (!$env{'form.validatepass'}) {
                   7181: 	$env{'form.validatepass'} = 0;
1.157     albertel 7182:     }
1.257     albertel 7183:     my $currentphase=$env{'form.validatepass'};
1.157     albertel 7184: 
1.448     foxr     7185: 
1.157     albertel 7186:     my $stop=0;
                   7187:     while (!$stop && $currentphase < scalar(@validate_phases)) {
1.503     raeburn  7188: 	$r->print(&mt('Validating '.$validate_phases[$currentphase]).'<br />');
1.157     albertel 7189: 	$r->rflush();
1.596.2.12.2.  6(raebur 7190:3): 
1.157     albertel 7191: 	my $which="scantron_validate_".$validate_phases[$currentphase];
                   7192: 	{
                   7193: 	    no strict 'refs';
                   7194: 	    ($stop,$currentphase)=&$which($r,$currentphase);
                   7195: 	}
                   7196:     }
                   7197:     if (!$stop) {
1.203     albertel 7198: 	my $warning=&scantron_warning_screen('Start Grading');
1.542     raeburn  7199: 	$r->print(&mt('Validation process complete.').'<br />'.
                   7200:                   $warning.
                   7201:                   &mt('Perform verification for each student after storage of submissions?').
                   7202:                   '&nbsp;<span class="LC_nobreak"><label>'.
                   7203:                   '<input type="radio" name="verifyrecord" value="1" />'.&mt('Yes').'</label>'.
                   7204:                   ('&nbsp;'x3).'<label>'.
                   7205:                   '<input type="radio" name="verifyrecord" value="0" checked="checked" />'.&mt('No').
                   7206:                   '</label></span><br />'.
                   7207:                   &mt('Grading will take longer if you use verification.').'<br />'.
1.572     www      7208:                   &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  7209:                   '<input type="submit" name="submit" value="'.&mt('Start Grading').'" />'.
                   7210:                   '<input type="hidden" name="command" value="scantron_process" />'."\n");
1.157     albertel 7211:     } else {
                   7212: 	$r->print('<input type="hidden" name="command" value="scantron_validate" />');
                   7213: 	$r->print("<input type='hidden' name='validatepass' value='".$currentphase."' />");
                   7214:     }
                   7215:     if ($stop) {
1.334     albertel 7216: 	if ($validate_phases[$currentphase] eq 'sequence') {
1.539     riegler  7217: 	    $r->print('<input type="submit" name="submit" value="'.&mt('Ignore').' &rarr; " />');
1.492     albertel 7218: 	    $r->print(' '.&mt('this error').' <br />');
1.334     albertel 7219: 
1.492     albertel 7220: 	    $r->print(" <p>".&mt("Or click the 'Grading Menu' button to start over.")."</p>");
1.334     albertel 7221: 	} else {
1.503     raeburn  7222:             if ($validate_phases[$currentphase] eq 'doublebubble' || $validate_phases[$currentphase] eq 'missingbubbles') {
1.539     riegler  7223: 	        $r->print('<input type="button" name="submitbutton" value="'.&mt('Continue').' &rarr;" onclick="javascript:verify_bubble_radio(this.form)" />');
1.503     raeburn  7224:             } else {
1.539     riegler  7225:                 $r->print('<input type="submit" name="submit" value="'.&mt('Continue').' &rarr;" />');
1.503     raeburn  7226:             }
1.492     albertel 7227: 	    $r->print(' '.&mt('using corrected info').' <br />');
                   7228: 	    $r->print("<input type='submit' value='".&mt("Skip")."' name='scantron_skip_record' />");
                   7229: 	    $r->print(" ".&mt("this scanline saving it for later."));
1.334     albertel 7230: 	}
1.157     albertel 7231:     }
1.352     albertel 7232:     $r->print(" </form><br />".&show_grading_menu_form($symb));
1.157     albertel 7233:     return '';
                   7234: }
                   7235: 
1.423     albertel 7236: 
                   7237: =pod
                   7238: 
                   7239: =item scantron_remove_file
                   7240: 
1.596.2.6  raeburn  7241:    Removes the requested bubblesheet data file, makes sure that
1.424     albertel 7242:    scantron_original_<filename> is never removed
                   7243: 
                   7244: 
1.423     albertel 7245: =cut
                   7246: 
1.200     albertel 7247: sub scantron_remove_file {
1.192     albertel 7248:     my ($which)=@_;
1.257     albertel 7249:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   7250:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1.192     albertel 7251:     my $file='scantron_';
1.200     albertel 7252:     if ($which eq 'corrected' || $which eq 'skipped') {
                   7253: 	$file.=$which.'_';
1.192     albertel 7254:     } else {
                   7255: 	return 'refused';
                   7256:     }
1.257     albertel 7257:     $file.=$env{'form.scantron_selectfile'};
1.200     albertel 7258:     return &Apache::lonnet::removeuserfile($cname,$cdom,$file);
                   7259: }
                   7260: 
1.423     albertel 7261: 
                   7262: =pod
                   7263: 
                   7264: =item scantron_remove_scan_data
                   7265: 
1.596.2.6  raeburn  7266:    Removes all scan_data correction for the requested bubblesheet
1.424     albertel 7267:    data file.  (In the case that both the are doing skipped records we need
                   7268:    to remember the old skipped lines for the time being so that element
                   7269:    persists for a while.)
                   7270: 
1.423     albertel 7271: =cut
                   7272: 
1.200     albertel 7273: sub scantron_remove_scan_data {
1.257     albertel 7274:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   7275:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1.192     albertel 7276:     my @keys=&Apache::lonnet::getkeys('nohist_scantrondata',$cdom,$cname);
                   7277:     my @todelete;
1.257     albertel 7278:     my $filename=$env{'form.scantron_selectfile'};
1.192     albertel 7279:     foreach my $key (@keys) {
                   7280: 	if ($key=~/^\Q$filename\E_/) {
1.257     albertel 7281: 	    if ($env{'form.scantron_options_redo'} eq 'redo_skipped_ready' &&
1.200     albertel 7282: 		$key=~/remember_skipping/) {
                   7283: 		next;
                   7284: 	    }
1.192     albertel 7285: 	    push(@todelete,$key);
                   7286: 	}
                   7287:     }
1.200     albertel 7288:     my $result;
1.192     albertel 7289:     if (@todelete) {
1.491     albertel 7290: 	$result = &Apache::lonnet::del('nohist_scantrondata',
                   7291: 				       \@todelete,$cdom,$cname);
                   7292:     } else {
                   7293: 	$result = 'ok';
1.192     albertel 7294:     }
                   7295:     return $result;
                   7296: }
                   7297: 
1.423     albertel 7298: 
                   7299: =pod
                   7300: 
                   7301: =item scantron_getfile
                   7302: 
1.596.2.6  raeburn  7303:     Fetches the requested bubblesheet data file (all 3 versions), and
1.424     albertel 7304:     the scan_data hash
                   7305:   
                   7306:   Arguments:
                   7307:     None
                   7308: 
                   7309:   Returns:
                   7310:     2 hash references
                   7311: 
                   7312:      - first one has 
                   7313:          orig      -
                   7314:          corrected -
                   7315:          skipped   -  each of which points to an array ref of the specified
                   7316:                       file broken up into individual lines
                   7317:          count     - number of scanlines
                   7318:  
                   7319:      - second is the scan_data hash possible keys are
1.425     albertel 7320:        ($number refers to scanline numbered $number and thus the key affects
                   7321:         only that scanline
                   7322:         $bubline refers to the specific bubble line element and the aspects
                   7323:         refers to that specific bubble line element)
                   7324: 
                   7325:        $number.user - username:domain to use
                   7326:        $number.CODE_ignore_dup 
                   7327:                     - ignore the duplicate CODE error 
                   7328:        $number.useCODE
                   7329:                     - use the CODE in the scanline as is
                   7330:        $number.no_bubble.$bubline
                   7331:                     - it is valid that there is no bubbled in bubble
                   7332:                       at $number $bubline
                   7333:        remember_skipping
                   7334:                     - a frozen hash containing keys of $number and values
                   7335:                       of either 
                   7336:                         1 - we are on a 'do skipped records pass' and plan
                   7337:                             on processing this line
                   7338:                         2 - we are on a 'do skipped records pass' and this
                   7339:                             scanline has been marked to skip yet again
1.424     albertel 7340: 
1.423     albertel 7341: =cut
                   7342: 
1.157     albertel 7343: sub scantron_getfile {
1.200     albertel 7344:     #FIXME really would prefer a scantron directory
1.257     albertel 7345:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   7346:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1.157     albertel 7347:     my $lines;
                   7348:     $lines=&Apache::lonnet::getfile('/uploaded/'.$cdom.'/'.$cname.'/'.
1.257     albertel 7349: 		       'scantron_orig_'.$env{'form.scantron_selectfile'});
1.157     albertel 7350:     my %scanlines;
                   7351:     $scanlines{'orig'}=[(split("\n",$lines,-1))];
                   7352:     my $temp=$scanlines{'orig'};
                   7353:     $scanlines{'count'}=$#$temp;
                   7354: 
                   7355:     $lines=&Apache::lonnet::getfile('/uploaded/'.$cdom.'/'.$cname.'/'.
1.257     albertel 7356: 		       'scantron_corrected_'.$env{'form.scantron_selectfile'});
1.157     albertel 7357:     if ($lines eq '-1') {
                   7358: 	$scanlines{'corrected'}=[];
                   7359:     } else {
                   7360: 	$scanlines{'corrected'}=[(split("\n",$lines,-1))];
                   7361:     }
                   7362:     $lines=&Apache::lonnet::getfile('/uploaded/'.$cdom.'/'.$cname.'/'.
1.257     albertel 7363: 		       'scantron_skipped_'.$env{'form.scantron_selectfile'});
1.157     albertel 7364:     if ($lines eq '-1') {
                   7365: 	$scanlines{'skipped'}=[];
                   7366:     } else {
                   7367: 	$scanlines{'skipped'}=[(split("\n",$lines,-1))];
                   7368:     }
1.175     albertel 7369:     my @tmp=&Apache::lonnet::dump('nohist_scantrondata',$cdom,$cname);
1.157     albertel 7370:     if ($tmp[0] =~ /^(error:|no_such_host)/) { @tmp=(); }
                   7371:     my %scan_data = @tmp;
                   7372:     return (\%scanlines,\%scan_data);
                   7373: }
                   7374: 
1.423     albertel 7375: =pod
                   7376: 
                   7377: =item lonnet_putfile
                   7378: 
1.424     albertel 7379:    Wrapper routine to call &Apache::lonnet::finishuserfileupload
                   7380: 
                   7381:  Arguments:
                   7382:    $contents - data to store
                   7383:    $filename - filename to store $contents into
                   7384: 
                   7385:  Returns:
                   7386:    result value from &Apache::lonnet::finishuserfileupload
                   7387: 
1.423     albertel 7388: =cut
                   7389: 
1.157     albertel 7390: sub lonnet_putfile {
                   7391:     my ($contents,$filename)=@_;
1.257     albertel 7392:     my $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   7393:     my $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
                   7394:     $env{'form.sillywaytopassafilearound'}=$contents;
1.275     albertel 7395:     &Apache::lonnet::finishuserfileupload($docuname,$docudom,'sillywaytopassafilearound',$filename);
1.157     albertel 7396: 
                   7397: }
                   7398: 
1.423     albertel 7399: =pod
                   7400: 
                   7401: =item scantron_putfile
                   7402: 
1.596.2.6  raeburn  7403:     Stores the current version of the bubblesheet data files, and the
1.424     albertel 7404:     scan_data hash. (Does not modify the original version only the
                   7405:     corrected and skipped versions.
                   7406: 
                   7407:  Arguments:
                   7408:     $scanlines - hash ref that looks like the first return value from
                   7409:                  &scantron_getfile()
                   7410:     $scan_data - hash ref that looks like the second return value from
                   7411:                  &scantron_getfile()
                   7412: 
1.423     albertel 7413: =cut
                   7414: 
1.157     albertel 7415: sub scantron_putfile {
                   7416:     my ($scanlines,$scan_data) = @_;
1.200     albertel 7417:     #FIXME really would prefer a scantron directory
1.257     albertel 7418:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   7419:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1.200     albertel 7420:     if ($scanlines) {
                   7421: 	my $prefix='scantron_';
1.157     albertel 7422: # no need to update orig, shouldn't change
                   7423: #   &lonnet_putfile(join("\n",@{$scanlines->{'orig'}}),$prefix.'orig_'.
1.257     albertel 7424: #		    $env{'form.scantron_selectfile'});
1.200     albertel 7425: 	&lonnet_putfile(join("\n",@{$scanlines->{'corrected'}}),
                   7426: 			$prefix.'corrected_'.
1.257     albertel 7427: 			$env{'form.scantron_selectfile'});
1.200     albertel 7428: 	&lonnet_putfile(join("\n",@{$scanlines->{'skipped'}}),
                   7429: 			$prefix.'skipped_'.
1.257     albertel 7430: 			$env{'form.scantron_selectfile'});
1.200     albertel 7431:     }
1.175     albertel 7432:     &Apache::lonnet::put('nohist_scantrondata',$scan_data,$cdom,$cname);
1.157     albertel 7433: }
                   7434: 
1.423     albertel 7435: =pod
                   7436: 
                   7437: =item scantron_get_line
                   7438: 
1.424     albertel 7439:    Returns the correct version of the scanline
                   7440: 
                   7441:  Arguments:
                   7442:     $scanlines - hash ref that looks like the first return value from
                   7443:                  &scantron_getfile()
                   7444:     $scan_data - hash ref that looks like the second return value from
                   7445:                  &scantron_getfile()
                   7446:     $i         - number of the requested line (starts at 0)
                   7447: 
                   7448:  Returns:
                   7449:    A scanline, (either the original or the corrected one if it
                   7450:    exists), or undef if the requested scanline should be
                   7451:    skipped. (Either because it's an skipped scanline, or it's an
                   7452:    unskipped scanline and we are not doing a 'do skipped scanlines'
                   7453:    pass.
                   7454: 
1.423     albertel 7455: =cut
                   7456: 
1.157     albertel 7457: sub scantron_get_line {
1.200     albertel 7458:     my ($scanlines,$scan_data,$i)=@_;
1.376     albertel 7459:     if (&should_be_skipped($scanlines,$scan_data,$i)) { return undef; }
                   7460:     #if ($scanlines->{'skipped'}[$i]) { return undef; }
1.157     albertel 7461:     if ($scanlines->{'corrected'}[$i]) {return $scanlines->{'corrected'}[$i];}
                   7462:     return $scanlines->{'orig'}[$i]; 
                   7463: }
                   7464: 
1.423     albertel 7465: =pod
                   7466: 
                   7467: =item scantron_todo_count
                   7468: 
1.424     albertel 7469:     Counts the number of scanlines that need processing.
                   7470: 
                   7471:  Arguments:
                   7472:     $scanlines - hash ref that looks like the first return value from
                   7473:                  &scantron_getfile()
                   7474:     $scan_data - hash ref that looks like the second return value from
                   7475:                  &scantron_getfile()
                   7476: 
                   7477:  Returns:
                   7478:     $count - number of scanlines to process
                   7479: 
1.423     albertel 7480: =cut
                   7481: 
1.200     albertel 7482: sub get_todo_count {
                   7483:     my ($scanlines,$scan_data)=@_;
                   7484:     my $count=0;
                   7485:     for (my $i=0;$i<=$scanlines->{'count'};$i++) {
                   7486: 	my $line=&scantron_get_line($scanlines,$scan_data,$i);
                   7487: 	if ($line=~/^[\s\cz]*$/) { next; }
                   7488: 	$count++;
                   7489:     }
                   7490:     return $count;
                   7491: }
                   7492: 
1.423     albertel 7493: =pod
                   7494: 
                   7495: =item scantron_put_line
                   7496: 
1.596.2.6  raeburn  7497:     Updates the 'corrected' or 'skipped' versions of the bubblesheet
1.424     albertel 7498:     data file.
                   7499: 
                   7500:  Arguments:
                   7501:     $scanlines - hash ref that looks like the first return value from
                   7502:                  &scantron_getfile()
                   7503:     $scan_data - hash ref that looks like the second return value from
                   7504:                  &scantron_getfile()
                   7505:     $i         - line number to update
                   7506:     $newline   - contents of the updated scanline
                   7507:     $skip      - if true make the line for skipping and update the
                   7508:                  'skipped' file
                   7509: 
1.423     albertel 7510: =cut
                   7511: 
1.157     albertel 7512: sub scantron_put_line {
1.200     albertel 7513:     my ($scanlines,$scan_data,$i,$newline,$skip)=@_;
1.157     albertel 7514:     if ($skip) {
                   7515: 	$scanlines->{'skipped'}[$i]=$newline;
1.376     albertel 7516: 	&start_skipping($scan_data,$i);
1.157     albertel 7517: 	return;
                   7518:     }
                   7519:     $scanlines->{'corrected'}[$i]=$newline;
                   7520: }
                   7521: 
1.423     albertel 7522: =pod
                   7523: 
                   7524: =item scantron_clear_skip
                   7525: 
1.424     albertel 7526:    Remove a line from the 'skipped' file
                   7527: 
                   7528:  Arguments:
                   7529:     $scanlines - hash ref that looks like the first return value from
                   7530:                  &scantron_getfile()
                   7531:     $scan_data - hash ref that looks like the second return value from
                   7532:                  &scantron_getfile()
                   7533:     $i         - line number to update
                   7534: 
1.423     albertel 7535: =cut
                   7536: 
1.376     albertel 7537: sub scantron_clear_skip {
                   7538:     my ($scanlines,$scan_data,$i)=@_;
                   7539:     if (exists($scanlines->{'skipped'}[$i])) {
                   7540: 	undef($scanlines->{'skipped'}[$i]);
                   7541: 	return 1;
                   7542:     }
                   7543:     return 0;
                   7544: }
                   7545: 
1.423     albertel 7546: =pod
                   7547: 
                   7548: =item scantron_filter_not_exam
                   7549: 
1.424     albertel 7550:    Filter routine used by &Apache::lonnavmaps::retrieveResources(), to
                   7551:    filter out resources that are not marked as 'exam' mode
                   7552: 
1.423     albertel 7553: =cut
                   7554: 
1.334     albertel 7555: sub scantron_filter_not_exam {
                   7556:     my ($curres)=@_;
                   7557:     
                   7558:     if (ref($curres) && $curres->is_problem() && !$curres->is_exam()) {
                   7559: 	# if the user has asked to not have either hidden
                   7560: 	# or 'randomout' controlled resources to be graded
                   7561: 	# don't include them
                   7562: 	if ($env{'form.scantron_options_hidden'} eq 'ignore_hidden'
                   7563: 	    && $curres->randomout) {
                   7564: 	    return 0;
                   7565: 	}
                   7566: 	return 1;
                   7567:     }
                   7568:     return 0;
                   7569: }
                   7570: 
1.423     albertel 7571: =pod
                   7572: 
                   7573: =item scantron_validate_sequence
                   7574: 
1.424     albertel 7575:     Validates the selected sequence, checking for resource that are
                   7576:     not set to exam mode.
                   7577: 
1.423     albertel 7578: =cut
                   7579: 
1.334     albertel 7580: sub scantron_validate_sequence {
                   7581:     my ($r,$currentphase) = @_;
                   7582: 
                   7583:     my $navmap=Apache::lonnavmaps::navmap->new();
1.582     raeburn  7584:     unless (ref($navmap)) {
                   7585:         $r->print(&navmap_errormsg());
                   7586:         return (1,$currentphase);
                   7587:     }
1.334     albertel 7588:     my (undef,undef,$sequence)=
                   7589: 	&Apache::lonnet::decode_symb($env{'form.selectpage'});
                   7590: 
                   7591:     my $map=$navmap->getResourceByUrl($sequence);
                   7592: 
                   7593:     $r->print('<input type="hidden" name="validate_sequence_exam"
                   7594:                                     value="ignore" />');
                   7595:     if ($env{'form.validate_sequence_exam'} ne 'ignore') {
                   7596: 	my @resources=
                   7597: 	    $navmap->retrieveResources($map,\&scantron_filter_not_exam,1,0);
                   7598: 	if (@resources) {
1.596.2.12.2.  0(raebur 7599:2): 	    $r->print('<p class="LC_warning">'
                   7600:2):                .&mt('Some resources in the sequence currently are not set to'
                   7601:2):                    .' exam mode. Grading these resources currently may not'
                   7602:2):                    .' work correctly.')
                   7603:2):                .'</p>'
                   7604:2):             );
1.334     albertel 7605: 	    return (1,$currentphase);
                   7606: 	}
                   7607:     }
                   7608: 
                   7609:     return (0,$currentphase+1);
                   7610: }
                   7611: 
1.423     albertel 7612: 
                   7613: 
1.157     albertel 7614: sub scantron_validate_ID {
                   7615:     my ($r,$currentphase) = @_;
                   7616:     
                   7617:     #get student info
                   7618:     my $classlist=&Apache::loncoursedata::get_classlist();
                   7619:     my %idmap=&username_to_idmap($classlist);
                   7620: 
                   7621:     #get scantron line setup
1.257     albertel 7622:     my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
1.157     albertel 7623:     my ($scanlines,$scan_data)=&scantron_getfile();
1.582     raeburn  7624: 
                   7625:     my $nav_error;
1.596.2.12.2.  (raeburn 7626:):     &scantron_get_maxbubble(\$nav_error,\%scantron_config); # parse needs the bubble_lines.. array.
1.582     raeburn  7627:     if ($nav_error) {
                   7628:         $r->print(&navmap_errormsg());
                   7629:         return(1,$currentphase);
                   7630:     }
1.157     albertel 7631: 
                   7632:     my %found=('ids'=>{},'usernames'=>{});
                   7633:     for (my $i=0;$i<=$scanlines->{'count'};$i++) {
1.200     albertel 7634: 	my $line=&scantron_get_line($scanlines,$scan_data,$i);
1.157     albertel 7635: 	if ($line=~/^[\s\cz]*$/) { next; }
                   7636: 	my $scan_record=&scantron_parse_scanline($line,$i,\%scantron_config,
                   7637: 						 $scan_data);
                   7638: 	my $id=$$scan_record{'scantron.ID'};
                   7639: 	my $found;
                   7640: 	foreach my $checkid (keys(%idmap)) {
                   7641: 	    if (lc($checkid) eq lc($id)) { $found=$checkid;last; }
                   7642: 	}
                   7643: 	if ($found) {
                   7644: 	    my $username=$idmap{$found};
                   7645: 	    if ($found{'ids'}{$found}) {
                   7646: 		&scantron_get_correction($r,$i,$scan_record,\%scantron_config,
                   7647: 					 $line,'duplicateID',$found);
1.194     albertel 7648: 		return(1,$currentphase);
1.157     albertel 7649: 	    } elsif ($found{'usernames'}{$username}) {
                   7650: 		&scantron_get_correction($r,$i,$scan_record,\%scantron_config,
                   7651: 					 $line,'duplicateID',$username);
1.194     albertel 7652: 		return(1,$currentphase);
1.157     albertel 7653: 	    }
1.186     albertel 7654: 	    #FIXME store away line we previously saw the ID on to use above
1.157     albertel 7655: 	    $found{'ids'}{$found}++;
                   7656: 	    $found{'usernames'}{$username}++;
                   7657: 	} else {
                   7658: 	    if ($id =~ /^\s*$/) {
1.158     albertel 7659: 		my $username=&scan_data($scan_data,"$i.user");
1.157     albertel 7660: 		if (defined($username) && $found{'usernames'}{$username}) {
                   7661: 		    &scantron_get_correction($r,$i,$scan_record,
                   7662: 					     \%scantron_config,
                   7663: 					     $line,'duplicateID',$username);
1.194     albertel 7664: 		    return(1,$currentphase);
1.157     albertel 7665: 		} elsif (!defined($username)) {
                   7666: 		    &scantron_get_correction($r,$i,$scan_record,
                   7667: 					     \%scantron_config,
                   7668: 					     $line,'incorrectID');
1.194     albertel 7669: 		    return(1,$currentphase);
1.157     albertel 7670: 		}
                   7671: 		$found{'usernames'}{$username}++;
                   7672: 	    } else {
                   7673: 		&scantron_get_correction($r,$i,$scan_record,\%scantron_config,
                   7674: 					 $line,'incorrectID');
1.194     albertel 7675: 		return(1,$currentphase);
1.157     albertel 7676: 	    }
                   7677: 	}
                   7678:     }
                   7679: 
                   7680:     return (0,$currentphase+1);
                   7681: }
                   7682: 
1.423     albertel 7683: 
1.157     albertel 7684: sub scantron_get_correction {
1.596.2.12.2.  6(raebur 7685:3):     my ($r,$i,$scan_record,$scan_config,$line,$error,$arg,
                   7686:3):         $randomorder,$randompick,$respnumlookup,$startline)=@_;
1.454     banghart 7687: #FIXME in the case of a duplicated ID the previous line, probably need
1.157     albertel 7688: #to show both the current line and the previous one and allow skipping
                   7689: #the previous one or the current one
                   7690: 
1.333     albertel 7691:     if ( $$scan_record{'scantron.PaperID'} =~ /\S/) {
1.596.2.6  raeburn  7692:         $r->print(
                   7693:             '<p class="LC_warning">'
                   7694:            .&mt('An error was detected ([_1]) for PaperID [_2]',
                   7695:                 "<b>$error</b>",
                   7696:                 '<tt>'.$$scan_record{'scantron.PaperID'}.'</tt>')
                   7697:            ."</p> \n");
1.157     albertel 7698:     } else {
1.596.2.6  raeburn  7699:         $r->print(
                   7700:             '<p class="LC_warning">'
                   7701:            .&mt('An error was detected ([_1]) in scanline [_2] [_3]',
                   7702:                 "<b>$error</b>", $i, "<pre>$line</pre>")
                   7703:            ."</p> \n");
                   7704:     }
                   7705:     my $message =
                   7706:         '<p>'
                   7707:        .&mt('The ID on the form is [_1]',
                   7708:             "<tt>$$scan_record{'scantron.ID'}</tt>")
                   7709:        .'<br />'
1.596.2.12  raeburn  7710:        .&mt('The name on the paper is [_1], [_2]',
1.596.2.6  raeburn  7711:             $$scan_record{'scantron.LastName'},
                   7712:             $$scan_record{'scantron.FirstName'})
                   7713:        .'</p>';
1.242     albertel 7714: 
1.157     albertel 7715:     $r->print('<input type="hidden" name="scantron_corrections" value="'.$error.'" />'."\n");
                   7716:     $r->print('<input type="hidden" name="scantron_line" value="'.$i.'" />'."\n");
1.503     raeburn  7717:                            # Array populated for doublebubble or
                   7718:     my @lines_to_correct;  # missingbubble errors to build javascript
                   7719:                            # to validate radio button checking   
                   7720: 
1.157     albertel 7721:     if ($error =~ /ID$/) {
1.186     albertel 7722: 	if ($error eq 'incorrectID') {
1.596.2.6  raeburn  7723: 	    $r->print('<p class="LC_warning">'.&mt("The encoded ID is not in the classlist").
1.492     albertel 7724: 		      "</p>\n");
1.157     albertel 7725: 	} elsif ($error eq 'duplicateID') {
1.596.2.6  raeburn  7726: 	    $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 7727: 	}
1.242     albertel 7728: 	$r->print($message);
1.492     albertel 7729: 	$r->print("<p>".&mt("How should I handle this?")." <br /> \n");
1.157     albertel 7730: 	$r->print("\n<ul><li> ");
                   7731: 	#FIXME it would be nice if this sent back the user ID and
                   7732: 	#could do partial userID matches
                   7733: 	$r->print(&Apache::loncommon::selectstudent_link('scantronupload',
                   7734: 				       'scantron_username','scantron_domain'));
                   7735: 	$r->print(": <input type='text' name='scantron_username' value='' />");
1.596.2.12.2.  3(raebur 7736:3): 	$r->print("\n:\n".
1.257     albertel 7737: 		 &Apache::loncommon::select_dom_form($env{'request.role.domain'},'scantron_domain'));
1.157     albertel 7738: 
                   7739: 	$r->print('</li>');
1.186     albertel 7740:     } elsif ($error =~ /CODE$/) {
                   7741: 	if ($error eq 'incorrectCODE') {
1.596.2.6  raeburn  7742: 	    $r->print('<p class="LC_warning">'.&mt("The encoded CODE is not in the list of possible CODEs.")."</p>\n");
1.186     albertel 7743: 	} elsif ($error eq 'duplicateCODE') {
1.596.2.6  raeburn  7744: 	    $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 7745: 	}
1.596.2.6  raeburn  7746:         $r->print("<p>".&mt('The CODE on the form is [_1]',
                   7747:                             "<tt>'$$scan_record{'scantron.CODE'}'</tt>")
                   7748:                  ."</p>\n");
1.242     albertel 7749: 	$r->print($message);
1.596.2.6  raeburn  7750: 	$r->print("<p>".&mt("How should I handle this?")."</p>\n");
1.187     albertel 7751: 	$r->print("\n<br /> ");
1.194     albertel 7752: 	my $i=0;
1.273     albertel 7753: 	if ($error eq 'incorrectCODE' 
                   7754: 	    && $$scan_record{'scantron.CODE'}=~/\S/ ) {
1.194     albertel 7755: 	    my ($max,$closest)=&scantron_get_closely_matching_CODEs($arg,$$scan_record{'scantron.CODE'});
1.278     albertel 7756: 	    if ($closest > 0) {
                   7757: 		foreach my $testcode (@{$closest}) {
                   7758: 		    my $checked='';
1.569     bisitz   7759: 		    if (!$i) { $checked=' checked="checked"'; }
1.492     albertel 7760: 		    $r->print("
                   7761:    <label>
1.569     bisitz   7762:        <input type='radio' name='scantron_CODE_resolution' value='use_closest_$i'$checked />
1.492     albertel 7763:        ".&mt("Use the similar CODE [_1] instead.",
                   7764: 	    "<b><tt>".$testcode."</tt></b>")."
                   7765:     </label>
                   7766:     <input type='hidden' name='scantron_CODE_closest_$i' value='$testcode' />");
1.278     albertel 7767: 		    $r->print("\n<br />");
                   7768: 		    $i++;
                   7769: 		}
1.194     albertel 7770: 	    }
                   7771: 	}
1.273     albertel 7772: 	if ($$scan_record{'scantron.CODE'}=~/\S/ ) {
1.569     bisitz   7773: 	    my $checked; if (!$i) { $checked=' checked="checked"'; }
1.492     albertel 7774: 	    $r->print("
                   7775:     <label>
1.569     bisitz   7776:         <input type='radio' name='scantron_CODE_resolution' value='use_unfound'$checked />
1.596.2.6  raeburn  7777:        ".&mt("Use the CODE [_1] that was on the paper, ignoring the error.",
1.492     albertel 7778: 	     "<b><tt>".$$scan_record{'scantron.CODE'}."</tt></b>")."
                   7779:     </label>");
1.273     albertel 7780: 	    $r->print("\n<br />");
                   7781: 	}
1.194     albertel 7782: 
1.188     albertel 7783: 	$r->print(<<ENDSCRIPT);
                   7784: <script type="text/javascript">
                   7785: function change_radio(field) {
1.190     albertel 7786:     var slct=document.scantronupload.scantron_CODE_resolution;
1.188     albertel 7787:     var i;
                   7788:     for (i=0;i<slct.length;i++) {
                   7789:         if (slct[i].value==field) { slct[i].checked=true; }
                   7790:     }
                   7791: }
                   7792: </script>
                   7793: ENDSCRIPT
1.187     albertel 7794: 	my $href="/adm/pickcode?".
1.359     www      7795: 	   "form=".&escape("scantronupload").
                   7796: 	   "&scantron_format=".&escape($env{'form.scantron_format'}).
                   7797: 	   "&scantron_CODElist=".&escape($env{'form.scantron_CODElist'}).
                   7798: 	   "&curCODE=".&escape($$scan_record{'scantron.CODE'}).
                   7799: 	   "&scantron_selectfile=".&escape($env{'form.scantron_selectfile'});
1.332     albertel 7800: 	if ($env{'form.scantron_CODElist'} =~ /\S/) { 
1.492     albertel 7801: 	    $r->print("
                   7802:     <label>
                   7803:        <input type='radio' name='scantron_CODE_resolution' value='use_found' />
                   7804:        ".&mt("[_1]Select[_2] a CODE from the list of all CODEs and use it.",
                   7805: 	     "<a target='_blank' href='$href'>","</a>")."
                   7806:     </label> 
1.558     bisitz   7807:     ".&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 7808: 	    $r->print("\n<br />");
                   7809: 	}
1.492     albertel 7810: 	$r->print("
                   7811:     <label>
                   7812:        <input type='radio' name='scantron_CODE_resolution' value='use_typed' />
                   7813:        ".&mt("Use [_1] as the CODE.",
                   7814: 	     "</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 7815: 	$r->print("\n<br /><br />");
1.157     albertel 7816:     } elsif ($error eq 'doublebubble') {
1.596.2.6  raeburn  7817: 	$r->print('<p class="LC_warning">'.&mt("There have been multiple bubbles scanned for some question(s)")."</p>\n");
1.497     foxr     7818: 
                   7819: 	# The form field scantron_questions is acutally a list of line numbers.
                   7820: 	# represented by this form so:
                   7821: 
1.596.2.12.2.  6(raebur 7822:3): 	my $line_list = &questions_to_line_list($arg,$randomorder,$randompick,
                   7823:3):                                                 $respnumlookup,$startline);
1.497     foxr     7824: 
1.157     albertel 7825: 	$r->print('<input type="hidden" name="scantron_questions" value="'.
1.497     foxr     7826: 		  $line_list.'" />');
1.242     albertel 7827: 	$r->print($message);
1.492     albertel 7828: 	$r->print("<p>".&mt("Please indicate which bubble should be used for grading")."</p>");
1.157     albertel 7829: 	foreach my $question (@{$arg}) {
1.503     raeburn  7830: 	    my @linenums = &prompt_for_corrections($r,$question,$scan_config,
1.596.2.12.2.  6(raebur 7831:3):                                                    $scan_record, $error,
                   7832:3):                                                    $randomorder,$randompick,
                   7833:3):                                                    $respnumlookup,$startline);
1.524     raeburn  7834:             push(@lines_to_correct,@linenums);
1.157     albertel 7835: 	}
1.503     raeburn  7836:         $r->print(&verify_bubbles_checked(@lines_to_correct));
1.157     albertel 7837:     } elsif ($error eq 'missingbubble') {
1.596.2.9  raeburn  7838: 	$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 7839: 	$r->print($message);
1.492     albertel 7840: 	$r->print("<p>".&mt("Please indicate which bubble should be used for grading.")."</p>");
1.503     raeburn  7841: 	$r->print(&mt("Some questions have no scanned bubbles.")."\n");
1.497     foxr     7842: 
1.503     raeburn  7843: 	# The form field scantron_questions is actually a list of line numbers not
1.497     foxr     7844: 	# a list of question numbers. Therefore:
                   7845: 	#
                   7846: 	
1.596.2.12.2.  6(raebur 7847:3): 	my $line_list = &questions_to_line_list($arg,$randomorder,$randompick,
                   7848:3):                                                 $respnumlookup,$startline);
1.497     foxr     7849: 
1.157     albertel 7850: 	$r->print('<input type="hidden" name="scantron_questions" value="'.
1.497     foxr     7851: 		  $line_list.'" />');
1.157     albertel 7852: 	foreach my $question (@{$arg}) {
1.503     raeburn  7853: 	    my @linenums = &prompt_for_corrections($r,$question,$scan_config,
1.596.2.12.2.  6(raebur 7854:3):                                                    $scan_record, $error,
                   7855:3):                                                    $randomorder,$randompick,
                   7856:3):                                                    $respnumlookup,$startline);
1.524     raeburn  7857:             push(@lines_to_correct,@linenums);
1.157     albertel 7858: 	}
1.503     raeburn  7859:         $r->print(&verify_bubbles_checked(@lines_to_correct));
1.157     albertel 7860:     } else {
                   7861: 	$r->print("\n<ul>");
                   7862:     }
                   7863:     $r->print("\n</li></ul>");
1.497     foxr     7864: }
                   7865: 
1.503     raeburn  7866: sub verify_bubbles_checked {
                   7867:     my (@ansnums) = @_;
                   7868:     my $ansnumstr = join('","',@ansnums);
                   7869:     my $warning = &mt("A bubble or 'No bubble' selection has not been made for one or more lines.");
1.596.2.12.2.  6(raebur 7870:6):     &js_escape(\$warning);
1.503     raeburn  7871:     my $output = (<<ENDSCRIPT);
                   7872: <script type="text/javascript">
                   7873: function verify_bubble_radio(form) {
                   7874:     var ansnumArray = new Array ("$ansnumstr");
                   7875:     var need_bubble_count = 0;
                   7876:     for (var i=0; i<ansnumArray.length; i++) {
                   7877:         if (form.elements["scantron_correct_Q_"+ansnumArray[i]].length > 1) {
                   7878:             var bubble_picked = 0; 
                   7879:             for (var j=0; j<form.elements["scantron_correct_Q_"+ansnumArray[i]].length; j++) {
                   7880:                 if (form.elements["scantron_correct_Q_"+ansnumArray[i]][j].checked == true) {
                   7881:                     bubble_picked = 1;
                   7882:                 }
                   7883:             }
                   7884:             if (bubble_picked == 0) {
                   7885:                 need_bubble_count ++;
                   7886:             }
                   7887:         }
                   7888:     }
                   7889:     if (need_bubble_count) {
                   7890:         alert("$warning");
                   7891:         return;
                   7892:     }
                   7893:     form.submit(); 
                   7894: }
                   7895: </script>
                   7896: ENDSCRIPT
                   7897:     return $output;
                   7898: }
                   7899: 
1.497     foxr     7900: =pod
                   7901: 
                   7902: =item  questions_to_line_list
1.157     albertel 7903: 
1.497     foxr     7904: Converts a list of questions into a string of comma separated
                   7905: line numbers in the answer sheet used by the questions.  This is
                   7906: used to fill in the scantron_questions form field.
                   7907: 
                   7908:   Arguments:
                   7909:      questions    - Reference to an array of questions.
1.596.2.12.2.  6(raebur 7910:3):      randomorder  - True if randomorder in use.
                   7911:3):      randompick   - True if randompick in use.
                   7912:3):      respnumlookup - Reference to HASH mapping question numbers in bubble lines
                   7913:3):                      for current line to question number used for same question
                   7914:3):                      in "Master Seqence" (as seen by Course Coordinator).
                   7915:3):      startline    - Reference to hash where key is question number (0 is first)
                   7916:3):                     and key is number of first bubble line for current student
                   7917:3):                     or code-based randompick and/or randomorder.
1.497     foxr     7918: 
                   7919: =cut
                   7920: 
                   7921: 
                   7922: sub questions_to_line_list {
1.596.2.12.2.  6(raebur 7923:3):     my ($questions,$randomorder,$randompick,$respnumlookup,$startline) = @_;
1.497     foxr     7924:     my @lines;
                   7925: 
1.503     raeburn  7926:     foreach my $item (@{$questions}) {
                   7927:         my $question = $item;
                   7928:         my ($first,$count,$last);
                   7929:         if ($item =~ /^(\d+)\.(\d+)$/) {
                   7930:             $question = $1;
                   7931:             my $subquestion = $2;
1.596.2.12.2.  6(raebur 7932:3):             my $responsenum = $question-1;
                   7933:3):             if (($randomorder || $randompick) && (ref($respnumlookup) eq 'HASH')) {
                   7934:3):                 $responsenum = $respnumlookup->{$question-1};
                   7935:3):                 if (ref($startline) eq 'HASH') {
                   7936:3):                     $first = $startline->{$question-1} + 1;
                   7937:3):                 }
                   7938:3):             } else {
                   7939:3):                 $first = $first_bubble_line{$responsenum} + 1;
                   7940:3):             }
          7(raebur 7941:3):             my @subans = split(/,/,$subdivided_bubble_lines{$responsenum});
1.503     raeburn  7942:             my $subcount = 1;
                   7943:             while ($subcount<$subquestion) {
                   7944:                 $first += $subans[$subcount-1];
                   7945:                 $subcount ++;
                   7946:             }
                   7947:             $count = $subans[$subquestion-1];
                   7948:         } else {
1.596.2.12.2.  7(raebur 7949:3):             my $responsenum = $question-1;
                   7950:3):             if (($randomorder || $randompick) && (ref($respnumlookup) eq 'HASH')) {
                   7951:3):                 $responsenum = $respnumlookup->{$question-1};
                   7952:3):                 if (ref($startline) eq 'HASH') {
                   7953:3):                     $first = $startline->{$question-1} + 1;
                   7954:3):                 }
                   7955:3):             } else {
                   7956:3):                 $first = $first_bubble_line{$responsenum} + 1;
                   7957:3):             }
                   7958:3):             $count   = $bubble_lines_per_response{$responsenum};
1.503     raeburn  7959:         }
1.506     raeburn  7960:         $last = $first+$count-1;
1.503     raeburn  7961:         push(@lines, ($first..$last));
1.497     foxr     7962:     }
                   7963:     return join(',', @lines);
                   7964: }
                   7965: 
                   7966: =pod 
                   7967: 
                   7968: =item prompt_for_corrections
                   7969: 
                   7970: Prompts for a potentially multiline correction to the
                   7971: user's bubbling (factors out common code from scantron_get_correction
                   7972: for multi and missing bubble cases).
                   7973: 
                   7974:  Arguments:
                   7975:    $r           - Apache request object.
                   7976:    $question    - The question number to prompt for.
                   7977:    $scan_config - The scantron file configuration hash.
                   7978:    $scan_record - Reference to the hash that has the the parsed scanlines.
1.503     raeburn  7979:    $error       - Type of error
1.596.2.12.2.  7(raebur 7980:3):    $randomorder - True if randomorder in use.
                   7981:3):    $randompick  - True if randompick in use.
                   7982:3):    $respnumlookup - Reference to HASH mapping question numbers in bubble lines
                   7983:3):                     for current line to question number used for same question
                   7984:3):                     in "Master Seqence" (as seen by Course Coordinator).
                   7985:3):    $startline   - Reference to hash where key is question number (0 is first)
                   7986:3):                   and value is number of first bubble line for current student
                   7987:3):                   or code-based randompick and/or randomorder.
1.497     foxr     7988: 
                   7989:  Implicit inputs:
                   7990:    %bubble_lines_per_response   - Starting line numbers for each question.
                   7991:                                   Numbered from 0 (but question numbers are from
                   7992:                                   1.
                   7993:    %first_bubble_line           - Starting bubble line for each question.
1.509     raeburn  7994:    %subdivided_bubble_lines     - optionresponse, matchresponse and rankresponse 
                   7995:                                   type problems render as separate sub-questions, 
1.503     raeburn  7996:                                   in exam mode. This hash contains a 
                   7997:                                   comma-separated list of the lines per 
                   7998:                                   sub-question.
1.510     raeburn  7999:    %responsetype_per_response   - essayresponse, formularesponse,
                   8000:                                   stringresponse, imageresponse, reactionresponse,
                   8001:                                   and organicresponse type problem parts can have
1.503     raeburn  8002:                                   multiple lines per response if the weight
                   8003:                                   assigned exceeds 10.  In this case, only
                   8004:                                   one bubble per line is permitted, but more 
                   8005:                                   than one line might contain bubbles, e.g.
                   8006:                                   bubbling of: line 1 - J, line 2 - J, 
                   8007:                                   line 3 - B would assign 22 points.  
1.497     foxr     8008: 
                   8009: =cut
                   8010: 
                   8011: sub prompt_for_corrections {
1.596.2.12.2.  6(raebur 8012:3):     my ($r, $question, $scan_config, $scan_record, $error, $randomorder,
                   8013:3):         $randompick, $respnumlookup, $startline) = @_;
1.503     raeburn  8014:     my ($current_line,$lines);
                   8015:     my @linenums;
                   8016:     my $questionnum = $question;
1.596.2.12.2.  6(raebur 8017:3):     my ($first,$responsenum);
1.503     raeburn  8018:     if ($question =~ /^(\d+)\.(\d+)$/) {
                   8019:         $question = $1;
                   8020:         my $subquestion = $2;
1.596.2.12.2.  6(raebur 8021:3):         if (($randomorder || $randompick) && (ref($respnumlookup) eq 'HASH')) {
                   8022:3):             $responsenum = $respnumlookup->{$question-1};
                   8023:3):             if (ref($startline) eq 'HASH') {
                   8024:3):                 $first = $startline->{$question-1};
                   8025:3):             }
                   8026:3):         } else {
                   8027:3):             $responsenum = $question-1;
          7(raebur 8028:4):             $first = $first_bubble_line{$responsenum};
          6(raebur 8029:3):         }
                   8030:3):         $current_line = $first + 1 ;
                   8031:3):         my @subans = split(/,/,$subdivided_bubble_lines{$responsenum});
1.503     raeburn  8032:         my $subcount = 1;
                   8033:         while ($subcount<$subquestion) {
                   8034:             $current_line += $subans[$subcount-1];
                   8035:             $subcount ++;
                   8036:         }
                   8037:         $lines = $subans[$subquestion-1];
                   8038:     } else {
1.596.2.12.2.  6(raebur 8039:3):         if (($randomorder || $randompick) && (ref($respnumlookup) eq 'HASH')) {
                   8040:3):             $responsenum = $respnumlookup->{$question-1};
                   8041:3):             if (ref($startline) eq 'HASH') {
                   8042:3):                 $first = $startline->{$question-1};
                   8043:3):             }
                   8044:3):         } else {
                   8045:3):             $responsenum = $question-1;
                   8046:3):             $first = $first_bubble_line{$responsenum};
                   8047:3):         }
                   8048:3):         $current_line = $first + 1;
                   8049:3):         $lines        = $bubble_lines_per_response{$responsenum};
1.503     raeburn  8050:     }
1.497     foxr     8051:     if ($lines > 1) {
1.503     raeburn  8052:         $r->print(&mt('The group of bubble lines below responds to a single question.').'<br />');
1.596.2.12.2.  6(raebur 8053:3):         if (($responsetype_per_response{$responsenum} eq 'essayresponse') ||
                   8054:3):             ($responsetype_per_response{$responsenum} eq 'formularesponse') ||
                   8055:3):             ($responsetype_per_response{$responsenum} eq 'stringresponse') ||
                   8056:3):             ($responsetype_per_response{$responsenum} eq 'imageresponse') ||
                   8057:3):             ($responsetype_per_response{$responsenum} eq 'reactionresponse') ||
                   8058:3):             ($responsetype_per_response{$responsenum} eq 'organicresponse')) {
          4(raebur 8059:3):             $r->print(&mt("Although this particular question type requires handgrading, the instructions for this question in the bubblesheet 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  8060:         } else {
                   8061:             $r->print(&mt("Select at most one bubble in a single line and select 'No Bubble' in all the other lines. ")."<br />");
                   8062:         }
1.497     foxr     8063:     }
                   8064:     for (my $i =0; $i < $lines; $i++) {
1.503     raeburn  8065:         my $selected = $$scan_record{"scantron.$current_line.answer"};
1.596.2.12.2.  6(raebur 8066:3): 	&scantron_bubble_selector($r,$scan_config,$current_line,
1.503     raeburn  8067: 	        		  $questionnum,$error,split('', $selected));
1.524     raeburn  8068:         push(@linenums,$current_line);
1.497     foxr     8069: 	$current_line++;
                   8070:     }
                   8071:     if ($lines > 1) {
                   8072: 	$r->print("<hr /><br />");
                   8073:     }
1.503     raeburn  8074:     return @linenums;
1.157     albertel 8075: }
1.423     albertel 8076: 
                   8077: =pod
                   8078: 
                   8079: =item scantron_bubble_selector
                   8080:   
                   8081:    Generates the html radiobuttons to correct a single bubble line
1.424     albertel 8082:    possibly showing the existing the selected bubbles if known
1.423     albertel 8083: 
                   8084:  Arguments:
                   8085:     $r           - Apache request object
                   8086:     $scan_config - hash from &get_scantron_config()
1.497     foxr     8087:     $line        - Number of the line being displayed.
1.503     raeburn  8088:     $questionnum - Question number (may include subquestion)
                   8089:     $error       - Type of error.
1.497     foxr     8090:     @selected    - Array of bubbles picked on this line.
1.423     albertel 8091: 
                   8092: =cut
                   8093: 
1.157     albertel 8094: sub scantron_bubble_selector {
1.503     raeburn  8095:     my ($r,$scan_config,$line,$questionnum,$error,@selected)=@_;
1.157     albertel 8096:     my $max=$$scan_config{'Qlength'};
1.274     albertel 8097: 
                   8098:     my $scmode=$$scan_config{'Qon'};
1.596.2.12.2.  (raeburn 8099:):     if ($scmode eq 'number' || $scmode eq 'letter') {
                   8100:):         if (($$scan_config{'BubblesPerRow'} =~ /^\d+$/) &&
                   8101:):             ($$scan_config{'BubblesPerRow'} > 0)) {
                   8102:):             $max=$$scan_config{'BubblesPerRow'};
                   8103:):             if (($scmode eq 'number') && ($max > 10)) {
                   8104:):                 $max = 10;
                   8105:):             } elsif (($scmode eq 'letter') && $max > 26) {
                   8106:):                 $max = 26;
                   8107:):             }
                   8108:):         } else {
                   8109:):             $max = 10;
                   8110:):         }
                   8111:):     }
1.274     albertel 8112: 
1.157     albertel 8113:     my @alphabet=('A'..'Z');
1.503     raeburn  8114:     $r->print(&Apache::loncommon::start_data_table().
                   8115:               &Apache::loncommon::start_data_table_row());
                   8116:     $r->print('<td rowspan="2" class="LC_leftcol_header">'.$line.'</td>');
1.497     foxr     8117:     for (my $i=0;$i<$max+1;$i++) {
                   8118: 	$r->print("\n".'<td align="center">');
                   8119: 	if ($selected[0] eq $alphabet[$i]) { $r->print('X'); shift(@selected) }
                   8120: 	else { $r->print('&nbsp;'); }
                   8121: 	$r->print('</td>');
                   8122:     }
1.503     raeburn  8123:     $r->print(&Apache::loncommon::end_data_table_row().
                   8124:               &Apache::loncommon::start_data_table_row());
1.497     foxr     8125:     for (my $i=0;$i<$max;$i++) {
                   8126: 	$r->print("\n".
                   8127: 		  '<td><label><input type="radio" name="scantron_correct_Q_'.
                   8128: 		  $line.'" value="'.$i.'" />'.$alphabet[$i]."</label></td>");
                   8129:     }
1.503     raeburn  8130:     my $nobub_checked = ' ';
                   8131:     if ($error eq 'missingbubble') {
                   8132:         $nobub_checked = ' checked = "checked" ';
                   8133:     }
                   8134:     $r->print("\n".'<td><label><input type="radio" name="scantron_correct_Q_'.
                   8135: 	      $line.'" value="none"'.$nobub_checked.'/>'.&mt('No bubble').
                   8136:               '</label>'."\n".'<input type="hidden" name="scantron_questionnum_Q_'.
                   8137:               $line.'" value="'.$questionnum.'" /></td>');
                   8138:     $r->print(&Apache::loncommon::end_data_table_row().
                   8139:               &Apache::loncommon::end_data_table());
1.157     albertel 8140: }
                   8141: 
1.423     albertel 8142: =pod
                   8143: 
                   8144: =item num_matches
                   8145: 
1.424     albertel 8146:    Counts the number of characters that are the same between the two arguments.
                   8147: 
                   8148:  Arguments:
                   8149:    $orig - CODE from the scanline
                   8150:    $code - CODE to match against
                   8151: 
                   8152:  Returns:
                   8153:    $count - integer count of the number of same characters between the
                   8154:             two arguments
                   8155: 
1.423     albertel 8156: =cut
                   8157: 
1.194     albertel 8158: sub num_matches {
                   8159:     my ($orig,$code) = @_;
                   8160:     my @code=split(//,$code);
                   8161:     my @orig=split(//,$orig);
                   8162:     my $same=0;
                   8163:     for (my $i=0;$i<scalar(@code);$i++) {
                   8164: 	if ($code[$i] eq $orig[$i]) { $same++; }
                   8165:     }
                   8166:     return $same;
                   8167: }
                   8168: 
1.423     albertel 8169: =pod
                   8170: 
                   8171: =item scantron_get_closely_matching_CODEs
                   8172: 
1.424     albertel 8173:    Cycles through all CODEs and finds the set that has the greatest
                   8174:    number of same characters as the provided CODE
                   8175: 
                   8176:  Arguments:
                   8177:    $allcodes - hash ref returned by &get_codes()
                   8178:    $CODE     - CODE from the current scanline
                   8179: 
                   8180:  Returns:
                   8181:    2 element list
                   8182:     - first elements is number of how closely matching the best fit is 
                   8183:       (5 means best set has 5 matching characters)
                   8184:     - second element is an arrary ref containing the set of valid CODEs
                   8185:       that best fit the passed in CODE
                   8186: 
1.423     albertel 8187: =cut
                   8188: 
1.194     albertel 8189: sub scantron_get_closely_matching_CODEs {
                   8190:     my ($allcodes,$CODE)=@_;
                   8191:     my @CODEs;
                   8192:     foreach my $testcode (sort(keys(%{$allcodes}))) {
                   8193: 	push(@{$CODEs[&num_matches($CODE,$testcode)]},$testcode);
                   8194:     }
                   8195: 
                   8196:     return ($#CODEs,$CODEs[-1]);
                   8197: }
                   8198: 
1.423     albertel 8199: =pod
                   8200: 
                   8201: =item get_codes
                   8202: 
1.424     albertel 8203:    Builds a hash which has keys of all of the valid CODEs from the selected
                   8204:    set of remembered CODEs.
                   8205: 
                   8206:  Arguments:
                   8207:   $old_name - name of the set of remembered CODEs
                   8208:   $cdom     - domain of the course
                   8209:   $cnum     - internal course name
                   8210: 
                   8211:  Returns:
                   8212:   %allcodes - keys are the valid CODEs, values are all 1
                   8213: 
1.423     albertel 8214: =cut
                   8215: 
1.194     albertel 8216: sub get_codes {
1.280     foxr     8217:     my ($old_name, $cdom, $cnum) = @_;
                   8218:     if (!$old_name) {
                   8219: 	$old_name=$env{'form.scantron_CODElist'};
                   8220:     }
                   8221:     if (!$cdom) {
                   8222: 	$cdom =$env{'course.'.$env{'request.course.id'}.'.domain'};
                   8223:     }
                   8224:     if (!$cnum) {
                   8225: 	$cnum =$env{'course.'.$env{'request.course.id'}.'.num'};
                   8226:     }
1.278     albertel 8227:     my %result=&Apache::lonnet::get('CODEs',[$old_name,"type\0$old_name"],
                   8228: 				    $cdom,$cnum);
                   8229:     my %allcodes;
                   8230:     if ($result{"type\0$old_name"} eq 'number') {
                   8231: 	%allcodes=map {($_,1)} split(',',$result{$old_name});
                   8232:     } else {
                   8233: 	%allcodes=map {(&Apache::lonprintout::num_to_letters($_),1)} split(',',$result{$old_name});
                   8234:     }
1.194     albertel 8235:     return %allcodes;
                   8236: }
                   8237: 
1.423     albertel 8238: =pod
                   8239: 
                   8240: =item scantron_validate_CODE
                   8241: 
1.424     albertel 8242:    Validates all scanlines in the selected file to not have any
                   8243:    invalid or underspecified CODEs and that none of the codes are
                   8244:    duplicated if this was requested.
                   8245: 
1.423     albertel 8246: =cut
                   8247: 
1.157     albertel 8248: sub scantron_validate_CODE {
                   8249:     my ($r,$currentphase) = @_;
1.257     albertel 8250:     my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
1.186     albertel 8251:     if ($scantron_config{'CODElocation'} &&
                   8252: 	$scantron_config{'CODEstart'} &&
                   8253: 	$scantron_config{'CODElength'}) {
1.257     albertel 8254: 	if (!defined($env{'form.scantron_CODElist'})) {
1.186     albertel 8255: 	    &FIXME_blow_up()
                   8256: 	}
                   8257:     } else {
                   8258: 	return (0,$currentphase+1);
                   8259:     }
                   8260:     
                   8261:     my %usedCODEs;
                   8262: 
1.194     albertel 8263:     my %allcodes=&get_codes();
1.186     albertel 8264: 
1.582     raeburn  8265:     my $nav_error;
1.596.2.12.2.  (raeburn 8266:):     &scantron_get_maxbubble(\$nav_error,\%scantron_config); # parse needs the lines per response array.
1.582     raeburn  8267:     if ($nav_error) {
                   8268:         $r->print(&navmap_errormsg());
                   8269:         return(1,$currentphase);
                   8270:     }
1.447     foxr     8271: 
1.186     albertel 8272:     my ($scanlines,$scan_data)=&scantron_getfile();
                   8273:     for (my $i=0;$i<=$scanlines->{'count'};$i++) {
1.200     albertel 8274: 	my $line=&scantron_get_line($scanlines,$scan_data,$i);
1.186     albertel 8275: 	if ($line=~/^[\s\cz]*$/) { next; }
                   8276: 	my $scan_record=&scantron_parse_scanline($line,$i,\%scantron_config,
                   8277: 						 $scan_data);
                   8278: 	my $CODE=$$scan_record{'scantron.CODE'};
                   8279: 	my $error=0;
1.224     albertel 8280: 	if (!&Apache::lonnet::validCODE($CODE)) {
                   8281: 	    &scantron_get_correction($r,$i,$scan_record,
                   8282: 				     \%scantron_config,
                   8283: 				     $line,'incorrectCODE',\%allcodes);
                   8284: 	    return(1,$currentphase);
                   8285: 	}
1.221     albertel 8286: 	if (%allcodes && !exists($allcodes{$CODE}) 
                   8287: 	    && !$$scan_record{'scantron.useCODE'}) {
1.186     albertel 8288: 	    &scantron_get_correction($r,$i,$scan_record,
                   8289: 				     \%scantron_config,
1.194     albertel 8290: 				     $line,'incorrectCODE',\%allcodes);
                   8291: 	    return(1,$currentphase);
1.186     albertel 8292: 	}
1.214     albertel 8293: 	if (exists($usedCODEs{$CODE}) 
1.257     albertel 8294: 	    && $env{'form.scantron_CODEunique'} eq 'yes'
1.192     albertel 8295: 	    && !$$scan_record{'scantron.CODE_ignore_dup'}) {
1.186     albertel 8296: 	    &scantron_get_correction($r,$i,$scan_record,
                   8297: 				     \%scantron_config,
1.194     albertel 8298: 				     $line,'duplicateCODE',$usedCODEs{$CODE});
                   8299: 	    return(1,$currentphase);
1.186     albertel 8300: 	}
1.524     raeburn  8301: 	push(@{$usedCODEs{$CODE}},$$scan_record{'scantron.PaperID'});
1.186     albertel 8302:     }
1.157     albertel 8303:     return (0,$currentphase+1);
                   8304: }
                   8305: 
1.423     albertel 8306: =pod
                   8307: 
                   8308: =item scantron_validate_doublebubble
                   8309: 
1.424     albertel 8310:    Validates all scanlines in the selected file to not have any
                   8311:    bubble lines with multiple bubbles marked.
                   8312: 
1.423     albertel 8313: =cut
                   8314: 
1.157     albertel 8315: sub scantron_validate_doublebubble {
                   8316:     my ($r,$currentphase) = @_;
                   8317:     #get student info
                   8318:     my $classlist=&Apache::loncoursedata::get_classlist();
                   8319:     my %idmap=&username_to_idmap($classlist);
1.596.2.12.2.  6(raebur 8320:3):     my (undef,undef,$sequence)=
                   8321:3):         &Apache::lonnet::decode_symb($env{'form.selectpage'});
1.157     albertel 8322: 
                   8323:     #get scantron line setup
1.257     albertel 8324:     my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
1.157     albertel 8325:     my ($scanlines,$scan_data)=&scantron_getfile();
1.596.2.12.2.  6(raebur 8326:3): 
                   8327:3):     my $navmap = Apache::lonnavmaps::navmap->new();
                   8328:3):     unless (ref($navmap)) {
                   8329:3):         $r->print(&navmap_errormsg());
                   8330:3):         return(1,$currentphase);
                   8331:3):     }
                   8332:3):     my $map=$navmap->getResourceByUrl($sequence);
                   8333:3):     my @resources=$navmap->retrieveResources($map,\&scantron_filter,1,0);
                   8334:3):     my ($randomorder,$randompick,@master_seq,%symb_to_resource,%grader_partids_by_symb,
                   8335:3):         %grader_randomlists_by_symb,%orderedforcode,%respnumlookup,%startline);
                   8336:3):     my $bubbles_per_row = &bubblesheet_bubbles_per_row(\%scantron_config);
                   8337:3): 
1.583     raeburn  8338:     my $nav_error;
1.596.2.12.2.  6(raebur 8339:3):     if (ref($map)) {
                   8340:3):         $randomorder = $map->randomorder();
                   8341:3):         $randompick = $map->randompick();
                   8342:3):         if ($randomorder || $randompick) {
                   8343:3):             $nav_error = &get_master_seq(\@resources,\@master_seq,\%symb_to_resource);
                   8344:3):             if ($nav_error) {
                   8345:3):                 $r->print(&navmap_errormsg());
                   8346:3):                 return(1,$currentphase);
                   8347:3):             }
                   8348:3):             &graders_resources_pass(\@resources,\%grader_partids_by_symb,
                   8349:3):                                     \%grader_randomlists_by_symb,$bubbles_per_row);
                   8350:3):         }
                   8351:3):     } else {
                   8352:3):         $r->print(&navmap_errormsg());
                   8353:3):         return(1,$currentphase);
                   8354:3):     }
                   8355:3): 
          (raeburn 8356:):     &scantron_get_maxbubble(\$nav_error,\%scantron_config); # parse needs the bubble line array.
1.583     raeburn  8357:     if ($nav_error) {
                   8358:         $r->print(&navmap_errormsg());
                   8359:         return(1,$currentphase);
                   8360:     }
1.447     foxr     8361: 
1.157     albertel 8362:     for (my $i=0;$i<=$scanlines->{'count'};$i++) {
1.200     albertel 8363: 	my $line=&scantron_get_line($scanlines,$scan_data,$i);
1.157     albertel 8364: 	if ($line=~/^[\s\cz]*$/) { next; }
                   8365: 	my $scan_record=&scantron_parse_scanline($line,$i,\%scantron_config,
1.596.2.12.2.  6(raebur 8366:3): 						 $scan_data,undef,\%idmap,$randomorder,
                   8367:3):                                                  $randompick,$sequence,\@master_seq,
                   8368:3):                                                  \%symb_to_resource,\%grader_partids_by_symb,
                   8369:3):                                                  \%orderedforcode,\%respnumlookup,\%startline);
1.157     albertel 8370: 	if (!defined($$scan_record{'scantron.doubleerror'})) { next; }
                   8371: 	&scantron_get_correction($r,$i,$scan_record,\%scantron_config,$line,
                   8372: 				 'doublebubble',
1.596.2.12.2.  6(raebur 8373:3): 				 $$scan_record{'scantron.doubleerror'},
                   8374:3):                                  $randomorder,$randompick,\%respnumlookup,\%startline);
1.157     albertel 8375:     	return (1,$currentphase);
                   8376:     }
                   8377:     return (0,$currentphase+1);
                   8378: }
                   8379: 
1.423     albertel 8380: 
1.503     raeburn  8381: sub scantron_get_maxbubble {
1.596.2.12.2.  (raeburn 8382:):     my ($nav_error,$scantron_config) = @_;
1.257     albertel 8383:     if (defined($env{'form.scantron_maxbubble'}) &&
                   8384: 	$env{'form.scantron_maxbubble'}) {
1.447     foxr     8385: 	&restore_bubble_lines();
1.257     albertel 8386: 	return $env{'form.scantron_maxbubble'};
1.191     albertel 8387:     }
1.330     albertel 8388: 
1.447     foxr     8389:     my (undef, undef, $sequence) =
1.257     albertel 8390: 	&Apache::lonnet::decode_symb($env{'form.selectpage'});
1.330     albertel 8391: 
1.447     foxr     8392:     my $navmap=Apache::lonnavmaps::navmap->new();
1.582     raeburn  8393:     unless (ref($navmap)) {
                   8394:         if (ref($nav_error)) {
                   8395:             $$nav_error = 1;
                   8396:         }
1.591     raeburn  8397:         return;
1.582     raeburn  8398:     }
1.191     albertel 8399:     my $map=$navmap->getResourceByUrl($sequence);
                   8400:     my @resources=$navmap->retrieveResources($map,\&scantron_filter,1,0);
1.596.2.12.2.  (raeburn 8401:):     my $bubbles_per_row = &bubblesheet_bubbles_per_row($scantron_config);
1.330     albertel 8402: 
                   8403:     &Apache::lonxml::clear_problem_counter();
                   8404: 
1.557     raeburn  8405:     my $uname       = $env{'user.name'};
                   8406:     my $udom        = $env{'user.domain'};
1.435     foxr     8407:     my $cid         = $env{'request.course.id'};
                   8408:     my $total_lines = 0;
                   8409:     %bubble_lines_per_response = ();
1.447     foxr     8410:     %first_bubble_line         = ();
1.503     raeburn  8411:     %subdivided_bubble_lines   = ();
                   8412:     %responsetype_per_response = ();
1.596.2.12.2.  6(raebur 8413:3):     %masterseq_id_responsenum  = ();
1.554     raeburn  8414: 
1.447     foxr     8415:     my $response_number = 0;
                   8416:     my $bubble_line     = 0;
1.191     albertel 8417:     foreach my $resource (@resources) {
1.596.2.12.2.  6(raebur 8418:3):         my $resid = $resource->id();
          (raeburn 8419:):         my ($analysis,$parts) = &scantron_partids_tograde($resource,$cid,$uname,
          7(raebur 8420:3):                                                           $udom,undef,$bubbles_per_row);
1.542     raeburn  8421:         if ((ref($analysis) eq 'HASH') && (ref($parts) eq 'ARRAY')) {
                   8422: 	    foreach my $part_id (@{$parts}) {
                   8423:                 my $lines;
                   8424: 
                   8425: 	        # TODO - make this a persistent hash not an array.
                   8426: 
                   8427:                 # optionresponse, matchresponse and rankresponse type items 
                   8428:                 # render as separate sub-questions in exam mode.
                   8429:                 if (($analysis->{$part_id.'.type'} eq 'optionresponse') ||
                   8430:                     ($analysis->{$part_id.'.type'} eq 'matchresponse') ||
                   8431:                     ($analysis->{$part_id.'.type'} eq 'rankresponse')) {
                   8432:                     my ($numbub,$numshown);
                   8433:                     if ($analysis->{$part_id.'.type'} eq 'optionresponse') {
                   8434:                         if (ref($analysis->{$part_id.'.options'}) eq 'ARRAY') {
                   8435:                             $numbub = scalar(@{$analysis->{$part_id.'.options'}});
                   8436:                         }
                   8437:                     } elsif ($analysis->{$part_id.'.type'} eq 'matchresponse') {
                   8438:                         if (ref($analysis->{$part_id.'.items'}) eq 'ARRAY') {
                   8439:                             $numbub = scalar(@{$analysis->{$part_id.'.items'}});
                   8440:                         }
                   8441:                     } elsif ($analysis->{$part_id.'.type'} eq 'rankresponse') {
                   8442:                         if (ref($analysis->{$part_id.'.foils'}) eq 'ARRAY') {
                   8443:                             $numbub = scalar(@{$analysis->{$part_id.'.foils'}});
                   8444:                         }
                   8445:                     }
                   8446:                     if (ref($analysis->{$part_id.'.shown'}) eq 'ARRAY') {
                   8447:                         $numshown = scalar(@{$analysis->{$part_id.'.shown'}});
                   8448:                     }
1.596.2.12.2.  (raeburn 8449:):                     my $bubbles_per_row =
                   8450:):                         &bubblesheet_bubbles_per_row($scantron_config);
                   8451:):                     my $inner_bubble_lines = int($numbub/$bubbles_per_row);
                   8452:):                     if (($numbub % $bubbles_per_row) != 0) {
1.542     raeburn  8453:                         $inner_bubble_lines++;
                   8454:                     }
                   8455:                     for (my $i=0; $i<$numshown; $i++) {
                   8456:                         $subdivided_bubble_lines{$response_number} .= 
                   8457:                             $inner_bubble_lines.',';
                   8458:                     }
                   8459:                     $subdivided_bubble_lines{$response_number} =~ s/,$//;
                   8460:                     $lines = $numshown * $inner_bubble_lines;
                   8461:                 } else {
                   8462:                     $lines = $analysis->{"$part_id.bubble_lines"};
1.596.2.12.2.  (raeburn 8463:):                 }
1.542     raeburn  8464: 
                   8465:                 $first_bubble_line{$response_number} = $bubble_line;
                   8466: 	        $bubble_lines_per_response{$response_number} = $lines;
                   8467:                 $responsetype_per_response{$response_number} = 
                   8468:                     $analysis->{$part_id.'.type'};
1.596.2.12.2.  6(raebur 8469:3):                 $masterseq_id_responsenum{$resid.'_'.$part_id} = $response_number;
1.542     raeburn  8470: 	        $response_number++;
                   8471: 
                   8472: 	        $bubble_line +=  $lines;
                   8473: 	        $total_lines +=  $lines;
                   8474: 	    }
                   8475:         }
                   8476:     }
1.552     raeburn  8477:     &Apache::lonnet::delenv('scantron.');
1.542     raeburn  8478: 
                   8479:     &save_bubble_lines();
                   8480:     $env{'form.scantron_maxbubble'} =
                   8481: 	$total_lines;
                   8482:     return $env{'form.scantron_maxbubble'};
                   8483: }
1.523     raeburn  8484: 
1.596.2.12.2.  (raeburn 8485:): sub bubblesheet_bubbles_per_row {
                   8486:):     my ($scantron_config) = @_;
                   8487:):     my $bubbles_per_row;
                   8488:):     if (ref($scantron_config) eq 'HASH') {
                   8489:):         $bubbles_per_row = $scantron_config->{'BubblesPerRow'};
                   8490:):     }
                   8491:):     if ((!$bubbles_per_row) || ($bubbles_per_row < 1)) {
                   8492:):         $bubbles_per_row = 10;
                   8493:):     }
                   8494:):     return $bubbles_per_row;
                   8495:): }
                   8496:): 
1.157     albertel 8497: sub scantron_validate_missingbubbles {
                   8498:     my ($r,$currentphase) = @_;
                   8499:     #get student info
                   8500:     my $classlist=&Apache::loncoursedata::get_classlist();
                   8501:     my %idmap=&username_to_idmap($classlist);
1.596.2.12.2.  6(raebur 8502:3):     my (undef,undef,$sequence)=
                   8503:3):         &Apache::lonnet::decode_symb($env{'form.selectpage'});
1.157     albertel 8504: 
                   8505:     #get scantron line setup
1.257     albertel 8506:     my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
1.157     albertel 8507:     my ($scanlines,$scan_data)=&scantron_getfile();
1.596.2.12.2.  6(raebur 8508:3): 
                   8509:3):     my $navmap = Apache::lonnavmaps::navmap->new();
                   8510:3):     unless (ref($navmap)) {
                   8511:3):         $r->print(&navmap_errormsg());
                   8512:3):         return(1,$currentphase);
                   8513:3):     }
                   8514:3): 
                   8515:3):     my $map=$navmap->getResourceByUrl($sequence);
                   8516:3):     my @resources=$navmap->retrieveResources($map,\&scantron_filter,1,0);
                   8517:3):     my ($randomorder,$randompick,@master_seq,%symb_to_resource,%grader_partids_by_symb,
                   8518:3):         %grader_randomlists_by_symb,%orderedforcode,%respnumlookup,%startline);
                   8519:3):     my $bubbles_per_row = &bubblesheet_bubbles_per_row(\%scantron_config);
                   8520:3): 
1.582     raeburn  8521:     my $nav_error;
1.596.2.12.2.  6(raebur 8522:3):     if (ref($map)) {
                   8523:3):         $randomorder = $map->randomorder();
                   8524:3):         $randompick = $map->randompick();
          7(raebur 8525:3):         if ($randomorder || $randompick) {
                   8526:3):             $nav_error = &get_master_seq(\@resources,\@master_seq,\%symb_to_resource);
                   8527:3):             if ($nav_error) {
                   8528:3):                 $r->print(&navmap_errormsg());
                   8529:3):                 return(1,$currentphase);
                   8530:3):             }
                   8531:3):             &graders_resources_pass(\@resources,\%grader_partids_by_symb,
                   8532:3):                                     \%grader_randomlists_by_symb,$bubbles_per_row);
                   8533:3):         }
          6(raebur 8534:3):     } else {
                   8535:3):         $r->print(&navmap_errormsg());
          7(raebur 8536:3):         return(1,$currentphase);
          6(raebur 8537:3):     }
                   8538:3): 
                   8539:3): 
          (raeburn 8540:):     my $max_bubble=&scantron_get_maxbubble(\$nav_error,\%scantron_config);
1.582     raeburn  8541:     if ($nav_error) {
1.596.2.12.2.  6(raebur 8542:3):         $r->print(&navmap_errormsg());
1.582     raeburn  8543:         return(1,$currentphase);
                   8544:     }
1.596.2.12.2.  6(raebur 8545:3): 
1.157     albertel 8546:     if (!$max_bubble) { $max_bubble=2**31; }
                   8547:     for (my $i=0;$i<=$scanlines->{'count'};$i++) {
1.200     albertel 8548: 	my $line=&scantron_get_line($scanlines,$scan_data,$i);
1.157     albertel 8549: 	if ($line=~/^[\s\cz]*$/) { next; }
1.596.2.12.2.  6(raebur 8550:3):         my $scan_record =
                   8551:3):             &scantron_parse_scanline($line,$i,\%scantron_config,$scan_data,undef,\%idmap,
                   8552:3):                                      $randomorder,$randompick,$sequence,\@master_seq,
                   8553:3):                                      \%symb_to_resource,\%grader_partids_by_symb,
                   8554:3):                                      \%orderedforcode,\%respnumlookup,\%startline);
1.157     albertel 8555: 	if (!defined($$scan_record{'scantron.missingerror'})) { next; }
                   8556: 	my @to_correct;
1.470     foxr     8557: 	
                   8558: 	# Probably here's where the error is...
                   8559: 
1.157     albertel 8560: 	foreach my $missing (@{$$scan_record{'scantron.missingerror'}}) {
1.505     raeburn  8561:             my $lastbubble;
                   8562:             if ($missing =~ /^(\d+)\.(\d+)$/) {
1.596.2.12.2.  6(raebur 8563:3):                 my $question = $1;
                   8564:3):                 my $subquestion = $2;
                   8565:3):                 my ($first,$responsenum);
                   8566:3):                 if ($randomorder || $randompick) {
                   8567:3):                     $responsenum = $respnumlookup{$question-1};
                   8568:3):                     $first = $startline{$question-1};
                   8569:3):                 } else {
                   8570:3):                     $responsenum = $question-1;
                   8571:3):                     $first = $first_bubble_line{$responsenum};
                   8572:3):                 }
                   8573:3):                 if (!defined($first)) { next; }
          7(raebur 8574:3):                 my @subans = split(/,/,$subdivided_bubble_lines{$responsenum});
          6(raebur 8575:3):                 my $subcount = 1;
                   8576:3):                 while ($subcount<$subquestion) {
                   8577:3):                     $first += $subans[$subcount-1];
                   8578:3):                     $subcount ++;
                   8579:3):                 }
                   8580:3):                 my $count = $subans[$subquestion-1];
                   8581:3):                 $lastbubble = $first + $count;
1.505     raeburn  8582:             } else {
1.596.2.12.2.  6(raebur 8583:3):                 my ($first,$responsenum);
                   8584:3):                 if ($randomorder || $randompick) {
                   8585:3):                     $responsenum = $respnumlookup{$missing-1};
                   8586:3):                     $first = $startline{$missing-1};
                   8587:3):                 } else {
                   8588:3):                     $responsenum = $missing-1;
                   8589:3):                     $first = $first_bubble_line{$responsenum};
                   8590:3):                 }
                   8591:3):                 if (!defined($first)) { next; }
                   8592:3):                 $lastbubble = $first + $bubble_lines_per_response{$responsenum};
1.505     raeburn  8593:             }
                   8594:             if ($lastbubble > $max_bubble) { next; }
1.157     albertel 8595: 	    push(@to_correct,$missing);
                   8596: 	}
                   8597: 	if (@to_correct) {
                   8598: 	    &scantron_get_correction($r,$i,$scan_record,\%scantron_config,
1.596.2.12.2.  6(raebur 8599:3): 				     $line,'missingbubble',\@to_correct,
                   8600:3):                                      $randomorder,$randompick,\%respnumlookup,
                   8601:3):                                      \%startline);
1.157     albertel 8602: 	    return (1,$currentphase);
                   8603: 	}
                   8604: 
                   8605:     }
                   8606:     return (0,$currentphase+1);
                   8607: }
                   8608: 
1.596.2.12.2.  (raeburn 8609:): sub hand_bubble_option {
                   8610:):     my (undef, undef, $sequence) =
                   8611:):         &Apache::lonnet::decode_symb($env{'form.selectpage'});
                   8612:):     return if ($sequence eq '');
                   8613:):     my $navmap = Apache::lonnavmaps::navmap->new();
                   8614:):     unless (ref($navmap)) {
                   8615:):         return;
                   8616:):     }
                   8617:):     my $needs_hand_bubbles;
                   8618:):     my $map=$navmap->getResourceByUrl($sequence);
                   8619:):     my @resources=$navmap->retrieveResources($map,\&scantron_filter,1,0);
                   8620:):     foreach my $res (@resources) {
                   8621:):         if (ref($res)) {
                   8622:):             if ($res->is_problem()) {
                   8623:):                 my $partlist = $res->parts();
                   8624:):                 foreach my $part (@{ $partlist }) {
                   8625:):                     my @types = $res->responseType($part);
                   8626:):                     if (grep(/^(chem|essay|image|formula|math|string|functionplot)$/,@types)) {
                   8627:):                         $needs_hand_bubbles = 1;
                   8628:):                         last;
                   8629:):                     }
                   8630:):                 }
                   8631:):             }
                   8632:):         }
                   8633:):     }
                   8634:):     if ($needs_hand_bubbles) {
                   8635:):         my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
                   8636:):         my $bubbles_per_row = &bubblesheet_bubbles_per_row(\%scantron_config);
                   8637:):         return &mt('The sequence to be graded contains response types which are handgraded.').'<p>'.
                   8638:):                &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 />').
                   8639:):                '<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;'.
          8(raebur 8640:4):                '<label><input type="radio" name="scantron_lastbubblepoints" value="0" />'.&mt('0 points').'</label></p>';
          (raeburn 8641:):     }
                   8642:):     return;
                   8643:): }
1.423     albertel 8644: 
1.82      albertel 8645: sub scantron_process_students {
1.75      albertel 8646:     my ($r) = @_;
1.513     foxr     8647: 
1.257     albertel 8648:     my (undef,undef,$sequence)=&Apache::lonnet::decode_symb($env{'form.selectpage'});
1.324     albertel 8649:     my ($symb)=&get_symb($r);
1.513     foxr     8650:     if (!$symb) {
                   8651: 	return '';
                   8652:     }
1.324     albertel 8653:     my $default_form_data=&defaultFormData($symb);
1.82      albertel 8654: 
1.257     albertel 8655:     my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
1.596.2.12.2.  6(raebur 8656:3):     my $bubbles_per_row = &bubblesheet_bubbles_per_row(\%scantron_config);
1.157     albertel 8657:     my ($scanlines,$scan_data)=&scantron_getfile();
1.82      albertel 8658:     my $classlist=&Apache::loncoursedata::get_classlist();
                   8659:     my %idmap=&username_to_idmap($classlist);
1.132     bowersj2 8660:     my $navmap=Apache::lonnavmaps::navmap->new();
1.582     raeburn  8661:     unless (ref($navmap)) {
                   8662:         $r->print(&navmap_errormsg());
                   8663:         return '';
1.596.2.12.2.  6(raebur 8664:3):     }
1.83      albertel 8665:     my $map=$navmap->getResourceByUrl($sequence);
1.596.2.12.2.  6(raebur 8666:3):     my ($randomorder,$randompick,@master_seq,%symb_to_resource,%grader_partids_by_symb,
                   8667:3):         %grader_randomlists_by_symb);
          1(raebur 8668:2):     if (ref($map)) {
                   8669:2):         $randomorder = $map->randomorder();
          6(raebur 8670:3):         $randompick = $map->randompick();
                   8671:3):     } else {
                   8672:3):         $r->print(&navmap_errormsg());
                   8673:3):         return '';
          1(raebur 8674:2):     }
          6(raebur 8675:3):     my $nav_error;
1.83      albertel 8676:     my @resources=$navmap->retrieveResources($map,\&scantron_filter,1,0);
1.596.2.12.2.  6(raebur 8677:3):     if ($randomorder || $randompick) {
                   8678:3):         $nav_error = &get_master_seq(\@resources,\@master_seq,\%symb_to_resource);
                   8679:3):         if ($nav_error) {
                   8680:3):             $r->print(&navmap_errormsg());
                   8681:3):             return '';
1.586     raeburn  8682:         }
                   8683:     }
1.596.2.12.2.  6(raebur 8684:3):     &graders_resources_pass(\@resources,\%grader_partids_by_symb,
                   8685:3):                             \%grader_randomlists_by_symb,$bubbles_per_row);
1.557     raeburn  8686: 
1.554     raeburn  8687:     my ($uname,$udom);
1.82      albertel 8688:     my $result= <<SCANTRONFORM;
1.81      albertel 8689: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="scantronupload">
                   8690:   <input type="hidden" name="command" value="scantron_configphase" />
                   8691:   $default_form_data
                   8692: SCANTRONFORM
1.82      albertel 8693:     $r->print($result);
                   8694: 
                   8695:     my @delayqueue;
1.542     raeburn  8696:     my (%completedstudents,%scandata);
1.140     albertel 8697:     
1.520     www      8698:     my $lock=&Apache::lonnet::set_lock(&mt('Grading bubblesheet exam'));
1.200     albertel 8699:     my $count=&get_todo_count($scanlines,$scan_data);
1.596.2.12.2.  (raeburn 8700:):     my %prog_state=&Apache::lonhtmlcommon::Create_PrgWin($r,$count);
1.140     albertel 8701:     &Apache::lonhtmlcommon::Update_PrgWin($r,\%prog_state,
                   8702: 					  'Processing first student');
1.542     raeburn  8703:     $r->print('<br />');
1.140     albertel 8704:     my $start=&Time::HiRes::time();
1.158     albertel 8705:     my $i=-1;
1.542     raeburn  8706:     my $started;
1.447     foxr     8707: 
1.596.2.12.2.  (raeburn 8708:):     &scantron_get_maxbubble(\$nav_error,\%scantron_config); # Need the bubble lines array to parse.
1.582     raeburn  8709:     if ($nav_error) {
                   8710:         $r->print(&navmap_errormsg());
                   8711:         return '';
                   8712:     }
                   8713: 
1.513     foxr     8714:     # If an ssi failed in scantron_get_maxbubble, put an error message out to
                   8715:     # the user and return.
                   8716: 
                   8717:     if ($ssi_error) {
                   8718: 	$r->print("</form>");
                   8719: 	&ssi_print_error($r);
                   8720: 	$r->print(&show_grading_menu_form($symb));
1.520     www      8721:         &Apache::lonnet::remove_lock($lock);
1.513     foxr     8722: 	return '';		# Dunno why the other returns return '' rather than just returning.
                   8723:     }
1.447     foxr     8724: 
1.542     raeburn  8725:     my %lettdig = &letter_to_digits();
                   8726:     my $numletts = scalar(keys(%lettdig));
1.596.2.12.2.  6(raebur 8727:3):     my %orderedforcode;
1.542     raeburn  8728: 
1.157     albertel 8729:     while ($i<$scanlines->{'count'}) {
                   8730:  	($uname,$udom)=('','');
                   8731:  	$i++;
1.200     albertel 8732:  	my $line=&scantron_get_line($scanlines,$scan_data,$i);
1.157     albertel 8733:  	if ($line=~/^[\s\cz]*$/) { next; }
1.200     albertel 8734: 	if ($started) {
                   8735: 	    &Apache::lonhtmlcommon::Increment_PrgWin($r,\%prog_state,
                   8736: 						     'last student');
                   8737: 	}
                   8738: 	$started=1;
1.596.2.12.2.  6(raebur 8739:3):         my %respnumlookup = ();
                   8740:3):         my %startline = ();
                   8741:3):         my $total;
1.157     albertel 8742:  	my $scan_record=&scantron_parse_scanline($line,$i,\%scantron_config,
1.596.2.12.2.  6(raebur 8743:3):  						 $scan_data,undef,\%idmap,$randomorder,
                   8744:3):                                                  $randompick,$sequence,\@master_seq,
                   8745:3):                                                  \%symb_to_resource,\%grader_partids_by_symb,
                   8746:3):                                                  \%orderedforcode,\%respnumlookup,\%startline,
                   8747:3):                                                  \$total);
1.157     albertel 8748:  	unless ($uname=&scantron_find_student($scan_record,$scan_data,
                   8749:  					      \%idmap,$i)) {
                   8750:   	    &scantron_add_delay(\@delayqueue,$line,
                   8751:  				'Unable to find a student that matches',1);
                   8752:  	    next;
                   8753:   	}
                   8754:  	if (exists $completedstudents{$uname}) {
                   8755:  	    &scantron_add_delay(\@delayqueue,$line,
                   8756:  				'Student '.$uname.' has multiple sheets',2);
                   8757:  	    next;
                   8758:  	}
1.596.2.12.2.  1(raebur 8759:2):         my $usec = $classlist->{$uname}->[&Apache::loncoursedata::CL_SECTION];
                   8760:2):         my $user = $uname.':'.$usec;
1.157     albertel 8761:   	($uname,$udom)=split(/:/,$uname);
1.330     albertel 8762: 
1.596.2.12.2.  1(raebur 8763:2):         my $scancode;
                   8764:2):         if ((exists($scan_record->{'scantron.CODE'})) &&
                   8765:2):             (&Apache::lonnet::validCODE($scan_record->{'scantron.CODE'}))) {
                   8766:2):             $scancode = $scan_record->{'scantron.CODE'};
                   8767:2):         } else {
                   8768:2):             $scancode = '';
                   8769:2):         }
                   8770:2): 
                   8771:2):         my @mapresources = @resources;
          6(raebur 8772:3):         if ($randomorder || $randompick) {
          1(raebur 8773:2):             @mapresources =
          6(raebur 8774:3):                 &users_order($user,$scancode,$sequence,\@master_seq,\%symb_to_resource,
                   8775:3):                              \%orderedforcode);
          1(raebur 8776:2):         }
1.586     raeburn  8777:         my (%partids_by_symb,$res_error);
1.596.2.12.2.  1(raebur 8778:2):         foreach my $resource (@mapresources) {
1.586     raeburn  8779:             my $ressymb;
                   8780:             if (ref($resource)) {
                   8781:                 $ressymb = $resource->symb();
                   8782:             } else {
                   8783:                 $res_error = 1;
                   8784:                 last;
                   8785:             }
1.557     raeburn  8786:             if ((exists($grader_randomlists_by_symb{$ressymb})) ||
                   8787:                 (ref($grader_partids_by_symb{$ressymb}) ne 'ARRAY')) {
                   8788:                 my ($analysis,$parts) =
1.596.2.12.2.  (raeburn 8789:):                     &scantron_partids_tograde($resource,$env{'request.course.id'},
                   8790:):                                               $uname,$udom,undef,$bubbles_per_row);
1.557     raeburn  8791:                 $partids_by_symb{$ressymb} = $parts;
                   8792:             } else {
                   8793:                 $partids_by_symb{$ressymb} = $grader_partids_by_symb{$ressymb};
                   8794:             }
1.554     raeburn  8795:         }
                   8796: 
1.586     raeburn  8797:         if ($res_error) {
                   8798:             &scantron_add_delay(\@delayqueue,$line,
                   8799:                                 'An error occurred while grading student '.$uname,2);
                   8800:             next;
                   8801:         }
                   8802: 
1.330     albertel 8803: 	&Apache::lonxml::clear_problem_counter();
1.514     raeburn  8804:   	&Apache::lonnet::appenv($scan_record);
1.376     albertel 8805: 
                   8806: 	if (&scantron_clear_skip($scanlines,$scan_data,$i)) {
                   8807: 	    &scantron_putfile($scanlines,$scan_data);
                   8808: 	}
1.161     albertel 8809: 	
1.542     raeburn  8810:         if (&grade_student_bubbles($r,$uname,$udom,$scan_record,$scancode,
1.596.2.12.2.  1(raebur 8811:2):                                    \@mapresources,\%partids_by_symb,
          6(raebur 8812:3):                                    $bubbles_per_row,$randomorder,$randompick,
                   8813:3):                                    \%respnumlookup,\%startline) 
                   8814:3):             eq 'ssi_error') {
1.542     raeburn  8815:             $ssi_error = 0; # So end of handler error message does not trigger.
                   8816:             $r->print("</form>");
                   8817:             &ssi_print_error($r);
                   8818:             $r->print(&show_grading_menu_form($symb));
                   8819:             &Apache::lonnet::remove_lock($lock);
                   8820:             return '';      # Why return ''?  Beats me.
                   8821:         }
1.513     foxr     8822: 
1.596.2.12.2.  6(raebur 8823:3):         if (($scancode) && ($randomorder || $randompick)) {
                   8824:3):             my $parmresult =
                   8825:3):                 &Apache::lonparmset::storeparm_by_symb($symb,
                   8826:3):                                                        '0_examcode',2,$scancode,
                   8827:3):                                                        'string_examcode',$uname,
                   8828:3):                                                        $udom);
                   8829:3):         }
1.140     albertel 8830: 	$completedstudents{$uname}={'line'=>$line};
1.542     raeburn  8831:         if ($env{'form.verifyrecord'}) {
                   8832:             my $lastpos = $env{'form.scantron_maxbubble'}*$scantron_config{'Qlength'};
1.596.2.12.2.  6(raebur 8833:3):             if ($randompick) {
                   8834:3):                 if ($total) {
                   8835:3):                     $lastpos = $total*$scantron_config{'Qlength'};
                   8836:3):                 }
                   8837:3):             }
                   8838:3): 
1.542     raeburn  8839:             my $studentdata = substr($line,$scantron_config{'Qstart'}-1,$lastpos);
                   8840:             chomp($studentdata);
                   8841:             $studentdata =~ s/\r$//;
                   8842:             my $studentrecord = '';
                   8843:             my $counter = -1;
1.596.2.12.2.  1(raebur 8844:2):             foreach my $resource (@mapresources) {
1.554     raeburn  8845:                 my $ressymb = $resource->symb();
1.542     raeburn  8846:                 ($counter,my $recording) =
                   8847:                     &verify_scantron_grading($resource,$udom,$uname,$env{'request.course.id'},
1.554     raeburn  8848:                                              $counter,$studentdata,$partids_by_symb{$ressymb},
1.596.2.12.2.  6(raebur 8849:3):                                              \%scantron_config,\%lettdig,$numletts,$randomorder,
                   8850:3):                                              $randompick,\%respnumlookup,\%startline);
1.542     raeburn  8851:                 $studentrecord .= $recording;
                   8852:             }
                   8853:             if ($studentrecord ne $studentdata) {
1.554     raeburn  8854:                 &Apache::lonxml::clear_problem_counter();
                   8855:                 if (&grade_student_bubbles($r,$uname,$udom,$scan_record,$scancode,
1.596.2.12.2.  1(raebur 8856:2):                                            \@mapresources,\%partids_by_symb,
          6(raebur 8857:3):                                            $bubbles_per_row,$randomorder,$randompick,
                   8858:3):                                            \%respnumlookup,\%startline)
                   8859:3):                     eq 'ssi_error') {
1.554     raeburn  8860:                     $ssi_error = 0; # So end of handler error message does not trigger.
                   8861:                     $r->print("</form>");
                   8862:                     &ssi_print_error($r);
                   8863:                     $r->print(&show_grading_menu_form($symb));
                   8864:                     &Apache::lonnet::remove_lock($lock);
                   8865:                     delete($completedstudents{$uname});
                   8866:                     return '';
                   8867:                 }
1.542     raeburn  8868:                 $counter = -1;
                   8869:                 $studentrecord = '';
1.596.2.12.2.  1(raebur 8870:2):                 foreach my $resource (@mapresources) {
1.554     raeburn  8871:                     my $ressymb = $resource->symb();
1.542     raeburn  8872:                     ($counter,my $recording) =
                   8873:                         &verify_scantron_grading($resource,$udom,$uname,$env{'request.course.id'},
1.554     raeburn  8874:                                                  $counter,$studentdata,$partids_by_symb{$ressymb},
1.596.2.12.2.  6(raebur 8875:3):                                                  \%scantron_config,\%lettdig,$numletts,
                   8876:3):                                                  $randomorder,$randompick,\%respnumlookup,
                   8877:3):                                                  \%startline);
1.542     raeburn  8878:                     $studentrecord .= $recording;
                   8879:                 }
                   8880:                 if ($studentrecord ne $studentdata) {
1.596.2.6  raeburn  8881:                     $r->print('<p><span class="LC_warning">');
1.542     raeburn  8882:                     if ($scancode eq '') {
1.596.2.6  raeburn  8883:                         $r->print(&mt('Mismatch grading bubblesheet for user: [_1] with ID: [_2].',
1.542     raeburn  8884:                                   $uname.':'.$udom,$scan_record->{'scantron.ID'}));
                   8885:                     } else {
1.596.2.6  raeburn  8886:                         $r->print(&mt('Mismatch grading bubblesheet for user: [_1] with ID: [_2] and CODE: [_3].',
1.542     raeburn  8887:                                   $uname.':'.$udom,$scan_record->{'scantron.ID'},$scancode));
                   8888:                     }
                   8889:                     $r->print('</span><br />'.&Apache::loncommon::start_data_table()."\n".
                   8890:                               &Apache::loncommon::start_data_table_header_row()."\n".
                   8891:                               '<th>'.&mt('Source').'</th><th>'.&mt('Bubbled responses').'</th>'.
                   8892:                               &Apache::loncommon::end_data_table_header_row()."\n".
                   8893:                               &Apache::loncommon::start_data_table_row().
1.596.2.6  raeburn  8894:                               '<td>'.&mt('Bubblesheet').'</td>'.
1.596.2.12.2.  4(raebur 8895:3):                               '<td><span class="LC_nobreak" style="white-space: pre;"><tt>'.$studentdata.'</tt></span></td>'.
1.542     raeburn  8896:                               &Apache::loncommon::end_data_table_row().
                   8897:                               &Apache::loncommon::start_data_table_row().
1.596.2.6  raeburn  8898:                               '<td>'.&mt('Stored submissions').'</td>'.
1.596.2.12.2.  4(raebur 8899:3):                               '<td><span class="LC_nobreak" style="white-space: pre;"><tt>'.$studentrecord.'</tt></span></td>'."\n".
1.542     raeburn  8900:                               &Apache::loncommon::end_data_table_row().
                   8901:                               &Apache::loncommon::end_data_table().'</p>');
                   8902:                 } else {
                   8903:                     $r->print('<br /><span class="LC_warning">'.
                   8904:                              &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 />'.
                   8905:                              &mt("As a consequence, this user's submission history records two tries.").
                   8906:                                  '</span><br />');
                   8907:                 }
                   8908:             }
                   8909:         }
1.543     raeburn  8910:         if (&Apache::loncommon::connection_aborted($r)) { last; }
1.140     albertel 8911:     } continue {
1.330     albertel 8912: 	&Apache::lonxml::clear_problem_counter();
1.552     raeburn  8913: 	&Apache::lonnet::delenv('scantron.');
1.82      albertel 8914:     }
1.140     albertel 8915:     &Apache::lonhtmlcommon::Close_PrgWin($r,\%prog_state);
1.520     www      8916:     &Apache::lonnet::remove_lock($lock);
1.172     albertel 8917: #    my $lasttime = &Time::HiRes::time()-$start;
                   8918: #    $r->print("<p>took $lasttime</p>");
1.140     albertel 8919: 
1.200     albertel 8920:     $r->print("</form>");
1.324     albertel 8921:     $r->print(&show_grading_menu_form($symb));
1.157     albertel 8922:     return '';
1.75      albertel 8923: }
1.157     albertel 8924: 
1.557     raeburn  8925: sub graders_resources_pass {
1.596.2.12.2.  (raeburn 8926:):     my ($resources,$grader_partids_by_symb,$grader_randomlists_by_symb,
                   8927:):         $bubbles_per_row) = @_;
1.557     raeburn  8928:     if ((ref($resources) eq 'ARRAY') && (ref($grader_partids_by_symb)) && 
                   8929:         (ref($grader_randomlists_by_symb) eq 'HASH')) {
                   8930:         foreach my $resource (@{$resources}) {
                   8931:             my $ressymb = $resource->symb();
                   8932:             my ($analysis,$parts) =
                   8933:                 &scantron_partids_tograde($resource,$env{'request.course.id'},
1.596.2.12.2.  (raeburn 8934:):                                           $env{'user.name'},$env{'user.domain'},
                   8935:):                                           1,$bubbles_per_row);
1.557     raeburn  8936:             $grader_partids_by_symb->{$ressymb} = $parts;
                   8937:             if (ref($analysis) eq 'HASH') {
                   8938:                 if (ref($analysis->{'parts_withrandomlist'}) eq 'ARRAY') {
                   8939:                     $grader_randomlists_by_symb->{$ressymb} =
                   8940:                         $analysis->{'parts_withrandomlist'};
                   8941:                 }
                   8942:             }
                   8943:         }
                   8944:     }
                   8945:     return;
                   8946: }
                   8947: 
1.596.2.12.2.  1(raebur 8948:2): =pod
                   8949:2): 
                   8950:2): =item users_order
                   8951:2): 
                   8952:2):   Returns array of resources in current map, ordered based on either CODE,
                   8953:2):   if this is a CODEd exam, or based on student's identity if this is a
                   8954:2):   "NAMEd" exam.
                   8955:2): 
          6(raebur 8956:3):   Should be used when randomorder and/or randompick applied when the 
                   8957:3):   corresponding exam was printed, prior to students completing bubblesheets 
                   8958:3):   for the version of the exam the student received.
          1(raebur 8959:2): 
                   8960:2): =cut
                   8961:2): 
                   8962:2): sub users_order  {
          6(raebur 8963:3):     my ($user,$scancode,$mapurl,$master_seq,$symb_to_resource,$orderedforcode) = @_;
          1(raebur 8964:2):     my @mapresources;
          6(raebur 8965:3):     unless ((ref($master_seq) eq 'ARRAY') && (ref($symb_to_resource) eq 'HASH')) {
          1(raebur 8966:2):         return @mapresources;
                   8967:2):     }
          6(raebur 8968:3):     if ($scancode) {
                   8969:3):         if ((ref($orderedforcode) eq 'HASH') && (ref($orderedforcode->{$scancode}) eq 'ARRAY')) {
                   8970:3):             @mapresources = @{$orderedforcode->{$scancode}};
                   8971:3):         } else {
                   8972:3):             $env{'form.CODE'} = $scancode;
                   8973:3):             my $actual_seq =
                   8974:3):                 &Apache::lonprintout::master_seq_to_person_seq($mapurl,
                   8975:3):                                                                $master_seq,
                   8976:3):                                                                $user,$scancode,1);
                   8977:3):             if (ref($actual_seq) eq 'ARRAY') {
                   8978:3):                 @mapresources = map { $symb_to_resource->{$_}; } @{$actual_seq};
                   8979:3):                 if (ref($orderedforcode) eq 'HASH') {
                   8980:3):                     if (@mapresources > 0) {
                   8981:3):                         $orderedforcode->{$scancode} = \@mapresources;
                   8982:3):                     }
                   8983:3):                 }
                   8984:3):             }
                   8985:3):             delete($env{'form.CODE'});
          1(raebur 8986:2):         }
                   8987:2):     } else {
                   8988:2):         my $actual_seq =
                   8989:2):             &Apache::lonprintout::master_seq_to_person_seq($mapurl,
                   8990:2):                                                            $master_seq,
          5(raebur 8991:3):                                                            $user,undef,1);
          1(raebur 8992:2):         if (ref($actual_seq) eq 'ARRAY') {
                   8993:2):             @mapresources =
                   8994:2):                 map { $symb_to_resource->{$_}; } @{$actual_seq};
                   8995:2):         }
          6(raebur 8996:3):     }
                   8997:3):     return @mapresources;
          1(raebur 8998:2): }
                   8999:2): 
1.542     raeburn  9000: sub grade_student_bubbles {
1.596.2.12.2.  6(raebur 9001:3):     my ($r,$uname,$udom,$scan_record,$scancode,$resources,$parts,$bubbles_per_row,
                   9002:3):         $randomorder,$randompick,$respnumlookup,$startline) = @_;
                   9003:3):     my $uselookup = 0;
                   9004:3):     if (($randomorder || $randompick) && (ref($respnumlookup) eq 'HASH') &&
                   9005:3):         (ref($startline) eq 'HASH')) {
                   9006:3):         $uselookup = 1;
                   9007:3):     }
                   9008:3): 
1.554     raeburn  9009:     if (ref($resources) eq 'ARRAY') {
                   9010:         my $count = 0;
                   9011:         foreach my $resource (@{$resources}) {
                   9012:             my $ressymb = $resource->symb();
                   9013:             my %form = ('submitted'      => 'scantron',
                   9014:                         'grade_target'   => 'grade',
                   9015:                         'grade_username' => $uname,
                   9016:                         'grade_domain'   => $udom,
                   9017:                         'grade_courseid' => $env{'request.course.id'},
                   9018:                         'grade_symb'     => $ressymb,
                   9019:                         'CODE'           => $scancode
                   9020:                        );
1.596.2.12.2.  (raeburn 9021:):             if ($bubbles_per_row ne '') {
                   9022:):                 $form{'bubbles_per_row'} = $bubbles_per_row;
                   9023:):             }
                   9024:):             if ($env{'form.scantron_lastbubblepoints'} ne '') {
                   9025:):                 $form{'scantron_lastbubblepoints'} = $env{'form.scantron_lastbubblepoints'};
                   9026:):             }
1.554     raeburn  9027:             if (ref($parts) eq 'HASH') {
                   9028:                 if (ref($parts->{$ressymb}) eq 'ARRAY') {
                   9029:                     foreach my $part (@{$parts->{$ressymb}}) {
1.596.2.12.2.  6(raebur 9030:3):                         if ($uselookup) {
                   9031:3):                             $form{'scantron_questnum_start.'.$part} = $startline->{$count} + 1;
                   9032:3):                         } else {
                   9033:3):                             $form{'scantron_questnum_start.'.$part} =
                   9034:3):                                 1+$env{'form.scantron.first_bubble_line.'.$count};
                   9035:3):                         }
1.554     raeburn  9036:                         $count++;
                   9037:                     }
                   9038:                 }
                   9039:             }
                   9040:             my $result=&ssi_with_retries($resource->src(),$ssi_retries,%form);
                   9041:             return 'ssi_error' if ($ssi_error);
                   9042:             last if (&Apache::loncommon::connection_aborted($r));
                   9043:         }
1.542     raeburn  9044:     }
                   9045:     return;
                   9046: }
                   9047: 
1.157     albertel 9048: sub scantron_upload_scantron_data {
                   9049:     my ($r)=@_;
1.565     raeburn  9050:     my $dom = $env{'request.role.domain'};
                   9051:     my $domdesc = &Apache::lonnet::domain($dom,'description');
                   9052:     $r->print(&Apache::loncommon::coursebrowser_javascript($dom));
1.157     albertel 9053:     my $select_link=&Apache::loncommon::selectcourse_link('rules','courseid',
1.181     albertel 9054: 							  'domainid',
1.565     raeburn  9055: 							  'coursename',$dom);
                   9056:     my $syllabuslink = '<a href="javascript:ToSyllabus();">'.&mt('Syllabus').'</a>'.
1.596.2.12.2.  (raeburn 9057:):                        ('&nbsp'x2).&mt('(shows course personnel)');
                   9058:):     my ($symb) = &get_symb($r,1);
                   9059:):     my $default_form_data=&defaultFormData($symb);
1.579     raeburn  9060:     my $nofile_alert = &mt('Please use the browse button to select a file from your local directory.');
1.596.2.12.2.  7(raebur 9061:6):     &js_escape(\$nofile_alert);
1.579     raeburn  9062:     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.596.2.12.2.  6(raebur 9063:6):     &js_escape(\$nocourseid_alert);
1.492     albertel 9064:     $r->print('
1.157     albertel 9065: <script type="text/javascript" language="javascript">
                   9066:     function checkUpload(formname) {
                   9067: 	if (formname.upfile.value == "") {
1.579     raeburn  9068: 	    alert("'.$nofile_alert.'");
1.157     albertel 9069: 	    return false;
                   9070: 	}
1.565     raeburn  9071:         if (formname.courseid.value == "") {
1.579     raeburn  9072:             alert("'.$nocourseid_alert.'");
1.565     raeburn  9073:             return false;
                   9074:         }
1.157     albertel 9075: 	formname.submit();
                   9076:     }
1.565     raeburn  9077: 
                   9078:     function ToSyllabus() {
                   9079:         var cdom = '."'$dom'".';
                   9080:         var cnum = document.rules.courseid.value;
                   9081:         if (cdom == "" || cdom == null) {
                   9082:             return;
                   9083:         }
                   9084:         if (cnum == "" || cnum == null) {
                   9085:            return;
                   9086:         }
                   9087:         syllwin=window.open("/public/"+cdom+"/"+cnum+"/syllabus","LONCAPASyllabus",
                   9088:                             "height=350,width=350,scrollbars=yes,menubar=no");
                   9089:         return;
                   9090:     }
                   9091: 
1.157     albertel 9092: </script>
                   9093: 
1.596.2.4  raeburn  9094: <h3>'.&mt('Send bubblesheet data to a course').'</h3>
1.566     raeburn  9095: 
1.492     albertel 9096: <form enctype="multipart/form-data" action="/adm/grades" name="rules" method="post">
1.565     raeburn  9097: '.$default_form_data.
                   9098:   &Apache::lonhtmlcommon::start_pick_box().
                   9099:   &Apache::lonhtmlcommon::row_title(&mt('Course ID')).
                   9100:   '<input name="courseid" type="text" size="30" />'.$select_link.
                   9101:   &Apache::lonhtmlcommon::row_closure().
                   9102:   &Apache::lonhtmlcommon::row_title(&mt('Course Name')).
                   9103:   '<input name="coursename" type="text" size="30" />'.$syllabuslink.
                   9104:   &Apache::lonhtmlcommon::row_closure().
                   9105:   &Apache::lonhtmlcommon::row_title(&mt('Domain')).
                   9106:   '<input name="domainid" type="hidden" />'.$domdesc.
                   9107:   &Apache::lonhtmlcommon::row_closure().
                   9108:   &Apache::lonhtmlcommon::row_title(&mt('File to upload')).
                   9109:   '<input type="file" name="upfile" size="50" />'.
                   9110:   &Apache::lonhtmlcommon::row_closure(1).
                   9111:   &Apache::lonhtmlcommon::end_pick_box().'<br />
                   9112: 
1.492     albertel 9113: <input name="command" value="scantronupload_save" type="hidden" />
1.589     bisitz   9114: <input type="button" onclick="javascript:checkUpload(this.form);" value="'.&mt('Upload Bubblesheet Data').'" />
1.157     albertel 9115: </form>
1.492     albertel 9116: ');
1.157     albertel 9117:     return '';
                   9118: }
                   9119: 
1.423     albertel 9120: 
1.157     albertel 9121: sub scantron_upload_scantron_data_save {
                   9122:     my($r)=@_;
1.324     albertel 9123:     my ($symb)=&get_symb($r,1);
1.182     albertel 9124:     my $doanotherupload=
                   9125: 	'<br /><form action="/adm/grades" method="post">'."\n".
                   9126: 	'<input type="hidden" name="command" value="scantronupload" />'."\n".
1.492     albertel 9127: 	'<input type="submit" name="submit" value="'.&mt('Do Another Upload').'" />'."\n".
1.182     albertel 9128: 	'</form>'."\n";
1.257     albertel 9129:     if (!&Apache::lonnet::allowed('usc',$env{'form.domainid'}) &&
1.162     albertel 9130: 	!&Apache::lonnet::allowed('usc',
1.257     albertel 9131: 			    $env{'form.domainid'}.'_'.$env{'form.courseid'})) {
1.575     www      9132: 	$r->print(&mt("You are not allowed to upload bubblesheet data to the requested course.")."<br />");
1.182     albertel 9133: 	if ($symb) {
1.324     albertel 9134: 	    $r->print(&show_grading_menu_form($symb));
1.182     albertel 9135: 	} else {
                   9136: 	    $r->print($doanotherupload);
                   9137: 	}
1.162     albertel 9138: 	return '';
                   9139:     }
1.257     albertel 9140:     my %coursedata=&Apache::lonnet::coursedescription($env{'form.domainid'}.'_'.$env{'form.courseid'});
1.568     raeburn  9141:     my $uploadedfile;
1.596.2.12.2.  5(raebur 9142:3):     $r->print('<p>'.&mt("Uploading file to [_1]",$coursedata{'description'}).'</p>');
1.257     albertel 9143:     if (length($env{'form.upfile'}) < 2) {
1.596.2.12.2.  5(raebur 9144:3):         $r->print(
                   9145:3):             &Apache::lonhtmlcommon::confirm_success(
                   9146:3):                 &mt('The file: [_1] you attempted to upload contained no information. Please check that you entered the correct filename.',
                   9147:3):                         '<span class="LC_filename">'.&HTML::Entities::encode($env{'form.upfile.filename'},'<>&"').'</span>'),1));
1.183     albertel 9148:     } else {
1.568     raeburn  9149:         my $result = 
                   9150:             &Apache::lonnet::userfileupload('upfile','','scantron','','','',
                   9151:                                             $env{'form.courseid'},$env{'form.domainid'});
                   9152: 	if ($result =~ m{^/uploaded/}) {
1.596.2.12.2.  5(raebur 9153:3):             $r->print(
                   9154:3):                 &Apache::lonhtmlcommon::confirm_success(&mt('Upload successful')).'<br />'.
                   9155:3):                 &mt('Uploaded [_1] bytes of data into location: [_2]',
                   9156:3):                         (length($env{'form.upfile'})-1),
                   9157:3):                         '<span class="LC_filename">'.$result.'</span>'));
1.568     raeburn  9158:             ($uploadedfile) = ($result =~ m{/([^/]+)$});
1.567     raeburn  9159:             $r->print(&validate_uploaded_scantron_file($env{'form.domainid'},
1.568     raeburn  9160:                                                        $env{'form.courseid'},$uploadedfile));
1.210     albertel 9161: 	} else {
1.596.2.12.2.  5(raebur 9162:3):             $r->print(
                   9163:3):                 &Apache::lonhtmlcommon::confirm_success(&mt('Upload failed'),1).'<br />'.
                   9164:3):                     &mt('An error ([_1]) occurred when attempting to upload the file: [_2]',
                   9165:3):                           $result,
1.568     raeburn  9166: 			  '<span class="LC_filename">'.&HTML::Entities::encode($env{'form.upfile.filename'},'<>&"').'</span>'));
1.183     albertel 9167: 	}
                   9168:     }
1.174     albertel 9169:     if ($symb) {
1.209     ng       9170: 	$r->print(&scantron_selectphase($r,$uploadedfile));
1.174     albertel 9171:     } else {
1.182     albertel 9172: 	$r->print($doanotherupload);
1.174     albertel 9173:     }
1.157     albertel 9174:     return '';
                   9175: }
                   9176: 
1.567     raeburn  9177: sub validate_uploaded_scantron_file {
                   9178:     my ($cdom,$cname,$fname) = @_;
                   9179:     my $scanlines=&Apache::lonnet::getfile('/uploaded/'.$cdom.'/'.$cname.'/'.$fname);
                   9180:     my @lines;
                   9181:     if ($scanlines ne '-1') {
                   9182:         @lines=split("\n",$scanlines,-1);
                   9183:     }
                   9184:     my $output;
                   9185:     if (@lines) {
                   9186:         my (%counts,$max_match_format);
1.596.2.12.2.  5(raebur 9187:3):         my ($found_match_count,$max_match_count,$max_match_pct) = (0,0,0);
1.567     raeburn  9188:         my $classlist = &Apache::loncoursedata::get_classlist($cdom,$cname);
                   9189:         my %idmap = &username_to_idmap($classlist);
                   9190:         foreach my $key (keys(%idmap)) {
                   9191:             my $lckey = lc($key);
                   9192:             $idmap{$lckey} = $idmap{$key};
                   9193:         }
                   9194:         my %unique_formats;
                   9195:         my @formatlines = &get_scantronformat_file();
                   9196:         foreach my $line (@formatlines) {
                   9197:             chomp($line);
                   9198:             my @config = split(/:/,$line);
                   9199:             my $idstart = $config[5];
                   9200:             my $idlength = $config[6];
                   9201:             if (($idstart ne '') && ($idlength > 0)) {
                   9202:                 if (ref($unique_formats{$idstart.':'.$idlength}) eq 'ARRAY') {
                   9203:                     push(@{$unique_formats{$idstart.':'.$idlength}},$config[0].':'.$config[1]); 
                   9204:                 } else {
                   9205:                     $unique_formats{$idstart.':'.$idlength} = [$config[0].':'.$config[1]];
                   9206:                 }
                   9207:             }
                   9208:         }
                   9209:         foreach my $key (keys(%unique_formats)) {
                   9210:             my ($idstart,$idlength) = split(':',$key);
                   9211:             %{$counts{$key}} = (
                   9212:                                'found'   => 0,
                   9213:                                'total'   => 0,
                   9214:                               );
                   9215:             foreach my $line (@lines) {
                   9216:                 next if ($line =~ /^#/);
                   9217:                 next if ($line =~ /^[\s\cz]*$/);
                   9218:                 my $id = substr($line,$idstart-1,$idlength);
                   9219:                 $id = lc($id);
                   9220:                 if (exists($idmap{$id})) {
                   9221:                     $counts{$key}{'found'} ++;
                   9222:                 }
                   9223:                 $counts{$key}{'total'} ++;
                   9224:             }
                   9225:             if ($counts{$key}{'total'}) {
                   9226:                 my $percent_match = (100*$counts{$key}{'found'})/($counts{$key}{'total'});
                   9227:                 if (($max_match_format eq '') || ($percent_match > $max_match_pct)) {
                   9228:                     $max_match_pct = $percent_match;
                   9229:                     $max_match_format = $key;
1.596.2.12.2.  5(raebur 9230:3):                     $found_match_count = $counts{$key}{'found'};
1.567     raeburn  9231:                     $max_match_count = $counts{$key}{'total'};
                   9232:                 }
                   9233:             }
                   9234:         }
                   9235:         if (ref($unique_formats{$max_match_format}) eq 'ARRAY') {
                   9236:             my $format_descs;
                   9237:             my $numwithformat = @{$unique_formats{$max_match_format}};
                   9238:             for (my $i=0; $i<$numwithformat; $i++) {
                   9239:                 my ($name,$desc) = split(':',$unique_formats{$max_match_format}[$i]);
                   9240:                 if ($i<$numwithformat-2) {
                   9241:                     $format_descs .= '"<i>'.$desc.'</i>", ';
                   9242:                 } elsif ($i==$numwithformat-2) {
                   9243:                     $format_descs .= '"<i>'.$desc.'</i>" '.&mt('and').' ';
                   9244:                 } elsif ($i==$numwithformat-1) {
                   9245:                     $format_descs .= '"<i>'.$desc.'</i>"';
                   9246:                 }
                   9247:             }
                   9248:             my $showpct = sprintf("%.0f",$max_match_pct).'%';
1.596.2.12.2.  5(raebur 9249:3):             $output .= '<br />';
                   9250:3):             if ($found_match_count == $max_match_count) {
                   9251:3):                 # 100% matching entries
                   9252:3):                 $output .= &Apache::lonhtmlcommon::confirm_success(
                   9253:3):                      &mt('Comparison of student IDs: [_1] matching ([quant,_2,entry,entries])',
                   9254:3):                             '<b>'.$showpct.'</b>',$found_match_count)).'<br />'.
                   9255:3):                 &mt('Comparison of student IDs in the uploaded file with'.
                   9256:3):                     ' the course roster found matches for [_1] of the [_2] entries'.
                   9257:3):                     ' in the file (for the format defined for [_3]).',
                   9258:3):                         '<b>'.$showpct.'</b>','<b>'.$max_match_count.'</b>',$format_descs);
                   9259:3):             } else {
                   9260:3):                 # Not all entries matching? -> Show warning and additional info
                   9261:3):                 $output .=
                   9262:3):                     &Apache::lonhtmlcommon::confirm_success(
                   9263:3):                         &mt('Comparison of student IDs: [_1] matching ([_2]/[quant,_3,entry,entries])',
                   9264:3):                                 '<b>'.$showpct.'</b>',$found_match_count,$max_match_count).'<br />'.
                   9265:3):                         &mt('Not all entries could be matched!'),1).'<br />'.
                   9266:3):                     &mt('Comparison of student IDs in the uploaded file with'.
                   9267:3):                         ' the course roster found matches for [_1] of the [_2] entries'.
                   9268:3):                         ' in the file (for the format defined for [_3]).',
                   9269:3):                             '<b>'.$showpct.'</b>','<b>'.$max_match_count.'</b>',$format_descs).
                   9270:3):                     '<p class="LC_info">'.
                   9271:3):                     &mt('A low percentage of matches results from one of the following:').
                   9272:3):                     '</p><ul>'.
                   9273:3):                     '<li>'.&mt('The file was uploaded to the wrong course.').'</li>'.
                   9274:3):                     '<li>'.&mt('The data is not in the format expected for the domain: [_1]',
                   9275:3):                                '<i>'.$cdom.'</i>').'</li>'.
                   9276:3):                     '<li>'.&mt('Students did not bubble their IDs, or mis-bubbled them').'</li>'.
                   9277:3):                     '<li>'.&mt('The course roster is not up to date.').'</li>'.
                   9278:3):                     '</ul>';
                   9279:3):             }
1.567     raeburn  9280:         }
                   9281:     } else {
1.596.2.12.2.  5(raebur 9282:3):         $output = '<p class="LC_warning">'.&mt('Uploaded file contained no data').'</p>';
1.567     raeburn  9283:     }
                   9284:     return $output;
                   9285: }
                   9286: 
1.202     albertel 9287: sub valid_file {
                   9288:     my ($requested_file)=@_;
                   9289:     foreach my $filename (sort(&scantron_filenames())) {
                   9290: 	if ($requested_file eq $filename) { return 1; }
                   9291:     }
                   9292:     return 0;
                   9293: }
                   9294: 
                   9295: sub scantron_download_scantron_data {
                   9296:     my ($r)=@_;
1.596.2.12.2.  (raeburn 9297:):     my ($symb) = &get_symb($r,1);
                   9298:):     my $default_form_data=&defaultFormData($symb);
1.257     albertel 9299:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   9300:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
                   9301:     my $file=$env{'form.scantron_selectfile'};
1.202     albertel 9302:     if (! &valid_file($file)) {
1.492     albertel 9303: 	$r->print('
1.202     albertel 9304: 	<p>
1.596.2.12.2.  3(raebur 9305:3): 	    '.&mt('The requested filename was invalid.').'
1.202     albertel 9306:         </p>
1.492     albertel 9307: ');
1.596.2.12.2.  (raeburn 9308:): 	$r->print(&show_grading_menu_form($symb));
1.202     albertel 9309: 	return;
                   9310:     }
                   9311:     my $orig='/uploaded/'.$cdom.'/'.$cname.'/scantron_orig_'.$file;
                   9312:     my $corrected='/uploaded/'.$cdom.'/'.$cname.'/scantron_corrected_'.$file;
                   9313:     my $skipped='/uploaded/'.$cdom.'/'.$cname.'/scantron_skipped_'.$file;
                   9314:     &Apache::lonnet::allowuploaded('/adm/grades',$orig);
                   9315:     &Apache::lonnet::allowuploaded('/adm/grades',$corrected);
                   9316:     &Apache::lonnet::allowuploaded('/adm/grades',$skipped);
1.492     albertel 9317:     $r->print('
1.202     albertel 9318:     <p>
1.596.2.12.2.  8(raebur 9319:4): 	'.&mt('[_1]Original[_2] file as uploaded by bubblesheet scanning office.',
1.492     albertel 9320: 	      '<a href="'.$orig.'">','</a>').'
1.202     albertel 9321:     </p>
                   9322:     <p>
1.492     albertel 9323: 	'.&mt('[_1]Corrections[_2], a file of corrected records that were used in grading.',
                   9324: 	      '<a href="'.$corrected.'">','</a>').'
1.202     albertel 9325:     </p>
                   9326:     <p>
1.492     albertel 9327: 	'.&mt('[_1]Skipped[_2], a file of records that were skipped.',
                   9328: 	      '<a href="'.$skipped.'">','</a>').'
1.202     albertel 9329:     </p>
1.492     albertel 9330: ');
1.596.2.12.2.  (raeburn 9331:):     $r->print(&show_grading_menu_form($symb));
1.202     albertel 9332:     return '';
                   9333: }
1.157     albertel 9334: 
1.523     raeburn  9335: sub checkscantron_results {
                   9336:     my ($r) = @_;
                   9337:     my ($symb)=&get_symb($r);
                   9338:     if (!$symb) {return '';}
                   9339:     my $grading_menu_button=&show_grading_menu_form($symb);
                   9340:     my $cid = $env{'request.course.id'};
1.542     raeburn  9341:     my %lettdig = &letter_to_digits();
1.523     raeburn  9342:     my $numletts = scalar(keys(%lettdig));
                   9343:     my $cnum = $env{'course.'.$cid.'.num'};
                   9344:     my $cdom = $env{'course.'.$cid.'.domain'};
                   9345:     my (undef, undef, $sequence) = &Apache::lonnet::decode_symb($env{'form.selectpage'});
                   9346:     my %record;
                   9347:     my %scantron_config =
                   9348:         &Apache::grades::get_scantron_config($env{'form.scantron_format'});
1.596.2.12.2.  (raeburn 9349:):     my $bubbles_per_row = &bubblesheet_bubbles_per_row(\%scantron_config);
1.523     raeburn  9350:     my ($scanlines,$scan_data)=&Apache::grades::scantron_getfile();
                   9351:     my $classlist=&Apache::loncoursedata::get_classlist();
                   9352:     my %idmap=&Apache::grades::username_to_idmap($classlist);
                   9353:     my $navmap=Apache::lonnavmaps::navmap->new();
1.582     raeburn  9354:     unless (ref($navmap)) {
                   9355:         $r->print(&navmap_errormsg());
                   9356:         return '';
                   9357:     }
1.523     raeburn  9358:     my $map=$navmap->getResourceByUrl($sequence);
1.596.2.12.2.  6(raebur 9359:3):     my ($randomorder,$randompick,@master_seq,%symb_to_resource,%grader_partids_by_symb,
                   9360:3):         %grader_randomlists_by_symb,%orderedforcode);
          1(raebur 9361:2):     if (ref($map)) {
                   9362:2):         $randomorder=$map->randomorder();
          7(raebur 9363:3):         $randompick=$map->randompick();
          1(raebur 9364:2):     }
1.557     raeburn  9365:     my @resources=$navmap->retrieveResources($map,\&scantron_filter,1,0);
1.596.2.12.2.  6(raebur 9366:3):     my $nav_error = &get_master_seq(\@resources,\@master_seq,\%symb_to_resource);
                   9367:3):     if ($nav_error) {
                   9368:3):         $r->print(&navmap_errormsg());
                   9369:3):         return '';
          1(raebur 9370:2):     }
          (raeburn 9371:):     &graders_resources_pass(\@resources,\%grader_partids_by_symb,
                   9372:):                             \%grader_randomlists_by_symb,$bubbles_per_row);
1.554     raeburn  9373:     my ($uname,$udom);
1.523     raeburn  9374:     my (%scandata,%lastname,%bylast);
                   9375:     $r->print('
                   9376: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="checkscantron">'."\n");
                   9377: 
                   9378:     my @delayqueue;
                   9379:     my %completedstudents;
                   9380: 
1.596.2.12.2.  6(raebur 9381:3):     my $count=&get_todo_count($scanlines,$scan_data);
          (raeburn 9382:):     my %prog_state=&Apache::lonhtmlcommon::Create_PrgWin($r,$count);
          6(raebur 9383:3):     my ($username,$domain,$started);
          (raeburn 9384:):     &scantron_get_maxbubble(\$nav_error,\%scantron_config); # Need the bubble lines array to parse.
1.582     raeburn  9385:     if ($nav_error) {
                   9386:         $r->print(&navmap_errormsg());
                   9387:         return '';
                   9388:     }
1.523     raeburn  9389: 
                   9390:     &Apache::lonhtmlcommon::Update_PrgWin($r,\%prog_state,
                   9391:                                           'Processing first student');
                   9392:     my $start=&Time::HiRes::time();
                   9393:     my $i=-1;
                   9394: 
                   9395:     while ($i<$scanlines->{'count'}) {
                   9396:         ($username,$domain,$uname)=('','','');
                   9397:         $i++;
                   9398:         my $line=&Apache::grades::scantron_get_line($scanlines,$scan_data,$i);
                   9399:         if ($line=~/^[\s\cz]*$/) { next; }
                   9400:         if ($started) {
                   9401:             &Apache::lonhtmlcommon::Increment_PrgWin($r,\%prog_state,
                   9402:                                                      'last student');
                   9403:         }
                   9404:         $started=1;
                   9405:         my $scan_record=
                   9406:             &Apache::grades::scantron_parse_scanline($line,$i,\%scantron_config,
                   9407:                                                      $scan_data);
1.596.2.12.2.  6(raebur 9408:3):         unless ($uname=&scantron_find_student($scan_record,$scan_data,
                   9409:3):                                               \%idmap,$i)) {
1.523     raeburn  9410:             &Apache::grades::scantron_add_delay(\@delayqueue,$line,
                   9411:                                 'Unable to find a student that matches',1);
                   9412:             next;
                   9413:         }
                   9414:         if (exists $completedstudents{$uname}) {
                   9415:             &Apache::grades::scantron_add_delay(\@delayqueue,$line,
                   9416:                                 'Student '.$uname.' has multiple sheets',2);
                   9417:             next;
                   9418:         }
                   9419:         my $pid = $scan_record->{'scantron.ID'};
                   9420:         $lastname{$pid} = $scan_record->{'scantron.LastName'};
                   9421:         push(@{$bylast{$lastname{$pid}}},$pid);
1.596.2.12.2.  1(raebur 9422:2):         my $usec = $classlist->{$uname}->[&Apache::loncoursedata::CL_SECTION];
                   9423:2):         my $user = $uname.':'.$usec;
1.523     raeburn  9424:         ($username,$domain)=split(/:/,$uname);
1.596.2.12.2.  1(raebur 9425:2): 
                   9426:2):         my $scancode;
                   9427:2):         if ((exists($scan_record->{'scantron.CODE'})) &&
                   9428:2):             (&Apache::lonnet::validCODE($scan_record->{'scantron.CODE'}))) {
                   9429:2):             $scancode = $scan_record->{'scantron.CODE'};
                   9430:2):         } else {
                   9431:2):             $scancode = '';
                   9432:2):         }
                   9433:2): 
                   9434:2):         my @mapresources = @resources;
          6(raebur 9435:3):         my $lastpos = $env{'form.scantron_maxbubble'}*$scantron_config{'Qlength'};
                   9436:3):         my %respnumlookup=();
                   9437:3):         my %startline=();
                   9438:3):         if ($randomorder || $randompick) {
          1(raebur 9439:2):             @mapresources =
          6(raebur 9440:3):                 &users_order($user,$scancode,$sequence,\@master_seq,\%symb_to_resource,
                   9441:3):                              \%orderedforcode);
                   9442:3):             my $total = &get_respnum_lookups($sequence,$scan_data,\%idmap,$line,
                   9443:3):                                              $scan_record,\@master_seq,\%symb_to_resource,
                   9444:3):                                              \%grader_partids_by_symb,\%orderedforcode,
                   9445:3):                                              \%respnumlookup,\%startline);
                   9446:3):             if ($randompick && $total) {
                   9447:3):                 $lastpos = $total*$scantron_config{'Qlength'};
                   9448:3):             }
          1(raebur 9449:2):         }
          6(raebur 9450:3):         $scandata{$pid} = substr($line,$scantron_config{'Qstart'}-1,$lastpos);
                   9451:3):         chomp($scandata{$pid});
                   9452:3):         $scandata{$pid} =~ s/\r$//;
                   9453:3): 
1.523     raeburn  9454:         my $counter = -1;
1.596.2.12.2.  1(raebur 9455:2):         foreach my $resource (@mapresources) {
1.557     raeburn  9456:             my $parts;
1.554     raeburn  9457:             my $ressymb = $resource->symb();
1.557     raeburn  9458:             if ((exists($grader_randomlists_by_symb{$ressymb})) ||
                   9459:                 (ref($grader_partids_by_symb{$ressymb}) ne 'ARRAY')) {
                   9460:                 (my $analysis,$parts) =
1.596.2.12.2.  (raeburn 9461:):                     &scantron_partids_tograde($resource,$env{'request.course.id'},
                   9462:):                                               $username,$domain,undef,
                   9463:):                                               $bubbles_per_row);
1.557     raeburn  9464:             } else {
                   9465:                 $parts = $grader_partids_by_symb{$ressymb};
                   9466:             }
1.542     raeburn  9467:             ($counter,my $recording) =
                   9468:                 &verify_scantron_grading($resource,$domain,$username,$cid,$counter,
1.554     raeburn  9469:                                          $scandata{$pid},$parts,
1.596.2.12.2.  6(raebur 9470:3):                                          \%scantron_config,\%lettdig,$numletts,
                   9471:3):                                          $randomorder,$randompick,
                   9472:3):                                          \%respnumlookup,\%startline);
1.542     raeburn  9473:             $record{$pid} .= $recording;
1.523     raeburn  9474:         }
                   9475:     }
                   9476:     &Apache::lonhtmlcommon::Close_PrgWin($r,\%prog_state);
                   9477:     $r->print('<br />');
                   9478:     my ($okstudents,$badstudents,$numstudents,$passed,$failed);
                   9479:     $passed = 0;
                   9480:     $failed = 0;
                   9481:     $numstudents = 0;
                   9482:     foreach my $last (sort(keys(%bylast))) {
                   9483:         if (ref($bylast{$last}) eq 'ARRAY') {
                   9484:             foreach my $pid (sort(@{$bylast{$last}})) {
                   9485:                 my $showscandata = $scandata{$pid};
                   9486:                 my $showrecord = $record{$pid};
                   9487:                 $showscandata =~ s/\s/&nbsp;/g;
                   9488:                 $showrecord =~ s/\s/&nbsp;/g;
                   9489:                 if ($scandata{$pid} eq $record{$pid}) {
                   9490:                     my $css_class = ($passed % 2)?'LC_odd_row':'LC_even_row';
                   9491:                     $okstudents .= '<tr class="'.$css_class.'">'.
1.581     www      9492: '<td>'.&mt('Bubblesheet').'</td><td>'.$showscandata.'</td><td rowspan="2">'.$last.'</td><td rowspan="2">'.$pid.'</td>'."\n".
1.523     raeburn  9493: '</tr>'."\n".
                   9494: '<tr class="'.$css_class.'">'."\n".
1.596.2.12.2.  8(raebur 9495:4): '<td>'.&mt('Submissions').'</td><td>'.$showrecord.'</td></tr>'."\n";
1.523     raeburn  9496:                     $passed ++;
                   9497:                 } else {
                   9498:                     my $css_class = ($failed % 2)?'LC_odd_row':'LC_even_row';
1.581     www      9499:                     $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  9500: '</tr>'."\n".
                   9501: '<tr class="'.$css_class.'">'."\n".
1.596.2.12.2.  8(raebur 9502:4): '<td>'.&mt('Submissions').'</td><td><span class="LC_nobreak">'.$record{$pid}.'</span></td>'."\n".
1.523     raeburn  9503: '</tr>'."\n";
                   9504:                     $failed ++;
                   9505:                 }
                   9506:                 $numstudents ++;
                   9507:             }
                   9508:         }
                   9509:     }
1.596.2.4  raeburn  9510:     $r->print('<p>'.
1.596.2.8  raeburn  9511:               &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  9512:                   '<b>',
                   9513:                   $numstudents,
                   9514:                   '</b>',
                   9515:                   $env{'form.scantron_maxbubble'}).
                   9516:               '</p>'
                   9517:     );
1.596.2.12.2.  2(raebur 9518:2):     $r->print('<p>'
                   9519:2):              .&mt('Exact matches for [_1][quant,_2,student][_3].','<b>',$passed,'</b>')
                   9520:2):              .'<br />'
                   9521:2):              .&mt('Discrepancies detected for [_1][quant,_2,student][_3].','<b>',$failed,'</b>')
                   9522:2):              .'</p>');
1.523     raeburn  9523:     if ($passed) {
1.572     www      9524:         $r->print(&mt('Students with exact correspondence between bubblesheet data and submissions are as follows:').'<br /><br />');
1.523     raeburn  9525:         $r->print(&Apache::loncommon::start_data_table()."\n".
                   9526:                  &Apache::loncommon::start_data_table_header_row()."\n".
                   9527:                  '<th>'.&mt('Source').'</th><th>'.&mt('Bubble records').'</th><th>'.&mt('Name').'</th><th>'.&mt('ID').'</th>'.
                   9528:                  &Apache::loncommon::end_data_table_header_row()."\n".
                   9529:                  $okstudents."\n".
                   9530:                  &Apache::loncommon::end_data_table().'<br />');
                   9531:     }
                   9532:     if ($failed) {
1.572     www      9533:         $r->print(&mt('Students with differences between bubblesheet data and submissions are as follows:').'<br /><br />');
1.523     raeburn  9534:         $r->print(&Apache::loncommon::start_data_table()."\n".
                   9535:                  &Apache::loncommon::start_data_table_header_row()."\n".
                   9536:                  '<th>'.&mt('Source').'</th><th>'.&mt('Bubble records').'</th><th>'.&mt('Name').'</th><th>'.&mt('ID').'</th>'.
                   9537:                  &Apache::loncommon::end_data_table_header_row()."\n".
                   9538:                  $badstudents."\n".
                   9539:                  &Apache::loncommon::end_data_table()).'<br />'.
1.572     www      9540:                  &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  9541:     }
                   9542:     $r->print('</form><br />'.$grading_menu_button);
                   9543:     return;
                   9544: }
                   9545: 
1.542     raeburn  9546: sub verify_scantron_grading {
1.554     raeburn  9547:     my ($resource,$domain,$username,$cid,$counter,$scandata,$partids,
1.596.2.12.2.  6(raebur 9548:3):         $scantron_config,$lettdig,$numletts,$randomorder,$randompick,
                   9549:3):         $respnumlookup,$startline) = @_;
1.542     raeburn  9550:     my ($record,%expected,%startpos);
                   9551:     return ($counter,$record) if (!ref($resource));
                   9552:     return ($counter,$record) if (!$resource->is_problem());
                   9553:     my $symb = $resource->symb();
1.554     raeburn  9554:     return ($counter,$record) if (ref($partids) ne 'ARRAY');
                   9555:     foreach my $part_id (@{$partids}) {
1.542     raeburn  9556:         $counter ++;
                   9557:         $expected{$part_id} = 0;
1.596.2.12.2.  6(raebur 9558:3):         my $respnum = $counter;
                   9559:3):         if ($randomorder || $randompick) {
                   9560:3):             $respnum = $respnumlookup->{$counter};
                   9561:3):             $startpos{$part_id} = $startline->{$counter} + 1;
                   9562:3):         } else {
                   9563:3):             $startpos{$part_id} = $env{"form.scantron.first_bubble_line.$counter"};
                   9564:3):         }
                   9565:3):         if ($env{"form.scantron.sub_bubblelines.$respnum"}) {
                   9566:3):             my @sub_lines = split(/,/,$env{"form.scantron.sub_bubblelines.$respnum"});
1.542     raeburn  9567:             foreach my $item (@sub_lines) {
                   9568:                 $expected{$part_id} += $item;
                   9569:             }
                   9570:         } else {
1.596.2.12.2.  6(raebur 9571:3):             $expected{$part_id} = $env{"form.scantron.bubblelines.$respnum"};
1.542     raeburn  9572:         }
                   9573:     }
                   9574:     if ($symb) {
                   9575:         my %recorded;
                   9576:         my (%returnhash) = &Apache::lonnet::restore($symb,$cid,$domain,$username);
                   9577:         if ($returnhash{'version'}) {
                   9578:             my %lasthash=();
                   9579:             my $version;
                   9580:             for ($version=1;$version<=$returnhash{'version'};$version++) {
                   9581:                 foreach my $key (sort(split(/\:/,$returnhash{$version.':keys'}))) {
                   9582:                     $lasthash{$key}=$returnhash{$version.':'.$key};
                   9583:                 }
                   9584:             }
                   9585:             foreach my $key (keys(%lasthash)) {
                   9586:                 if ($key =~ /\.scantron$/) {
                   9587:                     my $value = &unescape($lasthash{$key});
                   9588:                     my ($part_id) = ($key =~ /^resource\.(.+)\.scantron$/);
                   9589:                     if ($value eq '') {
                   9590:                         for (my $i=0; $i<$expected{$part_id}; $i++) {
                   9591:                             for (my $j=0; $j<$scantron_config->{'length'}; $j++) {
                   9592:                                 $recorded{$part_id} .= $scantron_config->{'Qoff'};
                   9593:                             }
                   9594:                         }
                   9595:                     } else {
                   9596:                         my @tocheck;
                   9597:                         my @items = split(//,$value);
                   9598:                         if (($scantron_config->{'Qon'} eq 'letter') ||
                   9599:                             ($scantron_config->{'Qon'} eq 'number')) {
                   9600:                             if (@items < $expected{$part_id}) {
                   9601:                                 my $fragment = substr($scandata,$startpos{$part_id},$expected{$part_id});
                   9602:                                 my @singles = split(//,$fragment);
                   9603:                                 foreach my $pos (@singles) {
                   9604:                                     if ($pos eq ' ') {
                   9605:                                         push(@tocheck,$pos);
                   9606:                                     } else {
                   9607:                                         my $next = shift(@items);
                   9608:                                         push(@tocheck,$next);
                   9609:                                     }
                   9610:                                 }
                   9611:                             } else {
                   9612:                                 @tocheck = @items;
                   9613:                             }
                   9614:                             foreach my $letter (@tocheck) {
                   9615:                                 if ($scantron_config->{'Qon'} eq 'letter') {
                   9616:                                     if ($letter !~ /^[A-J]$/) {
                   9617:                                         $letter = $scantron_config->{'Qoff'};
                   9618:                                     }
                   9619:                                     $recorded{$part_id} .= $letter;
                   9620:                                 } elsif ($scantron_config->{'Qon'} eq 'number') {
                   9621:                                     my $digit;
                   9622:                                     if ($letter !~ /^[A-J]$/) {
                   9623:                                         $digit = $scantron_config->{'Qoff'};
                   9624:                                     } else {
                   9625:                                         $digit = $lettdig->{$letter};
                   9626:                                     }
                   9627:                                     $recorded{$part_id} .= $digit;
                   9628:                                 }
                   9629:                             }
                   9630:                         } else {
                   9631:                             @tocheck = @items;
                   9632:                             for (my $i=0; $i<$expected{$part_id}; $i++) {
                   9633:                                 my $curr_sub = shift(@tocheck);
                   9634:                                 my $digit;
                   9635:                                 if ($curr_sub =~ /^[A-J]$/) {
                   9636:                                     $digit = $lettdig->{$curr_sub}-1;
                   9637:                                 }
                   9638:                                 if ($curr_sub eq 'J') {
                   9639:                                     $digit += scalar($numletts);
                   9640:                                 }
                   9641:                                 for (my $j=0; $j<$scantron_config->{'Qlength'}; $j++) {
                   9642:                                     if ($j == $digit) {
                   9643:                                         $recorded{$part_id} .= $scantron_config->{'Qon'};
                   9644:                                     } else {
                   9645:                                         $recorded{$part_id} .= $scantron_config->{'Qoff'};
                   9646:                                     }
                   9647:                                 }
                   9648:                             }
                   9649:                         }
                   9650:                     }
                   9651:                 }
                   9652:             }
                   9653:         }
1.554     raeburn  9654:         foreach my $part_id (@{$partids}) {
1.542     raeburn  9655:             if ($recorded{$part_id} eq '') {
                   9656:                 for (my $i=0; $i<$expected{$part_id}; $i++) {
                   9657:                     for (my $j=0; $j<$scantron_config->{'Qlength'}; $j++) {
                   9658:                         $recorded{$part_id} .= $scantron_config->{'Qoff'};
                   9659:                     }
                   9660:                 }
                   9661:             }
                   9662:             $record .= $recorded{$part_id};
                   9663:         }
                   9664:     }
                   9665:     return ($counter,$record);
                   9666: }
                   9667: 
1.596.2.12.2.  6(raebur 9668:3): sub letter_to_digits {
1.542     raeburn  9669:     my %lettdig = (
                   9670:                     A => 1,
                   9671:                     B => 2,
                   9672:                     C => 3,
                   9673:                     D => 4,
                   9674:                     E => 5,
                   9675:                     F => 6,
                   9676:                     G => 7,
                   9677:                     H => 8,
                   9678:                     I => 9,
                   9679:                     J => 0,
                   9680:                   );
                   9681:     return %lettdig;
                   9682: }
                   9683: 
1.423     albertel 9684: 
1.75      albertel 9685: #-------- end of section for handling grading scantron forms -------
                   9686: #
                   9687: #-------------------------------------------------------------------
                   9688: 
1.72      ng       9689: #-------------------------- Menu interface -------------------------
                   9690: #
                   9691: #--- Show a Grading Menu button - Calls the next routine ---
                   9692: sub show_grading_menu_form {
1.324     albertel 9693:     my ($symb)=@_;
1.125     ng       9694:     my $result.='<br /><form action="/adm/grades" method="post">'."\n".
1.418     albertel 9695: 	'<input type="hidden" name="symb" value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
1.257     albertel 9696: 	'<input type="hidden" name="saveState"  value="'.$env{'form.saveState'}.'" />'."\n".
1.72      ng       9697: 	'<input type="hidden" name="command" value="gradingmenu" />'."\n".
1.478     albertel 9698: 	'<input type="submit" name="submit" value="'.&mt('Grading Menu').'" />'."\n".
1.72      ng       9699: 	'</form>'."\n";
                   9700:     return $result;
                   9701: }
                   9702: 
1.77      ng       9703: # -- Retrieve choices for grading form
                   9704: sub savedState {
                   9705:     my %savedState = ();
1.257     albertel 9706:     if ($env{'form.saveState'}) {
                   9707: 	foreach (split(/:/,$env{'form.saveState'})) {
1.77      ng       9708: 	    my ($key,$value) = split(/=/,$_,2);
                   9709: 	    $savedState{$key} = $value;
                   9710: 	}
                   9711:     }
                   9712:     return \%savedState;
                   9713: }
1.76      ng       9714: 
1.596.2.12.2.  (raeburn 9715:): #--- Href with symb and command ---
                   9716:): 
                   9717:): sub href_symb_cmd {
                   9718:):     my ($symb,$cmd)=@_;
                   9719:):     return '/adm/grades?symb='.&HTML::Entities::encode(&Apache::lonenc::check_encrypt($symb),'<>&"').'&amp;command='.$cmd;
                   9720:): }
                   9721:): 
1.443     banghart 9722: sub grading_menu {
                   9723:     my ($request) = @_;
                   9724:     my ($symb)=&get_symb($request);
                   9725:     if (!$symb) {return '';}
                   9726:     my $probTitle = &Apache::lonnet::gettitle($symb);
                   9727:     my ($table,undef,$hdgrade) = &showResourceInfo($symb,$probTitle);
                   9728: 
1.444     banghart 9729:     $request->print($table);
1.443     banghart 9730:     my %fields = ('symb'=>&Apache::lonenc::check_encrypt($symb),
                   9731:                   'handgrade'=>$hdgrade,
                   9732:                   'probTitle'=>$probTitle,
                   9733:                   'command'=>'submit_options',
                   9734:                   'saveState'=>"",
                   9735:                   'gradingMenu'=>1,
                   9736:                   'showgrading'=>"yes");
1.538     schulted 9737:     
                   9738:     my $url1 = &Apache::lonhtmlcommon::build_url('grades/',\%fields);
                   9739:     
1.443     banghart 9740:     $fields{'command'} = 'csvform';
1.538     schulted 9741:     my $url2 = &Apache::lonhtmlcommon::build_url('grades/',\%fields);
                   9742:     
1.443     banghart 9743:     $fields{'command'} = 'processclicker';
1.538     schulted 9744:     my $url3 = &Apache::lonhtmlcommon::build_url('grades/',\%fields);
                   9745:     
1.443     banghart 9746:     $fields{'command'} = 'scantron_selectphase';
1.538     schulted 9747:     my $url4 = &Apache::lonhtmlcommon::build_url('grades/',\%fields);
                   9748:     
                   9749:     my @menu = ({	categorytitle=>'Course Grading',
                   9750:             items =>[
                   9751:                         {	linktext => 'Manual Grading/View Submissions',
                   9752:                     		url => $url1,
                   9753:                     		permission => 'F',
                   9754:                     		icon => 'edit-find-replace.png',
                   9755:                     		linktitle => 'Start the process of hand grading submissions.'
                   9756:                         },
                   9757:                 	    {	linktext => 'Upload Scores',
                   9758:                     		url => $url2,
                   9759:                     		permission => 'F',
                   9760:                     		icon => 'uploadscores.png',
                   9761:                     		linktitle => 'Specify a file containing the class scores for current resource.'
                   9762:                 	    },
                   9763:                 	    {	linktext => 'Process Clicker',
                   9764:                     		url => $url3,
                   9765:                     		permission => 'F',
                   9766:                     		icon => 'addClickerInfoFile.png',
                   9767:                     		linktitle => 'Specify a file containing the clicker information for this resource.'
                   9768:                 	    },
1.587     raeburn  9769:                 	    {	linktext => 'Grade/Manage/Review Bubblesheets',
1.538     schulted 9770:                     		url => $url4,
                   9771:                     		permission => 'F',
                   9772:                     		icon => 'stat.png',
1.596.2.4  raeburn  9773:                     		linktitle => 'Grade bubblesheet exams, upload/download bubblesheet data files, and review previously graded bubblesheet exams.'
1.538     schulted 9774:                 	    }
                   9775:                     ]
                   9776:             });
                   9777: 
                   9778:     #$fields{'command'} = 'verify';
                   9779:     #$url = &Apache::lonhtmlcommon::build_url('grades/',\%fields);
1.443     banghart 9780:     #
                   9781:     # Create the menu
                   9782:     my $Str;
1.444     banghart 9783:     # $Str .= '<h2>'.&mt('Please select a grading task').'</h2>';
1.445     banghart 9784:     $Str .= '<form method="post" action="" name="gradingMenu">';
                   9785:     $Str .= '<input type="hidden" name="command" value="" />'.
                   9786:     	'<input type="hidden" name="symb"        value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
                   9787: 	'<input type="hidden" name="handgrade"   value="'.$hdgrade.'" />'."\n".
1.476     albertel 9788: 	'<input type="hidden" name="probTitle"   value="'.$probTitle.'" />'."\n".
1.445     banghart 9789: 	'<input type="hidden" name="saveState"   value="" />'."\n".
                   9790: 	'<input type="hidden" name="gradingMenu" value="1" />'."\n".
                   9791: 	'<input type="hidden" name="showgrading" value="yes" />'."\n";
                   9792: 
1.538     schulted 9793:     $Str .= Apache::lonhtmlcommon::generate_menu(@menu);
                   9794:     #$menudata->{'jscript'}
1.584     bisitz   9795:     $Str .='<hr /><input type="button" value="'.&mt('Verify Receipt No.').'" '.
1.589     bisitz   9796:         ' onclick="javascript:checkChoice(document.forms.gradingMenu,\'5\',\'verify\')" '.
1.538     schulted 9797:         ' /> '.
                   9798:         &Apache::lonnet::recprefix($env{'request.course.id'}).
1.589     bisitz   9799:         '-<input type="text" name="receipt" size="4" onchange="javascript:checkReceiptNo(this.form,\'OK\')" />';
1.538     schulted 9800: 
1.444     banghart 9801:     $Str .="</form>\n";
1.539     riegler  9802:     my $receiptalert = &mt("Please enter a receipt number given by a student in the receipt box.");
1.443     banghart 9803:     $request->print(<<GRADINGMENUJS);
                   9804: <script type="text/javascript" language="javascript">
                   9805:     function checkChoice(formname,val,cmdx) {
                   9806: 	if (val <= 2) {
                   9807: 	    var cmd = radioSelection(formname.radioChoice);
                   9808: 	    var cmdsave = cmd;
                   9809: 	} else {
                   9810: 	    cmd = cmdx;
                   9811: 	    cmdsave = 'submission';
                   9812: 	}
                   9813: 	formname.command.value = cmd;
                   9814: 	if (val < 5) formname.submit();
                   9815: 	if (val == 5) {
1.458     banghart 9816: 	    if (!checkReceiptNo(formname,'notOK')) { 
                   9817: 	        return false;
                   9818: 	    } else {
                   9819: 	        formname.submit();
                   9820: 	    }
1.445     banghart 9821: 	}
                   9822:     }
1.443     banghart 9823: 
                   9824:     function checkReceiptNo(formname,nospace) {
                   9825: 	var receiptNo = formname.receipt.value;
                   9826: 	var checkOpt = false;
                   9827: 	if (nospace == "OK" && isNaN(receiptNo)) {checkOpt = true;}
                   9828: 	if (nospace == "notOK" && (isNaN(receiptNo) || receiptNo == "")) {checkOpt = true;}
                   9829: 	if (checkOpt) {
1.539     riegler  9830: 	    alert("$receiptalert");
1.443     banghart 9831: 	    formname.receipt.value = "";
                   9832: 	    formname.receipt.focus();
                   9833: 	    return false;
                   9834: 	}
                   9835: 	return true;
                   9836:     }
                   9837: </script>
                   9838: GRADINGMENUJS
                   9839:     &commonJSfunctions($request);
                   9840:     return $Str;    
                   9841: }
                   9842: 
                   9843: 
                   9844: #--- Displays the submissions first page -------
                   9845: sub submit_options {
1.72      ng       9846:     my ($request) = @_;
1.324     albertel 9847:     my ($symb)=&get_symb($request);
1.72      ng       9848:     if (!$symb) {return '';}
1.76      ng       9849:     my $probTitle = &Apache::lonnet::gettitle($symb);
1.72      ng       9850: 
1.539     riegler  9851:     my $receiptalert = &mt("Please enter a receipt number given by a student in the receipt box."); 
1.72      ng       9852:     $request->print(<<GRADINGMENUJS);
                   9853: <script type="text/javascript" language="javascript">
1.116     ng       9854:     function checkChoice(formname,val,cmdx) {
                   9855: 	if (val <= 2) {
                   9856: 	    var cmd = radioSelection(formname.radioChoice);
1.118     ng       9857: 	    var cmdsave = cmd;
1.116     ng       9858: 	} else {
                   9859: 	    cmd = cmdx;
1.118     ng       9860: 	    cmdsave = 'submission';
1.116     ng       9861: 	}
                   9862: 	formname.command.value = cmd;
1.118     ng       9863: 	formname.saveState.value = "saveCmd="+cmdsave+":saveSec="+pullDownSelection(formname.section)+
1.145     albertel 9864: 	    ":saveSub="+pullDownSelection(formname.submitonly)+":saveStatus="+pullDownSelection(formname.Status);
1.116     ng       9865: 	if (val < 5) formname.submit();
                   9866: 	if (val == 5) {
1.72      ng       9867: 	    if (!checkReceiptNo(formname,'notOK')) { return false;}
                   9868: 	    formname.submit();
                   9869: 	}
1.238     albertel 9870: 	if (val < 7) formname.submit();
1.72      ng       9871:     }
                   9872: 
                   9873:     function checkReceiptNo(formname,nospace) {
                   9874: 	var receiptNo = formname.receipt.value;
                   9875: 	var checkOpt = false;
                   9876: 	if (nospace == "OK" && isNaN(receiptNo)) {checkOpt = true;}
                   9877: 	if (nospace == "notOK" && (isNaN(receiptNo) || receiptNo == "")) {checkOpt = true;}
                   9878: 	if (checkOpt) {
1.539     riegler  9879: 	    alert("$receiptalert");
1.72      ng       9880: 	    formname.receipt.value = "";
                   9881: 	    formname.receipt.focus();
                   9882: 	    return false;
                   9883: 	}
                   9884: 	return true;
                   9885:     }
                   9886: </script>
                   9887: GRADINGMENUJS
1.118     ng       9888:     &commonJSfunctions($request);
1.324     albertel 9889:     my ($table,undef,$hdgrade) = &showResourceInfo($symb,$probTitle);
1.473     albertel 9890:     my $result;
1.76      ng       9891:     my (undef,$sections) = &getclasslist('all','0');
1.77      ng       9892:     my $savedState = &savedState();
1.118     ng       9893:     my $saveCmd = ($$savedState{'saveCmd'} eq '' ? 'submission' : $$savedState{'saveCmd'});
1.77      ng       9894:     my $saveSec = ($$savedState{'saveSec'} eq '' ? 'all' : $$savedState{'saveSec'});
1.118     ng       9895:     my $saveSub = ($$savedState{'saveSub'} eq '' ? 'all' : $$savedState{'saveSub'});
1.77      ng       9896:     my $saveStatus = ($$savedState{'saveStatus'} eq '' ? 'Active' : $$savedState{'saveStatus'});
1.72      ng       9897: 
1.533     bisitz   9898:     # Preselect sections
                   9899:     my $selsec="";
                   9900:     if (ref($sections)) {
                   9901:         foreach my $section (sort(@$sections)) {
                   9902:             $selsec.='<option value="'.$section.'" '.
                   9903:                 ($saveSec eq $section ? 'selected="selected"':'').'>'.$section.'</option>'."\n";
                   9904:         }
                   9905:     }
                   9906: 
1.72      ng       9907:     $result.='<form action="/adm/grades" method="post" name="gradingMenu">'."\n".
1.418     albertel 9908: 	'<input type="hidden" name="symb"        value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
1.72      ng       9909: 	'<input type="hidden" name="handgrade"   value="'.$hdgrade.'" />'."\n".
                   9910: 	'<input type="hidden" name="probTitle"   value="'.$probTitle.'" />'."\n".
1.116     ng       9911: 	'<input type="hidden" name="command"     value="" />'."\n".
1.77      ng       9912: 	'<input type="hidden" name="saveState"   value="" />'."\n".
1.124     ng       9913: 	'<input type="hidden" name="gradingMenu" value="1" />'."\n".
1.72      ng       9914: 	'<input type="hidden" name="showgrading" value="yes" />'."\n";
                   9915: 
1.472     albertel 9916:     $result.='
1.533     bisitz   9917: <h2>
                   9918:   '.&mt('Grade Current Resource').'
                   9919: </h2>
                   9920: <div>
                   9921:   '.$table.'
                   9922: </div>
                   9923: 
1.537     harmsja  9924: <div class="LC_columnSection">
                   9925:   
1.533     bisitz   9926:     <fieldset>
                   9927:       <legend>
                   9928:        '.&mt('Sections').'
                   9929:       </legend>
                   9930:       <select name="section" multiple="multiple" size="5">'."\n";
                   9931:     $result.= $selsec;
1.401     albertel 9932:     $result.= '<option value="all" '.($saveSec eq 'all' ? 'selected="selected"' : ''). '>all</option></select> &nbsp; ';
1.472     albertel 9933:     $result.='
1.533     bisitz   9934:     </fieldset>
1.537     harmsja  9935:   
1.533     bisitz   9936:     <fieldset>
                   9937:       <legend>
                   9938:         '.&mt('Groups').'
                   9939:       </legend>
                   9940:       '.&Apache::lonstatistics::GroupSelect('group','multiple',5).'
                   9941:     </fieldset>
1.537     harmsja  9942:   
1.533     bisitz   9943:     <fieldset>
                   9944:       <legend>
                   9945:         '.&mt('Access Status').'
                   9946:       </legend>
                   9947:       '.&Apache::lonhtmlcommon::StatusOptions($saveStatus,undef,5,undef,'mult').'
                   9948:     </fieldset>
1.537     harmsja  9949:   
1.533     bisitz   9950:     <fieldset>
                   9951:       <legend>
                   9952:         '.&mt('Submission Status').'
                   9953:       </legend>
                   9954:       <select name="submitonly" size="5">
1.473     albertel 9955: 	         <option value="yes" '.      ($saveSub eq 'yes'       ? 'selected="selected"' : '').'>'.&mt('with submissions').'</option>
                   9956: 	         <option value="queued" '.   ($saveSub eq 'queued'    ? 'selected="selected"' : '').'>'.&mt('in grading queue').'</option>
                   9957: 	         <option value="graded" '.   ($saveSub eq 'graded'    ? 'selected="selected"' : '').'>'.&mt('with ungraded submissions').'</option>
                   9958: 	         <option value="incorrect" '.($saveSub eq 'incorrect' ? 'selected="selected"' : '').'>'.&mt('with incorrect submissions').'</option>
                   9959:                  <option value="all" '.      ($saveSub eq 'all'       ? 'selected="selected"' : '').'>'.&mt('with any status').'</option>
1.533     bisitz   9960:       </select>
                   9961:     </fieldset>
1.537     harmsja  9962:   
1.533     bisitz   9963: </div>
                   9964: 
                   9965: <br />
                   9966:           <div>
                   9967:             <div>
1.473     albertel 9968:               <label>
                   9969:                 <input type="radio" name="radioChoice" value="submission" '.
                   9970:                   ($saveCmd eq 'submission' ? 'checked="checked"' : '').' /> '.
                   9971:              &mt('Select individual students to grade and view submissions.').'
                   9972: 	      </label> 
                   9973:             </div>
1.533     bisitz   9974:             <div>
1.473     albertel 9975: 	      <label>
                   9976:                 <input type="radio" name="radioChoice" value="viewgrades" '.
                   9977:                   ($saveCmd eq 'viewgrades' ? 'checked="checked"' : '').' /> '.
                   9978:                     &mt('Grade all selected students in a grading table.').'
                   9979:               </label>
                   9980:             </div>
1.533     bisitz   9981:             <div>
1.589     bisitz   9982: 	      <input type="button" onclick="javascript:checkChoice(this.form,\'2\');" value="'.&mt('Next').' &rarr;" />
1.473     albertel 9983:             </div>
1.472     albertel 9984:           </div>
1.533     bisitz   9985: 
                   9986: 
1.473     albertel 9987:         <h2>
                   9988:          '.&mt('Grade Complete Folder for One Student').'
                   9989:         </h2>
1.533     bisitz   9990:         <div>
                   9991:             <div>
1.473     albertel 9992:               <label>
                   9993:                 <input type="radio" name="radioChoice" value="pickStudentPage" '.
                   9994: 	  ($saveCmd eq 'pickStudentPage' ? 'checked="checked"' : '').' /> '.
                   9995:   &mt('The <b>complete</b> page/sequence/folder: For one student').'
                   9996:               </label>
                   9997:             </div>
1.533     bisitz   9998:             <div>
1.589     bisitz   9999: 	      <input type="button" onclick="javascript:checkChoice(this.form,\'2\');" value="'.&mt('Next').' &rarr;" />
1.473     albertel 10000:             </div>
1.472     albertel 10001:         </div>
                   10002:   </form>';
1.499     albertel 10003:     $result .= &show_grading_menu_form($symb);
1.44      ng       10004:     return $result;
1.2       albertel 10005: }
                   10006: 
1.596.2.12.2.  7(raebur 10007:6): sub substatus_options {
                   10008:6):     return &Apache::lonlocal::texthash(
                   10009:6):                                       'yes'       => 'with submissions',
                   10010:6):                                       'queued'    => 'in grading queue',
                   10011:6):                                       'graded'    => 'with ungraded submissions',
                   10012:6):                                       'incorrect' => 'with incorrect submissions',
          0(raebur 10013:7):                                       'all'       => 'with any status',
                   10014:7):                                       );
          7(raebur 10015:6): }
                   10016:6): 
1.285     albertel 10017: sub reset_perm {
                   10018:     undef(%perm);
                   10019: }
                   10020: 
                   10021: sub init_perm {
                   10022:     &reset_perm();
1.300     albertel 10023:     foreach my $test_perm ('vgr','mgr','opa') {
                   10024: 
                   10025: 	my $scope = $env{'request.course.id'};
                   10026: 	if (!($perm{$test_perm}=&Apache::lonnet::allowed($test_perm,$scope))) {
                   10027: 
                   10028: 	    $scope .= '/'.$env{'request.course.sec'};
                   10029: 	    if ( $perm{$test_perm}=
                   10030: 		 &Apache::lonnet::allowed($test_perm,$scope)) {
                   10031: 		$perm{$test_perm.'_section'}=$env{'request.course.sec'};
                   10032: 	    } else {
                   10033: 		delete($perm{$test_perm});
                   10034: 	    }
1.285     albertel 10035: 	}
                   10036:     }
                   10037: }
                   10038: 
1.596.2.12.2.  (raeburn 10039:): sub init_old_essays {
                   10040:):     my ($symb,$apath,$adom,$aname) = @_;
                   10041:):     if ($symb ne '') {
                   10042:):         my %essays = &Apache::lonnet::dump('nohist_essay_'.$apath,$adom,$aname);
                   10043:):         if (keys(%essays) > 0) {
                   10044:):             $old_essays{$symb} = \%essays;
                   10045:):         }
                   10046:):     }
                   10047:):     return;
                   10048:): }
                   10049:): 
                   10050:): sub reset_old_essays {
                   10051:):     undef(%old_essays);
                   10052:): }
                   10053:): 
1.400     www      10054: sub gather_clicker_ids {
1.408     albertel 10055:     my %clicker_ids;
1.400     www      10056: 
                   10057:     my $classlist = &Apache::loncoursedata::get_classlist();
                   10058: 
                   10059:     # Set up a couple variables.
1.407     albertel 10060:     my $username_idx = &Apache::loncoursedata::CL_SNAME();
                   10061:     my $domain_idx   = &Apache::loncoursedata::CL_SDOM();
1.438     www      10062:     my $status_idx   = &Apache::loncoursedata::CL_STATUS();
1.400     www      10063: 
1.407     albertel 10064:     foreach my $student (keys(%$classlist)) {
1.438     www      10065:         if ($classlist->{$student}->[$status_idx] ne 'Active') { next; }
1.407     albertel 10066:         my $username = $classlist->{$student}->[$username_idx];
                   10067:         my $domain   = $classlist->{$student}->[$domain_idx];
1.400     www      10068:         my $clickers =
1.408     albertel 10069: 	    (&Apache::lonnet::userenvironment($domain,$username,'clickers'))[1];
1.400     www      10070:         foreach my $id (split(/\,/,$clickers)) {
1.414     www      10071:             $id=~s/^[\#0]+//;
1.421     www      10072:             $id=~s/[\-\:]//g;
1.407     albertel 10073:             if (exists($clicker_ids{$id})) {
1.408     albertel 10074: 		$clicker_ids{$id}.=','.$username.':'.$domain;
1.400     www      10075:             } else {
1.408     albertel 10076: 		$clicker_ids{$id}=$username.':'.$domain;
1.400     www      10077:             }
                   10078:         }
                   10079:     }
1.407     albertel 10080:     return %clicker_ids;
1.400     www      10081: }
                   10082: 
1.402     www      10083: sub gather_adv_clicker_ids {
1.408     albertel 10084:     my %clicker_ids;
1.402     www      10085:     my $cnum=$env{'course.'.$env{'request.course.id'}.'.num'};
                   10086:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
                   10087:     my %coursepersonnel=&Apache::lonnet::get_course_adv_roles($cdom.'/'.$cnum);
1.409     albertel 10088:     foreach my $element (sort(keys(%coursepersonnel))) {
1.402     www      10089:         foreach my $person (split(/\,/,$coursepersonnel{$element})) {
                   10090:             my ($puname,$pudom)=split(/\:/,$person);
                   10091:             my $clickers =
1.408     albertel 10092: 		(&Apache::lonnet::userenvironment($pudom,$puname,'clickers'))[1];
1.405     www      10093:             foreach my $id (split(/\,/,$clickers)) {
1.414     www      10094: 		$id=~s/^[\#0]+//;
1.421     www      10095:                 $id=~s/[\-\:]//g;
1.408     albertel 10096: 		if (exists($clicker_ids{$id})) {
                   10097: 		    $clicker_ids{$id}.=','.$puname.':'.$pudom;
                   10098: 		} else {
                   10099: 		    $clicker_ids{$id}=$puname.':'.$pudom;
                   10100: 		}
1.405     www      10101:             }
1.402     www      10102:         }
                   10103:     }
1.407     albertel 10104:     return %clicker_ids;
1.402     www      10105: }
                   10106: 
1.413     www      10107: sub clicker_grading_parameters {
                   10108:     return ('gradingmechanism' => 'scalar',
                   10109:             'upfiletype' => 'scalar',
                   10110:             'specificid' => 'scalar',
                   10111:             'pcorrect' => 'scalar',
                   10112:             'pincorrect' => 'scalar');
                   10113: }
                   10114: 
1.400     www      10115: sub process_clicker {
                   10116:     my ($r)=@_;
                   10117:     my ($symb)=&get_symb($r);
                   10118:     if (!$symb) {return '';}
                   10119:     my $result=&checkforfile_js();
                   10120:     $env{'form.probTitle'} = &Apache::lonnet::gettitle($symb);
                   10121:     my ($table) = &showResourceInfo($symb,$env{'form.probTitle'});
                   10122:     $result.=$table;
                   10123:     $result.='<br /><table width="100%" border="0"><tr><td bgcolor="#777777">'."\n";
                   10124:     $result.='<table width="100%" border="0"><tr bgcolor="#e6ffff"><td>'."\n";
1.538     schulted 10125:     $result.='&nbsp;<b>'.&mt('Specify a file containing the clicker information for this resource.').
                   10126:         '</b></td></tr>'."\n";
1.596.2.4  raeburn  10127:     $result.='<tr bgcolor="#ffffe6"><td>'."\n";
1.413     www      10128: # Attempt to restore parameters from last session, set defaults if not present
                   10129:     my %Saveable_Parameters=&clicker_grading_parameters();
                   10130:     &Apache::loncommon::restore_course_settings('grades_clicker',
                   10131:                                                  \%Saveable_Parameters);
                   10132:     if (!$env{'form.pcorrect'}) { $env{'form.pcorrect'}=100; }
                   10133:     if (!$env{'form.pincorrect'}) { $env{'form.pincorrect'}=100; }
                   10134:     if (!$env{'form.gradingmechanism'}) { $env{'form.gradingmechanism'}='attendance'; }
                   10135:     if (!$env{'form.upfiletype'}) { $env{'form.upfiletype'}='iclicker'; }
                   10136: 
                   10137:     my %checked;
1.521     www      10138:     foreach my $gradingmechanism ('attendance','personnel','specific','given') {
1.413     www      10139:        if ($env{'form.gradingmechanism'} eq $gradingmechanism) {
1.569     bisitz   10140:           $checked{$gradingmechanism}=' checked="checked"';
1.413     www      10141:        }
                   10142:     }
                   10143: 
1.400     www      10144:     my $upload=&mt("Upload File");
                   10145:     my $type=&mt("Type");
1.402     www      10146:     my $attendance=&mt("Award points just for participation");
                   10147:     my $personnel=&mt("Correctness determined from response by course personnel");
1.414     www      10148:     my $specific=&mt("Correctness determined from response with clicker ID(s)"); 
1.521     www      10149:     my $given=&mt("Correctness determined from given list of answers").' '.
                   10150:               '<font size="-2"><tt>('.&mt("Provide comma-separated list. Use '*' for any answer correct, '-' for skip").')</tt></font>';
1.402     www      10151:     my $pcorrect=&mt("Percentage points for correct solution");
                   10152:     my $pincorrect=&mt("Percentage points for incorrect solution");
1.413     www      10153:     my $selectform=&Apache::loncommon::select_form($env{'form.upfiletype'},'upfiletype',
1.596.2.1  raeburn  10154:                                                    {'iclicker' => 'i>clicker',
1.596.2.12.2.  (raeburn 10155:):                                                     'interwrite' => 'interwrite PRS',
                   10156:):                                                     'turning' => 'Turning Technologies'});
1.418     albertel 10157:     $symb = &Apache::lonenc::check_encrypt($symb);
1.400     www      10158:     $result.=<<ENDUPFORM;
1.402     www      10159: <script type="text/javascript">
                   10160: function sanitycheck() {
                   10161: // Accept only integer percentages
                   10162:    document.forms.gradesupload.pcorrect.value=Math.round(document.forms.gradesupload.pcorrect.value);
                   10163:    document.forms.gradesupload.pincorrect.value=Math.round(document.forms.gradesupload.pincorrect.value);
                   10164: // Find out grading choice
                   10165:    for (i=0; i<document.forms.gradesupload.gradingmechanism.length; i++) {
                   10166:       if (document.forms.gradesupload.gradingmechanism[i].checked) {
                   10167:          gradingchoice=document.forms.gradesupload.gradingmechanism[i].value;
                   10168:       }
                   10169:    }
                   10170: // By default, new choice equals user selection
                   10171:    newgradingchoice=gradingchoice;
                   10172: // Not good to give more points for false answers than correct ones
                   10173:    if (Math.round(document.forms.gradesupload.pcorrect.value)<Math.round(document.forms.gradesupload.pincorrect.value)) {
                   10174:       document.forms.gradesupload.pcorrect.value=document.forms.gradesupload.pincorrect.value;
                   10175:    }
                   10176: // If new choice is attendance only, and old choice was correctness-based, restore defaults
                   10177:    if ((gradingchoice=='attendance') && (document.forms.gradesupload.waschecked.value!='attendance')) {
                   10178:       document.forms.gradesupload.pcorrect.value=100;
                   10179:       document.forms.gradesupload.pincorrect.value=100;
                   10180:    }
                   10181: // If the values are different, cannot be attendance only
                   10182:    if ((Math.round(document.forms.gradesupload.pcorrect.value)!=Math.round(document.forms.gradesupload.pincorrect.value)) &&
                   10183:        (gradingchoice=='attendance')) {
                   10184:        newgradingchoice='personnel';
                   10185:    }
                   10186: // Change grading choice to new one
                   10187:    for (i=0; i<document.forms.gradesupload.gradingmechanism.length; i++) {
                   10188:       if (document.forms.gradesupload.gradingmechanism[i].value==newgradingchoice) {
                   10189:          document.forms.gradesupload.gradingmechanism[i].checked=true;
                   10190:       } else {
                   10191:          document.forms.gradesupload.gradingmechanism[i].checked=false;
                   10192:       }
                   10193:    }
                   10194: // Remember the old state
                   10195:    document.forms.gradesupload.waschecked.value=newgradingchoice;
                   10196: }
                   10197: </script>
1.400     www      10198: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="gradesupload">
                   10199: <input type="hidden" name="symb" value="$symb" />
                   10200: <input type="hidden" name="command" value="processclickerfile" />
                   10201: <input type="hidden" name="probTitle" value="$env{'form.probTitle'}" />
                   10202: <input type="hidden" name="saveState"  value="$env{'form.saveState'}" />
                   10203: <input type="file" name="upfile" size="50" />
                   10204: <br /><label>$type: $selectform</label>
1.589     bisitz   10205: <br /><label><input type="radio" name="gradingmechanism" value="attendance"$checked{'attendance'} onclick="sanitycheck()" />$attendance </label>
                   10206: <br /><label><input type="radio" name="gradingmechanism" value="personnel"$checked{'personnel'} onclick="sanitycheck()" />$personnel</label>
                   10207: <br /><label><input type="radio" name="gradingmechanism" value="specific"$checked{'specific'} onclick="sanitycheck()" />$specific </label>
1.414     www      10208: <input type="text" name="specificid" value="$env{'form.specificid'}" size="20" />
1.589     bisitz   10209: <br /><label><input type="radio" name="gradingmechanism" value="given"$checked{'given'} onclick="sanitycheck()" />$given </label>
1.521     www      10210: <br />&nbsp;&nbsp;&nbsp;
                   10211: <input type="text" name="givenanswer" size="50" />
1.413     www      10212: <input type="hidden" name="waschecked" value="$env{'form.gradingmechanism'}" />
1.589     bisitz   10213: <br /><label>$pcorrect: <input type="text" name="pcorrect" size="4" value="$env{'form.pcorrect'}" onchange="sanitycheck()" /></label>
                   10214: <br /><label>$pincorrect: <input type="text" name="pincorrect" size="4" value="$env{'form.pincorrect'}" onchange="sanitycheck()" /></label>
                   10215: <br /><input type="button" onclick="javascript:checkUpload(this.form);" value="$upload" />
1.400     www      10216: </form>
                   10217: ENDUPFORM
                   10218:     $result.='</td></tr></table>'."\n".
                   10219:              '</td></tr></table><br /><br />'."\n";
                   10220:     $result.=&show_grading_menu_form($symb);
                   10221:     return $result;
                   10222: }
                   10223: 
                   10224: sub process_clicker_file {
                   10225:     my ($r)=@_;
                   10226:     my ($symb)=&get_symb($r);
                   10227:     if (!$symb) {return '';}
1.413     www      10228: 
                   10229:     my %Saveable_Parameters=&clicker_grading_parameters();
                   10230:     &Apache::loncommon::store_course_settings('grades_clicker',
                   10231:                                               \%Saveable_Parameters);
                   10232: 
1.400     www      10233:     my ($result) = &showResourceInfo($symb,$env{'form.probTitle'});
1.404     www      10234:     if (($env{'form.gradingmechanism'} eq 'specific') && ($env{'form.specificid'}!~/\w/)) {
1.408     albertel 10235: 	$result.='<span class="LC_error">'.&mt('You need to specify a clicker ID for the correct answer').'</span>';
                   10236: 	return $result.&show_grading_menu_form($symb);
1.404     www      10237:     }
1.522     www      10238:     if (($env{'form.gradingmechanism'} eq 'given') && ($env{'form.givenanswer'}!~/\S/)) {
1.521     www      10239:         $result.='<span class="LC_error">'.&mt('You need to specify the correct answer').'</span>';
                   10240:         return $result.&show_grading_menu_form($symb);
                   10241:     }
1.522     www      10242:     my $foundgiven=0;
1.521     www      10243:     if ($env{'form.gradingmechanism'} eq 'given') {
                   10244:         $env{'form.givenanswer'}=~s/^\s*//gs;
                   10245:         $env{'form.givenanswer'}=~s/\s*$//gs;
1.596.2.4  raeburn  10246:         $env{'form.givenanswer'}=~s/[^a-zA-Z0-9\.\*\-\+]+/\,/g;
1.521     www      10247:         $env{'form.givenanswer'}=uc($env{'form.givenanswer'});
1.522     www      10248:         my @answers=split(/\,/,$env{'form.givenanswer'});
                   10249:         $foundgiven=$#answers+1;
1.521     www      10250:     }
1.407     albertel 10251:     my %clicker_ids=&gather_clicker_ids();
1.408     albertel 10252:     my %correct_ids;
1.404     www      10253:     if ($env{'form.gradingmechanism'} eq 'personnel') {
1.408     albertel 10254: 	%correct_ids=&gather_adv_clicker_ids();
1.404     www      10255:     }
                   10256:     if ($env{'form.gradingmechanism'} eq 'specific') {
1.414     www      10257: 	foreach my $correct_id (split(/[\s\,]/,$env{'form.specificid'})) {;
                   10258: 	   $correct_id=~tr/a-z/A-Z/;
                   10259: 	   $correct_id=~s/\s//gs;
                   10260: 	   $correct_id=~s/^[\#0]+//;
1.421     www      10261:            $correct_id=~s/[\-\:]//g;
1.414     www      10262:            if ($correct_id) {
                   10263: 	      $correct_ids{$correct_id}='specified';
                   10264:            }
                   10265:         }
1.400     www      10266:     }
1.404     www      10267:     if ($env{'form.gradingmechanism'} eq 'attendance') {
1.408     albertel 10268: 	$result.=&mt('Score based on attendance only');
1.521     www      10269:     } elsif ($env{'form.gradingmechanism'} eq 'given') {
1.522     www      10270:         $result.=&mt('Score based on [_1] ([_2] answers)','<tt>'.$env{'form.givenanswer'}.'</tt>',$foundgiven);
1.404     www      10271:     } else {
1.408     albertel 10272: 	my $number=0;
1.411     www      10273: 	$result.='<p><b>'.&mt('Correctness determined by the following IDs').'</b>';
1.408     albertel 10274: 	foreach my $id (sort(keys(%correct_ids))) {
1.411     www      10275: 	    $result.='<br /><tt>'.$id.'</tt> - ';
1.408     albertel 10276: 	    if ($correct_ids{$id} eq 'specified') {
                   10277: 		$result.=&mt('specified');
                   10278: 	    } else {
                   10279: 		my ($uname,$udom)=split(/\:/,$correct_ids{$id});
                   10280: 		$result.=&Apache::loncommon::plainname($uname,$udom);
                   10281: 	    }
                   10282: 	    $number++;
                   10283: 	}
1.411     www      10284:         $result.="</p>\n";
1.596.2.12.2.  5(raebur 10285:3):         if ($number==0) {
                   10286:3):             $result .=
                   10287:3):                  &Apache::lonhtmlcommon::confirm_success(
                   10288:3):                      &mt('No IDs found to determine correct answer'),1);
                   10289:3):             return $result,.&show_grading_menu_form($symb);
                   10290:3):         }
1.404     www      10291:     }
1.405     www      10292:     if (length($env{'form.upfile'}) < 2) {
1.596.2.12.2.  5(raebur 10293:3):         $result .=
                   10294:3):             &Apache::lonhtmlcommon::confirm_success(
                   10295:3):                 &mt('The file: [_1] you attempted to upload contained no information. Please check that you entered the correct filename.',
                   10296:3):                         '<span class="LC_filename">'.&HTML::Entities::encode($env{'form.upfile.filename'},'<>&"').'</span>'),1);
1.405     www      10297:         return $result.&show_grading_menu_form($symb);
                   10298:     }
1.410     www      10299: 
                   10300: # Were able to get all the info needed, now analyze the file
                   10301: 
1.411     www      10302:     $result.=&Apache::loncommon::studentbrowser_javascript();
1.418     albertel 10303:     $symb = &Apache::lonenc::check_encrypt($symb);
1.410     www      10304:     my $heading=&mt('Scanning clicker file');
                   10305:     $result.=(<<ENDHEADER);
                   10306: <br /><table width="100%" border="0"><tr><td bgcolor="#777777">
                   10307: <table width="100%" border="0"><tr bgcolor="#e6ffff"><td>
1.596.2.4  raeburn  10308: <b>$heading</b></td></tr><tr bgcolor="#ffffe6"><td>
1.410     www      10309: <form method="post" action="/adm/grades" name="clickeranalysis">
                   10310: <input type="hidden" name="symb" value="$symb" />
                   10311: <input type="hidden" name="command" value="assignclickergrades" />
                   10312: <input type="hidden" name="probTitle" value="$env{'form.probTitle'}" />
                   10313: <input type="hidden" name="saveState"  value="$env{'form.saveState'}" />
1.411     www      10314: <input type="hidden" name="gradingmechanism" value="$env{'form.gradingmechanism'}" />
                   10315: <input type="hidden" name="pcorrect" value="$env{'form.pcorrect'}" />
                   10316: <input type="hidden" name="pincorrect" value="$env{'form.pincorrect'}" />
1.410     www      10317: ENDHEADER
1.522     www      10318:     if ($env{'form.gradingmechanism'} eq 'given') {
                   10319:        $result.='<input type="hidden" name="correct:given" value="'.$env{'form.givenanswer'}.'" />';
                   10320:     } 
1.408     albertel 10321:     my %responses;
                   10322:     my @questiontitles;
1.405     www      10323:     my $errormsg='';
                   10324:     my $number=0;
                   10325:     if ($env{'form.upfiletype'} eq 'iclicker') {
1.408     albertel 10326: 	($errormsg,$number)=&iclicker_eval(\@questiontitles,\%responses);
1.406     www      10327:     }
1.419     www      10328:     if ($env{'form.upfiletype'} eq 'interwrite') {
                   10329:         ($errormsg,$number)=&interwrite_eval(\@questiontitles,\%responses);
                   10330:     }
1.596.2.12.2.  (raeburn 10331:):     if ($env{'form.upfiletype'} eq 'turning') {
                   10332:):         ($errormsg,$number)=&turning_eval(\@questiontitles,\%responses);
                   10333:):     }
1.411     www      10334:     $result.='<br />'.&mt('Found [_1] question(s)',$number).'<br />'.
                   10335:              '<input type="hidden" name="number" value="'.$number.'" />'.
                   10336:              &mt('Awarding [_1] percent for correct and [_2] percent for incorrect responses',
                   10337:                  $env{'form.pcorrect'},$env{'form.pincorrect'}).
                   10338:              '<br />';
1.522     www      10339:     if (($env{'form.gradingmechanism'} eq 'given') && ($number!=$foundgiven)) {
                   10340:        $result.='<span class="LC_error">'.&mt('Number of given answers does not agree with number of questions in file.').'</span>';
                   10341:        return $result.&show_grading_menu_form($symb);
                   10342:     } 
1.414     www      10343: # Remember Question Titles
                   10344: # FIXME: Possibly need delimiter other than ":"
                   10345:     for (my $i=0;$i<$number;$i++) {
                   10346:         $result.='<input type="hidden" name="question:'.$i.'" value="'.
                   10347:                  &HTML::Entities::encode($questiontitles[$i],'"&<>').'" />';
                   10348:     }
1.411     www      10349:     my $correct_count=0;
                   10350:     my $student_count=0;
                   10351:     my $unknown_count=0;
1.414     www      10352: # Match answers with usernames
                   10353: # FIXME: Possibly need delimiter other than ":"
1.409     albertel 10354:     foreach my $id (keys(%responses)) {
1.410     www      10355:        if ($correct_ids{$id}) {
1.414     www      10356:           $result.="\n".'<input type="hidden" name="correct:'.$correct_count.':'.$correct_ids{$id}.'" value="'.$responses{$id}.'" />';
1.411     www      10357:           $correct_count++;
1.410     www      10358:        } elsif ($clicker_ids{$id}) {
1.437     www      10359:           if ($clicker_ids{$id}=~/\,/) {
                   10360: # More than one user with the same clicker!
                   10361:              $result.="\n<hr />".&mt('Clicker registered more than once').": <tt>".$id."</tt><br />";
                   10362:              $result.="\n".'<input type="hidden" name="unknown:'.$id.'" value="'.$responses{$id}.'" />'.
                   10363:                            "<select name='multi".$id."'>";
                   10364:              foreach my $reguser (sort(split(/\,/,$clicker_ids{$id}))) {
                   10365:                  $result.="<option value='".$reguser."'>".&Apache::loncommon::plainname(split(/\:/,$reguser)).' ('.$reguser.')</option>';
                   10366:              }
                   10367:              $result.='</select>';
                   10368:              $unknown_count++;
                   10369:           } else {
                   10370: # Good: found one and only one user with the right clicker
                   10371:              $result.="\n".'<input type="hidden" name="student:'.$clicker_ids{$id}.'" value="'.$responses{$id}.'" />';
                   10372:              $student_count++;
                   10373:           }
1.410     www      10374:        } else {
1.411     www      10375:           $result.="\n<hr />".&mt('Unregistered Clicker')." <tt>".$id."</tt><br />";
                   10376:           $result.="\n".'<input type="hidden" name="unknown:'.$id.'" value="'.$responses{$id}.'" />'.
                   10377:                    "\n".&mt("Username").": <input type='text' name='uname".$id."' />&nbsp;".
                   10378:                    "\n".&mt("Domain").": ".
                   10379:                    &Apache::loncommon::select_dom_form($env{'course.'.$env{'request.course.id'}.'.domain'},'udom'.$id).'&nbsp;'.
1.596.2.4  raeburn  10380:                    &Apache::loncommon::selectstudent_link('clickeranalysis','uname'.$id,'udom'.$id,0,$id);
1.411     www      10381:           $unknown_count++;
1.410     www      10382:        }
1.405     www      10383:     }
1.412     www      10384:     $result.='<hr />'.
                   10385:              &mt('Found [_1] registered and [_2] unregistered clickers.',$student_count,$unknown_count);
1.521     www      10386:     if (($env{'form.gradingmechanism'} ne 'attendance') && ($env{'form.gradingmechanism'} ne 'given')) {
1.412     www      10387:        if ($correct_count==0) {
1.596.2.12.2.  8(raebur 10388:3):           $errormsg.="Found no correct answers for grading!";
1.412     www      10389:        } elsif ($correct_count>1) {
1.414     www      10390:           $result.='<br /><span class="LC_warning">'.&mt("Found [_1] entries for grading!",$correct_count).'</span>';
1.412     www      10391:        }
                   10392:     }
1.428     www      10393:     if ($number<1) {
                   10394:        $errormsg.="Found no questions.";
                   10395:     }
1.412     www      10396:     if ($errormsg) {
                   10397:        $result.='<br /><span class="LC_error">'.&mt($errormsg).'</span>';
                   10398:     } else {
                   10399:        $result.='<br /><input type="submit" name="finalize" value="'.&mt('Finalize Grading').'" />';
                   10400:     }
                   10401:     $result.='</form></td></tr></table>'."\n".
1.410     www      10402:              '</td></tr></table><br /><br />'."\n";
1.404     www      10403:     return $result.&show_grading_menu_form($symb);
1.400     www      10404: }
                   10405: 
1.405     www      10406: sub iclicker_eval {
1.406     www      10407:     my ($questiontitles,$responses)=@_;
1.405     www      10408:     my $number=0;
                   10409:     my $errormsg='';
                   10410:     foreach my $line (split(/[\n\r]/,$env{'form.upfile'})) {
1.410     www      10411:         my %components=&Apache::loncommon::record_sep($line);
                   10412:         my @entries=map {$components{$_}} (sort(keys(%components)));
1.408     albertel 10413: 	if ($entries[0] eq 'Question') {
                   10414: 	    for (my $i=3;$i<$#entries;$i+=6) {
                   10415: 		$$questiontitles[$number]=$entries[$i];
                   10416: 		$number++;
                   10417: 	    }
                   10418: 	}
                   10419: 	if ($entries[0]=~/^\#/) {
                   10420: 	    my $id=$entries[0];
                   10421: 	    my @idresponses;
                   10422: 	    $id=~s/^[\#0]+//;
                   10423: 	    for (my $i=0;$i<$number;$i++) {
                   10424: 		my $idx=3+$i*6;
1.596.2.4  raeburn  10425:                 $entries[$idx]=~s/[^a-zA-Z0-9\.\*\-\+]+//g;
1.408     albertel 10426: 		push(@idresponses,$entries[$idx]);
                   10427: 	    }
                   10428: 	    $$responses{$id}=join(',',@idresponses);
                   10429: 	}
1.405     www      10430:     }
                   10431:     return ($errormsg,$number);
                   10432: }
                   10433: 
1.419     www      10434: sub interwrite_eval {
                   10435:     my ($questiontitles,$responses)=@_;
                   10436:     my $number=0;
                   10437:     my $errormsg='';
1.420     www      10438:     my $skipline=1;
                   10439:     my $questionnumber=0;
                   10440:     my %idresponses=();
1.419     www      10441:     foreach my $line (split(/[\n\r]/,$env{'form.upfile'})) {
                   10442:         my %components=&Apache::loncommon::record_sep($line);
                   10443:         my @entries=map {$components{$_}} (sort(keys(%components)));
1.420     www      10444:         if ($entries[1] eq 'Time') { $skipline=0; next; }
                   10445:         if ($entries[1] eq 'Response') { $skipline=1; }
                   10446:         next if $skipline;
                   10447:         if ($entries[0]!=$questionnumber) {
                   10448:            $questionnumber=$entries[0];
                   10449:            $$questiontitles[$number]=&mt('Question [_1]',$questionnumber);
                   10450:            $number++;
1.419     www      10451:         }
1.420     www      10452:         my $id=$entries[4];
                   10453:         $id=~s/^[\#0]+//;
1.421     www      10454:         $id=~s/^v\d*\://i;
                   10455:         $id=~s/[\-\:]//g;
1.420     www      10456:         $idresponses{$id}[$number]=$entries[6];
                   10457:     }
1.524     raeburn  10458:     foreach my $id (keys(%idresponses)) {
1.420     www      10459:        $$responses{$id}=join(',',@{$idresponses{$id}});
                   10460:        $$responses{$id}=~s/^\s*\,//;
1.419     www      10461:     }
                   10462:     return ($errormsg,$number);
                   10463: }
                   10464: 
1.596.2.12.2.  (raeburn 10465:): sub turning_eval {
                   10466:):     my ($questiontitles,$responses)=@_;
                   10467:):     my $number=0;
                   10468:):     my $errormsg='';
                   10469:):     foreach my $line (split(/[\n\r]/,$env{'form.upfile'})) {
                   10470:):         my %components=&Apache::loncommon::record_sep($line);
                   10471:):         my @entries=map {$components{$_}} (sort(keys(%components)));
                   10472:):         if ($#entries>$number) { $number=$#entries; }
                   10473:):         my $id=$entries[0];
                   10474:):         my @idresponses;
                   10475:):         $id=~s/^[\#0]+//;
                   10476:):         unless ($id) { next; }
                   10477:):         for (my $idx=1;$idx<=$#entries;$idx++) {
                   10478:):             $entries[$idx]=~s/\,/\;/g;
                   10479:):             $entries[$idx]=~s/[^a-zA-Z0-9\.\*\-\+\;]+//g;
                   10480:):             push(@idresponses,$entries[$idx]);
                   10481:):         }
                   10482:):         $$responses{$id}=join(',',@idresponses);
                   10483:):     }
                   10484:):     for (my $i=1; $i<=$number; $i++) {
                   10485:):         $$questiontitles[$i]=&mt('Question [_1]',$i);
                   10486:):     }
                   10487:):     return ($errormsg,$number);
                   10488:): }
                   10489:): 
1.414     www      10490: sub assign_clicker_grades {
                   10491:     my ($r)=@_;
                   10492:     my ($symb)=&get_symb($r);
                   10493:     if (!$symb) {return '';}
1.416     www      10494: # See which part we are saving to
1.582     raeburn  10495:     my $res_error;
                   10496:     my ($partlist,$handgrade,$responseType) = &response_type($symb,\$res_error);
                   10497:     if ($res_error) {
                   10498:         return &navmap_errormsg();
                   10499:     }
1.416     www      10500: # FIXME: This should probably look for the first handgradeable part
                   10501:     my $part=$$partlist[0];
                   10502: # Start screen output
1.596.2.10  raeburn  10503:     my ($result) = &showResourceInfo($symb,$env{'form.probTitle'});
1.596.2.4  raeburn  10504: 
1.596.2.10  raeburn  10505:     $result .= '<br />'.
                   10506:                &Apache::loncommon::start_data_table().
1.596.2.4  raeburn  10507:                &Apache::loncommon::start_data_table_header_row().
                   10508:                '<th>'.&mt('Assigning grades based on clicker file').'</th>'.
                   10509:                &Apache::loncommon::end_data_table_header_row().
                   10510:                &Apache::loncommon::start_data_table_row().'<td>';
1.416     www      10511: 
1.414     www      10512: # Get correct result
                   10513: # FIXME: Possibly need delimiter other than ":"
                   10514:     my @correct=();
1.415     www      10515:     my $gradingmechanism=$env{'form.gradingmechanism'};
                   10516:     my $number=$env{'form.number'};
                   10517:     if ($gradingmechanism ne 'attendance') {
1.414     www      10518:        foreach my $key (keys(%env)) {
                   10519:           if ($key=~/^form\.correct\:/) {
                   10520:              my @input=split(/\,/,$env{$key});
                   10521:              for (my $i=0;$i<=$#input;$i++) {
                   10522:                  if (($correct[$i]) && ($input[$i]) &&
                   10523:                      ($correct[$i] ne $input[$i])) {
                   10524:                     $result.='<br /><span class="LC_warning">'.
                   10525:                              &mt('More than one correct result given for question "[_1]": [_2] versus [_3].',
                   10526:                                  $env{'form.question:'.$i},$correct[$i],$input[$i]).'</span>';
1.596.2.4  raeburn  10527:                  } elsif (($input[$i]) || ($input[$i] eq '0')) {
1.414     www      10528:                     $correct[$i]=$input[$i];
                   10529:                  }
                   10530:              }
                   10531:           }
                   10532:        }
1.415     www      10533:        for (my $i=0;$i<$number;$i++) {
1.596.2.4  raeburn  10534:           if ((!$correct[$i]) && ($correct[$i] ne '0')) {
1.414     www      10535:              $result.='<br /><span class="LC_error">'.
                   10536:                       &mt('No correct result given for question "[_1]"!',
                   10537:                           $env{'form.question:'.$i}).'</span>';
                   10538:           }
                   10539:        }
1.596.2.4  raeburn  10540:        $result.='<br />'.&mt("Correct answer: [_1]",join(', ',map { ((($_) || ($_ eq '0'))?$_:'-') } @correct));
1.414     www      10541:     }
                   10542: # Start grading
1.415     www      10543:     my $pcorrect=$env{'form.pcorrect'};
                   10544:     my $pincorrect=$env{'form.pincorrect'};
1.416     www      10545:     my $storecount=0;
1.596.2.4  raeburn  10546:     my %users=();
1.415     www      10547:     foreach my $key (keys(%env)) {
1.420     www      10548:        my $user='';
1.415     www      10549:        if ($key=~/^form\.student\:(.*)$/) {
1.420     www      10550:           $user=$1;
                   10551:        }
                   10552:        if ($key=~/^form\.unknown\:(.*)$/) {
                   10553:           my $id=$1;
                   10554:           if (($env{'form.uname'.$id}) && ($env{'form.udom'.$id})) {
                   10555:              $user=$env{'form.uname'.$id}.':'.$env{'form.udom'.$id};
1.437     www      10556:           } elsif ($env{'form.multi'.$id}) {
                   10557:              $user=$env{'form.multi'.$id};
1.420     www      10558:           }
                   10559:        }
1.596.2.4  raeburn  10560:        if ($user) {
                   10561:           if ($users{$user}) {
                   10562:              $result.='<br /><span class="LC_warning">'.
1.596.2.12.2.  8(raebur 10563:3):                       &mt('More than one entry found for [_1]!','<tt>'.$user.'</tt>').
1.596.2.4  raeburn  10564:                       '</span><br />';
                   10565:           }
                   10566:           $users{$user}=1;
1.415     www      10567:           my @answer=split(/\,/,$env{$key});
                   10568:           my $sum=0;
1.522     www      10569:           my $realnumber=$number;
1.415     www      10570:           for (my $i=0;$i<$number;$i++) {
1.576     www      10571:              if  ($correct[$i] eq '-') {
                   10572:                 $realnumber--;
                   10573:              } elsif ($answer[$i]) {
1.415     www      10574:                 if ($gradingmechanism eq 'attendance') {
                   10575:                    $sum+=$pcorrect;
1.576     www      10576:                 } elsif ($correct[$i] eq '*') {
1.522     www      10577:                    $sum+=$pcorrect;
1.415     www      10578:                 } else {
1.596.2.4  raeburn  10579: # We actually grade if correct or not
                   10580:                    my $increment=$pincorrect;
                   10581: # Special case: numerical answer "0"
                   10582:                    if ($correct[$i] eq '0') {
                   10583:                       if ($answer[$i]=~/^[0\.]+$/) {
                   10584:                          $increment=$pcorrect;
                   10585:                       }
                   10586: # General numerical answer, both evaluate to something non-zero
                   10587:                    } elsif ((1.0*$correct[$i]!=0) && (1.0*$answer[$i]!=0)) {
                   10588:                       if (1.0*$correct[$i]==1.0*$answer[$i]) {
                   10589:                          $increment=$pcorrect;
                   10590:                       }
                   10591: # Must be just alphanumeric
                   10592:                    } elsif ($answer[$i] eq $correct[$i]) {
                   10593:                       $increment=$pcorrect;
1.415     www      10594:                    }
1.596.2.4  raeburn  10595:                    $sum+=$increment;
1.415     www      10596:                 }
                   10597:              }
                   10598:           }
1.522     www      10599:           my $ave=$sum/(100*$realnumber);
1.416     www      10600: # Store
                   10601:           my ($username,$domain)=split(/\:/,$user);
                   10602:           my %grades=();
                   10603:           $grades{"resource.$part.solved"}='correct_by_override';
                   10604:           $grades{"resource.$part.awarded"}=$ave;
                   10605:           $grades{"resource.regrader"}="$env{'user.name'}:$env{'user.domain'}";
                   10606:           my $returncode=&Apache::lonnet::cstore(\%grades,$symb,
                   10607:                                                  $env{'request.course.id'},
                   10608:                                                  $domain,$username);
                   10609:           if ($returncode ne 'ok') {
                   10610:              $result.="<br /><span class=\"LC_error\">Failed to save student $username:$domain. Message when trying to save was ($returncode)</span>";
                   10611:           } else {
                   10612:              $storecount++;
                   10613:           }
1.415     www      10614:        }
                   10615:     }
                   10616: # We are done
1.549     hauer    10617:     $result.='<br />'.&mt('Successfully stored grades for [quant,_1,student].',$storecount).
1.596.2.4  raeburn  10618:              '</td>'.
                   10619:              &Apache::loncommon::end_data_table_row().
                   10620:              &Apache::loncommon::end_data_table()."<br /><br />\n";
1.414     www      10621:     return $result.&show_grading_menu_form($symb);
                   10622: }
                   10623: 
1.582     raeburn  10624: sub navmap_errormsg {
                   10625:     return '<div class="LC_error">'.
                   10626:            &mt('An error occurred retrieving information about resources in the course.').'<br />'.
1.595     raeburn  10627:            &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  10628:            '</div>';
                   10629: }
                   10630: 
1.596.2.12.2.  (raeburn 10631:): sub startpage {
                   10632:):     my ($r,$symb,$crumbs,$onlyfolderflag,$nodisplayflag,$stuvcurrent,$stuvdisp,$nomenu,$js) = @_;
                   10633:):     if ($nomenu) {
                   10634:):         $r->print(&Apache::loncommon::start_page("Student's Version",$js,{'only_body' => '1'}));
                   10635:):     } else {
                   10636:):         $r->print(&Apache::loncommon::start_page('Grading',$js,
                   10637:):                                                  {'bread_crumbs' => $crumbs}));
                   10638:):     }
                   10639:):     unless ($nodisplayflag) {
                   10640:):        $r->print(&Apache::lonhtmlcommon::resource_info_box($symb,$onlyfolderflag,$stuvcurrent,$stuvdisp));
                   10641:):     }
                   10642:): }
                   10643:): 
1.1       albertel 10644: sub handler {
1.41      ng       10645:     my $request=$_[0];
1.434     albertel 10646:     &reset_caches();
1.596.2.4  raeburn  10647:     if ($request->header_only) {
                   10648:         &Apache::loncommon::content_type($request,'text/html');
                   10649:         $request->send_http_header;
                   10650:         return OK;
1.41      ng       10651:     }
                   10652:     &Apache::loncommon::get_unprocessed_cgi($ENV{'QUERY_STRING'});
1.596.2.4  raeburn  10653: 
1.324     albertel 10654:     my $symb=&get_symb($request,1);
1.160     albertel 10655:     my @commands=&Apache::loncommon::get_env_multiple('form.command');
                   10656:     my $command=$commands[0];
1.447     foxr     10657: 
1.160     albertel 10658:     if ($#commands > 0) {
                   10659: 	&Apache::lonnet::logthis("grades got multiple commands ".join(':',@commands));
                   10660:     }
1.447     foxr     10661: 
1.513     foxr     10662:     $ssi_error = 0;
1.535     raeburn  10663:     my $brcrum = [{href=>"/adm/grades",text=>"Grading"}];
1.596.2.4  raeburn  10664:     my $start_page = &Apache::loncommon::start_page('Grading',undef,
1.596.2.12.2.  (raeburn 10665:):                                                     {'bread_crumbs' => $brcrum});
1.324     albertel 10666:     if ($symb eq '' && $command eq '') {
1.257     albertel 10667: 	if ($env{'user.adv'}) {
1.596.2.4  raeburn  10668:             &Apache::loncommon::content_type($request,'text/html');
                   10669:             $request->send_http_header;
                   10670:             $request->print($start_page);
1.257     albertel 10671: 	    if (($env{'form.codeone'}) && ($env{'form.codetwo'}) &&
                   10672: 		($env{'form.codethree'})) {
                   10673: 		my $token=$env{'form.codeone'}.'*'.$env{'form.codetwo'}.'*'.
                   10674: 		    $env{'form.codethree'};
1.41      ng       10675: 		my ($tsymb,$tuname,$tudom,$tcrsid)=
                   10676: 		    &Apache::lonnet::checkin($token);
                   10677: 		if ($tsymb) {
1.137     albertel 10678: 		    my ($map,$id,$url)=&Apache::lonnet::decode_symb($tsymb);
1.41      ng       10679: 		    if (&Apache::lonnet::allowed('mgr',$tcrsid)) {
1.513     foxr     10680: 			$request->print(&ssi_with_retries('/res/'.$url, $ssi_retries,
1.99      albertel 10681: 					  ('grade_username' => $tuname,
                   10682: 					   'grade_domain' => $tudom,
                   10683: 					   'grade_courseid' => $tcrsid,
                   10684: 					   'grade_symb' => $tsymb)));
1.41      ng       10685: 		    } else {
1.45      ng       10686: 			$request->print('<h3>Not authorized: '.$token.'</h3>');
1.99      albertel 10687: 		    }
1.41      ng       10688: 		} else {
1.45      ng       10689: 		    $request->print('<h3>Not a valid DocID: '.$token.'</h3>');
1.41      ng       10690: 		}
1.14      www      10691: 	    } else {
1.41      ng       10692: 		$request->print(&Apache::lonxml::tokeninputfield());
                   10693: 	    }
1.596.2.4  raeburn  10694:         } elsif ($env{'request.course.id'}) {
                   10695:             &init_perm(); 
                   10696:             if (!%perm) {
                   10697:                 $request->internal_redirect('/adm/quickgrades');
1.596.2.12.2.  3(raebur 10698:3):                 return OK;
1.596.2.4  raeburn  10699:             } else {
                   10700:                 &Apache::loncommon::content_type($request,'text/html');
                   10701:                 $request->send_http_header;
                   10702:                 $request->print($start_page);
                   10703:             }
                   10704:         }
1.41      ng       10705:     } else {
1.596.2.4  raeburn  10706:         &init_perm();
                   10707:         if (!$env{'request.course.id'}) {
1.596.2.11  raeburn  10708:             unless ((&Apache::lonnet::allowed('usc',$env{'request.role.domain'})) &&
                   10709:                     ($command =~ /^scantronupload/)) {
                   10710:                 # Not in a course.
                   10711:                 $env{'user.error.msg'}="/adm/grades::vgr:0:0:Cannot display grades page outside course context";
                   10712:                 return HTTP_NOT_ACCEPTABLE;
                   10713:             }
1.596.2.4  raeburn  10714:         } elsif (!%perm) {
                   10715:             $request->internal_redirect('/adm/quickgrades');
                   10716:         }
                   10717:         &Apache::loncommon::content_type($request,'text/html');
                   10718:         $request->send_http_header;
1.596.2.12.2.  (raeburn 10719:):         unless ((($command eq 'submission' || $command eq 'versionsub')) && ($perm{'vgr'})) {
                   10720:):             $request->print($start_page); 
                   10721:):         }
1.104     albertel 10722: 	if ($command eq 'submission' && $perm{'vgr'}) {
1.596.2.12.2.  (raeburn 10723:):             my ($stuvcurrent,$stuvdisp,$versionform,$js);
                   10724:):             if (($env{'form.student'} ne '') && ($env{'form.userdom'} ne '')) {
                   10725:):                 ($stuvcurrent,$stuvdisp,$versionform,$js) =
                   10726:):                     &choose_task_version_form($symb,$env{'form.student'},
                   10727:):                                               $env{'form.userdom'});
                   10728:):             }
                   10729:):             &startpage($request,$symb,[{href=>"", text=>"Student Submissions"}],undef,undef,$stuvcurrent,$stuvdisp,undef,$js);
                   10730:):             if ($versionform) {
                   10731:):                 $request->print($versionform);
                   10732:):             }
                   10733:):             $request->print('<br clear="all" />');
1.257     albertel 10734: 	    ($env{'form.student'} eq '' ? &listStudents($request) : &submission($request,0,0));
1.596.2.12.2.  (raeburn 10735:):         } elsif ($command eq 'versionsub' && $perm{'vgr'}) {
                   10736:):             my ($stuvcurrent,$stuvdisp,$versionform,$js) =
                   10737:):                 &choose_task_version_form($symb,$env{'form.student'},
                   10738:):                                           $env{'form.userdom'},
                   10739:):                                           $env{'form.inhibitmenu'});
                   10740:):             &startpage($request,$symb,[{href=>"", text=>"Previous Student Version"}],undef,undef,$stuvcurrent,$stuvdisp,$env{'form.inhibitmenu'},$js);
                   10741:):             if ($versionform) {
                   10742:):                 $request->print($versionform);
                   10743:):             }
                   10744:):             $request->print('<br clear="all" />');
                   10745:):             $request->print(&show_previous_task_version($request,$symb));
1.103     albertel 10746: 	} elsif ($command eq 'pickStudentPage' && $perm{'vgr'}) {
1.68      ng       10747: 	    &pickStudentPage($request);
1.103     albertel 10748: 	} elsif ($command eq 'displayPage' && $perm{'vgr'}) {
1.68      ng       10749: 	    &displayPage($request);
1.104     albertel 10750: 	} elsif ($command eq 'gradeByPage' && $perm{'mgr'}) {
1.71      ng       10751: 	    &updateGradeByPage($request);
1.104     albertel 10752: 	} elsif ($command eq 'processGroup' && $perm{'vgr'}) {
1.41      ng       10753: 	    &processGroup($request);
1.104     albertel 10754: 	} elsif ($command eq 'gradingmenu' && $perm{'vgr'}) {
1.443     banghart 10755: 	    $request->print(&grading_menu($request));
                   10756: 	} elsif ($command eq 'submit_options' && $perm{'vgr'}) {
                   10757: 	    $request->print(&submit_options($request));
1.104     albertel 10758: 	} elsif ($command eq 'viewgrades' && $perm{'vgr'}) {
1.41      ng       10759: 	    $request->print(&viewgrades($request));
1.104     albertel 10760: 	} elsif ($command eq 'handgrade' && $perm{'mgr'}) {
1.41      ng       10761: 	    $request->print(&processHandGrade($request));
1.106     albertel 10762: 	} elsif ($command eq 'editgrades' && $perm{'mgr'}) {
1.41      ng       10763: 	    $request->print(&editgrades($request));
1.106     albertel 10764: 	} elsif ($command eq 'verify' && $perm{'vgr'}) {
1.41      ng       10765: 	    $request->print(&verifyreceipt($request));
1.400     www      10766:         } elsif ($command eq 'processclicker' && $perm{'mgr'}) {
                   10767:             $request->print(&process_clicker($request));
                   10768:         } elsif ($command eq 'processclickerfile' && $perm{'mgr'}) {
                   10769:             $request->print(&process_clicker_file($request));
1.414     www      10770:         } elsif ($command eq 'assignclickergrades' && $perm{'mgr'}) {
                   10771:             $request->print(&assign_clicker_grades($request));
1.106     albertel 10772: 	} elsif ($command eq 'csvform' && $perm{'mgr'}) {
1.72      ng       10773: 	    $request->print(&upcsvScores_form($request));
1.106     albertel 10774: 	} elsif ($command eq 'csvupload' && $perm{'mgr'}) {
1.41      ng       10775: 	    $request->print(&csvupload($request));
1.106     albertel 10776: 	} elsif ($command eq 'csvuploadmap' && $perm{'mgr'} ) {
1.41      ng       10777: 	    $request->print(&csvuploadmap($request));
1.246     albertel 10778: 	} elsif ($command eq 'csvuploadoptions' && $perm{'mgr'}) {
1.257     albertel 10779: 	    if ($env{'form.associate'} ne 'Reverse Association') {
1.246     albertel 10780: 		$request->print(&csvuploadoptions($request));
1.41      ng       10781: 	    } else {
1.257     albertel 10782: 		if ( $env{'form.upfile_associate'} ne 'reverse' ) {
                   10783: 		    $env{'form.upfile_associate'} = 'reverse';
1.41      ng       10784: 		} else {
1.257     albertel 10785: 		    $env{'form.upfile_associate'} = 'forward';
1.41      ng       10786: 		}
                   10787: 		$request->print(&csvuploadmap($request));
                   10788: 	    }
1.246     albertel 10789: 	} elsif ($command eq 'csvuploadassign' && $perm{'mgr'} ) {
                   10790: 	    $request->print(&csvuploadassign($request));
1.106     albertel 10791: 	} elsif ($command eq 'scantron_selectphase' && $perm{'mgr'}) {
1.75      albertel 10792: 	    $request->print(&scantron_selectphase($request));
1.203     albertel 10793:  	} elsif ($command eq 'scantron_warning' && $perm{'mgr'}) {
                   10794:  	    $request->print(&scantron_do_warning($request));
1.142     albertel 10795: 	} elsif ($command eq 'scantron_validate' && $perm{'mgr'}) {
                   10796: 	    $request->print(&scantron_validate_file($request));
1.106     albertel 10797: 	} elsif ($command eq 'scantron_process' && $perm{'mgr'}) {
1.82      albertel 10798: 	    $request->print(&scantron_process_students($request));
1.157     albertel 10799:  	} elsif ($command eq 'scantronupload' && 
1.257     albertel 10800:  		 (&Apache::lonnet::allowed('usc',$env{'request.role.domain'})||
                   10801: 		  &Apache::lonnet::allowed('usc',$env{'request.course.id'}))) {
1.162     albertel 10802:  	    $request->print(&scantron_upload_scantron_data($request)); 
1.157     albertel 10803:  	} elsif ($command eq 'scantronupload_save' &&
1.257     albertel 10804:  		 (&Apache::lonnet::allowed('usc',$env{'request.role.domain'})||
                   10805: 		  &Apache::lonnet::allowed('usc',$env{'request.course.id'}))) {
1.157     albertel 10806:  	    $request->print(&scantron_upload_scantron_data_save($request));
1.202     albertel 10807:  	} elsif ($command eq 'scantron_download' &&
1.257     albertel 10808: 		 &Apache::lonnet::allowed('usc',$env{'request.course.id'})) {
1.162     albertel 10809:  	    $request->print(&scantron_download_scantron_data($request));
1.523     raeburn  10810:         } elsif ($command eq 'checksubmissions' && $perm{'vgr'}) {
                   10811:             $request->print(&checkscantron_results($request));     
1.106     albertel 10812: 	} elsif ($command) {
1.562     bisitz   10813: 	    $request->print('<p class="LC_error">'.&mt('Access Denied ([_1])',$command).'</p>');
1.26      albertel 10814: 	}
1.2       albertel 10815:     }
1.513     foxr     10816:     if ($ssi_error) {
                   10817: 	&ssi_print_error($request);
                   10818:     }
1.353     albertel 10819:     $request->print(&Apache::loncommon::end_page());
1.434     albertel 10820:     &reset_caches();
1.596.2.4  raeburn  10821:     return OK;
1.44      ng       10822: }
                   10823: 
1.1       albertel 10824: 1;
                   10825: 
1.13      albertel 10826: __END__;
1.531     jms      10827: 
                   10828: 
                   10829: =head1 NAME
                   10830: 
                   10831: Apache::grades
                   10832: 
                   10833: =head1 SYNOPSIS
                   10834: 
                   10835: Handles the viewing of grades.
                   10836: 
                   10837: This is part of the LearningOnline Network with CAPA project
                   10838: described at http://www.lon-capa.org.
                   10839: 
                   10840: =head1 OVERVIEW
                   10841: 
                   10842: Do an ssi with retries:
                   10843: While I'd love to factor out this with the vesrion in lonprintout,
                   10844: 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
                   10845: I'm not quite ready to invent (e.g. an ssi_with_retry object).
                   10846: 
                   10847: At least the logic that drives this has been pulled out into loncommon.
                   10848: 
                   10849: 
                   10850: 
                   10851: ssi_with_retries - Does the server side include of a resource.
                   10852:                      if the ssi call returns an error we'll retry it up to
                   10853:                      the number of times requested by the caller.
1.596.2.12.2.  8(raebur 10854:4):                      If we still have a problem, no text is appended to the
1.531     jms      10855:                      output and we set some global variables.
                   10856:                      to indicate to the caller an SSI error occurred.  
                   10857:                      All of this is supposed to deal with the issues described
1.596.2.12.2.  8(raebur 10858:4):                      in LON-CAPA BZ 5631 see:
1.531     jms      10859:                      http://bugs.lon-capa.org/show_bug.cgi?id=5631
                   10860:                      by informing the user that this happened.
                   10861: 
                   10862: Parameters:
                   10863:   resource   - The resource to include.  This is passed directly, without
                   10864:                interpretation to lonnet::ssi.
                   10865:   form       - The form hash parameters that guide the interpretation of the resource
                   10866:                
                   10867:   retries    - Number of retries allowed before giving up completely.
                   10868: Returns:
                   10869:   On success, returns the rendered resource identified by the resource parameter.
                   10870: Side Effects:
                   10871:   The following global variables can be set:
                   10872:    ssi_error                - If an unrecoverable error occurred this becomes true.
                   10873:                               It is up to the caller to initialize this to false
                   10874:                               if desired.
                   10875:    ssi_error_resource  - If an unrecoverable error occurred, this is the value
                   10876:                               of the resource that could not be rendered by the ssi
                   10877:                               call.
                   10878:    ssi_error_message   - The error string fetched from the ssi response
                   10879:                               in the event of an error.
                   10880: 
                   10881: 
                   10882: =head1 HANDLER SUBROUTINE
                   10883: 
                   10884: ssi_with_retries()
                   10885: 
                   10886: =head1 SUBROUTINES
                   10887: 
                   10888: =over
                   10889: 
                   10890: =item scantron_get_correction() : 
                   10891: 
                   10892:    Builds the interface screen to interact with the operator to fix a
                   10893:    specific error condition in a specific scanline
                   10894: 
                   10895:  Arguments:
                   10896:     $r           - Apache request object
                   10897:     $i           - number of the current scanline
                   10898:     $scan_record - hash ref as returned from &scantron_parse_scanline()
                   10899:     $scan_config - hash ref as returned from &get_scantron_config()
                   10900:     $line        - full contents of the current scanline
                   10901:     $error       - error condition, valid values are
                   10902:                    'incorrectCODE', 'duplicateCODE',
                   10903:                    'doublebubble', 'missingbubble',
                   10904:                    'duplicateID', 'incorrectID'
                   10905:     $arg         - extra information needed
                   10906:        For errors:
                   10907:          - duplicateID   - paper number that this studentID was seen before on
                   10908:          - duplicateCODE - array ref of the paper numbers this CODE was
                   10909:                            seen on before
                   10910:          - incorrectCODE - current incorrect CODE 
                   10911:          - doublebubble  - array ref of the bubble lines that have double
                   10912:                            bubble errors
                   10913:          - missingbubble - array ref of the bubble lines that have missing
                   10914:                            bubble errors
                   10915: 
1.596.2.12.2.  6(raebur 10916:3):    $randomorder - True if exam folder has randomorder set
                   10917:3):    $randompick  - True if exam folder has randompick set
                   10918:3):    $respnumlookup - Reference to HASH mapping question numbers in bubble lines
                   10919:3):                      for current line to question number used for same question
                   10920:3):                      in "Master Seqence" (as seen by Course Coordinator).
                   10921:3):    $startline   - Reference to hash where key is question number (0 is first)
                   10922:3):                   and value is number of first bubble line for current student
                   10923:3):                   or code-based randompick and/or randomorder.
                   10924:3): 
                   10925:3): 
1.531     jms      10926: =item  scantron_get_maxbubble() : 
                   10927: 
1.582     raeburn  10928:    Arguments:
                   10929:        $nav_error  - Reference to scalar which is a flag to indicate a
                   10930:                       failure to retrieve a navmap object.
                   10931:        if $nav_error is set to 1 by scantron_get_maxbubble(), the 
                   10932:        calling routine should trap the error condition and display the warning
                   10933:        found in &navmap_errormsg().
                   10934: 
1.596.2.12.2.  (raeburn 10935:):        $scantron_config - Reference to bubblesheet format configuration hash.
                   10936:): 
1.531     jms      10937:    Returns the maximum number of bubble lines that are expected to
                   10938:    occur. Does this by walking the selected sequence rendering the
                   10939:    resource and then checking &Apache::lonxml::get_problem_counter()
                   10940:    for what the current value of the problem counter is.
                   10941: 
                   10942:    Caches the results to $env{'form.scantron_maxbubble'},
                   10943:    $env{'form.scantron.bubble_lines.n'}, 
                   10944:    $env{'form.scantron.first_bubble_line.n'} and
                   10945:    $env{"form.scantron.sub_bubblelines.n"}
1.596.2.12.2.  6(raebur 10946:3):    which are the total number of bubble lines, the number of bubble
1.531     jms      10947:    lines for response n and number of the first bubble line for response n,
                   10948:    and a comma separated list of numbers of bubble lines for sub-questions
                   10949:    (for optionresponse, matchresponse, and rankresponse items), for response n.  
                   10950: 
                   10951: 
                   10952: =item  scantron_validate_missingbubbles() : 
                   10953: 
                   10954:    Validates all scanlines in the selected file to not have any
                   10955:     answers that don't have bubbles that have not been verified
                   10956:     to be bubble free.
                   10957: 
                   10958: =item  scantron_process_students() : 
                   10959: 
1.596.2.6  raeburn  10960:    Routine that does the actual grading of the bubblesheet information.
1.531     jms      10961: 
                   10962:    The parsed scanline hash is added to %env 
                   10963: 
                   10964:    Then foreach unskipped scanline it does an &Apache::lonnet::ssi()
                   10965:    foreach resource , with the form data of
                   10966: 
                   10967: 	'submitted'     =>'scantron' 
                   10968: 	'grade_target'  =>'grade',
                   10969: 	'grade_username'=> username of student
                   10970: 	'grade_domain'  => domain of student
                   10971: 	'grade_courseid'=> of course
                   10972: 	'grade_symb'    => symb of resource to grade
                   10973: 
                   10974:     This triggers a grading pass. The problem grading code takes care
                   10975:     of converting the bubbled letter information (now in %env) into a
                   10976:     valid submission.
                   10977: 
                   10978: =item  scantron_upload_scantron_data() :
                   10979: 
1.596.2.6  raeburn  10980:     Creates the screen for adding a new bubblesheet data file to a course.
1.531     jms      10981: 
                   10982: =item  scantron_upload_scantron_data_save() : 
                   10983: 
                   10984:    Adds a provided bubble information data file to the course if user
                   10985:    has the correct privileges to do so. 
                   10986: 
                   10987: =item  valid_file() :
                   10988: 
                   10989:    Validates that the requested bubble data file exists in the course.
                   10990: 
                   10991: =item  scantron_download_scantron_data() : 
                   10992: 
                   10993:    Shows a list of the three internal files (original, corrected,
1.596.2.6  raeburn  10994:    skipped) for a specific bubblesheet data file that exists in the
1.531     jms      10995:    course.
                   10996: 
                   10997: =item  scantron_validate_ID() : 
                   10998: 
                   10999:    Validates all scanlines in the selected file to not have any
1.556     weissno  11000:    invalid or underspecified student/employee IDs
1.531     jms      11001: 
1.582     raeburn  11002: =item navmap_errormsg() :
                   11003: 
                   11004:    Returns HTML mark-up inside a <div></div> with a link to re-initialize the course.
                   11005:    Should be called whenever the request to instantiate a navmap object fails.  
                   11006: 
1.531     jms      11007: =back
                   11008: 
                   11009: =cut

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