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

1.17      albertel    1: # The LearningOnline Network with CAPA
1.13      albertel    2: # The LON-CAPA Grading handler
1.17      albertel    3: #
1.597   ! wenzelju    4: # $Id: grades.pm,v 1.596 2010/02/28 23:31:42 raeburn Exp $
1.17      albertel    5: #
                      6: # Copyright Michigan State University Board of Trustees
                      7: #
                      8: # This file is part of the LearningOnline Network with CAPA (LON-CAPA).
                      9: #
                     10: # LON-CAPA is free software; you can redistribute it and/or modify
                     11: # it under the terms of the GNU General Public License as published by
                     12: # the Free Software Foundation; either version 2 of the License, or
                     13: # (at your option) any later version.
                     14: #
                     15: # LON-CAPA is distributed in the hope that it will be useful,
                     16: # but WITHOUT ANY WARRANTY; without even the implied warranty of
                     17: # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
                     18: # GNU General Public License for more details.
                     19: #
                     20: # You should have received a copy of the GNU General Public License
                     21: # along with LON-CAPA; if not, write to the Free Software
                     22: # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
                     23: #
                     24: # /home/httpd/html/adm/gpl.txt
                     25: #
                     26: # http://www.lon-capa.org/
                     27: #
1.1       albertel   28: 
1.529     jms        29: 
                     30: 
1.1       albertel   31: package Apache::grades;
                     32: use strict;
                     33: use Apache::style;
                     34: use Apache::lonxml;
                     35: use Apache::lonnet;
1.3       albertel   36: use Apache::loncommon;
1.112     ng         37: use Apache::lonhtmlcommon;
1.68      ng         38: use Apache::lonnavmaps;
1.1       albertel   39: use Apache::lonhomework;
1.456     banghart   40: use Apache::lonpickcode;
1.55      matthew    41: use Apache::loncoursedata;
1.362     albertel   42: use Apache::lonmsg();
1.1       albertel   43: use Apache::Constants qw(:common);
1.167     sakharuk   44: use Apache::lonlocal;
1.386     raeburn    45: use Apache::lonenc;
1.170     albertel   46: use String::Similarity;
1.359     www        47: use LONCAPA;
                     48: 
1.315     bowersj2   49: use POSIX qw(floor);
1.87      www        50: 
1.435     foxr       51: 
1.513     foxr       52: 
1.435     foxr       53: my %perm=();
1.447     foxr       54: 
1.513     foxr       55: #  These variables are used to recover from ssi errors
                     56: 
                     57: my $ssi_retries = 5;
                     58: my $ssi_error;
                     59: my $ssi_error_resource;
                     60: my $ssi_error_message;
                     61: 
                     62: 
                     63: sub ssi_with_retries {
                     64:     my ($resource, $retries, %form) = @_;
                     65:     my ($content, $response) = &Apache::loncommon::ssi_with_retries($resource, $retries, %form);
                     66:     if ($response->is_error) {
                     67: 	$ssi_error          = 1;
                     68: 	$ssi_error_resource = $resource;
                     69: 	$ssi_error_message  = $response->code . " " . $response->message;
                     70:     }
                     71: 
                     72:     return $content;
                     73: 
                     74: }
                     75: #
                     76: #  Prodcuces an ssi retry failure error message to the user:
                     77: #
                     78: 
                     79: sub ssi_print_error {
                     80:     my ($r) = @_;
1.516     raeburn    81:     my $helpurl = &Apache::loncommon::top_nav_help('Helpdesk');
                     82:     $r->print('
                     83: <br />
                     84: <h2>'.&mt('An unrecoverable network error occurred:').'</h2>
                     85: <p>
                     86: '.&mt('Unable to retrieve a resource from a server:').'<br />
                     87: '.&mt('Resource:').' '.$ssi_error_resource.'<br />
                     88: '.&mt('Error:').' '.$ssi_error_message.'
                     89: </p>
                     90: <p>'.
                     91: &mt('It is recommended that you try again later, as this error may mean the server was just temporarily unavailable, or is down for maintenance.').'<br />'.
                     92: &mt('If the error persists, please contact the [_1] for assistance.',$helpurl).
                     93: '</p>');
                     94:     return;
1.513     foxr       95: }
                     96: 
1.44      ng         97: #
1.146     albertel   98: # --- Retrieve the parts from the metadata file.---
1.44      ng         99: sub getpartlist {
1.582     raeburn   100:     my ($symb,$errorref) = @_;
1.439     albertel  101: 
                    102:     my $navmap   = Apache::lonnavmaps::navmap->new();
1.582     raeburn   103:     unless (ref($navmap)) {
                    104:         if (ref($errorref)) { 
                    105:             $$errorref = 'navmap';
                    106:             return;
                    107:         }
                    108:     }
1.439     albertel  109:     my $res      = $navmap->getBySymb($symb);
                    110:     my $partlist = $res->parts();
                    111:     my $url      = $res->src();
                    112:     my @metakeys = split(/,/,&Apache::lonnet::metadata($url,'keys'));
                    113: 
1.146     albertel  114:     my @stores;
1.439     albertel  115:     foreach my $part (@{ $partlist }) {
1.146     albertel  116: 	foreach my $key (@metakeys) {
                    117: 	    if ($key =~ m/^stores_\Q$part\E_/) { push(@stores,$key); }
                    118: 	}
                    119:     }
                    120:     return @stores;
1.2       albertel  121: }
                    122: 
1.44      ng        123: # --- Get the symbolic name of a problem and the url
1.324     albertel  124: sub get_symb {
1.173     albertel  125:     my ($request,$silent) = @_;
1.257     albertel  126:     (my $url=$env{'form.url'}) =~ s-^http://($ENV{'SERVER_NAME'}|$ENV{'HTTP_HOST'})--;
                    127:     my $symb=($env{'form.symb'} ne '' ? $env{'form.symb'} : (&Apache::lonnet::symbread($url)));
1.173     albertel  128:     if ($symb eq '') { 
                    129: 	if (!$silent) {
                    130: 	    $request->print("Unable to handle ambiguous references:$url:.");
                    131: 	    return ();
                    132: 	}
                    133:     }
1.418     albertel  134:     &Apache::lonenc::check_decrypt(\$symb);
1.324     albertel  135:     return ($symb);
1.32      ng        136: }
                    137: 
1.129     ng        138: #--- Format fullname, username:domain if different for display
                    139: #--- Use anywhere where the student names are listed
                    140: sub nameUserString {
                    141:     my ($type,$fullname,$uname,$udom) = @_;
                    142:     if ($type eq 'header') {
1.485     albertel  143: 	return '<b>&nbsp;'.&mt('Fullname').'&nbsp;</b><span class="LC_internal_info">('.&mt('Username').')</span>';
1.129     ng        144:     } else {
1.398     albertel  145: 	return '&nbsp;'.$fullname.'<span class="LC_internal_info">&nbsp;('.$uname.
                    146: 	    ($env{'user.domain'} eq $udom ? '' : ' ('.$udom.')').')</span>';
1.129     ng        147:     }
                    148: }
                    149: 
1.44      ng        150: #--- Get the partlist and the response type for a given problem. ---
                    151: #--- Indicate if a response type is coded handgraded or not. ---
1.39      ng        152: sub response_type {
1.582     raeburn   153:     my ($symb,$response_error) = @_;
1.377     albertel  154: 
                    155:     my $navmap = Apache::lonnavmaps::navmap->new();
1.582     raeburn   156:     unless (ref($navmap)) {
                    157:         if (ref($response_error)) {
                    158:             $$response_error = 1;
                    159:         }
                    160:         return;
                    161:     }
1.377     albertel  162:     my $res = $navmap->getBySymb($symb);
1.593     raeburn   163:     unless (ref($res)) {
                    164:         $$response_error = 1;
                    165:         return;
                    166:     }
1.377     albertel  167:     my $partlist = $res->parts();
1.392     albertel  168:     my %vPart = 
                    169: 	map { $_ => 1 } (&Apache::loncommon::get_env_multiple('form.vPart'));
1.377     albertel  170:     my (%response_types,%handgrade);
                    171:     foreach my $part (@{ $partlist }) {
1.392     albertel  172: 	next if (%vPart && !exists($vPart{$part}));
                    173: 
1.377     albertel  174: 	my @types = $res->responseType($part);
                    175: 	my @ids = $res->responseIds($part);
                    176: 	for (my $i=0; $i < scalar(@ids); $i++) {
                    177: 	    $response_types{$part}{$ids[$i]} = $types[$i];
                    178: 	    $handgrade{$part.'_'.$ids[$i]} = 
                    179: 		&Apache::lonnet::EXT('resource.'.$part.'_'.$ids[$i].
                    180: 				     '.handgrade',$symb);
1.41      ng        181: 	}
                    182:     }
1.377     albertel  183:     return ($partlist,\%handgrade,\%response_types);
1.39      ng        184: }
                    185: 
1.375     albertel  186: sub flatten_responseType {
                    187:     my ($responseType) = @_;
                    188:     my @part_response_id =
                    189: 	map { 
                    190: 	    my $part = $_;
                    191: 	    map {
                    192: 		[$part,$_]
                    193: 		} sort(keys(%{ $responseType->{$part} }));
                    194: 	} sort(keys(%$responseType));
                    195:     return @part_response_id;
                    196: }
                    197: 
1.207     albertel  198: sub get_display_part {
1.324     albertel  199:     my ($partID,$symb)=@_;
1.207     albertel  200:     my $display=&Apache::lonnet::EXT('resource.'.$partID.'.display',$symb);
                    201:     if (defined($display) and $display ne '') {
1.577     bisitz    202:         $display.= ' (<span class="LC_internal_info">'
                    203:                   .&mt('Part ID: [_1]',$partID).'</span>)';
1.207     albertel  204:     } else {
                    205: 	$display=$partID;
                    206:     }
                    207:     return $display;
                    208: }
1.269     raeburn   209: 
1.118     ng        210: #--- Show resource title
                    211: #--- and parts and response type
                    212: sub showResourceInfo {
1.582     raeburn   213:     my ($symb,$probTitle,$checkboxes,$res_error) = @_;
1.398     albertel  214:     my $result = '<h3>'.&mt('Current Resource').': '.$probTitle.'</h3>'."\n";
1.582     raeburn   215:     my ($partlist,$handgrade,$responseType) = &response_type($symb,$res_error);
                    216:     if (ref($res_error)) {
                    217:         if ($$res_error) {
                    218:             return;
                    219:         }
                    220:     }
1.584     bisitz    221:     $result.=&Apache::loncommon::start_data_table()
                    222:             .&Apache::loncommon::start_data_table_header_row();
                    223:     if ($checkboxes) {
                    224:         $result.='<th>&nbsp;</th>';
                    225:     }
                    226:     $result.='<th>'.&mt('Problem Part').'</th>'
                    227:             .'<th>'.&mt('Res. ID').'</th>'
                    228:             .'<th>'.&mt('Type').'</th>'
                    229:             .&Apache::loncommon::end_data_table_header_row();
1.126     ng        230:     my %resptype = ();
1.122     ng        231:     my $hdgrade='no';
1.154     albertel  232:     my %partsseen;
1.524     raeburn   233:     foreach my $partID (sort(keys(%$responseType))) {
1.584     bisitz    234:         foreach my $resID (sort(keys(%{ $responseType->{$partID} }))) {
                    235:             my $handgrade=$$handgrade{$partID.'_'.$resID};
                    236:             my $responsetype = $responseType->{$partID}->{$resID};
                    237:             $hdgrade = $handgrade if ($handgrade eq 'yes');
                    238:             $result.=&Apache::loncommon::start_data_table_row();
                    239:             if ($checkboxes) {
                    240:                 if (exists($partsseen{$partID})) {
                    241:                     $result.="<td>&nbsp;</td>";
                    242:                 } else {
                    243:                     $result.="<td><input type='checkbox' name='vPart' value='$partID' checked='checked' /></td>";
                    244:                 }
                    245:                 $partsseen{$partID}=1;
                    246:             }
                    247:             my $display_part=&get_display_part($partID,$symb);
                    248:             $result.='<td>'.$display_part.'</td>'
                    249:                     .'<td>'.'<span class="LC_internal_info">'.$resID.'</span></td>'
                    250:                     .'<td>'.&mt($responsetype).'</td>'
                    251: #                   .'<td>'.&mt('<b>Handgrade: </b>[_1]',$handgrade).'</td>'
                    252:                     .&Apache::loncommon::end_data_table_row();
                    253:         }
1.118     ng        254:     }
1.584     bisitz    255:     $result.=&Apache::loncommon::end_data_table();
1.147     albertel  256:     return $result,$responseType,$hdgrade,$partlist,$handgrade;
1.118     ng        257: }
                    258: 
1.434     albertel  259: sub reset_caches {
                    260:     &reset_analyze_cache();
                    261:     &reset_perm();
                    262: }
                    263: 
                    264: {
                    265:     my %analyze_cache;
1.557     raeburn   266:     my %analyze_cache_formkeys;
1.148     albertel  267: 
1.434     albertel  268:     sub reset_analyze_cache {
                    269: 	undef(%analyze_cache);
1.557     raeburn   270:         undef(%analyze_cache_formkeys);
1.434     albertel  271:     }
                    272: 
                    273:     sub get_analyze {
1.557     raeburn   274: 	my ($symb,$uname,$udom,$no_increment,$add_to_hash)=@_;
1.434     albertel  275: 	my $key = "$symb\0$uname\0$udom";
1.557     raeburn   276: 	if (exists($analyze_cache{$key})) {
                    277:             my $getupdate = 0;
                    278:             if (ref($add_to_hash) eq 'HASH') {
                    279:                 foreach my $item (keys(%{$add_to_hash})) {
                    280:                     if (ref($analyze_cache_formkeys{$key}) eq 'HASH') {
                    281:                         if (!exists($analyze_cache_formkeys{$key}{$item})) {
                    282:                             $getupdate = 1;
                    283:                             last;
                    284:                         }
                    285:                     } else {
                    286:                         $getupdate = 1;
                    287:                     }
                    288:                 }
                    289:             }
                    290:             if (!$getupdate) {
                    291:                 return $analyze_cache{$key};
                    292:             }
                    293:         }
1.434     albertel  294: 
                    295: 	my (undef,undef,$url)=&Apache::lonnet::decode_symb($symb);
                    296: 	$url=&Apache::lonnet::clutter($url);
1.557     raeburn   297:         my %form = ('grade_target'      => 'analyze',
                    298:                     'grade_domain'      => $udom,
                    299:                     'grade_symb'        => $symb,
                    300:                     'grade_courseid'    =>  $env{'request.course.id'},
                    301:                     'grade_username'    => $uname,
                    302:                     'grade_noincrement' => $no_increment);
                    303:         if (ref($add_to_hash)) {
                    304:             %form = (%form,%{$add_to_hash});
                    305:         } 
                    306: 	my $subresult=&ssi_with_retries($url, $ssi_retries,%form);
1.434     albertel  307: 	(undef,$subresult)=split(/_HASH_REF__/,$subresult,2);
                    308: 	my %analyze=&Apache::lonnet::str2hash($subresult);
1.557     raeburn   309:         if (ref($add_to_hash) eq 'HASH') {
                    310:             $analyze_cache_formkeys{$key} = $add_to_hash;
                    311:         } else {
                    312:             $analyze_cache_formkeys{$key} = {};
                    313:         }
1.434     albertel  314: 	return $analyze_cache{$key} = \%analyze;
                    315:     }
                    316: 
                    317:     sub get_order {
1.525     raeburn   318: 	my ($partid,$respid,$symb,$uname,$udom,$no_increment)=@_;
                    319: 	my $analyze = &get_analyze($symb,$uname,$udom,$no_increment);
1.434     albertel  320: 	return $analyze->{"$partid.$respid.shown"};
                    321:     }
                    322: 
                    323:     sub get_radiobutton_correct_foil {
                    324: 	my ($partid,$respid,$symb,$uname,$udom)=@_;
                    325: 	my $analyze = &get_analyze($symb,$uname,$udom);
1.555     raeburn   326:         my $foils = &get_order($partid,$respid,$symb,$uname,$udom);
                    327:         if (ref($foils) eq 'ARRAY') {
                    328: 	    foreach my $foil (@{$foils}) {
                    329: 	        if ($analyze->{"$partid.$respid.foil.value.$foil"} eq 'true') {
                    330: 		    return $foil;
                    331: 	        }
1.434     albertel  332: 	    }
                    333: 	}
                    334:     }
1.554     raeburn   335: 
                    336:     sub scantron_partids_tograde {
1.557     raeburn   337:         my ($resource,$cid,$uname,$udom,$check_for_randomlist) = @_;
1.554     raeburn   338:         my (%analysis,@parts);
                    339:         if (ref($resource)) {
                    340:             my $symb = $resource->symb();
1.557     raeburn   341:             my $add_to_form;
                    342:             if ($check_for_randomlist) {
                    343:                 $add_to_form = { 'check_parts_withrandomlist' => 1,};
                    344:             }
                    345:             my $analyze = &get_analyze($symb,$uname,$udom,undef,$add_to_form);
1.554     raeburn   346:             if (ref($analyze) eq 'HASH') {
                    347:                 %analysis = %{$analyze};
                    348:             }
                    349:             if (ref($analysis{'parts'}) eq 'ARRAY') {
                    350:                 foreach my $part (@{$analysis{'parts'}}) {
                    351:                     my ($id,$respid) = split(/\./,$part);
                    352:                     if (!&Apache::loncommon::check_if_partid_hidden($id,$symb,$udom,$uname)) {
                    353:                         push(@parts,$part);
                    354:                     }
                    355:                 }
                    356:             }
                    357:         }
                    358:         return (\%analysis,\@parts);
                    359:     }
                    360: 
1.148     albertel  361: }
1.434     albertel  362: 
1.118     ng        363: #--- Clean response type for display
1.335     albertel  364: #--- Currently filters option/rank/radiobutton/match/essay/Task
                    365: #        response types only.
1.118     ng        366: sub cleanRecord {
1.336     albertel  367:     my ($answer,$response,$symb,$partid,$respid,$record,$order,$version,
                    368: 	$uname,$udom) = @_;
1.398     albertel  369:     my $grayFont = '<span class="LC_internal_info">';
1.148     albertel  370:     if ($response =~ /^(option|rank)$/) {
                    371: 	my %answer=&Apache::lonnet::str2hash($answer);
                    372: 	my %grading=&Apache::lonnet::str2hash($record->{$version."resource.$partid.$respid.submissiongrading"});
                    373: 	my ($toprow,$bottomrow);
                    374: 	foreach my $foil (@$order) {
                    375: 	    if ($grading{$foil} == 1) {
                    376: 		$toprow.='<td><b>'.$answer{$foil}.'&nbsp;</b></td>';
                    377: 	    } else {
                    378: 		$toprow.='<td><i>'.$answer{$foil}.'&nbsp;</i></td>';
                    379: 	    }
1.398     albertel  380: 	    $bottomrow.='<td>'.$grayFont.$foil.'</span>&nbsp;</td>';
1.148     albertel  381: 	}
                    382: 	return '<blockquote><table border="1">'.
1.466     albertel  383: 	    '<tr valign="top"><td>'.&mt('Answer').'</td>'.$toprow.'</tr>'.
                    384: 	    '<tr valign="top"><td>'.$grayFont.&mt('Option ID').'</span></td>'.
1.148     albertel  385: 	    $grayFont.$bottomrow.'</tr>'.'</table></blockquote>';
                    386:     } elsif ($response eq 'match') {
                    387: 	my %answer=&Apache::lonnet::str2hash($answer);
                    388: 	my %grading=&Apache::lonnet::str2hash($record->{$version."resource.$partid.$respid.submissiongrading"});
                    389: 	my @items=&Apache::lonnet::str2array($record->{$version."resource.$partid.$respid.submissionitems"});
                    390: 	my ($toprow,$middlerow,$bottomrow);
                    391: 	foreach my $foil (@$order) {
                    392: 	    my $item=shift(@items);
                    393: 	    if ($grading{$foil} == 1) {
                    394: 		$toprow.='<td><b>'.$item.'&nbsp;</b></td>';
1.398     albertel  395: 		$middlerow.='<td><b>'.$grayFont.$answer{$foil}.'&nbsp;</span></b></td>';
1.148     albertel  396: 	    } else {
                    397: 		$toprow.='<td><i>'.$item.'&nbsp;</i></td>';
1.398     albertel  398: 		$middlerow.='<td><i>'.$grayFont.$answer{$foil}.'&nbsp;</span></i></td>';
1.148     albertel  399: 	    }
1.398     albertel  400: 	    $bottomrow.='<td>'.$grayFont.$foil.'</span>&nbsp;</td>';
1.118     ng        401: 	}
1.126     ng        402: 	return '<blockquote><table border="1">'.
1.466     albertel  403: 	    '<tr valign="top"><td>'.&mt('Answer').'</td>'.$toprow.'</tr>'.
                    404: 	    '<tr valign="top"><td>'.$grayFont.&mt('Item ID').'</span></td>'.
1.148     albertel  405: 	    $middlerow.'</tr>'.
1.466     albertel  406: 	    '<tr valign="top"><td>'.$grayFont.&mt('Option ID').'</span></td>'.
1.148     albertel  407: 	    $bottomrow.'</tr>'.'</table></blockquote>';
                    408:     } elsif ($response eq 'radiobutton') {
                    409: 	my %answer=&Apache::lonnet::str2hash($answer);
                    410: 	my ($toprow,$bottomrow);
1.434     albertel  411: 	my $correct = 
                    412: 	    &get_radiobutton_correct_foil($partid,$respid,$symb,$uname,$udom);
                    413: 	foreach my $foil (@$order) {
1.148     albertel  414: 	    if (exists($answer{$foil})) {
1.434     albertel  415: 		if ($foil eq $correct) {
1.466     albertel  416: 		    $toprow.='<td><b>'.&mt('true').'</b></td>';
1.148     albertel  417: 		} else {
1.466     albertel  418: 		    $toprow.='<td><i>'.&mt('true').'</i></td>';
1.148     albertel  419: 		}
                    420: 	    } else {
1.466     albertel  421: 		$toprow.='<td>'.&mt('false').'</td>';
1.148     albertel  422: 	    }
1.398     albertel  423: 	    $bottomrow.='<td>'.$grayFont.$foil.'</span>&nbsp;</td>';
1.148     albertel  424: 	}
                    425: 	return '<blockquote><table border="1">'.
1.466     albertel  426: 	    '<tr valign="top"><td>'.&mt('Answer').'</td>'.$toprow.'</tr>'.
                    427: 	    '<tr valign="top"><td>'.$grayFont.&mt('Option ID').'</span></td>'.
1.597   ! wenzelju  428: 	    $bottomrow.'</tr>'.'</table></blockquote>';
1.148     albertel  429:     } elsif ($response eq 'essay') {
1.257     albertel  430: 	if (! exists ($env{'form.'.$symb})) {
1.122     ng        431: 	    my (%keyhash) = &Apache::lonnet::dump('nohist_handgrade',
1.257     albertel  432: 						  $env{'course.'.$env{'request.course.id'}.'.domain'},
                    433: 						  $env{'course.'.$env{'request.course.id'}.'.num'});
1.122     ng        434: 
1.257     albertel  435: 	    my $loginuser = $env{'user.name'}.':'.$env{'user.domain'};
                    436: 	    $env{'form.keywords'} = $keyhash{$symb.'_keywords'} ne '' ? $keyhash{$symb.'_keywords'} : '';
                    437: 	    $env{'form.kwclr'}    = $keyhash{$loginuser.'_kwclr'} ne '' ? $keyhash{$loginuser.'_kwclr'} : 'red';
                    438: 	    $env{'form.kwsize'}   = $keyhash{$loginuser.'_kwsize'} ne '' ? $keyhash{$loginuser.'_kwsize'} : '0';
                    439: 	    $env{'form.kwstyle'}  = $keyhash{$loginuser.'_kwstyle'} ne '' ? $keyhash{$loginuser.'_kwstyle'} : '';
                    440: 	    $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        441: 	}
1.166     albertel  442: 	$answer =~ s-\n-<br />-g;
                    443: 	return '<br /><br /><blockquote><tt>'.&keywords_highlight($answer).'</tt></blockquote>';
1.268     albertel  444:     } elsif ( $response eq 'organic') {
                    445: 	my $result='Smile representation: "<tt>'.$answer.'</tt>"';
                    446: 	my $jme=$record->{$version."resource.$partid.$respid.molecule"};
                    447: 	$result.=&Apache::chemresponse::jme_img($jme,$answer,400);
                    448: 	return $result;
1.335     albertel  449:     } elsif ( $response eq 'Task') {
                    450: 	if ( $answer eq 'SUBMITTED') {
                    451: 	    my $files = $record->{$version."resource.$respid.$partid.bridgetask.portfiles"};
1.336     albertel  452: 	    my $result = &Apache::bridgetask::file_list($files,$uname,$udom);
1.335     albertel  453: 	    return $result;
                    454: 	} elsif ( grep(/^\Q$version\E.*?\.instance$/, keys(%{$record})) ) {
                    455: 	    my @matches = grep(/^\Q$version\E.*?\.instance$/,
                    456: 			       keys(%{$record}));
                    457: 	    return join('<br />',($version,@matches));
                    458: 			       
                    459: 			       
                    460: 	} else {
                    461: 	    my $result =
                    462: 		'<p>'
                    463: 		.&mt('Overall result: [_1]',
                    464: 		     $record->{$version."resource.$respid.$partid.status"})
                    465: 		.'</p>';
                    466: 	    
                    467: 	    $result .= '<ul>';
                    468: 	    my @grade = grep(/^\Q${version}resource.$respid.$partid.\E[^.]*[.]status$/,
                    469: 			     keys(%{$record}));
                    470: 	    foreach my $grade (sort(@grade)) {
                    471: 		my ($dim) = ($grade =~/[.]([^.]+)[.]status$/);
                    472: 		$result.= '<li>'.&mt("Dimension: [_1], status [_2] ",
                    473: 				     $dim, $record->{$grade}).
                    474: 			  '</li>';
                    475: 	    }
                    476: 	    $result.='</ul>';
                    477: 	    return $result;
                    478: 	}
1.440     albertel  479:     } elsif ( $response =~ m/(?:numerical|formula)/) {
                    480: 	$answer = 
                    481: 	    &Apache::loncommon::format_previous_attempt_value('submission',
                    482: 							      $answer);
1.122     ng        483:     }
1.118     ng        484:     return $answer;
                    485: }
                    486: 
                    487: #-- A couple of common js functions
                    488: sub commonJSfunctions {
                    489:     my $request = shift;
1.597   ! wenzelju  490:     $request->print(&Apache::lonhtmlcommon::scripttag(<<COMMONJSFUNCTIONS));
1.118     ng        491:     function radioSelection(radioButton) {
                    492: 	var selection=null;
                    493: 	if (radioButton.length > 1) {
                    494: 	    for (var i=0; i<radioButton.length; i++) {
                    495: 		if (radioButton[i].checked) {
                    496: 		    return radioButton[i].value;
                    497: 		}
                    498: 	    }
                    499: 	} else {
                    500: 	    if (radioButton.checked) return radioButton.value;
                    501: 	}
                    502: 	return selection;
                    503:     }
                    504: 
                    505:     function pullDownSelection(selectOne) {
                    506: 	var selection="";
                    507: 	if (selectOne.length > 1) {
                    508: 	    for (var i=0; i<selectOne.length; i++) {
                    509: 		if (selectOne[i].selected) {
                    510: 		    return selectOne[i].value;
                    511: 		}
                    512: 	    }
                    513: 	} else {
1.138     albertel  514:             // only one value it must be the selected one
                    515: 	    return selectOne.value;
1.118     ng        516: 	}
                    517:     }
                    518: COMMONJSFUNCTIONS
                    519: }
                    520: 
1.44      ng        521: #--- Dumps the class list with usernames,list of sections,
                    522: #--- section, ids and fullnames for each user.
                    523: sub getclasslist {
1.449     banghart  524:     my ($getsec,$filterlist,$getgroup) = @_;
1.291     albertel  525:     my @getsec;
1.450     banghart  526:     my @getgroup;
1.442     banghart  527:     my $stu_status = join(':',&Apache::loncommon::get_env_multiple('form.Status'));
1.291     albertel  528:     if (!ref($getsec)) {
                    529: 	if ($getsec ne '' && $getsec ne 'all') {
                    530: 	    @getsec=($getsec);
                    531: 	}
                    532:     } else {
                    533: 	@getsec=@{$getsec};
                    534:     }
                    535:     if (grep(/^all$/,@getsec)) { undef(@getsec); }
1.450     banghart  536:     if (!ref($getgroup)) {
                    537: 	if ($getgroup ne '' && $getgroup ne 'all') {
                    538: 	    @getgroup=($getgroup);
                    539: 	}
                    540:     } else {
                    541: 	@getgroup=@{$getgroup};
                    542:     }
                    543:     if (grep(/^all$/,@getgroup)) { undef(@getgroup); }
1.291     albertel  544: 
1.449     banghart  545:     my ($classlist,$keylist)=&Apache::loncoursedata::get_classlist();
1.49      albertel  546:     # Bail out if we were unable to get the classlist
1.56      matthew   547:     return if (! defined($classlist));
1.449     banghart  548:     &Apache::loncoursedata::get_group_memberships($classlist,$keylist);
1.56      matthew   549:     #
                    550:     my %sections;
                    551:     my %fullnames;
1.205     matthew   552:     foreach my $student (keys(%$classlist)) {
                    553:         my $end      = 
                    554:             $classlist->{$student}->[&Apache::loncoursedata::CL_END()];
                    555:         my $start    = 
                    556:             $classlist->{$student}->[&Apache::loncoursedata::CL_START()];
                    557:         my $id       = 
                    558:             $classlist->{$student}->[&Apache::loncoursedata::CL_ID()];
                    559:         my $section  = 
                    560:             $classlist->{$student}->[&Apache::loncoursedata::CL_SECTION()];
                    561:         my $fullname = 
                    562:             $classlist->{$student}->[&Apache::loncoursedata::CL_FULLNAME()];
                    563:         my $status   = 
                    564:             $classlist->{$student}->[&Apache::loncoursedata::CL_STATUS()];
1.449     banghart  565:         my $group   = 
                    566:             $classlist->{$student}->[&Apache::loncoursedata::CL_GROUP()];
1.76      ng        567: 	# filter students according to status selected
1.442     banghart  568: 	if ($filterlist && (!($stu_status =~ /Any/))) {
                    569: 	    if (!($stu_status =~ $status)) {
1.450     banghart  570: 		delete($classlist->{$student});
1.76      ng        571: 		next;
                    572: 	    }
                    573: 	}
1.450     banghart  574: 	# filter students according to groups selected
1.453     banghart  575: 	my @stu_groups = split(/,/,$group);
1.450     banghart  576: 	if (@getgroup) {
                    577: 	    my $exclude = 1;
1.454     banghart  578: 	    foreach my $grp (@getgroup) {
                    579: 	        foreach my $stu_group (@stu_groups) {
1.453     banghart  580: 	            if ($stu_group eq $grp) {
                    581: 	                $exclude = 0;
                    582:     	            } 
1.450     banghart  583: 	        }
1.453     banghart  584:     	        if (($grp eq 'none') && !$group) {
                    585:         	        $exclude = 0;
                    586:         	}
1.450     banghart  587: 	    }
                    588: 	    if ($exclude) {
                    589: 	        delete($classlist->{$student});
                    590: 	    }
                    591: 	}
1.205     matthew   592: 	$section = ($section ne '' ? $section : 'none');
1.106     albertel  593: 	if (&canview($section)) {
1.291     albertel  594: 	    if (!@getsec || grep(/^\Q$section\E$/,@getsec)) {
1.103     albertel  595: 		$sections{$section}++;
1.450     banghart  596: 		if ($classlist->{$student}) {
                    597: 		    $fullnames{$student}=$fullname;
                    598: 		}
1.103     albertel  599: 	    } else {
1.205     matthew   600: 		delete($classlist->{$student});
1.103     albertel  601: 	    }
                    602: 	} else {
1.205     matthew   603: 	    delete($classlist->{$student});
1.103     albertel  604: 	}
1.44      ng        605:     }
                    606:     my %seen = ();
1.56      matthew   607:     my @sections = sort(keys(%sections));
                    608:     return ($classlist,\@sections,\%fullnames);
1.44      ng        609: }
                    610: 
1.103     albertel  611: sub canmodify {
                    612:     my ($sec)=@_;
                    613:     if ($perm{'mgr'}) {
                    614: 	if (!defined($perm{'mgr_section'})) {
                    615: 	    # can modify whole class
                    616: 	    return 1;
                    617: 	} else {
                    618: 	    if ($sec eq $perm{'mgr_section'}) {
                    619: 		#can modify the requested section
                    620: 		return 1;
                    621: 	    } else {
                    622: 		# can't modify the request section
                    623: 		return 0;
                    624: 	    }
                    625: 	}
                    626:     }
                    627:     #can't modify
                    628:     return 0;
                    629: }
                    630: 
                    631: sub canview {
                    632:     my ($sec)=@_;
                    633:     if ($perm{'vgr'}) {
                    634: 	if (!defined($perm{'vgr_section'})) {
                    635: 	    # can modify whole class
                    636: 	    return 1;
                    637: 	} else {
                    638: 	    if ($sec eq $perm{'vgr_section'}) {
                    639: 		#can modify the requested section
                    640: 		return 1;
                    641: 	    } else {
                    642: 		# can't modify the request section
                    643: 		return 0;
                    644: 	    }
                    645: 	}
                    646:     }
                    647:     #can't modify
                    648:     return 0;
                    649: }
                    650: 
1.44      ng        651: #--- Retrieve the grade status of a student for all the parts
                    652: sub student_gradeStatus {
1.324     albertel  653:     my ($symb,$udom,$uname,$partlist) = @_;
1.257     albertel  654:     my %record     = &Apache::lonnet::restore($symb,$env{'request.course.id'},$udom,$uname);
1.44      ng        655:     my %partstatus = ();
                    656:     foreach (@$partlist) {
1.128     ng        657: 	my ($status,undef)   = split(/_/,$record{"resource.$_.solved"},2);
1.44      ng        658: 	$status              = 'nothing' if ($status eq '');
                    659: 	$partstatus{$_}      = $status;
                    660: 	my $subkey           = "resource.$_.submitted_by";
                    661: 	$partstatus{$subkey} = $record{$subkey} if ($record{$subkey} ne '');
                    662:     }
                    663:     return %partstatus;
                    664: }
                    665: 
1.45      ng        666: # hidden form and javascript that calls the form
                    667: # Use by verifyscript and viewgrades
                    668: # Shows a student's view of problem and submission
                    669: sub jscriptNform {
1.324     albertel  670:     my ($symb) = @_;
1.442     banghart  671:     my $stu_status = join(':',&Apache::loncommon::get_env_multiple('form.Status'));
1.597   ! wenzelju  672:     my $jscript= &Apache::lonhtmlcommon::scripttag(
1.45      ng        673: 	'    function viewOneStudent(user,domain) {'."\n".
                    674: 	'	document.onestudent.student.value = user;'."\n".
                    675: 	'	document.onestudent.userdom.value = domain;'."\n".
                    676: 	'	document.onestudent.submit();'."\n".
                    677: 	'    }'."\n".
1.597   ! wenzelju  678: 	"\n");
1.45      ng        679:     $jscript.= '<form action="/adm/grades" method="post" name="onestudent">'."\n".
1.418     albertel  680: 	'<input type="hidden" name="symb"    value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
1.257     albertel  681: 	'<input type="hidden" name="saveState" value="'.$env{'form.saveState'}.'" />'."\n".
                    682: 	'<input type="hidden" name="probTitle" value="'.$env{'form.probTitle'}.'" />'."\n".
1.442     banghart  683: 	'<input type="hidden" name="Status"  value="'.$stu_status.'" />'."\n".
1.45      ng        684: 	'<input type="hidden" name="command" value="submission" />'."\n".
                    685: 	'<input type="hidden" name="student" value="" />'."\n".
                    686: 	'<input type="hidden" name="userdom" value="" />'."\n".
                    687: 	'</form>'."\n";
                    688:     return $jscript;
                    689: }
1.39      ng        690: 
1.447     foxr      691: 
                    692: 
1.315     bowersj2  693: # Given the score (as a number [0-1] and the weight) what is the final
                    694: # point value? This function will round to the nearest tenth, third,
                    695: # or quarter if one of those is within the tolerance of .00001.
1.316     albertel  696: sub compute_points {
1.315     bowersj2  697:     my ($score, $weight) = @_;
                    698:     
                    699:     my $tolerance = .00001;
                    700:     my $points = $score * $weight;
                    701: 
                    702:     # Check for nearness to 1/x.
                    703:     my $check_for_nearness = sub {
                    704:         my ($factor) = @_;
                    705:         my $num = ($points * $factor) + $tolerance;
                    706:         my $floored_num = floor($num);
1.316     albertel  707:         if ($num - $floored_num < 2 * $tolerance * $factor) {
1.315     bowersj2  708:             return $floored_num / $factor;
                    709:         }
                    710:         return $points;
                    711:     };
                    712: 
                    713:     $points = $check_for_nearness->(10);
                    714:     $points = $check_for_nearness->(3);
                    715:     $points = $check_for_nearness->(4);
                    716:     
                    717:     return $points;
                    718: }
                    719: 
1.44      ng        720: #------------------ End of general use routines --------------------
1.87      www       721: 
                    722: #
                    723: # Find most similar essay
                    724: #
                    725: 
                    726: sub most_similar {
1.426     albertel  727:     my ($uname,$udom,$uessay,$old_essays)=@_;
1.87      www       728: 
                    729: # ignore spaces and punctuation
                    730: 
                    731:     $uessay=~s/\W+/ /gs;
                    732: 
1.282     www       733: # ignore empty submissions (occuring when only files are sent)
                    734: 
                    735:     unless ($uessay=~/\w+/) { return ''; }
                    736: 
1.87      www       737: # these will be returned. Do not care if not at least 50 percent similar
1.88      www       738:     my $limit=0.6;
1.87      www       739:     my $sname='';
                    740:     my $sdom='';
                    741:     my $scrsid='';
                    742:     my $sessay='';
                    743: # go through all essays ...
1.426     albertel  744:     foreach my $tkey (keys(%$old_essays)) {
                    745: 	my ($tname,$tdom,$tcrsid)=map {&unescape($_)} (split(/\./,$tkey));
1.87      www       746: # ... except the same student
1.426     albertel  747:         next if (($tname eq $uname) && ($tdom eq $udom));
                    748: 	my $tessay=$old_essays->{$tkey};
                    749: 	$tessay=~s/\W+/ /gs;
1.87      www       750: # String similarity gives up if not even limit
1.426     albertel  751: 	my $tsimilar=&String::Similarity::similarity($uessay,$tessay,$limit);
1.87      www       752: # Found one
1.426     albertel  753: 	if ($tsimilar>$limit) {
                    754: 	    $limit=$tsimilar;
                    755: 	    $sname=$tname;
                    756: 	    $sdom=$tdom;
                    757: 	    $scrsid=$tcrsid;
                    758: 	    $sessay=$old_essays->{$tkey};
                    759: 	}
1.87      www       760:     }
1.88      www       761:     if ($limit>0.6) {
1.87      www       762:        return ($sname,$sdom,$scrsid,$sessay,$limit);
                    763:     } else {
                    764:        return ('','','','',0);
                    765:     }
                    766: }
                    767: 
1.44      ng        768: #-------------------------------------------------------------------
                    769: 
                    770: #------------------------------------ Receipt Verification Routines
1.45      ng        771: #
1.44      ng        772: #--- Check whether a receipt number is valid.---
                    773: sub verifyreceipt {
                    774:     my $request  = shift;
                    775: 
1.257     albertel  776:     my $courseid = $env{'request.course.id'};
1.184     www       777:     my $receipt  = &Apache::lonnet::recprefix($courseid).'-'.
1.257     albertel  778: 	$env{'form.receipt'};
1.44      ng        779:     $receipt     =~ s/[^\-\d]//g;
1.378     albertel  780:     my ($symb)   = &get_symb($request);
1.44      ng        781: 
1.487     albertel  782:     my $title.=
                    783: 	'<h3><span class="LC_info">'.
1.584     bisitz    784: 	&mt('Verifying Receipt No. [_1]',$receipt).
1.487     albertel  785: 	'</span></h3>'."\n".
                    786: 	'<h4>'.&mt('<b>Resource: </b>[_1]',$env{'form.probTitle'}).
                    787: 	'</h4>'."\n";
1.44      ng        788: 
                    789:     my ($string,$contents,$matches) = ('','',0);
1.56      matthew   790:     my (undef,undef,$fullname) = &getclasslist('all','0');
1.177     albertel  791:     
                    792:     my $receiptparts=0;
1.390     albertel  793:     if ($env{"course.$courseid.receiptalg"} eq 'receipt2' ||
                    794: 	$env{"course.$courseid.receiptalg"} eq 'receipt3') { $receiptparts=1; }
1.177     albertel  795:     my $parts=['0'];
1.582     raeburn   796:     if ($receiptparts) {
                    797:         my $res_error; 
                    798:         ($parts)=&response_type($symb,\$res_error);
                    799:         if ($res_error) {
                    800:             return &navmap_errormsg();
                    801:         } 
                    802:     }
1.486     albertel  803:     
                    804:     my $header = 
                    805: 	&Apache::loncommon::start_data_table().
                    806: 	&Apache::loncommon::start_data_table_header_row().
1.487     albertel  807: 	'<th>&nbsp;'.&mt('Fullname').'&nbsp;</th>'."\n".
                    808: 	'<th>&nbsp;'.&mt('Username').'&nbsp;</th>'."\n".
                    809: 	'<th>&nbsp;'.&mt('Domain').'&nbsp;</th>';
1.486     albertel  810:     if ($receiptparts) {
1.487     albertel  811: 	$header.='<th>&nbsp;'.&mt('Problem Part').'&nbsp;</th>';
1.486     albertel  812:     }
                    813:     $header.=
                    814: 	&Apache::loncommon::end_data_table_header_row();
                    815: 
1.294     albertel  816:     foreach (sort 
                    817: 	     {
                    818: 		 if (lc($$fullname{$a}) ne lc($$fullname{$b})) {
                    819: 		     return (lc($$fullname{$a}) cmp lc($$fullname{$b}));
                    820: 		 }
                    821: 		 return $a cmp $b;
                    822: 	     } (keys(%$fullname))) {
1.44      ng        823: 	my ($uname,$udom)=split(/\:/);
1.177     albertel  824: 	foreach my $part (@$parts) {
                    825: 	    if ($receipt eq &Apache::lonnet::ireceipt($uname,$udom,$courseid,$symb,$part)) {
1.486     albertel  826: 		$contents.=
                    827: 		    &Apache::loncommon::start_data_table_row().
                    828: 		    '<td>&nbsp;'."\n".
1.177     albertel  829: 		    '<a href="javascript:viewOneStudent(\''.$uname.'\',\''.$udom.
1.417     albertel  830: 		    '\');" target="_self">'.$$fullname{$_}.'</a>&nbsp;</td>'."\n".
1.177     albertel  831: 		    '<td>&nbsp;'.$uname.'&nbsp;</td>'.
                    832: 		    '<td>&nbsp;'.$udom.'&nbsp;</td>';
                    833: 		if ($receiptparts) {
                    834: 		    $contents.='<td>&nbsp;'.$part.'&nbsp;</td>';
                    835: 		}
1.486     albertel  836: 		$contents.= 
                    837: 		    &Apache::loncommon::end_data_table_row()."\n";
1.177     albertel  838: 		
                    839: 		$matches++;
                    840: 	    }
1.44      ng        841: 	}
                    842:     }
                    843:     if ($matches == 0) {
1.584     bisitz    844:         $string = $title
                    845:                  .'<p class="LC_warning">'
                    846:                  .&mt('No match found for the above receipt number.')
                    847:                  .'</p>';
1.44      ng        848:     } else {
1.324     albertel  849: 	$string = &jscriptNform($symb).$title.
1.487     albertel  850: 	    '<p>'.
1.584     bisitz    851: 	    &mt('The above receipt number matches the following [quant,_1,student].',$matches).
1.487     albertel  852: 	    '</p>'.
1.486     albertel  853: 	    $header.
                    854: 	    $contents.
                    855: 	    &Apache::loncommon::end_data_table()."\n";
1.44      ng        856:     }
1.324     albertel  857:     return $string.&show_grading_menu_form($symb);
1.44      ng        858: }
                    859: 
                    860: #--- This is called by a number of programs.
                    861: #--- Called from the Grading Menu - View/Grade an individual student
                    862: #--- Also called directly when one clicks on the subm button 
                    863: #    on the problem page.
1.30      ng        864: sub listStudents {
1.41      ng        865:     my ($request) = shift;
1.49      albertel  866: 
1.324     albertel  867:     my ($symb) = &get_symb($request);
1.257     albertel  868:     my $cdom      = $env{"course.$env{'request.course.id'}.domain"};
                    869:     my $cnum      = $env{"course.$env{'request.course.id'}.num"};
                    870:     my $getsec    = $env{'form.section'} eq '' ? 'all' : $env{'form.section'};
1.449     banghart  871:     my $getgroup  = $env{'form.group'} eq '' ? 'all' : $env{'form.group'};
1.257     albertel  872:     my $submitonly= $env{'form.submitonly'} eq '' ? 'all' : $env{'form.submitonly'};
1.548     bisitz    873:     my $viewgrade = $env{'form.showgrading'} eq 'yes' ? 'View/Grade/Regrade' : 'View';
1.257     albertel  874:     $env{'form.probTitle'} = $env{'form.probTitle'} eq '' ? 
                    875: 	&Apache::lonnet::gettitle($symb) : $env{'form.probTitle'};
1.49      albertel  876: 
1.548     bisitz    877:     my $result='<h3><span class="LC_info">&nbsp;'
                    878: 	.&mt("$viewgrade Submissions for a Student or a Group of Students")
1.485     albertel  879: 	.'</span></h3>';
1.118     ng        880: 
1.324     albertel  881:     my ($table,undef,$hdgrade,$partlist,$handgrade) = &showResourceInfo($symb,$env{'form.probTitle'},($env{'form.showgrading'} eq 'yes'));
1.49      albertel  882: 
1.559     raeburn   883:     my %lt = &Apache::lonlocal::texthash (
                    884: 		'multiple' => 'Please select a student or group of students before clicking on the Next button.',
                    885: 		'single'   => 'Please select the student before clicking on the Next button.',
                    886: 	     );
1.597   ! wenzelju  887:     $request->print(&Apache::lonhtmlcommon::scripttag(<<LISTJAVASCRIPT));
1.110     ng        888:     function checkSelect(checkBox) {
                    889: 	var ctr=0;
                    890: 	var sense="";
                    891: 	if (checkBox.length > 1) {
                    892: 	    for (var i=0; i<checkBox.length; i++) {
                    893: 		if (checkBox[i].checked) {
                    894: 		    ctr++;
                    895: 		}
                    896: 	    }
1.485     albertel  897: 	    sense = '$lt{'multiple'}';
1.110     ng        898: 	} else {
                    899: 	    if (checkBox.checked) {
                    900: 		ctr = 1;
                    901: 	    }
1.485     albertel  902: 	    sense = '$lt{'single'}';
1.110     ng        903: 	}
                    904: 	if (ctr == 0) {
1.485     albertel  905: 	    alert(sense);
1.110     ng        906: 	    return false;
                    907: 	}
                    908: 	document.gradesub.submit();
                    909:     }
                    910: 
                    911:     function reLoadList(formname) {
1.112     ng        912: 	if (formname.saveStatusOld.value == pullDownSelection(formname.Status)) {return;}
1.110     ng        913: 	formname.command.value = 'submission';
                    914: 	formname.submit();
                    915:     }
1.45      ng        916: LISTJAVASCRIPT
                    917: 
1.118     ng        918:     &commonJSfunctions($request);
1.41      ng        919:     $request->print($result);
1.39      ng        920: 
1.401     albertel  921:     my $checkhdgrade = ($env{'form.handgrade'} eq 'yes' && scalar(@$partlist) > 1 ) ? 'checked="checked"' : '';
                    922:     my $checklastsub = $checkhdgrade eq '' ? 'checked="checked"' : '';
1.154     albertel  923:     my $gradeTable='<form action="/adm/grades" method="post" name="gradesub">'.
1.485     albertel  924: 	"\n".$table;
                    925: 	
1.561     bisitz    926:     $gradeTable .= &Apache::lonhtmlcommon::start_pick_box();
                    927:     $gradeTable .= &Apache::lonhtmlcommon::row_title(&mt('View Problem Text'))
                    928:                   .'<label><input type="radio" name="vProb" value="no" checked="checked" /> '.&mt('no').' </label>'."\n"
                    929:                   .'<label><input type="radio" name="vProb" value="yes" /> '.&mt('one student').' </label>'."\n"
                    930:                   .'<label><input type="radio" name="vProb" value="all" /> '.&mt('all students').' </label><br />'."\n"
                    931:                   .&Apache::lonhtmlcommon::row_closure();
                    932:     $gradeTable .= &Apache::lonhtmlcommon::row_title(&mt('View Answer'))
                    933:                   .'<label><input type="radio" name="vAns" value="no"  /> '.&mt('no').' </label>'."\n"
                    934:                   .'<label><input type="radio" name="vAns" value="yes" /> '.&mt('one student').' </label>'."\n"
                    935:                   .'<label><input type="radio" name="vAns" value="all" checked="checked" /> '.&mt('all students').' </label><br />'."\n"
                    936:                   .&Apache::lonhtmlcommon::row_closure();
1.485     albertel  937: 
                    938:     my $submission_options;
1.257     albertel  939:     if ($env{'form.handgrade'} eq 'yes' && scalar(@$partlist) > 1) {
1.485     albertel  940: 	$submission_options.=
                    941: 	    '<label><input type="radio" name="lastSub" value="hdgrade" '.$checkhdgrade.' /> '.&mt('essay part only').' </label>'."\n";
1.49      albertel  942:     }
1.442     banghart  943:     my $stu_status = join(':',&Apache::loncommon::get_env_multiple('form.Status'));
                    944:     my $saveStatus = $stu_status eq '' ? 'Active' : $stu_status;
1.257     albertel  945:     $env{'form.Status'} = $saveStatus;
1.485     albertel  946:     $submission_options.=
1.592     bisitz    947:         '<span class="LC_nobreak">'.
                    948:         '<label><input type="radio" name="lastSub" value="lastonly" '.$checklastsub.' /> '.
                    949:         &mt('last submission only').' </label></span>'."\n".
                    950:         '<span class="LC_nobreak">'.
                    951:         '<label><input type="radio" name="lastSub" value="last" /> '.
                    952:         &mt('last submission &amp; parts info').' </label></span>'."\n".
                    953:         '<span class="LC_nobreak">'.
                    954:         '<label><input type="radio" name="lastSub" value="datesub" /> '.
                    955:         &mt('by dates and submissions').'</label></span>'."\n".
                    956:         '<span class="LC_nobreak">'.
                    957:         '<label><input type="radio" name="lastSub" value="all" /> '.
                    958:         &mt('all details').'</label></span>';
1.561     bisitz    959:     $gradeTable .= &Apache::lonhtmlcommon::row_title(&mt('Submissions'))
                    960:                   .$submission_options
                    961:                   .&Apache::lonhtmlcommon::row_closure();
                    962: 
                    963:     $gradeTable .= &Apache::lonhtmlcommon::row_title(&mt('Grading Increments'))
                    964:                   .'<select name="increment">'
                    965:                   .'<option value="1">'.&mt('Whole Points').'</option>'
                    966:                   .'<option value=".5">'.&mt('Half Points').'</option>'
                    967:                   .'<option value=".25">'.&mt('Quarter Points').'</option>'
                    968:                   .'<option value=".1">'.&mt('Tenths of a Point').'</option>'
                    969:                   .'</select>'
                    970:                   .&Apache::lonhtmlcommon::row_closure();
1.485     albertel  971: 
                    972:     $gradeTable .= 
1.432     banghart  973:         &build_section_inputs().
1.45      ng        974: 	'<input type="hidden" name="submitonly"  value="'.$submitonly.'" />'."\n".
1.257     albertel  975: 	'<input type="hidden" name="handgrade"   value="'.$env{'form.handgrade'}.'" /><br />'."\n".
                    976: 	'<input type="hidden" name="showgrading" value="'.$env{'form.showgrading'}.'" /><br />'."\n".
                    977: 	'<input type="hidden" name="saveState"   value="'.$env{'form.saveState'}.'" />'."\n".
                    978: 	'<input type="hidden" name="probTitle"   value="'.$env{'form.probTitle'}.'" />'."\n".
1.418     albertel  979: 	'<input type="hidden" name="symb" value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
1.110     ng        980: 	'<input type="hidden" name="saveStatusOld" value="'.$saveStatus.'" />'."\n";
                    981: 
1.257     albertel  982:     if (exists($env{'form.gradingMenu'}) && exists($env{'form.Status'})) {
1.561     bisitz    983: 	$gradeTable .= '<input type="hidden" name="Status" value="'.$stu_status.'" />'."\n";
1.124     ng        984:     } else {
1.561     bisitz    985:         $gradeTable .= &Apache::lonhtmlcommon::row_title(&mt('Student Status'))
                    986:                       .&Apache::lonhtmlcommon::StatusOptions(
                    987:                            $saveStatus,undef,1,'javascript:reLoadList(this.form);')
                    988:                       .&Apache::lonhtmlcommon::row_closure();
1.124     ng        989:     }
1.112     ng        990: 
1.561     bisitz    991:     $gradeTable .= &Apache::lonhtmlcommon::row_title(&mt('Check For Plagiarism'))
                    992:                   .'<input type="checkbox" name="checkPlag" checked="checked" />'
                    993:                   .&Apache::lonhtmlcommon::row_closure(1)
                    994:                   .&Apache::lonhtmlcommon::end_pick_box();
                    995: 
                    996:     $gradeTable .= '<p>'
                    997:                   .&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"
                    998:                   .'<input type="hidden" name="command" value="processGroup" />'
                    999:                   .'</p>';
1.249     albertel 1000: 
                   1001: # checkall buttons
                   1002:     $gradeTable.=&check_script('gradesub', 'stuinfo');
1.110     ng       1003:     $gradeTable.='<input type="button" '."\n".
1.589     bisitz   1004:         'onclick="javascript:checkSelect(this.form.stuinfo);" '."\n".
                   1005:         'value="'.&mt('Next').' &rarr;" /> <br />'."\n";
1.249     albertel 1006:     $gradeTable.=&check_buttons();
1.450     banghart 1007:     my ($classlist, undef, $fullname) = &getclasslist($getsec,'1',$getgroup);
1.474     albertel 1008:     $gradeTable.= &Apache::loncommon::start_data_table().
                   1009: 	&Apache::loncommon::start_data_table_header_row();
1.110     ng       1010:     my $loop = 0;
                   1011:     while ($loop < 2) {
1.485     albertel 1012: 	$gradeTable.='<th>'.&mt('No.').'</th><th>'.&mt('Select').'</th>'.
                   1013: 	    '<th>'.&nameUserString('header').'&nbsp;'.&mt('Section/Group').'</th>';
1.301     albertel 1014: 	if ($env{'form.showgrading'} eq 'yes' 
                   1015: 	    && $submitonly ne 'queued'
                   1016: 	    && $submitonly ne 'all') {
1.485     albertel 1017: 	    foreach my $part (sort(@$partlist)) {
                   1018: 		my $display_part=
                   1019: 		    &get_display_part((split(/_/,$part))[0],$symb);
                   1020: 		$gradeTable.=
                   1021: 		    '<th>'.&mt('Part: [_1] Status',$display_part).'</th>';
1.110     ng       1022: 	    }
1.301     albertel 1023: 	} elsif ($submitonly eq 'queued') {
1.474     albertel 1024: 	    $gradeTable.='<th>'.&mt('Queue Status').'&nbsp;</th>';
1.110     ng       1025: 	}
                   1026: 	$loop++;
1.126     ng       1027: #	$gradeTable.='<td></td>' if ($loop%2 ==1);
1.41      ng       1028:     }
1.474     albertel 1029:     $gradeTable.=&Apache::loncommon::end_data_table_header_row()."\n";
1.41      ng       1030: 
1.45      ng       1031:     my $ctr = 0;
1.294     albertel 1032:     foreach my $student (sort 
                   1033: 			 {
                   1034: 			     if (lc($$fullname{$a}) ne lc($$fullname{$b})) {
                   1035: 				 return (lc($$fullname{$a}) cmp lc($$fullname{$b}));
                   1036: 			     }
                   1037: 			     return $a cmp $b;
                   1038: 			 }
                   1039: 			 (keys(%$fullname))) {
1.41      ng       1040: 	my ($uname,$udom) = split(/:/,$student);
1.301     albertel 1041: 
1.110     ng       1042: 	my %status = ();
1.301     albertel 1043: 
                   1044: 	if ($submitonly eq 'queued') {
                   1045: 	    my %queue_status = 
                   1046: 		&Apache::bridgetask::get_student_status($symb,$cdom,$cnum,
                   1047: 							$udom,$uname);
                   1048: 	    next if (!defined($queue_status{'gradingqueue'}));
                   1049: 	    $status{'gradingqueue'} = $queue_status{'gradingqueue'};
                   1050: 	}
                   1051: 
                   1052: 	if ($env{'form.showgrading'} eq 'yes' 
                   1053: 	    && $submitonly ne 'queued'
                   1054: 	    && $submitonly ne 'all') {
1.324     albertel 1055: 	    (%status) =&student_gradeStatus($symb,$udom,$uname,$partlist);
1.145     albertel 1056: 	    my $submitted = 0;
1.164     albertel 1057: 	    my $graded = 0;
1.248     albertel 1058: 	    my $incorrect = 0;
1.110     ng       1059: 	    foreach (keys(%status)) {
1.145     albertel 1060: 		$submitted = 1 if ($status{$_} ne 'nothing');
1.248     albertel 1061: 		$graded = 1 if ($status{$_} =~ /^ungraded/);
                   1062: 		$incorrect = 1 if ($status{$_} =~ /^incorrect/);
                   1063: 		
1.110     ng       1064: 		my ($foo,$partid,$foo1) = split(/\./,$_);
                   1065: 		if ($status{'resource.'.$partid.'.submitted_by'} ne '') {
1.145     albertel 1066: 		    $submitted = 0;
1.150     albertel 1067: 		    my ($part)=split(/\./,$partid);
1.110     ng       1068: 		    $gradeTable.='<input type="hidden" name="'.
1.150     albertel 1069: 			$student.':'.$part.':submitted_by" value="'.
1.110     ng       1070: 			$status{'resource.'.$partid.'.submitted_by'}.'" />';
                   1071: 		}
1.41      ng       1072: 	    }
1.248     albertel 1073: 	    
1.156     albertel 1074: 	    next if (!$submitted && ($submitonly eq 'yes' ||
                   1075: 				     $submitonly eq 'incorrect' ||
                   1076: 				     $submitonly eq 'graded'));
1.248     albertel 1077: 	    next if (!$graded && ($submitonly eq 'graded'));
                   1078: 	    next if (!$incorrect && $submitonly eq 'incorrect');
1.41      ng       1079: 	}
1.34      ng       1080: 
1.45      ng       1081: 	$ctr++;
1.249     albertel 1082: 	my $section = $classlist->{$student}->[&Apache::loncoursedata::CL_SECTION()];
1.452     banghart 1083:         my $group = $classlist->{$student}->[&Apache::loncoursedata::CL_GROUP()];
1.104     albertel 1084: 	if ( $perm{'vgr'} eq 'F' ) {
1.474     albertel 1085: 	    if ($ctr%2 ==1) {
                   1086: 		$gradeTable.= &Apache::loncommon::start_data_table_row();
                   1087: 	    }
1.126     ng       1088: 	    $gradeTable.='<td align="right">'.$ctr.'&nbsp;</td>'.
1.563     bisitz   1089:                '<td align="center"><label><input type="checkbox" name="stuinfo" value="'.
1.249     albertel 1090:                $student.':'.$$fullname{$student}.':::SECTION'.$section.
                   1091: 	       ')&nbsp;" />&nbsp;&nbsp;</label></td>'."\n".'<td>'.
                   1092: 	       &nameUserString(undef,$$fullname{$student},$uname,$udom).
1.474     albertel 1093: 	       '&nbsp;'.$section.($group ne '' ?'/'.$group:'').'</td>'."\n";
1.110     ng       1094: 
1.257     albertel 1095: 	    if ($env{'form.showgrading'} eq 'yes' && $submitonly ne 'all') {
1.524     raeburn  1096: 		foreach (sort(keys(%status))) {
1.485     albertel 1097: 		    next if ($_ =~ /^resource.*?submitted_by$/);
                   1098: 		    $gradeTable.='<td align="center">&nbsp;'.&mt($status{$_}).'&nbsp;</td>'."\n";
1.110     ng       1099: 		}
1.41      ng       1100: 	    }
1.126     ng       1101: #	    $gradeTable.='<td></td>' if ($ctr%2 ==1);
1.474     albertel 1102: 	    if ($ctr%2 ==0) {
                   1103: 		$gradeTable.=&Apache::loncommon::end_data_table_row()."\n";
                   1104: 	    }
1.41      ng       1105: 	}
                   1106:     }
1.110     ng       1107:     if ($ctr%2 ==1) {
1.126     ng       1108: 	$gradeTable.='<td>&nbsp;</td><td>&nbsp;</td><td>&nbsp;</td>';
1.301     albertel 1109: 	    if ($env{'form.showgrading'} eq 'yes' 
                   1110: 		&& $submitonly ne 'queued'
                   1111: 		&& $submitonly ne 'all') {
1.110     ng       1112: 		foreach (@$partlist) {
                   1113: 		    $gradeTable.='<td>&nbsp;</td>';
                   1114: 		}
1.301     albertel 1115: 	    } elsif ($submitonly eq 'queued') {
                   1116: 		$gradeTable.='<td>&nbsp;</td>';
1.110     ng       1117: 	    }
1.474     albertel 1118: 	$gradeTable.=&Apache::loncommon::end_data_table_row();
1.110     ng       1119:     }
                   1120: 
1.474     albertel 1121:     $gradeTable.=&Apache::loncommon::end_data_table()."\n".
1.589     bisitz   1122:         '<input type="button" '.
                   1123:         'onclick="javascript:checkSelect(this.form.stuinfo);" '.
                   1124:         'value="'.&mt('Next').' &rarr;" /></form>'."\n";
1.45      ng       1125:     if ($ctr == 0) {
1.96      albertel 1126: 	my $num_students=(scalar(keys(%$fullname)));
                   1127: 	if ($num_students eq 0) {
1.485     albertel 1128: 	    $gradeTable='<br />&nbsp;<span class="LC_warning">'.&mt('There are no students currently enrolled.').'</span>';
1.96      albertel 1129: 	} else {
1.171     albertel 1130: 	    my $submissions='submissions';
                   1131: 	    if ($submitonly eq 'incorrect') { $submissions = 'incorrect submissions'; }
                   1132: 	    if ($submitonly eq 'graded'   ) { $submissions = 'ungraded submissions'; }
1.301     albertel 1133: 	    if ($submitonly eq 'queued'   ) { $submissions = 'queued submissions'; }
1.398     albertel 1134: 	    $gradeTable='<br />&nbsp;<span class="LC_warning">'.
1.485     albertel 1135: 		&mt('No '.$submissions.' found for this resource for any students. ([_1] students checked for '.$submissions.')',
                   1136: 		    $num_students).
                   1137: 		'</span><br />';
1.96      albertel 1138: 	}
1.46      ng       1139:     } elsif ($ctr == 1) {
1.474     albertel 1140: 	$gradeTable =~ s/type="checkbox"/type="checkbox" checked="checked"/;
1.45      ng       1141:     }
1.324     albertel 1142:     $gradeTable.=&show_grading_menu_form($symb);
1.45      ng       1143:     $request->print($gradeTable);
1.44      ng       1144:     return '';
1.10      ng       1145: }
                   1146: 
1.44      ng       1147: #---- Called from the listStudents routine
1.249     albertel 1148: 
                   1149: sub check_script {
                   1150:     my ($form, $type)=@_;
1.597   ! wenzelju 1151:     my $chkallscript= &Apache::lonhtmlcommon::scripttag('
1.249     albertel 1152:     function checkall() {
                   1153:         for (i=0; i<document.forms.'.$form.'.elements.length; i++) {
                   1154:             ele = document.forms.'.$form.'.elements[i];
                   1155:             if (ele.name == "'.$type.'") {
                   1156:             document.forms.'.$form.'.elements[i].checked=true;
                   1157:                                        }
                   1158:         }
                   1159:     }
                   1160: 
                   1161:     function checksec() {
                   1162:         for (i=0; i<document.forms.'.$form.'.elements.length; i++) {
                   1163:             ele = document.forms.'.$form.'.elements[i];
                   1164:            string = document.forms.'.$form.'.chksec.value;
                   1165:            if
                   1166:           (ele.value.indexOf(":::SECTION"+string)>0) {
                   1167:               document.forms.'.$form.'.elements[i].checked=true;
                   1168:             }
                   1169:         }
                   1170:     }
                   1171: 
                   1172: 
                   1173:     function uncheckall() {
                   1174:         for (i=0; i<document.forms.'.$form.'.elements.length; i++) {
                   1175:             ele = document.forms.'.$form.'.elements[i];
                   1176:             if (ele.name == "'.$type.'") {
                   1177:             document.forms.'.$form.'.elements[i].checked=false;
                   1178:                                        }
                   1179:         }
                   1180:     }
                   1181: 
1.597   ! wenzelju 1182: '."\n");
1.249     albertel 1183:     return $chkallscript;
                   1184: }
                   1185: 
                   1186: sub check_buttons {
1.485     albertel 1187:     my $buttons.='<input type="button" onclick="checkall()" value="'.&mt('Check All').'" />';
                   1188:     $buttons.='<input type="button" onclick="uncheckall()" value="'.&mt('Uncheck All').'" />&nbsp;';
                   1189:     $buttons.='<input type="button" onclick="checksec()" value="'.&mt('Check Section/Group').'" />';
1.249     albertel 1190:     $buttons.='<input type="text" size="5" name="chksec" />&nbsp;';
                   1191:     return $buttons;
                   1192: }
                   1193: 
1.44      ng       1194: #     Displays the submissions for one student or a group of students
1.34      ng       1195: sub processGroup {
1.41      ng       1196:     my ($request)  = shift;
                   1197:     my $ctr        = 0;
1.155     albertel 1198:     my @stuchecked = &Apache::loncommon::get_env_multiple('form.stuinfo');
1.41      ng       1199:     my $total      = scalar(@stuchecked)-1;
1.45      ng       1200: 
1.396     banghart 1201:     foreach my $student (@stuchecked) {
                   1202: 	my ($uname,$udom,$fullname) = split(/:/,$student);
1.257     albertel 1203: 	$env{'form.student'}        = $uname;
                   1204: 	$env{'form.userdom'}        = $udom;
                   1205: 	$env{'form.fullname'}       = $fullname;
1.41      ng       1206: 	&submission($request,$ctr,$total);
                   1207: 	$ctr++;
                   1208:     }
                   1209:     return '';
1.35      ng       1210: }
1.34      ng       1211: 
1.44      ng       1212: #------------------------------------------------------------------------------------
                   1213: #
                   1214: #-------------------------- Next few routines handles grading by student, essentially
                   1215: #                           handles essay response type problem/part
                   1216: #
                   1217: #--- Javascript to handle the submission page functionality ---
                   1218: sub sub_page_js {
                   1219:     my $request = shift;
1.539     riegler  1220: 	    my $alertmsg = &mt('A number equal or greater than 0 is expected. Entered value = ');
1.597   ! wenzelju 1221:     $request->print(&Apache::lonhtmlcommon::scripttag(<<SUBJAVASCRIPT));
1.71      ng       1222:     function updateRadio(formname,id,weight) {
1.125     ng       1223: 	var gradeBox = formname["GD_BOX"+id];
                   1224: 	var radioButton = formname["RADVAL"+id];
                   1225: 	var oldpts = formname["oldpts"+id].value;
1.72      ng       1226: 	var pts = checkSolved(formname,id) == 'update' ? gradeBox.value : oldpts;
1.71      ng       1227: 	gradeBox.value = pts;
                   1228: 	var resetbox = false;
                   1229: 	if (isNaN(pts) || pts < 0) {
1.539     riegler  1230: 	    alert("$alertmsg"+pts);
1.71      ng       1231: 	    for (var i=0; i<radioButton.length; i++) {
                   1232: 		if (radioButton[i].checked) {
                   1233: 		    gradeBox.value = i;
                   1234: 		    resetbox = true;
                   1235: 		}
                   1236: 	    }
                   1237: 	    if (!resetbox) {
                   1238: 		formtextbox.value = "";
                   1239: 	    }
                   1240: 	    return;
1.44      ng       1241: 	}
1.71      ng       1242: 
                   1243: 	if (pts > weight) {
                   1244: 	    var resp = confirm("You entered a value ("+pts+
                   1245: 			       ") greater than the weight for the part. Accept?");
                   1246: 	    if (resp == false) {
1.125     ng       1247: 		gradeBox.value = oldpts;
1.71      ng       1248: 		return;
                   1249: 	    }
1.44      ng       1250: 	}
1.13      albertel 1251: 
1.71      ng       1252: 	for (var i=0; i<radioButton.length; i++) {
                   1253: 	    radioButton[i].checked=false;
                   1254: 	    if (pts == i && pts != "") {
                   1255: 		radioButton[i].checked=true;
                   1256: 	    }
                   1257: 	}
                   1258: 	updateSelect(formname,id);
1.125     ng       1259: 	formname["stores"+id].value = "0";
1.41      ng       1260:     }
1.5       albertel 1261: 
1.72      ng       1262:     function writeBox(formname,id,pts) {
1.125     ng       1263: 	var gradeBox = formname["GD_BOX"+id];
1.71      ng       1264: 	if (checkSolved(formname,id) == 'update') {
                   1265: 	    gradeBox.value = pts;
                   1266: 	} else {
1.125     ng       1267: 	    var oldpts = formname["oldpts"+id].value;
1.72      ng       1268: 	    gradeBox.value = oldpts;
1.125     ng       1269: 	    var radioButton = formname["RADVAL"+id];
1.71      ng       1270: 	    for (var i=0; i<radioButton.length; i++) {
                   1271: 		radioButton[i].checked=false;
1.72      ng       1272: 		if (i == oldpts) {
1.71      ng       1273: 		    radioButton[i].checked=true;
                   1274: 		}
                   1275: 	    }
1.41      ng       1276: 	}
1.125     ng       1277: 	formname["stores"+id].value = "0";
1.71      ng       1278: 	updateSelect(formname,id);
                   1279: 	return;
1.41      ng       1280:     }
1.44      ng       1281: 
1.71      ng       1282:     function clearRadBox(formname,id) {
                   1283: 	if (checkSolved(formname,id) == 'noupdate') {
                   1284: 	    updateSelect(formname,id);
                   1285: 	    return;
                   1286: 	}
1.125     ng       1287: 	gradeSelect = formname["GD_SEL"+id];
1.71      ng       1288: 	for (var i=0; i<gradeSelect.length; i++) {
                   1289: 	    if (gradeSelect[i].selected) {
                   1290: 		var selectx=i;
                   1291: 	    }
                   1292: 	}
1.125     ng       1293: 	var stores = formname["stores"+id];
1.71      ng       1294: 	if (selectx == stores.value) { return };
1.125     ng       1295: 	var gradeBox = formname["GD_BOX"+id];
1.71      ng       1296: 	gradeBox.value = "";
1.125     ng       1297: 	var radioButton = formname["RADVAL"+id];
1.71      ng       1298: 	for (var i=0; i<radioButton.length; i++) {
                   1299: 	    radioButton[i].checked=false;
                   1300: 	}
                   1301: 	stores.value = selectx;
                   1302:     }
1.5       albertel 1303: 
1.71      ng       1304:     function checkSolved(formname,id) {
1.125     ng       1305: 	if (formname["solved"+id].value == "correct_by_student" && formname.overRideScore.value == 'no') {
1.118     ng       1306: 	    var reply = confirm("This problem has been graded correct by the computer. Do you want to change the score?");
                   1307: 	    if (!reply) {return "noupdate";}
1.120     ng       1308: 	    formname.overRideScore.value = 'yes';
1.41      ng       1309: 	}
1.71      ng       1310: 	return "update";
1.13      albertel 1311:     }
1.71      ng       1312: 
                   1313:     function updateSelect(formname,id) {
1.125     ng       1314: 	formname["GD_SEL"+id][0].selected = true;
1.71      ng       1315: 	return;
1.41      ng       1316:     }
1.33      ng       1317: 
1.121     ng       1318: //=========== Check that a point is assigned for all the parts  ============
1.71      ng       1319:     function checksubmit(formname,val,total,parttot) {
1.121     ng       1320: 	formname.gradeOpt.value = val;
1.71      ng       1321: 	if (val == "Save & Next") {
                   1322: 	    for (i=0;i<=total;i++) {
                   1323: 		for (j=0;j<parttot;j++) {
1.125     ng       1324: 		    var partid = formname["partid"+i+"_"+j].value;
1.127     ng       1325: 		    if (formname["GD_SEL"+i+"_"+partid][0].selected) {
1.125     ng       1326: 			var points = formname["GD_BOX"+i+"_"+partid].value;
1.71      ng       1327: 			if (points == "") {
1.125     ng       1328: 			    var name = formname["name"+i].value;
1.129     ng       1329: 			    var studentID = (name != '' ? name : formname["unamedom"+i].value);
                   1330: 			    var resp = confirm("You did not assign a score for "+studentID+
                   1331: 					       ", part "+partid+". Continue?");
1.71      ng       1332: 			    if (resp == false) {
1.125     ng       1333: 				formname["GD_BOX"+i+"_"+partid].focus();
1.71      ng       1334: 				return false;
                   1335: 			    }
                   1336: 			}
                   1337: 		    }
                   1338: 		    
                   1339: 		}
                   1340: 	    }
                   1341: 	    
                   1342: 	}
1.121     ng       1343: 	if (val == "Grade Student") {
                   1344: 	    formname.showgrading.value = "yes";
                   1345: 	    if (formname.Status.value == "") {
                   1346: 		formname.Status.value = "Active";
                   1347: 	    }
                   1348: 	    formname.studentNo.value = total;
                   1349: 	}
1.120     ng       1350: 	formname.submit();
                   1351:     }
                   1352: 
1.71      ng       1353: //======= Check that a score is assigned for all the problems (page/sequence grading only) =========
                   1354:     function checkSubmitPage(formname,total) {
                   1355: 	noscore = new Array(100);
                   1356: 	var ptr = 0;
                   1357: 	for (i=1;i<total;i++) {
1.125     ng       1358: 	    var partid = formname["q_"+i].value;
1.127     ng       1359: 	    if (formname["GD_SEL"+i+"_"+partid][0].selected) {
1.125     ng       1360: 		var points = formname["GD_BOX"+i+"_"+partid].value;
                   1361: 		var status = formname["solved"+i+"_"+partid].value;
1.71      ng       1362: 		if (points == "" && status != "correct_by_student") {
                   1363: 		    noscore[ptr] = i;
                   1364: 		    ptr++;
                   1365: 		}
                   1366: 	    }
                   1367: 	}
                   1368: 	if (ptr != 0) {
                   1369: 	    var sense = ptr == 1 ? ": " : "s: ";
                   1370: 	    var prolist = "";
                   1371: 	    if (ptr == 1) {
                   1372: 		prolist = noscore[0];
                   1373: 	    } else {
                   1374: 		var i = 0;
                   1375: 		while (i < ptr-1) {
                   1376: 		    prolist += noscore[i]+", ";
                   1377: 		    i++;
                   1378: 		}
                   1379: 		prolist += "and "+noscore[i];
                   1380: 	    }
                   1381: 	    var resp = confirm("You did not assign any score for the following problem"+sense+prolist+". Continue?");
                   1382: 	    if (resp == false) {
                   1383: 		return false;
                   1384: 	    }
                   1385: 	}
1.45      ng       1386: 
1.71      ng       1387: 	formname.submit();
                   1388:     }
                   1389: SUBJAVASCRIPT
                   1390: }
1.45      ng       1391: 
1.71      ng       1392: #--- javascript for essay type problem --
                   1393: sub sub_page_kw_js {
                   1394:     my $request = shift;
1.80      ng       1395:     my $iconpath = $request->dir_config('lonIconsURL');
1.118     ng       1396:     &commonJSfunctions($request);
1.350     albertel 1397: 
1.597   ! wenzelju 1398:     my $inner_js_msg_central= &Apache::lonhtmlcommon::scripttag(<<INNERJS);
1.350     albertel 1399:     function checkInput() {
                   1400:       opener.document.SCORE.msgsub.value = opener.checkEntities(document.msgcenter.msgsub.value);
                   1401:       var nmsg   = opener.document.SCORE.savemsgN.value;
                   1402:       var usrctr = document.msgcenter.usrctr.value;
                   1403:       var newval = opener.document.SCORE["newmsg"+usrctr];
                   1404:       newval.value = opener.checkEntities(document.msgcenter.newmsg.value);
                   1405: 
                   1406:       var msgchk = "";
                   1407:       if (document.msgcenter.subchk.checked) {
                   1408:          msgchk = "msgsub,";
                   1409:       }
                   1410:       var includemsg = 0;
                   1411:       for (var i=1; i<=nmsg; i++) {
                   1412:           var opnmsg = opener.document.SCORE["savemsg"+i];
                   1413:           var frmmsg = document.msgcenter["msg"+i];
                   1414:           opnmsg.value = opener.checkEntities(frmmsg.value);
                   1415:           var showflg = opener.document.SCORE["shownOnce"+i];
                   1416:           showflg.value = "1";
                   1417:           var chkbox = document.msgcenter["msgn"+i];
                   1418:           if (chkbox.checked) {
                   1419:              msgchk += "savemsg"+i+",";
                   1420:              includemsg = 1;
                   1421:           }
                   1422:       }
                   1423:       if (document.msgcenter.newmsgchk.checked) {
                   1424:          msgchk += "newmsg"+usrctr;
                   1425:          includemsg = 1;
                   1426:       }
                   1427:       imgformname = opener.document.SCORE["mailicon"+usrctr];
                   1428:       imgformname.src = "$iconpath/"+((includemsg) ? "mailto.gif" : "mailbkgrd.gif");
                   1429:       var includemsg = opener.document.SCORE["includemsg"+usrctr];
                   1430:       includemsg.value = msgchk;
                   1431: 
                   1432:       self.close()
                   1433: 
                   1434:     }
                   1435: INNERJS
                   1436: 
1.597   ! wenzelju 1437:     my $inner_js_highlight_central= &Apache::lonhtmlcommon::scripttag(<<INNERJS);
1.351     albertel 1438:     function updateChoice(flag) {
                   1439:       opener.document.SCORE.kwclr.value = opener.radioSelection(document.hlCenter.kwdclr);
                   1440:       opener.document.SCORE.kwsize.value = opener.radioSelection(document.hlCenter.kwdsize);
                   1441:       opener.document.SCORE.kwstyle.value = opener.radioSelection(document.hlCenter.kwdstyle);
                   1442:       opener.document.SCORE.refresh.value = "on";
                   1443:       if (opener.document.SCORE.keywords.value!=""){
                   1444:          opener.document.SCORE.submit();
                   1445:       }
                   1446:       self.close()
                   1447:     }
                   1448: INNERJS
                   1449: 
                   1450:     my $start_page_msg_central = 
                   1451:         &Apache::loncommon::start_page('Message Central',$inner_js_msg_central,
                   1452: 				       {'js_ready'  => 1,
                   1453: 					'only_body' => 1,
                   1454: 					'bgcolor'   =>'#FFFFFF',});
                   1455:     my $end_page_msg_central = 
                   1456: 	&Apache::loncommon::end_page({'js_ready' => 1});
                   1457: 
                   1458: 
                   1459:     my $start_page_highlight_central = 
                   1460:         &Apache::loncommon::start_page('Highlight Central',
                   1461: 				       $inner_js_highlight_central,
1.350     albertel 1462: 				       {'js_ready'  => 1,
                   1463: 					'only_body' => 1,
                   1464: 					'bgcolor'   =>'#FFFFFF',});
1.351     albertel 1465:     my $end_page_highlight_central = 
1.350     albertel 1466: 	&Apache::loncommon::end_page({'js_ready' => 1});
                   1467: 
1.219     www      1468:     my $docopen=&Apache::lonhtmlcommon::javascript_docopen();
1.236     albertel 1469:     $docopen=~s/^document\.//;
1.539     riegler  1470:     my $alertmsg = &mt('Please select a word or group of words from document and then click this link.');
1.597   ! wenzelju 1471:     $request->print(&Apache::lonhtmlcommon::scripttag(<<SUBJAVASCRIPT));
1.45      ng       1472: 
1.44      ng       1473: //===================== Show list of keywords ====================
1.122     ng       1474:   function keywords(formname) {
                   1475:     var nret = prompt("Keywords list, separated by a space. Add/delete to list if desired.",formname.keywords.value);
1.44      ng       1476:     if (nret==null) return;
1.122     ng       1477:     formname.keywords.value = nret;
1.44      ng       1478: 
1.122     ng       1479:     if (formname.keywords.value != "") {
1.128     ng       1480: 	formname.refresh.value = "on";
1.122     ng       1481: 	formname.submit();
1.44      ng       1482:     }
                   1483:     return;
                   1484:   }
                   1485: 
                   1486: //===================== Script to view submitted by ==================
                   1487:   function viewSubmitter(submitter) {
                   1488:     document.SCORE.refresh.value = "on";
                   1489:     document.SCORE.NCT.value = "1";
                   1490:     document.SCORE.unamedom0.value = submitter;
                   1491:     document.SCORE.submit();
                   1492:     return;
                   1493:   }
                   1494: 
                   1495: //===================== Script to add keyword(s) ==================
                   1496:   function getSel() {
                   1497:     if (document.getSelection) txt = document.getSelection();
                   1498:     else if (document.selection) txt = document.selection.createRange().text;
                   1499:     else return;
                   1500:     var cleantxt = txt.replace(new RegExp('([\\f\\n\\r\\t\\v ])+', 'g')," ");
                   1501:     if (cleantxt=="") {
1.539     riegler  1502: 	alert("$alertmsg");
1.44      ng       1503: 	return;
                   1504:     }
                   1505:     var nret = prompt("Add selection to keyword list? Edit if desired.",cleantxt);
                   1506:     if (nret==null) return;
1.127     ng       1507:     document.SCORE.keywords.value = document.SCORE.keywords.value+" "+nret;
1.44      ng       1508:     if (document.SCORE.keywords.value != "") {
1.127     ng       1509: 	document.SCORE.refresh.value = "on";
1.44      ng       1510: 	document.SCORE.submit();
                   1511:     }
                   1512:     return;
                   1513:   }
                   1514: 
                   1515: //====================== Script for composing message ==============
1.80      ng       1516:    // preload images
                   1517:    img1 = new Image();
                   1518:    img1.src = "$iconpath/mailbkgrd.gif";
                   1519:    img2 = new Image();
                   1520:    img2.src = "$iconpath/mailto.gif";
                   1521: 
1.44      ng       1522:   function msgCenter(msgform,usrctr,fullname) {
                   1523:     var Nmsg  = msgform.savemsgN.value;
                   1524:     savedMsgHeader(Nmsg,usrctr,fullname);
                   1525:     var subject = msgform.msgsub.value;
1.127     ng       1526:     var msgchk = document.SCORE["includemsg"+usrctr].value;
1.44      ng       1527:     re = /msgsub/;
                   1528:     var shwsel = "";
                   1529:     if (re.test(msgchk)) { shwsel = "checked" }
1.123     ng       1530:     subject = (document.SCORE.shownSub.value == 0 ? checkEntities(subject) : subject);
                   1531:     displaySubject(checkEntities(subject),shwsel);
1.44      ng       1532:     for (var i=1; i<=Nmsg; i++) {
1.123     ng       1533: 	var testmsg = "savemsg"+i+",";
                   1534: 	re = new RegExp(testmsg,"g");
1.44      ng       1535: 	shwsel = "";
                   1536: 	if (re.test(msgchk)) { shwsel = "checked" }
1.125     ng       1537: 	var message = document.SCORE["savemsg"+i].value;
1.126     ng       1538: 	message = (document.SCORE["shownOnce"+i].value == 0 ? checkEntities(message) : message);
1.123     ng       1539: 	displaySavedMsg(i,message,shwsel); //I do not get it. w/o checkEntities on saved messages,
                   1540: 	                                   //any &lt; is already converted to <, etc. However, only once!!
1.44      ng       1541:     }
1.125     ng       1542:     newmsg = document.SCORE["newmsg"+usrctr].value;
1.44      ng       1543:     shwsel = "";
                   1544:     re = /newmsg/;
                   1545:     if (re.test(msgchk)) { shwsel = "checked" }
                   1546:     newMsg(newmsg,shwsel);
                   1547:     msgTail(); 
                   1548:     return;
                   1549:   }
                   1550: 
1.123     ng       1551:   function checkEntities(strx) {
                   1552:     if (strx.length == 0) return strx;
                   1553:     var orgStr = ["&", "<", ">", '"']; 
                   1554:     var newStr = ["&amp;", "&lt;", "&gt;", "&quot;"];
                   1555:     var counter = 0;
                   1556:     while (counter < 4) {
                   1557: 	strx = strReplace(strx,orgStr[counter],newStr[counter]);
                   1558: 	counter++;
                   1559:     }
                   1560:     return strx;
                   1561:   }
                   1562: 
                   1563:   function strReplace(strx, orgStr, newStr) {
                   1564:     return strx.split(orgStr).join(newStr);
                   1565:   }
                   1566: 
1.44      ng       1567:   function savedMsgHeader(Nmsg,usrctr,fullname) {
1.76      ng       1568:     var height = 70*Nmsg+250;
1.44      ng       1569:     var scrollbar = "no";
                   1570:     if (height > 600) {
                   1571: 	height = 600;
                   1572: 	scrollbar = "yes";
                   1573:     }
1.118     ng       1574:     var xpos = (screen.width-600)/2;
                   1575:     xpos = (xpos < 0) ? '0' : xpos;
                   1576:     var ypos = (screen.height-height)/2-30;
                   1577:     ypos = (ypos < 0) ? '0' : ypos;
                   1578: 
1.206     albertel 1579:     pWin = window.open('', 'MessageCenter', 'resizable=yes,toolbar=no,location=no,scrollbars='+scrollbar+',screenx='+xpos+',screeny='+ypos+',width=600,height='+height);
1.76      ng       1580:     pWin.focus();
                   1581:     pDoc = pWin.document;
1.219     www      1582:     pDoc.$docopen;
1.351     albertel 1583:     pDoc.write('$start_page_msg_central');
1.76      ng       1584: 
                   1585:     pDoc.write("<form action=\\"inactive\\" name=\\"msgcenter\\">");
                   1586:     pDoc.write("<input value=\\""+usrctr+"\\" name=\\"usrctr\\" type=\\"hidden\\">");
1.465     albertel 1587:     pDoc.write("<h3><span class=\\"LC_info\\">&nbsp;Compose Message for \"+fullname+\"<\\/span><\\/h3><br /><br />");
1.76      ng       1588: 
1.564     bisitz   1589:     pDoc.write('<table border="0" width="100%"><tr><td bgcolor="#777777">');
                   1590:     pDoc.write('<table border="0" width="100%"><tr bgcolor="#DDFFFF">');
1.465     albertel 1591:     pDoc.write("<td><b>Type<\\/b><\\/td><td><b>Include<\\/b><\\/td><td><b>Message<\\/td><\\/tr>");
1.44      ng       1592: }
                   1593:     function displaySubject(msg,shwsel) {
1.76      ng       1594:     pDoc = pWin.document;
                   1595:     pDoc.write("<tr bgcolor=\\"#ffffdd\\">");
1.465     albertel 1596:     pDoc.write("<td>Subject<\\/td>");
                   1597:     pDoc.write("<td align=\\"center\\"><input name=\\"subchk\\" type=\\"checkbox\\"" +shwsel+"><\\/td>");
                   1598:     pDoc.write("<td><input name=\\"msgsub\\" type=\\"text\\" value=\\""+msg+"\\"size=\\"60\\" maxlength=\\"80\\"><\\/td><\\/tr>");
1.44      ng       1599: }
                   1600: 
1.72      ng       1601:   function displaySavedMsg(ctr,msg,shwsel) {
1.76      ng       1602:     pDoc = pWin.document;
                   1603:     pDoc.write("<tr bgcolor=\\"#ffffdd\\">");
1.465     albertel 1604:     pDoc.write("<td align=\\"center\\">"+ctr+"<\\/td>");
                   1605:     pDoc.write("<td align=\\"center\\"><input name=\\"msgn"+ctr+"\\" type=\\"checkbox\\"" +shwsel+"><\\/td>");
                   1606:     pDoc.write("<td><textarea name=\\"msg"+ctr+"\\" cols=\\"60\\" rows=\\"3\\">"+msg+"<\\/textarea><\\/td><\\/tr>");
1.44      ng       1607: }
                   1608: 
                   1609:   function newMsg(newmsg,shwsel) {
1.76      ng       1610:     pDoc = pWin.document;
                   1611:     pDoc.write("<tr bgcolor=\\"#ffffdd\\">");
1.465     albertel 1612:     pDoc.write("<td align=\\"center\\">New<\\/td>");
                   1613:     pDoc.write("<td align=\\"center\\"><input name=\\"newmsgchk\\" type=\\"checkbox\\"" +shwsel+"><\\/td>");
                   1614:     pDoc.write("<td><textarea name=\\"newmsg\\" cols=\\"60\\" rows=\\"3\\" onchange=\\"javascript:this.form.newmsgchk.checked=true\\" >"+newmsg+"<\\/textarea><\\/td><\\/tr>");
1.44      ng       1615: }
                   1616: 
                   1617:   function msgTail() {
1.76      ng       1618:     pDoc = pWin.document;
1.465     albertel 1619:     pDoc.write("<\\/table>");
                   1620:     pDoc.write("<\\/td><\\/tr><\\/table>&nbsp;");
1.589     bisitz   1621:     pDoc.write("<input type=\\"button\\" value=\\"Save\\" onclick=\\"javascript:checkInput()\\">&nbsp;&nbsp;");
                   1622:     pDoc.write("<input type=\\"button\\" value=\\"Cancel\\" onclick=\\"self.close()\\"><br /><br />");
1.465     albertel 1623:     pDoc.write("<\\/form>");
1.351     albertel 1624:     pDoc.write('$end_page_msg_central');
1.128     ng       1625:     pDoc.close();
1.44      ng       1626: }
                   1627: 
                   1628: //====================== Script for keyword highlight options ==============
                   1629:   function kwhighlight() {
                   1630:     var kwclr    = document.SCORE.kwclr.value;
                   1631:     var kwsize   = document.SCORE.kwsize.value;
                   1632:     var kwstyle  = document.SCORE.kwstyle.value;
                   1633:     var redsel = "";
                   1634:     var grnsel = "";
                   1635:     var blusel = "";
                   1636:     if (kwclr=="red")   {var redsel="checked"};
                   1637:     if (kwclr=="green") {var grnsel="checked"};
                   1638:     if (kwclr=="blue")  {var blusel="checked"};
                   1639:     var sznsel = "";
                   1640:     var sz1sel = "";
                   1641:     var sz2sel = "";
                   1642:     if (kwsize=="0")  {var sznsel="checked"};
                   1643:     if (kwsize=="+1") {var sz1sel="checked"};
                   1644:     if (kwsize=="+2") {var sz2sel="checked"};
                   1645:     var synsel = "";
                   1646:     var syisel = "";
                   1647:     var sybsel = "";
                   1648:     if (kwstyle=="")    {var synsel="checked"};
                   1649:     if (kwstyle=="<i>") {var syisel="checked"};
                   1650:     if (kwstyle=="<b>") {var sybsel="checked"};
                   1651:     highlightCentral();
                   1652:     highlightbody('red','red',redsel,'0','normal',sznsel,'','normal',synsel);
                   1653:     highlightbody('green','green',grnsel,'+1','+1',sz1sel,'<i>','italic',syisel);
                   1654:     highlightbody('blue','blue',blusel,'+2','+2',sz2sel,'<b>','bold',sybsel);
                   1655:     highlightend();
                   1656:     return;
                   1657:   }
                   1658: 
                   1659:   function highlightCentral() {
1.76      ng       1660: //    if (window.hwdWin) window.hwdWin.close();
1.118     ng       1661:     var xpos = (screen.width-400)/2;
                   1662:     xpos = (xpos < 0) ? '0' : xpos;
                   1663:     var ypos = (screen.height-330)/2-30;
                   1664:     ypos = (ypos < 0) ? '0' : ypos;
                   1665: 
1.206     albertel 1666:     hwdWin = window.open('', 'KeywordHighlightCentral', 'resizeable=yes,toolbar=no,location=no,scrollbars=no,width=400,height=300,screenx='+xpos+',screeny='+ypos);
1.76      ng       1667:     hwdWin.focus();
                   1668:     var hDoc = hwdWin.document;
1.219     www      1669:     hDoc.$docopen;
1.351     albertel 1670:     hDoc.write('$start_page_highlight_central');
1.76      ng       1671:     hDoc.write("<form action=\\"inactive\\" name=\\"hlCenter\\">");
1.465     albertel 1672:     hDoc.write("<h3><span class=\\"LC_info\\">&nbsp;Keyword Highlight Options<\\/span><\\/h3><br /><br />");
1.76      ng       1673: 
1.564     bisitz   1674:     hDoc.write('<table border="0" width="100%"><tr><td bgcolor="#777777">');
                   1675:     hDoc.write('<table border="0" width="100%"><tr bgcolor="#DDFFFF">');
1.465     albertel 1676:     hDoc.write("<td><b>Text Color<\\/b><\\/td><td><b>Font Size<\\/b><\\/td><td><b>Font Style<\\/td><\\/tr>");
1.44      ng       1677:   }
                   1678: 
                   1679:   function highlightbody(clrval,clrtxt,clrsel,szval,sztxt,szsel,syval,sytxt,sysel) { 
1.76      ng       1680:     var hDoc = hwdWin.document;
                   1681:     hDoc.write("<tr bgcolor=\\"#ffffdd\\">");
                   1682:     hDoc.write("<td align=\\"left\\">");
1.465     albertel 1683:     hDoc.write("<input name=\\"kwdclr\\" type=\\"radio\\" value=\\""+clrval+"\\" "+clrsel+">&nbsp;"+clrtxt+"<\\/td>");
1.76      ng       1684:     hDoc.write("<td align=\\"left\\">");
1.465     albertel 1685:     hDoc.write("<input name=\\"kwdsize\\" type=\\"radio\\" value=\\""+szval+"\\" "+szsel+">&nbsp;"+sztxt+"<\\/td>");
1.76      ng       1686:     hDoc.write("<td align=\\"left\\">");
1.465     albertel 1687:     hDoc.write("<input name=\\"kwdstyle\\" type=\\"radio\\" value=\\""+syval+"\\" "+sysel+">&nbsp;"+sytxt+"<\\/td>");
                   1688:     hDoc.write("<\\/tr>");
1.44      ng       1689:   }
                   1690: 
                   1691:   function highlightend() { 
1.76      ng       1692:     var hDoc = hwdWin.document;
1.465     albertel 1693:     hDoc.write("<\\/table>");
                   1694:     hDoc.write("<\\/td><\\/tr><\\/table>&nbsp;");
1.589     bisitz   1695:     hDoc.write("<input type=\\"button\\" value=\\"Save\\" onclick=\\"javascript:updateChoice(1)\\">&nbsp;&nbsp;");
                   1696:     hDoc.write("<input type=\\"button\\" value=\\"Cancel\\" onclick=\\"self.close()\\"><br /><br />");
1.465     albertel 1697:     hDoc.write("<\\/form>");
1.351     albertel 1698:     hDoc.write('$end_page_highlight_central');
1.128     ng       1699:     hDoc.close();
1.44      ng       1700:   }
                   1701: 
                   1702: SUBJAVASCRIPT
                   1703: }
                   1704: 
1.349     albertel 1705: sub get_increment {
1.348     bowersj2 1706:     my $increment = $env{'form.increment'};
                   1707:     if ($increment != 1 && $increment != .5 && $increment != .25 &&
                   1708:         $increment != .1) {
                   1709:         $increment = 1;
                   1710:     }
                   1711:     return $increment;
                   1712: }
                   1713: 
1.585     bisitz   1714: sub gradeBox_start {
                   1715:     return (
                   1716:         &Apache::loncommon::start_data_table()
                   1717:        .&Apache::loncommon::start_data_table_header_row()
                   1718:        .'<th>'.&mt('Part').'</th>'
                   1719:        .'<th>'.&mt('Points').'</th>'
                   1720:        .'<th>&nbsp;</th>'
                   1721:        .'<th>'.&mt('Assign Grade').'</th>'
                   1722:        .'<th>'.&mt('Weight').'</th>'
                   1723:        .'<th>'.&mt('Grade Status').'</th>'
                   1724:        .&Apache::loncommon::end_data_table_header_row()
                   1725:     );
                   1726: }
                   1727: 
                   1728: sub gradeBox_end {
                   1729:     return (
                   1730:         &Apache::loncommon::end_data_table()
                   1731:     );
                   1732: }
1.71      ng       1733: #--- displays the grading box, used in essay type problem and grading by page/sequence
                   1734: sub gradeBox {
1.322     albertel 1735:     my ($request,$symb,$uname,$udom,$counter,$partid,$record) = @_;
1.381     albertel 1736:     my $checkIcon = '<img alt="'.&mt('Check Mark').
1.485     albertel 1737: 	'" src="'.&Apache::loncommon::lonhttpdurl($request->dir_config('lonIconsURL').'/check.gif').'" height="16" border="0" />';
1.71      ng       1738:     my $wgt    = &Apache::lonnet::EXT('resource.'.$partid.'.weight',$symb,$udom,$uname);
1.466     albertel 1739:     my $wgtmsg = ($wgt > 0) ? &mt('(problem weight)') 
                   1740:                            : '<span class="LC_info">'.&mt('problem weight assigned by computer').'</span>';
1.71      ng       1741:     $wgt       = ($wgt > 0 ? $wgt : '1');
                   1742:     my $score  = ($$record{'resource.'.$partid.'.awarded'} eq '' ?
1.320     albertel 1743: 		  '' : &compute_points($$record{'resource.'.$partid.'.awarded'},$wgt));
1.71      ng       1744:     my $result='<input type="hidden" name="WGT'.$counter.'_'.$partid.'" value="'.$wgt.'" />'."\n";
1.466     albertel 1745:     my $display_part= &get_display_part($partid,$symb);
1.270     albertel 1746:     my %last_resets = &get_last_resets($symb,$env{'request.course.id'},
                   1747: 				       [$partid]);
                   1748:     my $aggtries = $$record{'resource.'.$partid.'.tries'};
1.269     raeburn  1749:     if ($last_resets{$partid}) {
                   1750:         $aggtries = &get_num_tries($record,$last_resets{$partid},$partid);
                   1751:     }
1.585     bisitz   1752:     $result.=&Apache::loncommon::start_data_table_row();
1.71      ng       1753:     my $ctr = 0;
1.348     bowersj2 1754:     my $thisweight = 0;
1.349     albertel 1755:     my $increment = &get_increment();
1.485     albertel 1756: 
                   1757:     my $radio.='<table border="0"><tr>'."\n";  # display radio buttons in a nice table 10 across
1.348     bowersj2 1758:     while ($thisweight<=$wgt) {
1.532     bisitz   1759: 	$radio.= '<td><span class="LC_nobreak"><label><input type="radio" name="RADVAL'.$counter.'_'.$partid.'" '.
1.589     bisitz   1760:         'onclick="javascript:writeBox(this.form,\''.$counter.'_'.$partid.'\','.
1.348     bowersj2 1761: 	    $thisweight.')" value="'.$thisweight.'" '.
1.401     albertel 1762: 	    ($score eq $thisweight ? 'checked="checked"':'').' /> '.$thisweight."</label></span></td>\n";
1.485     albertel 1763: 	$radio.=(($ctr+1)%10 == 0 ? '</tr><tr>' : '');
1.348     bowersj2 1764:         $thisweight += $increment;
1.71      ng       1765: 	$ctr++;
                   1766:     }
1.485     albertel 1767:     $radio.='</tr></table>';
                   1768: 
                   1769:     my $line.='<input type="text" name="GD_BOX'.$counter.'_'.$partid.'"'.
1.71      ng       1770: 	($score ne ''? ' value = "'.$score.'"':'').' size="4" '.
1.589     bisitz   1771: 	'onchange="javascript:updateRadio(this.form,\''.$counter.'_'.$partid.'\','.
1.71      ng       1772: 	$wgt.')" /></td>'."\n";
1.485     albertel 1773:     $line.='<td>/'.$wgt.' '.$wgtmsg.
1.71      ng       1774: 	($$record{'resource.'.$partid.'.solved'} eq 'correct_by_student' ? '&nbsp;'.$checkIcon : '').
1.585     bisitz   1775: 	' </td>'."\n";
                   1776:     $line.='<td><select name="GD_SEL'.$counter.'_'.$partid.'" '.
1.589     bisitz   1777: 	'onchange="javascript:clearRadBox(this.form,\''.$counter.'_'.$partid.'\')" >'."\n";
1.71      ng       1778:     if ($$record{'resource.'.$partid.'.solved'} eq 'excused') {
1.485     albertel 1779: 	$line.='<option></option>'.
                   1780: 	    '<option value="excused" selected="selected">'.&mt('excused').'</option>';
1.71      ng       1781:     } else {
1.485     albertel 1782: 	$line.='<option selected="selected"></option>'.
                   1783: 	    '<option value="excused" >'.&mt('excused').'</option>';
1.71      ng       1784:     }
1.485     albertel 1785:     $line.='<option value="reset status">'.&mt('reset status').'</option></select>'."\n";
                   1786: 
                   1787: 
1.540     riegler  1788: 	#&mt('<td><b>Part:</b></td><td>[_1]</td><td><b>Points:</b></td><td>[_2]</td><td>or</td><td>[_3]</td>',$display_part,$radio,$line);
1.485     albertel 1789:     $result .= 
1.585     bisitz   1790: 	    '<td>'.$display_part.'</td><td>'.$radio.'</td><td>'.&mt('or').'</td><td>'.$line.'</td>';
                   1791:     $result.=&Apache::loncommon::end_data_table_row();
1.71      ng       1792:     $result.='<input type="hidden" name="stores'.$counter.'_'.$partid.'" value="" />'."\n".
                   1793: 	'<input type="hidden" name="oldpts'.$counter.'_'.$partid.'" value="'.$score.'" />'."\n".
                   1794: 	'<input type="hidden" name="solved'.$counter.'_'.$partid.'" value="'.
1.269     raeburn  1795: 	$$record{'resource.'.$partid.'.solved'}.'" />'."\n".
                   1796:         '<input type="hidden" name="totaltries'.$counter.'_'.$partid.'" value="'.
                   1797:         $$record{'resource.'.$partid.'.tries'}.'" />'."\n".
                   1798:         '<input type="hidden" name="aggtries'.$counter.'_'.$partid.'" value="'.
                   1799:         $aggtries.'" />'."\n";
1.582     raeburn  1800:     my $res_error;
                   1801:     $result.=&handback_box($symb,$uname,$udom,$counter,$partid,$record,\$res_error);
                   1802:     if ($res_error) {
                   1803:         return &navmap_errormsg();
                   1804:     }
1.318     banghart 1805:     return $result;
                   1806: }
1.322     albertel 1807: 
                   1808: sub handback_box {
1.582     raeburn  1809:     my ($symb,$uname,$udom,$counter,$partid,$record,$res_error) = @_;
                   1810:     my ($partlist,$handgrade,$responseType) = &response_type($symb,$res_error);
1.323     banghart 1811:     my (@respids);
1.375     albertel 1812:      my @part_response_id = &flatten_responseType($responseType);
                   1813:     foreach my $part_response_id (@part_response_id) {
                   1814:     	my ($part,$resp) = @{ $part_response_id };
1.323     banghart 1815:         if ($part eq $partid) {
1.375     albertel 1816:             push(@respids,$resp);
1.323     banghart 1817:         }
                   1818:     }
1.318     banghart 1819:     my $result;
1.323     banghart 1820:     foreach my $respid (@respids) {
1.322     albertel 1821: 	my $prefix = $counter.'_'.$partid.'_'.$respid.'_';
                   1822: 	my $files=&get_submitted_files($udom,$uname,$partid,$respid,$record);
                   1823: 	next if (!@$files);
                   1824: 	my $file_counter = 1;
1.313     banghart 1825: 	foreach my $file (@$files) {
1.368     banghart 1826: 	    if ($file =~ /\/portfolio\//) {
                   1827:     	        my ($file_path, $file_disp) = ($file =~ m|(.+/)(.+)$|);
                   1828:     	        my ($name,$version,$ext) = &file_name_version_ext($file_disp);
                   1829:     	        $file_disp = "$name.$ext";
                   1830:     	        $file = $file_path.$file_disp;
                   1831:     	        $result.=&mt('Return commented version of [_1] to student.',
                   1832:     			 '<span class="LC_filename">'.$file_disp.'</span>');
                   1833:     	        $result.='<input type="file"   name="'.$prefix.'returndoc'.$file_counter.'" />'."\n";
                   1834:     	        $result.='<input type="hidden" name="'.$prefix.'origdoc'.$file_counter.'" value="'.$file.'" /><br />';
1.485     albertel 1835:     	        $result.='('.&mt('File will be uploaded when you click on Save &amp; Next below.').')<br />';
1.368     banghart 1836:     	        $file_counter++;
                   1837: 	    }
1.322     albertel 1838: 	}
1.313     banghart 1839:     }
1.318     banghart 1840:     return $result;    
1.71      ng       1841: }
1.44      ng       1842: 
1.58      albertel 1843: sub show_problem {
1.382     albertel 1844:     my ($request,$symb,$uname,$udom,$removeform,$viewon,$mode,$form) = @_;
1.144     albertel 1845:     my $rendered;
1.382     albertel 1846:     my %form = ((ref($form) eq 'HASH')? %{$form} : ());
1.329     albertel 1847:     &Apache::lonxml::remember_problem_counter();
1.144     albertel 1848:     if ($mode eq 'both' or $mode eq 'text') {
                   1849: 	$rendered=&Apache::loncommon::get_student_view($symb,$uname,$udom,
1.382     albertel 1850: 						       $env{'request.course.id'},
                   1851: 						       undef,\%form);
1.144     albertel 1852:     }
1.58      albertel 1853:     if ($removeform) {
                   1854: 	$rendered=~s|<form(.*?)>||g;
                   1855: 	$rendered=~s|</form>||g;
1.374     albertel 1856: 	$rendered=~s|(<input[^>]*name\s*=\s*"?)(\w+)("?)|$1would_have_been_$2$3|g;
1.58      albertel 1857:     }
1.144     albertel 1858:     my $companswer;
                   1859:     if ($mode eq 'both' or $mode eq 'answer') {
1.329     albertel 1860: 	&Apache::lonxml::restore_problem_counter();
1.382     albertel 1861: 	$companswer=
                   1862: 	    &Apache::loncommon::get_student_answers($symb,$uname,$udom,
                   1863: 						    $env{'request.course.id'},
                   1864: 						    %form);
1.144     albertel 1865:     }
1.58      albertel 1866:     if ($removeform) {
                   1867: 	$companswer=~s|<form(.*?)>||g;
                   1868: 	$companswer=~s|</form>||g;
1.144     albertel 1869: 	$companswer=~s|name="submit"|name="would_have_been_submit"|g;
1.58      albertel 1870:     }
1.468     albertel 1871:     $rendered=
1.588     bisitz   1872:         '<div class="LC_Box">'
                   1873:        .'<h3 class="LC_hcell">'.&mt('View of the problem').'</h3>'
                   1874:        .$rendered
                   1875:        .'</div>';
1.468     albertel 1876:     $companswer=
1.588     bisitz   1877:         '<div class="LC_Box">'
                   1878:        .'<h3 class="LC_hcell">'.&mt('Correct answer').'</h3>'
                   1879:        .$companswer
                   1880:        .'</div>';
1.468     albertel 1881:     my $result;
1.144     albertel 1882:     if ($mode eq 'both') {
1.588     bisitz   1883:         $result=$rendered.$companswer;
1.144     albertel 1884:     } elsif ($mode eq 'text') {
1.588     bisitz   1885:         $result=$rendered;
1.144     albertel 1886:     } elsif ($mode eq 'answer') {
1.588     bisitz   1887:         $result=$companswer;
1.144     albertel 1888:     }
1.71      ng       1889:     return $result;
1.58      albertel 1890: }
1.397     albertel 1891: 
1.396     banghart 1892: sub files_exist {
                   1893:     my ($r, $symb) = @_;
                   1894:     my @students = &Apache::loncommon::get_env_multiple('form.stuinfo');
1.397     albertel 1895: 
1.396     banghart 1896:     foreach my $student (@students) {
                   1897:         my ($uname,$udom,$fullname) = split(/:/,$student);
1.397     albertel 1898:         my %record = &Apache::lonnet::restore($symb,$env{'request.course.id'},
                   1899: 					      $udom,$uname);
1.396     banghart 1900:         my ($string,$timestamp)= &get_last_submission(\%record);
1.397     albertel 1901:         foreach my $submission (@$string) {
                   1902:             my ($partid,$respid) =
                   1903: 		($submission =~ /^resource\.([^\.]*)\.([^\.]*)\.submission/);
                   1904:             my $files=&get_submitted_files($udom,$uname,$partid,$respid,
                   1905: 					   \%record);
                   1906:             return 1 if (@$files);
1.396     banghart 1907:         }
                   1908:     }
1.397     albertel 1909:     return 0;
1.396     banghart 1910: }
1.397     albertel 1911: 
1.394     banghart 1912: sub download_all_link {
                   1913:     my ($r,$symb) = @_;
1.395     albertel 1914:     my $all_students = 
                   1915: 	join("\n", &Apache::loncommon::get_env_multiple('form.stuinfo'));
                   1916: 
                   1917:     my $parts =
                   1918: 	join("\n",&Apache::loncommon::get_env_multiple('form.vPart'));
                   1919: 
1.394     banghart 1920:     my $identifier = &Apache::loncommon::get_cgi_id();
1.514     raeburn  1921:     &Apache::lonnet::appenv({'cgi.'.$identifier.'.students' => $all_students,
                   1922:                              'cgi.'.$identifier.'.symb' => $symb,
                   1923:                              'cgi.'.$identifier.'.parts' => $parts,});
1.395     albertel 1924:     $r->print('<a href="/cgi-bin/multidownload.pl?'.$identifier.'">'.
                   1925: 	      &mt('Download All Submitted Documents').'</a>');
1.394     banghart 1926:     return
                   1927: }
1.395     albertel 1928: 
1.432     banghart 1929: sub build_section_inputs {
                   1930:     my $section_inputs;
                   1931:     if ($env{'form.section'} eq '') {
                   1932:         $section_inputs .= '<input type="hidden" name="section" value="all" />'."\n";
                   1933:     } else {
                   1934:         my @sections = &Apache::loncommon::get_env_multiple('form.section');
1.434     albertel 1935:         foreach my $section (@sections) {
1.432     banghart 1936:             $section_inputs .= '<input type="hidden" name="section" value="'.$section.'" />'."\n";
                   1937:         }
                   1938:     }
                   1939:     return $section_inputs;
                   1940: }
                   1941: 
1.44      ng       1942: # --------------------------- show submissions of a student, option to grade 
                   1943: sub submission {
                   1944:     my ($request,$counter,$total) = @_;
1.257     albertel 1945:     my ($uname,$udom)     = ($env{'form.student'},$env{'form.userdom'});
                   1946:     $udom = ($udom eq '' ? $env{'user.domain'} : $udom); #has form.userdom changed for a student?
                   1947:     my $usec = &Apache::lonnet::getsection($udom,$uname,$env{'request.course.id'});
                   1948:     $env{'form.fullname'} = &Apache::loncommon::plainname($uname,$udom,'lastname') if $env{'form.fullname'} eq '';
1.324     albertel 1949:     my $symb = &get_symb($request); 
                   1950:     if ($symb eq '') { $request->print("Unable to handle ambiguous references:."); return ''; }
1.104     albertel 1951: 
                   1952:     if (!&canview($usec)) {
1.398     albertel 1953: 	$request->print('<span class="LC_warning">Unable to view requested student.('.
                   1954: 			$uname.':'.$udom.' in section '.$usec.' in course id '.
                   1955: 			$env{'request.course.id'}.')</span>');
1.324     albertel 1956: 	$request->print(&show_grading_menu_form($symb));
1.104     albertel 1957: 	return;
                   1958:     }
                   1959: 
1.257     albertel 1960:     if (!$env{'form.lastSub'}) { $env{'form.lastSub'} = 'datesub'; }
                   1961:     if (!$env{'form.vProb'}) { $env{'form.vProb'} = 'yes'; }
                   1962:     if (!$env{'form.vAns'}) { $env{'form.vAns'} = 'yes'; }
                   1963:     my $last = ($env{'form.lastSub'} eq 'last' ? 'last' : '');
1.381     albertel 1964:     my $checkIcon = '<img alt="'.&mt('Check Mark').
                   1965: 	'" src="'.$request->dir_config('lonIconsURL').
1.122     ng       1966: 	'/check.gif" height="16" border="0" />';
1.41      ng       1967: 
1.426     albertel 1968:     my %old_essays;
1.41      ng       1969:     # header info
                   1970:     if ($counter == 0) {
                   1971: 	&sub_page_js($request);
1.257     albertel 1972: 	&sub_page_kw_js($request) if ($env{'form.handgrade'} eq 'yes');
                   1973: 	$env{'form.probTitle'} = $env{'form.probTitle'} eq '' ? 
                   1974: 	    &Apache::lonnet::gettitle($symb) : $env{'form.probTitle'};
1.397     albertel 1975: 	if ($env{'form.handgrade'} eq 'yes' && &files_exist($request, $symb)) {
1.396     banghart 1976: 	    &download_all_link($request, $symb);
                   1977: 	}
1.485     albertel 1978: 	$request->print('<h3>&nbsp;<span class="LC_info">'.&mt('Submission Record').'</span></h3>'."\n".
                   1979: 			'<h4>&nbsp;'.&mt('<b>Resource: </b> [_1]',$env{'form.probTitle'}).'</h4>'."\n");
1.118     ng       1980: 
1.44      ng       1981: 	# option to display problem, only once else it cause problems 
                   1982:         # with the form later since the problem has a form.
1.257     albertel 1983: 	if ($env{'form.vProb'} eq 'yes' or $env{'form.vAns'} eq 'yes') {
1.144     albertel 1984: 	    my $mode;
1.257     albertel 1985: 	    if ($env{'form.vProb'} eq 'yes' && $env{'form.vAns'} eq 'yes') {
1.144     albertel 1986: 		$mode='both';
1.257     albertel 1987: 	    } elsif ($env{'form.vProb'} eq 'yes') {
1.144     albertel 1988: 		$mode='text';
1.257     albertel 1989: 	    } elsif ($env{'form.vAns'} eq 'yes') {
1.144     albertel 1990: 		$mode='answer';
                   1991: 	    }
1.329     albertel 1992: 	    &Apache::lonxml::clear_problem_counter();
1.144     albertel 1993: 	    $request->print(&show_problem($request,$symb,$uname,$udom,0,1,$mode));
1.41      ng       1994: 	}
1.441     www      1995: 
1.44      ng       1996: 	# kwclr is the only variable that is guaranteed to be non blank 
                   1997:         # if this subroutine has been called once.
1.41      ng       1998: 	my %keyhash = ();
1.257     albertel 1999: 	if ($env{'form.kwclr'} eq '' && $env{'form.handgrade'} eq 'yes') {
1.41      ng       2000: 	    %keyhash = &Apache::lonnet::dump('nohist_handgrade',
1.257     albertel 2001: 					     $env{'course.'.$env{'request.course.id'}.'.domain'},
                   2002: 					     $env{'course.'.$env{'request.course.id'}.'.num'});
1.41      ng       2003: 
1.257     albertel 2004: 	    my $loginuser = $env{'user.name'}.':'.$env{'user.domain'};
                   2005: 	    $env{'form.keywords'} = $keyhash{$symb.'_keywords'} ne '' ? $keyhash{$symb.'_keywords'} : '';
                   2006: 	    $env{'form.kwclr'}    = $keyhash{$loginuser.'_kwclr'} ne '' ? $keyhash{$loginuser.'_kwclr'} : 'red';
                   2007: 	    $env{'form.kwsize'}   = $keyhash{$loginuser.'_kwsize'} ne '' ? $keyhash{$loginuser.'_kwsize'} : '0';
                   2008: 	    $env{'form.kwstyle'}  = $keyhash{$loginuser.'_kwstyle'} ne '' ? $keyhash{$loginuser.'_kwstyle'} : '';
                   2009: 	    $env{'form.msgsub'}   = $keyhash{$symb.'_subject'} ne '' ? 
                   2010: 		$keyhash{$symb.'_subject'} : $env{'form.probTitle'};
                   2011: 	    $env{'form.savemsgN'} = $keyhash{$symb.'_savemsgN'} ne '' ? $keyhash{$symb.'_savemsgN'} : '0';
1.41      ng       2012: 	}
1.257     albertel 2013: 	my $overRideScore = $env{'form.overRideScore'} eq '' ? 'no' : $env{'form.overRideScore'};
1.442     banghart 2014: 	my $stu_status = join(':',&Apache::loncommon::get_env_multiple('form.Status'));
1.303     banghart 2015: 	$request->print('<form action="/adm/grades" method="post" name="SCORE" enctype="multipart/form-data">'."\n".
1.41      ng       2016: 			'<input type="hidden" name="command"    value="handgrade" />'."\n".
1.257     albertel 2017: 			'<input type="hidden" name="saveState"  value="'.$env{'form.saveState'}.'" />'."\n".
1.442     banghart 2018: 			'<input type="hidden" name="Status"     value="'.$stu_status.'" />'."\n".
1.120     ng       2019: 			'<input type="hidden" name="overRideScore" value="'.$overRideScore.'" />'."\n".
1.257     albertel 2020: 			'<input type="hidden" name="probTitle"  value="'.$env{'form.probTitle'}.'" />'."\n".
1.41      ng       2021: 			'<input type="hidden" name="refresh"    value="off" />'."\n".
1.120     ng       2022: 			'<input type="hidden" name="studentNo"  value="" />'."\n".
                   2023: 			'<input type="hidden" name="gradeOpt"   value="" />'."\n".
1.418     albertel 2024: 			'<input type="hidden" name="symb"       value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
1.257     albertel 2025: 			'<input type="hidden" name="showgrading" value="'.$env{'form.showgrading'}.'" />'."\n".
                   2026: 			'<input type="hidden" name="vProb"      value="'.$env{'form.vProb'}.'" />'."\n".
                   2027: 			'<input type="hidden" name="vAns"       value="'.$env{'form.vAns'}.'" />'."\n".
                   2028: 			'<input type="hidden" name="lastSub"    value="'.$env{'form.lastSub'}.'" />'."\n".
1.432     banghart 2029: 			&build_section_inputs().
1.326     albertel 2030: 			'<input type="hidden" name="submitonly" value="'.$env{'form.submitonly'}.'" />'."\n".
                   2031: 			'<input type="hidden" name="handgrade"  value="'.$env{'form.handgrade'}.'" />'."\n".
1.41      ng       2032: 			'<input type="hidden" name="NCT"'.
1.257     albertel 2033: 			' value="'.($env{'form.NTSTU'} ne '' ? $env{'form.NTSTU'} : $total+1).'" />'."\n");
                   2034: 	if ($env{'form.handgrade'} eq 'yes') {
                   2035: 	    $request->print('<input type="hidden" name="keywords" value="'.$env{'form.keywords'}.'" />'."\n".
                   2036: 			    '<input type="hidden" name="kwclr"    value="'.$env{'form.kwclr'}.'" />'."\n".
                   2037: 			    '<input type="hidden" name="kwsize"   value="'.$env{'form.kwsize'}.'" />'."\n".
                   2038: 			    '<input type="hidden" name="kwstyle"  value="'.$env{'form.kwstyle'}.'" />'."\n".
                   2039: 			    '<input type="hidden" name="msgsub"   value="'.$env{'form.msgsub'}.'" />'."\n".
1.123     ng       2040: 			    '<input type="hidden" name="shownSub" value="0" />'."\n".
1.257     albertel 2041: 			    '<input type="hidden" name="savemsgN" value="'.$env{'form.savemsgN'}.'" />'."\n");
1.154     albertel 2042: 	    foreach my $partid (&Apache::loncommon::get_env_multiple('form.vPart')) {
                   2043: 		$request->print('<input type="hidden" name="vPart" value="'.$partid.'" />'."\n");
                   2044: 	    }
1.123     ng       2045: 	}
1.41      ng       2046: 	
                   2047: 	my ($cts,$prnmsg) = (1,'');
1.257     albertel 2048: 	while ($cts <= $env{'form.savemsgN'}) {
1.41      ng       2049: 	    $prnmsg.='<input type="hidden" name="savemsg'.$cts.'" value="'.
1.123     ng       2050: 		(!exists($keyhash{$symb.'_savemsg'.$cts}) ? 
1.257     albertel 2051: 		 &Apache::lonfeedback::clear_out_html($env{'form.savemsg'.$cts}) :
1.80      ng       2052: 		 &Apache::lonfeedback::clear_out_html($keyhash{$symb.'_savemsg'.$cts})).
1.123     ng       2053: 		'" />'."\n".
                   2054: 		'<input type="hidden" name="shownOnce'.$cts.'" value="0" />'."\n";
1.41      ng       2055: 	    $cts++;
                   2056: 	}
                   2057: 	$request->print($prnmsg);
1.32      ng       2058: 
1.257     albertel 2059: 	if ($env{'form.handgrade'} eq 'yes' && $env{'form.showgrading'} eq 'yes') {
1.88      www      2060: #
                   2061: # Print out the keyword options line
                   2062: #
1.41      ng       2063: 	    $request->print(<<KEYWORDS);
1.38      ng       2064: &nbsp;<b>Keyword Options:</b>&nbsp;
1.417     albertel 2065: <a href="javascript:keywords(document.SCORE);" target="_self">List</a>&nbsp; &nbsp;
1.589     bisitz   2066: <a href="#" onmousedown="javascript:getSel(); return false"
1.38      ng       2067:  CLASS="page">Paste Selection to List</a>&nbsp; &nbsp;
1.417     albertel 2068: <a href="javascript:kwhighlight();" target="_self">Highlight Attribute</a><br /><br />
1.38      ng       2069: KEYWORDS
1.88      www      2070: #
                   2071: # Load the other essays for similarity check
                   2072: #
1.324     albertel 2073:             my (undef,undef,$essayurl) = &Apache::lonnet::decode_symb($symb);
1.384     albertel 2074: 	    my ($adom,$aname,$apath)=($essayurl=~/^($LONCAPA::domain_re)\/($LONCAPA::username_re)\/(.*)$/);
1.359     www      2075: 	    $apath=&escape($apath);
1.88      www      2076: 	    $apath=~s/\W/\_/gs;
1.426     albertel 2077: 	    %old_essays=&Apache::lonnet::dump('nohist_essay_'.$apath,$adom,$aname);
1.41      ng       2078:         }
                   2079:     }
1.44      ng       2080: 
1.441     www      2081: # This is where output for one specific student would start
1.592     bisitz   2082:     my $add_class = ($counter%2) ? ' LC_grade_show_user_odd_row' : '';
                   2083:     $request->print(
                   2084:         "\n\n"
                   2085:        .'<div class="LC_grade_show_user'.$add_class.'">'
                   2086:        .'<h2>'.&nameUserString(undef,$env{'form.fullname'},$uname,$udom).'</h2>'
                   2087:        ."\n"
                   2088:     );
1.441     www      2089: 
1.592     bisitz   2090:     # Show additional functions if allowed
                   2091:     if ($perm{'vgr'}) {
                   2092:         $request->print(
                   2093:             &Apache::loncommon::track_student_link(
                   2094:                 &mt('View recent activity'),
                   2095:                 $uname,$udom,'check')
                   2096:            .' '
                   2097:         );
                   2098:     }
                   2099:     if ($perm{'opa'}) {
                   2100:         $request->print(
                   2101:             &Apache::loncommon::pprmlink(
                   2102:                 &mt('Set/Change parameters'),
                   2103:                 $uname,$udom,$symb,'check'));
                   2104:     }
                   2105: 
                   2106:     # Show Problem
1.257     albertel 2107:     if ($env{'form.vProb'} eq 'all' or $env{'form.vAns'} eq 'all') {
1.144     albertel 2108: 	my $mode;
1.257     albertel 2109: 	if ($env{'form.vProb'} eq 'all' && $env{'form.vAns'} eq 'all') {
1.144     albertel 2110: 	    $mode='both';
1.257     albertel 2111: 	} elsif ($env{'form.vProb'} eq 'all' ) {
1.144     albertel 2112: 	    $mode='text';
1.257     albertel 2113: 	} elsif ($env{'form.vAns'} eq 'all') {
1.144     albertel 2114: 	    $mode='answer';
                   2115: 	}
1.329     albertel 2116: 	&Apache::lonxml::clear_problem_counter();
1.475     albertel 2117: 	$request->print(&show_problem($request,$symb,$uname,$udom,1,1,$mode,{'request.prefix' => 'ctr'.$counter}));
1.58      albertel 2118:     }
1.144     albertel 2119: 
1.257     albertel 2120:     my %record = &Apache::lonnet::restore($symb,$env{'request.course.id'},$udom,$uname);
1.582     raeburn  2121:     my $res_error;
                   2122:     my ($partlist,$handgrade,$responseType) = &response_type($symb,\$res_error);
                   2123:     if ($res_error) {
                   2124:         $request->print(&navmap_errormsg());
                   2125:         return;
                   2126:     }
1.41      ng       2127: 
1.44      ng       2128:     # Display student info
1.41      ng       2129:     $request->print(($counter == 0 ? '' : '<br />'));
1.590     bisitz   2130: 
                   2131:     my $result='<div class="LC_Box">'
                   2132:               .'<h3 class="LC_hcell">'.&mt('Submissions').'</h3>';
1.45      ng       2133:     $result.='<input type="hidden" name="name'.$counter.
1.588     bisitz   2134:              '" value="'.$env{'form.fullname'}.'" />'."\n";
1.469     albertel 2135:     if ($env{'form.handgrade'} eq 'no') {
1.588     bisitz   2136:         $result.='<p class="LC_info">'
                   2137:                 .&mt('Part(s) graded correct by the computer is marked with a [_1] symbol.',$checkIcon)
                   2138:                 ."</p>\n";
1.469     albertel 2139:     }
                   2140: 
1.118     ng       2141:     # If any part of the problem is an essay-response (handgraded), then check for collaborators
1.464     albertel 2142:     my $fullname;
                   2143:     my $col_fullnames = [];
1.257     albertel 2144:     if ($env{'form.handgrade'} eq 'yes') {
1.464     albertel 2145: 	(my $sub_result,$fullname,$col_fullnames)=
                   2146: 	    &check_collaborators($symb,$uname,$udom,\%record,$handgrade,
                   2147: 				 $counter);
                   2148: 	$result.=$sub_result;
1.41      ng       2149:     }
1.44      ng       2150:     $request->print($result."\n");
1.588     bisitz   2151: 
1.44      ng       2152:     # print student answer/submission
1.588     bisitz   2153:     # Options are (1) Handgraded submission only
1.44      ng       2154:     #             (2) Last submission, includes submission that is not handgraded 
                   2155:     #                  (for multi-response type part)
                   2156:     #             (3) Last submission plus the parts info
                   2157:     #             (4) The whole record for this student
1.257     albertel 2158:     if ($env{'form.lastSub'} =~ /^(lastonly|hdgrade)$/) {
1.151     albertel 2159: 	my ($string,$timestamp)= &get_last_submission(\%record);
1.468     albertel 2160: 	
                   2161: 	my $lastsubonly;
                   2162: 
1.588     bisitz   2163:         if ($$timestamp eq '') {
                   2164:             $lastsubonly.='<div class="LC_grade_submissions_body">'.$$string[0].'</div>'; 
                   2165:         } else {
1.592     bisitz   2166:             $lastsubonly =
                   2167:                 '<div class="LC_grade_submissions_body">'
                   2168:                .'<b>'.&mt('Date Submitted:').'</b> '.$$timestamp."\n";
1.468     albertel 2169: 
1.151     albertel 2170: 	    my %seenparts;
1.375     albertel 2171: 	    my @part_response_id = &flatten_responseType($responseType);
                   2172: 	    foreach my $part (@part_response_id) {
1.393     albertel 2173: 		next if ($env{'form.lastSub'} eq 'hdgrade' 
                   2174: 			 && $$handgrade{$$part[0].'_'.$$part[1]} ne 'yes');
                   2175: 
1.375     albertel 2176: 		my ($partid,$respid) = @{ $part };
1.324     albertel 2177: 		my $display_part=&get_display_part($partid,$symb);
1.257     albertel 2178: 		if ($env{"form.$uname:$udom:$partid:submitted_by"}) {
1.151     albertel 2179: 		    if (exists($seenparts{$partid})) { next; }
                   2180: 		    $seenparts{$partid}=1;
1.207     albertel 2181: 		    my $submitby='<b>Part:</b> '.$display_part.
                   2182: 			' <b>Collaborative submission by:</b> '.
1.151     albertel 2183: 			'<a href="javascript:viewSubmitter(\''.
1.257     albertel 2184: 			$env{"form.$uname:$udom:$partid:submitted_by"}.
1.417     albertel 2185: 			'\');" target="_self">'.
1.257     albertel 2186: 			$$fullname{$env{"form.$uname:$udom:$partid:submitted_by"}}.'</a><br />';
1.151     albertel 2187: 		    $request->print($submitby);
                   2188: 		    next;
                   2189: 		}
                   2190: 		my $responsetype = $responseType->{$partid}->{$respid};
                   2191: 		if (!exists($record{"resource.$partid.$respid.submission"})) {
1.577     bisitz   2192:                     $lastsubonly.="\n".'<div class="LC_grade_submission_part">'.
                   2193:                         '<b>'.&mt('Part: [_1]',$display_part).'</b>'.
                   2194:                         ' <span class="LC_internal_info">'.
1.597   ! wenzelju 2195:                         '('.&mt('Part ID: [_1]',$respid).')'.
1.577     bisitz   2196:                         '</span>&nbsp; &nbsp;'.
1.539     riegler  2197: 			'<span class="LC_warning">'.&mt('Nothing submitted - no attempts.').'</span><br /><br /></div>';
1.151     albertel 2198: 		    next;
                   2199: 		}
1.468     albertel 2200: 		foreach my $submission (@$string) {
                   2201: 		    my ($partid,$respid) = ($submission =~ /^resource\.([^\.]*)\.([^\.]*)\.submission/);
1.375     albertel 2202: 		    if (join('_',@{$part}) ne ($partid.'_'.$respid)) { next; }
1.596     raeburn  2203: 		    my ($ressub,$hide,$subval) = split(/:/,$submission,3);
1.151     albertel 2204: 		    # Similarity check
                   2205: 		    my $similar='';
1.257     albertel 2206: 		    if($env{'form.checkPlag'}){
1.151     albertel 2207: 			my ($oname,$odom,$ocrsid,$oessay,$osim)=
1.426     albertel 2208: 			    &most_similar($uname,$udom,$subval,\%old_essays);
1.151     albertel 2209: 			if ($osim) {
                   2210: 			    $osim=int($osim*100.0);
1.426     albertel 2211: 			    my %old_course_desc = 
                   2212: 				&Apache::lonnet::coursedescription($ocrsid,
                   2213: 								   {'one_time' => 1});
                   2214: 
1.596     raeburn  2215:                             if ($hide) {
                   2216:                                 $similar='<hr /><span class="LC_warning">'.&mt("Essay was found to be similar to another essay submitted for this assignment.").'<br />'.
                   2217:                                          &mt('As the current submission is for an anonymous survey, no other details are available.').'</span><hr />';
                   2218:                             } else {
                   2219: 			        $similar="<hr /><h3><span class=\"LC_warning\">".
                   2220: 				    &mt('Essay is [_1]% similar to an essay by [_2] in course [_3] (course id [_4]:[_5])',
                   2221: 				        $osim,
                   2222: 				        &Apache::loncommon::plainname($oname,$odom).' ('.$oname.':'.$odom.')',
                   2223: 				        $old_course_desc{'description'},
                   2224: 				        $old_course_desc{'num'},
                   2225: 				        $old_course_desc{'domain'}).
                   2226: 				    '</span></h3><blockquote><i>'.
                   2227: 				    &keywords_highlight($oessay).
                   2228: 				    '</i></blockquote><hr />';
                   2229:                             }
1.151     albertel 2230: 			}
1.150     albertel 2231: 		    }
1.151     albertel 2232: 		    my $order=&get_order($partid,$respid,$symb,$uname,$udom);
1.257     albertel 2233: 		    if ($env{'form.lastSub'} eq 'lastonly' || 
                   2234: 			($env{'form.lastSub'} eq 'hdgrade' && 
1.377     albertel 2235: 			 $$handgrade{$$part[0].'_'.$$part[1]} eq 'yes')) {
1.324     albertel 2236: 			my $display_part=&get_display_part($partid,$symb);
1.577     bisitz   2237:                         $lastsubonly.='<div class="LC_grade_submission_part">'.
                   2238:                             '<b>'.&mt('Part: [_1]',$display_part).'</b>'.
                   2239:                             ' <span class="LC_internal_info">'.
                   2240:                             '('.&mt('Part ID: [_1]',$respid).')'.
1.597   ! wenzelju 2241:                             '</span>&nbsp; &nbsp;';
1.313     banghart 2242: 			my $files=&get_submitted_files($udom,$uname,$partid,$respid,\%record);
                   2243: 			if (@$files) {
1.596     raeburn  2244:                             if ($hide) {
                   2245:                                 $lastsubonly.='<br />'.&mt('[quant,_1,file] uploaded to this anonymous survey',scalar(@{$files}));
                   2246:                             } else {
                   2247:                                 $lastsubonly.='<br /><span class="LC_warning">'.&mt('Like all files provided by users, this file may contain viruses').'</span><br />';
                   2248:                                 foreach my $file (@$files) {
                   2249:                                     &Apache::lonnet::allowuploaded('/adm/grades',$file);
                   2250:                                     $lastsubonly.='<br /><a href="'.$file.'?rawmode=1" target="lonGRDs"><img src="'.&Apache::loncommon::icon($file).'" border="0" /> '.$file.'</a>';
                   2251:                                 }
                   2252:                             }
1.236     albertel 2253: 			    $lastsubonly.='<br />';
1.41      ng       2254: 			}
1.596     raeburn  2255:                         if ($hide) {
                   2256:                             $lastsubonly.='<b>'.&mt('Anonymous Survey').'</b>'; 
                   2257:                         } else {
                   2258: 			    $lastsubonly.='<b>'.&mt('Submitted Answer:').' </b>'.
                   2259: 			        &cleanRecord($subval,$responsetype,$symb,$partid,
                   2260: 					     $respid,\%record,$order,undef,$uname,$udom);
                   2261:                         }
1.151     albertel 2262: 			if ($similar) {$lastsubonly.="<br /><br />$similar\n";}
1.468     albertel 2263: 			$lastsubonly.='</div>';
1.41      ng       2264: 		    }
                   2265: 		}
                   2266: 	    }
1.588     bisitz   2267: 	    $lastsubonly.='</div>'."\n"; # End: LC_grade_submissions_body
1.151     albertel 2268: 	}
                   2269: 	$request->print($lastsubonly);
1.468     albertel 2270:    } elsif ($env{'form.lastSub'} eq 'datesub') {
1.324     albertel 2271: 	my (undef,$responseType,undef,$parts) = &showResourceInfo($symb);
1.148     albertel 2272: 	$request->print(&displaySubByDates($symb,\%record,$parts,$responseType,$checkIcon,$uname,$udom));
1.257     albertel 2273:     } elsif ($env{'form.lastSub'} =~ /^(last|all)$/) {
1.41      ng       2274: 	$request->print(&Apache::loncommon::get_previous_attempt($symb,$uname,$udom,
1.257     albertel 2275: 								 $env{'request.course.id'},
1.44      ng       2276: 								 $last,'.submission',
                   2277: 								 'Apache::grades::keywords_highlight'));
1.41      ng       2278:     }
1.120     ng       2279: 
1.121     ng       2280:     $request->print('<input type="hidden" name="unamedom'.$counter.'" value="'.$uname.':'
                   2281: 	.$udom.'" />'."\n");
1.44      ng       2282:     # return if view submission with no grading option
1.257     albertel 2283:     if ($env{'form.showgrading'} eq '' || (!&canmodify($usec))) {
1.120     ng       2284: 	my $toGrade.='<input type="button" value="Grade Student" '.
1.589     bisitz   2285: 	    'onclick="javascript:checksubmit(this.form,\'Grade Student\',\''
1.417     albertel 2286: 	    .$counter.'\');" target="_self" /> &nbsp;'."\n" if (&canmodify($usec));
1.468     albertel 2287: 	$toGrade.='</div>'."\n";
1.257     albertel 2288: 	if (($env{'form.command'} eq 'submission') || 
                   2289: 	    ($env{'form.command'} eq 'processGroup' && $counter == $total)) {
1.324     albertel 2290: 	    $toGrade.='</form>'.&show_grading_menu_form($symb); 
1.169     albertel 2291: 	}
1.180     albertel 2292: 	$request->print($toGrade);
1.41      ng       2293: 	return;
1.180     albertel 2294:     } else {
1.468     albertel 2295: 	$request->print('</div>'."\n");
1.41      ng       2296:     }
1.33      ng       2297: 
1.121     ng       2298:     # essay grading message center
1.257     albertel 2299:     if ($env{'form.handgrade'} eq 'yes') {
1.468     albertel 2300: 	my $result='<div class="LC_grade_message_center">';
                   2301:     
                   2302: 	$result.='<div class="LC_grade_message_center_header">'.
                   2303: 	    &mt('Send Message').'</div><div class="LC_grade_message_center_body">';
1.257     albertel 2304: 	my ($lastname,$givenn) = split(/,/,$env{'form.fullname'});
1.118     ng       2305: 	my $msgfor = $givenn.' '.$lastname;
1.464     albertel 2306: 	if (scalar(@$col_fullnames) > 0) {
                   2307: 	    my $lastone = pop(@$col_fullnames);
                   2308: 	    $msgfor .= ', '.(join ', ',@$col_fullnames).' and '.$lastone.'.';
1.118     ng       2309: 	}
                   2310: 	$msgfor =~ s/\'/\\'/g; #' stupid emacs - no! javascript
1.468     albertel 2311: 	$result.='<input type="hidden" name="includemsg'.$counter.'" value="" />'."\n".
1.121     ng       2312: 	    '<input type="hidden" name="newmsg'.$counter.'" value="" />'."\n";
                   2313: 	$result.='&nbsp;<a href="javascript:msgCenter(document.SCORE,'.$counter.
1.417     albertel 2314: 	    ',\''.$msgfor.'\');" target="_self">'.
1.464     albertel 2315: 	    &mt('Compose message to student').(scalar(@$col_fullnames) >= 1 ? 's' : '').'</a><label> ('.
1.350     albertel 2316: 	    &mt('incl. grades').' <input type="checkbox" name="withgrades'.$counter.'" /></label>)'.
1.118     ng       2317: 	    '<img src="'.$request->dir_config('lonIconsURL').
                   2318: 	    '/mailbkgrd.gif" width="14" height="10" name="mailicon'.$counter.'" />'."\n".
1.298     www      2319: 	    '<br />&nbsp;('.
1.468     albertel 2320: 	    &mt('Message will be sent when you click on Save &amp; Next below.').")\n";
                   2321: 	$result.='</div></div>';
1.121     ng       2322: 	$request->print($result);
1.118     ng       2323:     }
1.41      ng       2324: 
                   2325:     my %seen = ();
                   2326:     my @partlist;
1.129     ng       2327:     my @gradePartRespid;
1.375     albertel 2328:     my @part_response_id = &flatten_responseType($responseType);
1.585     bisitz   2329:     $request->print(
1.588     bisitz   2330:         '<div class="LC_Box">'
                   2331:        .'<h3 class="LC_hcell">'.&mt('Assign Grades').'</h3>'
1.585     bisitz   2332:     );
1.592     bisitz   2333:     $request->print(&gradeBox_start());
1.375     albertel 2334:     foreach my $part_response_id (@part_response_id) {
                   2335:     	my ($partid,$respid) = @{ $part_response_id };
                   2336: 	my $part_resp = join('_',@{ $part_response_id });
1.322     albertel 2337: 	next if ($seen{$partid} > 0);
1.41      ng       2338: 	$seen{$partid}++;
1.393     albertel 2339: 	next if ($$handgrade{$part_resp} ne 'yes' 
                   2340: 		 && $env{'form.lastSub'} eq 'hdgrade');
1.524     raeburn  2341: 	push(@partlist,$partid);
                   2342: 	push(@gradePartRespid,$partid.'.'.$respid);
1.322     albertel 2343: 	$request->print(&gradeBox($request,$symb,$uname,$udom,$counter,$partid,\%record));
1.41      ng       2344:     }
1.585     bisitz   2345:     $request->print(&gradeBox_end()); # </div>
                   2346:     $request->print('</div>');
1.468     albertel 2347: 
                   2348:     $request->print('<div class="LC_grade_info_links">');
                   2349:     $request->print('</div>');
                   2350: 
1.45      ng       2351:     $result='<input type="hidden" name="partlist'.$counter.
                   2352: 	'" value="'.(join ":",@partlist).'" />'."\n";
1.129     ng       2353:     $result.='<input type="hidden" name="gradePartRespid'.
                   2354: 	'" value="'.(join ":",@gradePartRespid).'" />'."\n" if ($counter == 0);
1.45      ng       2355:     my $ctr = 0;
                   2356:     while ($ctr < scalar(@partlist)) {
                   2357: 	$result.='<input type="hidden" name="partid'.$counter.'_'.$ctr.'" value="'.
                   2358: 	    $partlist[$ctr].'" />'."\n";
                   2359: 	$ctr++;
                   2360:     }
1.468     albertel 2361:     $request->print($result.''."\n");
1.41      ng       2362: 
1.441     www      2363: # Done with printing info for one student
                   2364: 
1.468     albertel 2365:     $request->print('</div>');#LC_grade_show_user
1.441     www      2366: 
                   2367: 
1.41      ng       2368:     # print end of form
                   2369:     if ($counter == $total) {
1.592     bisitz   2370:         my $endform='<br /><hr /><table border="0"><tr><td>'."\n";
1.485     albertel 2371: 	$endform.='<input type="button" value="'.&mt('Save &amp; Next').'" '.
1.589     bisitz   2372: 	    'onclick="javascript:checksubmit(this.form,\'Save & Next\','.
1.417     albertel 2373: 	    $total.','.scalar(@partlist).');" target="_self" /> &nbsp;'."\n";
1.119     ng       2374: 	my $ntstu ='<select name="NTSTU">'.
                   2375: 	    '<option>1</option><option>2</option>'.
                   2376: 	    '<option>3</option><option>5</option>'.
                   2377: 	    '<option>7</option><option>10</option></select>'."\n";
1.257     albertel 2378: 	my $nsel = ($env{'form.NTSTU'} ne '' ? $env{'form.NTSTU'} : '1');
1.401     albertel 2379: 	$ntstu =~ s/<option>$nsel</<option selected="selected">$nsel</;
1.578     raeburn  2380:         $endform.=&mt('[_1]student(s)',$ntstu);
1.485     albertel 2381: 	$endform.='&nbsp;&nbsp;<input type="button" value="'.&mt('Previous').'" '.
1.589     bisitz   2382: 	    'onclick="javascript:checksubmit(this.form,\'Previous\');" target="_self" /> &nbsp;'."\n".
1.485     albertel 2383: 	    '<input type="button" value="'.&mt('Next').'" '.
1.589     bisitz   2384: 	    'onclick="javascript:checksubmit(this.form,\'Next\');" target="_self" /> &nbsp;';
1.592     bisitz   2385:         $endform.='<span class="LC_warning">'.
                   2386:                   &mt('(Next and Previous (student) do not save the scores.)').
                   2387:                   '</span>'."\n" ;
1.349     albertel 2388:         $endform.="<input type='hidden' value='".&get_increment().
1.348     bowersj2 2389:             "' name='increment' />";
1.485     albertel 2390: 	$endform.='</td></tr></table></form>';
1.324     albertel 2391: 	$endform.=&show_grading_menu_form($symb);
1.41      ng       2392: 	$request->print($endform);
                   2393:     }
                   2394:     return '';
1.38      ng       2395: }
                   2396: 
1.464     albertel 2397: sub check_collaborators {
                   2398:     my ($symb,$uname,$udom,$record,$handgrade,$counter) = @_;
                   2399:     my ($result,@col_fullnames);
                   2400:     my ($classlist,undef,$fullname) = &getclasslist('all','0');
                   2401:     foreach my $part (keys(%$handgrade)) {
                   2402: 	my $ncol = &Apache::lonnet::EXT('resource.'.$part.
                   2403: 					'.maxcollaborators',
                   2404: 					$symb,$udom,$uname);
                   2405: 	next if ($ncol <= 0);
                   2406: 	$part =~ s/\_/\./g;
                   2407: 	next if ($record->{'resource.'.$part.'.collaborators'} eq '');
                   2408: 	my (@good_collaborators, @bad_collaborators);
                   2409: 	foreach my $possible_collaborator
                   2410: 	    (split(/,?\s+/,$record->{'resource.'.$part.'.collaborators'})) { 
                   2411: 	    $possible_collaborator =~ s/[\$\^\(\)]//g;
                   2412: 	    next if ($possible_collaborator eq '');
                   2413: 	    my ($co_name,$co_dom) = split(/\@|:/,$possible_collaborator);
                   2414: 	    $co_dom = $udom if (! defined($co_dom) || $co_dom =~ /^domain$/i);
                   2415: 	    next if ($co_name eq $uname && $co_dom eq $udom);
                   2416: 	    # Doing this grep allows 'fuzzy' specification
                   2417: 	    my @matches = grep(/^\Q$co_name\E:\Q$co_dom\E$/i, 
                   2418: 			       keys(%$classlist));
                   2419: 	    if (! scalar(@matches)) {
                   2420: 		push(@bad_collaborators, $possible_collaborator);
                   2421: 	    } else {
                   2422: 		push(@good_collaborators, @matches);
                   2423: 	    }
                   2424: 	}
                   2425: 	if (scalar(@good_collaborators) != 0) {
1.466     albertel 2426: 	    $result.='<br />'.&mt('Collaborators: ');
1.464     albertel 2427: 	    foreach my $name (@good_collaborators) {
                   2428: 		my ($lastname,$givenn) = split(/,/,$$fullname{$name});
                   2429: 		push(@col_fullnames, $givenn.' '.$lastname);
                   2430: 		$result.=$fullname->{$name}.'&nbsp; &nbsp; &nbsp;';
                   2431: 	    }
                   2432: 	    $result.='<br />'."\n";
1.466     albertel 2433: 	    my ($part)=split(/\./,$part);
1.464     albertel 2434: 	    $result.='<input type="hidden" name="collaborator'.$counter.
                   2435: 		'" value="'.$part.':'.(join ':',@good_collaborators).'" />'.
                   2436: 		"\n";
                   2437: 	}
                   2438: 	if (scalar(@bad_collaborators) > 0) {
1.466     albertel 2439: 	    $result.='<div class="LC_warning">';
1.464     albertel 2440: 	    $result.=&mt('This student has submitted [quant,_1,invalid collaborator]: [_2]',scalar(@bad_collaborators),join(', ',@bad_collaborators));
                   2441: 	    $result .= '</div>';
                   2442: 	}         
                   2443: 	if (scalar(@bad_collaborators > $ncol)) {
1.466     albertel 2444: 	    $result .= '<div class="LC_warning">';
1.464     albertel 2445: 	    $result .= &mt('This student has submitted too many '.
                   2446: 		'collaborators.  Maximum is [_1].',$ncol);
                   2447: 	    $result .= '</div>';
                   2448: 	}
                   2449:     }
                   2450:     return ($result,$fullname,\@col_fullnames);
                   2451: }
                   2452: 
1.44      ng       2453: #--- Retrieve the last submission for all the parts
1.38      ng       2454: sub get_last_submission {
1.119     ng       2455:     my ($returnhash)=@_;
1.596     raeburn  2456:     my (@string,$timestamp,%lasthidden);
1.119     ng       2457:     if ($$returnhash{'version'}) {
1.46      ng       2458: 	my %lasthash=();
                   2459: 	my ($version);
1.119     ng       2460: 	for ($version=1;$version<=$$returnhash{'version'};$version++) {
1.397     albertel 2461: 	    foreach my $key (sort(split(/\:/,
                   2462: 					$$returnhash{$version.':keys'}))) {
                   2463: 		$lasthash{$key}=$$returnhash{$version.':'.$key};
                   2464: 		$timestamp = 
1.545     raeburn  2465: 		    &Apache::lonlocal::locallocaltime($$returnhash{$version.':timestamp'});
1.46      ng       2466: 	    }
                   2467: 	}
1.596     raeburn  2468:         my %typeparts;
                   2469:         my $showsurv = 
                   2470:             &Apache::lonnet::allowed('vas',$env{'request.course.id'});
                   2471:         foreach my $key (sort(keys(%lasthash))) {
                   2472:             if ($key =~ /\.type$/) {
                   2473:                 if (($lasthash{$key} eq 'anonsurvey') || 
                   2474:                     ($lasthash{$key} eq 'anonsurveycred')) {
                   2475:                     my ($ign,@parts) = split(/\./,$key);
                   2476:                     pop(@parts);
                   2477:                     unless ($showsurv) {
                   2478:                         my $id = join(',',@parts);
                   2479:                         $typeparts{$ign.'.'.$id} = $lasthash{$key};
                   2480:                     }
                   2481:                     delete($lasthash{$key});
                   2482:                 }
                   2483:             }
                   2484:         }
                   2485:         my @hidden = keys(%typeparts);
1.397     albertel 2486: 	foreach my $key (keys(%lasthash)) {
                   2487: 	    next if ($key !~ /\.submission$/);
1.596     raeburn  2488:             my $hide;
                   2489:             if (@hidden) {
                   2490:                 foreach my $id (@hidden) {
                   2491:                     if ($key =~ /^\Q$id\E/) {
                   2492:                         $hide = 1;
                   2493:                         last;
                   2494:                     }
                   2495:                 }
                   2496:             }
1.397     albertel 2497: 	    my ($partid,$foo) = split(/submission$/,$key);
                   2498: 	    my $draft  = $lasthash{$partid.'awarddetail'} eq 'DRAFT' ?
1.398     albertel 2499: 		'<span class="LC_warning">Draft Copy</span> ' : '';
1.596     raeburn  2500: 	    push(@string, join(':', $key, $hide, $draft.$lasthash{$key}));
1.41      ng       2501: 	}
                   2502:     }
1.397     albertel 2503:     if (!@string) {
                   2504: 	$string[0] =
1.539     riegler  2505: 	    '<span class="LC_warning">'.&mt('Nothing submitted - no attempts.').'</span>';
1.397     albertel 2506:     }
                   2507:     return (\@string,\$timestamp);
1.38      ng       2508: }
1.35      ng       2509: 
1.44      ng       2510: #--- High light keywords, with style choosen by user.
1.38      ng       2511: sub keywords_highlight {
1.44      ng       2512:     my $string    = shift;
1.257     albertel 2513:     my $size      = $env{'form.kwsize'} eq '0' ? '' : 'size='.$env{'form.kwsize'};
                   2514:     my $styleon   = $env{'form.kwstyle'} eq ''  ? '' : $env{'form.kwstyle'};
1.41      ng       2515:     (my $styleoff = $styleon) =~ s/\</\<\//;
1.257     albertel 2516:     my @keylist   = split(/[,\s+]/,$env{'form.keywords'});
1.398     albertel 2517:     foreach my $keyword (@keylist) {
                   2518: 	$string =~ s/\b\Q$keyword\E(\b|\.)/<font color\=$env{'form.kwclr'} $size\>$styleon$keyword$styleoff<\/font>/gi;
1.41      ng       2519:     }
                   2520:     return $string;
1.38      ng       2521: }
1.36      ng       2522: 
1.44      ng       2523: #--- Called from submission routine
1.38      ng       2524: sub processHandGrade {
1.41      ng       2525:     my ($request) = shift;
1.324     albertel 2526:     my $symb   = &get_symb($request);
                   2527:     my (undef,undef,$url) = &Apache::lonnet::decode_symb($symb);
1.257     albertel 2528:     my $button = $env{'form.gradeOpt'};
                   2529:     my $ngrade = $env{'form.NCT'};
                   2530:     my $ntstu  = $env{'form.NTSTU'};
1.301     albertel 2531:     my $cdom   = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   2532:     my $cnum   = $env{'course.'.$env{'request.course.id'}.'.num'};
                   2533: 
1.44      ng       2534:     if ($button eq 'Save & Next') {
                   2535: 	my $ctr = 0;
                   2536: 	while ($ctr < $ngrade) {
1.257     albertel 2537: 	    my ($uname,$udom) = split(/:/,$env{'form.unamedom'.$ctr});
1.324     albertel 2538: 	    my ($errorflag,$pts,$wgt) = &saveHandGrade($request,$symb,$uname,$udom,$ctr);
1.71      ng       2539: 	    if ($errorflag eq 'no_score') {
                   2540: 		$ctr++;
                   2541: 		next;
                   2542: 	    }
1.104     albertel 2543: 	    if ($errorflag eq 'not_allowed') {
1.398     albertel 2544: 		$request->print("<span class=\"LC_warning\">Not allowed to modify grades for $uname:$udom</span>");
1.104     albertel 2545: 		$ctr++;
                   2546: 		next;
                   2547: 	    }
1.257     albertel 2548: 	    my $includemsg = $env{'form.includemsg'.$ctr};
1.44      ng       2549: 	    my ($subject,$message,$msgstatus) = ('','','');
1.418     albertel 2550: 	    my $restitle = &Apache::lonnet::gettitle($symb);
                   2551:             my ($feedurl,$showsymb) =
                   2552: 		&get_feedurl_and_symb($symb,$uname,$udom);
                   2553: 	    my $messagetail;
1.62      albertel 2554: 	    if ($includemsg =~ /savemsg|newmsg\Q$ctr\E/) {
1.298     www      2555: 		$subject = $env{'form.msgsub'} if ($includemsg =~ /msgsub/);
1.295     www      2556: 		unless ($subject=~/\w/) { $subject=&mt('Grading Feedback'); }
1.386     raeburn  2557: 		$subject.=' ['.$restitle.']';
1.44      ng       2558: 		my (@msgnum) = split(/,/,$includemsg);
                   2559: 		foreach (@msgnum) {
1.257     albertel 2560: 		    $message.=$env{'form.'.$_} if ($_ =~ /savemsg|newmsg/ && $_ ne '');
1.44      ng       2561: 		}
1.80      ng       2562: 		$message =&Apache::lonfeedback::clear_out_html($message);
1.298     www      2563: 		if ($env{'form.withgrades'.$ctr}) {
                   2564: 		    $message.="\n\nPoint".($pts > 1 ? 's':'').' awarded = '.$pts.' out of '.$wgt;
1.386     raeburn  2565: 		    $messagetail = " for <a href=\"".
1.418     albertel 2566: 		                   $feedurl."?symb=$showsymb\">$env{'form.probTitle'}</a>";
1.386     raeburn  2567: 		}
                   2568: 		$msgstatus = 
                   2569:                     &Apache::lonmsg::user_normal_msg($uname,$udom,$subject,
                   2570: 						     $message.$messagetail,
1.418     albertel 2571:                                                      undef,$feedurl,undef,
1.386     raeburn  2572:                                                      undef,undef,$showsymb,
                   2573:                                                      $restitle);
1.574     bisitz   2574: 		$request->print('<br />'.&mt('Sending message to [_1]',$uname.':'.$udom).': '.
1.296     www      2575: 				$msgstatus);
1.44      ng       2576: 	    }
1.257     albertel 2577: 	    if ($env{'form.collaborator'.$ctr}) {
1.155     albertel 2578: 		my @collabstrs=&Apache::loncommon::get_env_multiple("form.collaborator$ctr");
1.150     albertel 2579: 		foreach my $collabstr (@collabstrs) {
                   2580: 		    my ($part,@collaborators) = split(/:/,$collabstr);
1.310     banghart 2581: 		    foreach my $collaborator (@collaborators) {
1.150     albertel 2582: 			my ($errorflag,$pts,$wgt) = 
1.324     albertel 2583: 			    &saveHandGrade($request,$symb,$collaborator,$udom,$ctr,
1.257     albertel 2584: 					   $env{'form.unamedom'.$ctr},$part);
1.150     albertel 2585: 			if ($errorflag eq 'not_allowed') {
1.362     albertel 2586: 			    $request->print("<span class=\"LC_error\">".&mt('Not allowed to modify grades for [_1]',"$collaborator:$udom")."</span>");
1.150     albertel 2587: 			    next;
1.418     albertel 2588: 			} elsif ($message ne '') {
                   2589: 			    my ($baseurl,$showsymb) = 
                   2590: 				&get_feedurl_and_symb($symb,$collaborator,
                   2591: 						      $udom);
                   2592: 			    if ($env{'form.withgrades'.$ctr}) {
                   2593: 				$messagetail = " for <a href=\"".
1.386     raeburn  2594:                                     $baseurl."?symb=$showsymb\">$env{'form.probTitle'}</a>";
1.150     albertel 2595: 			    }
1.418     albertel 2596: 			    $msgstatus = 
                   2597: 				&Apache::lonmsg::user_normal_msg($collaborator,$udom,$subject,$message.$messagetail,undef,$baseurl,undef,undef,undef,$showsymb,$restitle);
1.104     albertel 2598: 			}
1.44      ng       2599: 		    }
                   2600: 		}
                   2601: 	    }
                   2602: 	    $ctr++;
                   2603: 	}
                   2604:     }
                   2605: 
1.257     albertel 2606:     if ($env{'form.handgrade'} eq 'yes') {
1.119     ng       2607: 	# Keywords sorted in alphabatical order
1.257     albertel 2608: 	my $loginuser = $env{'user.name'}.':'.$env{'user.domain'};
1.119     ng       2609: 	my %keyhash = ();
1.257     albertel 2610: 	$env{'form.keywords'}           =~ s/,\s{0,}|\s+/ /g;
                   2611: 	$env{'form.keywords'}           =~ s/^\s+|\s+$//;
                   2612: 	my (@keywords) = sort(split(/\s+/,$env{'form.keywords'}));
                   2613: 	$env{'form.keywords'} = join(' ',@keywords);
                   2614: 	$keyhash{$symb.'_keywords'}     = $env{'form.keywords'};
                   2615: 	$keyhash{$symb.'_subject'}      = $env{'form.msgsub'};
                   2616: 	$keyhash{$loginuser.'_kwclr'}   = $env{'form.kwclr'};
                   2617: 	$keyhash{$loginuser.'_kwsize'}  = $env{'form.kwsize'};
                   2618: 	$keyhash{$loginuser.'_kwstyle'} = $env{'form.kwstyle'};
1.119     ng       2619: 
                   2620: 	# message center - Order of message gets changed. Blank line is eliminated.
1.257     albertel 2621: 	# New messages are saved in env for the next student.
1.119     ng       2622: 	# All messages are saved in nohist_handgrade.db
                   2623: 	my ($ctr,$idx) = (1,1);
1.257     albertel 2624: 	while ($ctr <= $env{'form.savemsgN'}) {
                   2625: 	    if ($env{'form.savemsg'.$ctr} ne '') {
                   2626: 		$keyhash{$symb.'_savemsg'.$idx} = $env{'form.savemsg'.$ctr};
1.119     ng       2627: 		$idx++;
                   2628: 	    }
                   2629: 	    $ctr++;
1.41      ng       2630: 	}
1.119     ng       2631: 	$ctr = 0;
                   2632: 	while ($ctr < $ngrade) {
1.257     albertel 2633: 	    if ($env{'form.newmsg'.$ctr} ne '') {
                   2634: 		$keyhash{$symb.'_savemsg'.$idx} = $env{'form.newmsg'.$ctr};
                   2635: 		$env{'form.savemsg'.$idx} = $env{'form.newmsg'.$ctr};
1.119     ng       2636: 		$idx++;
                   2637: 	    }
                   2638: 	    $ctr++;
1.41      ng       2639: 	}
1.257     albertel 2640: 	$env{'form.savemsgN'} = --$idx;
                   2641: 	$keyhash{$symb.'_savemsgN'} = $env{'form.savemsgN'};
1.119     ng       2642: 	my $putresult = &Apache::lonnet::put
1.301     albertel 2643: 	    ('nohist_handgrade',\%keyhash,$cdom,$cnum);
1.41      ng       2644:     }
1.44      ng       2645:     # Called by Save & Refresh from Highlight Attribute Window
1.257     albertel 2646:     my (undef,undef,$fullname) = &getclasslist($env{'form.section'},'1');
                   2647:     if ($env{'form.refresh'} eq 'on') {
1.86      ng       2648: 	my ($ctr,$total) = (0,0);
                   2649: 	while ($ctr < $ngrade) {
1.257     albertel 2650: 	    $total++ if  $env{'form.unamedom'.$ctr} ne '';
1.86      ng       2651: 	    $ctr++;
                   2652: 	}
1.257     albertel 2653: 	$env{'form.NTSTU'}=$ngrade;
1.86      ng       2654: 	$ctr = 0;
                   2655: 	while ($ctr < $total) {
1.257     albertel 2656: 	    my $processUser = $env{'form.unamedom'.$ctr};
                   2657: 	    ($env{'form.student'},$env{'form.userdom'}) = split(/:/,$processUser);
                   2658: 	    $env{'form.fullname'} = $$fullname{$processUser};
1.86      ng       2659: 	    &submission($request,$ctr,$total-1);
1.41      ng       2660: 	    $ctr++;
                   2661: 	}
                   2662: 	return '';
                   2663:     }
1.36      ng       2664: 
1.121     ng       2665: # Go directly to grade student - from submission or link from chart page
1.120     ng       2666:     if ($button eq 'Grade Student') {
1.324     albertel 2667: 	(undef,undef,$env{'form.handgrade'},undef,undef) = &showResourceInfo($symb);
1.257     albertel 2668: 	my $processUser = $env{'form.unamedom'.$env{'form.studentNo'}};
                   2669: 	($env{'form.student'},$env{'form.userdom'}) = split(/:/,$processUser);
                   2670: 	$env{'form.fullname'} = $$fullname{$processUser};
1.120     ng       2671: 	&submission($request,0,0);
                   2672: 	return '';
                   2673:     }
                   2674: 
1.44      ng       2675:     # Get the next/previous one or group of students
1.257     albertel 2676:     my $firststu = $env{'form.unamedom0'};
                   2677:     my $laststu = $env{'form.unamedom'.($ngrade-1)};
1.119     ng       2678:     my $ctr = 2;
1.41      ng       2679:     while ($laststu eq '') {
1.257     albertel 2680: 	$laststu  = $env{'form.unamedom'.($ngrade-$ctr)};
1.41      ng       2681: 	$ctr++;
                   2682: 	$laststu = $firststu if ($ctr > $ngrade);
                   2683:     }
1.44      ng       2684: 
1.41      ng       2685:     my (@parsedlist,@nextlist);
                   2686:     my ($nextflg) = 0;
1.524     raeburn  2687:     foreach my $item (sort 
1.294     albertel 2688: 	     {
                   2689: 		 if (lc($$fullname{$a}) ne lc($$fullname{$b})) {
                   2690: 		     return (lc($$fullname{$a}) cmp lc($$fullname{$b}));
                   2691: 		 }
                   2692: 		 return $a cmp $b;
                   2693: 	     } (keys(%$fullname))) {
1.41      ng       2694: 	if ($nextflg == 1 && $button =~ /Next$/) {
1.524     raeburn  2695: 	    push(@parsedlist,$item);
1.41      ng       2696: 	}
1.524     raeburn  2697: 	$nextflg = 1 if ($item eq $laststu);
1.41      ng       2698: 	if ($button eq 'Previous') {
1.524     raeburn  2699: 	    last if ($item eq $firststu);
                   2700: 	    push(@parsedlist,$item);
1.41      ng       2701: 	}
                   2702:     }
                   2703:     $ctr = 0;
                   2704:     @parsedlist = reverse @parsedlist if ($button eq 'Previous');
1.582     raeburn  2705:     my $res_error;
                   2706:     my ($partlist) = &response_type($symb,\$res_error);
                   2707:     if ($res_error) {
                   2708:         $request->print(&navmap_errormsg());
                   2709:         return;
                   2710:     }
1.41      ng       2711:     foreach my $student (@parsedlist) {
1.257     albertel 2712: 	my $submitonly=$env{'form.submitonly'};
1.41      ng       2713: 	my ($uname,$udom) = split(/:/,$student);
1.301     albertel 2714: 	
                   2715: 	if ($submitonly eq 'queued') {
                   2716: 	    my %queue_status = 
                   2717: 		&Apache::bridgetask::get_student_status($symb,$cdom,$cnum,
                   2718: 							$udom,$uname);
                   2719: 	    next if (!defined($queue_status{'gradingqueue'}));
                   2720: 	}
                   2721: 
1.156     albertel 2722: 	if ($submitonly =~ /^(yes|graded|incorrect)$/) {
1.257     albertel 2723: #	    my %record = &Apache::lonnet::restore($symb,$env{'request.course.id'},$udom,$uname);
1.324     albertel 2724: 	    my %status=&student_gradeStatus($symb,$udom,$uname,$partlist);
1.145     albertel 2725: 	    my $submitted = 0;
1.248     albertel 2726: 	    my $ungraded = 0;
                   2727: 	    my $incorrect = 0;
1.524     raeburn  2728: 	    foreach my $item (keys(%status)) {
                   2729: 		$submitted = 1 if ($status{$item} ne 'nothing');
                   2730: 		$ungraded = 1 if ($status{$item} =~ /^ungraded/);
                   2731: 		$incorrect = 1 if ($status{$item} =~ /^incorrect/);
                   2732: 		my ($foo,$partid,$foo1) = split(/\./,$item);
1.145     albertel 2733: 		if ($status{'resource.'.$partid.'.submitted_by'} ne '') {
                   2734: 		    $submitted = 0;
                   2735: 		}
1.41      ng       2736: 	    }
1.156     albertel 2737: 	    next if (!$submitted && ($submitonly eq 'yes' ||
                   2738: 				     $submitonly eq 'incorrect' ||
                   2739: 				     $submitonly eq 'graded'));
1.248     albertel 2740: 	    next if (!$ungraded && ($submitonly eq 'graded'));
                   2741: 	    next if (!$incorrect && $submitonly eq 'incorrect');
1.41      ng       2742: 	}
1.524     raeburn  2743: 	push(@nextlist,$student) if ($ctr < $ntstu);
1.129     ng       2744: 	last if ($ctr == $ntstu);
1.41      ng       2745: 	$ctr++;
                   2746:     }
1.36      ng       2747: 
1.41      ng       2748:     $ctr = 0;
                   2749:     my $total = scalar(@nextlist)-1;
1.39      ng       2750: 
1.524     raeburn  2751:     foreach (sort(@nextlist)) {
1.41      ng       2752: 	my ($uname,$udom,$submitter) = split(/:/);
1.257     albertel 2753: 	$env{'form.student'}  = $uname;
                   2754: 	$env{'form.userdom'}  = $udom;
                   2755: 	$env{'form.fullname'} = $$fullname{$_};
1.41      ng       2756: 	&submission($request,$ctr,$total);
                   2757: 	$ctr++;
                   2758:     }
                   2759:     if ($total < 0) {
1.485     albertel 2760: 	my $the_end = '<h3><span class="LC_info">'.&mt('LON-CAPA User Message').'</span></h3><br />'."\n";
                   2761: 	$the_end.=&mt('<b>Message: </b> No more students for this section or class.').'<br /><br />'."\n";
                   2762: 	$the_end.=&mt('Click on the button below to return to the grading menu.').'<br /><br />'."\n";
1.324     albertel 2763: 	$the_end.=&show_grading_menu_form($symb);
1.41      ng       2764: 	$request->print($the_end);
                   2765:     }
                   2766:     return '';
1.38      ng       2767: }
1.36      ng       2768: 
1.44      ng       2769: #---- Save the score and award for each student, if changed
1.38      ng       2770: sub saveHandGrade {
1.324     albertel 2771:     my ($request,$symb,$stuname,$domain,$newflg,$submitter,$part) = @_;
1.342     banghart 2772:     my @version_parts;
1.104     albertel 2773:     my $usec = &Apache::lonnet::getsection($domain,$stuname,
1.257     albertel 2774: 					   $env{'request.course.id'});
1.104     albertel 2775:     if (!&canmodify($usec)) { return('not_allowed'); }
1.337     banghart 2776:     my %record = &Apache::lonnet::restore($symb,$env{'request.course.id'},$domain,$stuname);
1.251     banghart 2777:     my @parts_graded;
1.77      ng       2778:     my %newrecord  = ();
                   2779:     my ($pts,$wgt) = ('','');
1.269     raeburn  2780:     my %aggregate = ();
                   2781:     my $aggregateflag = 0;
1.301     albertel 2782:     my @parts = split(/:/,$env{'form.partlist'.$newflg});
                   2783:     foreach my $new_part (@parts) {
1.337     banghart 2784: 	#collaborator ($submi may vary for different parts
1.259     banghart 2785: 	if ($submitter && $new_part ne $part) { next; }
                   2786: 	my $dropMenu = $env{'form.GD_SEL'.$newflg.'_'.$new_part};
1.125     ng       2787: 	if ($dropMenu eq 'excused') {
1.259     banghart 2788: 	    if ($record{'resource.'.$new_part.'.solved'} ne 'excused') {
                   2789: 		$newrecord{'resource.'.$new_part.'.solved'} = 'excused';
                   2790: 		if (exists($record{'resource.'.$new_part.'.awarded'})) {
                   2791: 		    $newrecord{'resource.'.$new_part.'.awarded'} = '';
1.58      albertel 2792: 		}
1.364     banghart 2793: 	        $newrecord{'resource.'.$new_part.'.regrader'}="$env{'user.name'}:$env{'user.domain'}";
1.58      albertel 2794: 	    }
1.125     ng       2795: 	} elsif ($dropMenu eq 'reset status'
1.259     banghart 2796: 		 && exists($record{'resource.'.$new_part.'.solved'})) { #don't bother if no old records -> no attempts
1.524     raeburn  2797: 	    foreach my $key (keys(%record)) {
1.259     banghart 2798: 		if ($key=~/^resource\.\Q$new_part\E\./) { $newrecord{$key} = ''; }
1.197     albertel 2799: 	    }
1.259     banghart 2800: 	    $newrecord{'resource.'.$new_part.'.regrader'}=
1.257     albertel 2801: 		"$env{'user.name'}:$env{'user.domain'}";
1.270     albertel 2802:             my $totaltries = $record{'resource.'.$part.'.tries'};
                   2803: 
                   2804:             my %last_resets = &get_last_resets($symb,$env{'request.course.id'},
                   2805: 					       [$new_part]);
                   2806:             my $aggtries =$totaltries;
1.269     raeburn  2807:             if ($last_resets{$new_part}) {
1.270     albertel 2808:                 $aggtries = &get_num_tries(\%record,$last_resets{$new_part},
                   2809: 					   $new_part);
1.269     raeburn  2810:             }
1.270     albertel 2811: 
                   2812:             my $solvedstatus = $record{'resource.'.$new_part.'.solved'};
1.269     raeburn  2813:             if ($aggtries > 0) {
1.327     albertel 2814:                 &decrement_aggs($symb,$new_part,\%aggregate,$aggtries,$totaltries,$solvedstatus);
1.269     raeburn  2815:                 $aggregateflag = 1;
                   2816:             }
1.125     ng       2817: 	} elsif ($dropMenu eq '') {
1.259     banghart 2818: 	    $pts = ($env{'form.GD_BOX'.$newflg.'_'.$new_part} ne '' ? 
                   2819: 		    $env{'form.GD_BOX'.$newflg.'_'.$new_part} : 
                   2820: 		    $env{'form.RADVAL'.$newflg.'_'.$new_part});
                   2821: 	    if ($pts eq '' && $env{'form.GD_SEL'.$newflg.'_'.$new_part} eq '') {
1.153     albertel 2822: 		next;
                   2823: 	    }
1.259     banghart 2824: 	    $wgt = $env{'form.WGT'.$newflg.'_'.$new_part} eq '' ? 1 : 
                   2825: 		$env{'form.WGT'.$newflg.'_'.$new_part};
1.41      ng       2826: 	    my $partial= $pts/$wgt;
1.259     banghart 2827: 	    if ($partial eq $record{'resource.'.$new_part.'.awarded'}) {
1.153     albertel 2828: 		#do not update score for part if not changed.
1.346     banghart 2829:                 &handback_files($request,$symb,$stuname,$domain,$newflg,$new_part,\%newrecord);
1.153     albertel 2830: 		next;
1.251     banghart 2831: 	    } else {
1.524     raeburn  2832: 	        push(@parts_graded,$new_part);
1.153     albertel 2833: 	    }
1.259     banghart 2834: 	    if ($record{'resource.'.$new_part.'.awarded'} ne $partial) {
                   2835: 		$newrecord{'resource.'.$new_part.'.awarded'}  = $partial;
1.153     albertel 2836: 	    }
1.259     banghart 2837: 	    my $reckey = 'resource.'.$new_part.'.solved';
1.41      ng       2838: 	    if ($partial == 0) {
1.153     albertel 2839: 		if ($record{$reckey} ne 'incorrect_by_override') {
                   2840: 		    $newrecord{$reckey} = 'incorrect_by_override';
                   2841: 		}
1.41      ng       2842: 	    } else {
1.153     albertel 2843: 		if ($record{$reckey} ne 'correct_by_override') {
                   2844: 		    $newrecord{$reckey} = 'correct_by_override';
                   2845: 		}
                   2846: 	    }	    
                   2847: 	    if ($submitter && 
1.259     banghart 2848: 		($record{'resource.'.$new_part.'.submitted_by'} ne $submitter)) {
                   2849: 		$newrecord{'resource.'.$new_part.'.submitted_by'} = $submitter;
1.41      ng       2850: 	    }
1.259     banghart 2851: 	    $newrecord{'resource.'.$new_part.'.regrader'}=
1.257     albertel 2852: 		"$env{'user.name'}:$env{'user.domain'}";
1.41      ng       2853: 	}
1.259     banghart 2854: 	# unless problem has been graded, set flag to version the submitted files
1.305     banghart 2855: 	unless ($record{'resource.'.$new_part.'.solved'} =~ /^correct_/  || 
                   2856: 	        $record{'resource.'.$new_part.'.solved'} eq 'incorrect_by_override' ||
                   2857: 	        $dropMenu eq 'reset status')
                   2858: 	   {
1.524     raeburn  2859: 	    push(@version_parts,$new_part);
1.259     banghart 2860: 	}
1.41      ng       2861:     }
1.301     albertel 2862:     my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   2863:     my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   2864: 
1.344     albertel 2865:     if (%newrecord) {
                   2866:         if (@version_parts) {
1.364     banghart 2867:             my @changed_keys = &version_portfiles(\%record, \@parts_graded, 
                   2868:                                 $env{'request.course.id'}, $symb, $domain, $stuname, \@version_parts);
1.344     albertel 2869: 	    @newrecord{@changed_keys} = @record{@changed_keys};
1.367     albertel 2870: 	    foreach my $new_part (@version_parts) {
                   2871: 		&handback_files($request,$symb,$stuname,$domain,$newflg,
                   2872: 				$new_part,\%newrecord);
                   2873: 	    }
1.259     banghart 2874:         }
1.44      ng       2875: 	&Apache::lonnet::cstore(\%newrecord,$symb,
1.257     albertel 2876: 				$env{'request.course.id'},$domain,$stuname);
1.380     albertel 2877: 	&check_and_remove_from_queue(\@parts,\%record,\%newrecord,$symb,
                   2878: 				     $cdom,$cnum,$domain,$stuname);
1.41      ng       2879:     }
1.269     raeburn  2880:     if ($aggregateflag) {
                   2881:         &Apache::lonnet::cinc('nohist_resourcetracker',\%aggregate,
1.301     albertel 2882: 			      $cdom,$cnum);
1.269     raeburn  2883:     }
1.301     albertel 2884:     return ('',$pts,$wgt);
1.36      ng       2885: }
1.322     albertel 2886: 
1.380     albertel 2887: sub check_and_remove_from_queue {
                   2888:     my ($parts,$record,$newrecord,$symb,$cdom,$cnum,$domain,$stuname) = @_;
                   2889:     my @ungraded_parts;
                   2890:     foreach my $part (@{$parts}) {
                   2891: 	if (    $record->{   'resource.'.$part.'.awarded'} eq ''
                   2892: 	     && $record->{   'resource.'.$part.'.solved' } ne 'excused'
                   2893: 	     && $newrecord->{'resource.'.$part.'.awarded'} eq ''
                   2894: 	     && $newrecord->{'resource.'.$part.'.solved' } ne 'excused'
                   2895: 		) {
                   2896: 	    push(@ungraded_parts, $part);
                   2897: 	}
                   2898:     }
                   2899:     if ( !@ungraded_parts ) {
                   2900: 	&Apache::bridgetask::remove_from_queue('gradingqueue',$symb,$cdom,
                   2901: 					       $cnum,$domain,$stuname);
                   2902:     }
                   2903: }
                   2904: 
1.337     banghart 2905: sub handback_files {
                   2906:     my ($request,$symb,$stuname,$domain,$newflg,$new_part,$newrecord) = @_;
1.517     raeburn  2907:     my $portfolio_root = '/userfiles/portfolio';
1.582     raeburn  2908:     my $res_error;
                   2909:     my ($partlist,$handgrade,$responseType) = &response_type($symb,\$res_error);
                   2910:     if ($res_error) {
                   2911:         $request->print('<br />'.&navmap_errormsg().'<br />');
                   2912:         return;
                   2913:     }
1.375     albertel 2914:     my @part_response_id = &flatten_responseType($responseType);
                   2915:     foreach my $part_response_id (@part_response_id) {
                   2916:     	my ($part_id,$resp_id) = @{ $part_response_id };
                   2917: 	my $part_resp = join('_',@{ $part_response_id });
1.337     banghart 2918:             if (($env{'form.'.$newflg.'_'.$part_resp.'_returndoc1'}) && ($new_part == $part_id)) {
                   2919:                 # if multiple files are uploaded names will be 'returndoc2','returndoc3'
                   2920:                 my $file_counter = 1;
1.367     albertel 2921: 		my $file_msg;
1.337     banghart 2922:                 while ($env{'form.'.$newflg.'_'.$part_resp.'_returndoc'.$file_counter}) {
                   2923:                     my $fname=$env{'form.'.$newflg.'_'.$part_resp.'_returndoc'.$file_counter.'.filename'};
1.338     banghart 2924:                     my ($directory,$answer_file) = 
                   2925:                         ($env{'form.'.$newflg.'_'.$part_resp.'_origdoc'.$file_counter} =~ /^(.*?)([^\/]*)$/);
                   2926:                     my ($answer_name,$answer_ver,$answer_ext) =
                   2927: 		        &file_name_version_ext($answer_file);
1.355     banghart 2928: 		    my ($portfolio_path) = ($directory =~ /^.+$stuname\/portfolio(.*)/);
1.517     raeburn  2929:                     my $getpropath = 1;
                   2930: 		    my @dir_list = &Apache::lonnet::dirlist($portfolio_root.$portfolio_path,$domain,$stuname,$getpropath);
1.338     banghart 2931: 		    my $version = &get_next_version($answer_name, $answer_ext, \@dir_list);
1.355     banghart 2932:                     # fix file name
                   2933:                     my ($save_file_name) = (($directory.$answer_name.".$version.".$answer_ext) =~ /^.+\/${stuname}\/(.*)/);
                   2934:                     my $result=&Apache::lonnet::finishuserfileupload($stuname,$domain,
                   2935:             	                                $newflg.'_'.$part_resp.'_returndoc'.$file_counter,
                   2936:             	                                $save_file_name);
1.337     banghart 2937:                     if ($result !~ m|^/uploaded/|) {
1.536     raeburn  2938:                         $request->print('<br /><span class="LC_error">'.
                   2939:                             &mt('An error occurred ([_1]) while trying to upload [_2].',
                   2940:                                 $result,$newflg.'_'.$part_resp.'_returndoc'.$file_counter).
                   2941:                                         '</span>');
1.356     banghart 2942:                     } else {
1.360     banghart 2943:                         # mark the file as read only
                   2944:                         my @files = ($save_file_name);
1.372     albertel 2945:                         my @what = ($symb,$env{'request.course.id'},'handback');
1.360     banghart 2946:                         &Apache::lonnet::mark_as_readonly($domain,$stuname,\@files,\@what);
1.367     albertel 2947: 			if (exists($$newrecord{"resource.$new_part.$resp_id.handback"})) {
                   2948: 			    $$newrecord{"resource.$new_part.$resp_id.handback"}.=',';
                   2949: 			}
                   2950:                         $$newrecord{"resource.$new_part.$resp_id.handback"} .= $save_file_name;
                   2951: 			$file_msg.= "\n".'<br /><span class="LC_filename"><a href="/uploaded/'."$domain/$stuname/".$save_file_name.'">'.$save_file_name."</a></span><br />";
                   2952: 
1.337     banghart 2953:                     }
                   2954:                     $request->print("<br />".$fname." will be the uploaded file name");
1.354     albertel 2955:                     $request->print(" ".$env{'form.'.$newflg.'_'.$part_resp.'_origdoc'.$file_counter});
1.337     banghart 2956:                     $file_counter++;
                   2957:                 }
1.367     albertel 2958: 		my $subject = "File Handed Back by Instructor ";
                   2959: 		my $message = "A file has been returned that was originally submitted in reponse to: <br />";
                   2960: 		$message .= "<strong>".&Apache::lonnet::gettitle($symb)."</strong><br />";
                   2961: 		$message .= ' The returned file(s) are named: '. $file_msg;
                   2962: 		$message .= " and can be found in your portfolio space.";
1.418     albertel 2963: 		my ($feedurl,$showsymb) = 
                   2964: 		    &get_feedurl_and_symb($symb,$domain,$stuname);
1.386     raeburn  2965:                 my $restitle = &Apache::lonnet::gettitle($symb);
                   2966: 		my $msgstatus = 
                   2967:                    &Apache::lonmsg::user_normal_msg($stuname,$domain,$subject.
                   2968: 			 ' (File Returned) ['.$restitle.']',$message,undef,
1.418     albertel 2969:                          $feedurl,undef,undef,undef,$showsymb,$restitle);
1.337     banghart 2970:             }
                   2971:         }
1.338     banghart 2972:     return;
1.337     banghart 2973: }
                   2974: 
1.418     albertel 2975: sub get_feedurl_and_symb {
                   2976:     my ($symb,$uname,$udom) = @_;
                   2977:     my (undef,undef,$url) = &Apache::lonnet::decode_symb($symb);
                   2978:     $url = &Apache::lonnet::clutter($url);
                   2979:     my $encrypturl=&Apache::lonnet::EXT('resource.0.encrypturl',
                   2980: 					$symb,$udom,$uname);
                   2981:     if ($encrypturl =~ /^yes$/i) {
                   2982: 	&Apache::lonenc::encrypted(\$url,1);
                   2983: 	&Apache::lonenc::encrypted(\$symb,1);
                   2984:     }
                   2985:     return ($url,$symb);
                   2986: }
                   2987: 
1.313     banghart 2988: sub get_submitted_files {
                   2989:     my ($udom,$uname,$partid,$respid,$record) = @_;
                   2990:     my @files;
                   2991:     if ($$record{"resource.$partid.$respid.portfiles"}) {
                   2992:         my $file_url = '/uploaded/'.$udom.'/'.$uname.'/portfolio';
                   2993:         foreach my $file (split(',',$$record{"resource.$partid.$respid.portfiles"})) {
                   2994:     	    push(@files,$file_url.$file);
                   2995:         }
                   2996:     }
                   2997:     if ($$record{"resource.$partid.$respid.uploadedurl"}) {
                   2998:         push(@files,$$record{"resource.$partid.$respid.uploadedurl"});
                   2999:     }
                   3000:     return (\@files);
                   3001: }
1.322     albertel 3002: 
1.269     raeburn  3003: # ----------- Provides number of tries since last reset.
                   3004: sub get_num_tries {
                   3005:     my ($record,$last_reset,$part) = @_;
                   3006:     my $timestamp = '';
                   3007:     my $num_tries = 0;
                   3008:     if ($$record{'version'}) {
                   3009:         for (my $version=$$record{'version'};$version>=1;$version--) {
                   3010:             if (exists($$record{$version.':resource.'.$part.'.solved'})) {
                   3011:                 $timestamp = $$record{$version.':timestamp'};
                   3012:                 if ($timestamp > $last_reset) {
                   3013:                     $num_tries ++;
                   3014:                 } else {
                   3015:                     last;
                   3016:                 }
                   3017:             }
                   3018:         }
                   3019:     }
                   3020:     return $num_tries;
                   3021: }
                   3022: 
                   3023: # ----------- Determine decrements required in aggregate totals 
                   3024: sub decrement_aggs {
                   3025:     my ($symb,$part,$aggregate,$aggtries,$totaltries,$solvedstatus) = @_;
                   3026:     my %decrement = (
                   3027:                         attempts => 0,
                   3028:                         users => 0,
                   3029:                         correct => 0
                   3030:                     );
                   3031:     $decrement{'attempts'} = $aggtries;
                   3032:     if ($solvedstatus =~ /^correct/) {
                   3033:         $decrement{'correct'} = 1;
                   3034:     }
                   3035:     if ($aggtries == $totaltries) {
                   3036:         $decrement{'users'} = 1;
                   3037:     }
1.524     raeburn  3038:     foreach my $type (keys(%decrement)) {
1.269     raeburn  3039:         $$aggregate{$symb."\0".$part."\0".$type} = -$decrement{$type};
                   3040:     }
                   3041:     return;
                   3042: }
                   3043: 
                   3044: # ----------- Determine timestamps for last reset of aggregate totals for parts  
                   3045: sub get_last_resets {
1.270     albertel 3046:     my ($symb,$courseid,$partids) =@_;
                   3047:     my %last_resets;
1.269     raeburn  3048:     my $cdom = $env{'course.'.$courseid.'.domain'};
                   3049:     my $cname = $env{'course.'.$courseid.'.num'};
1.271     albertel 3050:     my @keys;
                   3051:     foreach my $part (@{$partids}) {
                   3052: 	push(@keys,"$symb\0$part\0resettime");
                   3053:     }
                   3054:     my %results=&Apache::lonnet::get('nohist_resourcetracker',\@keys,
                   3055: 				     $cdom,$cname);
                   3056:     foreach my $part (@{$partids}) {
                   3057: 	$last_resets{$part}=$results{"$symb\0$part\0resettime"};
1.269     raeburn  3058:     }
1.270     albertel 3059:     return %last_resets;
1.269     raeburn  3060: }
                   3061: 
1.251     banghart 3062: # ----------- Handles creating versions for portfolio files as answers
                   3063: sub version_portfiles {
1.343     banghart 3064:     my ($record, $parts_graded, $courseid, $symb, $domain, $stu_name, $v_flag) = @_;
1.263     banghart 3065:     my $version_parts = join('|',@$v_flag);
1.343     banghart 3066:     my @returned_keys;
1.255     banghart 3067:     my $parts = join('|', @$parts_graded);
1.517     raeburn  3068:     my $portfolio_root = '/userfiles/portfolio';
1.277     albertel 3069:     foreach my $key (keys(%$record)) {
1.259     banghart 3070:         my $new_portfiles;
1.263     banghart 3071:         if ($key =~ /^resource\.($version_parts)\./ && $key =~ /\.portfiles$/ ) {
1.342     banghart 3072:             my @versioned_portfiles;
1.367     albertel 3073:             my @portfiles = split(/\s*,\s*/,$$record{$key});
1.252     banghart 3074:             foreach my $file (@portfiles) {
1.306     banghart 3075:                 &Apache::lonnet::unmark_as_readonly($domain,$stu_name,[$symb,$env{'request.course.id'}],$file);
1.304     albertel 3076:                 my ($directory,$answer_file) =($file =~ /^(.*?)([^\/]*)$/);
                   3077: 		my ($answer_name,$answer_ver,$answer_ext) =
                   3078: 		    &file_name_version_ext($answer_file);
1.517     raeburn  3079:                 my $getpropath = 1;    
                   3080:                 my @dir_list = &Apache::lonnet::dirlist($portfolio_root.$directory,$domain,$stu_name,$getpropath);
1.342     banghart 3081:                 my $version = &get_next_version($answer_name, $answer_ext, \@dir_list);
1.306     banghart 3082:                 my $new_answer = &version_selected_portfile($domain, $stu_name, $directory, $answer_file, $version);
                   3083:                 if ($new_answer ne 'problem getting file') {
1.342     banghart 3084:                     push(@versioned_portfiles, $directory.$new_answer);
1.306     banghart 3085:                     &Apache::lonnet::mark_as_readonly($domain,$stu_name,
1.367     albertel 3086:                         [$directory.$new_answer],
1.306     banghart 3087:                         [$symb,$env{'request.course.id'},'graded']);
1.259     banghart 3088:                 }
1.252     banghart 3089:             }
1.343     banghart 3090:             $$record{$key} = join(',',@versioned_portfiles);
                   3091:             push(@returned_keys,$key);
1.251     banghart 3092:         }
                   3093:     } 
1.343     banghart 3094:     return (@returned_keys);   
1.305     banghart 3095: }
                   3096: 
1.307     banghart 3097: sub get_next_version {
1.341     banghart 3098:     my ($answer_name, $answer_ext, $dir_list) = @_;
1.307     banghart 3099:     my $version;
                   3100:     foreach my $row (@$dir_list) {
                   3101:         my ($file) = split(/\&/,$row,2);
                   3102:         my ($file_name,$file_version,$file_ext) =
                   3103: 	    &file_name_version_ext($file);
                   3104:         if (($file_name eq $answer_name) && 
                   3105: 	    ($file_ext eq $answer_ext)) {
                   3106:                 # gets here if filename and extension match, regardless of version
                   3107:                 if ($file_version ne '') {
                   3108:                 # a versioned file is found  so save it for later
                   3109:                 if ($file_version > $version) {
                   3110: 		    $version = $file_version;
                   3111: 	        }
                   3112:             }
                   3113:         }
                   3114:     } 
                   3115:     $version ++;
                   3116:     return($version);
                   3117: }
                   3118: 
1.305     banghart 3119: sub version_selected_portfile {
1.306     banghart 3120:     my ($domain,$stu_name,$directory,$file_name,$version) = @_;
                   3121:     my ($answer_name,$answer_ver,$answer_ext) =
                   3122:         &file_name_version_ext($file_name);
                   3123:     my $new_answer;
                   3124:     $env{'form.copy'} = &Apache::lonnet::getfile("/uploaded/$domain/$stu_name/portfolio$directory$file_name");
                   3125:     if($env{'form.copy'} eq '-1') {
                   3126:         $new_answer = 'problem getting file';
                   3127:     } else {
                   3128:         $new_answer = $answer_name.'.'.$version.'.'.$answer_ext;
                   3129:         my $copy_result = &Apache::lonnet::finishuserfileupload(
                   3130:                             $stu_name,$domain,'copy',
                   3131: 		        '/portfolio'.$directory.$new_answer);
                   3132:     }    
                   3133:     return ($new_answer);
1.251     banghart 3134: }
                   3135: 
1.304     albertel 3136: sub file_name_version_ext {
                   3137:     my ($file)=@_;
                   3138:     my @file_parts = split(/\./, $file);
                   3139:     my ($name,$version,$ext);
                   3140:     if (@file_parts > 1) {
                   3141: 	$ext=pop(@file_parts);
                   3142: 	if (@file_parts > 1 && $file_parts[-1] =~ /^\d+$/) {
                   3143: 	    $version=pop(@file_parts);
                   3144: 	}
                   3145: 	$name=join('.',@file_parts);
                   3146:     } else {
                   3147: 	$name=join('.',@file_parts);
                   3148:     }
                   3149:     return($name,$version,$ext);
                   3150: }
                   3151: 
1.44      ng       3152: #--------------------------------------------------------------------------------------
                   3153: #
                   3154: #-------------------------- Next few routines handles grading by section or whole class
                   3155: #
                   3156: #--- Javascript to handle grading by section or whole class
1.42      ng       3157: sub viewgrades_js {
                   3158:     my ($request) = shift;
                   3159: 
1.539     riegler  3160:     my $alertmsg = &mt('A number equal or greater than 0 is expected. Entered value = ');
1.597   ! wenzelju 3161:     $request->print(&Apache::lonhtmlcommon::scripttag(<<VIEWJAVASCRIPT));
1.45      ng       3162:    function writePoint(partid,weight,point) {
1.125     ng       3163: 	var radioButton = document.classgrade["RADVAL_"+partid];
                   3164: 	var textbox = document.classgrade["TEXTVAL_"+partid];
1.42      ng       3165: 	if (point == "textval") {
1.125     ng       3166: 	    point = document.classgrade["TEXTVAL_"+partid].value;
1.109     matthew  3167: 	    if (isNaN(point) || parseFloat(point) < 0) {
1.539     riegler  3168: 		alert("$alertmsg"+parseFloat(point));
1.42      ng       3169: 		var resetbox = false;
                   3170: 		for (var i=0; i<radioButton.length; i++) {
                   3171: 		    if (radioButton[i].checked) {
                   3172: 			textbox.value = i;
                   3173: 			resetbox = true;
                   3174: 		    }
                   3175: 		}
                   3176: 		if (!resetbox) {
                   3177: 		    textbox.value = "";
                   3178: 		}
                   3179: 		return;
                   3180: 	    }
1.109     matthew  3181: 	    if (parseFloat(point) > parseFloat(weight)) {
                   3182: 		var resp = confirm("You entered a value ("+parseFloat(point)+
1.44      ng       3183: 				   ") greater than the weight for the part. Accept?");
                   3184: 		if (resp == false) {
                   3185: 		    textbox.value = "";
                   3186: 		    return;
                   3187: 		}
                   3188: 	    }
1.42      ng       3189: 	    for (var i=0; i<radioButton.length; i++) {
                   3190: 		radioButton[i].checked=false;
1.109     matthew  3191: 		if (parseFloat(point) == i) {
1.42      ng       3192: 		    radioButton[i].checked=true;
                   3193: 		}
                   3194: 	    }
1.41      ng       3195: 
1.42      ng       3196: 	} else {
1.125     ng       3197: 	    textbox.value = parseFloat(point);
1.42      ng       3198: 	}
1.41      ng       3199: 	for (i=0;i<document.classgrade.total.value;i++) {
1.125     ng       3200: 	    var user = document.classgrade["ctr"+i].value;
1.289     albertel 3201: 	    user = user.replace(new RegExp(':', 'g'),"_");
1.125     ng       3202: 	    var scorename = document.classgrade["GD_"+user+"_"+partid+"_awarded"];
                   3203: 	    var saveval   = document.classgrade["GD_"+user+"_"+partid+"_solved_s"].value;
                   3204: 	    var selname   = document.classgrade["GD_"+user+"_"+partid+"_solved"];
1.42      ng       3205: 	    if (saveval != "correct") {
                   3206: 		scorename.value = point;
1.43      ng       3207: 		if (selname[0].selected != true) {
                   3208: 		    selname[0].selected = true;
                   3209: 		}
1.42      ng       3210: 	    }
                   3211: 	}
1.125     ng       3212: 	document.classgrade["SELVAL_"+partid][0].selected = true;
1.42      ng       3213:     }
                   3214: 
                   3215:     function writeRadText(partid,weight) {
1.125     ng       3216: 	var selval   = document.classgrade["SELVAL_"+partid];
                   3217: 	var radioButton = document.classgrade["RADVAL_"+partid];
1.265     www      3218:         var override = document.classgrade["FORCE_"+partid].checked;
1.125     ng       3219: 	var textbox = document.classgrade["TEXTVAL_"+partid];
                   3220: 	if (selval[1].selected || selval[2].selected) {
1.42      ng       3221: 	    for (var i=0; i<radioButton.length; i++) {
                   3222: 		radioButton[i].checked=false;
                   3223: 
                   3224: 	    }
                   3225: 	    textbox.value = "";
                   3226: 
                   3227: 	    for (i=0;i<document.classgrade.total.value;i++) {
1.125     ng       3228: 		var user = document.classgrade["ctr"+i].value;
1.289     albertel 3229: 		user = user.replace(new RegExp(':', 'g'),"_");
1.125     ng       3230: 		var scorename = document.classgrade["GD_"+user+"_"+partid+"_awarded"];
                   3231: 		var saveval   = document.classgrade["GD_"+user+"_"+partid+"_solved_s"].value;
                   3232: 		var selname   = document.classgrade["GD_"+user+"_"+partid+"_solved"];
1.265     www      3233: 		if ((saveval != "correct") || override) {
1.42      ng       3234: 		    scorename.value = "";
1.125     ng       3235: 		    if (selval[1].selected) {
                   3236: 			selname[1].selected = true;
                   3237: 		    } else {
                   3238: 			selname[2].selected = true;
                   3239: 			if (Number(document.classgrade["GD_"+user+"_"+partid+"_tries"].value)) 
                   3240: 			{document.classgrade["GD_"+user+"_"+partid+"_tries"].value = '0';}
                   3241: 		    }
1.42      ng       3242: 		}
                   3243: 	    }
1.43      ng       3244: 	} else {
                   3245: 	    for (i=0;i<document.classgrade.total.value;i++) {
1.125     ng       3246: 		var user = document.classgrade["ctr"+i].value;
1.289     albertel 3247: 		user = user.replace(new RegExp(':', 'g'),"_");
1.125     ng       3248: 		var scorename = document.classgrade["GD_"+user+"_"+partid+"_awarded"];
                   3249: 		var saveval   = document.classgrade["GD_"+user+"_"+partid+"_solved_s"].value;
                   3250: 		var selname   = document.classgrade["GD_"+user+"_"+partid+"_solved"];
1.265     www      3251: 		if ((saveval != "correct") || override) {
1.125     ng       3252: 		    scorename.value = document.classgrade["GD_"+user+"_"+partid+"_awarded_s"].value;
1.43      ng       3253: 		    selname[0].selected = true;
                   3254: 		}
                   3255: 	    }
                   3256: 	}	    
1.42      ng       3257:     }
                   3258: 
                   3259:     function changeSelect(partid,user) {
1.125     ng       3260: 	var selval = document.classgrade["GD_"+user+'_'+partid+"_solved"];
                   3261: 	var textbox = document.classgrade["GD_"+user+'_'+partid+"_awarded"];
1.44      ng       3262: 	var point  = textbox.value;
1.125     ng       3263: 	var weight = document.classgrade["weight_"+partid].value;
1.44      ng       3264: 
1.109     matthew  3265: 	if (isNaN(point) || parseFloat(point) < 0) {
1.539     riegler  3266: 	    alert("$alertmsg"+parseFloat(point));
1.44      ng       3267: 	    textbox.value = "";
                   3268: 	    return;
                   3269: 	}
1.109     matthew  3270: 	if (parseFloat(point) > parseFloat(weight)) {
                   3271: 	    var resp = confirm("You entered a value ("+parseFloat(point)+
1.44      ng       3272: 			       ") greater than the weight of the part. Accept?");
                   3273: 	    if (resp == false) {
                   3274: 		textbox.value = "";
                   3275: 		return;
                   3276: 	    }
                   3277: 	}
1.42      ng       3278: 	selval[0].selected = true;
                   3279:     }
                   3280: 
                   3281:     function changeOneScore(partid,user) {
1.125     ng       3282: 	var selval = document.classgrade["GD_"+user+'_'+partid+"_solved"];
                   3283: 	if (selval[1].selected || selval[2].selected) {
                   3284: 	    document.classgrade["GD_"+user+'_'+partid+"_awarded"].value = "";
                   3285: 	    if (selval[2].selected) {
                   3286: 		document.classgrade["GD_"+user+'_'+partid+"_tries"].value = "0";
                   3287: 	    }
1.269     raeburn  3288:         }
1.42      ng       3289:     }
                   3290: 
                   3291:     function resetEntry(numpart) {
                   3292: 	for (ctpart=0;ctpart<numpart;ctpart++) {
1.125     ng       3293: 	    var partid = document.classgrade["partid_"+ctpart].value;
                   3294: 	    var radioButton = document.classgrade["RADVAL_"+partid];
                   3295: 	    var textbox = document.classgrade["TEXTVAL_"+partid];
                   3296: 	    var selval  = document.classgrade["SELVAL_"+partid];
1.42      ng       3297: 	    for (var i=0; i<radioButton.length; i++) {
                   3298: 		radioButton[i].checked=false;
                   3299: 
                   3300: 	    }
                   3301: 	    textbox.value = "";
                   3302: 	    selval[0].selected = true;
                   3303: 
                   3304: 	    for (i=0;i<document.classgrade.total.value;i++) {
1.125     ng       3305: 		var user = document.classgrade["ctr"+i].value;
1.289     albertel 3306: 		user = user.replace(new RegExp(':', 'g'),"_");
1.125     ng       3307: 		var resetscore = document.classgrade["GD_"+user+"_"+partid+"_awarded"];
                   3308: 		resetscore.value = document.classgrade["GD_"+user+"_"+partid+"_awarded_s"].value;
                   3309: 		var resettries = document.classgrade["GD_"+user+"_"+partid+"_tries"];
                   3310: 		resettries.value = document.classgrade["GD_"+user+"_"+partid+"_tries_s"].value;
                   3311: 		var saveselval   = document.classgrade["GD_"+user+"_"+partid+"_solved_s"].value;
                   3312: 		var selname   = document.classgrade["GD_"+user+"_"+partid+"_solved"];
1.42      ng       3313: 		if (saveselval == "excused") {
1.43      ng       3314: 		    if (selname[1].selected == false) { selname[1].selected = true;}
1.42      ng       3315: 		} else {
1.43      ng       3316: 		    if (selname[0].selected == false) {selname[0].selected = true};
1.42      ng       3317: 		}
                   3318: 	    }
1.41      ng       3319: 	}
1.42      ng       3320:     }
                   3321: 
1.41      ng       3322: VIEWJAVASCRIPT
1.42      ng       3323: }
                   3324: 
1.44      ng       3325: #--- show scores for a section or whole class w/ option to change/update a score
1.42      ng       3326: sub viewgrades {
                   3327:     my ($request) = shift;
                   3328:     &viewgrades_js($request);
1.41      ng       3329: 
1.324     albertel 3330:     my ($symb) = &get_symb($request);
1.168     albertel 3331:     #need to make sure we have the correct data for later EXT calls, 
                   3332:     #thus invalidate the cache
                   3333:     &Apache::lonnet::devalidatecourseresdata(
1.257     albertel 3334:                  $env{'course.'.$env{'request.course.id'}.'.num'},
                   3335:                  $env{'course.'.$env{'request.course.id'}.'.domain'});
1.168     albertel 3336:     &Apache::lonnet::clear_EXT_cache_status();
                   3337: 
1.398     albertel 3338:     my $result='<h3><span class="LC_info">'.&mt('Manual Grading').'</span></h3>';
1.485     albertel 3339:     $result.='<h4>'.&mt('<b>Current Resource: </b>[_1]',$env{'form.probTitle'}).'</h4>'."\n";
1.41      ng       3340: 
                   3341:     #view individual student submission form - called using Javascript viewOneStudent
1.324     albertel 3342:     $result.=&jscriptNform($symb);
1.41      ng       3343: 
1.44      ng       3344:     #beginning of class grading form
1.442     banghart 3345:     my $stu_status = join(':',&Apache::loncommon::get_env_multiple('form.Status'));
1.41      ng       3346:     $result.= '<form action="/adm/grades" method="post" name="classgrade">'."\n".
1.418     albertel 3347: 	'<input type="hidden" name="symb"    value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
1.38      ng       3348: 	'<input type="hidden" name="command" value="editgrades" />'."\n".
1.432     banghart 3349: 	&build_section_inputs().
1.257     albertel 3350: 	'<input type="hidden" name="saveState" value="'.$env{'form.saveState'}.'" />'."\n".
1.442     banghart 3351: 	'<input type="hidden" name="Status" value="'.$env{'stu_status'}.'" />'."\n".
1.257     albertel 3352: 	'<input type="hidden" name="probTitle" value="'.$env{'form.probTitle'}.'" />'."\n";
1.72      ng       3353: 
1.560     raeburn  3354:     my ($common_header,$specific_header);
1.257     albertel 3355:     if ($env{'form.section'} eq 'all') {
1.560     raeburn  3356: 	$common_header = &mt('Assign Common Grade to Class');
                   3357:         $specific_header = &mt('Assign Grade to Specific Students in Class');
1.257     albertel 3358:     } elsif ($env{'form.section'} eq 'none') {
1.560     raeburn  3359:         $common_header = &mt('Assign Common Grade to Students in no Section');
                   3360: 	$specific_header = &mt('Assign Grade to Specific Students in no Section');
1.52      albertel 3361:     } else {
1.560     raeburn  3362:         my $section_display = join (", ",&Apache::loncommon::get_env_multiple('form.section'));
                   3363:         $common_header = &mt('Assign Common Grade to Students in Section(s) [_1]',$section_display);
                   3364: 	$specific_header = &mt('Assign Grade to Specific Students in Section(s) [_1]',$section_display);
1.52      albertel 3365:     }
1.560     raeburn  3366:     $result.= '<h3>'.$common_header.'</h3>'.&Apache::loncommon::start_data_table();
1.44      ng       3367:     #radio buttons/text box for assigning points for a section or class.
                   3368:     #handles different parts of a problem
1.582     raeburn  3369:     my $res_error;
                   3370:     my ($partlist,$handgrade,$responseType) = &response_type($symb,\$res_error);
                   3371:     if ($res_error) {
                   3372:         return &navmap_errormsg();
                   3373:     }
1.42      ng       3374:     my %weight = ();
                   3375:     my $ctsparts = 0;
1.45      ng       3376:     my %seen = ();
1.375     albertel 3377:     my @part_response_id = &flatten_responseType($responseType);
                   3378:     foreach my $part_response_id (@part_response_id) {
                   3379:     	my ($partid,$respid) = @{ $part_response_id };
                   3380: 	my $part_resp = join('_',@{ $part_response_id });
1.45      ng       3381: 	next if $seen{$partid};
                   3382: 	$seen{$partid}++;
1.375     albertel 3383: 	my $handgrade=$$handgrade{$part_resp};
1.42      ng       3384: 	my $wgt = &Apache::lonnet::EXT('resource.'.$partid.'.weight',$symb);
                   3385: 	$weight{$partid} = $wgt eq '' ? '1' : $wgt;
                   3386: 
1.324     albertel 3387: 	my $display_part=&get_display_part($partid,$symb);
1.485     albertel 3388: 	my $radio.='<table border="0"><tr>';  
1.41      ng       3389: 	my $ctr = 0;
1.42      ng       3390: 	while ($ctr<=$weight{$partid}) { # display radio buttons in a nice table 10 across
1.485     albertel 3391: 	    $radio.= '<td><label><input type="radio" name="RADVAL_'.$partid.'" '.
1.54      albertel 3392: 		'onclick="javascript:writePoint(\''.$partid.'\','.$weight{$partid}.
1.288     albertel 3393: 		','.$ctr.')" />'.$ctr."</label></td>\n";
1.41      ng       3394: 	    $result.=(($ctr+1)%10 == 0 ? '</tr><tr>' : '');
                   3395: 	    $ctr++;
                   3396: 	}
1.485     albertel 3397: 	$radio.='</tr></table>';
                   3398: 	my $line = '<input type="text" name="TEXTVAL_'.
1.589     bisitz   3399: 	    $partid.'" size="4" '.'onchange="javascript:writePoint(\''.
1.54      albertel 3400: 		$partid.'\','.$weight{$partid}.',\'textval\')" /> /'.
1.539     riegler  3401: 	    $weight{$partid}.' '.&mt('(problem weight)').'</td>'."\n";
                   3402: 	$line.= '<td><b>'.&mt('Grade Status').':</b><select name="SELVAL_'.$partid.'"'.
1.589     bisitz   3403: 	    'onchange="javascript:writeRadText(\''.$partid.'\','.
1.59      albertel 3404: 		$weight{$partid}.')"> '.
1.401     albertel 3405: 	    '<option selected="selected"> </option>'.
1.485     albertel 3406: 	    '<option value="excused">'.&mt('excused').'</option>'.
                   3407: 	    '<option value="reset status">'.&mt('reset status').'</option>'.
                   3408: 	    '</select></td>'.
                   3409:             '<td><label><input type="checkbox" name="FORCE_'.$partid.'" />'.&mt('Override "Correct"').'</label>';
                   3410: 	$line.='<input type="hidden" name="partid_'.
                   3411: 	    $ctsparts.'" value="'.$partid.'" />'."\n";
                   3412: 	$line.='<input type="hidden" name="weight_'.
                   3413: 	    $partid.'" value="'.$weight{$partid}.'" />'."\n";
                   3414: 
                   3415: 	$result.=
                   3416: 	    &Apache::loncommon::start_data_table_row()."\n".
1.577     bisitz   3417: 	    '<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 3418: 	    &Apache::loncommon::end_data_table_row()."\n";
1.42      ng       3419: 	$ctsparts++;
1.41      ng       3420:     }
1.474     albertel 3421:     $result.=&Apache::loncommon::end_data_table()."\n".
1.52      albertel 3422: 	'<input type="hidden" name="totalparts" value="'.$ctsparts.'" />';
1.485     albertel 3423:     $result.='<input type="button" value="'.&mt('Revert to Default').'" '.
1.589     bisitz   3424: 	'onclick="javascript:resetEntry('.$ctsparts.');" />';
1.41      ng       3425: 
1.44      ng       3426:     #table listing all the students in a section/class
                   3427:     #header of table
1.560     raeburn  3428:     $result.= '<h3>'.$specific_header.'</h3>'.
                   3429:               &Apache::loncommon::start_data_table().
                   3430: 	      &Apache::loncommon::start_data_table_header_row().
                   3431: 	      '<th>'.&mt('No.').'</th>'.
                   3432: 	      '<th>'.&nameUserString('header')."</th>\n";
1.582     raeburn  3433:     my $partserror;
                   3434:     my (@parts) = sort(&getpartlist($symb,\$partserror));
                   3435:     if ($partserror) {
                   3436:         return &navmap_errormsg();
                   3437:     }
1.324     albertel 3438:     my (undef,undef,$url)=&Apache::lonnet::decode_symb($symb);
1.269     raeburn  3439:     my @partids = ();
1.41      ng       3440:     foreach my $part (@parts) {
                   3441: 	my $display=&Apache::lonnet::metadata($url,$part.'.display');
1.539     riegler  3442:         my $narrowtext = &mt('Tries');
                   3443: 	$display =~ s|^Number of Attempts|$narrowtext <br />|; # makes the column narrower
1.41      ng       3444: 	if  (!$display) { $display = &Apache::lonnet::metadata($url,$part.'.name'); }
1.207     albertel 3445: 	my ($partid) = &split_part_type($part);
1.524     raeburn  3446:         push(@partids,$partid);
1.324     albertel 3447: 	my $display_part=&get_display_part($partid,$symb);
1.41      ng       3448: 	if ($display =~ /^Partial Credit Factor/) {
1.485     albertel 3449: 	    $result.='<th>'.
                   3450: 		&mt('Score Part: [_1]<br /> (weight = [_2])',
                   3451: 		    $display_part,$weight{$partid}).'</th>'."\n";
1.41      ng       3452: 	    next;
1.485     albertel 3453: 	    
1.207     albertel 3454: 	} else {
1.485     albertel 3455: 	    if ($display =~ /Problem Status/) {
                   3456: 		my $grade_status_mt = &mt('Grade Status');
                   3457: 		$display =~ s{Problem Status}{$grade_status_mt<br />};
                   3458: 	    }
                   3459: 	    my $part_mt = &mt('Part:');
                   3460: 	    $display =~s{\[Part: \Q$partid\E\]}{$part_mt $display_part};
1.41      ng       3461: 	}
1.485     albertel 3462: 
1.474     albertel 3463: 	$result.='<th>'.$display.'</th>'."\n";
1.41      ng       3464:     }
1.474     albertel 3465:     $result.=&Apache::loncommon::end_data_table_header_row();
1.44      ng       3466: 
1.270     albertel 3467:     my %last_resets = 
                   3468: 	&get_last_resets($symb,$env{'request.course.id'},\@partids);
1.269     raeburn  3469: 
1.41      ng       3470:     #get info for each student
1.44      ng       3471:     #list all the students - with points and grade status
1.257     albertel 3472:     my (undef,undef,$fullname) = &getclasslist($env{'form.section'},'1');
1.41      ng       3473:     my $ctr = 0;
1.294     albertel 3474:     foreach (sort 
                   3475: 	     {
                   3476: 		 if (lc($$fullname{$a}) ne lc($$fullname{$b})) {
                   3477: 		     return (lc($$fullname{$a}) cmp lc($$fullname{$b}));
                   3478: 		 }
                   3479: 		 return $a cmp $b;
                   3480: 	     } (keys(%$fullname))) {
1.126     ng       3481: 	$ctr++;
1.324     albertel 3482: 	$result.=&viewstudentgrade($symb,$env{'request.course.id'},
1.269     raeburn  3483: 				   $_,$$fullname{$_},\@parts,\%weight,$ctr,\%last_resets);
1.41      ng       3484:     }
1.474     albertel 3485:     $result.=&Apache::loncommon::end_data_table();
1.41      ng       3486:     $result.='<input type="hidden" name="total" value="'.$ctr.'" />'."\n";
1.485     albertel 3487:     $result.='<input type="button" value="'.&mt('Save').'" '.
1.589     bisitz   3488: 	'onclick="javascript:submit();" target="_self" /></form>'."\n";
1.96      albertel 3489:     if (scalar(%$fullname) eq 0) {
                   3490: 	my $colspan=3+scalar(@parts);
1.433     banghart 3491: 	my $section_display = join (", ",&Apache::loncommon::get_env_multiple('form.section'));
1.442     banghart 3492:         my $stu_status = join(' or ',&Apache::loncommon::get_env_multiple('form.Status'));
1.433     banghart 3493: 	$result='<span class="LC_warning">'.
1.485     albertel 3494: 	    &mt('There are no students in section(s) [_1] with enrollment status [_2] to modify or grade.',
1.442     banghart 3495: 	        $section_display, $stu_status).
1.433     banghart 3496: 	    '</span>';
1.96      albertel 3497:     }
1.324     albertel 3498:     $result.=&show_grading_menu_form($symb);
1.41      ng       3499:     return $result;
                   3500: }
                   3501: 
1.44      ng       3502: #--- call by previous routine to display each student
1.41      ng       3503: sub viewstudentgrade {
1.324     albertel 3504:     my ($symb,$courseid,$student,$fullname,$parts,$weight,$ctr,$last_resets) = @_;
1.44      ng       3505:     my ($uname,$udom) = split(/:/,$student);
                   3506:     my %record=&Apache::lonnet::restore($symb,$courseid,$udom,$uname);
1.269     raeburn  3507:     my %aggregates = (); 
1.474     albertel 3508:     my $result=&Apache::loncommon::start_data_table_row().'<td align="right">'.
1.233     albertel 3509: 	'<input type="hidden" name="ctr'.($ctr-1).'" value="'.$student.'" />'.
                   3510: 	"\n".$ctr.'&nbsp;</td><td>&nbsp;'.
1.44      ng       3511: 	'<a href="javascript:viewOneStudent(\''.$uname.'\',\''.$udom.
1.417     albertel 3512: 	'\');" target="_self">'.$fullname.'</a> '.
1.398     albertel 3513: 	'<span class="LC_internal_info">('.$uname.($env{'user.domain'} eq $udom ? '' : ':'.$udom).')</span></td>'."\n";
1.281     albertel 3514:     $student=~s/:/_/; # colon doen't work in javascript for names
1.63      albertel 3515:     foreach my $apart (@$parts) {
                   3516: 	my ($part,$type) = &split_part_type($apart);
1.41      ng       3517: 	my $score=$record{"resource.$part.$type"};
1.276     albertel 3518:         $result.='<td align="center">';
1.269     raeburn  3519:         my ($aggtries,$totaltries);
                   3520:         unless (exists($aggregates{$part})) {
1.270     albertel 3521: 	    $totaltries = $record{'resource.'.$part.'.tries'};
                   3522: 
                   3523: 	    $aggtries = $totaltries;
1.269     raeburn  3524:             if ($$last_resets{$part}) {  
1.270     albertel 3525:                 $aggtries = &get_num_tries(\%record,$$last_resets{$part},
                   3526: 					   $part);
                   3527:             }
1.269     raeburn  3528:             $result.='<input type="hidden" name="'.
                   3529:                 'GD_'.$student.'_'.$part.'_aggtries" value="'.$aggtries.'" />'."\n";
                   3530:             $result.='<input type="hidden" name="'.
                   3531:                 'GD_'.$student.'_'.$part.'_totaltries" value="'.$totaltries.'" />'."\n";
                   3532:             $aggregates{$part} = 1;
                   3533:         }
1.41      ng       3534: 	if ($type eq 'awarded') {
1.320     albertel 3535: 	    my $pts = $score eq '' ? '' : &compute_points($score,$$weight{$part});
1.42      ng       3536: 	    $result.='<input type="hidden" name="'.
1.89      albertel 3537: 		'GD_'.$student.'_'.$part.'_awarded_s" value="'.$pts.'" />'."\n";
1.233     albertel 3538: 	    $result.='<input type="text" name="'.
1.89      albertel 3539: 		'GD_'.$student.'_'.$part.'_awarded" '.
1.589     bisitz   3540:                 'onchange="javascript:changeSelect(\''.$part.'\',\''.$student.
1.44      ng       3541: 		'\')" value="'.$pts.'" size="4" /></td>'."\n";
1.41      ng       3542: 	} elsif ($type eq 'solved') {
                   3543: 	    my ($status,$foo)=split(/_/,$score,2);
                   3544: 	    $status = 'nothing' if ($status eq '');
1.89      albertel 3545: 	    $result.='<input type="hidden" name="'.'GD_'.$student.'_'.
1.54      albertel 3546: 		$part.'_solved_s" value="'.$status.'" />'."\n";
1.233     albertel 3547: 	    $result.='&nbsp;<select name="'.
1.89      albertel 3548: 		'GD_'.$student.'_'.$part.'_solved" '.
1.589     bisitz   3549:                 'onchange="javascript:changeOneScore(\''.$part.'\',\''.$student.'\')" >'."\n";
1.485     albertel 3550: 	    $result.= (($status eq 'excused') ? '<option> </option><option selected="selected" value="excused">'.&mt('excused').'</option>' 
                   3551: 		: '<option selected="selected"> </option><option value="excused">'.&mt('excused').'</option>')."\n";
                   3552: 	    $result.='<option value="reset status">'.&mt('reset status').'</option>';
1.126     ng       3553: 	    $result.="</select>&nbsp;</td>\n";
1.122     ng       3554: 	} else {
                   3555: 	    $result.='<input type="hidden" name="'.
                   3556: 		'GD_'.$student.'_'.$part.'_'.$type.'_s" value="'.$score.'" />'.
                   3557: 		    "\n";
1.233     albertel 3558: 	    $result.='<input type="text" name="'.
1.122     ng       3559: 		'GD_'.$student.'_'.$part.'_'.$type.'" '.
                   3560: 		'value="'.$score.'" size="4" /></td>'."\n";
1.41      ng       3561: 	}
                   3562:     }
1.474     albertel 3563:     $result.=&Apache::loncommon::end_data_table_row();
1.41      ng       3564:     return $result;
1.38      ng       3565: }
                   3566: 
1.44      ng       3567: #--- change scores for all the students in a section/class
                   3568: #    record does not get update if unchanged
1.38      ng       3569: sub editgrades {
1.41      ng       3570:     my ($request) = @_;
                   3571: 
1.324     albertel 3572:     my $symb=&get_symb($request);
1.433     banghart 3573:     my $section_display = join (", ",&Apache::loncommon::get_env_multiple('form.section'));
1.477     albertel 3574:     my $title='<h2>'.&mt('Current Grade Status').'</h2>';
                   3575:     $title.='<h4>'.&mt('<b>Current Resource: </b>[_1]',$env{'form.probTitle'}).'</h4>'."\n";
1.433     banghart 3576:     $title.='<h4>'.&mt('<b>Section: </b>[_1]',$section_display).'</h4>'."\n";
1.126     ng       3577: 
1.477     albertel 3578:     my $result= &Apache::loncommon::start_data_table().
                   3579: 	&Apache::loncommon::start_data_table_header_row().
                   3580: 	'<th rowspan="2" valign="middle">'.&mt('No.').'</th>'.
                   3581: 	'<th rowspan="2" valign="middle">'.&nameUserString('header')."</th>\n";
1.43      ng       3582:     my %scoreptr = (
                   3583: 		    'correct'  =>'correct_by_override',
                   3584: 		    'incorrect'=>'incorrect_by_override',
                   3585: 		    'excused'  =>'excused',
                   3586: 		    'ungraded' =>'ungraded_attempted',
1.596     raeburn  3587:                     'credited' =>'credit_attempted',
1.43      ng       3588: 		    'nothing'  => '',
                   3589: 		    );
1.257     albertel 3590:     my ($classlist,undef,$fullname) = &getclasslist($env{'form.section'},'0');
1.34      ng       3591: 
1.44      ng       3592:     my (@partid);
                   3593:     my %weight = ();
1.54      albertel 3594:     my %columns = ();
1.44      ng       3595:     my ($i,$ctr,$count,$rec_update) = (0,0,0,0);
1.54      albertel 3596: 
1.582     raeburn  3597:     my $partserror;
                   3598:     my (@parts) = sort(&getpartlist($symb,\$partserror));
                   3599:     if ($partserror) {
                   3600:         return &navmap_errormsg();
                   3601:     }
1.54      albertel 3602:     my $header;
1.257     albertel 3603:     while ($ctr < $env{'form.totalparts'}) {
                   3604: 	my $partid = $env{'form.partid_'.$ctr};
1.524     raeburn  3605: 	push(@partid,$partid);
1.257     albertel 3606: 	$weight{$partid} = $env{'form.weight_'.$partid};
1.44      ng       3607: 	$ctr++;
1.54      albertel 3608:     }
1.324     albertel 3609:     my (undef,undef,$url) = &Apache::lonnet::decode_symb($symb);
1.54      albertel 3610:     foreach my $partid (@partid) {
1.478     albertel 3611: 	$header .= '<th align="center">'.&mt('Old Score').'</th>'.
                   3612: 	    '<th align="center">'.&mt('New Score').'</th>';
1.54      albertel 3613: 	$columns{$partid}=2;
                   3614: 	foreach my $stores (@parts) {
                   3615: 	    my ($part,$type) = &split_part_type($stores);
                   3616: 	    if ($part !~ m/^\Q$partid\E/) { next;}
                   3617: 	    if ($type eq 'awarded' || $type eq 'solved') { next; }
                   3618: 	    my $display=&Apache::lonnet::metadata($url,$stores.'.display');
1.551     raeburn  3619: 	    $display =~ s/\[Part: \Q$part\E\]//;
1.539     riegler  3620:             my $narrowtext = &mt('Tries');
                   3621: 	    $display =~ s/Number of Attempts/$narrowtext/;
                   3622: 	    $header .= '<th align="center">'.&mt('Old').' '.$display.'</th>'.
                   3623: 		'<th align="center">'.&mt('New').' '.$display.'</th>';
1.54      albertel 3624: 	    $columns{$partid}+=2;
                   3625: 	}
                   3626:     }
                   3627:     foreach my $partid (@partid) {
1.324     albertel 3628: 	my $display_part=&get_display_part($partid,$symb);
1.478     albertel 3629: 	$result .= '<th colspan="'.$columns{$partid}.'" align="center">'.
                   3630: 	    &mt('Part: [_1] (Weight = [_2])',$display_part,$weight{$partid}).
                   3631: 	    '</th>';
1.54      albertel 3632: 
1.44      ng       3633:     }
1.477     albertel 3634:     $result .= &Apache::loncommon::end_data_table_header_row().
                   3635: 	&Apache::loncommon::start_data_table_header_row().
                   3636: 	$header.
                   3637: 	&Apache::loncommon::end_data_table_header_row();
                   3638:     my @noupdate;
1.126     ng       3639:     my ($updateCtr,$noupdateCtr) = (1,1);
1.257     albertel 3640:     for ($i=0; $i<$env{'form.total'}; $i++) {
1.93      albertel 3641: 	my $line;
1.257     albertel 3642: 	my $user = $env{'form.ctr'.$i};
1.281     albertel 3643: 	my ($uname,$udom)=split(/:/,$user);
1.44      ng       3644: 	my %newrecord;
                   3645: 	my $updateflag = 0;
1.281     albertel 3646: 	$line .= '<td>'.&nameUserString(undef,$$fullname{$user},$uname,$udom).'</td>';
1.108     albertel 3647: 	my $usec=$classlist->{"$uname:$udom"}[5];
1.105     albertel 3648: 	if (!&canmodify($usec)) {
1.126     ng       3649: 	    my $numcols=scalar(@partid)*4+2;
1.477     albertel 3650: 	    push(@noupdate,
1.478     albertel 3651: 		 $line."<td colspan=\"$numcols\"><span class=\"LC_warning\">".
                   3652: 		 &mt('Not allowed to modify student')."</span></td></tr>");
1.105     albertel 3653: 	    next;
                   3654: 	}
1.269     raeburn  3655:         my %aggregate = ();
                   3656:         my $aggregateflag = 0;
1.281     albertel 3657: 	$user=~s/:/_/; # colon doen't work in javascript for names
1.44      ng       3658: 	foreach (@partid) {
1.257     albertel 3659: 	    my $old_aw    = $env{'form.GD_'.$user.'_'.$_.'_awarded_s'};
1.54      albertel 3660: 	    my $old_part_pcr = $old_aw/($weight{$_} ne '0' ? $weight{$_}:1);
                   3661: 	    my $old_part  = $old_aw eq '' ? '' : $old_part_pcr;
1.257     albertel 3662: 	    my $old_score = $scoreptr{$env{'form.GD_'.$user.'_'.$_.'_solved_s'}};
                   3663: 	    my $awarded   = $env{'form.GD_'.$user.'_'.$_.'_awarded'};
1.54      albertel 3664: 	    my $pcr       = $awarded/($weight{$_} ne '0' ? $weight{$_} : 1);
                   3665: 	    my $partial   = $awarded eq '' ? '' : $pcr;
1.44      ng       3666: 	    my $score;
                   3667: 	    if ($partial eq '') {
1.257     albertel 3668: 		$score = $scoreptr{$env{'form.GD_'.$user.'_'.$_.'_solved_s'}};
1.44      ng       3669: 	    } elsif ($partial > 0) {
                   3670: 		$score = 'correct_by_override';
                   3671: 	    } elsif ($partial == 0) {
                   3672: 		$score = 'incorrect_by_override';
                   3673: 	    }
1.257     albertel 3674: 	    my $dropMenu = $env{'form.GD_'.$user.'_'.$_.'_solved'};
1.125     ng       3675: 	    $score = 'excused' if (($dropMenu eq 'excused') && ($score ne 'excused'));
                   3676: 
1.292     albertel 3677: 	    $newrecord{'resource.'.$_.'.regrader'}=
                   3678: 		"$env{'user.name'}:$env{'user.domain'}";
1.125     ng       3679: 	    if ($dropMenu eq 'reset status' &&
                   3680: 		$old_score ne '') { # ignore if no previous attempts => nothing to reset
1.299     albertel 3681: 		$newrecord{'resource.'.$_.'.tries'} = '';
1.125     ng       3682: 		$newrecord{'resource.'.$_.'.solved'} = '';
                   3683: 		$newrecord{'resource.'.$_.'.award'} = '';
1.299     albertel 3684: 		$newrecord{'resource.'.$_.'.awarded'} = '';
1.125     ng       3685: 		$updateflag = 1;
1.269     raeburn  3686:                 if ($env{'form.GD_'.$user.'_'.$_.'_aggtries'} > 0) {
                   3687:                     my $aggtries = $env{'form.GD_'.$user.'_'.$_.'_aggtries'};
                   3688:                     my $totaltries = $env{'form.GD_'.$user.'_'.$_.'_totaltries'};
                   3689:                     my $solvedstatus = $env{'form.GD_'.$user.'_'.$_.'_solved_s'};
                   3690:                     &decrement_aggs($symb,$_,\%aggregate,$aggtries,$totaltries,$solvedstatus);
                   3691:                     $aggregateflag = 1;
                   3692:                 }
1.139     albertel 3693: 	    } elsif (!($old_part eq $partial && $old_score eq $score)) {
                   3694: 		$updateflag = 1;
                   3695: 		$newrecord{'resource.'.$_.'.awarded'}  = $partial if $partial ne '';
                   3696: 		$newrecord{'resource.'.$_.'.solved'}   = $score;
                   3697: 		$rec_update++;
1.125     ng       3698: 	    }
                   3699: 
1.93      albertel 3700: 	    $line .= '<td align="center">'.$old_aw.'&nbsp;</td>'.
1.44      ng       3701: 		'<td align="center">'.$awarded.
                   3702: 		($score eq 'excused' ? $score : '').'&nbsp;</td>';
1.5       albertel 3703: 
1.54      albertel 3704: 
                   3705: 	    my $partid=$_;
                   3706: 	    foreach my $stores (@parts) {
                   3707: 		my ($part,$type) = &split_part_type($stores);
                   3708: 		if ($part !~ m/^\Q$partid\E/) { next;}
                   3709: 		if ($type eq 'awarded' || $type eq 'solved') { next; }
1.257     albertel 3710: 		my $old_aw    = $env{'form.GD_'.$user.'_'.$part.'_'.$type.'_s'};
                   3711: 		my $awarded   = $env{'form.GD_'.$user.'_'.$part.'_'.$type};
1.54      albertel 3712: 		if ($awarded ne '' && $awarded ne $old_aw) {
                   3713: 		    $newrecord{'resource.'.$part.'.'.$type}= $awarded;
1.257     albertel 3714: 		    $newrecord{'resource.'.$part.'.regrader'}="$env{'user.name'}:$env{'user.domain'}";
1.54      albertel 3715: 		    $updateflag=1;
                   3716: 		}
1.93      albertel 3717: 		$line .= '<td align="center">'.$old_aw.'&nbsp;</td>'.
1.54      albertel 3718: 		    '<td align="center">'.$awarded.'&nbsp;</td>';
                   3719: 	    }
1.44      ng       3720: 	}
1.477     albertel 3721: 	$line.="\n";
1.301     albertel 3722: 
                   3723: 	my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   3724: 	my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   3725: 
1.44      ng       3726: 	if ($updateflag) {
                   3727: 	    $count++;
1.257     albertel 3728: 	    &Apache::lonnet::cstore(\%newrecord,$symb,$env{'request.course.id'},
1.89      albertel 3729: 				    $udom,$uname);
1.301     albertel 3730: 
                   3731: 	    if (&Apache::bridgetask::in_queue('gradingqueue',$symb,$cdom,
                   3732: 					      $cnum,$udom,$uname)) {
                   3733: 		# need to figure out if should be in queue.
                   3734: 		my %record =  
                   3735: 		    &Apache::lonnet::restore($symb,$env{'request.course.id'},
                   3736: 					     $udom,$uname);
                   3737: 		my $all_graded = 1;
                   3738: 		my $none_graded = 1;
                   3739: 		foreach my $part (@parts) {
                   3740: 		    if ( $record{'resource.'.$part.'.awarded'} eq '' ) {
                   3741: 			$all_graded = 0;
                   3742: 		    } else {
                   3743: 			$none_graded = 0;
                   3744: 		    }
                   3745: 		}
                   3746: 
                   3747: 		if ($all_graded || $none_graded) {
                   3748: 		    &Apache::bridgetask::remove_from_queue('gradingqueue',
                   3749: 							   $symb,$cdom,$cnum,
                   3750: 							   $udom,$uname);
                   3751: 		}
                   3752: 	    }
                   3753: 
1.477     albertel 3754: 	    $result.=&Apache::loncommon::start_data_table_row().
                   3755: 		'<td align="right">&nbsp;'.$updateCtr.'&nbsp;</td>'.$line.
                   3756: 		&Apache::loncommon::end_data_table_row();
1.126     ng       3757: 	    $updateCtr++;
1.93      albertel 3758: 	} else {
1.477     albertel 3759: 	    push(@noupdate,
                   3760: 		 '<td align="right">&nbsp;'.$noupdateCtr.'&nbsp;</td>'.$line);
1.126     ng       3761: 	    $noupdateCtr++;
1.44      ng       3762: 	}
1.269     raeburn  3763:         if ($aggregateflag) {
                   3764:             &Apache::lonnet::cinc('nohist_resourcetracker',\%aggregate,
1.301     albertel 3765: 				  $cdom,$cnum);
1.269     raeburn  3766:         }
1.93      albertel 3767:     }
1.477     albertel 3768:     if (@noupdate) {
1.126     ng       3769: #	my $numcols=(scalar(@partid)*(scalar(@parts)-1)*2)+3;
                   3770: 	my $numcols=scalar(@partid)*4+2;
1.477     albertel 3771: 	$result .= &Apache::loncommon::start_data_table_row('LC_empty_row').
1.478     albertel 3772: 	    '<td align="center" colspan="'.$numcols.'">'.
                   3773: 	    &mt('No Changes Occurred For the Students Below').
                   3774: 	    '</td>'.
1.477     albertel 3775: 	    &Apache::loncommon::end_data_table_row();
                   3776: 	foreach my $line (@noupdate) {
                   3777: 	    $result.=
                   3778: 		&Apache::loncommon::start_data_table_row().
                   3779: 		$line.
                   3780: 		&Apache::loncommon::end_data_table_row();
                   3781: 	}
1.44      ng       3782:     }
1.477     albertel 3783:     $result .= &Apache::loncommon::end_data_table().
                   3784: 	&show_grading_menu_form($symb);
1.478     albertel 3785:     my $msg = '<p><b>'.
                   3786: 	&mt('Number of records updated = [_1] for [quant,_2,student].',
                   3787: 	    $rec_update,$count).'</b><br />'.
                   3788: 	'<b>'.&mt('Total number of students = [_1]',$env{'form.total'}).
                   3789: 	'</b></p>';
1.44      ng       3790:     return $title.$msg.$result;
1.5       albertel 3791: }
1.54      albertel 3792: 
                   3793: sub split_part_type {
                   3794:     my ($partstr) = @_;
                   3795:     my ($temp,@allparts)=split(/_/,$partstr);
                   3796:     my $type=pop(@allparts);
1.439     albertel 3797:     my $part=join('_',@allparts);
1.54      albertel 3798:     return ($part,$type);
                   3799: }
                   3800: 
1.44      ng       3801: #------------- end of section for handling grading by section/class ---------
                   3802: #
                   3803: #----------------------------------------------------------------------------
                   3804: 
1.5       albertel 3805: 
1.44      ng       3806: #----------------------------------------------------------------------------
                   3807: #
                   3808: #-------------------------- Next few routines handles grading by csv upload
                   3809: #
                   3810: #--- Javascript to handle csv upload
1.27      albertel 3811: sub csvupload_javascript_reverse_associate {
1.573     bisitz   3812:     my $error1=&mt('You need to specify the username or the student/employee ID');
1.246     albertel 3813:     my $error2=&mt('You need to specify at least one grading field');
1.27      albertel 3814:   return(<<ENDPICK);
                   3815:   function verify(vf) {
                   3816:     var foundsomething=0;
                   3817:     var founduname=0;
1.243     albertel 3818:     var foundID=0;
1.27      albertel 3819:     for (i=0;i<=vf.nfields.value;i++) {
                   3820:       tw=eval('vf.f'+i+'.selectedIndex');
1.243     albertel 3821:       if (i==0 && tw!=0) { foundID=1; }
                   3822:       if (i==1 && tw!=0) { founduname=1; }
                   3823:       if (i!=0 && i!=1 && i!=2 && tw!=0) { foundsomething=1; }
1.27      albertel 3824:     }
1.246     albertel 3825:     if (founduname==0 && foundID==0) {
                   3826: 	alert('$error1');
                   3827: 	return;
1.27      albertel 3828:     }
                   3829:     if (foundsomething==0) {
1.246     albertel 3830: 	alert('$error2');
                   3831: 	return;
1.27      albertel 3832:     }
                   3833:     vf.submit();
                   3834:   }
                   3835:   function flip(vf,tf) {
                   3836:     var nw=eval('vf.f'+tf+'.selectedIndex');
                   3837:     var i;
                   3838:     for (i=0;i<=vf.nfields.value;i++) {
                   3839:       //can not pick the same destination field for both name and domain
                   3840:       if (((i ==0)||(i ==1)) && 
                   3841:           ((tf==0)||(tf==1)) && 
                   3842:           (i!=tf) &&
                   3843:           (eval('vf.f'+i+'.selectedIndex')==nw)) {
                   3844:         eval('vf.f'+i+'.selectedIndex=0;')
                   3845:       }
                   3846:     }
                   3847:   }
                   3848: ENDPICK
                   3849: }
                   3850: 
                   3851: sub csvupload_javascript_forward_associate {
1.573     bisitz   3852:     my $error1=&mt('You need to specify the username or the student/employee ID');
1.246     albertel 3853:     my $error2=&mt('You need to specify at least one grading field');
1.27      albertel 3854:   return(<<ENDPICK);
                   3855:   function verify(vf) {
                   3856:     var foundsomething=0;
                   3857:     var founduname=0;
1.243     albertel 3858:     var foundID=0;
1.27      albertel 3859:     for (i=0;i<=vf.nfields.value;i++) {
                   3860:       tw=eval('vf.f'+i+'.selectedIndex');
1.243     albertel 3861:       if (tw==1) { foundID=1; }
                   3862:       if (tw==2) { founduname=1; }
                   3863:       if (tw>3) { foundsomething=1; }
1.27      albertel 3864:     }
1.246     albertel 3865:     if (founduname==0 && foundID==0) {
                   3866: 	alert('$error1');
                   3867: 	return;
1.27      albertel 3868:     }
                   3869:     if (foundsomething==0) {
1.246     albertel 3870: 	alert('$error2');
                   3871: 	return;
1.27      albertel 3872:     }
                   3873:     vf.submit();
                   3874:   }
                   3875:   function flip(vf,tf) {
                   3876:     var nw=eval('vf.f'+tf+'.selectedIndex');
                   3877:     var i;
                   3878:     //can not pick the same destination field twice
                   3879:     for (i=0;i<=vf.nfields.value;i++) {
                   3880:       if ((i!=tf) && (eval('vf.f'+i+'.selectedIndex')==nw)) {
                   3881:         eval('vf.f'+i+'.selectedIndex=0;')
                   3882:       }
                   3883:     }
                   3884:   }
                   3885: ENDPICK
                   3886: }
                   3887: 
1.26      albertel 3888: sub csvuploadmap_header {
1.324     albertel 3889:     my ($request,$symb,$datatoken,$distotal)= @_;
1.41      ng       3890:     my $javascript;
1.257     albertel 3891:     if ($env{'form.upfile_associate'} eq 'reverse') {
1.41      ng       3892: 	$javascript=&csvupload_javascript_reverse_associate();
                   3893:     } else {
                   3894: 	$javascript=&csvupload_javascript_forward_associate();
                   3895:     }
1.45      ng       3896: 
1.324     albertel 3897:     my ($result) = &showResourceInfo($symb,$env{'form.probTitle'});
1.257     albertel 3898:     my $checked=(($env{'form.noFirstLine'})?' checked="checked"':'');
1.245     albertel 3899:     my $ignore=&mt('Ignore First Line');
1.418     albertel 3900:     $symb = &Apache::lonenc::check_encrypt($symb);
1.41      ng       3901:     $request->print(<<ENDPICK);
1.26      albertel 3902: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="gradesupload">
1.398     albertel 3903: <h3><span class="LC_info">Uploading Class Grades</span></h3>
1.45      ng       3904: $result
1.326     albertel 3905: <hr />
1.26      albertel 3906: <h3>Identify fields</h3>
                   3907: Total number of records found in file: $distotal <hr />
                   3908: Enter as many fields as you can. The system will inform you and bring you back
                   3909: to this page if the data selected is insufficient to run your class.<hr />
1.589     bisitz   3910: <input type="button" value="Reverse Association" onclick="javascript:this.form.associate.value='Reverse Association';submit(this.form);" />
1.245     albertel 3911: <label><input type="checkbox" name="noFirstLine" $checked />$ignore</label>
1.26      albertel 3912: <input type="hidden" name="associate"  value="" />
                   3913: <input type="hidden" name="phase"      value="three" />
                   3914: <input type="hidden" name="datatoken"  value="$datatoken" />
1.257     albertel 3915: <input type="hidden" name="fileupload" value="$env{'form.fileupload'}" />
                   3916: <input type="hidden" name="upfiletype" value="$env{'form.upfiletype'}" />
1.26      albertel 3917: <input type="hidden" name="upfile_associate" 
1.257     albertel 3918:                                        value="$env{'form.upfile_associate'}" />
1.26      albertel 3919: <input type="hidden" name="symb"       value="$symb" />
1.257     albertel 3920: <input type="hidden" name="saveState"  value="$env{'form.saveState'}" />
                   3921: <input type="hidden" name="probTitle"  value="$env{'form.probTitle'}" />
1.246     albertel 3922: <input type="hidden" name="command"    value="csvuploadoptions" />
1.26      albertel 3923: <hr />
                   3924: ENDPICK
1.597   ! wenzelju 3925:     $request->print(&Apache::lonhtmlcommon::scripttag($javascript));
1.118     ng       3926:     return '';
1.26      albertel 3927: 
                   3928: }
                   3929: 
                   3930: sub csvupload_fields {
1.582     raeburn  3931:     my ($symb,$errorref) = @_;
                   3932:     my (@parts) = &getpartlist($symb,$errorref);
                   3933:     if (ref($errorref)) {
                   3934:         if ($$errorref) {
                   3935:             return;
                   3936:         }
                   3937:     }
                   3938: 
1.556     weissno  3939:     my @fields=(['ID','Student/Employee ID'],
1.243     albertel 3940: 		['username','Student Username'],
                   3941: 		['domain','Student Domain']);
1.324     albertel 3942:     my (undef,undef,$url) = &Apache::lonnet::decode_symb($symb);
1.41      ng       3943:     foreach my $part (sort(@parts)) {
                   3944: 	my @datum;
                   3945: 	my $display=&Apache::lonnet::metadata($url,$part.'.display');
                   3946: 	my $name=$part;
                   3947: 	if  (!$display) { $display = $name; }
                   3948: 	@datum=($name,$display);
1.244     albertel 3949: 	if ($name=~/^stores_(.*)_awarded/) {
                   3950: 	    push(@fields,['stores_'.$1.'_points',"Points [Part: $1]"]);
                   3951: 	}
1.41      ng       3952: 	push(@fields,\@datum);
                   3953:     }
                   3954:     return (@fields);
1.26      albertel 3955: }
                   3956: 
                   3957: sub csvuploadmap_footer {
1.41      ng       3958:     my ($request,$i,$keyfields) =@_;
                   3959:     $request->print(<<ENDPICK);
1.26      albertel 3960: </table>
                   3961: <input type="hidden" name="nfields" value="$i" />
                   3962: <input type="hidden" name="keyfields" value="$keyfields" />
1.589     bisitz   3963: <input type="button" onclick="javascript:verify(this.form)" value="Assign Grades" /><br />
1.26      albertel 3964: </form>
                   3965: ENDPICK
                   3966: }
                   3967: 
1.283     albertel 3968: sub checkforfile_js {
1.539     riegler  3969:     my $alertmsg = &mt('Please use the browse button to select a file from your local directory.');
1.597   ! wenzelju 3970:     my $result = &Apache::lonhtmlcommon::scripttag(<<CSVFORMJS);
1.86      ng       3971:     function checkUpload(formname) {
                   3972: 	if (formname.upfile.value == "") {
1.539     riegler  3973: 	    alert("$alertmsg");
1.86      ng       3974: 	    return false;
                   3975: 	}
                   3976: 	formname.submit();
                   3977:     }
                   3978: CSVFORMJS
1.283     albertel 3979:     return $result;
                   3980: }
                   3981: 
                   3982: sub upcsvScores_form {
                   3983:     my ($request) = shift;
1.324     albertel 3984:     my ($symb)=&get_symb($request);
1.283     albertel 3985:     if (!$symb) {return '';}
                   3986:     my $result=&checkforfile_js();
1.257     albertel 3987:     $env{'form.probTitle'} = &Apache::lonnet::gettitle($symb);
1.324     albertel 3988:     my ($table) = &showResourceInfo($symb,$env{'form.probTitle'});
1.118     ng       3989:     $result.=$table;
1.326     albertel 3990:     $result.='<br /><table width="100%" border="0"><tr><td bgcolor="#777777">'."\n";
                   3991:     $result.='<table width="100%" border="0"><tr bgcolor="#e6ffff"><td>'."\n";
1.538     schulted 3992:     $result.='&nbsp;<b>'.&mt('Specify a file containing the class scores for current resource.').
                   3993: 	'</b></td></tr>'."\n";
1.86      ng       3994:     $result.='<tr bgcolor=#ffffe6><td>'."\n";
1.370     www      3995:     my $upload=&mt("Upload Scores");
1.86      ng       3996:     my $upfile_select=&Apache::loncommon::upfile_select_html();
1.245     albertel 3997:     my $ignore=&mt('Ignore First Line');
1.418     albertel 3998:     $symb = &Apache::lonenc::check_encrypt($symb);
1.86      ng       3999:     $result.=<<ENDUPFORM;
1.106     albertel 4000: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="gradesupload">
1.86      ng       4001: <input type="hidden" name="symb" value="$symb" />
                   4002: <input type="hidden" name="command" value="csvuploadmap" />
1.257     albertel 4003: <input type="hidden" name="probTitle" value="$env{'form.probTitle'}" />
                   4004: <input type="hidden" name="saveState"  value="$env{'form.saveState'}" />
1.86      ng       4005: $upfile_select
1.589     bisitz   4006: <br /><input type="button" onclick="javascript:checkUpload(this.form);" value="$upload" />
1.283     albertel 4007: <label><input type="checkbox" name="noFirstLine" />$ignore</label>
1.86      ng       4008: </form>
                   4009: ENDUPFORM
1.370     www      4010:     $result.=&Apache::loncommon::help_open_topic("Course_Convert_To_CSV",
                   4011:                            &mt("How do I create a CSV file from a spreadsheet"))
                   4012:     .'</td></tr></table>'."\n";
1.86      ng       4013:     $result.='</td></tr></table><br /><br />'."\n";
1.324     albertel 4014:     $result.=&show_grading_menu_form($symb);
1.86      ng       4015:     return $result;
                   4016: }
                   4017: 
                   4018: 
1.26      albertel 4019: sub csvuploadmap {
1.41      ng       4020:     my ($request)= @_;
1.324     albertel 4021:     my ($symb)=&get_symb($request);
1.41      ng       4022:     if (!$symb) {return '';}
1.72      ng       4023: 
1.41      ng       4024:     my $datatoken;
1.257     albertel 4025:     if (!$env{'form.datatoken'}) {
1.41      ng       4026: 	$datatoken=&Apache::loncommon::upfile_store($request);
1.26      albertel 4027:     } else {
1.257     albertel 4028: 	$datatoken=$env{'form.datatoken'};
1.41      ng       4029: 	&Apache::loncommon::load_tmp_file($request);
1.26      albertel 4030:     }
1.41      ng       4031:     my @records=&Apache::loncommon::upfile_record_sep();
1.257     albertel 4032:     if ($env{'form.noFirstLine'}) { shift(@records); }
1.324     albertel 4033:     &csvuploadmap_header($request,$symb,$datatoken,$#records+1);
1.41      ng       4034:     my ($i,$keyfields);
                   4035:     if (@records) {
1.582     raeburn  4036:         my $fieldserror;
                   4037: 	my @fields=&csvupload_fields($symb,\$fieldserror);
                   4038:         if ($fieldserror) {
                   4039:             $request->print(&navmap_errormsg());
                   4040:             return;
                   4041:         }
1.257     albertel 4042: 	if ($env{'form.upfile_associate'} eq 'reverse') {	
1.41      ng       4043: 	    &Apache::loncommon::csv_print_samples($request,\@records);
                   4044: 	    $i=&Apache::loncommon::csv_print_select_table($request,\@records,
                   4045: 							  \@fields);
                   4046: 	    foreach (@fields) { $keyfields.=$_->[0].','; }
                   4047: 	    chop($keyfields);
                   4048: 	} else {
                   4049: 	    unshift(@fields,['none','']);
                   4050: 	    $i=&Apache::loncommon::csv_samples_select_table($request,\@records,
                   4051: 							    \@fields);
1.311     banghart 4052:             foreach my $rec (@records) {
                   4053:                 my %temp = &Apache::loncommon::record_sep($rec);
                   4054:                 if (%temp) {
                   4055:                     $keyfields=join(',',sort(keys(%temp)));
                   4056:                     last;
                   4057:                 }
                   4058:             }
1.41      ng       4059: 	}
                   4060:     }
                   4061:     &csvuploadmap_footer($request,$i,$keyfields);
1.324     albertel 4062:     $request->print(&show_grading_menu_form($symb));
1.72      ng       4063: 
1.41      ng       4064:     return '';
1.27      albertel 4065: }
                   4066: 
1.246     albertel 4067: sub csvuploadoptions {
1.41      ng       4068:     my ($request)= @_;
1.324     albertel 4069:     my ($symb)=&get_symb($request);
1.257     albertel 4070:     my $checked=(($env{'form.noFirstLine'})?'1':'0');
1.246     albertel 4071:     my $ignore=&mt('Ignore First Line');
                   4072:     $request->print(<<ENDPICK);
                   4073: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="gradesupload">
1.398     albertel 4074: <h3><span class="LC_info">Uploading Class Grade Options</span></h3>
1.246     albertel 4075: <input type="hidden" name="command"    value="csvuploadassign" />
1.302     albertel 4076: <!--
1.246     albertel 4077: <p>
                   4078: <label>
                   4079:    <input type="checkbox" name="show_full_results" />
                   4080:    Show a table of all changes
                   4081: </label>
                   4082: </p>
1.302     albertel 4083: -->
1.246     albertel 4084: <p>
                   4085: <label>
                   4086:    <input type="checkbox" name="overwite_scores" checked="checked" />
                   4087:    Overwrite any existing score
                   4088: </label>
                   4089: </p>
                   4090: ENDPICK
                   4091:     my %fields=&get_fields();
                   4092:     if (!defined($fields{'domain'})) {
1.257     albertel 4093: 	my $domform = &Apache::loncommon::select_dom_form($env{'request.role.domain'},'default_domain');
1.246     albertel 4094: 	$request->print("\n<p> Users are in domain: ".$domform."</p>\n");
                   4095:     }
1.257     albertel 4096:     foreach my $key (sort(keys(%env))) {
1.246     albertel 4097: 	if ($key !~ /^form\.(.*)$/) { next; }
                   4098: 	my $cleankey=$1;
                   4099: 	if ($cleankey eq 'command') { next; }
                   4100: 	$request->print('<input type="hidden" name="'.$cleankey.
1.257     albertel 4101: 			'"  value="'.$env{$key}.'" />'."\n");
1.246     albertel 4102:     }
                   4103:     # FIXME do a check for any duplicated user ids...
                   4104:     # FIXME do a check for any invalid user ids?...
1.290     albertel 4105:     $request->print('<input type="submit" value="Assign Grades" /><br />
                   4106: <hr /></form>'."\n");
1.324     albertel 4107:     $request->print(&show_grading_menu_form($symb));
1.246     albertel 4108:     return '';
                   4109: }
                   4110: 
                   4111: sub get_fields {
                   4112:     my %fields;
1.257     albertel 4113:     my @keyfields = split(/\,/,$env{'form.keyfields'});
                   4114:     for (my $i=0; $i<=$env{'form.nfields'}; $i++) {
                   4115: 	if ($env{'form.upfile_associate'} eq 'reverse') {
                   4116: 	    if ($env{'form.f'.$i} ne 'none') {
                   4117: 		$fields{$keyfields[$i]}=$env{'form.f'.$i};
1.41      ng       4118: 	    }
                   4119: 	} else {
1.257     albertel 4120: 	    if ($env{'form.f'.$i} ne 'none') {
                   4121: 		$fields{$env{'form.f'.$i}}=$keyfields[$i];
1.41      ng       4122: 	    }
                   4123: 	}
1.27      albertel 4124:     }
1.246     albertel 4125:     return %fields;
                   4126: }
                   4127: 
                   4128: sub csvuploadassign {
                   4129:     my ($request)= @_;
1.324     albertel 4130:     my ($symb)=&get_symb($request);
1.246     albertel 4131:     if (!$symb) {return '';}
1.345     bowersj2 4132:     my $error_msg = '';
1.246     albertel 4133:     &Apache::loncommon::load_tmp_file($request);
                   4134:     my @gradedata = &Apache::loncommon::upfile_record_sep();
1.257     albertel 4135:     if ($env{'form.noFirstLine'}) { shift(@gradedata); }
1.246     albertel 4136:     my %fields=&get_fields();
1.41      ng       4137:     $request->print('<h3>Assigning Grades</h3>');
1.257     albertel 4138:     my $courseid=$env{'request.course.id'};
1.97      albertel 4139:     my ($classlist) = &getclasslist('all',0);
1.106     albertel 4140:     my @notallowed;
1.41      ng       4141:     my @skipped;
                   4142:     my $countdone=0;
                   4143:     foreach my $grade (@gradedata) {
                   4144: 	my %entries=&Apache::loncommon::record_sep($grade);
1.246     albertel 4145: 	my $domain;
                   4146: 	if ($entries{$fields{'domain'}}) {
                   4147: 	    $domain=$entries{$fields{'domain'}};
                   4148: 	} else {
1.257     albertel 4149: 	    $domain=$env{'form.default_domain'};
1.246     albertel 4150: 	}
1.243     albertel 4151: 	$domain=~s/\s//g;
1.41      ng       4152: 	my $username=$entries{$fields{'username'}};
1.160     albertel 4153: 	$username=~s/\s//g;
1.243     albertel 4154: 	if (!$username) {
                   4155: 	    my $id=$entries{$fields{'ID'}};
1.247     albertel 4156: 	    $id=~s/\s//g;
1.243     albertel 4157: 	    my %ids=&Apache::lonnet::idget($domain,$id);
                   4158: 	    $username=$ids{$id};
                   4159: 	}
1.41      ng       4160: 	if (!exists($$classlist{"$username:$domain"})) {
1.247     albertel 4161: 	    my $id=$entries{$fields{'ID'}};
                   4162: 	    $id=~s/\s//g;
                   4163: 	    if ($id) {
                   4164: 		push(@skipped,"$id:$domain");
                   4165: 	    } else {
                   4166: 		push(@skipped,"$username:$domain");
                   4167: 	    }
1.41      ng       4168: 	    next;
                   4169: 	}
1.108     albertel 4170: 	my $usec=$classlist->{"$username:$domain"}[5];
1.106     albertel 4171: 	if (!&canmodify($usec)) {
                   4172: 	    push(@notallowed,"$username:$domain");
                   4173: 	    next;
                   4174: 	}
1.244     albertel 4175: 	my %points;
1.41      ng       4176: 	my %grades;
                   4177: 	foreach my $dest (keys(%fields)) {
1.244     albertel 4178: 	    if ($dest eq 'ID' || $dest eq 'username' ||
                   4179: 		$dest eq 'domain') { next; }
                   4180: 	    if ($entries{$fields{$dest}} =~ /^\s*$/) { next; }
                   4181: 	    if ($dest=~/stores_(.*)_points/) {
                   4182: 		my $part=$1;
                   4183: 		my $wgt =&Apache::lonnet::EXT('resource.'.$part.'.weight',
                   4184: 					      $symb,$domain,$username);
1.345     bowersj2 4185:                 if ($wgt) {
                   4186:                     $entries{$fields{$dest}}=~s/\s//g;
                   4187:                     my $pcr=$entries{$fields{$dest}} / $wgt;
1.463     albertel 4188:                     my $award=($pcr == 0) ? 'incorrect_by_override'
                   4189:                                           : 'correct_by_override';
1.345     bowersj2 4190:                     $grades{"resource.$part.awarded"}=$pcr;
                   4191:                     $grades{"resource.$part.solved"}=$award;
                   4192:                     $points{$part}=1;
                   4193:                 } else {
                   4194:                     $error_msg = "<br />" .
                   4195:                         &mt("Some point values were assigned"
                   4196:                             ." for problems with a weight "
                   4197:                             ."of zero. These values were "
                   4198:                             ."ignored.");
                   4199:                 }
1.244     albertel 4200: 	    } else {
                   4201: 		if ($dest=~/stores_(.*)_awarded/) { if ($points{$1}) {next;} }
                   4202: 		if ($dest=~/stores_(.*)_solved/)  { if ($points{$1}) {next;} }
                   4203: 		my $store_key=$dest;
                   4204: 		$store_key=~s/^stores/resource/;
                   4205: 		$store_key=~s/_/\./g;
                   4206: 		$grades{$store_key}=$entries{$fields{$dest}};
                   4207: 	    }
1.41      ng       4208: 	}
1.508     www      4209: 	if (! %grades) { 
                   4210:            push(@skipped,&mt("[_1]: no data to save","$username:$domain")); 
                   4211:         } else {
                   4212: 	   $grades{"resource.regrader"}="$env{'user.name'}:$env{'user.domain'}";
                   4213: 	   my $result=&Apache::lonnet::cstore(\%grades,$symb,
1.302     albertel 4214: 					   $env{'request.course.id'},
                   4215: 					   $domain,$username);
1.508     www      4216: 	   if ($result eq 'ok') {
                   4217: 	      $request->print('.');
                   4218: 	   } else {
                   4219: 	      $request->print("<p><span class=\"LC_error\">".
                   4220:                               &mt("Failed to save data for student [_1]. Message when trying to save was: [_2]",
                   4221:                                   "$username:$domain",$result)."</span></p>");
                   4222: 	   }
                   4223: 	   $request->rflush();
                   4224: 	   $countdone++;
                   4225:         }
1.41      ng       4226:     }
1.570     www      4227:     $request->print('<br />'.&Apache::lonhtmlcommon::confirm_success(&mt("Saved scores for [quant,_1,student]",$countdone),$countdone==0));
1.41      ng       4228:     if (@skipped) {
1.571     www      4229: 	$request->print('<br />'.&Apache::lonhtmlcommon::confirm_success(&mt('No scores stored for the following username(s):'),1).'<br />');
                   4230:         $request->print(join(', ',@skipped));
1.106     albertel 4231:     }
                   4232:     if (@notallowed) {
1.571     www      4233: 	$request->print('<br />'.&Apache::lonhtmlcommon::confirm_success(&mt('Modification of scores not allowed for the following username(s):'),1).'<br />');
                   4234: 	$request->print(join(', ',@notallowed));
1.41      ng       4235:     }
1.106     albertel 4236:     $request->print("<br />\n");
1.324     albertel 4237:     $request->print(&show_grading_menu_form($symb));
1.345     bowersj2 4238:     return $error_msg;
1.26      albertel 4239: }
1.44      ng       4240: #------------- end of section for handling csv file upload ---------
                   4241: #
                   4242: #-------------------------------------------------------------------
                   4243: #
1.122     ng       4244: #-------------- Next few routines handle grading by page/sequence
1.72      ng       4245: #
                   4246: #--- Select a page/sequence and a student to grade
1.68      ng       4247: sub pickStudentPage {
                   4248:     my ($request) = shift;
                   4249: 
1.539     riegler  4250:     my $alertmsg = &mt('Please select the student you wish to grade.');
1.597   ! wenzelju 4251:     $request->print(&Apache::lonhtmlcommon::scripttag(<<LISTJAVASCRIPT));
1.68      ng       4252: 
                   4253: function checkPickOne(formname) {
1.76      ng       4254:     if (radioSelection(formname.student) == null) {
1.539     riegler  4255: 	alert("$alertmsg");
1.68      ng       4256: 	return;
                   4257:     }
1.125     ng       4258:     ptr = pullDownSelection(formname.selectpage);
                   4259:     formname.page.value = formname["page"+ptr].value;
                   4260:     formname.title.value = formname["title"+ptr].value;
1.68      ng       4261:     formname.submit();
                   4262: }
                   4263: 
                   4264: LISTJAVASCRIPT
1.118     ng       4265:     &commonJSfunctions($request);
1.324     albertel 4266:     my ($symb) = &get_symb($request);
1.257     albertel 4267:     my $cdom      = $env{"course.$env{'request.course.id'}.domain"};
                   4268:     my $cnum      = $env{"course.$env{'request.course.id'}.num"};
                   4269:     my $getsec    = $env{'form.section'} eq '' ? 'all' : $env{'form.section'};
1.68      ng       4270: 
1.398     albertel 4271:     my $result='<h3><span class="LC_info">&nbsp;'.
1.485     albertel 4272: 	&mt('Manual Grading by Page or Sequence').'</span></h3>';
1.68      ng       4273: 
1.80      ng       4274:     $result.='<form action="/adm/grades" method="post" name="displayPage">'."\n";
1.582     raeburn  4275:     my $map_error;
                   4276:     my ($titles,$symbx) = &getSymbMap($map_error);
                   4277:     if ($map_error) {
                   4278:         $request->print(&navmap_errormsg());
                   4279:         return; 
                   4280:     }
1.137     albertel 4281:     my ($curpage) =&Apache::lonnet::decode_symb($symb); 
                   4282: #    my ($curpage,$mapId) =&Apache::lonnet::decode_symb($symb); 
                   4283: #    my $type=($curpage =~ /\.(page|sequence)/);
1.485     albertel 4284:     my $select = '<select name="selectpage">'."\n";
1.70      ng       4285:     my $ctr=0;
1.68      ng       4286:     foreach (@$titles) {
                   4287: 	my ($minder,$showtitle) = ($_ =~ /(\d+)\.(.*)/);
1.485     albertel 4288: 	$select.='<option value="'.$ctr.'" '.
1.401     albertel 4289: 	    ($$symbx{$_} =~ /$curpage$/ ? 'selected="selected"' : '').
1.71      ng       4290: 	    '>'.$showtitle.'</option>'."\n";
1.70      ng       4291: 	$ctr++;
1.68      ng       4292:     }
1.485     albertel 4293:     $select.= '</select>';
1.539     riegler  4294:     $result.='&nbsp;<b>'.&mt('Problems from').':</b> '.$select."<br />\n";
1.485     albertel 4295: 
1.70      ng       4296:     $ctr=0;
                   4297:     foreach (@$titles) {
                   4298: 	my ($minder,$showtitle) = ($_ =~ /(\d+)\.(.*)/);
                   4299: 	$result.='<input type="hidden" name="page'.$ctr.'" value="'.$$symbx{$_}.'" />'."\n";
                   4300: 	$result.='<input type="hidden" name="title'.$ctr.'" value="'.$showtitle.'" />'."\n";
                   4301: 	$ctr++;
                   4302:     }
1.72      ng       4303:     $result.='<input type="hidden" name="page" />'."\n".
                   4304: 	'<input type="hidden" name="title" />'."\n";
1.68      ng       4305: 
1.485     albertel 4306:     my $options =
                   4307: 	'<label><input type="radio" name="vProb" value="no" checked="checked" /> '.&mt('no').' </label>'."\n".
                   4308: 	'<label><input type="radio" name="vProb" value="yes" /> '.&mt('yes').' </label>'."<br />\n";
1.539     riegler  4309:     $result.='&nbsp;<b>'.&mt('View Problem Text').': </b>'.$options;
1.485     albertel 4310: 
                   4311:     $options =
                   4312: 	'<label><input type="radio" name="lastSub" value="none" /> '.&mt('none').' </label>'."\n".
                   4313: 	'<label><input type="radio" name="lastSub" value="datesub" checked="checked" /> '.&mt('by dates and submissions').'</label>'."\n".
                   4314: 	'<label><input type="radio" name="lastSub" value="all" /> '.&mt('all details').' </label>'."\n";
1.539     riegler  4315:     $result.='&nbsp;<b>'.&mt('Submissions').': </b>'.$options;
1.432     banghart 4316:     
                   4317:     $result.=&build_section_inputs();
1.442     banghart 4318:     my $stu_status = join(':',&Apache::loncommon::get_env_multiple('form.Status'));
                   4319:     $result.='<input type="hidden" name="Status"  value="'.$stu_status.'" />'."\n".
1.72      ng       4320: 	'<input type="hidden" name="command" value="displayPage" />'."\n".
1.418     albertel 4321: 	'<input type="hidden" name="symb"    value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
1.257     albertel 4322: 	'<input type="hidden" name="saveState" value="'.$env{'form.saveState'}.'" />'."<br />\n";
1.72      ng       4323: 
1.539     riegler  4324:     $result.='&nbsp;<b>'.&mt('Use CODE').': </b> <input type="text" name="CODE" value="" /> <br />'."\n";
1.382     albertel 4325: 
1.80      ng       4326:     $result.='&nbsp;<input type="button" '.
1.589     bisitz   4327:              'onclick="javascript:checkPickOne(this.form);" value="'.&mt('Next').' &rarr;" /><br />'."\n";
1.72      ng       4328: 
1.68      ng       4329:     $request->print($result);
                   4330: 
1.485     albertel 4331:     my $studentTable.='&nbsp;<b>'.&mt('Select a student you wish to grade and then click on the Next button.').'</b><br />'.
1.484     albertel 4332: 	&Apache::loncommon::start_data_table().
                   4333: 	&Apache::loncommon::start_data_table_header_row().
1.485     albertel 4334: 	'<th align="right">&nbsp;'.&mt('No.').'</th>'.
1.484     albertel 4335: 	'<th>'.&nameUserString('header').'</th>'.
1.485     albertel 4336: 	'<th align="right">&nbsp;'.&mt('No.').'</th>'.
1.484     albertel 4337: 	'<th>'.&nameUserString('header').'</th>'.
                   4338: 	&Apache::loncommon::end_data_table_header_row();
1.68      ng       4339:  
1.76      ng       4340:     my (undef,undef,$fullname) = &getclasslist($getsec,'1');
1.68      ng       4341:     my $ptr = 1;
1.294     albertel 4342:     foreach my $student (sort 
                   4343: 			 {
                   4344: 			     if (lc($$fullname{$a}) ne lc($$fullname{$b})) {
                   4345: 				 return (lc($$fullname{$a}) cmp lc($$fullname{$b}));
                   4346: 			     }
                   4347: 			     return $a cmp $b;
                   4348: 			 } (keys(%$fullname))) {
1.68      ng       4349: 	my ($uname,$udom) = split(/:/,$student);
1.484     albertel 4350: 	$studentTable.=($ptr%2==1 ? &Apache::loncommon::start_data_table_row()
                   4351:                                   : '</td>');
1.126     ng       4352: 	$studentTable.='<td align="right">'.$ptr.'&nbsp;</td>';
1.288     albertel 4353: 	$studentTable.='<td>&nbsp;<label><input type="radio" name="student" value="'.$student.'" /> '
                   4354: 	    .&nameUserString(undef,$$fullname{$student},$uname,$udom)."</label>\n";
1.484     albertel 4355: 	$studentTable.=
                   4356: 	    ($ptr%2 == 0 ? '</td>'.&Apache::loncommon::end_data_table_row() 
                   4357:                          : '');
1.68      ng       4358: 	$ptr++;
                   4359:     }
1.484     albertel 4360:     if ($ptr%2 == 0) {
                   4361: 	$studentTable.='</td><td>&nbsp;</td><td>&nbsp;</td>'.
                   4362: 	    &Apache::loncommon::end_data_table_row();
                   4363:     }
                   4364:     $studentTable.=&Apache::loncommon::end_data_table()."\n";
1.126     ng       4365:     $studentTable.='<input type="button" '.
1.589     bisitz   4366:                    'onclick="javascript:checkPickOne(this.form);" value="'.&mt('Next').' &rarr;" /></form>'."\n";
1.68      ng       4367: 
1.324     albertel 4368:     $studentTable.=&show_grading_menu_form($symb);
1.68      ng       4369:     $request->print($studentTable);
                   4370: 
                   4371:     return '';
                   4372: }
                   4373: 
                   4374: sub getSymbMap {
1.582     raeburn  4375:     my ($map_error) = @_;
1.132     bowersj2 4376:     my $navmap = Apache::lonnavmaps::navmap->new();
1.582     raeburn  4377:     unless (ref($navmap)) {
                   4378:         if (ref($map_error)) {
                   4379:             $$map_error = 'navmap';
                   4380:         }
                   4381:         return;
                   4382:     }
1.68      ng       4383:     my %symbx = ();
                   4384:     my @titles = ();
1.117     bowersj2 4385:     my $minder = 0;
                   4386: 
                   4387:     # Gather every sequence that has problems.
1.240     albertel 4388:     my @sequences = $navmap->retrieveResources(undef, sub { shift->is_map(); },
                   4389: 					       1,0,1);
1.117     bowersj2 4390:     for my $sequence ($navmap->getById('0.0'), @sequences) {
1.241     albertel 4391: 	if ($navmap->hasResource($sequence, sub { shift->is_problem(); }, 0) ) {
1.381     albertel 4392: 	    my $title = $minder.'.'.
                   4393: 		&HTML::Entities::encode($sequence->compTitle(),'"\'&');
                   4394: 	    push(@titles, $title); # minder in case two titles are identical
                   4395: 	    $symbx{$title} = &HTML::Entities::encode($sequence->symb(),'"\'&');
1.117     bowersj2 4396: 	    $minder++;
1.241     albertel 4397: 	}
1.68      ng       4398:     }
                   4399:     return \@titles,\%symbx;
                   4400: }
                   4401: 
1.72      ng       4402: #
                   4403: #--- Displays a page/sequence w/wo problems, w/wo submissions
1.68      ng       4404: sub displayPage {
                   4405:     my ($request) = shift;
                   4406: 
1.324     albertel 4407:     my ($symb) = &get_symb($request);
1.257     albertel 4408:     my $cdom      = $env{"course.$env{'request.course.id'}.domain"};
                   4409:     my $cnum      = $env{"course.$env{'request.course.id'}.num"};
                   4410:     my $getsec    = $env{'form.section'} eq '' ? 'all' : $env{'form.section'};
                   4411:     my $pageTitle = $env{'form.page'};
1.103     albertel 4412:     my ($classlist,undef,$fullname) = &getclasslist($getsec,'1');
1.257     albertel 4413:     my ($uname,$udom) = split(/:/,$env{'form.student'});
                   4414:     my $usec=$classlist->{$env{'form.student'}}[5];
1.168     albertel 4415: 
                   4416:     #need to make sure we have the correct data for later EXT calls, 
                   4417:     #thus invalidate the cache
                   4418:     &Apache::lonnet::devalidatecourseresdata(
1.257     albertel 4419:                  $env{'course.'.$env{'request.course.id'}.'.num'},
                   4420:                  $env{'course.'.$env{'request.course.id'}.'.domain'});
1.168     albertel 4421:     &Apache::lonnet::clear_EXT_cache_status();
                   4422: 
1.103     albertel 4423:     if (!&canview($usec)) {
1.485     albertel 4424: 	$request->print('<span class="LC_warning">'.&mt('Unable to view requested student. ([_1])',$env{'form.student'}).'</span>');
1.324     albertel 4425: 	$request->print(&show_grading_menu_form($symb));
1.103     albertel 4426: 	return;
                   4427:     }
1.398     albertel 4428:     my $result='<h3><span class="LC_info">&nbsp;'.$env{'form.title'}.'</span></h3>';
1.485     albertel 4429:     $result.='<h3>&nbsp;'.&mt('Student: [_1]',&nameUserString(undef,$$fullname{$env{'form.student'}},$uname,$udom)).
1.129     ng       4430: 	'</h3>'."\n";
1.500     albertel 4431:     $env{'form.CODE'} = uc($env{'form.CODE'});
1.501     foxr     4432:     if (&Apache::lonnet::validCODE(uc($env{'form.CODE'}))) {
1.485     albertel 4433: 	$result.='<h3>&nbsp;'.&mt('CODE: [_1]',$env{'form.CODE'}).'</h3>'."\n";
1.382     albertel 4434:     } else {
                   4435: 	delete($env{'form.CODE'});
                   4436:     }
1.71      ng       4437:     &sub_page_js($request);
                   4438:     $request->print($result);
                   4439: 
1.132     bowersj2 4440:     my $navmap = Apache::lonnavmaps::navmap->new();
1.582     raeburn  4441:     unless (ref($navmap)) {
                   4442:         $request->print(&navmap_errormsg());
                   4443:         $request->print(&show_grading_menu_form($symb));
                   4444:         return;
                   4445:     }
1.257     albertel 4446:     my ($mapUrl, $id, $resUrl)=&Apache::lonnet::decode_symb($env{'form.page'});
1.68      ng       4447:     my $map = $navmap->getResourceByUrl($resUrl); # add to navmaps
1.288     albertel 4448:     if (!$map) {
1.485     albertel 4449: 	$request->print('<span class="LC_warning">'.&mt('Unable to view requested sequence. ([_1])',$resUrl).'</span>');
1.324     albertel 4450: 	$request->print(&show_grading_menu_form($symb));
1.288     albertel 4451: 	return; 
                   4452:     }
1.68      ng       4453:     my $iterator = $navmap->getIterator($map->map_start(),
                   4454: 					$map->map_finish());
                   4455: 
1.71      ng       4456:     my $studentTable='<form action="/adm/grades" method="post" name="gradePage">'."\n".
1.72      ng       4457: 	'<input type="hidden" name="command" value="gradeByPage" />'."\n".
1.257     albertel 4458: 	'<input type="hidden" name="fullname" value="'.$$fullname{$env{'form.student'}}.'" />'."\n".
                   4459: 	'<input type="hidden" name="student" value="'.$env{'form.student'}.'" />'."\n".
1.72      ng       4460: 	'<input type="hidden" name="page"    value="'.$pageTitle.'" />'."\n".
1.257     albertel 4461: 	'<input type="hidden" name="title"   value="'.$env{'form.title'}.'" />'."\n".
1.418     albertel 4462: 	'<input type="hidden" name="symb"    value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
1.125     ng       4463: 	'<input type="hidden" name="overRideScore" value="no" />'."\n".
1.257     albertel 4464: 	'<input type="hidden" name="saveState" value="'.$env{'form.saveState'}.'" />'."\n";
1.71      ng       4465: 
1.382     albertel 4466:     if (defined($env{'form.CODE'})) {
                   4467: 	$studentTable.=
                   4468: 	    '<input type="hidden" name="CODE" value="'.$env{'form.CODE'}.'" />'."\n";
                   4469:     }
1.381     albertel 4470:     my $checkIcon = '<img alt="'.&mt('Check Mark').
1.485     albertel 4471: 	'" src="'.&Apache::loncommon::lonhttpdurl($request->dir_config('lonIconsURL').'/check.gif').'" height="16" border="0" />';
1.71      ng       4472: 
1.594     bisitz   4473:     $studentTable.='&nbsp;<span class="LC_info">'.
                   4474:         &mt('Problems graded correct by the computer are marked with a [_1] symbol.',$checkIcon).
                   4475:         '</span>'."\n".
1.484     albertel 4476: 	&Apache::loncommon::start_data_table().
                   4477: 	&Apache::loncommon::start_data_table_header_row().
                   4478: 	'<th align="center">&nbsp;Prob.&nbsp;</th>'.
1.485     albertel 4479: 	'<th>&nbsp;'.($env{'form.vProb'} eq 'no' ? &mt('Title') : &mt('Problem Text')).'/'.&mt('Grade').'</th>'.
1.484     albertel 4480: 	&Apache::loncommon::end_data_table_header_row();
1.71      ng       4481: 
1.329     albertel 4482:     &Apache::lonxml::clear_problem_counter();
1.196     albertel 4483:     my ($depth,$question,$prob) = (1,1,1);
1.68      ng       4484:     $iterator->next(); # skip the first BEGIN_MAP
                   4485:     my $curRes = $iterator->next(); # for "current resource"
1.101     albertel 4486:     while ($depth > 0) {
1.68      ng       4487:         if($curRes == $iterator->BEGIN_MAP) { $depth++; }
1.100     bowersj2 4488:         if($curRes == $iterator->END_MAP) { $depth--; }
1.68      ng       4489: 
1.385     albertel 4490:         if (ref($curRes) && $curRes->is_problem()) {
1.91      albertel 4491: 	    my $parts = $curRes->parts();
1.68      ng       4492:             my $title = $curRes->compTitle();
1.71      ng       4493: 	    my $symbx = $curRes->symb();
1.484     albertel 4494: 	    $studentTable.=
                   4495: 		&Apache::loncommon::start_data_table_row().
                   4496: 		'<td align="center" valign="top" >'.$prob.
1.485     albertel 4497: 		(scalar(@{$parts}) == 1 ? '' 
                   4498: 		                        : '<br />('.&mt('[_1]&nbsp;parts)',
                   4499: 							scalar(@{$parts}))
                   4500: 		 ).
                   4501: 		 '</td>';
1.71      ng       4502: 	    $studentTable.='<td valign="top">';
1.382     albertel 4503: 	    my %form = ('CODE' => $env{'form.CODE'},);
1.257     albertel 4504: 	    if ($env{'form.vProb'} eq 'yes' ) {
1.144     albertel 4505: 		$studentTable.=&show_problem($request,$symbx,$uname,$udom,1,
1.383     albertel 4506: 					     undef,'both',\%form);
1.71      ng       4507: 	    } else {
1.382     albertel 4508: 		my $companswer = &Apache::loncommon::get_student_answers($symbx,$uname,$udom,$env{'request.course.id'},%form);
1.80      ng       4509: 		$companswer =~ s|<form(.*?)>||g;
                   4510: 		$companswer =~ s|</form>||g;
1.71      ng       4511: #		while ($companswer =~ /(<a href\=\"javascript:newWindow.*?Script Vars<\/a>)/s) { #<a href="javascript:newWindow</a>
1.116     ng       4512: #		    $companswer =~ s/$1/ /ms;
1.326     albertel 4513: #		    $request->print('match='.$1."<br />\n");
1.71      ng       4514: #		}
1.116     ng       4515: #		$companswer =~ s|<table border=\"1\">|<table border=\"0\">|g;
1.539     riegler  4516: 		$studentTable.='&nbsp;<b>'.$title.'</b>&nbsp;<br />&nbsp;<b>'.&mt('Correct answer').':</b><br />'.$companswer;
1.71      ng       4517: 	    }
                   4518: 
1.257     albertel 4519: 	    my %record = &Apache::lonnet::restore($symbx,$env{'request.course.id'},$udom,$uname);
1.125     ng       4520: 
1.257     albertel 4521: 	    if ($env{'form.lastSub'} eq 'datesub') {
1.71      ng       4522: 		if ($record{'version'} eq '') {
1.485     albertel 4523: 		    $studentTable.='<br />&nbsp;<span class="LC_warning">'.&mt('No recorded submission for this problem.').'</span><br />';
1.71      ng       4524: 		} else {
1.116     ng       4525: 		    my %responseType = ();
                   4526: 		    foreach my $partid (@{$parts}) {
1.147     albertel 4527: 			my @responseIds =$curRes->responseIds($partid);
                   4528: 			my @responseType =$curRes->responseType($partid);
                   4529: 			my %responseIds;
                   4530: 			for (my $i=0;$i<=$#responseIds;$i++) {
                   4531: 			    $responseIds{$responseIds[$i]}=$responseType[$i];
                   4532: 			}
                   4533: 			$responseType{$partid} = \%responseIds;
1.116     ng       4534: 		    }
1.148     albertel 4535: 		    $studentTable.= &displaySubByDates($symbx,\%record,$parts,\%responseType,$checkIcon,$uname,$udom);
1.147     albertel 4536: 
1.71      ng       4537: 		}
1.257     albertel 4538: 	    } elsif ($env{'form.lastSub'} eq 'all') {
                   4539: 		my $last = ($env{'form.lastSub'} eq 'last' ? 'last' : '');
1.71      ng       4540: 		$studentTable.=&Apache::loncommon::get_previous_attempt($symbx,$uname,$udom,
1.257     albertel 4541: 									$env{'request.course.id'},
1.71      ng       4542: 									'','.submission');
                   4543:  
                   4544: 	    }
1.103     albertel 4545: 	    if (&canmodify($usec)) {
1.585     bisitz   4546:             $studentTable.=&gradeBox_start();
1.103     albertel 4547: 		foreach my $partid (@{$parts}) {
                   4548: 		    $studentTable.=&gradeBox($request,$symbx,$uname,$udom,$question,$partid,\%record);
                   4549: 		    $studentTable.='<input type="hidden" name="q_'.$question.'" value="'.$partid.'" />'."\n";
                   4550: 		    $question++;
                   4551: 		}
1.585     bisitz   4552:             $studentTable.=&gradeBox_end();
1.196     albertel 4553: 		$prob++;
1.71      ng       4554: 	    }
                   4555: 	    $studentTable.='</td></tr>';
1.68      ng       4556: 
1.103     albertel 4557: 	}
1.68      ng       4558:         $curRes = $iterator->next();
                   4559:     }
                   4560: 
1.589     bisitz   4561:     $studentTable.=
                   4562:         '</table>'."\n".
                   4563:         '<input type="button" value="'.&mt('Save').'" '.
                   4564:         'onclick="javascript:checkSubmitPage(this.form,'.$question.');" />'.
                   4565:         '</form>'."\n";
1.324     albertel 4566:     $studentTable.=&show_grading_menu_form($symb);
1.71      ng       4567:     $request->print($studentTable);
                   4568: 
                   4569:     return '';
1.119     ng       4570: }
                   4571: 
                   4572: sub displaySubByDates {
1.148     albertel 4573:     my ($symb,$record,$parts,$responseType,$checkIcon,$uname,$udom) = @_;
1.224     albertel 4574:     my $isCODE=0;
1.335     albertel 4575:     my $isTask = ($symb =~/\.task$/);
1.224     albertel 4576:     if (exists($record->{'resource.CODE'})) { $isCODE=1; }
1.467     albertel 4577:     my $studentTable=&Apache::loncommon::start_data_table().
                   4578: 	&Apache::loncommon::start_data_table_header_row().
                   4579: 	'<th>'.&mt('Date/Time').'</th>'.
                   4580: 	($isCODE?'<th>'.&mt('CODE').'</th>':'').
                   4581: 	'<th>'.&mt('Submission').'</th>'.
                   4582: 	'<th>'.&mt('Status').'</th>'.
                   4583: 	&Apache::loncommon::end_data_table_header_row();
1.119     ng       4584:     my ($version);
                   4585:     my %mark;
1.148     albertel 4586:     my %orders;
1.119     ng       4587:     $mark{'correct_by_student'} = $checkIcon;
1.147     albertel 4588:     if (!exists($$record{'1:timestamp'})) {
1.539     riegler  4589: 	return '<br />&nbsp;<span class="LC_warning">'.&mt('Nothing submitted - no attempts.').'</span><br />';
1.147     albertel 4590:     }
1.335     albertel 4591: 
                   4592:     my $interaction;
1.525     raeburn  4593:     my $no_increment = 1;
1.119     ng       4594:     for ($version=1;$version<=$$record{'version'};$version++) {
1.467     albertel 4595: 	my $timestamp = 
                   4596: 	    &Apache::lonlocal::locallocaltime($$record{$version.':timestamp'});
1.335     albertel 4597: 	if (exists($$record{$version.':resource.0.version'})) {
                   4598: 	    $interaction = $$record{$version.':resource.0.version'};
                   4599: 	}
                   4600: 
                   4601: 	my $where = ($isTask ? "$version:resource.$interaction"
                   4602: 		             : "$version:resource");
1.467     albertel 4603: 	$studentTable.=&Apache::loncommon::start_data_table_row().
                   4604: 	    '<td>'.$timestamp.'</td>';
1.224     albertel 4605: 	if ($isCODE) {
                   4606: 	    $studentTable.='<td>'.$record->{$version.':resource.CODE'}.'</td>';
                   4607: 	}
1.119     ng       4608: 	my @versionKeys = split(/\:/,$$record{$version.':keys'});
                   4609: 	my @displaySub = ();
                   4610: 	foreach my $partid (@{$parts}) {
1.596     raeburn  4611:             my $hidden;
                   4612:             if (($$record{$version.':resource.'.$partid.'.type'} eq 'anonsurvey') ||
                   4613:                 ($$record{$version.':resource.'.$partid.'.type'} eq 'anonsurveycred')) {
                   4614:                 $hidden = 1;
                   4615:             }
1.335     albertel 4616: 	    my @matchKey = ($isTask ? sort(grep /^resource\.\d+\.\Q$partid\E\.award$/,@versionKeys)
                   4617: 			            : sort(grep /^resource\.\Q$partid\E\..*?\.submission$/,@versionKeys));
                   4618: 	    
1.122     ng       4619: #	    next if ($$record{"$version:resource.$partid.solved"} eq '');
1.324     albertel 4620: 	    my $display_part=&get_display_part($partid,$symb);
1.147     albertel 4621: 	    foreach my $matchKey (@matchKey) {
1.198     albertel 4622: 		if (exists($$record{$version.':'.$matchKey}) &&
                   4623: 		    $$record{$version.':'.$matchKey} ne '') {
1.596     raeburn  4624:                     
1.335     albertel 4625: 		    my ($responseId)= ($isTask ? ($matchKey=~ /^resource\.(.*?)\.\Q$partid\E\.award$/)
                   4626: 				               : ($matchKey=~ /^resource\.\Q$partid\E\.(.*?)\.submission$/));
1.577     bisitz   4627:                     $displaySub[0].='<span class="LC_nobreak"';
                   4628:                     $displaySub[0].='<b>'.&mt('Part: [_1]',$display_part).'</b>'
                   4629:                                    .' <span class="LC_internal_info">'
                   4630:                                    .'('.&mt('Part ID: [_1]',$responseId).')'
                   4631:                                    .'</span>'
                   4632:                                    .' <b>';
1.596     raeburn  4633:                     if ($hidden) {
                   4634:                         $displaySub[0].= &mt('Anonymous Survey').'</b>';
                   4635:                     } else {
                   4636: 		        if ($$record{"$where.$partid.tries"} eq '') {
                   4637: 			    $displaySub[0].=&mt('Trial not counted');
                   4638: 		        } else {
                   4639: 			    $displaySub[0].=&mt('Trial: [_1]',
1.467     albertel 4640: 					    $$record{"$where.$partid.tries"});
1.596     raeburn  4641: 		        }
                   4642: 		        my $responseType=($isTask ? 'Task'
1.335     albertel 4643:                                               : $responseType->{$partid}->{$responseId});
1.596     raeburn  4644: 		        if (!exists($orders{$partid})) { $orders{$partid}={}; }
                   4645: 		        if (!exists($orders{$partid}->{$responseId})) {
                   4646: 			    $orders{$partid}->{$responseId}=
                   4647: 			        &get_order($partid,$responseId,$symb,$uname,$udom,
                   4648:                                            $no_increment);
                   4649: 		        }
                   4650: 		        $displaySub[0].='</b></span>'; # /nobreak
                   4651: 		        $displaySub[0].='&nbsp; '.
                   4652: 			    &cleanRecord($$record{$version.':'.$matchKey},$responseType,$symb,$partid,$responseId,$record,$orders{$partid}->{$responseId},"$version:",$uname,$udom).'<br />';
                   4653:                     }
1.147     albertel 4654: 		}
                   4655: 	    }
1.335     albertel 4656: 	    if (exists($$record{"$where.$partid.checkedin"})) {
1.485     albertel 4657: 		$displaySub[1].=&mt('Checked in by [_1] into slot [_2]',
                   4658: 				    $$record{"$where.$partid.checkedin"},
                   4659: 				    $$record{"$where.$partid.checkedin.slot"}).
                   4660: 					'<br />';
1.335     albertel 4661: 	    }
                   4662: 	    if (exists $$record{"$where.$partid.award"}) {
1.485     albertel 4663: 		$displaySub[1].='<b>'.&mt('Part:').'</b>&nbsp;'.$display_part.' &nbsp;'.
1.335     albertel 4664: 		    lc($$record{"$where.$partid.award"}).' '.
                   4665: 		    $mark{$$record{"$where.$partid.solved"}}.
1.147     albertel 4666: 		    '<br />';
                   4667: 	    }
1.335     albertel 4668: 	    if (exists $$record{"$where.$partid.regrader"}) {
                   4669: 		$displaySub[2].=$$record{"$where.$partid.regrader"}.
                   4670: 		    ' (<b>'.&mt('Part').':</b> '.$display_part.')';
                   4671: 	    } elsif ($$record{"$version:resource.$partid.regrader"} =~ /\S/) {
                   4672: 		$displaySub[2].=
                   4673: 		    $$record{"$version:resource.$partid.regrader"}.
1.207     albertel 4674: 		    ' (<b>'.&mt('Part').':</b> '.$display_part.')';
1.147     albertel 4675: 	    }
                   4676: 	}
                   4677: 	# needed because old essay regrader has not parts info
                   4678: 	if (exists $$record{"$version:resource.regrader"}) {
                   4679: 	    $displaySub[2].=$$record{"$version:resource.regrader"};
                   4680: 	}
                   4681: 	$studentTable.='<td>'.$displaySub[0].'&nbsp;</td><td>'.$displaySub[1];
                   4682: 	if ($displaySub[2]) {
1.467     albertel 4683: 	    $studentTable.=&mt('Manually graded by [_1]',$displaySub[2]);
1.147     albertel 4684: 	}
1.467     albertel 4685: 	$studentTable.='&nbsp;</td>'.
                   4686: 	    &Apache::loncommon::end_data_table_row();
1.119     ng       4687:     }
1.467     albertel 4688:     $studentTable.=&Apache::loncommon::end_data_table();
1.119     ng       4689:     return $studentTable;
1.71      ng       4690: }
                   4691: 
                   4692: sub updateGradeByPage {
                   4693:     my ($request) = shift;
                   4694: 
1.257     albertel 4695:     my $cdom      = $env{"course.$env{'request.course.id'}.domain"};
                   4696:     my $cnum      = $env{"course.$env{'request.course.id'}.num"};
                   4697:     my $getsec    = $env{'form.section'} eq '' ? 'all' : $env{'form.section'};
                   4698:     my $pageTitle = $env{'form.page'};
1.103     albertel 4699:     my ($classlist,undef,$fullname) = &getclasslist($getsec,'1');
1.257     albertel 4700:     my ($uname,$udom) = split(/:/,$env{'form.student'});
                   4701:     my $usec=$classlist->{$env{'form.student'}}[5];
1.103     albertel 4702:     if (!&canmodify($usec)) {
1.526     raeburn  4703: 	$request->print('<span class="LC_warning">'.&mt('Unable to modify requested student ([_1])',$env{'form.student'}).'</span>');
1.324     albertel 4704: 	$request->print(&show_grading_menu_form($env{'form.symb'}));
1.103     albertel 4705: 	return;
                   4706:     }
1.398     albertel 4707:     my $result='<h3><span class="LC_info">&nbsp;'.$env{'form.title'}.'</span></h3>';
1.526     raeburn  4708:     $result.='<h3>&nbsp;'.&mt('Student: ').&nameUserString(undef,$env{'form.fullname'},$uname,$udom).
1.129     ng       4709: 	'</h3>'."\n";
1.70      ng       4710: 
1.68      ng       4711:     $request->print($result);
                   4712: 
1.582     raeburn  4713: 
1.132     bowersj2 4714:     my $navmap = Apache::lonnavmaps::navmap->new();
1.582     raeburn  4715:     unless (ref($navmap)) {
                   4716:         $request->print(&navmap_errormsg());
                   4717:         return;
                   4718:     }
1.257     albertel 4719:     my ($mapUrl, $id, $resUrl) = &Apache::lonnet::decode_symb( $env{'form.page'});
1.71      ng       4720:     my $map = $navmap->getResourceByUrl($resUrl); # add to navmaps
1.288     albertel 4721:     if (!$map) {
1.527     raeburn  4722: 	$request->print('<span class="LC_warning">'.&mt('Unable to grade requested sequence ([_1]).',$resUrl).'</span>');
1.324     albertel 4723: 	my ($symb)=&get_symb($request);
                   4724: 	$request->print(&show_grading_menu_form($symb));
1.288     albertel 4725: 	return; 
                   4726:     }
1.71      ng       4727:     my $iterator = $navmap->getIterator($map->map_start(),
                   4728: 					$map->map_finish());
1.70      ng       4729: 
1.484     albertel 4730:     my $studentTable=
                   4731: 	&Apache::loncommon::start_data_table().
                   4732: 	&Apache::loncommon::start_data_table_header_row().
1.485     albertel 4733: 	'<th align="center">&nbsp;'.&mt('Prob.').'&nbsp;</th>'.
                   4734: 	'<th>&nbsp;'.&mt('Title').'&nbsp;</th>'.
                   4735: 	'<th>&nbsp;'.&mt('Previous Score').'&nbsp;</th>'.
                   4736: 	'<th>&nbsp;'.&mt('New Score').'&nbsp;</th>'.
1.484     albertel 4737: 	&Apache::loncommon::end_data_table_header_row();
1.71      ng       4738: 
                   4739:     $iterator->next(); # skip the first BEGIN_MAP
                   4740:     my $curRes = $iterator->next(); # for "current resource"
1.196     albertel 4741:     my ($depth,$question,$prob,$changeflag)= (1,1,1,0);
1.101     albertel 4742:     while ($depth > 0) {
1.71      ng       4743:         if($curRes == $iterator->BEGIN_MAP) { $depth++; }
1.100     bowersj2 4744:         if($curRes == $iterator->END_MAP) { $depth--; }
1.71      ng       4745: 
1.385     albertel 4746:         if (ref($curRes) && $curRes->is_problem()) {
1.91      albertel 4747: 	    my $parts = $curRes->parts();
1.71      ng       4748:             my $title = $curRes->compTitle();
                   4749: 	    my $symbx = $curRes->symb();
1.484     albertel 4750: 	    $studentTable.=
                   4751: 		&Apache::loncommon::start_data_table_row().
                   4752: 		'<td align="center" valign="top" >'.$prob.
1.485     albertel 4753: 		(scalar(@{$parts}) == 1 ? '' 
1.526     raeburn  4754:                                         : '<br />('.&mt('[quant,_1,&nbsp;part]',scalar(@{$parts}))
                   4755: 		.')').'</td>';
1.71      ng       4756: 	    $studentTable.='<td valign="top">&nbsp;<b>'.$title.'</b>&nbsp;</td>';
                   4757: 
                   4758: 	    my %newrecord=();
                   4759: 	    my @displayPts=();
1.269     raeburn  4760:             my %aggregate = ();
                   4761:             my $aggregateflag = 0;
1.71      ng       4762: 	    foreach my $partid (@{$parts}) {
1.257     albertel 4763: 		my $newpts = $env{'form.GD_BOX'.$question.'_'.$partid};
                   4764: 		my $oldpts = $env{'form.oldpts'.$question.'_'.$partid};
1.71      ng       4765: 
1.257     albertel 4766: 		my $wgt = $env{'form.WGT'.$question.'_'.$partid} != 0 ? 
                   4767: 		    $env{'form.WGT'.$question.'_'.$partid} : 1;
1.71      ng       4768: 		my $partial = $newpts/$wgt;
                   4769: 		my $score;
                   4770: 		if ($partial > 0) {
                   4771: 		    $score = 'correct_by_override';
1.125     ng       4772: 		} elsif ($newpts ne '') { #empty is taken as 0
1.71      ng       4773: 		    $score = 'incorrect_by_override';
                   4774: 		}
1.257     albertel 4775: 		my $dropMenu = $env{'form.GD_SEL'.$question.'_'.$partid};
1.125     ng       4776: 		if ($dropMenu eq 'excused') {
1.71      ng       4777: 		    $partial = '';
                   4778: 		    $score = 'excused';
1.125     ng       4779: 		} elsif ($dropMenu eq 'reset status'
1.257     albertel 4780: 			 && $env{'form.solved'.$question.'_'.$partid} ne '') { #update only if previous record exists
1.125     ng       4781: 		    $newrecord{'resource.'.$partid.'.tries'} = 0;
                   4782: 		    $newrecord{'resource.'.$partid.'.solved'} = '';
                   4783: 		    $newrecord{'resource.'.$partid.'.award'} = '';
                   4784: 		    $newrecord{'resource.'.$partid.'.awarded'} = 0;
1.257     albertel 4785: 		    $newrecord{'resource.'.$partid.'.regrader'} = "$env{'user.name'}:$env{'user.domain'}";
1.125     ng       4786: 		    $changeflag++;
                   4787: 		    $newpts = '';
1.269     raeburn  4788:                     
                   4789:                     my $aggtries =  $env{'form.aggtries'.$question.'_'.$partid};
                   4790:                     my $totaltries = $env{'form.totaltries'.$question.'_'.$partid};
                   4791:                     my $solvedstatus = $env{'form.solved'.$question.'_'.$partid};
                   4792:                     if ($aggtries > 0) {
                   4793:                         &decrement_aggs($symbx,$partid,\%aggregate,$aggtries,$totaltries,$solvedstatus);
                   4794:                         $aggregateflag = 1;
                   4795:                     }
1.71      ng       4796: 		}
1.324     albertel 4797: 		my $display_part=&get_display_part($partid,$curRes->symb());
1.257     albertel 4798: 		my $oldstatus = $env{'form.solved'.$question.'_'.$partid};
1.526     raeburn  4799: 		$displayPts[0].='&nbsp;<b>'.&mt('Part').':</b> '.$display_part.' = '.
1.71      ng       4800: 		    (($oldstatus eq 'excused') ? 'excused' : $oldpts).
1.326     albertel 4801: 		    '&nbsp;<br />';
1.526     raeburn  4802: 		$displayPts[1].='&nbsp;<b>'.&mt('Part').':</b> '.$display_part.' = '.
1.125     ng       4803: 		     (($score eq 'excused') ? 'excused' : $newpts).
1.326     albertel 4804: 		    '&nbsp;<br />';
1.71      ng       4805: 		$question++;
1.380     albertel 4806: 		next if ($dropMenu eq 'reset status' || ($newpts eq $oldpts && $score ne 'excused'));
1.125     ng       4807: 
1.71      ng       4808: 		$newrecord{'resource.'.$partid.'.awarded'}  = $partial if $partial ne '';
1.125     ng       4809: 		$newrecord{'resource.'.$partid.'.solved'}   = $score if $score ne '';
1.257     albertel 4810: 		$newrecord{'resource.'.$partid.'.regrader'} = "$env{'user.name'}:$env{'user.domain'}"
1.125     ng       4811: 		    if (scalar(keys(%newrecord)) > 0);
1.71      ng       4812: 
                   4813: 		$changeflag++;
                   4814: 	    }
                   4815: 	    if (scalar(keys(%newrecord)) > 0) {
1.382     albertel 4816: 		my %record = 
                   4817: 		    &Apache::lonnet::restore($symbx,$env{'request.course.id'},
                   4818: 					     $udom,$uname);
                   4819: 
                   4820: 		if (&Apache::lonnet::validCODE($env{'form.CODE'})) {
                   4821: 		    $newrecord{'resource.CODE'} = $env{'form.CODE'};
                   4822: 		} elsif (&Apache::lonnet::validCODE($record{'resource.CODE'})) {
                   4823: 		    $newrecord{'resource.CODE'} = '';
                   4824: 		}
1.257     albertel 4825: 		&Apache::lonnet::cstore(\%newrecord,$symbx,$env{'request.course.id'},
1.71      ng       4826: 					$udom,$uname);
1.382     albertel 4827: 		%record = &Apache::lonnet::restore($symbx,
                   4828: 						   $env{'request.course.id'},
                   4829: 						   $udom,$uname);
1.380     albertel 4830: 		&check_and_remove_from_queue($parts,\%record,undef,$symbx,
                   4831: 					     $cdom,$cnum,$udom,$uname);
1.71      ng       4832: 	    }
1.380     albertel 4833: 	    
1.269     raeburn  4834:             if ($aggregateflag) {
                   4835:                 &Apache::lonnet::cinc('nohist_resourcetracker',\%aggregate,
                   4836:                       $env{'course.'.$env{'request.course.id'}.'.domain'},
                   4837:                       $env{'course.'.$env{'request.course.id'}.'.num'});
                   4838:             }
1.125     ng       4839: 
1.71      ng       4840: 	    $studentTable.='<td valign="top">'.$displayPts[0].'</td>'.
                   4841: 		'<td valign="top">'.$displayPts[1].'</td>'.
1.484     albertel 4842: 		&Apache::loncommon::end_data_table_row();
1.68      ng       4843: 
1.196     albertel 4844: 	    $prob++;
1.68      ng       4845: 	}
1.71      ng       4846:         $curRes = $iterator->next();
1.68      ng       4847:     }
1.98      albertel 4848: 
1.484     albertel 4849:     $studentTable.=&Apache::loncommon::end_data_table();
1.324     albertel 4850:     $studentTable.=&show_grading_menu_form($env{'form.symb'});
1.526     raeburn  4851:     my $grademsg=($changeflag == 0 ? &mt('No score was changed or updated.') :
                   4852: 		  &mt('The scores were changed for [quant,_1,problem].',
                   4853: 		  $changeflag));
1.76      ng       4854:     $request->print($grademsg.$studentTable);
1.68      ng       4855: 
1.70      ng       4856:     return '';
                   4857: }
                   4858: 
1.72      ng       4859: #-------- end of section for handling grading by page/sequence ---------
                   4860: #
                   4861: #-------------------------------------------------------------------
                   4862: 
1.581     www      4863: #-------------------- Bubblesheet (Scantron) Grading -------------------
1.75      albertel 4864: #
                   4865: #------ start of section for handling grading by page/sequence ---------
                   4866: 
1.423     albertel 4867: =pod
                   4868: 
                   4869: =head1 Bubble sheet grading routines
                   4870: 
1.424     albertel 4871:   For this documentation:
                   4872: 
                   4873:    'scanline' refers to the full line of characters
                   4874:    from the file that we are parsing that represents one entire sheet
                   4875: 
                   4876:    'bubble line' refers to the data
                   4877:    representing the line of bubbles that are on the physical bubble sheet
                   4878: 
                   4879: 
                   4880: The overall process is that a scanned in bubble sheet data is uploaded
                   4881: into a course. When a user wants to grade, they select a
                   4882: sequence/folder of resources, a file of bubble sheet info, and pick
                   4883: one of the predefined configurations for what each scanline looks
                   4884: like.
                   4885: 
                   4886: Next each scanline is checked for any errors of either 'missing
1.435     foxr     4887: bubbles' (it's an error because it may have been mis-scanned
1.424     albertel 4888: because too light bubbling), 'double bubble' (each bubble line should
                   4889: have no more that one letter picked), invalid or duplicated CODE,
1.556     weissno  4890: invalid student/employee ID
1.424     albertel 4891: 
                   4892: If the CODE option is used that determines the randomization of the
1.556     weissno  4893: homework problems, either way the student/employee ID is looked up into a
1.424     albertel 4894: username:domain.
                   4895: 
                   4896: During the validation phase the instructor can choose to skip scanlines. 
                   4897: 
1.435     foxr     4898: After the validation phase, there are now 3 bubble sheet files
1.424     albertel 4899: 
                   4900:   scantron_original_filename (unmodified original file)
                   4901:   scantron_corrected_filename (file where the corrected information has replaced the original information)
                   4902:   scantron_skipped_filename (contains the exact text of scanlines that where skipped)
                   4903: 
                   4904: Also there is a separate hash nohist_scantrondata that contains extra
                   4905: correction information that isn't representable in the bubble sheet
                   4906: file (see &scantron_getfile() for more information)
                   4907: 
                   4908: After all scanlines are either valid, marked as valid or skipped, then
                   4909: foreach line foreach problem in the picked sequence, an ssi request is
                   4910: made that simulates a user submitting their selected letter(s) against
                   4911: the homework problem.
1.423     albertel 4912: 
                   4913: =over 4
                   4914: 
                   4915: 
                   4916: 
                   4917: =item defaultFormData
                   4918: 
                   4919:   Returns html hidden inputs used to hold context/default values.
                   4920: 
                   4921:  Arguments:
                   4922:   $symb - $symb of the current resource 
                   4923: 
                   4924: =cut
1.422     foxr     4925: 
1.81      albertel 4926: sub defaultFormData {
1.324     albertel 4927:     my ($symb)=@_;
1.447     foxr     4928:     return '<input type="hidden" name="symb"    value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
1.257     albertel 4929:      '<input type="hidden" name="saveState" value="'.$env{'form.saveState'}.'" />'."\n".
                   4930:      '<input type="hidden" name="probTitle" value="'.$env{'form.probTitle'}.'" />'."\n";
1.81      albertel 4931: }
                   4932: 
1.447     foxr     4933: 
1.423     albertel 4934: =pod 
                   4935: 
                   4936: =item getSequenceDropDown
                   4937: 
                   4938:    Return html dropdown of possible sequences to grade
                   4939:  
                   4940:  Arguments:
1.582     raeburn  4941:    $symb - $symb of the current resource
                   4942:    $map_error - ref to scalar which will container error if
                   4943:                 $navmap object is unavailable in &getSymbMap().
1.423     albertel 4944: 
                   4945: =cut
1.422     foxr     4946: 
1.75      albertel 4947: sub getSequenceDropDown {
1.582     raeburn  4948:     my ($symb,$map_error)=@_;
1.75      albertel 4949:     my $result='<select name="selectpage">'."\n";
1.582     raeburn  4950:     my ($titles,$symbx) = &getSymbMap($map_error);
                   4951:     if (ref($map_error)) {
                   4952:         return if ($$map_error);
                   4953:     }
1.137     albertel 4954:     my ($curpage)=&Apache::lonnet::decode_symb($symb); 
1.75      albertel 4955:     my $ctr=0;
                   4956:     foreach (@$titles) {
                   4957: 	my ($minder,$showtitle) = ($_ =~ /(\d+)\.(.*)/);
                   4958: 	$result.='<option value="'.$$symbx{$_}.'" '.
1.401     albertel 4959: 	    ($$symbx{$_} =~ /$curpage$/ ? 'selected="selected"' : '').
1.75      albertel 4960: 	    '>'.$showtitle.'</option>'."\n";
                   4961: 	$ctr++;
                   4962:     }
                   4963:     $result.= '</select>';
                   4964:     return $result;
                   4965: }
                   4966: 
1.495     albertel 4967: my %bubble_lines_per_response;     # no. bubble lines for each response.
1.554     raeburn  4968:                                    # key is zero-based index - 0, 1, 2 ...
1.495     albertel 4969: 
                   4970: my %first_bubble_line;             # First bubble line no. for each bubble.
                   4971: 
1.509     raeburn  4972: my %subdivided_bubble_lines;       # no. bubble lines for optionresponse, 
                   4973:                                    # matchresponse or rankresponse, where 
                   4974:                                    # an individual response can have multiple 
                   4975:                                    # lines
1.503     raeburn  4976: 
                   4977: my %responsetype_per_response;     # responsetype for each response
                   4978: 
1.495     albertel 4979: # Save and restore the bubble lines array to the form env.
                   4980: 
                   4981: 
                   4982: sub save_bubble_lines {
                   4983:     foreach my $line (keys(%bubble_lines_per_response)) {
                   4984: 	$env{"form.scantron.bubblelines.$line"}  = $bubble_lines_per_response{$line};
                   4985: 	$env{"form.scantron.first_bubble_line.$line"} =
                   4986: 	    $first_bubble_line{$line};
1.503     raeburn  4987:         $env{"form.scantron.sub_bubblelines.$line"} = 
                   4988:             $subdivided_bubble_lines{$line};
                   4989:         $env{"form.scantron.responsetype.$line"} =
                   4990:             $responsetype_per_response{$line};
1.495     albertel 4991:     }
                   4992: }
                   4993: 
                   4994: 
                   4995: sub restore_bubble_lines {
                   4996:     my $line = 0;
                   4997:     %bubble_lines_per_response = ();
                   4998:     while ($env{"form.scantron.bubblelines.$line"}) {
                   4999: 	my $value = $env{"form.scantron.bubblelines.$line"};
                   5000: 	$bubble_lines_per_response{$line} = $value;
                   5001: 	$first_bubble_line{$line}  =
                   5002: 	    $env{"form.scantron.first_bubble_line.$line"};
1.503     raeburn  5003:         $subdivided_bubble_lines{$line} =
                   5004:             $env{"form.scantron.sub_bubblelines.$line"};
                   5005:         $responsetype_per_response{$line} =
                   5006:             $env{"form.scantron.responsetype.$line"};
1.495     albertel 5007: 	$line++;
                   5008:     }
                   5009: }
                   5010: 
                   5011: #  Given the parsed scanline, get the response for 
                   5012: #  'answer' number n:
                   5013: 
                   5014: sub get_response_bubbles {
                   5015:     my ($parsed_line, $response)  = @_;
                   5016: 
                   5017:     my $bubble_line = $first_bubble_line{$response-1} +1;
                   5018:     my $bubble_lines= $bubble_lines_per_response{$response-1};
                   5019:     
                   5020:     my $selected = "";
                   5021: 
                   5022:     for (my $bline = 0; $bline < $bubble_lines; $bline++) {
                   5023: 	$selected .= $$parsed_line{"scantron.$bubble_line.answer"}.":";
                   5024: 	$bubble_line++;
                   5025:     }
                   5026:     return $selected;
                   5027: }
1.423     albertel 5028: 
                   5029: =pod 
                   5030: 
                   5031: =item scantron_filenames
                   5032: 
                   5033:    Returns a list of the scantron files in the current course 
                   5034: 
                   5035: =cut
1.422     foxr     5036: 
1.202     albertel 5037: sub scantron_filenames {
1.257     albertel 5038:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
                   5039:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
1.517     raeburn  5040:     my $getpropath = 1;
1.157     albertel 5041:     my @files=&Apache::lonnet::dirlist('userfiles',$cdom,$cname,
1.517     raeburn  5042:                                        $getpropath);
1.202     albertel 5043:     my @possiblenames;
1.201     albertel 5044:     foreach my $filename (sort(@files)) {
1.157     albertel 5045: 	($filename)=split(/&/,$filename);
                   5046: 	if ($filename!~/^scantron_orig_/) { next ; }
                   5047: 	$filename=~s/^scantron_orig_//;
1.202     albertel 5048: 	push(@possiblenames,$filename);
                   5049:     }
                   5050:     return @possiblenames;
                   5051: }
                   5052: 
1.423     albertel 5053: =pod 
                   5054: 
                   5055: =item scantron_uploads
                   5056: 
                   5057:    Returns  html drop-down list of scantron files in current course.
                   5058: 
                   5059:  Arguments:
                   5060:    $file2grade - filename to set as selected in the dropdown
                   5061: 
                   5062: =cut
1.422     foxr     5063: 
1.202     albertel 5064: sub scantron_uploads {
1.209     ng       5065:     my ($file2grade) = @_;
1.202     albertel 5066:     my $result=	'<select name="scantron_selectfile">';
                   5067:     $result.="<option></option>";
                   5068:     foreach my $filename (sort(&scantron_filenames())) {
1.401     albertel 5069: 	$result.="<option".($filename eq $file2grade ? ' selected="selected"':'').">$filename</option>\n";
1.81      albertel 5070:     }
                   5071:     $result.="</select>";
                   5072:     return $result;
                   5073: }
                   5074: 
1.423     albertel 5075: =pod 
                   5076: 
                   5077: =item scantron_scantab
                   5078: 
                   5079:   Returns html drop down of the scantron formats in the scantronformat.tab
                   5080:   file.
                   5081: 
                   5082: =cut
1.422     foxr     5083: 
1.82      albertel 5084: sub scantron_scantab {
                   5085:     my $result='<select name="scantron_format">'."\n";
1.191     albertel 5086:     $result.='<option></option>'."\n";
1.518     raeburn  5087:     my @lines = &get_scantronformat_file();
                   5088:     if (@lines > 0) {
                   5089:         foreach my $line (@lines) {
                   5090:             next if (($line =~ /^\#/) || ($line eq ''));
                   5091: 	    my ($name,$descrip)=split(/:/,$line);
                   5092: 	    $result.='<option value="'.$name.'">'.$descrip.'</option>'."\n";
                   5093:         }
1.82      albertel 5094:     }
                   5095:     $result.='</select>'."\n";
1.518     raeburn  5096:     return $result;
                   5097: }
                   5098: 
                   5099: =pod
                   5100: 
                   5101: =item get_scantronformat_file
                   5102: 
                   5103:   Returns an array containing lines from the scantron format file for
                   5104:   the domain of the course.
                   5105: 
                   5106:   If a url for a custom.tab file is listed in domain's configuration.db, 
                   5107:   lines are from this file.
                   5108: 
                   5109:   Otherwise, if a default.tab has been published in RES space by the 
                   5110:   domainconfig user, lines are from this file.
                   5111: 
                   5112:   Otherwise, fall back to getting lines from the legacy file on the
1.519     raeburn  5113:   local server:  /home/httpd/lonTabs/default_scantronformat.tab    
1.82      albertel 5114: 
1.518     raeburn  5115: =cut
                   5116: 
                   5117: sub get_scantronformat_file {
                   5118:     my $cdom= $env{'course.'.$env{'request.course.id'}.'.domain'};
                   5119:     my %domconfig = &Apache::lonnet::get_dom('configuration',['scantron'],$cdom);
                   5120:     my $gottab = 0;
                   5121:     my @lines;
                   5122:     if (ref($domconfig{'scantron'}) eq 'HASH') {
                   5123:         if ($domconfig{'scantron'}{'scantronformat'} ne '') {
                   5124:             my $formatfile = &Apache::lonnet::getfile($Apache::lonnet::perlvar{'lonDocRoot'}.$domconfig{'scantron'}{'scantronformat'});
                   5125:             if ($formatfile ne '-1') {
                   5126:                 @lines = split("\n",$formatfile,-1);
                   5127:                 $gottab = 1;
                   5128:             }
                   5129:         }
                   5130:     }
                   5131:     if (!$gottab) {
                   5132:         my $confname = $cdom.'-domainconfig';
                   5133:         my $default = $Apache::lonnet::perlvar{'lonDocRoot'}.'/res/'.$cdom.'/'.$confname.'/default.tab';
                   5134:         my $formatfile =  &Apache::lonnet::getfile($default);
                   5135:         if ($formatfile ne '-1') {
                   5136:             @lines = split("\n",$formatfile,-1);
                   5137:             $gottab = 1;
                   5138:         }
                   5139:     }
                   5140:     if (!$gottab) {
1.519     raeburn  5141:         my @domains = &Apache::lonnet::current_machine_domains();
                   5142:         if (grep(/^\Q$cdom\E$/,@domains)) {
                   5143:             my $fh=Apache::File->new($Apache::lonnet::perlvar{'lonTabDir'}.'/scantronformat.tab');
                   5144:             @lines = <$fh>;
                   5145:             close($fh);
                   5146:         } else {
                   5147:             my $fh=Apache::File->new($Apache::lonnet::perlvar{'lonTabDir'}.'/default_scantronformat.tab');
                   5148:             @lines = <$fh>;
                   5149:             close($fh);
                   5150:         }
1.518     raeburn  5151:     }
                   5152:     return @lines;
1.82      albertel 5153: }
                   5154: 
1.423     albertel 5155: =pod 
                   5156: 
                   5157: =item scantron_CODElist
                   5158: 
                   5159:   Returns html drop down of the saved CODE lists from current course,
                   5160:   generated from earlier printings.
                   5161: 
                   5162: =cut
1.422     foxr     5163: 
1.186     albertel 5164: sub scantron_CODElist {
1.257     albertel 5165:     my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   5166:     my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
1.186     albertel 5167:     my @names=&Apache::lonnet::getkeys('CODEs',$cdom,$cnum);
                   5168:     my $namechoice='<option></option>';
1.225     albertel 5169:     foreach my $name (sort {uc($a) cmp uc($b)} @names) {
1.191     albertel 5170: 	if ($name =~ /^error: 2 /) { next; }
1.278     albertel 5171: 	if ($name =~ /^type\0/) { next; }
1.186     albertel 5172: 	$namechoice.='<option value="'.$name.'">'.$name.'</option>';
                   5173:     }
                   5174:     $namechoice='<select name="scantron_CODElist">'.$namechoice.'</select>';
                   5175:     return $namechoice;
                   5176: }
                   5177: 
1.423     albertel 5178: =pod 
                   5179: 
                   5180: =item scantron_CODEunique
                   5181: 
                   5182:   Returns the html for "Each CODE to be used once" radio.
                   5183: 
                   5184: =cut
1.422     foxr     5185: 
1.186     albertel 5186: sub scantron_CODEunique {
1.532     bisitz   5187:     my $result='<span class="LC_nobreak">
1.272     albertel 5188:                  <label><input type="radio" name="scantron_CODEunique"
1.423     albertel 5189:                         value="yes" checked="checked" />'.&mt('Yes').' </label>
1.381     albertel 5190:                 </span>
1.532     bisitz   5191:                 <span class="LC_nobreak">
1.272     albertel 5192:                  <label><input type="radio" name="scantron_CODEunique"
1.423     albertel 5193:                         value="no" />'.&mt('No').' </label>
1.381     albertel 5194:                 </span>';
1.186     albertel 5195:     return $result;
                   5196: }
1.423     albertel 5197: 
                   5198: =pod 
                   5199: 
                   5200: =item scantron_selectphase
                   5201: 
                   5202:   Generates the initial screen to start the bubble sheet process.
                   5203:   Allows for - starting a grading run.
1.424     albertel 5204:              - downloading existing scan data (original, corrected
1.423     albertel 5205:                                                 or skipped info)
                   5206: 
                   5207:              - uploading new scan data
                   5208: 
                   5209:  Arguments:
                   5210:   $r          - The Apache request object
                   5211:   $file2grade - name of the file that contain the scanned data to score
                   5212: 
                   5213: =cut
1.186     albertel 5214: 
1.75      albertel 5215: sub scantron_selectphase {
1.209     ng       5216:     my ($r,$file2grade) = @_;
1.324     albertel 5217:     my ($symb)=&get_symb($r);
1.75      albertel 5218:     if (!$symb) {return '';}
1.582     raeburn  5219:     my $map_error;
                   5220:     my $sequence_selector=&getSequenceDropDown($symb,\$map_error);
                   5221:     if ($map_error) {
                   5222:         $r->print('<br />'.&navmap_errormsg().'<br />');
                   5223:         return;
                   5224:     }
1.324     albertel 5225:     my $default_form_data=&defaultFormData($symb);
                   5226:     my $grading_menu_button=&show_grading_menu_form($symb);
1.209     ng       5227:     my $file_selector=&scantron_uploads($file2grade);
1.82      albertel 5228:     my $format_selector=&scantron_scantab();
1.186     albertel 5229:     my $CODE_selector=&scantron_CODElist();
                   5230:     my $CODE_unique=&scantron_CODEunique();
1.75      albertel 5231:     my $result;
1.422     foxr     5232: 
1.513     foxr     5233:     $ssi_error = 0;
                   5234: 
1.422     foxr     5235:     # Chunk of form to prompt for a file to grade and how:
                   5236: 
1.489     albertel 5237:     $result.= '
                   5238:     <br />
                   5239:     <form method="post" enctype="multipart/form-data" action="/adm/grades" name="scantron_process">
                   5240:     <input type="hidden" name="command" value="scantron_warning" />
                   5241:     '.$default_form_data.'
                   5242:     '.&Apache::loncommon::start_data_table('LC_scantron_action').'
                   5243:        '.&Apache::loncommon::start_data_table_header_row().'
                   5244:             <th colspan="2">
1.492     albertel 5245:               &nbsp;'.&mt('Specify file and which Folder/Sequence to grade').'
1.489     albertel 5246:             </th>
                   5247:        '.&Apache::loncommon::end_data_table_header_row().'
                   5248:        '.&Apache::loncommon::start_data_table_row().'
1.492     albertel 5249:             <td> '.&mt('Sequence to grade:').' </td><td> '.$sequence_selector.' </td>
1.489     albertel 5250:        '.&Apache::loncommon::end_data_table_row().'
                   5251:        '.&Apache::loncommon::start_data_table_row().'
1.572     www      5252:             <td> '.&mt('Filename of bubblesheet data file:').' </td><td> '.$file_selector.' </td>
1.489     albertel 5253:        '.&Apache::loncommon::end_data_table_row().'
                   5254:        '.&Apache::loncommon::start_data_table_row().'
1.572     www      5255:             <td> '.&mt('Format of bubblesheet data file:').' </td><td> '.$format_selector.' </td>
1.489     albertel 5256:        '.&Apache::loncommon::end_data_table_row().'
                   5257:        '.&Apache::loncommon::start_data_table_row().'
1.492     albertel 5258:             <td> '.&mt('Saved CODEs to validate against:').' </td><td> '.$CODE_selector.' </td>
1.489     albertel 5259:        '.&Apache::loncommon::end_data_table_row().'
                   5260:        '.&Apache::loncommon::start_data_table_row().'
1.492     albertel 5261:             <td> '.&mt('Each CODE is only to be used once:').'</td><td> '.$CODE_unique.' </td>
1.489     albertel 5262:        '.&Apache::loncommon::end_data_table_row().'
                   5263:        '.&Apache::loncommon::start_data_table_row().'
1.492     albertel 5264: 	    <td> '.&mt('Options:').' </td>
1.187     albertel 5265:             <td>
1.492     albertel 5266: 	       <label><input type="checkbox" name="scantron_options_redo" value="redo_skipped"/> '.&mt('Do only previously skipped records').'</label> <br />
                   5267:                <label><input type="checkbox" name="scantron_options_ignore" value="ignore_corrections"/> '.&mt('Remove all existing corrections').'</label> <br />
                   5268:                <label><input type="checkbox" name="scantron_options_hidden" value="ignore_hidden"/> '.&mt('Skip hidden resources when grading').'</label>
1.187     albertel 5269: 	    </td>
1.489     albertel 5270:        '.&Apache::loncommon::end_data_table_row().'
                   5271:        '.&Apache::loncommon::start_data_table_row().'
1.174     albertel 5272:             <td colspan="2">
1.572     www      5273:               <input type="submit" value="'.&mt('Grading: Validate Bubblesheet Records').'" />
1.162     albertel 5274:             </td>
1.489     albertel 5275:        '.&Apache::loncommon::end_data_table_row().'
                   5276:     '.&Apache::loncommon::end_data_table().'
                   5277:     </form>
                   5278: ';
1.162     albertel 5279:    
                   5280:     $r->print($result);
                   5281: 
1.257     albertel 5282:     if (&Apache::lonnet::allowed('usc',$env{'request.role.domain'}) ||
                   5283:         &Apache::lonnet::allowed('usc',$env{'request.course.id'})) {
1.162     albertel 5284: 
1.422     foxr     5285: 	# Chunk of form to prompt for a scantron file upload.
                   5286: 
1.489     albertel 5287:         $r->print('
                   5288:     <br />
                   5289:     '.&Apache::loncommon::start_data_table('LC_scantron_action').'
                   5290:        '.&Apache::loncommon::start_data_table_header_row().'
                   5291:             <th>
1.572     www      5292:               &nbsp;'.&mt('Specify a bubblesheet data file to upload.').'
1.489     albertel 5293:             </th>
                   5294:        '.&Apache::loncommon::end_data_table_header_row().'
                   5295:        '.&Apache::loncommon::start_data_table_row().'
1.162     albertel 5296:             <td>
1.489     albertel 5297: ');
1.324     albertel 5298:     my $default_form_data=&defaultFormData(&get_symb($r,1));
1.257     albertel 5299:     my $cdom= $env{'course.'.$env{'request.course.id'}.'.domain'};
                   5300:     my $cnum= $env{'course.'.$env{'request.course.id'}.'.num'};
1.597   ! wenzelju 5301:     $r->print(&Apache::lonhtmlcommon::scripttag('
1.174     albertel 5302:     function checkUpload(formname) {
                   5303: 	if (formname.upfile.value == "") {
1.492     albertel 5304: 	    alert("'.&mt('Please use the browse button to select a file from your local directory.').'");
1.174     albertel 5305: 	    return false;
                   5306: 	}
                   5307: 	formname.submit();
1.597   ! wenzelju 5308:     }'));
        !          5309:     $r->print('
1.492     albertel 5310:               <form enctype="multipart/form-data" action="/adm/grades" name="rules" method="post">
                   5311:                 '.$default_form_data.'
                   5312:                 <input name="courseid" type="hidden" value="'.$cnum.'" />
                   5313:                 <input name="domainid" type="hidden" value="'.$cdom.'" />
                   5314:                 <input name="command" value="scantronupload_save" type="hidden" />
                   5315:                 '.&mt('File to upload: [_1]','<input type="file" name="upfile" size="50" />').'
1.174     albertel 5316:                 <br />
1.589     bisitz   5317:                 <input type="button" onclick="javascript:checkUpload(this.form);" value="'.&mt('Upload Bubblesheet Data').'" />
1.174     albertel 5318:               </form>
1.492     albertel 5319: ');
1.162     albertel 5320: 
1.489     albertel 5321:         $r->print('
1.162     albertel 5322:             </td>
1.489     albertel 5323:        '.&Apache::loncommon::end_data_table_row().'
                   5324:        '.&Apache::loncommon::end_data_table().'
                   5325: ');
1.162     albertel 5326:     }
1.422     foxr     5327: 
                   5328:     # Chunk of the form that prompts to view a scoring office file,
                   5329:     # corrected file, skipped records in a file.
                   5330: 
1.489     albertel 5331:     $r->print('
                   5332:    <br />
                   5333:    <form action="/adm/grades" name="scantron_download">
                   5334:      '.$default_form_data.'
                   5335:      <input type="hidden" name="command" value="scantron_download" />
                   5336:      '.&Apache::loncommon::start_data_table('LC_scantron_action').'
                   5337:        '.&Apache::loncommon::start_data_table_header_row().'
                   5338:               <th>
1.492     albertel 5339:                 &nbsp;'.&mt('Download a scoring office file').'
1.489     albertel 5340:               </th>
                   5341:        '.&Apache::loncommon::end_data_table_header_row().'
                   5342:        '.&Apache::loncommon::start_data_table_row().'
1.492     albertel 5343:               <td> '.&mt('Filename of scoring office file: [_1]',$file_selector).' 
1.489     albertel 5344:                 <br />
1.492     albertel 5345:                 <input type="submit" value="'.&mt('Download: Show List of Associated Files').'" />
1.489     albertel 5346:        '.&Apache::loncommon::end_data_table_row().'
                   5347:      '.&Apache::loncommon::end_data_table().'
                   5348:    </form>
                   5349:    <br />
                   5350: ');
1.162     albertel 5351: 
1.457     banghart 5352:     &Apache::lonpickcode::code_list($r,2);
1.523     raeburn  5353: 
1.528     raeburn  5354:     $r->print('<br /><form method="post" name="checkscantron">'.
1.523     raeburn  5355:              $default_form_data."\n".
                   5356:              &Apache::loncommon::start_data_table('LC_scantron_action')."\n".
                   5357:              &Apache::loncommon::start_data_table_header_row()."\n".
                   5358:              '<th colspan="2">
1.572     www      5359:               &nbsp;'.&mt('Review bubblesheet data and submissions for a previously graded folder/sequence')."\n".
1.523     raeburn  5360:              '</th>'."\n".
                   5361:               &Apache::loncommon::end_data_table_header_row()."\n".
                   5362:               &Apache::loncommon::start_data_table_row()."\n".
                   5363:               '<td> '.&mt('Graded folder/sequence:').' </td>'."\n".
                   5364:               '<td> '.$sequence_selector.' </td>'.
                   5365:               &Apache::loncommon::end_data_table_row()."\n".
                   5366:               &Apache::loncommon::start_data_table_row()."\n".
                   5367:               '<td> '.&mt('Filename of scoring office file:').' </td>'."\n".
                   5368:               '<td> '.$file_selector.' </td>'."\n".
                   5369:               &Apache::loncommon::end_data_table_row()."\n".
                   5370:               &Apache::loncommon::start_data_table_row()."\n".
                   5371:               '<td> '.&mt('Format of data file:').' </td>'."\n".
                   5372:               '<td> '.$format_selector.' </td>'."\n".
                   5373:               &Apache::loncommon::end_data_table_row()."\n".
                   5374:               &Apache::loncommon::start_data_table_row()."\n".
1.557     raeburn  5375:               '<td> '.&mt('Options').' </td>'."\n".
                   5376:               '<td> <label><input type="checkbox" name="scantron_options_hidden" value="ignore_hidden"/> '.&mt('Skip hidden resources').'</label></td>'.
                   5377:               &Apache::loncommon::end_data_table_row()."\n".
                   5378:               &Apache::loncommon::start_data_table_row()."\n".
1.523     raeburn  5379:               '<td colspan="2">'."\n".
                   5380:               '<input type="hidden" name="command" value="checksubmissions" />'."\n".
1.575     www      5381:               '<input type="submit" value="'.&mt('Review Bubblesheet Data and Submission Records').'" />'."\n".
1.523     raeburn  5382:               '</td>'."\n".
                   5383:               &Apache::loncommon::end_data_table_row()."\n".
                   5384:               &Apache::loncommon::end_data_table()."\n".
                   5385:               '</form><br />');
1.457     banghart 5386:     $r->print($grading_menu_button);
1.523     raeburn  5387:     return;
1.75      albertel 5388: }
                   5389: 
1.423     albertel 5390: =pod
                   5391: 
                   5392: =item get_scantron_config
                   5393: 
                   5394:    Parse and return the scantron configuration line selected as a
                   5395:    hash of configuration file fields.
                   5396: 
                   5397:  Arguments:
                   5398:     which - the name of the configuration to parse from the file.
                   5399: 
                   5400: 
                   5401:  Returns:
                   5402:             If the named configuration is not in the file, an empty
                   5403:             hash is returned.
                   5404:     a hash with the fields
                   5405:       name         - internal name for the this configuration setup
                   5406:       description  - text to display to operator that describes this config
                   5407:       CODElocation - if 0 or the string 'none'
                   5408:                           - no CODE exists for this config
                   5409:                      if -1 || the string 'letter'
                   5410:                           - a CODE exists for this config and is
                   5411:                             a string of letters
                   5412:                      Unsupported value (but planned for future support)
                   5413:                           if a positive integer
                   5414:                                - The CODE exists as the first n items from
                   5415:                                  the question section of the form
                   5416:                           if the string 'number'
                   5417:                                - The CODE exists for this config and is
                   5418:                                  a string of numbers
                   5419:       CODEstart   - (only matter if a CODE exists) column in the line where
                   5420:                      the CODE starts
                   5421:       CODElength  - length of the CODE
1.573     bisitz   5422:       IDstart     - column where the student/employee ID starts
1.556     weissno  5423:       IDlength    - length of the student/employee ID info
1.423     albertel 5424:       Qstart      - column where the information from the bubbled
                   5425:                     'questions' start
                   5426:       Qlength     - number of columns comprising a single bubble line from
                   5427:                     the sheet. (usually either 1 or 10)
1.424     albertel 5428:       Qon         - either a single character representing the character used
1.423     albertel 5429:                     to signal a bubble was chosen in the positional setup, or
                   5430:                     the string 'letter' if the letter of the chosen bubble is
                   5431:                     in the final, or 'number' if a number representing the
                   5432:                     chosen bubble is in the file (1->A 0->J)
1.424     albertel 5433:       Qoff        - the character used to represent that a bubble was
                   5434:                     left blank
1.423     albertel 5435:       PaperID     - if the scanning process generates a unique number for each
                   5436:                     sheet scanned the column that this ID number starts in
                   5437:       PaperIDlength - number of columns that comprise the unique ID number
                   5438:                       for the sheet of paper
1.424     albertel 5439:       FirstName   - column that the first name starts in
1.423     albertel 5440:       FirstNameLength - number of columns that the first name spans
                   5441:  
                   5442:       LastName    - column that the last name starts in
                   5443:       LastNameLength - number of columns that the last name spans
                   5444: 
                   5445: =cut
1.422     foxr     5446: 
1.82      albertel 5447: sub get_scantron_config {
                   5448:     my ($which) = @_;
1.518     raeburn  5449:     my @lines = &get_scantronformat_file();
1.82      albertel 5450:     my %config;
1.157     albertel 5451:     #FIXME probably should move to XML it has already gotten a bit much now
1.518     raeburn  5452:     foreach my $line (@lines) {
1.82      albertel 5453: 	my ($name,$descrip)=split(/:/,$line);
                   5454: 	if ($name ne $which ) { next; }
                   5455: 	chomp($line);
                   5456: 	my @config=split(/:/,$line);
                   5457: 	$config{'name'}=$config[0];
                   5458: 	$config{'description'}=$config[1];
                   5459: 	$config{'CODElocation'}=$config[2];
                   5460: 	$config{'CODEstart'}=$config[3];
                   5461: 	$config{'CODElength'}=$config[4];
                   5462: 	$config{'IDstart'}=$config[5];
                   5463: 	$config{'IDlength'}=$config[6];
                   5464: 	$config{'Qstart'}=$config[7];
1.497     foxr     5465:  	$config{'Qlength'}=$config[8];
1.82      albertel 5466: 	$config{'Qoff'}=$config[9];
                   5467: 	$config{'Qon'}=$config[10];
1.157     albertel 5468: 	$config{'PaperID'}=$config[11];
                   5469: 	$config{'PaperIDlength'}=$config[12];
                   5470: 	$config{'FirstName'}=$config[13];
                   5471: 	$config{'FirstNamelength'}=$config[14];
                   5472: 	$config{'LastName'}=$config[15];
                   5473: 	$config{'LastNamelength'}=$config[16];
1.82      albertel 5474: 	last;
                   5475:     }
                   5476:     return %config;
                   5477: }
                   5478: 
1.423     albertel 5479: =pod 
                   5480: 
                   5481: =item username_to_idmap
                   5482: 
1.556     weissno  5483:     creates a hash keyed by student/employee ID with values of the corresponding
1.423     albertel 5484:     student username:domain.
                   5485: 
                   5486:   Arguments:
                   5487: 
                   5488:     $classlist - reference to the class list hash. This is a hash
                   5489:                  keyed by student name:domain  whose elements are references
1.424     albertel 5490:                  to arrays containing various chunks of information
1.423     albertel 5491:                  about the student. (See loncoursedata for more info).
                   5492: 
                   5493:   Returns
                   5494:     %idmap - the constructed hash
                   5495: 
                   5496: =cut
                   5497: 
1.82      albertel 5498: sub username_to_idmap {
                   5499:     my ($classlist)= @_;
                   5500:     my %idmap;
                   5501:     foreach my $student (keys(%$classlist)) {
                   5502: 	$idmap{$classlist->{$student}->[&Apache::loncoursedata::CL_ID]}=
                   5503: 	    $student;
                   5504:     }
                   5505:     return %idmap;
                   5506: }
1.423     albertel 5507: 
                   5508: =pod
                   5509: 
1.424     albertel 5510: =item scantron_fixup_scanline
1.423     albertel 5511: 
                   5512:    Process a requested correction to a scanline.
                   5513: 
                   5514:   Arguments:
                   5515:     $scantron_config   - hash from &get_scantron_config()
                   5516:     $scan_data         - hash of correction information 
                   5517:                           (see &scantron_getfile())
                   5518:     $line              - existing scanline
                   5519:     $whichline         - line number of the passed in scanline
                   5520:     $field             - type of change to process 
                   5521:                          (either 
1.573     bisitz   5522:                           'ID'     -> correct the student/employee ID
1.423     albertel 5523:                           'CODE'   -> correct the CODE
                   5524:                           'answer' -> fixup the submitted answers)
                   5525:     
                   5526:    $args               - hash of additional info,
                   5527:                           - 'ID' 
                   5528:                                'newid' -> studentID to use in replacement
1.424     albertel 5529:                                           of existing one
1.423     albertel 5530:                           - 'CODE' 
                   5531:                                'CODE_ignore_dup' - set to true if duplicates
                   5532:                                                    should be ignored.
                   5533: 	                       'CODE' - is new code or 'use_unfound'
1.424     albertel 5534:                                         if the existing unfound code should
1.423     albertel 5535:                                         be used as is
                   5536:                           - 'answer'
                   5537:                                'response' - new answer or 'none' if blank
                   5538:                                'question' - the bubble line to change
1.503     raeburn  5539:                                'questionnum' - the question identifier,
                   5540:                                                may include subquestion. 
1.423     albertel 5541: 
                   5542:   Returns:
                   5543:     $line - the modified scanline
                   5544: 
                   5545:   Side effects: 
                   5546:     $scan_data - may be updated
                   5547: 
                   5548: =cut
                   5549: 
1.82      albertel 5550: 
1.157     albertel 5551: sub scantron_fixup_scanline {
                   5552:     my ($scantron_config,$scan_data,$line,$whichline,$field,$args)=@_;
                   5553:     if ($field eq 'ID') {
                   5554: 	if (length($args->{'newid'}) > $$scantron_config{'IDlength'}) {
1.186     albertel 5555: 	    return ($line,1,'New value too large');
1.157     albertel 5556: 	}
                   5557: 	if (length($args->{'newid'}) < $$scantron_config{'IDlength'}) {
                   5558: 	    $args->{'newid'}=sprintf('%-'.$$scantron_config{'IDlength'}.'s',
                   5559: 				     $args->{'newid'});
                   5560: 	}
                   5561: 	substr($line,$$scantron_config{'IDstart'}-1,
                   5562: 	       $$scantron_config{'IDlength'})=$args->{'newid'};
                   5563: 	if ($args->{'newid'}=~/^\s*$/) {
                   5564: 	    &scan_data($scan_data,"$whichline.user",
                   5565: 		       $args->{'username'}.':'.$args->{'domain'});
                   5566: 	}
1.186     albertel 5567:     } elsif ($field eq 'CODE') {
1.192     albertel 5568: 	if ($args->{'CODE_ignore_dup'}) {
                   5569: 	    &scan_data($scan_data,"$whichline.CODE_ignore_dup",'1');
                   5570: 	}
                   5571: 	&scan_data($scan_data,"$whichline.useCODE",'1');
                   5572: 	if ($args->{'CODE'} ne 'use_unfound') {
1.191     albertel 5573: 	    if (length($args->{'CODE'}) > $$scantron_config{'CODElength'}) {
                   5574: 		return ($line,1,'New CODE value too large');
                   5575: 	    }
                   5576: 	    if (length($args->{'CODE'}) < $$scantron_config{'CODElength'}) {
                   5577: 		$args->{'CODE'}=sprintf('%-'.$$scantron_config{'CODElength'}.'s',$args->{'CODE'});
                   5578: 	    }
                   5579: 	    substr($line,$$scantron_config{'CODEstart'}-1,
                   5580: 		   $$scantron_config{'CODElength'})=$args->{'CODE'};
1.186     albertel 5581: 	}
1.157     albertel 5582:     } elsif ($field eq 'answer') {
1.497     foxr     5583: 	my $length=$scantron_config->{'Qlength'};
1.157     albertel 5584: 	my $off=$scantron_config->{'Qoff'};
                   5585: 	my $on=$scantron_config->{'Qon'};
1.497     foxr     5586: 	my $answer=${off}x$length;
                   5587: 	if ($args->{'response'} eq 'none') {
                   5588: 	    &scan_data($scan_data,
1.503     raeburn  5589: 		       "$whichline.no_bubble.".$args->{'questionnum'},'1');
1.497     foxr     5590: 	} else {
                   5591: 	    if ($on eq 'letter') {
                   5592: 		my @alphabet=('A'..'Z');
                   5593: 		$answer=$alphabet[$args->{'response'}];
                   5594: 	    } elsif ($on eq 'number') {
                   5595: 		$answer=$args->{'response'}+1;
                   5596: 		if ($answer == 10) { $answer = '0'; }
1.274     albertel 5597: 	    } else {
1.497     foxr     5598: 		substr($answer,$args->{'response'},1)=$on;
1.274     albertel 5599: 	    }
1.497     foxr     5600: 	    &scan_data($scan_data,
1.503     raeburn  5601: 		       "$whichline.no_bubble.".$args->{'questionnum'},undef,'1');
1.157     albertel 5602: 	}
1.497     foxr     5603: 	my $where=$length*($args->{'question'}-1)+$scantron_config->{'Qstart'};
                   5604: 	substr($line,$where-1,$length)=$answer;
1.157     albertel 5605:     }
                   5606:     return $line;
                   5607: }
1.423     albertel 5608: 
                   5609: =pod
                   5610: 
                   5611: =item scan_data
                   5612: 
                   5613:     Edit or look up  an item in the scan_data hash.
                   5614: 
                   5615:   Arguments:
                   5616:     $scan_data  - The hash (see scantron_getfile)
                   5617:     $key        - shorthand of the key to edit (actual key is
1.424     albertel 5618:                   scantronfilename_key).
1.423     albertel 5619:     $data        - New value of the hash entry.
                   5620:     $delete      - If true, the entry is removed from the hash.
                   5621: 
                   5622:   Returns:
                   5623:     The new value of the hash table field (undefined if deleted).
                   5624: 
                   5625: =cut
                   5626: 
                   5627: 
1.157     albertel 5628: sub scan_data {
                   5629:     my ($scan_data,$key,$value,$delete)=@_;
1.257     albertel 5630:     my $filename=$env{'form.scantron_selectfile'};
1.157     albertel 5631:     if (defined($value)) {
                   5632: 	$scan_data->{$filename.'_'.$key} = $value;
                   5633:     }
                   5634:     if ($delete) { delete($scan_data->{$filename.'_'.$key}); }
                   5635:     return $scan_data->{$filename.'_'.$key};
                   5636: }
1.423     albertel 5637: 
1.495     albertel 5638: # ----- These first few routines are general use routines.----
                   5639: 
                   5640: # Return the number of occurences of a pattern in a string.
                   5641: 
                   5642: sub occurence_count {
                   5643:     my ($string, $pattern) = @_;
                   5644: 
                   5645:     my @matches = ($string =~ /$pattern/g);
                   5646: 
                   5647:     return scalar(@matches);
                   5648: }
                   5649: 
                   5650: 
                   5651: # Take a string known to have digits and convert all the
                   5652: # digits into letters in the range J,A..I.
                   5653: 
                   5654: sub digits_to_letters {
                   5655:     my ($input) = @_;
                   5656: 
                   5657:     my @alphabet = ('J', 'A'..'I');
                   5658: 
                   5659:     my @input    = split(//, $input);
                   5660:     my $output ='';
                   5661:     for (my $i = 0; $i < scalar(@input); $i++) {
                   5662: 	if ($input[$i] =~ /\d/) {
                   5663: 	    $output .= $alphabet[$input[$i]];
                   5664: 	} else {
                   5665: 	    $output .= $input[$i];
                   5666: 	}
                   5667:     }
                   5668:     return $output;
                   5669: }
                   5670: 
1.423     albertel 5671: =pod 
                   5672: 
                   5673: =item scantron_parse_scanline
                   5674: 
                   5675:   Decodes a scanline from the selected scantron file
                   5676: 
                   5677:  Arguments:
                   5678:     line             - The text of the scantron file line to process
                   5679:     whichline        - Line number
                   5680:     scantron_config  - Hash describing the format of the scantron lines.
                   5681:     scan_data        - Hash of extra information about the scanline
                   5682:                        (see scantron_getfile for more information)
                   5683:     just_header      - True if should not process question answers but only
                   5684:                        the stuff to the left of the answers.
                   5685:  Returns:
                   5686:    Hash containing the result of parsing the scanline
                   5687: 
                   5688:    Keys are all proceeded by the string 'scantron.'
                   5689: 
                   5690:        CODE    - the CODE in use for this scanline
                   5691:        useCODE - 1 if the CODE is invalid but it usage has been forced
                   5692:                  by the operator
                   5693:        CODE_ignore_dup - 1 if the CODE is a duplicated use when unique
                   5694:                             CODEs were selected, but the usage has been
                   5695:                             forced by the operator
1.556     weissno  5696:        ID  - student/employee ID
1.423     albertel 5697:        PaperID - if used, the ID number printed on the sheet when the 
                   5698:                  paper was scanned
                   5699:        FirstName - first name from the sheet
                   5700:        LastName  - last name from the sheet
                   5701: 
                   5702:      if just_header was not true these key may also exist
                   5703: 
1.447     foxr     5704:        missingerror - a list of bubble ranges that are considered to be answers
                   5705:                       to a single question that don't have any bubbles filled in.
                   5706:                       Of the form questionnumber:firstbubblenumber:count.
                   5707:        doubleerror  - a list of bubble ranges that are considered to be answers
                   5708:                       to a single question that have more than one bubble filled in.
                   5709:                       Of the form questionnumber::firstbubblenumber:count
                   5710:    
                   5711:                 In the above, count is the number of bubble responses in the
                   5712:                 input line needed to represent the possible answers to the question.
                   5713:                 e.g. a radioresponse with 15 choices in an answer sheet with 10 choices
                   5714:                 per line would have count = 2.
                   5715: 
1.423     albertel 5716:        maxquest     - the number of the last bubble line that was parsed
                   5717: 
                   5718:        (<number> starts at 1)
                   5719:        <number>.answer - zero or more letters representing the selected
                   5720:                          letters from the scanline for the bubble line 
                   5721:                          <number>.
                   5722:                          if blank there was either no bubble or there where
                   5723:                          multiple bubbles, (consult the keys missingerror and
                   5724:                          doubleerror if this is an error condition)
                   5725: 
                   5726: =cut
                   5727: 
1.82      albertel 5728: sub scantron_parse_scanline {
1.423     albertel 5729:     my ($line,$whichline,$scantron_config,$scan_data,$just_header)=@_;
1.470     foxr     5730: 
1.82      albertel 5731:     my %record;
1.550     raeburn  5732:     my $lastpos = $env{'form.scantron_maxbubble'}*$$scantron_config{'Qlength'};
                   5733:     my $questions=substr($line,$$scantron_config{'Qstart'}-1,$lastpos);  # Answers
1.422     foxr     5734:     my $data=substr($line,0,$$scantron_config{'Qstart'}-1);     # earlier stuff
1.278     albertel 5735:     if (!($$scantron_config{'CODElocation'} eq 0 ||
                   5736: 	  $$scantron_config{'CODElocation'} eq 'none')) {
                   5737: 	if ($$scantron_config{'CODElocation'} < 0 ||
                   5738: 	    $$scantron_config{'CODElocation'} eq 'letter' ||
                   5739: 	    $$scantron_config{'CODElocation'} eq 'number') {
1.191     albertel 5740: 	    $record{'scantron.CODE'}=substr($data,
                   5741: 					    $$scantron_config{'CODEstart'}-1,
1.83      albertel 5742: 					    $$scantron_config{'CODElength'});
1.191     albertel 5743: 	    if (&scan_data($scan_data,"$whichline.useCODE")) {
                   5744: 		$record{'scantron.useCODE'}=1;
                   5745: 	    }
1.192     albertel 5746: 	    if (&scan_data($scan_data,"$whichline.CODE_ignore_dup")) {
                   5747: 		$record{'scantron.CODE_ignore_dup'}=1;
                   5748: 	    }
1.82      albertel 5749: 	} else {
                   5750: 	    #FIXME interpret first N questions
                   5751: 	}
                   5752:     }
1.83      albertel 5753:     $record{'scantron.ID'}=substr($data,$$scantron_config{'IDstart'}-1,
                   5754: 				  $$scantron_config{'IDlength'});
1.157     albertel 5755:     $record{'scantron.PaperID'}=
                   5756: 	substr($data,$$scantron_config{'PaperID'}-1,
                   5757: 	       $$scantron_config{'PaperIDlength'});
                   5758:     $record{'scantron.FirstName'}=
                   5759: 	substr($data,$$scantron_config{'FirstName'}-1,
                   5760: 	       $$scantron_config{'FirstNamelength'});
                   5761:     $record{'scantron.LastName'}=
                   5762: 	substr($data,$$scantron_config{'LastName'}-1,
                   5763: 	       $$scantron_config{'LastNamelength'});
1.423     albertel 5764:     if ($just_header) { return \%record; }
1.194     albertel 5765: 
1.82      albertel 5766:     my @alphabet=('A'..'Z');
                   5767:     my $questnum=0;
1.447     foxr     5768:     my $ansnum  =1;		# Multiple 'answer lines'/question.
                   5769: 
1.470     foxr     5770:     chomp($questions);		# Get rid of any trailing \n.
                   5771:     $questions =~ s/\r$//;      # Get rid of trailing \r too (MAC or Win uploads).
                   5772:     while (length($questions)) {
1.447     foxr     5773: 	my $answers_needed = $bubble_lines_per_response{$questnum};
1.503     raeburn  5774:         my $answer_length  = ($$scantron_config{'Qlength'} * $answers_needed)
                   5775:                              || 1;
                   5776:         $questnum++;
                   5777:         my $quest_id = $questnum;
                   5778:         my $currentquest = substr($questions,0,$answer_length);
                   5779:         $questions       = substr($questions,$answer_length);
                   5780:         if (length($currentquest) < $answer_length) { next; }
                   5781: 
                   5782:         if ($subdivided_bubble_lines{$questnum-1} =~ /,/) {
                   5783:             my $subquestnum = 1;
                   5784:             my $subquestions = $currentquest;
                   5785:             my @subanswers_needed = 
                   5786:                 split(/,/,$subdivided_bubble_lines{$questnum-1});  
                   5787:             foreach my $subans (@subanswers_needed) {
                   5788:                 my $subans_length =
                   5789:                     ($$scantron_config{'Qlength'} * $subans)  || 1;
                   5790:                 my $currsubquest = substr($subquestions,0,$subans_length);
                   5791:                 $subquestions   = substr($subquestions,$subans_length);
                   5792:                 $quest_id = "$questnum.$subquestnum";
                   5793:                 if (($$scantron_config{'Qon'} eq 'letter') ||
                   5794:                     ($$scantron_config{'Qon'} eq 'number')) {
                   5795:                     $ansnum = &scantron_validator_lettnum($ansnum, 
                   5796:                         $questnum,$quest_id,$subans,$currsubquest,$whichline,
                   5797:                         \@alphabet,\%record,$scantron_config,$scan_data);
                   5798:                 } else {
                   5799:                     $ansnum = &scantron_validator_positional($ansnum,
                   5800:                         $questnum,$quest_id,$subans,$currsubquest,$whichline,                        \@alphabet,\%record,$scantron_config,$scan_data);
                   5801:                 }
                   5802:                 $subquestnum ++;
                   5803:             }
                   5804:         } else {
                   5805:             if (($$scantron_config{'Qon'} eq 'letter') ||
                   5806:                 ($$scantron_config{'Qon'} eq 'number')) {
                   5807:                 $ansnum = &scantron_validator_lettnum($ansnum,$questnum,
                   5808:                     $quest_id,$answers_needed,$currentquest,$whichline,
                   5809:                     \@alphabet,\%record,$scantron_config,$scan_data);
                   5810:             } else {
                   5811:                 $ansnum = &scantron_validator_positional($ansnum,$questnum,
                   5812:                     $quest_id,$answers_needed,$currentquest,$whichline,
                   5813:                     \@alphabet,\%record,$scantron_config,$scan_data);
                   5814:             }
                   5815:         }
                   5816:     }
                   5817:     $record{'scantron.maxquest'}=$questnum;
                   5818:     return \%record;
                   5819: }
1.447     foxr     5820: 
1.503     raeburn  5821: sub scantron_validator_lettnum {
                   5822:     my ($ansnum,$questnum,$quest_id,$answers_needed,$currquest,$whichline,
                   5823:         $alphabet,$record,$scantron_config,$scan_data) = @_;
                   5824: 
                   5825:     # Qon 'letter' implies for each slot in currquest we have:
                   5826:     #    ? or * for doubles, a letter in A-Z for a bubble, and
                   5827:     #    about anything else (esp. a value of Qoff) for missing
                   5828:     #    bubbles.
                   5829:     #
                   5830:     # Qon 'number' implies each slot gives a digit that indexes the
                   5831:     #    bubbles filled, or Qoff, or a non-number for unbubbled lines,
                   5832:     #    and * or ? for double bubbles on a single line.
                   5833:     #
1.447     foxr     5834: 
1.503     raeburn  5835:     my $matchon;
                   5836:     if ($$scantron_config{'Qon'} eq 'letter') {
                   5837:         $matchon = '[A-Z]';
                   5838:     } elsif ($$scantron_config{'Qon'} eq 'number') {
                   5839:         $matchon = '\d';
                   5840:     }
                   5841:     my $occurrences = 0;
                   5842:     if (($responsetype_per_response{$questnum-1} eq 'essayresponse') ||
                   5843:         ($responsetype_per_response{$questnum-1} eq 'formularesponse') ||
1.510     raeburn  5844:         ($responsetype_per_response{$questnum-1} eq 'stringresponse') ||
                   5845:         ($responsetype_per_response{$questnum-1} eq 'imageresponse') ||
                   5846:         ($responsetype_per_response{$questnum-1} eq 'reactionresponse') ||
                   5847:         ($responsetype_per_response{$questnum-1} eq 'organicresponse')) {
1.503     raeburn  5848:         my @singlelines = split('',$currquest);
                   5849:         foreach my $entry (@singlelines) {
                   5850:             $occurrences = &occurence_count($entry,$matchon);
                   5851:             if ($occurrences > 1) {
                   5852:                 last;
                   5853:             }
                   5854:         } 
                   5855:     } else {
                   5856:         $occurrences = &occurence_count($currquest,$matchon); 
                   5857:     }
                   5858:     if (($currquest =~ /\?/ || $currquest =~ /\*/) || ($occurrences > 1)) {
                   5859:         push(@{$record->{'scantron.doubleerror'}},$quest_id);
                   5860:         for (my $ans=0; $ans<$answers_needed; $ans++) {
                   5861:             my $bubble = substr($currquest,$ans,1);
                   5862:             if ($bubble =~ /$matchon/ ) {
                   5863:                 if ($$scantron_config{'Qon'} eq 'number') {
                   5864:                     if ($bubble == 0) {
                   5865:                         $bubble = 10; 
                   5866:                     }
                   5867:                     $record->{"scantron.$ansnum.answer"} = 
                   5868:                         $alphabet->[$bubble-1];
                   5869:                 } else {
                   5870:                     $record->{"scantron.$ansnum.answer"} = $bubble;
                   5871:                 }
                   5872:             } else {
                   5873:                 $record->{"scantron.$ansnum.answer"}='';
                   5874:             }
                   5875:             $ansnum++;
                   5876:         }
                   5877:     } elsif (!defined($currquest)
                   5878:             || (&occurence_count($currquest, $$scantron_config{'Qoff'}) == length($currquest))
                   5879:             || (&occurence_count($currquest,$matchon) == 0)) {
                   5880:         for (my $ans=0; $ans<$answers_needed; $ans++ ) {
                   5881:             $record->{"scantron.$ansnum.answer"}='';
                   5882:             $ansnum++;
                   5883:         }
                   5884:         if (!&scan_data($scan_data,"$whichline.no_bubble.$quest_id")) {
                   5885:             push(@{$record->{'scantron.missingerror'}},$quest_id);
                   5886:         }
                   5887:     } else {
                   5888:         if ($$scantron_config{'Qon'} eq 'number') {
                   5889:             $currquest = &digits_to_letters($currquest);            
                   5890:         }
                   5891:         for (my $ans=0; $ans<$answers_needed; $ans++) {
                   5892:             my $bubble = substr($currquest,$ans,1);
                   5893:             $record->{"scantron.$ansnum.answer"} = $bubble;
                   5894:             $ansnum++;
                   5895:         }
                   5896:     }
                   5897:     return $ansnum;
                   5898: }
1.447     foxr     5899: 
1.503     raeburn  5900: sub scantron_validator_positional {
                   5901:     my ($ansnum,$questnum,$quest_id,$answers_needed,$currquest,
                   5902:         $whichline,$alphabet,$record,$scantron_config,$scan_data) = @_;
1.447     foxr     5903: 
1.503     raeburn  5904:     # Otherwise there's a positional notation;
                   5905:     # each bubble line requires Qlength items, and there are filled in
                   5906:     # bubbles for each case where there 'Qon' characters.
                   5907:     #
1.447     foxr     5908: 
1.503     raeburn  5909:     my @array=split($$scantron_config{'Qon'},$currquest,-1);
1.447     foxr     5910: 
1.503     raeburn  5911:     # If the split only gives us one element.. the full length of the
                   5912:     # answer string, no bubbles are filled in:
1.447     foxr     5913: 
1.507     raeburn  5914:     if ($answers_needed eq '') {
                   5915:         return;
                   5916:     }
                   5917: 
1.503     raeburn  5918:     if (length($array[0]) eq $$scantron_config{'Qlength'}*$answers_needed) {
                   5919:         for (my $ans=0; $ans<$answers_needed; $ans++ ) {
                   5920:             $record->{"scantron.$ansnum.answer"}='';
                   5921:             $ansnum++;
                   5922:         }
                   5923:         if (!&scan_data($scan_data,"$whichline.no_bubble.$quest_id")) {
                   5924:             push(@{$record->{"scantron.missingerror"}},$quest_id);
                   5925:         }
                   5926:     } elsif (scalar(@array) == 2) {
                   5927:         my $location = length($array[0]);
                   5928:         my $line_num = int($location / $$scantron_config{'Qlength'});
                   5929:         my $bubble   = $alphabet->[$location % $$scantron_config{'Qlength'}];
                   5930:         for (my $ans=0; $ans<$answers_needed; $ans++) {
                   5931:             if ($ans eq $line_num) {
                   5932:                 $record->{"scantron.$ansnum.answer"} = $bubble;
                   5933:             } else {
                   5934:                 $record->{"scantron.$ansnum.answer"} = ' ';
                   5935:             }
                   5936:             $ansnum++;
                   5937:          }
                   5938:     } else {
                   5939:         #  If there's more than one instance of a bubble character
                   5940:         #  That's a double bubble; with positional notation we can
                   5941:         #  record all the bubbles filled in as well as the
                   5942:         #  fact this response consists of multiple bubbles.
                   5943:         #
                   5944:         if (($responsetype_per_response{$questnum-1} eq 'essayresponse') ||
                   5945:             ($responsetype_per_response{$questnum-1} eq 'formularesponse') ||
1.510     raeburn  5946:             ($responsetype_per_response{$questnum-1} eq 'stringresponse') ||
                   5947:             ($responsetype_per_response{$questnum-1} eq 'imageresponse') ||
                   5948:             ($responsetype_per_response{$questnum-1} eq 'reactionresponse') ||
                   5949:             ($responsetype_per_response{$questnum-1} eq 'organicresponse')) {
1.503     raeburn  5950:             my $doubleerror = 0;
                   5951:             while (($currquest >= $$scantron_config{'Qlength'}) && 
                   5952:                    (!$doubleerror)) {
                   5953:                my $currline = substr($currquest,0,$$scantron_config{'Qlength'});
                   5954:                $currquest = substr($currquest,$$scantron_config{'Qlength'});
                   5955:                my @currarray = split($$scantron_config{'Qon'},$currline,-1);
                   5956:                if (length(@currarray) > 2) {
                   5957:                    $doubleerror = 1;
                   5958:                } 
                   5959:             }
                   5960:             if ($doubleerror) {
                   5961:                 push(@{$record->{'scantron.doubleerror'}},$quest_id);
                   5962:             }
                   5963:         } else {
                   5964:             push(@{$record->{'scantron.doubleerror'}},$quest_id);
                   5965:         }
                   5966:         my $item = $ansnum;
                   5967:         for (my $ans=0; $ans<$answers_needed; $ans++) {
                   5968:             $record->{"scantron.$item.answer"} = '';
                   5969:             $item ++;
                   5970:         }
1.447     foxr     5971: 
1.503     raeburn  5972:         my @ans=@array;
                   5973:         my $i=0;
                   5974:         my $increment = 0;
                   5975:         while ($#ans) {
                   5976:             $i+=length($ans[0]) + $increment;
                   5977:             my $line   = int($i/$$scantron_config{'Qlength'} + $ansnum);
                   5978:             my $bubble = $i%$$scantron_config{'Qlength'};
                   5979:             $record->{"scantron.$line.answer"}.=$alphabet->[$bubble];
                   5980:             shift(@ans);
                   5981:             $increment = 1;
                   5982:         }
                   5983:         $ansnum += $answers_needed;
1.82      albertel 5984:     }
1.503     raeburn  5985:     return $ansnum;
1.82      albertel 5986: }
                   5987: 
1.423     albertel 5988: =pod
                   5989: 
                   5990: =item scantron_add_delay
                   5991: 
                   5992:    Adds an error message that occurred during the grading phase to a
                   5993:    queue of messages to be shown after grading pass is complete
                   5994: 
                   5995:  Arguments:
1.424     albertel 5996:    $delayqueue  - arrary ref of hash ref of error messages
1.423     albertel 5997:    $scanline    - the scanline that caused the error
                   5998:    $errormesage - the error message
                   5999:    $errorcode   - a numeric code for the error
                   6000: 
                   6001:  Side Effects:
1.424     albertel 6002:    updates the $delayqueue to have a new hash ref of the error
1.423     albertel 6003: 
                   6004: =cut
                   6005: 
1.82      albertel 6006: sub scantron_add_delay {
1.140     albertel 6007:     my ($delayqueue,$scanline,$errormessage,$errorcode)=@_;
                   6008:     push(@$delayqueue,
                   6009: 	 {'line' => $scanline, 'emsg' => $errormessage,
                   6010: 	  'ecode' => $errorcode }
                   6011: 	 );
1.82      albertel 6012: }
                   6013: 
1.423     albertel 6014: =pod
                   6015: 
                   6016: =item scantron_find_student
                   6017: 
1.424     albertel 6018:    Finds the username for the current scanline
                   6019: 
                   6020:   Arguments:
                   6021:    $scantron_record - hash result from scantron_parse_scanline
                   6022:    $scan_data       - hash of correction information 
                   6023:                       (see &scantron_getfile() form more information)
                   6024:    $idmap           - hash from &username_to_idmap()
                   6025:    $line            - number of current scanline
                   6026:  
                   6027:   Returns:
                   6028:    Either 'username:domain' or undef if unknown
                   6029: 
1.423     albertel 6030: =cut
                   6031: 
1.82      albertel 6032: sub scantron_find_student {
1.157     albertel 6033:     my ($scantron_record,$scan_data,$idmap,$line)=@_;
1.83      albertel 6034:     my $scanID=$$scantron_record{'scantron.ID'};
1.157     albertel 6035:     if ($scanID =~ /^\s*$/) {
                   6036:  	return &scan_data($scan_data,"$line.user");
                   6037:     }
1.83      albertel 6038:     foreach my $id (keys(%$idmap)) {
1.157     albertel 6039:  	if (lc($id) eq lc($scanID)) {
                   6040:  	    return $$idmap{$id};
                   6041:  	}
1.83      albertel 6042:     }
                   6043:     return undef;
                   6044: }
                   6045: 
1.423     albertel 6046: =pod
                   6047: 
                   6048: =item scantron_filter
                   6049: 
1.424     albertel 6050:    Filter sub for lonnavmaps, filters out hidden resources if ignore
                   6051:    hidden resources was selected
                   6052: 
1.423     albertel 6053: =cut
                   6054: 
1.83      albertel 6055: sub scantron_filter {
                   6056:     my ($curres)=@_;
1.331     albertel 6057: 
                   6058:     if (ref($curres) && $curres->is_problem()) {
                   6059: 	# if the user has asked to not have either hidden
                   6060: 	# or 'randomout' controlled resources to be graded
                   6061: 	# don't include them
                   6062: 	if ($env{'form.scantron_options_hidden'} eq 'ignore_hidden'
                   6063: 	    && $curres->randomout) {
                   6064: 	    return 0;
                   6065: 	}
1.83      albertel 6066: 	return 1;
                   6067:     }
                   6068:     return 0;
1.82      albertel 6069: }
                   6070: 
1.423     albertel 6071: =pod
                   6072: 
                   6073: =item scantron_process_corrections
                   6074: 
1.424     albertel 6075:    Gets correction information out of submitted form data and corrects
                   6076:    the scanline
                   6077: 
1.423     albertel 6078: =cut
                   6079: 
1.157     albertel 6080: sub scantron_process_corrections {
                   6081:     my ($r) = @_;
1.257     albertel 6082:     my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
1.157     albertel 6083:     my ($scanlines,$scan_data)=&scantron_getfile();
                   6084:     my $classlist=&Apache::loncoursedata::get_classlist();
1.257     albertel 6085:     my $which=$env{'form.scantron_line'};
1.200     albertel 6086:     my $line=&scantron_get_line($scanlines,$scan_data,$which);
1.157     albertel 6087:     my ($skip,$err,$errmsg);
1.257     albertel 6088:     if ($env{'form.scantron_skip_record'}) {
1.157     albertel 6089: 	$skip=1;
1.257     albertel 6090:     } elsif ($env{'form.scantron_corrections'} =~ /^(duplicate|incorrect)ID$/) {
                   6091: 	my $newstudent=$env{'form.scantron_username'}.':'.
                   6092: 	    $env{'form.scantron_domain'};
1.157     albertel 6093: 	my $newid=$classlist->{$newstudent}->[&Apache::loncoursedata::CL_ID];
                   6094: 	($line,$err,$errmsg)=
                   6095: 	    &scantron_fixup_scanline(\%scantron_config,$scan_data,$line,$which,
                   6096: 				     'ID',{'newid'=>$newid,
1.257     albertel 6097: 				    'username'=>$env{'form.scantron_username'},
                   6098: 				    'domain'=>$env{'form.scantron_domain'}});
                   6099:     } elsif ($env{'form.scantron_corrections'} =~ /^(duplicate|incorrect)CODE$/) {
                   6100: 	my $resolution=$env{'form.scantron_CODE_resolution'};
1.190     albertel 6101: 	my $newCODE;
1.192     albertel 6102: 	my %args;
1.190     albertel 6103: 	if      ($resolution eq 'use_unfound') {
1.191     albertel 6104: 	    $newCODE='use_unfound';
1.190     albertel 6105: 	} elsif ($resolution eq 'use_found') {
1.257     albertel 6106: 	    $newCODE=$env{'form.scantron_CODE_selectedvalue'};
1.190     albertel 6107: 	} elsif ($resolution eq 'use_typed') {
1.257     albertel 6108: 	    $newCODE=$env{'form.scantron_CODE_newvalue'};
1.194     albertel 6109: 	} elsif ($resolution =~ /^use_closest_(\d+)/) {
1.257     albertel 6110: 	    $newCODE=$env{"form.scantron_CODE_closest_$1"};
1.190     albertel 6111: 	}
1.257     albertel 6112: 	if ($env{'form.scantron_corrections'} eq 'duplicateCODE') {
1.192     albertel 6113: 	    $args{'CODE_ignore_dup'}=1;
                   6114: 	}
                   6115: 	$args{'CODE'}=$newCODE;
1.186     albertel 6116: 	($line,$err,$errmsg)=
                   6117: 	    &scantron_fixup_scanline(\%scantron_config,$scan_data,$line,$which,
1.192     albertel 6118: 				     'CODE',\%args);
1.257     albertel 6119:     } elsif ($env{'form.scantron_corrections'} =~ /^(missing|double)bubble$/) {
                   6120: 	foreach my $question (split(',',$env{'form.scantron_questions'})) {
1.157     albertel 6121: 	    ($line,$err,$errmsg)=
                   6122: 		&scantron_fixup_scanline(\%scantron_config,$scan_data,$line,
                   6123: 					 $which,'answer',
                   6124: 					 { 'question'=>$question,
1.503     raeburn  6125: 		      		   'response'=>$env{"form.scantron_correct_Q_$question"},
                   6126:                                    'questionnum'=>$env{"form.scantron_questionnum_Q_$question"}});
1.157     albertel 6127: 	    if ($err) { last; }
                   6128: 	}
                   6129:     }
                   6130:     if ($err) {
1.398     albertel 6131: 	$r->print("<span class=\"LC_warning\">Unable to accept last correction, an error occurred :$errmsg:</span>");
1.157     albertel 6132:     } else {
1.200     albertel 6133: 	&scantron_put_line($scanlines,$scan_data,$which,$line,$skip);
1.157     albertel 6134: 	&scantron_putfile($scanlines,$scan_data);
                   6135:     }
                   6136: }
                   6137: 
1.423     albertel 6138: =pod
                   6139: 
                   6140: =item reset_skipping_status
                   6141: 
1.424     albertel 6142:    Forgets the current set of remember skipped scanlines (and thus
                   6143:    reverts back to considering all lines in the
                   6144:    scantron_skipped_<filename> file)
                   6145: 
1.423     albertel 6146: =cut
                   6147: 
1.200     albertel 6148: sub reset_skipping_status {
                   6149:     my ($scanlines,$scan_data)=&scantron_getfile();
                   6150:     &scan_data($scan_data,'remember_skipping',undef,1);
                   6151:     &scantron_putfile(undef,$scan_data);
                   6152: }
                   6153: 
1.423     albertel 6154: =pod
                   6155: 
                   6156: =item start_skipping
                   6157: 
1.424     albertel 6158:    Marks a scanline to be skipped. 
                   6159: 
1.423     albertel 6160: =cut
                   6161: 
1.376     albertel 6162: sub start_skipping {
1.200     albertel 6163:     my ($scan_data,$i)=@_;
                   6164:     my %remembered=split(':',&scan_data($scan_data,'remember_skipping'));
1.376     albertel 6165:     if ($env{'form.scantron_options_redo'} =~ /^redo_/) {
                   6166: 	$remembered{$i}=2;
                   6167:     } else {
                   6168: 	$remembered{$i}=1;
                   6169:     }
1.200     albertel 6170:     &scan_data($scan_data,'remember_skipping',join(':',%remembered));
                   6171: }
                   6172: 
1.423     albertel 6173: =pod
                   6174: 
                   6175: =item should_be_skipped
                   6176: 
1.424     albertel 6177:    Checks whether a scanline should be skipped.
                   6178: 
1.423     albertel 6179: =cut
                   6180: 
1.200     albertel 6181: sub should_be_skipped {
1.376     albertel 6182:     my ($scanlines,$scan_data,$i)=@_;
1.257     albertel 6183:     if ($env{'form.scantron_options_redo'} !~ /^redo_/) {
1.200     albertel 6184: 	# not redoing old skips
1.376     albertel 6185: 	if ($scanlines->{'skipped'}[$i]) { return 1; }
1.200     albertel 6186: 	return 0;
                   6187:     }
                   6188:     my %remembered=split(':',&scan_data($scan_data,'remember_skipping'));
1.376     albertel 6189: 
                   6190:     if (exists($remembered{$i}) && $remembered{$i} != 2 ) {
                   6191: 	return 0;
                   6192:     }
1.200     albertel 6193:     return 1;
                   6194: }
                   6195: 
1.423     albertel 6196: =pod
                   6197: 
                   6198: =item remember_current_skipped
                   6199: 
1.424     albertel 6200:    Discovers what scanlines are in the scantron_skipped_<filename>
                   6201:    file and remembers them into scan_data for later use.
                   6202: 
1.423     albertel 6203: =cut
                   6204: 
1.200     albertel 6205: sub remember_current_skipped {
                   6206:     my ($scanlines,$scan_data)=&scantron_getfile();
                   6207:     my %to_remember;
                   6208:     for (my $i=0;$i<=$scanlines->{'count'};$i++) {
                   6209: 	if ($scanlines->{'skipped'}[$i]) {
                   6210: 	    $to_remember{$i}=1;
                   6211: 	}
                   6212:     }
1.376     albertel 6213: 
1.200     albertel 6214:     &scan_data($scan_data,'remember_skipping',join(':',%to_remember));
                   6215:     &scantron_putfile(undef,$scan_data);
                   6216: }
                   6217: 
1.423     albertel 6218: =pod
                   6219: 
                   6220: =item check_for_error
                   6221: 
1.424     albertel 6222:     Checks if there was an error when attempting to remove a specific
                   6223:     scantron_.. bubble sheet data file. Prints out an error if
                   6224:     something went wrong.
                   6225: 
1.423     albertel 6226: =cut
                   6227: 
1.200     albertel 6228: sub check_for_error {
                   6229:     my ($r,$result)=@_;
                   6230:     if ($result ne 'ok' && $result ne 'not_found' ) {
1.492     albertel 6231: 	$r->print(&mt("An error occurred ([_1]) when trying to remove the existing corrections.",$result));
1.200     albertel 6232:     }
                   6233: }
1.157     albertel 6234: 
1.423     albertel 6235: =pod
                   6236: 
                   6237: =item scantron_warning_screen
                   6238: 
1.424     albertel 6239:    Interstitial screen to make sure the operator has selected the
                   6240:    correct options before we start the validation phase.
                   6241: 
1.423     albertel 6242: =cut
                   6243: 
1.203     albertel 6244: sub scantron_warning_screen {
                   6245:     my ($button_text)=@_;
1.257     albertel 6246:     my $title=&Apache::lonnet::gettitle($env{'form.selectpage'});
1.284     albertel 6247:     my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
1.373     albertel 6248:     my $CODElist;
1.284     albertel 6249:     if ($scantron_config{'CODElocation'} &&
                   6250: 	$scantron_config{'CODEstart'} &&
                   6251: 	$scantron_config{'CODElength'}) {
                   6252: 	$CODElist=$env{'form.scantron_CODElist'};
1.398     albertel 6253: 	if ($env{'form.scantron_CODElist'} eq '') { $CODElist='<span class="LC_warning">None</span>'; }
1.284     albertel 6254: 	$CODElist=
1.492     albertel 6255: 	    '<tr><td><b>'.&mt('List of CODES to validate against:').'</b></td><td><tt>'.
1.373     albertel 6256: 	    $env{'form.scantron_CODElist'}.'</tt></td></tr>';
1.284     albertel 6257:     }
1.492     albertel 6258:     return ('
1.203     albertel 6259: <p>
1.492     albertel 6260: <span class="LC_warning">
                   6261: '.&mt('Please double check the information below before clicking on \'[_1]\'',&mt($button_text)).'</span>
1.203     albertel 6262: </p>
                   6263: <table>
1.492     albertel 6264: <tr><td><b>'.&mt('Sequence to be Graded:').'</b></td><td>'.$title.'</td></tr>
                   6265: <tr><td><b>'.&mt('Data File that will be used:').'</b></td><td><tt>'.$env{'form.scantron_selectfile'}.'</tt></td></tr>
                   6266: '.$CODElist.'
1.203     albertel 6267: </table>
                   6268: <br />
1.492     albertel 6269: <p> '.&mt('If this information is correct, please click on \'[_1]\'.',&mt($button_text)).'</p>
                   6270: <p> '.&mt('If something is incorrect, please click the \'Grading Menu\' button to start over.').'</p>
1.203     albertel 6271: 
                   6272: <br />
1.492     albertel 6273: ');
1.203     albertel 6274: }
                   6275: 
1.423     albertel 6276: =pod
                   6277: 
                   6278: =item scantron_do_warning
                   6279: 
1.424     albertel 6280:    Check if the operator has picked something for all required
                   6281:    fields. Error out if something is missing.
                   6282: 
1.423     albertel 6283: =cut
                   6284: 
1.203     albertel 6285: sub scantron_do_warning {
                   6286:     my ($r)=@_;
1.324     albertel 6287:     my ($symb)=&get_symb($r);
1.203     albertel 6288:     if (!$symb) {return '';}
1.324     albertel 6289:     my $default_form_data=&defaultFormData($symb);
1.203     albertel 6290:     $r->print(&scantron_form_start().$default_form_data);
1.257     albertel 6291:     if ( $env{'form.selectpage'} eq '' ||
                   6292: 	 $env{'form.scantron_selectfile'} eq '' ||
                   6293: 	 $env{'form.scantron_format'} eq '' ) {
1.492     albertel 6294: 	$r->print("<p>".&mt('You have forgetten to specify some information. Please go Back and try again.')."</p>");
1.257     albertel 6295: 	if ( $env{'form.selectpage'} eq '') {
1.492     albertel 6296: 	    $r->print('<p><span class="LC_error">'.&mt('You have not selected a Sequence to grade').'</span></p>');
1.237     albertel 6297: 	} 
1.257     albertel 6298: 	if ( $env{'form.scantron_selectfile'} eq '') {
1.492     albertel 6299: 	    $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 6300: 	} 
1.257     albertel 6301: 	if ( $env{'form.scantron_format'} eq '') {
1.492     albertel 6302: 	    $r->print('<p><span class="LC_error">'.&mt('You have not selected a the format of the student\'s response data.').'</span></p>');
1.237     albertel 6303: 	} 
                   6304:     } else {
1.265     www      6305: 	my $warning=&scantron_warning_screen('Grading: Validate Records');
1.492     albertel 6306: 	$r->print('
                   6307: '.$warning.'
                   6308: <input type="submit" name="submit" value="'.&mt('Grading: Validate Records').'" />
1.203     albertel 6309: <input type="hidden" name="command" value="scantron_validate" />
1.492     albertel 6310: ');
1.237     albertel 6311:     }
1.352     albertel 6312:     $r->print("</form><br />".&show_grading_menu_form($symb));
1.203     albertel 6313:     return '';
                   6314: }
                   6315: 
1.423     albertel 6316: =pod
                   6317: 
                   6318: =item scantron_form_start
                   6319: 
1.424     albertel 6320:     html hidden input for remembering all selected grading options
                   6321: 
1.423     albertel 6322: =cut
                   6323: 
1.203     albertel 6324: sub scantron_form_start {
                   6325:     my ($max_bubble)=@_;
                   6326:     my $result= <<SCANTRONFORM;
                   6327: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="scantronupload">
1.257     albertel 6328:   <input type="hidden" name="selectpage" value="$env{'form.selectpage'}" />
                   6329:   <input type="hidden" name="scantron_format" value="$env{'form.scantron_format'}" />
                   6330:   <input type="hidden" name="scantron_selectfile" value="$env{'form.scantron_selectfile'}" />
1.218     albertel 6331:   <input type="hidden" name="scantron_maxbubble" value="$max_bubble" />
1.257     albertel 6332:   <input type="hidden" name="scantron_CODElist" value="$env{'form.scantron_CODElist'}" />
                   6333:   <input type="hidden" name="scantron_CODEunique" value="$env{'form.scantron_CODEunique'}" />
                   6334:   <input type="hidden" name="scantron_options_redo" value="$env{'form.scantron_options_redo'}" />
                   6335:   <input type="hidden" name="scantron_options_ignore" value="$env{'form.scantron_options_ignore'}" />
1.331     albertel 6336:   <input type="hidden" name="scantron_options_hidden" value="$env{'form.scantron_options_hidden'}" />
1.203     albertel 6337: SCANTRONFORM
1.447     foxr     6338: 
                   6339:   my $line = 0;
                   6340:     while (defined($env{"form.scantron.bubblelines.$line"})) {
                   6341:        my $chunk =
                   6342: 	   '<input type="hidden" name="scantron.bubblelines.'.$line.'" value="'.$env{"form.scantron.bubblelines.$line"}.'" />'."\n";
1.448     foxr     6343:        $chunk .=
                   6344: 	   '<input type="hidden" name="scantron.first_bubble_line.'.$line.'" value="'.$env{"form.scantron.first_bubble_line.$line"}.'" />'."\n";
1.503     raeburn  6345:        $chunk .= 
                   6346:            '<input type="hidden" name="scantron.sub_bubblelines.'.$line.'" value="'.$env{"form.scantron.sub_bubblelines.$line"}.'" />'."\n";
1.504     raeburn  6347:        $chunk .=
                   6348:            '<input type="hidden" name="scantron.responsetype.'.$line.'" value="'.$env{"form.scantron.responsetype.$line"}.'" />'."\n";
1.447     foxr     6349:        $result .= $chunk;
                   6350:        $line++;
                   6351:    }
1.203     albertel 6352:     return $result;
                   6353: }
                   6354: 
1.423     albertel 6355: =pod
                   6356: 
                   6357: =item scantron_validate_file
                   6358: 
1.424     albertel 6359:     Dispatch routine for doing validation of a bubble sheet data file.
                   6360: 
                   6361:     Also processes any necessary information resets that need to
                   6362:     occur before validation begins (ignore previous corrections,
                   6363:     restarting the skipped records processing)
                   6364: 
1.423     albertel 6365: =cut
                   6366: 
1.157     albertel 6367: sub scantron_validate_file {
                   6368:     my ($r) = @_;
1.324     albertel 6369:     my ($symb)=&get_symb($r);
1.157     albertel 6370:     if (!$symb) {return '';}
1.324     albertel 6371:     my $default_form_data=&defaultFormData($symb);
1.200     albertel 6372:     
                   6373:     # do the detection of only doing skipped records first befroe we delete
1.424     albertel 6374:     # them when doing the corrections reset
1.257     albertel 6375:     if ($env{'form.scantron_options_redo'} ne 'redo_skipped_ready') {
1.200     albertel 6376: 	&reset_skipping_status();
                   6377:     }
1.257     albertel 6378:     if ($env{'form.scantron_options_redo'} eq 'redo_skipped') {
1.200     albertel 6379: 	&remember_current_skipped();
1.257     albertel 6380: 	$env{'form.scantron_options_redo'}='redo_skipped_ready';
1.200     albertel 6381:     }
                   6382: 
1.257     albertel 6383:     if ($env{'form.scantron_options_ignore'} eq 'ignore_corrections') {
1.200     albertel 6384: 	&check_for_error($r,&scantron_remove_file('corrected'));
                   6385: 	&check_for_error($r,&scantron_remove_file('skipped'));
                   6386: 	&check_for_error($r,&scantron_remove_scan_data());
1.257     albertel 6387: 	$env{'form.scantron_options_ignore'}='done';
1.192     albertel 6388:     }
1.200     albertel 6389: 
1.257     albertel 6390:     if ($env{'form.scantron_corrections'}) {
1.157     albertel 6391: 	&scantron_process_corrections($r);
                   6392:     }
1.503     raeburn  6393:     $r->print('<p>'.&mt('Gathering necessary information.').'</p>');$r->rflush();
1.157     albertel 6394:     #get the student pick code ready
                   6395:     $r->print(&Apache::loncommon::studentbrowser_javascript());
1.582     raeburn  6396:     my $nav_error;
                   6397:     my $max_bubble=&scantron_get_maxbubble(\$nav_error);
                   6398:     if ($nav_error) {
                   6399:         $r->print(&navmap_errormsg());
                   6400:         return '';
                   6401:     }
1.203     albertel 6402:     my $result=&scantron_form_start($max_bubble).$default_form_data;
1.157     albertel 6403:     $r->print($result);
                   6404:     
1.334     albertel 6405:     my @validate_phases=( 'sequence',
                   6406: 			  'ID',
1.157     albertel 6407: 			  'CODE',
                   6408: 			  'doublebubble',
                   6409: 			  'missingbubbles');
1.257     albertel 6410:     if (!$env{'form.validatepass'}) {
                   6411: 	$env{'form.validatepass'} = 0;
1.157     albertel 6412:     }
1.257     albertel 6413:     my $currentphase=$env{'form.validatepass'};
1.157     albertel 6414: 
1.448     foxr     6415: 
1.157     albertel 6416:     my $stop=0;
                   6417:     while (!$stop && $currentphase < scalar(@validate_phases)) {
1.503     raeburn  6418: 	$r->print(&mt('Validating '.$validate_phases[$currentphase]).'<br />');
1.157     albertel 6419: 	$r->rflush();
                   6420: 	my $which="scantron_validate_".$validate_phases[$currentphase];
                   6421: 	{
                   6422: 	    no strict 'refs';
                   6423: 	    ($stop,$currentphase)=&$which($r,$currentphase);
                   6424: 	}
                   6425:     }
                   6426:     if (!$stop) {
1.203     albertel 6427: 	my $warning=&scantron_warning_screen('Start Grading');
1.542     raeburn  6428: 	$r->print(&mt('Validation process complete.').'<br />'.
                   6429:                   $warning.
                   6430:                   &mt('Perform verification for each student after storage of submissions?').
                   6431:                   '&nbsp;<span class="LC_nobreak"><label>'.
                   6432:                   '<input type="radio" name="verifyrecord" value="1" />'.&mt('Yes').'</label>'.
                   6433:                   ('&nbsp;'x3).'<label>'.
                   6434:                   '<input type="radio" name="verifyrecord" value="0" checked="checked" />'.&mt('No').
                   6435:                   '</label></span><br />'.
                   6436:                   &mt('Grading will take longer if you use verification.').'<br />'.
1.572     www      6437:                   &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  6438:                   '<input type="submit" name="submit" value="'.&mt('Start Grading').'" />'.
                   6439:                   '<input type="hidden" name="command" value="scantron_process" />'."\n");
1.157     albertel 6440:     } else {
                   6441: 	$r->print('<input type="hidden" name="command" value="scantron_validate" />');
                   6442: 	$r->print("<input type='hidden' name='validatepass' value='".$currentphase."' />");
                   6443:     }
                   6444:     if ($stop) {
1.334     albertel 6445: 	if ($validate_phases[$currentphase] eq 'sequence') {
1.539     riegler  6446: 	    $r->print('<input type="submit" name="submit" value="'.&mt('Ignore').' &rarr; " />');
1.492     albertel 6447: 	    $r->print(' '.&mt('this error').' <br />');
1.334     albertel 6448: 
1.492     albertel 6449: 	    $r->print(" <p>".&mt("Or click the 'Grading Menu' button to start over.")."</p>");
1.334     albertel 6450: 	} else {
1.503     raeburn  6451:             if ($validate_phases[$currentphase] eq 'doublebubble' || $validate_phases[$currentphase] eq 'missingbubbles') {
1.539     riegler  6452: 	        $r->print('<input type="button" name="submitbutton" value="'.&mt('Continue').' &rarr;" onclick="javascript:verify_bubble_radio(this.form)" />');
1.503     raeburn  6453:             } else {
1.539     riegler  6454:                 $r->print('<input type="submit" name="submit" value="'.&mt('Continue').' &rarr;" />');
1.503     raeburn  6455:             }
1.492     albertel 6456: 	    $r->print(' '.&mt('using corrected info').' <br />');
                   6457: 	    $r->print("<input type='submit' value='".&mt("Skip")."' name='scantron_skip_record' />");
                   6458: 	    $r->print(" ".&mt("this scanline saving it for later."));
1.334     albertel 6459: 	}
1.157     albertel 6460:     }
1.352     albertel 6461:     $r->print(" </form><br />".&show_grading_menu_form($symb));
1.157     albertel 6462:     return '';
                   6463: }
                   6464: 
1.423     albertel 6465: 
                   6466: =pod
                   6467: 
                   6468: =item scantron_remove_file
                   6469: 
1.424     albertel 6470:    Removes the requested bubble sheet data file, makes sure that
                   6471:    scantron_original_<filename> is never removed
                   6472: 
                   6473: 
1.423     albertel 6474: =cut
                   6475: 
1.200     albertel 6476: sub scantron_remove_file {
1.192     albertel 6477:     my ($which)=@_;
1.257     albertel 6478:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   6479:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1.192     albertel 6480:     my $file='scantron_';
1.200     albertel 6481:     if ($which eq 'corrected' || $which eq 'skipped') {
                   6482: 	$file.=$which.'_';
1.192     albertel 6483:     } else {
                   6484: 	return 'refused';
                   6485:     }
1.257     albertel 6486:     $file.=$env{'form.scantron_selectfile'};
1.200     albertel 6487:     return &Apache::lonnet::removeuserfile($cname,$cdom,$file);
                   6488: }
                   6489: 
1.423     albertel 6490: 
                   6491: =pod
                   6492: 
                   6493: =item scantron_remove_scan_data
                   6494: 
1.424     albertel 6495:    Removes all scan_data correction for the requested bubble sheet
                   6496:    data file.  (In the case that both the are doing skipped records we need
                   6497:    to remember the old skipped lines for the time being so that element
                   6498:    persists for a while.)
                   6499: 
1.423     albertel 6500: =cut
                   6501: 
1.200     albertel 6502: sub scantron_remove_scan_data {
1.257     albertel 6503:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   6504:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1.192     albertel 6505:     my @keys=&Apache::lonnet::getkeys('nohist_scantrondata',$cdom,$cname);
                   6506:     my @todelete;
1.257     albertel 6507:     my $filename=$env{'form.scantron_selectfile'};
1.192     albertel 6508:     foreach my $key (@keys) {
                   6509: 	if ($key=~/^\Q$filename\E_/) {
1.257     albertel 6510: 	    if ($env{'form.scantron_options_redo'} eq 'redo_skipped_ready' &&
1.200     albertel 6511: 		$key=~/remember_skipping/) {
                   6512: 		next;
                   6513: 	    }
1.192     albertel 6514: 	    push(@todelete,$key);
                   6515: 	}
                   6516:     }
1.200     albertel 6517:     my $result;
1.192     albertel 6518:     if (@todelete) {
1.491     albertel 6519: 	$result = &Apache::lonnet::del('nohist_scantrondata',
                   6520: 				       \@todelete,$cdom,$cname);
                   6521:     } else {
                   6522: 	$result = 'ok';
1.192     albertel 6523:     }
                   6524:     return $result;
                   6525: }
                   6526: 
1.423     albertel 6527: 
                   6528: =pod
                   6529: 
                   6530: =item scantron_getfile
                   6531: 
1.424     albertel 6532:     Fetches the requested bubble sheet data file (all 3 versions), and
                   6533:     the scan_data hash
                   6534:   
                   6535:   Arguments:
                   6536:     None
                   6537: 
                   6538:   Returns:
                   6539:     2 hash references
                   6540: 
                   6541:      - first one has 
                   6542:          orig      -
                   6543:          corrected -
                   6544:          skipped   -  each of which points to an array ref of the specified
                   6545:                       file broken up into individual lines
                   6546:          count     - number of scanlines
                   6547:  
                   6548:      - second is the scan_data hash possible keys are
1.425     albertel 6549:        ($number refers to scanline numbered $number and thus the key affects
                   6550:         only that scanline
                   6551:         $bubline refers to the specific bubble line element and the aspects
                   6552:         refers to that specific bubble line element)
                   6553: 
                   6554:        $number.user - username:domain to use
                   6555:        $number.CODE_ignore_dup 
                   6556:                     - ignore the duplicate CODE error 
                   6557:        $number.useCODE
                   6558:                     - use the CODE in the scanline as is
                   6559:        $number.no_bubble.$bubline
                   6560:                     - it is valid that there is no bubbled in bubble
                   6561:                       at $number $bubline
                   6562:        remember_skipping
                   6563:                     - a frozen hash containing keys of $number and values
                   6564:                       of either 
                   6565:                         1 - we are on a 'do skipped records pass' and plan
                   6566:                             on processing this line
                   6567:                         2 - we are on a 'do skipped records pass' and this
                   6568:                             scanline has been marked to skip yet again
1.424     albertel 6569: 
1.423     albertel 6570: =cut
                   6571: 
1.157     albertel 6572: sub scantron_getfile {
1.200     albertel 6573:     #FIXME really would prefer a scantron directory
1.257     albertel 6574:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   6575:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1.157     albertel 6576:     my $lines;
                   6577:     $lines=&Apache::lonnet::getfile('/uploaded/'.$cdom.'/'.$cname.'/'.
1.257     albertel 6578: 		       'scantron_orig_'.$env{'form.scantron_selectfile'});
1.157     albertel 6579:     my %scanlines;
                   6580:     $scanlines{'orig'}=[(split("\n",$lines,-1))];
                   6581:     my $temp=$scanlines{'orig'};
                   6582:     $scanlines{'count'}=$#$temp;
                   6583: 
                   6584:     $lines=&Apache::lonnet::getfile('/uploaded/'.$cdom.'/'.$cname.'/'.
1.257     albertel 6585: 		       'scantron_corrected_'.$env{'form.scantron_selectfile'});
1.157     albertel 6586:     if ($lines eq '-1') {
                   6587: 	$scanlines{'corrected'}=[];
                   6588:     } else {
                   6589: 	$scanlines{'corrected'}=[(split("\n",$lines,-1))];
                   6590:     }
                   6591:     $lines=&Apache::lonnet::getfile('/uploaded/'.$cdom.'/'.$cname.'/'.
1.257     albertel 6592: 		       'scantron_skipped_'.$env{'form.scantron_selectfile'});
1.157     albertel 6593:     if ($lines eq '-1') {
                   6594: 	$scanlines{'skipped'}=[];
                   6595:     } else {
                   6596: 	$scanlines{'skipped'}=[(split("\n",$lines,-1))];
                   6597:     }
1.175     albertel 6598:     my @tmp=&Apache::lonnet::dump('nohist_scantrondata',$cdom,$cname);
1.157     albertel 6599:     if ($tmp[0] =~ /^(error:|no_such_host)/) { @tmp=(); }
                   6600:     my %scan_data = @tmp;
                   6601:     return (\%scanlines,\%scan_data);
                   6602: }
                   6603: 
1.423     albertel 6604: =pod
                   6605: 
                   6606: =item lonnet_putfile
                   6607: 
1.424     albertel 6608:    Wrapper routine to call &Apache::lonnet::finishuserfileupload
                   6609: 
                   6610:  Arguments:
                   6611:    $contents - data to store
                   6612:    $filename - filename to store $contents into
                   6613: 
                   6614:  Returns:
                   6615:    result value from &Apache::lonnet::finishuserfileupload
                   6616: 
1.423     albertel 6617: =cut
                   6618: 
1.157     albertel 6619: sub lonnet_putfile {
                   6620:     my ($contents,$filename)=@_;
1.257     albertel 6621:     my $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   6622:     my $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
                   6623:     $env{'form.sillywaytopassafilearound'}=$contents;
1.275     albertel 6624:     &Apache::lonnet::finishuserfileupload($docuname,$docudom,'sillywaytopassafilearound',$filename);
1.157     albertel 6625: 
                   6626: }
                   6627: 
1.423     albertel 6628: =pod
                   6629: 
                   6630: =item scantron_putfile
                   6631: 
1.424     albertel 6632:     Stores the current version of the bubble sheet data files, and the
                   6633:     scan_data hash. (Does not modify the original version only the
                   6634:     corrected and skipped versions.
                   6635: 
                   6636:  Arguments:
                   6637:     $scanlines - hash ref that looks like the first return value from
                   6638:                  &scantron_getfile()
                   6639:     $scan_data - hash ref that looks like the second return value from
                   6640:                  &scantron_getfile()
                   6641: 
1.423     albertel 6642: =cut
                   6643: 
1.157     albertel 6644: sub scantron_putfile {
                   6645:     my ($scanlines,$scan_data) = @_;
1.200     albertel 6646:     #FIXME really would prefer a scantron directory
1.257     albertel 6647:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   6648:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1.200     albertel 6649:     if ($scanlines) {
                   6650: 	my $prefix='scantron_';
1.157     albertel 6651: # no need to update orig, shouldn't change
                   6652: #   &lonnet_putfile(join("\n",@{$scanlines->{'orig'}}),$prefix.'orig_'.
1.257     albertel 6653: #		    $env{'form.scantron_selectfile'});
1.200     albertel 6654: 	&lonnet_putfile(join("\n",@{$scanlines->{'corrected'}}),
                   6655: 			$prefix.'corrected_'.
1.257     albertel 6656: 			$env{'form.scantron_selectfile'});
1.200     albertel 6657: 	&lonnet_putfile(join("\n",@{$scanlines->{'skipped'}}),
                   6658: 			$prefix.'skipped_'.
1.257     albertel 6659: 			$env{'form.scantron_selectfile'});
1.200     albertel 6660:     }
1.175     albertel 6661:     &Apache::lonnet::put('nohist_scantrondata',$scan_data,$cdom,$cname);
1.157     albertel 6662: }
                   6663: 
1.423     albertel 6664: =pod
                   6665: 
                   6666: =item scantron_get_line
                   6667: 
1.424     albertel 6668:    Returns the correct version of the scanline
                   6669: 
                   6670:  Arguments:
                   6671:     $scanlines - hash ref that looks like the first return value from
                   6672:                  &scantron_getfile()
                   6673:     $scan_data - hash ref that looks like the second return value from
                   6674:                  &scantron_getfile()
                   6675:     $i         - number of the requested line (starts at 0)
                   6676: 
                   6677:  Returns:
                   6678:    A scanline, (either the original or the corrected one if it
                   6679:    exists), or undef if the requested scanline should be
                   6680:    skipped. (Either because it's an skipped scanline, or it's an
                   6681:    unskipped scanline and we are not doing a 'do skipped scanlines'
                   6682:    pass.
                   6683: 
1.423     albertel 6684: =cut
                   6685: 
1.157     albertel 6686: sub scantron_get_line {
1.200     albertel 6687:     my ($scanlines,$scan_data,$i)=@_;
1.376     albertel 6688:     if (&should_be_skipped($scanlines,$scan_data,$i)) { return undef; }
                   6689:     #if ($scanlines->{'skipped'}[$i]) { return undef; }
1.157     albertel 6690:     if ($scanlines->{'corrected'}[$i]) {return $scanlines->{'corrected'}[$i];}
                   6691:     return $scanlines->{'orig'}[$i]; 
                   6692: }
                   6693: 
1.423     albertel 6694: =pod
                   6695: 
                   6696: =item scantron_todo_count
                   6697: 
1.424     albertel 6698:     Counts the number of scanlines that need processing.
                   6699: 
                   6700:  Arguments:
                   6701:     $scanlines - hash ref that looks like the first return value from
                   6702:                  &scantron_getfile()
                   6703:     $scan_data - hash ref that looks like the second return value from
                   6704:                  &scantron_getfile()
                   6705: 
                   6706:  Returns:
                   6707:     $count - number of scanlines to process
                   6708: 
1.423     albertel 6709: =cut
                   6710: 
1.200     albertel 6711: sub get_todo_count {
                   6712:     my ($scanlines,$scan_data)=@_;
                   6713:     my $count=0;
                   6714:     for (my $i=0;$i<=$scanlines->{'count'};$i++) {
                   6715: 	my $line=&scantron_get_line($scanlines,$scan_data,$i);
                   6716: 	if ($line=~/^[\s\cz]*$/) { next; }
                   6717: 	$count++;
                   6718:     }
                   6719:     return $count;
                   6720: }
                   6721: 
1.423     albertel 6722: =pod
                   6723: 
                   6724: =item scantron_put_line
                   6725: 
1.424     albertel 6726:     Updates the 'corrected' or 'skipped' versions of the bubble sheet
                   6727:     data file.
                   6728: 
                   6729:  Arguments:
                   6730:     $scanlines - hash ref that looks like the first return value from
                   6731:                  &scantron_getfile()
                   6732:     $scan_data - hash ref that looks like the second return value from
                   6733:                  &scantron_getfile()
                   6734:     $i         - line number to update
                   6735:     $newline   - contents of the updated scanline
                   6736:     $skip      - if true make the line for skipping and update the
                   6737:                  'skipped' file
                   6738: 
1.423     albertel 6739: =cut
                   6740: 
1.157     albertel 6741: sub scantron_put_line {
1.200     albertel 6742:     my ($scanlines,$scan_data,$i,$newline,$skip)=@_;
1.157     albertel 6743:     if ($skip) {
                   6744: 	$scanlines->{'skipped'}[$i]=$newline;
1.376     albertel 6745: 	&start_skipping($scan_data,$i);
1.157     albertel 6746: 	return;
                   6747:     }
                   6748:     $scanlines->{'corrected'}[$i]=$newline;
                   6749: }
                   6750: 
1.423     albertel 6751: =pod
                   6752: 
                   6753: =item scantron_clear_skip
                   6754: 
1.424     albertel 6755:    Remove a line from the 'skipped' file
                   6756: 
                   6757:  Arguments:
                   6758:     $scanlines - hash ref that looks like the first return value from
                   6759:                  &scantron_getfile()
                   6760:     $scan_data - hash ref that looks like the second return value from
                   6761:                  &scantron_getfile()
                   6762:     $i         - line number to update
                   6763: 
1.423     albertel 6764: =cut
                   6765: 
1.376     albertel 6766: sub scantron_clear_skip {
                   6767:     my ($scanlines,$scan_data,$i)=@_;
                   6768:     if (exists($scanlines->{'skipped'}[$i])) {
                   6769: 	undef($scanlines->{'skipped'}[$i]);
                   6770: 	return 1;
                   6771:     }
                   6772:     return 0;
                   6773: }
                   6774: 
1.423     albertel 6775: =pod
                   6776: 
                   6777: =item scantron_filter_not_exam
                   6778: 
1.424     albertel 6779:    Filter routine used by &Apache::lonnavmaps::retrieveResources(), to
                   6780:    filter out resources that are not marked as 'exam' mode
                   6781: 
1.423     albertel 6782: =cut
                   6783: 
1.334     albertel 6784: sub scantron_filter_not_exam {
                   6785:     my ($curres)=@_;
                   6786:     
                   6787:     if (ref($curres) && $curres->is_problem() && !$curres->is_exam()) {
                   6788: 	# if the user has asked to not have either hidden
                   6789: 	# or 'randomout' controlled resources to be graded
                   6790: 	# don't include them
                   6791: 	if ($env{'form.scantron_options_hidden'} eq 'ignore_hidden'
                   6792: 	    && $curres->randomout) {
                   6793: 	    return 0;
                   6794: 	}
                   6795: 	return 1;
                   6796:     }
                   6797:     return 0;
                   6798: }
                   6799: 
1.423     albertel 6800: =pod
                   6801: 
                   6802: =item scantron_validate_sequence
                   6803: 
1.424     albertel 6804:     Validates the selected sequence, checking for resource that are
                   6805:     not set to exam mode.
                   6806: 
1.423     albertel 6807: =cut
                   6808: 
1.334     albertel 6809: sub scantron_validate_sequence {
                   6810:     my ($r,$currentphase) = @_;
                   6811: 
                   6812:     my $navmap=Apache::lonnavmaps::navmap->new();
1.582     raeburn  6813:     unless (ref($navmap)) {
                   6814:         $r->print(&navmap_errormsg());
                   6815:         return (1,$currentphase);
                   6816:     }
1.334     albertel 6817:     my (undef,undef,$sequence)=
                   6818: 	&Apache::lonnet::decode_symb($env{'form.selectpage'});
                   6819: 
                   6820:     my $map=$navmap->getResourceByUrl($sequence);
                   6821: 
                   6822:     $r->print('<input type="hidden" name="validate_sequence_exam"
                   6823:                                     value="ignore" />');
                   6824:     if ($env{'form.validate_sequence_exam'} ne 'ignore') {
                   6825: 	my @resources=
                   6826: 	    $navmap->retrieveResources($map,\&scantron_filter_not_exam,1,0);
                   6827: 	if (@resources) {
1.357     banghart 6828: 	    $r->print("<p>".&mt('Some resources in the sequence currently are not set to exam mode. Grading these resources currently may not work correctly.')."</p>");
1.334     albertel 6829: 	    return (1,$currentphase);
                   6830: 	}
                   6831:     }
                   6832: 
                   6833:     return (0,$currentphase+1);
                   6834: }
                   6835: 
1.423     albertel 6836: 
                   6837: 
1.157     albertel 6838: sub scantron_validate_ID {
                   6839:     my ($r,$currentphase) = @_;
                   6840:     
                   6841:     #get student info
                   6842:     my $classlist=&Apache::loncoursedata::get_classlist();
                   6843:     my %idmap=&username_to_idmap($classlist);
                   6844: 
                   6845:     #get scantron line setup
1.257     albertel 6846:     my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
1.157     albertel 6847:     my ($scanlines,$scan_data)=&scantron_getfile();
1.582     raeburn  6848: 
                   6849:     my $nav_error;
                   6850:     &scantron_get_maxbubble(\$nav_error); # parse needs the bubble_lines.. array.
                   6851:     if ($nav_error) {
                   6852:         $r->print(&navmap_errormsg());
                   6853:         return(1,$currentphase);
                   6854:     }
1.157     albertel 6855: 
                   6856:     my %found=('ids'=>{},'usernames'=>{});
                   6857:     for (my $i=0;$i<=$scanlines->{'count'};$i++) {
1.200     albertel 6858: 	my $line=&scantron_get_line($scanlines,$scan_data,$i);
1.157     albertel 6859: 	if ($line=~/^[\s\cz]*$/) { next; }
                   6860: 	my $scan_record=&scantron_parse_scanline($line,$i,\%scantron_config,
                   6861: 						 $scan_data);
                   6862: 	my $id=$$scan_record{'scantron.ID'};
                   6863: 	my $found;
                   6864: 	foreach my $checkid (keys(%idmap)) {
                   6865: 	    if (lc($checkid) eq lc($id)) { $found=$checkid;last; }
                   6866: 	}
                   6867: 	if ($found) {
                   6868: 	    my $username=$idmap{$found};
                   6869: 	    if ($found{'ids'}{$found}) {
                   6870: 		&scantron_get_correction($r,$i,$scan_record,\%scantron_config,
                   6871: 					 $line,'duplicateID',$found);
1.194     albertel 6872: 		return(1,$currentphase);
1.157     albertel 6873: 	    } elsif ($found{'usernames'}{$username}) {
                   6874: 		&scantron_get_correction($r,$i,$scan_record,\%scantron_config,
                   6875: 					 $line,'duplicateID',$username);
1.194     albertel 6876: 		return(1,$currentphase);
1.157     albertel 6877: 	    }
1.186     albertel 6878: 	    #FIXME store away line we previously saw the ID on to use above
1.157     albertel 6879: 	    $found{'ids'}{$found}++;
                   6880: 	    $found{'usernames'}{$username}++;
                   6881: 	} else {
                   6882: 	    if ($id =~ /^\s*$/) {
1.158     albertel 6883: 		my $username=&scan_data($scan_data,"$i.user");
1.157     albertel 6884: 		if (defined($username) && $found{'usernames'}{$username}) {
                   6885: 		    &scantron_get_correction($r,$i,$scan_record,
                   6886: 					     \%scantron_config,
                   6887: 					     $line,'duplicateID',$username);
1.194     albertel 6888: 		    return(1,$currentphase);
1.157     albertel 6889: 		} elsif (!defined($username)) {
                   6890: 		    &scantron_get_correction($r,$i,$scan_record,
                   6891: 					     \%scantron_config,
                   6892: 					     $line,'incorrectID');
1.194     albertel 6893: 		    return(1,$currentphase);
1.157     albertel 6894: 		}
                   6895: 		$found{'usernames'}{$username}++;
                   6896: 	    } else {
                   6897: 		&scantron_get_correction($r,$i,$scan_record,\%scantron_config,
                   6898: 					 $line,'incorrectID');
1.194     albertel 6899: 		return(1,$currentphase);
1.157     albertel 6900: 	    }
                   6901: 	}
                   6902:     }
                   6903: 
                   6904:     return (0,$currentphase+1);
                   6905: }
                   6906: 
1.423     albertel 6907: 
1.157     albertel 6908: sub scantron_get_correction {
                   6909:     my ($r,$i,$scan_record,$scan_config,$line,$error,$arg)=@_;
1.454     banghart 6910: #FIXME in the case of a duplicated ID the previous line, probably need
1.157     albertel 6911: #to show both the current line and the previous one and allow skipping
                   6912: #the previous one or the current one
                   6913: 
1.333     albertel 6914:     if ( $$scan_record{'scantron.PaperID'} =~ /\S/) {
1.492     albertel 6915: 	$r->print("<p>".&mt("<b>An error was detected ($error)</b>".
                   6916: 			    " for PaperID <tt>[_1]</tt>",
                   6917: 			    $$scan_record{'scantron.PaperID'})."</p> \n");
1.157     albertel 6918:     } else {
1.492     albertel 6919: 	$r->print("<p>".&mt("<b>An error was detected ($error)</b>".
                   6920: 			    " in scanline [_1] <pre>[_2]</pre>",
                   6921: 			    $i,$line)."</p> \n");
                   6922:     }
                   6923:     my $message="<p>".&mt("The ID on the form is  <tt>[_1]</tt><br />".
                   6924: 			  "The name on the paper is [_2],[_3]",
                   6925: 			  $$scan_record{'scantron.ID'},
                   6926: 			  $$scan_record{'scantron.LastName'},
                   6927: 			  $$scan_record{'scantron.FirstName'})."</p>";
1.242     albertel 6928: 
1.157     albertel 6929:     $r->print('<input type="hidden" name="scantron_corrections" value="'.$error.'" />'."\n");
                   6930:     $r->print('<input type="hidden" name="scantron_line" value="'.$i.'" />'."\n");
1.503     raeburn  6931:                            # Array populated for doublebubble or
                   6932:     my @lines_to_correct;  # missingbubble errors to build javascript
                   6933:                            # to validate radio button checking   
                   6934: 
1.157     albertel 6935:     if ($error =~ /ID$/) {
1.186     albertel 6936: 	if ($error eq 'incorrectID') {
1.492     albertel 6937: 	    $r->print("<p>".&mt("The encoded ID is not in the classlist").
                   6938: 		      "</p>\n");
1.157     albertel 6939: 	} elsif ($error eq 'duplicateID') {
1.492     albertel 6940: 	    $r->print("<p>".&mt("The encoded ID has also been used by a previous paper [_1]",$arg)."</p>\n");
1.157     albertel 6941: 	}
1.242     albertel 6942: 	$r->print($message);
1.492     albertel 6943: 	$r->print("<p>".&mt("How should I handle this?")." <br /> \n");
1.157     albertel 6944: 	$r->print("\n<ul><li> ");
                   6945: 	#FIXME it would be nice if this sent back the user ID and
                   6946: 	#could do partial userID matches
                   6947: 	$r->print(&Apache::loncommon::selectstudent_link('scantronupload',
                   6948: 				       'scantron_username','scantron_domain'));
                   6949: 	$r->print(": <input type='text' name='scantron_username' value='' />");
                   6950: 	$r->print("\n@".
1.257     albertel 6951: 		 &Apache::loncommon::select_dom_form($env{'request.role.domain'},'scantron_domain'));
1.157     albertel 6952: 
                   6953: 	$r->print('</li>');
1.186     albertel 6954:     } elsif ($error =~ /CODE$/) {
                   6955: 	if ($error eq 'incorrectCODE') {
1.492     albertel 6956: 	    $r->print("<p>".&mt("The encoded CODE is not in the list of possible CODEs.")."</p>\n");
1.186     albertel 6957: 	} elsif ($error eq 'duplicateCODE') {
1.492     albertel 6958: 	    $r->print("<p>".&mt("The encoded CODE has also been used by a previous paper [_1], and CODEs are supposed to be unique.",join(', ',@{$arg}))."</p>\n");
1.186     albertel 6959: 	}
1.492     albertel 6960: 	$r->print("<p>".&mt("The CODE on the form is  <tt>'[_1]'</tt>",
                   6961: 			    $$scan_record{'scantron.CODE'})."<br />\n");
1.242     albertel 6962: 	$r->print($message);
1.492     albertel 6963: 	$r->print("<p>".&mt("How should I handle this?")." <br /> \n");
1.187     albertel 6964: 	$r->print("\n<br /> ");
1.194     albertel 6965: 	my $i=0;
1.273     albertel 6966: 	if ($error eq 'incorrectCODE' 
                   6967: 	    && $$scan_record{'scantron.CODE'}=~/\S/ ) {
1.194     albertel 6968: 	    my ($max,$closest)=&scantron_get_closely_matching_CODEs($arg,$$scan_record{'scantron.CODE'});
1.278     albertel 6969: 	    if ($closest > 0) {
                   6970: 		foreach my $testcode (@{$closest}) {
                   6971: 		    my $checked='';
1.569     bisitz   6972: 		    if (!$i) { $checked=' checked="checked"'; }
1.492     albertel 6973: 		    $r->print("
                   6974:    <label>
1.569     bisitz   6975:        <input type='radio' name='scantron_CODE_resolution' value='use_closest_$i'$checked />
1.492     albertel 6976:        ".&mt("Use the similar CODE [_1] instead.",
                   6977: 	    "<b><tt>".$testcode."</tt></b>")."
                   6978:     </label>
                   6979:     <input type='hidden' name='scantron_CODE_closest_$i' value='$testcode' />");
1.278     albertel 6980: 		    $r->print("\n<br />");
                   6981: 		    $i++;
                   6982: 		}
1.194     albertel 6983: 	    }
                   6984: 	}
1.273     albertel 6985: 	if ($$scan_record{'scantron.CODE'}=~/\S/ ) {
1.569     bisitz   6986: 	    my $checked; if (!$i) { $checked=' checked="checked"'; }
1.492     albertel 6987: 	    $r->print("
                   6988:     <label>
1.569     bisitz   6989:         <input type='radio' name='scantron_CODE_resolution' value='use_unfound'$checked />
1.492     albertel 6990:        ".&mt("Use the CODE [_1] that is was on the paper, ignoring the error.",
                   6991: 	     "<b><tt>".$$scan_record{'scantron.CODE'}."</tt></b>")."
                   6992:     </label>");
1.273     albertel 6993: 	    $r->print("\n<br />");
                   6994: 	}
1.194     albertel 6995: 
1.597   ! wenzelju 6996: 	$r->print(&Apache::lonhtmlcommon::scripttag(<<ENDSCRIPT));
1.188     albertel 6997: function change_radio(field) {
1.190     albertel 6998:     var slct=document.scantronupload.scantron_CODE_resolution;
1.188     albertel 6999:     var i;
                   7000:     for (i=0;i<slct.length;i++) {
                   7001:         if (slct[i].value==field) { slct[i].checked=true; }
                   7002:     }
                   7003: }
                   7004: ENDSCRIPT
1.187     albertel 7005: 	my $href="/adm/pickcode?".
1.359     www      7006: 	   "form=".&escape("scantronupload").
                   7007: 	   "&scantron_format=".&escape($env{'form.scantron_format'}).
                   7008: 	   "&scantron_CODElist=".&escape($env{'form.scantron_CODElist'}).
                   7009: 	   "&curCODE=".&escape($$scan_record{'scantron.CODE'}).
                   7010: 	   "&scantron_selectfile=".&escape($env{'form.scantron_selectfile'});
1.332     albertel 7011: 	if ($env{'form.scantron_CODElist'} =~ /\S/) { 
1.492     albertel 7012: 	    $r->print("
                   7013:     <label>
                   7014:        <input type='radio' name='scantron_CODE_resolution' value='use_found' />
                   7015:        ".&mt("[_1]Select[_2] a CODE from the list of all CODEs and use it.",
                   7016: 	     "<a target='_blank' href='$href'>","</a>")."
                   7017:     </label> 
1.558     bisitz   7018:     ".&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 7019: 	    $r->print("\n<br />");
                   7020: 	}
1.492     albertel 7021: 	$r->print("
                   7022:     <label>
                   7023:        <input type='radio' name='scantron_CODE_resolution' value='use_typed' />
                   7024:        ".&mt("Use [_1] as the CODE.",
                   7025: 	     "</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 7026: 	$r->print("\n<br /><br />");
1.157     albertel 7027:     } elsif ($error eq 'doublebubble') {
1.503     raeburn  7028: 	$r->print("<p>".&mt("There have been multiple bubbles scanned for some question(s)")."</p>\n");
1.497     foxr     7029: 
                   7030: 	# The form field scantron_questions is acutally a list of line numbers.
                   7031: 	# represented by this form so:
                   7032: 
                   7033: 	my $line_list = &questions_to_line_list($arg);
                   7034: 
1.157     albertel 7035: 	$r->print('<input type="hidden" name="scantron_questions" value="'.
1.497     foxr     7036: 		  $line_list.'" />');
1.242     albertel 7037: 	$r->print($message);
1.492     albertel 7038: 	$r->print("<p>".&mt("Please indicate which bubble should be used for grading")."</p>");
1.157     albertel 7039: 	foreach my $question (@{$arg}) {
1.503     raeburn  7040: 	    my @linenums = &prompt_for_corrections($r,$question,$scan_config,
                   7041:                                                    $scan_record, $error);
1.524     raeburn  7042:             push(@lines_to_correct,@linenums);
1.157     albertel 7043: 	}
1.503     raeburn  7044:         $r->print(&verify_bubbles_checked(@lines_to_correct));
1.157     albertel 7045:     } elsif ($error eq 'missingbubble') {
1.492     albertel 7046: 	$r->print("<p>".&mt("There have been <b>no</b> bubbles scanned for some question(s)")."</p>\n");
1.242     albertel 7047: 	$r->print($message);
1.492     albertel 7048: 	$r->print("<p>".&mt("Please indicate which bubble should be used for grading.")."</p>");
1.503     raeburn  7049: 	$r->print(&mt("Some questions have no scanned bubbles.")."\n");
1.497     foxr     7050: 
1.503     raeburn  7051: 	# The form field scantron_questions is actually a list of line numbers not
1.497     foxr     7052: 	# a list of question numbers. Therefore:
                   7053: 	#
                   7054: 	
                   7055: 	my $line_list = &questions_to_line_list($arg);
                   7056: 
1.157     albertel 7057: 	$r->print('<input type="hidden" name="scantron_questions" value="'.
1.497     foxr     7058: 		  $line_list.'" />');
1.157     albertel 7059: 	foreach my $question (@{$arg}) {
1.503     raeburn  7060: 	    my @linenums = &prompt_for_corrections($r,$question,$scan_config,
                   7061:                                                    $scan_record, $error);
1.524     raeburn  7062:             push(@lines_to_correct,@linenums);
1.157     albertel 7063: 	}
1.503     raeburn  7064:         $r->print(&verify_bubbles_checked(@lines_to_correct));
1.157     albertel 7065:     } else {
                   7066: 	$r->print("\n<ul>");
                   7067:     }
                   7068:     $r->print("\n</li></ul>");
1.497     foxr     7069: }
                   7070: 
1.503     raeburn  7071: sub verify_bubbles_checked {
                   7072:     my (@ansnums) = @_;
                   7073:     my $ansnumstr = join('","',@ansnums);
                   7074:     my $warning = &mt("A bubble or 'No bubble' selection has not been made for one or more lines.");
1.597   ! wenzelju 7075:     my $output = &Apache::lonhtmlcommon::scripttag((<<ENDSCRIPT));
1.503     raeburn  7076: function verify_bubble_radio(form) {
                   7077:     var ansnumArray = new Array ("$ansnumstr");
                   7078:     var need_bubble_count = 0;
                   7079:     for (var i=0; i<ansnumArray.length; i++) {
                   7080:         if (form.elements["scantron_correct_Q_"+ansnumArray[i]].length > 1) {
                   7081:             var bubble_picked = 0; 
                   7082:             for (var j=0; j<form.elements["scantron_correct_Q_"+ansnumArray[i]].length; j++) {
                   7083:                 if (form.elements["scantron_correct_Q_"+ansnumArray[i]][j].checked == true) {
                   7084:                     bubble_picked = 1;
                   7085:                 }
                   7086:             }
                   7087:             if (bubble_picked == 0) {
                   7088:                 need_bubble_count ++;
                   7089:             }
                   7090:         }
                   7091:     }
                   7092:     if (need_bubble_count) {
                   7093:         alert("$warning");
                   7094:         return;
                   7095:     }
                   7096:     form.submit(); 
                   7097: }
                   7098: ENDSCRIPT
                   7099:     return $output;
                   7100: }
                   7101: 
1.497     foxr     7102: =pod
                   7103: 
                   7104: =item  questions_to_line_list
1.157     albertel 7105: 
1.497     foxr     7106: Converts a list of questions into a string of comma separated
                   7107: line numbers in the answer sheet used by the questions.  This is
                   7108: used to fill in the scantron_questions form field.
                   7109: 
                   7110:   Arguments:
                   7111:      questions    - Reference to an array of questions.
                   7112: 
                   7113: =cut
                   7114: 
                   7115: 
                   7116: sub questions_to_line_list {
                   7117:     my ($questions) = @_;
                   7118:     my @lines;
                   7119: 
1.503     raeburn  7120:     foreach my $item (@{$questions}) {
                   7121:         my $question = $item;
                   7122:         my ($first,$count,$last);
                   7123:         if ($item =~ /^(\d+)\.(\d+)$/) {
                   7124:             $question = $1;
                   7125:             my $subquestion = $2;
                   7126:             $first = $first_bubble_line{$question-1} + 1;
                   7127:             my @subans = split(/,/,$subdivided_bubble_lines{$question-1});
                   7128:             my $subcount = 1;
                   7129:             while ($subcount<$subquestion) {
                   7130:                 $first += $subans[$subcount-1];
                   7131:                 $subcount ++;
                   7132:             }
                   7133:             $count = $subans[$subquestion-1];
                   7134:         } else {
                   7135: 	    $first   = $first_bubble_line{$question-1} + 1;
                   7136: 	    $count   = $bubble_lines_per_response{$question-1};
                   7137:         }
1.506     raeburn  7138:         $last = $first+$count-1;
1.503     raeburn  7139:         push(@lines, ($first..$last));
1.497     foxr     7140:     }
                   7141:     return join(',', @lines);
                   7142: }
                   7143: 
                   7144: =pod 
                   7145: 
                   7146: =item prompt_for_corrections
                   7147: 
                   7148: Prompts for a potentially multiline correction to the
                   7149: user's bubbling (factors out common code from scantron_get_correction
                   7150: for multi and missing bubble cases).
                   7151: 
                   7152:  Arguments:
                   7153:    $r           - Apache request object.
                   7154:    $question    - The question number to prompt for.
                   7155:    $scan_config - The scantron file configuration hash.
                   7156:    $scan_record - Reference to the hash that has the the parsed scanlines.
1.503     raeburn  7157:    $error       - Type of error
1.497     foxr     7158: 
                   7159:  Implicit inputs:
                   7160:    %bubble_lines_per_response   - Starting line numbers for each question.
                   7161:                                   Numbered from 0 (but question numbers are from
                   7162:                                   1.
                   7163:    %first_bubble_line           - Starting bubble line for each question.
1.509     raeburn  7164:    %subdivided_bubble_lines     - optionresponse, matchresponse and rankresponse 
                   7165:                                   type problems render as separate sub-questions, 
1.503     raeburn  7166:                                   in exam mode. This hash contains a 
                   7167:                                   comma-separated list of the lines per 
                   7168:                                   sub-question.
1.510     raeburn  7169:    %responsetype_per_response   - essayresponse, formularesponse,
                   7170:                                   stringresponse, imageresponse, reactionresponse,
                   7171:                                   and organicresponse type problem parts can have
1.503     raeburn  7172:                                   multiple lines per response if the weight
                   7173:                                   assigned exceeds 10.  In this case, only
                   7174:                                   one bubble per line is permitted, but more 
                   7175:                                   than one line might contain bubbles, e.g.
                   7176:                                   bubbling of: line 1 - J, line 2 - J, 
                   7177:                                   line 3 - B would assign 22 points.  
1.497     foxr     7178: 
                   7179: =cut
                   7180: 
                   7181: sub prompt_for_corrections {
1.503     raeburn  7182:     my ($r, $question, $scan_config, $scan_record, $error) = @_;
                   7183:     my ($current_line,$lines);
                   7184:     my @linenums;
                   7185:     my $questionnum = $question;
                   7186:     if ($question =~ /^(\d+)\.(\d+)$/) {
                   7187:         $question = $1;
                   7188:         $current_line = $first_bubble_line{$question-1} + 1 ;
                   7189:         my $subquestion = $2;
                   7190:         my @subans = split(/,/,$subdivided_bubble_lines{$question-1});
                   7191:         my $subcount = 1;
                   7192:         while ($subcount<$subquestion) {
                   7193:             $current_line += $subans[$subcount-1];
                   7194:             $subcount ++;
                   7195:         }
                   7196:         $lines = $subans[$subquestion-1];
                   7197:     } else {
                   7198:         $current_line = $first_bubble_line{$question-1} + 1 ;
                   7199:         $lines        = $bubble_lines_per_response{$question-1};
                   7200:     }
1.497     foxr     7201:     if ($lines > 1) {
1.503     raeburn  7202:         $r->print(&mt('The group of bubble lines below responds to a single question.').'<br />');
                   7203:         if (($responsetype_per_response{$question-1} eq 'essayresponse') ||
                   7204:             ($responsetype_per_response{$question-1} eq 'formularesponse') ||
1.510     raeburn  7205:             ($responsetype_per_response{$question-1} eq 'stringresponse') ||
                   7206:             ($responsetype_per_response{$question-1} eq 'imageresponse') ||
                   7207:             ($responsetype_per_response{$question-1} eq 'reactionresponse') ||
                   7208:             ($responsetype_per_response{$question-1} eq 'organicresponse')) {
1.572     www      7209:             $r->print(&mt("Although this particular question type requires handgrading, the instructions for this question in the exam directed students to leave [quant,_1,line] blank on their bubblesheets.",$lines).'<br /><br />'.&mt('A non-zero score can be assigned to the student during bubblesheet grading by selecting a bubble in at least one line.').'<br />'.&mt('The score for this question will be a sum of the numeric values for the selected bubbles from each line, where A=1 point, B=2 points etc.').'<br />'.&mt("To assign a score of zero for this question, mark all lines as 'No bubble'.").'<br /><br />');
1.503     raeburn  7210:         } else {
                   7211:             $r->print(&mt("Select at most one bubble in a single line and select 'No Bubble' in all the other lines. ")."<br />");
                   7212:         }
1.497     foxr     7213:     }
                   7214:     for (my $i =0; $i < $lines; $i++) {
1.503     raeburn  7215:         my $selected = $$scan_record{"scantron.$current_line.answer"};
                   7216: 	&scantron_bubble_selector($r,$scan_config,$current_line, 
                   7217: 	        		  $questionnum,$error,split('', $selected));
1.524     raeburn  7218:         push(@linenums,$current_line);
1.497     foxr     7219: 	$current_line++;
                   7220:     }
                   7221:     if ($lines > 1) {
                   7222: 	$r->print("<hr /><br />");
                   7223:     }
1.503     raeburn  7224:     return @linenums;
1.157     albertel 7225: }
1.423     albertel 7226: 
                   7227: =pod
                   7228: 
                   7229: =item scantron_bubble_selector
                   7230:   
                   7231:    Generates the html radiobuttons to correct a single bubble line
1.424     albertel 7232:    possibly showing the existing the selected bubbles if known
1.423     albertel 7233: 
                   7234:  Arguments:
                   7235:     $r           - Apache request object
                   7236:     $scan_config - hash from &get_scantron_config()
1.497     foxr     7237:     $line        - Number of the line being displayed.
1.503     raeburn  7238:     $questionnum - Question number (may include subquestion)
                   7239:     $error       - Type of error.
1.497     foxr     7240:     @selected    - Array of bubbles picked on this line.
1.423     albertel 7241: 
                   7242: =cut
                   7243: 
1.157     albertel 7244: sub scantron_bubble_selector {
1.503     raeburn  7245:     my ($r,$scan_config,$line,$questionnum,$error,@selected)=@_;
1.157     albertel 7246:     my $max=$$scan_config{'Qlength'};
1.274     albertel 7247: 
                   7248:     my $scmode=$$scan_config{'Qon'};
                   7249:     if ($scmode eq 'number' || $scmode eq 'letter') { $max=10; }	     
                   7250: 
1.157     albertel 7251:     my @alphabet=('A'..'Z');
1.503     raeburn  7252:     $r->print(&Apache::loncommon::start_data_table().
                   7253:               &Apache::loncommon::start_data_table_row());
                   7254:     $r->print('<td rowspan="2" class="LC_leftcol_header">'.$line.'</td>');
1.497     foxr     7255:     for (my $i=0;$i<$max+1;$i++) {
                   7256: 	$r->print("\n".'<td align="center">');
                   7257: 	if ($selected[0] eq $alphabet[$i]) { $r->print('X'); shift(@selected) }
                   7258: 	else { $r->print('&nbsp;'); }
                   7259: 	$r->print('</td>');
                   7260:     }
1.503     raeburn  7261:     $r->print(&Apache::loncommon::end_data_table_row().
                   7262:               &Apache::loncommon::start_data_table_row());
1.497     foxr     7263:     for (my $i=0;$i<$max;$i++) {
                   7264: 	$r->print("\n".
                   7265: 		  '<td><label><input type="radio" name="scantron_correct_Q_'.
                   7266: 		  $line.'" value="'.$i.'" />'.$alphabet[$i]."</label></td>");
                   7267:     }
1.503     raeburn  7268:     my $nobub_checked = ' ';
                   7269:     if ($error eq 'missingbubble') {
                   7270:         $nobub_checked = ' checked = "checked" ';
                   7271:     }
                   7272:     $r->print("\n".'<td><label><input type="radio" name="scantron_correct_Q_'.
                   7273: 	      $line.'" value="none"'.$nobub_checked.'/>'.&mt('No bubble').
                   7274:               '</label>'."\n".'<input type="hidden" name="scantron_questionnum_Q_'.
                   7275:               $line.'" value="'.$questionnum.'" /></td>');
                   7276:     $r->print(&Apache::loncommon::end_data_table_row().
                   7277:               &Apache::loncommon::end_data_table());
1.157     albertel 7278: }
                   7279: 
1.423     albertel 7280: =pod
                   7281: 
                   7282: =item num_matches
                   7283: 
1.424     albertel 7284:    Counts the number of characters that are the same between the two arguments.
                   7285: 
                   7286:  Arguments:
                   7287:    $orig - CODE from the scanline
                   7288:    $code - CODE to match against
                   7289: 
                   7290:  Returns:
                   7291:    $count - integer count of the number of same characters between the
                   7292:             two arguments
                   7293: 
1.423     albertel 7294: =cut
                   7295: 
1.194     albertel 7296: sub num_matches {
                   7297:     my ($orig,$code) = @_;
                   7298:     my @code=split(//,$code);
                   7299:     my @orig=split(//,$orig);
                   7300:     my $same=0;
                   7301:     for (my $i=0;$i<scalar(@code);$i++) {
                   7302: 	if ($code[$i] eq $orig[$i]) { $same++; }
                   7303:     }
                   7304:     return $same;
                   7305: }
                   7306: 
1.423     albertel 7307: =pod
                   7308: 
                   7309: =item scantron_get_closely_matching_CODEs
                   7310: 
1.424     albertel 7311:    Cycles through all CODEs and finds the set that has the greatest
                   7312:    number of same characters as the provided CODE
                   7313: 
                   7314:  Arguments:
                   7315:    $allcodes - hash ref returned by &get_codes()
                   7316:    $CODE     - CODE from the current scanline
                   7317: 
                   7318:  Returns:
                   7319:    2 element list
                   7320:     - first elements is number of how closely matching the best fit is 
                   7321:       (5 means best set has 5 matching characters)
                   7322:     - second element is an arrary ref containing the set of valid CODEs
                   7323:       that best fit the passed in CODE
                   7324: 
1.423     albertel 7325: =cut
                   7326: 
1.194     albertel 7327: sub scantron_get_closely_matching_CODEs {
                   7328:     my ($allcodes,$CODE)=@_;
                   7329:     my @CODEs;
                   7330:     foreach my $testcode (sort(keys(%{$allcodes}))) {
                   7331: 	push(@{$CODEs[&num_matches($CODE,$testcode)]},$testcode);
                   7332:     }
                   7333: 
                   7334:     return ($#CODEs,$CODEs[-1]);
                   7335: }
                   7336: 
1.423     albertel 7337: =pod
                   7338: 
                   7339: =item get_codes
                   7340: 
1.424     albertel 7341:    Builds a hash which has keys of all of the valid CODEs from the selected
                   7342:    set of remembered CODEs.
                   7343: 
                   7344:  Arguments:
                   7345:   $old_name - name of the set of remembered CODEs
                   7346:   $cdom     - domain of the course
                   7347:   $cnum     - internal course name
                   7348: 
                   7349:  Returns:
                   7350:   %allcodes - keys are the valid CODEs, values are all 1
                   7351: 
1.423     albertel 7352: =cut
                   7353: 
1.194     albertel 7354: sub get_codes {
1.280     foxr     7355:     my ($old_name, $cdom, $cnum) = @_;
                   7356:     if (!$old_name) {
                   7357: 	$old_name=$env{'form.scantron_CODElist'};
                   7358:     }
                   7359:     if (!$cdom) {
                   7360: 	$cdom =$env{'course.'.$env{'request.course.id'}.'.domain'};
                   7361:     }
                   7362:     if (!$cnum) {
                   7363: 	$cnum =$env{'course.'.$env{'request.course.id'}.'.num'};
                   7364:     }
1.278     albertel 7365:     my %result=&Apache::lonnet::get('CODEs',[$old_name,"type\0$old_name"],
                   7366: 				    $cdom,$cnum);
                   7367:     my %allcodes;
                   7368:     if ($result{"type\0$old_name"} eq 'number') {
                   7369: 	%allcodes=map {($_,1)} split(',',$result{$old_name});
                   7370:     } else {
                   7371: 	%allcodes=map {(&Apache::lonprintout::num_to_letters($_),1)} split(',',$result{$old_name});
                   7372:     }
1.194     albertel 7373:     return %allcodes;
                   7374: }
                   7375: 
1.423     albertel 7376: =pod
                   7377: 
                   7378: =item scantron_validate_CODE
                   7379: 
1.424     albertel 7380:    Validates all scanlines in the selected file to not have any
                   7381:    invalid or underspecified CODEs and that none of the codes are
                   7382:    duplicated if this was requested.
                   7383: 
1.423     albertel 7384: =cut
                   7385: 
1.157     albertel 7386: sub scantron_validate_CODE {
                   7387:     my ($r,$currentphase) = @_;
1.257     albertel 7388:     my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
1.186     albertel 7389:     if ($scantron_config{'CODElocation'} &&
                   7390: 	$scantron_config{'CODEstart'} &&
                   7391: 	$scantron_config{'CODElength'}) {
1.257     albertel 7392: 	if (!defined($env{'form.scantron_CODElist'})) {
1.186     albertel 7393: 	    &FIXME_blow_up()
                   7394: 	}
                   7395:     } else {
                   7396: 	return (0,$currentphase+1);
                   7397:     }
                   7398:     
                   7399:     my %usedCODEs;
                   7400: 
1.194     albertel 7401:     my %allcodes=&get_codes();
1.186     albertel 7402: 
1.582     raeburn  7403:     my $nav_error;
                   7404:     &scantron_get_maxbubble(\$nav_error); # parse needs the lines per response array.
                   7405:     if ($nav_error) {
                   7406:         $r->print(&navmap_errormsg());
                   7407:         return(1,$currentphase);
                   7408:     }
1.447     foxr     7409: 
1.186     albertel 7410:     my ($scanlines,$scan_data)=&scantron_getfile();
                   7411:     for (my $i=0;$i<=$scanlines->{'count'};$i++) {
1.200     albertel 7412: 	my $line=&scantron_get_line($scanlines,$scan_data,$i);
1.186     albertel 7413: 	if ($line=~/^[\s\cz]*$/) { next; }
                   7414: 	my $scan_record=&scantron_parse_scanline($line,$i,\%scantron_config,
                   7415: 						 $scan_data);
                   7416: 	my $CODE=$$scan_record{'scantron.CODE'};
                   7417: 	my $error=0;
1.224     albertel 7418: 	if (!&Apache::lonnet::validCODE($CODE)) {
                   7419: 	    &scantron_get_correction($r,$i,$scan_record,
                   7420: 				     \%scantron_config,
                   7421: 				     $line,'incorrectCODE',\%allcodes);
                   7422: 	    return(1,$currentphase);
                   7423: 	}
1.221     albertel 7424: 	if (%allcodes && !exists($allcodes{$CODE}) 
                   7425: 	    && !$$scan_record{'scantron.useCODE'}) {
1.186     albertel 7426: 	    &scantron_get_correction($r,$i,$scan_record,
                   7427: 				     \%scantron_config,
1.194     albertel 7428: 				     $line,'incorrectCODE',\%allcodes);
                   7429: 	    return(1,$currentphase);
1.186     albertel 7430: 	}
1.214     albertel 7431: 	if (exists($usedCODEs{$CODE}) 
1.257     albertel 7432: 	    && $env{'form.scantron_CODEunique'} eq 'yes'
1.192     albertel 7433: 	    && !$$scan_record{'scantron.CODE_ignore_dup'}) {
1.186     albertel 7434: 	    &scantron_get_correction($r,$i,$scan_record,
                   7435: 				     \%scantron_config,
1.194     albertel 7436: 				     $line,'duplicateCODE',$usedCODEs{$CODE});
                   7437: 	    return(1,$currentphase);
1.186     albertel 7438: 	}
1.524     raeburn  7439: 	push(@{$usedCODEs{$CODE}},$$scan_record{'scantron.PaperID'});
1.186     albertel 7440:     }
1.157     albertel 7441:     return (0,$currentphase+1);
                   7442: }
                   7443: 
1.423     albertel 7444: =pod
                   7445: 
                   7446: =item scantron_validate_doublebubble
                   7447: 
1.424     albertel 7448:    Validates all scanlines in the selected file to not have any
                   7449:    bubble lines with multiple bubbles marked.
                   7450: 
1.423     albertel 7451: =cut
                   7452: 
1.157     albertel 7453: sub scantron_validate_doublebubble {
                   7454:     my ($r,$currentphase) = @_;
                   7455:     #get student info
                   7456:     my $classlist=&Apache::loncoursedata::get_classlist();
                   7457:     my %idmap=&username_to_idmap($classlist);
                   7458: 
                   7459:     #get scantron line setup
1.257     albertel 7460:     my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
1.157     albertel 7461:     my ($scanlines,$scan_data)=&scantron_getfile();
1.583     raeburn  7462:     my $nav_error;
                   7463:     &scantron_get_maxbubble(\$nav_error); # parse needs the bubble line array.
                   7464:     if ($nav_error) {
                   7465:         $r->print(&navmap_errormsg());
                   7466:         return(1,$currentphase);
                   7467:     }
1.447     foxr     7468: 
1.157     albertel 7469:     for (my $i=0;$i<=$scanlines->{'count'};$i++) {
1.200     albertel 7470: 	my $line=&scantron_get_line($scanlines,$scan_data,$i);
1.157     albertel 7471: 	if ($line=~/^[\s\cz]*$/) { next; }
                   7472: 	my $scan_record=&scantron_parse_scanline($line,$i,\%scantron_config,
                   7473: 						 $scan_data);
                   7474: 	if (!defined($$scan_record{'scantron.doubleerror'})) { next; }
                   7475: 	&scantron_get_correction($r,$i,$scan_record,\%scantron_config,$line,
                   7476: 				 'doublebubble',
                   7477: 				 $$scan_record{'scantron.doubleerror'});
                   7478:     	return (1,$currentphase);
                   7479:     }
                   7480:     return (0,$currentphase+1);
                   7481: }
                   7482: 
1.423     albertel 7483: 
1.503     raeburn  7484: sub scantron_get_maxbubble {
1.582     raeburn  7485:     my ($nav_error) = @_;
1.257     albertel 7486:     if (defined($env{'form.scantron_maxbubble'}) &&
                   7487: 	$env{'form.scantron_maxbubble'}) {
1.447     foxr     7488: 	&restore_bubble_lines();
1.257     albertel 7489: 	return $env{'form.scantron_maxbubble'};
1.191     albertel 7490:     }
1.330     albertel 7491: 
1.447     foxr     7492:     my (undef, undef, $sequence) =
1.257     albertel 7493: 	&Apache::lonnet::decode_symb($env{'form.selectpage'});
1.330     albertel 7494: 
1.447     foxr     7495:     my $navmap=Apache::lonnavmaps::navmap->new();
1.582     raeburn  7496:     unless (ref($navmap)) {
                   7497:         if (ref($nav_error)) {
                   7498:             $$nav_error = 1;
                   7499:         }
1.591     raeburn  7500:         return;
1.582     raeburn  7501:     }
1.191     albertel 7502:     my $map=$navmap->getResourceByUrl($sequence);
                   7503:     my @resources=$navmap->retrieveResources($map,\&scantron_filter,1,0);
1.330     albertel 7504: 
                   7505:     &Apache::lonxml::clear_problem_counter();
                   7506: 
1.557     raeburn  7507:     my $uname       = $env{'user.name'};
                   7508:     my $udom        = $env{'user.domain'};
1.435     foxr     7509:     my $cid         = $env{'request.course.id'};
                   7510:     my $total_lines = 0;
                   7511:     %bubble_lines_per_response = ();
1.447     foxr     7512:     %first_bubble_line         = ();
1.503     raeburn  7513:     %subdivided_bubble_lines   = ();
                   7514:     %responsetype_per_response = ();
1.554     raeburn  7515: 
1.447     foxr     7516:     my $response_number = 0;
                   7517:     my $bubble_line     = 0;
1.191     albertel 7518:     foreach my $resource (@resources) {
1.542     raeburn  7519:         my ($analysis,$parts) = &scantron_partids_tograde($resource,$cid,$uname,$udom);
                   7520:         if ((ref($analysis) eq 'HASH') && (ref($parts) eq 'ARRAY')) {
                   7521: 	    foreach my $part_id (@{$parts}) {
                   7522:                 my $lines;
                   7523: 
                   7524: 	        # TODO - make this a persistent hash not an array.
                   7525: 
                   7526:                 # optionresponse, matchresponse and rankresponse type items 
                   7527:                 # render as separate sub-questions in exam mode.
                   7528:                 if (($analysis->{$part_id.'.type'} eq 'optionresponse') ||
                   7529:                     ($analysis->{$part_id.'.type'} eq 'matchresponse') ||
                   7530:                     ($analysis->{$part_id.'.type'} eq 'rankresponse')) {
                   7531:                     my ($numbub,$numshown);
                   7532:                     if ($analysis->{$part_id.'.type'} eq 'optionresponse') {
                   7533:                         if (ref($analysis->{$part_id.'.options'}) eq 'ARRAY') {
                   7534:                             $numbub = scalar(@{$analysis->{$part_id.'.options'}});
                   7535:                         }
                   7536:                     } elsif ($analysis->{$part_id.'.type'} eq 'matchresponse') {
                   7537:                         if (ref($analysis->{$part_id.'.items'}) eq 'ARRAY') {
                   7538:                             $numbub = scalar(@{$analysis->{$part_id.'.items'}});
                   7539:                         }
                   7540:                     } elsif ($analysis->{$part_id.'.type'} eq 'rankresponse') {
                   7541:                         if (ref($analysis->{$part_id.'.foils'}) eq 'ARRAY') {
                   7542:                             $numbub = scalar(@{$analysis->{$part_id.'.foils'}});
                   7543:                         }
                   7544:                     }
                   7545:                     if (ref($analysis->{$part_id.'.shown'}) eq 'ARRAY') {
                   7546:                         $numshown = scalar(@{$analysis->{$part_id.'.shown'}});
                   7547:                     }
                   7548:                     my $bubbles_per_line = 10;
                   7549:                     my $inner_bubble_lines = int($numbub/$bubbles_per_line);
                   7550:                     if (($numbub % $bubbles_per_line) != 0) {
                   7551:                         $inner_bubble_lines++;
                   7552:                     }
                   7553:                     for (my $i=0; $i<$numshown; $i++) {
                   7554:                         $subdivided_bubble_lines{$response_number} .= 
                   7555:                             $inner_bubble_lines.',';
                   7556:                     }
                   7557:                     $subdivided_bubble_lines{$response_number} =~ s/,$//;
                   7558:                     $lines = $numshown * $inner_bubble_lines;
                   7559:                 } else {
                   7560:                     $lines = $analysis->{"$part_id.bubble_lines"};
                   7561:                 } 
                   7562: 
                   7563:                 $first_bubble_line{$response_number} = $bubble_line;
                   7564: 	        $bubble_lines_per_response{$response_number} = $lines;
                   7565:                 $responsetype_per_response{$response_number} = 
                   7566:                     $analysis->{$part_id.'.type'};
                   7567: 	        $response_number++;
                   7568: 
                   7569: 	        $bubble_line +=  $lines;
                   7570: 	        $total_lines +=  $lines;
                   7571: 	    }
                   7572:         }
                   7573:     }
1.552     raeburn  7574:     &Apache::lonnet::delenv('scantron.');
1.542     raeburn  7575: 
                   7576:     &save_bubble_lines();
                   7577:     $env{'form.scantron_maxbubble'} =
                   7578: 	$total_lines;
                   7579:     return $env{'form.scantron_maxbubble'};
                   7580: }
1.523     raeburn  7581: 
1.157     albertel 7582: sub scantron_validate_missingbubbles {
                   7583:     my ($r,$currentphase) = @_;
                   7584:     #get student info
                   7585:     my $classlist=&Apache::loncoursedata::get_classlist();
                   7586:     my %idmap=&username_to_idmap($classlist);
                   7587: 
                   7588:     #get scantron line setup
1.257     albertel 7589:     my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
1.157     albertel 7590:     my ($scanlines,$scan_data)=&scantron_getfile();
1.582     raeburn  7591:     my $nav_error;
                   7592:     my $max_bubble=&scantron_get_maxbubble(\$nav_error);
                   7593:     if ($nav_error) {
                   7594:         return(1,$currentphase);
                   7595:     }
1.157     albertel 7596:     if (!$max_bubble) { $max_bubble=2**31; }
                   7597:     for (my $i=0;$i<=$scanlines->{'count'};$i++) {
1.200     albertel 7598: 	my $line=&scantron_get_line($scanlines,$scan_data,$i);
1.157     albertel 7599: 	if ($line=~/^[\s\cz]*$/) { next; }
                   7600: 	my $scan_record=&scantron_parse_scanline($line,$i,\%scantron_config,
                   7601: 						 $scan_data);
                   7602: 	if (!defined($$scan_record{'scantron.missingerror'})) { next; }
                   7603: 	my @to_correct;
1.470     foxr     7604: 	
                   7605: 	# Probably here's where the error is...
                   7606: 
1.157     albertel 7607: 	foreach my $missing (@{$$scan_record{'scantron.missingerror'}}) {
1.505     raeburn  7608:             my $lastbubble;
                   7609:             if ($missing =~ /^(\d+)\.(\d+)$/) {
                   7610:                my $question = $1;
                   7611:                my $subquestion = $2;
                   7612:                if (!defined($first_bubble_line{$question -1})) { next; }
                   7613:                my $first = $first_bubble_line{$question-1};
                   7614:                my @subans = split(/,/,$subdivided_bubble_lines{$question-1});
                   7615:                my $subcount = 1;
                   7616:                while ($subcount<$subquestion) {
                   7617:                    $first += $subans[$subcount-1];
                   7618:                    $subcount ++;
                   7619:                }
                   7620:                my $count = $subans[$subquestion-1];
                   7621:                $lastbubble = $first + $count;
                   7622:             } else {
                   7623:                 if (!defined($first_bubble_line{$missing - 1})) { next; }
                   7624:                 $lastbubble = $first_bubble_line{$missing - 1} + $bubble_lines_per_response{$missing - 1};
                   7625:             }
                   7626:             if ($lastbubble > $max_bubble) { next; }
1.157     albertel 7627: 	    push(@to_correct,$missing);
                   7628: 	}
                   7629: 	if (@to_correct) {
                   7630: 	    &scantron_get_correction($r,$i,$scan_record,\%scantron_config,
                   7631: 				     $line,'missingbubble',\@to_correct);
                   7632: 	    return (1,$currentphase);
                   7633: 	}
                   7634: 
                   7635:     }
                   7636:     return (0,$currentphase+1);
                   7637: }
                   7638: 
1.423     albertel 7639: 
1.82      albertel 7640: sub scantron_process_students {
1.75      albertel 7641:     my ($r) = @_;
1.513     foxr     7642: 
1.257     albertel 7643:     my (undef,undef,$sequence)=&Apache::lonnet::decode_symb($env{'form.selectpage'});
1.324     albertel 7644:     my ($symb)=&get_symb($r);
1.513     foxr     7645:     if (!$symb) {
                   7646: 	return '';
                   7647:     }
1.324     albertel 7648:     my $default_form_data=&defaultFormData($symb);
1.82      albertel 7649: 
1.257     albertel 7650:     my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
1.157     albertel 7651:     my ($scanlines,$scan_data)=&scantron_getfile();
1.82      albertel 7652:     my $classlist=&Apache::loncoursedata::get_classlist();
                   7653:     my %idmap=&username_to_idmap($classlist);
1.132     bowersj2 7654:     my $navmap=Apache::lonnavmaps::navmap->new();
1.582     raeburn  7655:     unless (ref($navmap)) {
                   7656:         $r->print(&navmap_errormsg());
                   7657:         return '';
                   7658:     }  
1.83      albertel 7659:     my $map=$navmap->getResourceByUrl($sequence);
                   7660:     my @resources=$navmap->retrieveResources($map,\&scantron_filter,1,0);
1.557     raeburn  7661:     my (%grader_partids_by_symb,%grader_randomlists_by_symb);
                   7662:     &graders_resources_pass(\@resources,\%grader_partids_by_symb,
                   7663:                             \%grader_randomlists_by_symb);
1.586     raeburn  7664:     my $resource_error;
1.557     raeburn  7665:     foreach my $resource (@resources) {
1.586     raeburn  7666:         my $ressymb;
                   7667:         if (ref($resource)) {
                   7668:             $ressymb = $resource->symb();
                   7669:         } else {
                   7670:             $resource_error = 1;
                   7671:             last;
                   7672:         }
1.557     raeburn  7673:         my ($analysis,$parts) =
                   7674:             &scantron_partids_tograde($resource,$env{'request.course.id'},
                   7675:                                       $env{'user.name'},$env{'user.domain'},1);
                   7676:         $grader_partids_by_symb{$ressymb} = $parts;
                   7677:         if (ref($analysis) eq 'HASH') {
                   7678:             if (ref($analysis->{'parts_withrandomlist'}) eq 'ARRAY') {
                   7679:                 $grader_randomlists_by_symb{$ressymb} = 
                   7680:                     $analysis->{'parts_withrandomlist'};
                   7681:             }
                   7682:         }
                   7683:     }
1.586     raeburn  7684:     if ($resource_error) {
                   7685:         $r->print(&navmap_errormsg());
                   7686:         return '';
                   7687:     }
1.557     raeburn  7688: 
1.554     raeburn  7689:     my ($uname,$udom);
1.82      albertel 7690:     my $result= <<SCANTRONFORM;
1.81      albertel 7691: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="scantronupload">
                   7692:   <input type="hidden" name="command" value="scantron_configphase" />
                   7693:   $default_form_data
                   7694: SCANTRONFORM
1.82      albertel 7695:     $r->print($result);
                   7696: 
                   7697:     my @delayqueue;
1.542     raeburn  7698:     my (%completedstudents,%scandata);
1.140     albertel 7699:     
1.520     www      7700:     my $lock=&Apache::lonnet::set_lock(&mt('Grading bubblesheet exam'));
1.200     albertel 7701:     my $count=&get_todo_count($scanlines,$scan_data);
1.575     www      7702:     my %prog_state=&Apache::lonhtmlcommon::Create_PrgWin($r,'Bubblesheet Status',
                   7703:  				    'Bubblesheet Progress',$count,
1.195     albertel 7704: 				    'inline',undef,'scantronupload');
1.140     albertel 7705:     &Apache::lonhtmlcommon::Update_PrgWin($r,\%prog_state,
                   7706: 					  'Processing first student');
1.542     raeburn  7707:     $r->print('<br />');
1.140     albertel 7708:     my $start=&Time::HiRes::time();
1.158     albertel 7709:     my $i=-1;
1.542     raeburn  7710:     my $started;
1.447     foxr     7711: 
1.582     raeburn  7712:     my $nav_error;
                   7713:     &scantron_get_maxbubble(\$nav_error); # Need the bubble lines array to parse.
                   7714:     if ($nav_error) {
                   7715:         $r->print(&navmap_errormsg());
                   7716:         return '';
                   7717:     }
                   7718: 
1.513     foxr     7719:     # If an ssi failed in scantron_get_maxbubble, put an error message out to
                   7720:     # the user and return.
                   7721: 
                   7722:     if ($ssi_error) {
                   7723: 	$r->print("</form>");
                   7724: 	&ssi_print_error($r);
                   7725: 	$r->print(&show_grading_menu_form($symb));
1.520     www      7726:         &Apache::lonnet::remove_lock($lock);
1.513     foxr     7727: 	return '';		# Dunno why the other returns return '' rather than just returning.
                   7728:     }
1.447     foxr     7729: 
1.542     raeburn  7730:     my %lettdig = &letter_to_digits();
                   7731:     my $numletts = scalar(keys(%lettdig));
                   7732: 
1.157     albertel 7733:     while ($i<$scanlines->{'count'}) {
                   7734:  	($uname,$udom)=('','');
                   7735:  	$i++;
1.200     albertel 7736:  	my $line=&scantron_get_line($scanlines,$scan_data,$i);
1.157     albertel 7737:  	if ($line=~/^[\s\cz]*$/) { next; }
1.200     albertel 7738: 	if ($started) {
                   7739: 	    &Apache::lonhtmlcommon::Increment_PrgWin($r,\%prog_state,
                   7740: 						     'last student');
                   7741: 	}
                   7742: 	$started=1;
1.157     albertel 7743:  	my $scan_record=&scantron_parse_scanline($line,$i,\%scantron_config,
                   7744:  						 $scan_data);
                   7745:  	unless ($uname=&scantron_find_student($scan_record,$scan_data,
                   7746:  					      \%idmap,$i)) {
                   7747:   	    &scantron_add_delay(\@delayqueue,$line,
                   7748:  				'Unable to find a student that matches',1);
                   7749:  	    next;
                   7750:   	}
                   7751:  	if (exists $completedstudents{$uname}) {
                   7752:  	    &scantron_add_delay(\@delayqueue,$line,
                   7753:  				'Student '.$uname.' has multiple sheets',2);
                   7754:  	    next;
                   7755:  	}
                   7756:   	($uname,$udom)=split(/:/,$uname);
1.330     albertel 7757: 
1.586     raeburn  7758:         my (%partids_by_symb,$res_error);
1.554     raeburn  7759:         foreach my $resource (@resources) {
1.586     raeburn  7760:             my $ressymb;
                   7761:             if (ref($resource)) {
                   7762:                 $ressymb = $resource->symb();
                   7763:             } else {
                   7764:                 $res_error = 1;
                   7765:                 last;
                   7766:             }
1.557     raeburn  7767:             if ((exists($grader_randomlists_by_symb{$ressymb})) ||
                   7768:                 (ref($grader_partids_by_symb{$ressymb}) ne 'ARRAY')) {
                   7769:                 my ($analysis,$parts) =
                   7770:                     &scantron_partids_tograde($resource,$env{'request.course.id'},$uname,$udom);
                   7771:                 $partids_by_symb{$ressymb} = $parts;
                   7772:             } else {
                   7773:                 $partids_by_symb{$ressymb} = $grader_partids_by_symb{$ressymb};
                   7774:             }
1.554     raeburn  7775:         }
                   7776: 
1.586     raeburn  7777:         if ($res_error) {
                   7778:             &scantron_add_delay(\@delayqueue,$line,
                   7779:                                 'An error occurred while grading student '.$uname,2);
                   7780:             next;
                   7781:         }
                   7782: 
1.330     albertel 7783: 	&Apache::lonxml::clear_problem_counter();
1.514     raeburn  7784:   	&Apache::lonnet::appenv($scan_record);
1.376     albertel 7785: 
                   7786: 	if (&scantron_clear_skip($scanlines,$scan_data,$i)) {
                   7787: 	    &scantron_putfile($scanlines,$scan_data);
                   7788: 	}
1.161     albertel 7789: 	
1.542     raeburn  7790:         my $scancode;
                   7791:         if ((exists($scan_record->{'scantron.CODE'})) &&
                   7792:             (&Apache::lonnet::validCODE($scan_record->{'scantron.CODE'}))) {
                   7793:             $scancode = $scan_record->{'scantron.CODE'};
                   7794:         } else {
                   7795:             $scancode = '';
                   7796:         }
                   7797: 
                   7798:         if (&grade_student_bubbles($r,$uname,$udom,$scan_record,$scancode,
1.554     raeburn  7799:                                    \@resources,\%partids_by_symb) eq 'ssi_error') {
1.542     raeburn  7800:             $ssi_error = 0; # So end of handler error message does not trigger.
                   7801:             $r->print("</form>");
                   7802:             &ssi_print_error($r);
                   7803:             $r->print(&show_grading_menu_form($symb));
                   7804:             &Apache::lonnet::remove_lock($lock);
                   7805:             return '';      # Why return ''?  Beats me.
                   7806:         }
1.513     foxr     7807: 
1.140     albertel 7808: 	$completedstudents{$uname}={'line'=>$line};
1.542     raeburn  7809:         if ($env{'form.verifyrecord'}) {
                   7810:             my $lastpos = $env{'form.scantron_maxbubble'}*$scantron_config{'Qlength'};
                   7811:             my $studentdata = substr($line,$scantron_config{'Qstart'}-1,$lastpos);
                   7812:             chomp($studentdata);
                   7813:             $studentdata =~ s/\r$//;
                   7814:             my $studentrecord = '';
                   7815:             my $counter = -1;
                   7816:             foreach my $resource (@resources) {
1.554     raeburn  7817:                 my $ressymb = $resource->symb();
1.542     raeburn  7818:                 ($counter,my $recording) =
                   7819:                     &verify_scantron_grading($resource,$udom,$uname,$env{'request.course.id'},
1.554     raeburn  7820:                                              $counter,$studentdata,$partids_by_symb{$ressymb},
1.542     raeburn  7821:                                              \%scantron_config,\%lettdig,$numletts);
                   7822:                 $studentrecord .= $recording;
                   7823:             }
                   7824:             if ($studentrecord ne $studentdata) {
1.554     raeburn  7825:                 &Apache::lonxml::clear_problem_counter();
                   7826:                 if (&grade_student_bubbles($r,$uname,$udom,$scan_record,$scancode,
                   7827:                                            \@resources,\%partids_by_symb) eq 'ssi_error') {
                   7828:                     $ssi_error = 0; # So end of handler error message does not trigger.
                   7829:                     $r->print("</form>");
                   7830:                     &ssi_print_error($r);
                   7831:                     $r->print(&show_grading_menu_form($symb));
                   7832:                     &Apache::lonnet::remove_lock($lock);
                   7833:                     delete($completedstudents{$uname});
                   7834:                     return '';
                   7835:                 }
1.542     raeburn  7836:                 $counter = -1;
                   7837:                 $studentrecord = '';
                   7838:                 foreach my $resource (@resources) {
1.554     raeburn  7839:                     my $ressymb = $resource->symb();
1.542     raeburn  7840:                     ($counter,my $recording) =
                   7841:                         &verify_scantron_grading($resource,$udom,$uname,$env{'request.course.id'},
1.554     raeburn  7842:                                                  $counter,$studentdata,$partids_by_symb{$ressymb},
1.542     raeburn  7843:                                                  \%scantron_config,\%lettdig,$numletts);
                   7844:                     $studentrecord .= $recording;
                   7845:                 }
                   7846:                 if ($studentrecord ne $studentdata) {
                   7847:                     $r->print('<p><span class="LC_error">');
                   7848:                     if ($scancode eq '') {
                   7849:                         $r->print(&mt('Mismatch grading bubble sheet for user: [_1] with ID: [_2].',
                   7850:                                   $uname.':'.$udom,$scan_record->{'scantron.ID'}));
                   7851:                     } else {
                   7852:                         $r->print(&mt('Mismatch grading bubble sheet for user: [_1] with ID: [_2] and CODE: [_3].',
                   7853:                                   $uname.':'.$udom,$scan_record->{'scantron.ID'},$scancode));
                   7854:                     }
                   7855:                     $r->print('</span><br />'.&Apache::loncommon::start_data_table()."\n".
                   7856:                               &Apache::loncommon::start_data_table_header_row()."\n".
                   7857:                               '<th>'.&mt('Source').'</th><th>'.&mt('Bubbled responses').'</th>'.
                   7858:                               &Apache::loncommon::end_data_table_header_row()."\n".
                   7859:                               &Apache::loncommon::start_data_table_row().
                   7860:                               '<td>'.&mt('Bubble Sheet').'</td>'.
                   7861:                               '<td><span class="LC_nobreak">'.$studentdata.'</span></td>'.
                   7862:                               &Apache::loncommon::end_data_table_row().
                   7863:                               &Apache::loncommon::start_data_table_row().
                   7864:                               '<td>Stored submissions</td>'.
                   7865:                               '<td><span class="LC_nobreak">'.$studentrecord.'</span></td>'."\n".
                   7866:                               &Apache::loncommon::end_data_table_row().
                   7867:                               &Apache::loncommon::end_data_table().'</p>');
                   7868:                 } else {
                   7869:                     $r->print('<br /><span class="LC_warning">'.
                   7870:                              &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 />'.
                   7871:                              &mt("As a consequence, this user's submission history records two tries.").
                   7872:                                  '</span><br />');
                   7873:                 }
                   7874:             }
                   7875:         }
1.543     raeburn  7876:         if (&Apache::loncommon::connection_aborted($r)) { last; }
1.140     albertel 7877:     } continue {
1.330     albertel 7878: 	&Apache::lonxml::clear_problem_counter();
1.552     raeburn  7879: 	&Apache::lonnet::delenv('scantron.');
1.82      albertel 7880:     }
1.140     albertel 7881:     &Apache::lonhtmlcommon::Close_PrgWin($r,\%prog_state);
1.520     www      7882:     &Apache::lonnet::remove_lock($lock);
1.172     albertel 7883: #    my $lasttime = &Time::HiRes::time()-$start;
                   7884: #    $r->print("<p>took $lasttime</p>");
1.140     albertel 7885: 
1.200     albertel 7886:     $r->print("</form>");
1.324     albertel 7887:     $r->print(&show_grading_menu_form($symb));
1.157     albertel 7888:     return '';
1.75      albertel 7889: }
1.157     albertel 7890: 
1.557     raeburn  7891: sub graders_resources_pass {
                   7892:     my ($resources,$grader_partids_by_symb,$grader_randomlists_by_symb) = @_;
                   7893:     if ((ref($resources) eq 'ARRAY') && (ref($grader_partids_by_symb)) && 
                   7894:         (ref($grader_randomlists_by_symb) eq 'HASH')) {
                   7895:         foreach my $resource (@{$resources}) {
                   7896:             my $ressymb = $resource->symb();
                   7897:             my ($analysis,$parts) =
                   7898:                 &scantron_partids_tograde($resource,$env{'request.course.id'},
                   7899:                                           $env{'user.name'},$env{'user.domain'},1);
                   7900:             $grader_partids_by_symb->{$ressymb} = $parts;
                   7901:             if (ref($analysis) eq 'HASH') {
                   7902:                 if (ref($analysis->{'parts_withrandomlist'}) eq 'ARRAY') {
                   7903:                     $grader_randomlists_by_symb->{$ressymb} =
                   7904:                         $analysis->{'parts_withrandomlist'};
                   7905:                 }
                   7906:             }
                   7907:         }
                   7908:     }
                   7909:     return;
                   7910: }
                   7911: 
1.542     raeburn  7912: sub grade_student_bubbles {
1.554     raeburn  7913:     my ($r,$uname,$udom,$scan_record,$scancode,$resources,$parts) = @_;
                   7914:     if (ref($resources) eq 'ARRAY') {
                   7915:         my $count = 0;
                   7916:         foreach my $resource (@{$resources}) {
                   7917:             my $ressymb = $resource->symb();
                   7918:             my %form = ('submitted'      => 'scantron',
                   7919:                         'grade_target'   => 'grade',
                   7920:                         'grade_username' => $uname,
                   7921:                         'grade_domain'   => $udom,
                   7922:                         'grade_courseid' => $env{'request.course.id'},
                   7923:                         'grade_symb'     => $ressymb,
                   7924:                         'CODE'           => $scancode
                   7925:                        );
                   7926:             if (ref($parts) eq 'HASH') {
                   7927:                 if (ref($parts->{$ressymb}) eq 'ARRAY') {
                   7928:                     foreach my $part (@{$parts->{$ressymb}}) {
                   7929:                         $form{'scantron_questnum_start.'.$part} =
                   7930:                             1+$env{'form.scantron.first_bubble_line.'.$count};
                   7931:                         $count++;
                   7932:                     }
                   7933:                 }
                   7934:             }
                   7935:             my $result=&ssi_with_retries($resource->src(),$ssi_retries,%form);
                   7936:             return 'ssi_error' if ($ssi_error);
                   7937:             last if (&Apache::loncommon::connection_aborted($r));
                   7938:         }
1.542     raeburn  7939:     }
                   7940:     return;
                   7941: }
                   7942: 
1.157     albertel 7943: sub scantron_upload_scantron_data {
                   7944:     my ($r)=@_;
1.565     raeburn  7945:     my $dom = $env{'request.role.domain'};
                   7946:     my $domdesc = &Apache::lonnet::domain($dom,'description');
                   7947:     $r->print(&Apache::loncommon::coursebrowser_javascript($dom));
1.157     albertel 7948:     my $select_link=&Apache::loncommon::selectcourse_link('rules','courseid',
1.181     albertel 7949: 							  'domainid',
1.565     raeburn  7950: 							  'coursename',$dom);
                   7951:     my $syllabuslink = '<a href="javascript:ToSyllabus();">'.&mt('Syllabus').'</a>'.
                   7952:                        ('&nbsp'x2).&mt('(shows course personnel)'); 
1.324     albertel 7953:     my $default_form_data=&defaultFormData(&get_symb($r,1));
1.579     raeburn  7954:     my $nofile_alert = &mt('Please use the browse button to select a file from your local directory.');
                   7955:     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.597   ! wenzelju 7956:     $r->print(&Apache::lonhtmlcommon::scripttag('
1.157     albertel 7957:     function checkUpload(formname) {
                   7958: 	if (formname.upfile.value == "") {
1.579     raeburn  7959: 	    alert("'.$nofile_alert.'");
1.157     albertel 7960: 	    return false;
                   7961: 	}
1.565     raeburn  7962:         if (formname.courseid.value == "") {
1.579     raeburn  7963:             alert("'.$nocourseid_alert.'");
1.565     raeburn  7964:             return false;
                   7965:         }
1.157     albertel 7966: 	formname.submit();
                   7967:     }
1.565     raeburn  7968: 
                   7969:     function ToSyllabus() {
                   7970:         var cdom = '."'$dom'".';
                   7971:         var cnum = document.rules.courseid.value;
                   7972:         if (cdom == "" || cdom == null) {
                   7973:             return;
                   7974:         }
                   7975:         if (cnum == "" || cnum == null) {
                   7976:            return;
                   7977:         }
                   7978:         syllwin=window.open("/public/"+cdom+"/"+cnum+"/syllabus","LONCAPASyllabus",
                   7979:                             "height=350,width=350,scrollbars=yes,menubar=no");
                   7980:         return;
                   7981:     }
                   7982: 
1.597   ! wenzelju 7983: '));
        !          7984:     $r->print('
1.566     raeburn  7985: <h3>'.&mt('Send scanned bubblesheet data to a course').'</h3>
                   7986: 
1.492     albertel 7987: <form enctype="multipart/form-data" action="/adm/grades" name="rules" method="post">
1.565     raeburn  7988: '.$default_form_data.
                   7989:   &Apache::lonhtmlcommon::start_pick_box().
                   7990:   &Apache::lonhtmlcommon::row_title(&mt('Course ID')).
                   7991:   '<input name="courseid" type="text" size="30" />'.$select_link.
                   7992:   &Apache::lonhtmlcommon::row_closure().
                   7993:   &Apache::lonhtmlcommon::row_title(&mt('Course Name')).
                   7994:   '<input name="coursename" type="text" size="30" />'.$syllabuslink.
                   7995:   &Apache::lonhtmlcommon::row_closure().
                   7996:   &Apache::lonhtmlcommon::row_title(&mt('Domain')).
                   7997:   '<input name="domainid" type="hidden" />'.$domdesc.
                   7998:   &Apache::lonhtmlcommon::row_closure().
                   7999:   &Apache::lonhtmlcommon::row_title(&mt('File to upload')).
                   8000:   '<input type="file" name="upfile" size="50" />'.
                   8001:   &Apache::lonhtmlcommon::row_closure(1).
                   8002:   &Apache::lonhtmlcommon::end_pick_box().'<br />
                   8003: 
1.492     albertel 8004: <input name="command" value="scantronupload_save" type="hidden" />
1.589     bisitz   8005: <input type="button" onclick="javascript:checkUpload(this.form);" value="'.&mt('Upload Bubblesheet Data').'" />
1.157     albertel 8006: </form>
1.492     albertel 8007: ');
1.157     albertel 8008:     return '';
                   8009: }
                   8010: 
1.423     albertel 8011: 
1.157     albertel 8012: sub scantron_upload_scantron_data_save {
                   8013:     my($r)=@_;
1.324     albertel 8014:     my ($symb)=&get_symb($r,1);
1.182     albertel 8015:     my $doanotherupload=
                   8016: 	'<br /><form action="/adm/grades" method="post">'."\n".
                   8017: 	'<input type="hidden" name="command" value="scantronupload" />'."\n".
1.492     albertel 8018: 	'<input type="submit" name="submit" value="'.&mt('Do Another Upload').'" />'."\n".
1.182     albertel 8019: 	'</form>'."\n";
1.257     albertel 8020:     if (!&Apache::lonnet::allowed('usc',$env{'form.domainid'}) &&
1.162     albertel 8021: 	!&Apache::lonnet::allowed('usc',
1.257     albertel 8022: 			    $env{'form.domainid'}.'_'.$env{'form.courseid'})) {
1.575     www      8023: 	$r->print(&mt("You are not allowed to upload bubblesheet data to the requested course.")."<br />");
1.182     albertel 8024: 	if ($symb) {
1.324     albertel 8025: 	    $r->print(&show_grading_menu_form($symb));
1.182     albertel 8026: 	} else {
                   8027: 	    $r->print($doanotherupload);
                   8028: 	}
1.162     albertel 8029: 	return '';
                   8030:     }
1.257     albertel 8031:     my %coursedata=&Apache::lonnet::coursedescription($env{'form.domainid'}.'_'.$env{'form.courseid'});
1.568     raeburn  8032:     my $uploadedfile;
1.567     raeburn  8033:     $r->print('<h3>'.&mt("Uploading file to [_1]",$coursedata{'description'}).'</h3>');
1.257     albertel 8034:     if (length($env{'form.upfile'}) < 2) {
1.568     raeburn  8035:         $r->print(&mt('[_1]Error:[_2] The file you attempted to upload, [_3] contained no information. Please check that you entered the correct filename.','<span class="LC_error">','</span>','<span class="LC_filename">'.&HTML::Entities::encode($env{'form.upfile.filename'},'<>&"').'</span>'));
1.183     albertel 8036:     } else {
1.568     raeburn  8037:         my $result = 
                   8038:             &Apache::lonnet::userfileupload('upfile','','scantron','','','',
                   8039:                                             $env{'form.courseid'},$env{'form.domainid'});
                   8040: 	if ($result =~ m{^/uploaded/}) {
1.567     raeburn  8041: 	    $r->print(&mt('[_1]Success:[_2] Successfully uploaded [_3] bytes of data into location: [_4]',
                   8042:                           '<span class="LC_success">','</span>',(length($env{'form.upfile'})-1),
                   8043: 			  '<span class="LC_filename">'.$result.'</span>'));
1.568     raeburn  8044:             ($uploadedfile) = ($result =~ m{/([^/]+)$});
1.567     raeburn  8045:             $r->print(&validate_uploaded_scantron_file($env{'form.domainid'},
1.568     raeburn  8046:                                                        $env{'form.courseid'},$uploadedfile));
1.210     albertel 8047: 	} else {
1.567     raeburn  8048: 	    $r->print(&mt('[_1]Error:[_2] An error ([_3]) occurred when attempting to upload the file, [_4]',
                   8049:                           '<span class="LC_error">','</span>',$result,
1.568     raeburn  8050: 			  '<span class="LC_filename">'.&HTML::Entities::encode($env{'form.upfile.filename'},'<>&"').'</span>'));
1.183     albertel 8051: 	}
                   8052:     }
1.174     albertel 8053:     if ($symb) {
1.209     ng       8054: 	$r->print(&scantron_selectphase($r,$uploadedfile));
1.174     albertel 8055:     } else {
1.182     albertel 8056: 	$r->print($doanotherupload);
1.174     albertel 8057:     }
1.157     albertel 8058:     return '';
                   8059: }
                   8060: 
1.567     raeburn  8061: sub validate_uploaded_scantron_file {
                   8062:     my ($cdom,$cname,$fname) = @_;
                   8063:     my $scanlines=&Apache::lonnet::getfile('/uploaded/'.$cdom.'/'.$cname.'/'.$fname);
                   8064:     my @lines;
                   8065:     if ($scanlines ne '-1') {
                   8066:         @lines=split("\n",$scanlines,-1);
                   8067:     }
                   8068:     my $output;
                   8069:     if (@lines) {
                   8070:         my (%counts,$max_match_format);
                   8071:         my ($max_match_count,$max_match_pct) = (0,0);
                   8072:         my $classlist = &Apache::loncoursedata::get_classlist($cdom,$cname);
                   8073:         my %idmap = &username_to_idmap($classlist);
                   8074:         foreach my $key (keys(%idmap)) {
                   8075:             my $lckey = lc($key);
                   8076:             $idmap{$lckey} = $idmap{$key};
                   8077:         }
                   8078:         my %unique_formats;
                   8079:         my @formatlines = &get_scantronformat_file();
                   8080:         foreach my $line (@formatlines) {
                   8081:             chomp($line);
                   8082:             my @config = split(/:/,$line);
                   8083:             my $idstart = $config[5];
                   8084:             my $idlength = $config[6];
                   8085:             if (($idstart ne '') && ($idlength > 0)) {
                   8086:                 if (ref($unique_formats{$idstart.':'.$idlength}) eq 'ARRAY') {
                   8087:                     push(@{$unique_formats{$idstart.':'.$idlength}},$config[0].':'.$config[1]); 
                   8088:                 } else {
                   8089:                     $unique_formats{$idstart.':'.$idlength} = [$config[0].':'.$config[1]];
                   8090:                 }
                   8091:             }
                   8092:         }
                   8093:         foreach my $key (keys(%unique_formats)) {
                   8094:             my ($idstart,$idlength) = split(':',$key);
                   8095:             %{$counts{$key}} = (
                   8096:                                'found'   => 0,
                   8097:                                'total'   => 0,
                   8098:                               );
                   8099:             foreach my $line (@lines) {
                   8100:                 next if ($line =~ /^#/);
                   8101:                 next if ($line =~ /^[\s\cz]*$/);
                   8102:                 my $id = substr($line,$idstart-1,$idlength);
                   8103:                 $id = lc($id);
                   8104:                 if (exists($idmap{$id})) {
                   8105:                     $counts{$key}{'found'} ++;
                   8106:                 }
                   8107:                 $counts{$key}{'total'} ++;
                   8108:             }
                   8109:             if ($counts{$key}{'total'}) {
                   8110:                 my $percent_match = (100*$counts{$key}{'found'})/($counts{$key}{'total'});
                   8111:                 if (($max_match_format eq '') || ($percent_match > $max_match_pct)) {
                   8112:                     $max_match_pct = $percent_match;
                   8113:                     $max_match_format = $key;
                   8114:                     $max_match_count = $counts{$key}{'total'};
                   8115:                 }
                   8116:             }
                   8117:         }
                   8118:         if (ref($unique_formats{$max_match_format}) eq 'ARRAY') {
                   8119:             my $format_descs;
                   8120:             my $numwithformat = @{$unique_formats{$max_match_format}};
                   8121:             for (my $i=0; $i<$numwithformat; $i++) {
                   8122:                 my ($name,$desc) = split(':',$unique_formats{$max_match_format}[$i]);
                   8123:                 if ($i<$numwithformat-2) {
                   8124:                     $format_descs .= '"<i>'.$desc.'</i>", ';
                   8125:                 } elsif ($i==$numwithformat-2) {
                   8126:                     $format_descs .= '"<i>'.$desc.'</i>" '.&mt('and').' ';
                   8127:                 } elsif ($i==$numwithformat-1) {
                   8128:                     $format_descs .= '"<i>'.$desc.'</i>"';
                   8129:                 }
                   8130:             }
                   8131:             my $showpct = sprintf("%.0f",$max_match_pct).'%';
                   8132:             $output .= '<br />'.&mt('Comparison of student IDs in the uploaded file with the course roster found matches for [_1] of the [_2] entries in the file (for the format defined for [_3]).','<b>'.$showpct.'</b>','<b>'.$max_match_count.'</b>',$format_descs).
                   8133:                        '<br />'.&mt('A low percentage of matches results from one of the following:').'<ul>'.
                   8134:                        '<li>'.&mt('The file was uploaded to the wrong course').'</li>'.
                   8135:                        '<li>'.&mt('The data are not in the format expected for the domain: [_1]',
                   8136:                                   '<i>'.$cdom.'</i>').'</li>'.
                   8137:                        '<li>'.&mt('Students did not bubble their IDs, or mis-bubbled them').'</li>'.
                   8138:                        '<li>'.&mt('The course roster is not up to date').'</li>'.
                   8139:                        '</ul>';
                   8140:         }
                   8141:     } else {
                   8142:         $output = '<span class="LC_warning">'.&mt('Uploaded file contained no data').'</span>';
                   8143:     }
                   8144:     return $output;
                   8145: }
                   8146: 
1.202     albertel 8147: sub valid_file {
                   8148:     my ($requested_file)=@_;
                   8149:     foreach my $filename (sort(&scantron_filenames())) {
                   8150: 	if ($requested_file eq $filename) { return 1; }
                   8151:     }
                   8152:     return 0;
                   8153: }
                   8154: 
                   8155: sub scantron_download_scantron_data {
                   8156:     my ($r)=@_;
1.324     albertel 8157:     my $default_form_data=&defaultFormData(&get_symb($r,1));
1.257     albertel 8158:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   8159:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
                   8160:     my $file=$env{'form.scantron_selectfile'};
1.202     albertel 8161:     if (! &valid_file($file)) {
1.492     albertel 8162: 	$r->print('
1.202     albertel 8163: 	<p>
1.492     albertel 8164: 	    '.&mt('The requested file name was invalid.').'
1.202     albertel 8165:         </p>
1.492     albertel 8166: ');
1.324     albertel 8167: 	$r->print(&show_grading_menu_form(&get_symb($r,1)));
1.202     albertel 8168: 	return;
                   8169:     }
                   8170:     my $orig='/uploaded/'.$cdom.'/'.$cname.'/scantron_orig_'.$file;
                   8171:     my $corrected='/uploaded/'.$cdom.'/'.$cname.'/scantron_corrected_'.$file;
                   8172:     my $skipped='/uploaded/'.$cdom.'/'.$cname.'/scantron_skipped_'.$file;
                   8173:     &Apache::lonnet::allowuploaded('/adm/grades',$orig);
                   8174:     &Apache::lonnet::allowuploaded('/adm/grades',$corrected);
                   8175:     &Apache::lonnet::allowuploaded('/adm/grades',$skipped);
1.492     albertel 8176:     $r->print('
1.202     albertel 8177:     <p>
1.492     albertel 8178: 	'.&mt('[_1]Original[_2] file as uploaded by the scantron office.',
                   8179: 	      '<a href="'.$orig.'">','</a>').'
1.202     albertel 8180:     </p>
                   8181:     <p>
1.492     albertel 8182: 	'.&mt('[_1]Corrections[_2], a file of corrected records that were used in grading.',
                   8183: 	      '<a href="'.$corrected.'">','</a>').'
1.202     albertel 8184:     </p>
                   8185:     <p>
1.492     albertel 8186: 	'.&mt('[_1]Skipped[_2], a file of records that were skipped.',
                   8187: 	      '<a href="'.$skipped.'">','</a>').'
1.202     albertel 8188:     </p>
1.492     albertel 8189: ');
1.324     albertel 8190:     $r->print(&show_grading_menu_form(&get_symb($r,1)));
1.202     albertel 8191:     return '';
                   8192: }
1.157     albertel 8193: 
1.523     raeburn  8194: sub checkscantron_results {
                   8195:     my ($r) = @_;
                   8196:     my ($symb)=&get_symb($r);
                   8197:     if (!$symb) {return '';}
                   8198:     my $grading_menu_button=&show_grading_menu_form($symb);
                   8199:     my $cid = $env{'request.course.id'};
1.542     raeburn  8200:     my %lettdig = &letter_to_digits();
1.523     raeburn  8201:     my $numletts = scalar(keys(%lettdig));
                   8202:     my $cnum = $env{'course.'.$cid.'.num'};
                   8203:     my $cdom = $env{'course.'.$cid.'.domain'};
                   8204:     my (undef, undef, $sequence) = &Apache::lonnet::decode_symb($env{'form.selectpage'});
                   8205:     my %record;
                   8206:     my %scantron_config =
                   8207:         &Apache::grades::get_scantron_config($env{'form.scantron_format'});
                   8208:     my ($scanlines,$scan_data)=&Apache::grades::scantron_getfile();
                   8209:     my $classlist=&Apache::loncoursedata::get_classlist();
                   8210:     my %idmap=&Apache::grades::username_to_idmap($classlist);
                   8211:     my $navmap=Apache::lonnavmaps::navmap->new();
1.582     raeburn  8212:     unless (ref($navmap)) {
                   8213:         $r->print(&navmap_errormsg());
                   8214:         return '';
                   8215:     }
1.523     raeburn  8216:     my $map=$navmap->getResourceByUrl($sequence);
1.557     raeburn  8217:     my @resources=$navmap->retrieveResources($map,\&scantron_filter,1,0);
                   8218:     my (%grader_partids_by_symb,%grader_randomlists_by_symb);
                   8219:     &graders_resources_pass(\@resources,\%grader_partids_by_symb,                             \%grader_randomlists_by_symb);
                   8220: 
1.554     raeburn  8221:     my ($uname,$udom);
1.523     raeburn  8222:     my (%scandata,%lastname,%bylast);
                   8223:     $r->print('
                   8224: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="checkscantron">'."\n");
                   8225: 
                   8226:     my @delayqueue;
                   8227:     my %completedstudents;
                   8228: 
                   8229:     my $count=&Apache::grades::get_todo_count($scanlines,$scan_data);
1.581     www      8230:     my %prog_state=&Apache::lonhtmlcommon::Create_PrgWin($r,'Bubblesheet/Submissions Comparison Status',
                   8231:                                     'Progress of Bubblesheet Data/Submission Records Comparison',$count,
1.523     raeburn  8232:                                     'inline',undef,'checkscantron');
1.546     raeburn  8233:     my ($username,$domain,$started);
1.582     raeburn  8234:     my $nav_error;
                   8235:     &scantron_get_maxbubble(\$nav_error); # Need the bubble lines array to parse.
                   8236:     if ($nav_error) {
                   8237:         $r->print(&navmap_errormsg());
                   8238:         return '';
                   8239:     }
1.523     raeburn  8240: 
                   8241:     &Apache::lonhtmlcommon::Update_PrgWin($r,\%prog_state,
                   8242:                                           'Processing first student');
                   8243:     my $start=&Time::HiRes::time();
                   8244:     my $i=-1;
                   8245: 
                   8246:     while ($i<$scanlines->{'count'}) {
                   8247:         ($username,$domain,$uname)=('','','');
                   8248:         $i++;
                   8249:         my $line=&Apache::grades::scantron_get_line($scanlines,$scan_data,$i);
                   8250:         if ($line=~/^[\s\cz]*$/) { next; }
                   8251:         if ($started) {
                   8252:             &Apache::lonhtmlcommon::Increment_PrgWin($r,\%prog_state,
                   8253:                                                      'last student');
                   8254:         }
                   8255:         $started=1;
                   8256:         my $scan_record=
                   8257:             &Apache::grades::scantron_parse_scanline($line,$i,\%scantron_config,
                   8258:                                                      $scan_data);
                   8259:         unless ($uname=&Apache::grades::scantron_find_student($scan_record,$scan_data,
                   8260:                                                               \%idmap,$i)) {
                   8261:             &Apache::grades::scantron_add_delay(\@delayqueue,$line,
                   8262:                                 'Unable to find a student that matches',1);
                   8263:             next;
                   8264:         }
                   8265:         if (exists $completedstudents{$uname}) {
                   8266:             &Apache::grades::scantron_add_delay(\@delayqueue,$line,
                   8267:                                 'Student '.$uname.' has multiple sheets',2);
                   8268:             next;
                   8269:         }
                   8270:         my $pid = $scan_record->{'scantron.ID'};
                   8271:         $lastname{$pid} = $scan_record->{'scantron.LastName'};
                   8272:         push(@{$bylast{$lastname{$pid}}},$pid);
                   8273:         my $lastpos = $env{'form.scantron_maxbubble'}*$scantron_config{'Qlength'};
                   8274:         $scandata{$pid} = substr($line,$scantron_config{'Qstart'}-1,$lastpos);
                   8275:         chomp($scandata{$pid});
                   8276:         $scandata{$pid} =~ s/\r$//;
                   8277:         ($username,$domain)=split(/:/,$uname);
                   8278:         my $counter = -1;
                   8279:         foreach my $resource (@resources) {
1.557     raeburn  8280:             my $parts;
1.554     raeburn  8281:             my $ressymb = $resource->symb();
1.557     raeburn  8282:             if ((exists($grader_randomlists_by_symb{$ressymb})) ||
                   8283:                 (ref($grader_partids_by_symb{$ressymb}) ne 'ARRAY')) {
                   8284:                 (my $analysis,$parts) =
                   8285:                     &scantron_partids_tograde($resource,$env{'request.course.id'},$username,$domain);
                   8286:             } else {
                   8287:                 $parts = $grader_partids_by_symb{$ressymb};
                   8288:             }
1.542     raeburn  8289:             ($counter,my $recording) =
                   8290:                 &verify_scantron_grading($resource,$domain,$username,$cid,$counter,
1.554     raeburn  8291:                                          $scandata{$pid},$parts,
1.542     raeburn  8292:                                          \%scantron_config,\%lettdig,$numletts);
                   8293:             $record{$pid} .= $recording;
1.523     raeburn  8294:         }
                   8295:     }
                   8296:     &Apache::lonhtmlcommon::Close_PrgWin($r,\%prog_state);
                   8297:     $r->print('<br />');
                   8298:     my ($okstudents,$badstudents,$numstudents,$passed,$failed);
                   8299:     $passed = 0;
                   8300:     $failed = 0;
                   8301:     $numstudents = 0;
                   8302:     foreach my $last (sort(keys(%bylast))) {
                   8303:         if (ref($bylast{$last}) eq 'ARRAY') {
                   8304:             foreach my $pid (sort(@{$bylast{$last}})) {
                   8305:                 my $showscandata = $scandata{$pid};
                   8306:                 my $showrecord = $record{$pid};
                   8307:                 $showscandata =~ s/\s/&nbsp;/g;
                   8308:                 $showrecord =~ s/\s/&nbsp;/g;
                   8309:                 if ($scandata{$pid} eq $record{$pid}) {
                   8310:                     my $css_class = ($passed % 2)?'LC_odd_row':'LC_even_row';
                   8311:                     $okstudents .= '<tr class="'.$css_class.'">'.
1.581     www      8312: '<td>'.&mt('Bubblesheet').'</td><td>'.$showscandata.'</td><td rowspan="2">'.$last.'</td><td rowspan="2">'.$pid.'</td>'."\n".
1.523     raeburn  8313: '</tr>'."\n".
                   8314: '<tr class="'.$css_class.'">'."\n".
                   8315: '<td>Submissions</td><td>'.$showrecord.'</td></tr>'."\n";
                   8316:                     $passed ++;
                   8317:                 } else {
                   8318:                     my $css_class = ($failed % 2)?'LC_odd_row':'LC_even_row';
1.581     www      8319:                     $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  8320: '</tr>'."\n".
                   8321: '<tr class="'.$css_class.'">'."\n".
                   8322: '<td>Submissions</td><td><span class="LC_nobreak">'.$record{$pid}.'</span></td>'."\n".
                   8323: '</tr>'."\n";
                   8324:                     $failed ++;
                   8325:                 }
                   8326:                 $numstudents ++;
                   8327:             }
                   8328:         }
                   8329:     }
1.572     www      8330:     $r->print('<p>'.&mt('Comparison of bubblesheet data (including corrections) with corresponding submission records (most recent submission) for <b>[quant,_1,student]</b>  ([_2] scantron lines/student).',$numstudents,$env{'form.scantron_maxbubble'}).'</p>');
1.523     raeburn  8331:     $r->print('<p>'.&mt('Exact matches for <b>[quant,_1,student]</b>.',$passed).'<br />'.&mt('Discrepancies detected for <b>[quant,_1,student]</b>.',$failed).'</p>');
                   8332:     if ($passed) {
1.572     www      8333:         $r->print(&mt('Students with exact correspondence between bubblesheet data and submissions are as follows:').'<br /><br />');
1.523     raeburn  8334:         $r->print(&Apache::loncommon::start_data_table()."\n".
                   8335:                  &Apache::loncommon::start_data_table_header_row()."\n".
                   8336:                  '<th>'.&mt('Source').'</th><th>'.&mt('Bubble records').'</th><th>'.&mt('Name').'</th><th>'.&mt('ID').'</th>'.
                   8337:                  &Apache::loncommon::end_data_table_header_row()."\n".
                   8338:                  $okstudents."\n".
                   8339:                  &Apache::loncommon::end_data_table().'<br />');
                   8340:     }
                   8341:     if ($failed) {
1.572     www      8342:         $r->print(&mt('Students with differences between bubblesheet data and submissions are as follows:').'<br /><br />');
1.523     raeburn  8343:         $r->print(&Apache::loncommon::start_data_table()."\n".
                   8344:                  &Apache::loncommon::start_data_table_header_row()."\n".
                   8345:                  '<th>'.&mt('Source').'</th><th>'.&mt('Bubble records').'</th><th>'.&mt('Name').'</th><th>'.&mt('ID').'</th>'.
                   8346:                  &Apache::loncommon::end_data_table_header_row()."\n".
                   8347:                  $badstudents."\n".
                   8348:                  &Apache::loncommon::end_data_table()).'<br />'.
1.572     www      8349:                  &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  8350:     }
                   8351:     $r->print('</form><br />'.$grading_menu_button);
                   8352:     return;
                   8353: }
                   8354: 
1.542     raeburn  8355: sub verify_scantron_grading {
1.554     raeburn  8356:     my ($resource,$domain,$username,$cid,$counter,$scandata,$partids,
1.542     raeburn  8357:         $scantron_config,$lettdig,$numletts) = @_;
                   8358:     my ($record,%expected,%startpos);
                   8359:     return ($counter,$record) if (!ref($resource));
                   8360:     return ($counter,$record) if (!$resource->is_problem());
                   8361:     my $symb = $resource->symb();
1.554     raeburn  8362:     return ($counter,$record) if (ref($partids) ne 'ARRAY');
                   8363:     foreach my $part_id (@{$partids}) {
1.542     raeburn  8364:         $counter ++;
                   8365:         $expected{$part_id} = 0;
                   8366:         if ($env{"form.scantron.sub_bubblelines.$counter"}) {
                   8367:             my @sub_lines = split(/,/,$env{"form.scantron.sub_bubblelines.$counter"});
                   8368:             foreach my $item (@sub_lines) {
                   8369:                 $expected{$part_id} += $item;
                   8370:             }
                   8371:         } else {
                   8372:             $expected{$part_id} = $env{"form.scantron.bubblelines.$counter"};
                   8373:         }
                   8374:         $startpos{$part_id} = $env{"form.scantron.first_bubble_line.$counter"};
                   8375:     }
                   8376:     if ($symb) {
                   8377:         my %recorded;
                   8378:         my (%returnhash) = &Apache::lonnet::restore($symb,$cid,$domain,$username);
                   8379:         if ($returnhash{'version'}) {
                   8380:             my %lasthash=();
                   8381:             my $version;
                   8382:             for ($version=1;$version<=$returnhash{'version'};$version++) {
                   8383:                 foreach my $key (sort(split(/\:/,$returnhash{$version.':keys'}))) {
                   8384:                     $lasthash{$key}=$returnhash{$version.':'.$key};
                   8385:                 }
                   8386:             }
                   8387:             foreach my $key (keys(%lasthash)) {
                   8388:                 if ($key =~ /\.scantron$/) {
                   8389:                     my $value = &unescape($lasthash{$key});
                   8390:                     my ($part_id) = ($key =~ /^resource\.(.+)\.scantron$/);
                   8391:                     if ($value eq '') {
                   8392:                         for (my $i=0; $i<$expected{$part_id}; $i++) {
                   8393:                             for (my $j=0; $j<$scantron_config->{'length'}; $j++) {
                   8394:                                 $recorded{$part_id} .= $scantron_config->{'Qoff'};
                   8395:                             }
                   8396:                         }
                   8397:                     } else {
                   8398:                         my @tocheck;
                   8399:                         my @items = split(//,$value);
                   8400:                         if (($scantron_config->{'Qon'} eq 'letter') ||
                   8401:                             ($scantron_config->{'Qon'} eq 'number')) {
                   8402:                             if (@items < $expected{$part_id}) {
                   8403:                                 my $fragment = substr($scandata,$startpos{$part_id},$expected{$part_id});
                   8404:                                 my @singles = split(//,$fragment);
                   8405:                                 foreach my $pos (@singles) {
                   8406:                                     if ($pos eq ' ') {
                   8407:                                         push(@tocheck,$pos);
                   8408:                                     } else {
                   8409:                                         my $next = shift(@items);
                   8410:                                         push(@tocheck,$next);
                   8411:                                     }
                   8412:                                 }
                   8413:                             } else {
                   8414:                                 @tocheck = @items;
                   8415:                             }
                   8416:                             foreach my $letter (@tocheck) {
                   8417:                                 if ($scantron_config->{'Qon'} eq 'letter') {
                   8418:                                     if ($letter !~ /^[A-J]$/) {
                   8419:                                         $letter = $scantron_config->{'Qoff'};
                   8420:                                     }
                   8421:                                     $recorded{$part_id} .= $letter;
                   8422:                                 } elsif ($scantron_config->{'Qon'} eq 'number') {
                   8423:                                     my $digit;
                   8424:                                     if ($letter !~ /^[A-J]$/) {
                   8425:                                         $digit = $scantron_config->{'Qoff'};
                   8426:                                     } else {
                   8427:                                         $digit = $lettdig->{$letter};
                   8428:                                     }
                   8429:                                     $recorded{$part_id} .= $digit;
                   8430:                                 }
                   8431:                             }
                   8432:                         } else {
                   8433:                             @tocheck = @items;
                   8434:                             for (my $i=0; $i<$expected{$part_id}; $i++) {
                   8435:                                 my $curr_sub = shift(@tocheck);
                   8436:                                 my $digit;
                   8437:                                 if ($curr_sub =~ /^[A-J]$/) {
                   8438:                                     $digit = $lettdig->{$curr_sub}-1;
                   8439:                                 }
                   8440:                                 if ($curr_sub eq 'J') {
                   8441:                                     $digit += scalar($numletts);
                   8442:                                 }
                   8443:                                 for (my $j=0; $j<$scantron_config->{'Qlength'}; $j++) {
                   8444:                                     if ($j == $digit) {
                   8445:                                         $recorded{$part_id} .= $scantron_config->{'Qon'};
                   8446:                                     } else {
                   8447:                                         $recorded{$part_id} .= $scantron_config->{'Qoff'};
                   8448:                                     }
                   8449:                                 }
                   8450:                             }
                   8451:                         }
                   8452:                     }
                   8453:                 }
                   8454:             }
                   8455:         }
1.554     raeburn  8456:         foreach my $part_id (@{$partids}) {
1.542     raeburn  8457:             if ($recorded{$part_id} eq '') {
                   8458:                 for (my $i=0; $i<$expected{$part_id}; $i++) {
                   8459:                     for (my $j=0; $j<$scantron_config->{'Qlength'}; $j++) {
                   8460:                         $recorded{$part_id} .= $scantron_config->{'Qoff'};
                   8461:                     }
                   8462:                 }
                   8463:             }
                   8464:             $record .= $recorded{$part_id};
                   8465:         }
                   8466:     }
                   8467:     return ($counter,$record);
                   8468: }
                   8469: 
                   8470: sub letter_to_digits { 
                   8471:     my %lettdig = (
                   8472:                     A => 1,
                   8473:                     B => 2,
                   8474:                     C => 3,
                   8475:                     D => 4,
                   8476:                     E => 5,
                   8477:                     F => 6,
                   8478:                     G => 7,
                   8479:                     H => 8,
                   8480:                     I => 9,
                   8481:                     J => 0,
                   8482:                   );
                   8483:     return %lettdig;
                   8484: }
                   8485: 
1.423     albertel 8486: 
1.75      albertel 8487: #-------- end of section for handling grading scantron forms -------
                   8488: #
                   8489: #-------------------------------------------------------------------
                   8490: 
1.72      ng       8491: #-------------------------- Menu interface -------------------------
                   8492: #
                   8493: #--- Show a Grading Menu button - Calls the next routine ---
                   8494: sub show_grading_menu_form {
1.324     albertel 8495:     my ($symb)=@_;
1.125     ng       8496:     my $result.='<br /><form action="/adm/grades" method="post">'."\n".
1.418     albertel 8497: 	'<input type="hidden" name="symb" value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
1.257     albertel 8498: 	'<input type="hidden" name="saveState"  value="'.$env{'form.saveState'}.'" />'."\n".
1.72      ng       8499: 	'<input type="hidden" name="command" value="gradingmenu" />'."\n".
1.478     albertel 8500: 	'<input type="submit" name="submit" value="'.&mt('Grading Menu').'" />'."\n".
1.72      ng       8501: 	'</form>'."\n";
                   8502:     return $result;
                   8503: }
                   8504: 
1.77      ng       8505: # -- Retrieve choices for grading form
                   8506: sub savedState {
                   8507:     my %savedState = ();
1.257     albertel 8508:     if ($env{'form.saveState'}) {
                   8509: 	foreach (split(/:/,$env{'form.saveState'})) {
1.77      ng       8510: 	    my ($key,$value) = split(/=/,$_,2);
                   8511: 	    $savedState{$key} = $value;
                   8512: 	}
                   8513:     }
                   8514:     return \%savedState;
                   8515: }
1.76      ng       8516: 
1.443     banghart 8517: sub grading_menu {
                   8518:     my ($request) = @_;
                   8519:     my ($symb)=&get_symb($request);
                   8520:     if (!$symb) {return '';}
                   8521:     my $probTitle = &Apache::lonnet::gettitle($symb);
                   8522:     my ($table,undef,$hdgrade) = &showResourceInfo($symb,$probTitle);
                   8523: 
1.444     banghart 8524:     $request->print($table);
1.443     banghart 8525:     my %fields = ('symb'=>&Apache::lonenc::check_encrypt($symb),
                   8526:                   'handgrade'=>$hdgrade,
                   8527:                   'probTitle'=>$probTitle,
                   8528:                   'command'=>'submit_options',
                   8529:                   'saveState'=>"",
                   8530:                   'gradingMenu'=>1,
                   8531:                   'showgrading'=>"yes");
1.538     schulted 8532:     
                   8533:     my $url1 = &Apache::lonhtmlcommon::build_url('grades/',\%fields);
                   8534:     
1.443     banghart 8535:     $fields{'command'} = 'csvform';
1.538     schulted 8536:     my $url2 = &Apache::lonhtmlcommon::build_url('grades/',\%fields);
                   8537:     
1.443     banghart 8538:     $fields{'command'} = 'processclicker';
1.538     schulted 8539:     my $url3 = &Apache::lonhtmlcommon::build_url('grades/',\%fields);
                   8540:     
1.443     banghart 8541:     $fields{'command'} = 'scantron_selectphase';
1.538     schulted 8542:     my $url4 = &Apache::lonhtmlcommon::build_url('grades/',\%fields);
                   8543:     
                   8544:     my @menu = ({	categorytitle=>'Course Grading',
                   8545:             items =>[
                   8546:                         {	linktext => 'Manual Grading/View Submissions',
                   8547:                     		url => $url1,
                   8548:                     		permission => 'F',
                   8549:                     		icon => 'edit-find-replace.png',
                   8550:                     		linktitle => 'Start the process of hand grading submissions.'
                   8551:                         },
                   8552:                 	    {	linktext => 'Upload Scores',
                   8553:                     		url => $url2,
                   8554:                     		permission => 'F',
                   8555:                     		icon => 'uploadscores.png',
                   8556:                     		linktitle => 'Specify a file containing the class scores for current resource.'
                   8557:                 	    },
                   8558:                 	    {	linktext => 'Process Clicker',
                   8559:                     		url => $url3,
                   8560:                     		permission => 'F',
                   8561:                     		icon => 'addClickerInfoFile.png',
                   8562:                     		linktitle => 'Specify a file containing the clicker information for this resource.'
                   8563:                 	    },
1.587     raeburn  8564:                 	    {	linktext => 'Grade/Manage/Review Bubblesheets',
1.538     schulted 8565:                     		url => $url4,
                   8566:                     		permission => 'F',
                   8567:                     		icon => 'stat.png',
                   8568:                     		linktitle => 'Grade scantron exams, upload/download scantron data files, and review previously graded scantron exams.'
                   8569:                 	    }
                   8570:                     ]
                   8571:             });
                   8572: 
                   8573:     #$fields{'command'} = 'verify';
                   8574:     #$url = &Apache::lonhtmlcommon::build_url('grades/',\%fields);
1.443     banghart 8575:     #
                   8576:     # Create the menu
                   8577:     my $Str;
1.444     banghart 8578:     # $Str .= '<h2>'.&mt('Please select a grading task').'</h2>';
1.445     banghart 8579:     $Str .= '<form method="post" action="" name="gradingMenu">';
                   8580:     $Str .= '<input type="hidden" name="command" value="" />'.
                   8581:     	'<input type="hidden" name="symb"        value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
                   8582: 	'<input type="hidden" name="handgrade"   value="'.$hdgrade.'" />'."\n".
1.476     albertel 8583: 	'<input type="hidden" name="probTitle"   value="'.$probTitle.'" />'."\n".
1.445     banghart 8584: 	'<input type="hidden" name="saveState"   value="" />'."\n".
                   8585: 	'<input type="hidden" name="gradingMenu" value="1" />'."\n".
                   8586: 	'<input type="hidden" name="showgrading" value="yes" />'."\n";
                   8587: 
1.538     schulted 8588:     $Str .= Apache::lonhtmlcommon::generate_menu(@menu);
                   8589:     #$menudata->{'jscript'}
1.584     bisitz   8590:     $Str .='<hr /><input type="button" value="'.&mt('Verify Receipt No.').'" '.
1.589     bisitz   8591:         ' onclick="javascript:checkChoice(document.forms.gradingMenu,\'5\',\'verify\')" '.
1.538     schulted 8592:         ' /> '.
                   8593:         &Apache::lonnet::recprefix($env{'request.course.id'}).
1.589     bisitz   8594:         '-<input type="text" name="receipt" size="4" onchange="javascript:checkReceiptNo(this.form,\'OK\')" />';
1.538     schulted 8595: 
1.444     banghart 8596:     $Str .="</form>\n";
1.539     riegler  8597:     my $receiptalert = &mt("Please enter a receipt number given by a student in the receipt box.");
1.597   ! wenzelju 8598:     $request->print(&Apache::lonhtmlcommon::scripttag(<<GRADINGMENUJS));
1.443     banghart 8599:     function checkChoice(formname,val,cmdx) {
                   8600: 	if (val <= 2) {
                   8601: 	    var cmd = radioSelection(formname.radioChoice);
                   8602: 	    var cmdsave = cmd;
                   8603: 	} else {
                   8604: 	    cmd = cmdx;
                   8605: 	    cmdsave = 'submission';
                   8606: 	}
                   8607: 	formname.command.value = cmd;
                   8608: 	if (val < 5) formname.submit();
                   8609: 	if (val == 5) {
1.458     banghart 8610: 	    if (!checkReceiptNo(formname,'notOK')) { 
                   8611: 	        return false;
                   8612: 	    } else {
                   8613: 	        formname.submit();
                   8614: 	    }
1.445     banghart 8615: 	}
                   8616:     }
1.443     banghart 8617: 
                   8618:     function checkReceiptNo(formname,nospace) {
                   8619: 	var receiptNo = formname.receipt.value;
                   8620: 	var checkOpt = false;
                   8621: 	if (nospace == "OK" && isNaN(receiptNo)) {checkOpt = true;}
                   8622: 	if (nospace == "notOK" && (isNaN(receiptNo) || receiptNo == "")) {checkOpt = true;}
                   8623: 	if (checkOpt) {
1.539     riegler  8624: 	    alert("$receiptalert");
1.443     banghart 8625: 	    formname.receipt.value = "";
                   8626: 	    formname.receipt.focus();
                   8627: 	    return false;
                   8628: 	}
                   8629: 	return true;
                   8630:     }
                   8631: GRADINGMENUJS
                   8632:     &commonJSfunctions($request);
                   8633:     return $Str;    
                   8634: }
                   8635: 
                   8636: 
                   8637: #--- Displays the submissions first page -------
                   8638: sub submit_options {
1.72      ng       8639:     my ($request) = @_;
1.324     albertel 8640:     my ($symb)=&get_symb($request);
1.72      ng       8641:     if (!$symb) {return '';}
1.76      ng       8642:     my $probTitle = &Apache::lonnet::gettitle($symb);
1.72      ng       8643: 
1.539     riegler  8644:     my $receiptalert = &mt("Please enter a receipt number given by a student in the receipt box."); 
1.597   ! wenzelju 8645:     $request->print(&Apache::lonhtmlcommon::scripttag(<<GRADINGMENUJS));
1.116     ng       8646:     function checkChoice(formname,val,cmdx) {
                   8647: 	if (val <= 2) {
                   8648: 	    var cmd = radioSelection(formname.radioChoice);
1.118     ng       8649: 	    var cmdsave = cmd;
1.116     ng       8650: 	} else {
                   8651: 	    cmd = cmdx;
1.118     ng       8652: 	    cmdsave = 'submission';
1.116     ng       8653: 	}
                   8654: 	formname.command.value = cmd;
1.118     ng       8655: 	formname.saveState.value = "saveCmd="+cmdsave+":saveSec="+pullDownSelection(formname.section)+
1.145     albertel 8656: 	    ":saveSub="+pullDownSelection(formname.submitonly)+":saveStatus="+pullDownSelection(formname.Status);
1.116     ng       8657: 	if (val < 5) formname.submit();
                   8658: 	if (val == 5) {
1.72      ng       8659: 	    if (!checkReceiptNo(formname,'notOK')) { return false;}
                   8660: 	    formname.submit();
                   8661: 	}
1.238     albertel 8662: 	if (val < 7) formname.submit();
1.72      ng       8663:     }
                   8664: 
                   8665:     function checkReceiptNo(formname,nospace) {
                   8666: 	var receiptNo = formname.receipt.value;
                   8667: 	var checkOpt = false;
                   8668: 	if (nospace == "OK" && isNaN(receiptNo)) {checkOpt = true;}
                   8669: 	if (nospace == "notOK" && (isNaN(receiptNo) || receiptNo == "")) {checkOpt = true;}
                   8670: 	if (checkOpt) {
1.539     riegler  8671: 	    alert("$receiptalert");
1.72      ng       8672: 	    formname.receipt.value = "";
                   8673: 	    formname.receipt.focus();
                   8674: 	    return false;
                   8675: 	}
                   8676: 	return true;
                   8677:     }
                   8678: GRADINGMENUJS
1.118     ng       8679:     &commonJSfunctions($request);
1.324     albertel 8680:     my ($table,undef,$hdgrade) = &showResourceInfo($symb,$probTitle);
1.473     albertel 8681:     my $result;
1.76      ng       8682:     my (undef,$sections) = &getclasslist('all','0');
1.77      ng       8683:     my $savedState = &savedState();
1.118     ng       8684:     my $saveCmd = ($$savedState{'saveCmd'} eq '' ? 'submission' : $$savedState{'saveCmd'});
1.77      ng       8685:     my $saveSec = ($$savedState{'saveSec'} eq '' ? 'all' : $$savedState{'saveSec'});
1.118     ng       8686:     my $saveSub = ($$savedState{'saveSub'} eq '' ? 'all' : $$savedState{'saveSub'});
1.77      ng       8687:     my $saveStatus = ($$savedState{'saveStatus'} eq '' ? 'Active' : $$savedState{'saveStatus'});
1.72      ng       8688: 
1.533     bisitz   8689:     # Preselect sections
                   8690:     my $selsec="";
                   8691:     if (ref($sections)) {
                   8692:         foreach my $section (sort(@$sections)) {
                   8693:             $selsec.='<option value="'.$section.'" '.
                   8694:                 ($saveSec eq $section ? 'selected="selected"':'').'>'.$section.'</option>'."\n";
                   8695:         }
                   8696:     }
                   8697: 
1.72      ng       8698:     $result.='<form action="/adm/grades" method="post" name="gradingMenu">'."\n".
1.418     albertel 8699: 	'<input type="hidden" name="symb"        value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
1.72      ng       8700: 	'<input type="hidden" name="handgrade"   value="'.$hdgrade.'" />'."\n".
                   8701: 	'<input type="hidden" name="probTitle"   value="'.$probTitle.'" />'."\n".
1.116     ng       8702: 	'<input type="hidden" name="command"     value="" />'."\n".
1.77      ng       8703: 	'<input type="hidden" name="saveState"   value="" />'."\n".
1.124     ng       8704: 	'<input type="hidden" name="gradingMenu" value="1" />'."\n".
1.72      ng       8705: 	'<input type="hidden" name="showgrading" value="yes" />'."\n";
                   8706: 
1.472     albertel 8707:     $result.='
1.533     bisitz   8708: <h2>
                   8709:   '.&mt('Grade Current Resource').'
                   8710: </h2>
                   8711: <div>
                   8712:   '.$table.'
                   8713: </div>
                   8714: 
1.537     harmsja  8715: <div class="LC_columnSection">
                   8716:   
1.533     bisitz   8717:     <fieldset>
                   8718:       <legend>
                   8719:        '.&mt('Sections').'
                   8720:       </legend>
                   8721:       <select name="section" multiple="multiple" size="5">'."\n";
                   8722:     $result.= $selsec;
1.401     albertel 8723:     $result.= '<option value="all" '.($saveSec eq 'all' ? 'selected="selected"' : ''). '>all</option></select> &nbsp; ';
1.472     albertel 8724:     $result.='
1.533     bisitz   8725:     </fieldset>
1.537     harmsja  8726:   
1.533     bisitz   8727:     <fieldset>
                   8728:       <legend>
                   8729:         '.&mt('Groups').'
                   8730:       </legend>
                   8731:       '.&Apache::lonstatistics::GroupSelect('group','multiple',5).'
                   8732:     </fieldset>
1.537     harmsja  8733:   
1.533     bisitz   8734:     <fieldset>
                   8735:       <legend>
                   8736:         '.&mt('Access Status').'
                   8737:       </legend>
                   8738:       '.&Apache::lonhtmlcommon::StatusOptions($saveStatus,undef,5,undef,'mult').'
                   8739:     </fieldset>
1.537     harmsja  8740:   
1.533     bisitz   8741:     <fieldset>
                   8742:       <legend>
                   8743:         '.&mt('Submission Status').'
                   8744:       </legend>
                   8745:       <select name="submitonly" size="5">
1.473     albertel 8746: 	         <option value="yes" '.      ($saveSub eq 'yes'       ? 'selected="selected"' : '').'>'.&mt('with submissions').'</option>
                   8747: 	         <option value="queued" '.   ($saveSub eq 'queued'    ? 'selected="selected"' : '').'>'.&mt('in grading queue').'</option>
                   8748: 	         <option value="graded" '.   ($saveSub eq 'graded'    ? 'selected="selected"' : '').'>'.&mt('with ungraded submissions').'</option>
                   8749: 	         <option value="incorrect" '.($saveSub eq 'incorrect' ? 'selected="selected"' : '').'>'.&mt('with incorrect submissions').'</option>
                   8750:                  <option value="all" '.      ($saveSub eq 'all'       ? 'selected="selected"' : '').'>'.&mt('with any status').'</option>
1.533     bisitz   8751:       </select>
                   8752:     </fieldset>
1.537     harmsja  8753:   
1.533     bisitz   8754: </div>
                   8755: 
                   8756: <br />
                   8757:           <div>
                   8758:             <div>
1.473     albertel 8759:               <label>
                   8760:                 <input type="radio" name="radioChoice" value="submission" '.
                   8761:                   ($saveCmd eq 'submission' ? 'checked="checked"' : '').' /> '.
                   8762:              &mt('Select individual students to grade and view submissions.').'
                   8763: 	      </label> 
                   8764:             </div>
1.533     bisitz   8765:             <div>
1.473     albertel 8766: 	      <label>
                   8767:                 <input type="radio" name="radioChoice" value="viewgrades" '.
                   8768:                   ($saveCmd eq 'viewgrades' ? 'checked="checked"' : '').' /> '.
                   8769:                     &mt('Grade all selected students in a grading table.').'
                   8770:               </label>
                   8771:             </div>
1.533     bisitz   8772:             <div>
1.589     bisitz   8773: 	      <input type="button" onclick="javascript:checkChoice(this.form,\'2\');" value="'.&mt('Next').' &rarr;" />
1.473     albertel 8774:             </div>
1.472     albertel 8775:           </div>
1.533     bisitz   8776: 
                   8777: 
1.473     albertel 8778:         <h2>
                   8779:          '.&mt('Grade Complete Folder for One Student').'
                   8780:         </h2>
1.533     bisitz   8781:         <div>
                   8782:             <div>
1.473     albertel 8783:               <label>
                   8784:                 <input type="radio" name="radioChoice" value="pickStudentPage" '.
                   8785: 	  ($saveCmd eq 'pickStudentPage' ? 'checked="checked"' : '').' /> '.
                   8786:   &mt('The <b>complete</b> page/sequence/folder: For one student').'
                   8787:               </label>
                   8788:             </div>
1.533     bisitz   8789:             <div>
1.589     bisitz   8790: 	      <input type="button" onclick="javascript:checkChoice(this.form,\'2\');" value="'.&mt('Next').' &rarr;" />
1.473     albertel 8791:             </div>
1.472     albertel 8792:         </div>
                   8793:   </form>';
1.499     albertel 8794:     $result .= &show_grading_menu_form($symb);
1.44      ng       8795:     return $result;
1.2       albertel 8796: }
                   8797: 
1.285     albertel 8798: sub reset_perm {
                   8799:     undef(%perm);
                   8800: }
                   8801: 
                   8802: sub init_perm {
                   8803:     &reset_perm();
1.300     albertel 8804:     foreach my $test_perm ('vgr','mgr','opa') {
                   8805: 
                   8806: 	my $scope = $env{'request.course.id'};
                   8807: 	if (!($perm{$test_perm}=&Apache::lonnet::allowed($test_perm,$scope))) {
                   8808: 
                   8809: 	    $scope .= '/'.$env{'request.course.sec'};
                   8810: 	    if ( $perm{$test_perm}=
                   8811: 		 &Apache::lonnet::allowed($test_perm,$scope)) {
                   8812: 		$perm{$test_perm.'_section'}=$env{'request.course.sec'};
                   8813: 	    } else {
                   8814: 		delete($perm{$test_perm});
                   8815: 	    }
1.285     albertel 8816: 	}
                   8817:     }
                   8818: }
                   8819: 
1.400     www      8820: sub gather_clicker_ids {
1.408     albertel 8821:     my %clicker_ids;
1.400     www      8822: 
                   8823:     my $classlist = &Apache::loncoursedata::get_classlist();
                   8824: 
                   8825:     # Set up a couple variables.
1.407     albertel 8826:     my $username_idx = &Apache::loncoursedata::CL_SNAME();
                   8827:     my $domain_idx   = &Apache::loncoursedata::CL_SDOM();
1.438     www      8828:     my $status_idx   = &Apache::loncoursedata::CL_STATUS();
1.400     www      8829: 
1.407     albertel 8830:     foreach my $student (keys(%$classlist)) {
1.438     www      8831:         if ($classlist->{$student}->[$status_idx] ne 'Active') { next; }
1.407     albertel 8832:         my $username = $classlist->{$student}->[$username_idx];
                   8833:         my $domain   = $classlist->{$student}->[$domain_idx];
1.400     www      8834:         my $clickers =
1.408     albertel 8835: 	    (&Apache::lonnet::userenvironment($domain,$username,'clickers'))[1];
1.400     www      8836:         foreach my $id (split(/\,/,$clickers)) {
1.414     www      8837:             $id=~s/^[\#0]+//;
1.421     www      8838:             $id=~s/[\-\:]//g;
1.407     albertel 8839:             if (exists($clicker_ids{$id})) {
1.408     albertel 8840: 		$clicker_ids{$id}.=','.$username.':'.$domain;
1.400     www      8841:             } else {
1.408     albertel 8842: 		$clicker_ids{$id}=$username.':'.$domain;
1.400     www      8843:             }
                   8844:         }
                   8845:     }
1.407     albertel 8846:     return %clicker_ids;
1.400     www      8847: }
                   8848: 
1.402     www      8849: sub gather_adv_clicker_ids {
1.408     albertel 8850:     my %clicker_ids;
1.402     www      8851:     my $cnum=$env{'course.'.$env{'request.course.id'}.'.num'};
                   8852:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
                   8853:     my %coursepersonnel=&Apache::lonnet::get_course_adv_roles($cdom.'/'.$cnum);
1.409     albertel 8854:     foreach my $element (sort(keys(%coursepersonnel))) {
1.402     www      8855:         foreach my $person (split(/\,/,$coursepersonnel{$element})) {
                   8856:             my ($puname,$pudom)=split(/\:/,$person);
                   8857:             my $clickers =
1.408     albertel 8858: 		(&Apache::lonnet::userenvironment($pudom,$puname,'clickers'))[1];
1.405     www      8859:             foreach my $id (split(/\,/,$clickers)) {
1.414     www      8860: 		$id=~s/^[\#0]+//;
1.421     www      8861:                 $id=~s/[\-\:]//g;
1.408     albertel 8862: 		if (exists($clicker_ids{$id})) {
                   8863: 		    $clicker_ids{$id}.=','.$puname.':'.$pudom;
                   8864: 		} else {
                   8865: 		    $clicker_ids{$id}=$puname.':'.$pudom;
                   8866: 		}
1.405     www      8867:             }
1.402     www      8868:         }
                   8869:     }
1.407     albertel 8870:     return %clicker_ids;
1.402     www      8871: }
                   8872: 
1.413     www      8873: sub clicker_grading_parameters {
                   8874:     return ('gradingmechanism' => 'scalar',
                   8875:             'upfiletype' => 'scalar',
                   8876:             'specificid' => 'scalar',
                   8877:             'pcorrect' => 'scalar',
                   8878:             'pincorrect' => 'scalar');
                   8879: }
                   8880: 
1.400     www      8881: sub process_clicker {
                   8882:     my ($r)=@_;
                   8883:     my ($symb)=&get_symb($r);
                   8884:     if (!$symb) {return '';}
                   8885:     my $result=&checkforfile_js();
                   8886:     $env{'form.probTitle'} = &Apache::lonnet::gettitle($symb);
                   8887:     my ($table) = &showResourceInfo($symb,$env{'form.probTitle'});
                   8888:     $result.=$table;
                   8889:     $result.='<br /><table width="100%" border="0"><tr><td bgcolor="#777777">'."\n";
                   8890:     $result.='<table width="100%" border="0"><tr bgcolor="#e6ffff"><td>'."\n";
1.538     schulted 8891:     $result.='&nbsp;<b>'.&mt('Specify a file containing the clicker information for this resource.').
                   8892:         '</b></td></tr>'."\n";
1.400     www      8893:     $result.='<tr bgcolor=#ffffe6><td>'."\n";
1.413     www      8894: # Attempt to restore parameters from last session, set defaults if not present
                   8895:     my %Saveable_Parameters=&clicker_grading_parameters();
                   8896:     &Apache::loncommon::restore_course_settings('grades_clicker',
                   8897:                                                  \%Saveable_Parameters);
                   8898:     if (!$env{'form.pcorrect'}) { $env{'form.pcorrect'}=100; }
                   8899:     if (!$env{'form.pincorrect'}) { $env{'form.pincorrect'}=100; }
                   8900:     if (!$env{'form.gradingmechanism'}) { $env{'form.gradingmechanism'}='attendance'; }
                   8901:     if (!$env{'form.upfiletype'}) { $env{'form.upfiletype'}='iclicker'; }
                   8902: 
                   8903:     my %checked;
1.521     www      8904:     foreach my $gradingmechanism ('attendance','personnel','specific','given') {
1.413     www      8905:        if ($env{'form.gradingmechanism'} eq $gradingmechanism) {
1.569     bisitz   8906:           $checked{$gradingmechanism}=' checked="checked"';
1.413     www      8907:        }
                   8908:     }
                   8909: 
1.400     www      8910:     my $upload=&mt("Upload File");
                   8911:     my $type=&mt("Type");
1.402     www      8912:     my $attendance=&mt("Award points just for participation");
                   8913:     my $personnel=&mt("Correctness determined from response by course personnel");
1.414     www      8914:     my $specific=&mt("Correctness determined from response with clicker ID(s)"); 
1.521     www      8915:     my $given=&mt("Correctness determined from given list of answers").' '.
                   8916:               '<font size="-2"><tt>('.&mt("Provide comma-separated list. Use '*' for any answer correct, '-' for skip").')</tt></font>';
1.402     www      8917:     my $pcorrect=&mt("Percentage points for correct solution");
                   8918:     my $pincorrect=&mt("Percentage points for incorrect solution");
1.413     www      8919:     my $selectform=&Apache::loncommon::select_form($env{'form.upfiletype'},'upfiletype',
1.419     www      8920: 						   ('iclicker' => 'i>clicker',
                   8921:                                                     'interwrite' => 'interwrite PRS'));
1.418     albertel 8922:     $symb = &Apache::lonenc::check_encrypt($symb);
1.597   ! wenzelju 8923:     $result.= &Apache::lonhtmlcommon::scripttag(<<ENDUPFORM);
1.402     www      8924: function sanitycheck() {
                   8925: // Accept only integer percentages
                   8926:    document.forms.gradesupload.pcorrect.value=Math.round(document.forms.gradesupload.pcorrect.value);
                   8927:    document.forms.gradesupload.pincorrect.value=Math.round(document.forms.gradesupload.pincorrect.value);
                   8928: // Find out grading choice
                   8929:    for (i=0; i<document.forms.gradesupload.gradingmechanism.length; i++) {
                   8930:       if (document.forms.gradesupload.gradingmechanism[i].checked) {
                   8931:          gradingchoice=document.forms.gradesupload.gradingmechanism[i].value;
                   8932:       }
                   8933:    }
                   8934: // By default, new choice equals user selection
                   8935:    newgradingchoice=gradingchoice;
                   8936: // Not good to give more points for false answers than correct ones
                   8937:    if (Math.round(document.forms.gradesupload.pcorrect.value)<Math.round(document.forms.gradesupload.pincorrect.value)) {
                   8938:       document.forms.gradesupload.pcorrect.value=document.forms.gradesupload.pincorrect.value;
                   8939:    }
                   8940: // If new choice is attendance only, and old choice was correctness-based, restore defaults
                   8941:    if ((gradingchoice=='attendance') && (document.forms.gradesupload.waschecked.value!='attendance')) {
                   8942:       document.forms.gradesupload.pcorrect.value=100;
                   8943:       document.forms.gradesupload.pincorrect.value=100;
                   8944:    }
                   8945: // If the values are different, cannot be attendance only
                   8946:    if ((Math.round(document.forms.gradesupload.pcorrect.value)!=Math.round(document.forms.gradesupload.pincorrect.value)) &&
                   8947:        (gradingchoice=='attendance')) {
                   8948:        newgradingchoice='personnel';
                   8949:    }
                   8950: // Change grading choice to new one
                   8951:    for (i=0; i<document.forms.gradesupload.gradingmechanism.length; i++) {
                   8952:       if (document.forms.gradesupload.gradingmechanism[i].value==newgradingchoice) {
                   8953:          document.forms.gradesupload.gradingmechanism[i].checked=true;
                   8954:       } else {
                   8955:          document.forms.gradesupload.gradingmechanism[i].checked=false;
                   8956:       }
                   8957:    }
                   8958: // Remember the old state
                   8959:    document.forms.gradesupload.waschecked.value=newgradingchoice;
                   8960: }
1.597   ! wenzelju 8961: ENDUPFORM
        !          8962:     $result.= <<ENDUPFORM;
1.400     www      8963: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="gradesupload">
                   8964: <input type="hidden" name="symb" value="$symb" />
                   8965: <input type="hidden" name="command" value="processclickerfile" />
                   8966: <input type="hidden" name="probTitle" value="$env{'form.probTitle'}" />
                   8967: <input type="hidden" name="saveState"  value="$env{'form.saveState'}" />
                   8968: <input type="file" name="upfile" size="50" />
                   8969: <br /><label>$type: $selectform</label>
1.589     bisitz   8970: <br /><label><input type="radio" name="gradingmechanism" value="attendance"$checked{'attendance'} onclick="sanitycheck()" />$attendance </label>
                   8971: <br /><label><input type="radio" name="gradingmechanism" value="personnel"$checked{'personnel'} onclick="sanitycheck()" />$personnel</label>
                   8972: <br /><label><input type="radio" name="gradingmechanism" value="specific"$checked{'specific'} onclick="sanitycheck()" />$specific </label>
1.414     www      8973: <input type="text" name="specificid" value="$env{'form.specificid'}" size="20" />
1.589     bisitz   8974: <br /><label><input type="radio" name="gradingmechanism" value="given"$checked{'given'} onclick="sanitycheck()" />$given </label>
1.521     www      8975: <br />&nbsp;&nbsp;&nbsp;
                   8976: <input type="text" name="givenanswer" size="50" />
1.413     www      8977: <input type="hidden" name="waschecked" value="$env{'form.gradingmechanism'}" />
1.589     bisitz   8978: <br /><label>$pcorrect: <input type="text" name="pcorrect" size="4" value="$env{'form.pcorrect'}" onchange="sanitycheck()" /></label>
                   8979: <br /><label>$pincorrect: <input type="text" name="pincorrect" size="4" value="$env{'form.pincorrect'}" onchange="sanitycheck()" /></label>
                   8980: <br /><input type="button" onclick="javascript:checkUpload(this.form);" value="$upload" />
1.597   ! wenzelju 8981: </form>'
1.400     www      8982: ENDUPFORM
                   8983:     $result.='</td></tr></table>'."\n".
                   8984:              '</td></tr></table><br /><br />'."\n";
                   8985:     $result.=&show_grading_menu_form($symb);
                   8986:     return $result;
                   8987: }
                   8988: 
                   8989: sub process_clicker_file {
                   8990:     my ($r)=@_;
                   8991:     my ($symb)=&get_symb($r);
                   8992:     if (!$symb) {return '';}
1.413     www      8993: 
                   8994:     my %Saveable_Parameters=&clicker_grading_parameters();
                   8995:     &Apache::loncommon::store_course_settings('grades_clicker',
                   8996:                                               \%Saveable_Parameters);
                   8997: 
1.400     www      8998:     my ($result) = &showResourceInfo($symb,$env{'form.probTitle'});
1.404     www      8999:     if (($env{'form.gradingmechanism'} eq 'specific') && ($env{'form.specificid'}!~/\w/)) {
1.408     albertel 9000: 	$result.='<span class="LC_error">'.&mt('You need to specify a clicker ID for the correct answer').'</span>';
                   9001: 	return $result.&show_grading_menu_form($symb);
1.404     www      9002:     }
1.522     www      9003:     if (($env{'form.gradingmechanism'} eq 'given') && ($env{'form.givenanswer'}!~/\S/)) {
1.521     www      9004:         $result.='<span class="LC_error">'.&mt('You need to specify the correct answer').'</span>';
                   9005:         return $result.&show_grading_menu_form($symb);
                   9006:     }
1.522     www      9007:     my $foundgiven=0;
1.521     www      9008:     if ($env{'form.gradingmechanism'} eq 'given') {
                   9009:         $env{'form.givenanswer'}=~s/^\s*//gs;
                   9010:         $env{'form.givenanswer'}=~s/\s*$//gs;
                   9011:         $env{'form.givenanswer'}=~s/[^a-zA-Z0-9\.\*\-]+/\,/g;
                   9012:         $env{'form.givenanswer'}=uc($env{'form.givenanswer'});
1.522     www      9013:         my @answers=split(/\,/,$env{'form.givenanswer'});
                   9014:         $foundgiven=$#answers+1;
1.521     www      9015:     }
1.407     albertel 9016:     my %clicker_ids=&gather_clicker_ids();
1.408     albertel 9017:     my %correct_ids;
1.404     www      9018:     if ($env{'form.gradingmechanism'} eq 'personnel') {
1.408     albertel 9019: 	%correct_ids=&gather_adv_clicker_ids();
1.404     www      9020:     }
                   9021:     if ($env{'form.gradingmechanism'} eq 'specific') {
1.414     www      9022: 	foreach my $correct_id (split(/[\s\,]/,$env{'form.specificid'})) {;
                   9023: 	   $correct_id=~tr/a-z/A-Z/;
                   9024: 	   $correct_id=~s/\s//gs;
                   9025: 	   $correct_id=~s/^[\#0]+//;
1.421     www      9026:            $correct_id=~s/[\-\:]//g;
1.414     www      9027:            if ($correct_id) {
                   9028: 	      $correct_ids{$correct_id}='specified';
                   9029:            }
                   9030:         }
1.400     www      9031:     }
1.404     www      9032:     if ($env{'form.gradingmechanism'} eq 'attendance') {
1.408     albertel 9033: 	$result.=&mt('Score based on attendance only');
1.521     www      9034:     } elsif ($env{'form.gradingmechanism'} eq 'given') {
1.522     www      9035:         $result.=&mt('Score based on [_1] ([_2] answers)','<tt>'.$env{'form.givenanswer'}.'</tt>',$foundgiven);
1.404     www      9036:     } else {
1.408     albertel 9037: 	my $number=0;
1.411     www      9038: 	$result.='<p><b>'.&mt('Correctness determined by the following IDs').'</b>';
1.408     albertel 9039: 	foreach my $id (sort(keys(%correct_ids))) {
1.411     www      9040: 	    $result.='<br /><tt>'.$id.'</tt> - ';
1.408     albertel 9041: 	    if ($correct_ids{$id} eq 'specified') {
                   9042: 		$result.=&mt('specified');
                   9043: 	    } else {
                   9044: 		my ($uname,$udom)=split(/\:/,$correct_ids{$id});
                   9045: 		$result.=&Apache::loncommon::plainname($uname,$udom);
                   9046: 	    }
                   9047: 	    $number++;
                   9048: 	}
1.411     www      9049:         $result.="</p>\n";
1.408     albertel 9050: 	if ($number==0) {
                   9051: 	    $result.='<span class="LC_error">'.&mt('No IDs found to determine correct answer').'</span>';
                   9052: 	    return $result.&show_grading_menu_form($symb);
                   9053: 	}
1.404     www      9054:     }
1.405     www      9055:     if (length($env{'form.upfile'}) < 2) {
1.407     albertel 9056:         $result.=&mt('[_1] Error: [_2] The file you attempted to upload, [_3] contained no information. Please check that you entered the correct filename.',
                   9057: 		     '<span class="LC_error">',
                   9058: 		     '</span>',
                   9059: 		     '<span class="LC_filename">'.&HTML::Entities::encode($env{'form.upfile.filename'},'<>&"').'</span>');
1.405     www      9060:         return $result.&show_grading_menu_form($symb);
                   9061:     }
1.410     www      9062: 
                   9063: # Were able to get all the info needed, now analyze the file
                   9064: 
1.411     www      9065:     $result.=&Apache::loncommon::studentbrowser_javascript();
1.418     albertel 9066:     $symb = &Apache::lonenc::check_encrypt($symb);
1.410     www      9067:     my $heading=&mt('Scanning clicker file');
                   9068:     $result.=(<<ENDHEADER);
                   9069: <br /><table width="100%" border="0"><tr><td bgcolor="#777777">
                   9070: <table width="100%" border="0"><tr bgcolor="#e6ffff"><td>
                   9071: <b>$heading</b></td></tr><tr bgcolor=#ffffe6><td>
                   9072: <form method="post" action="/adm/grades" name="clickeranalysis">
                   9073: <input type="hidden" name="symb" value="$symb" />
                   9074: <input type="hidden" name="command" value="assignclickergrades" />
                   9075: <input type="hidden" name="probTitle" value="$env{'form.probTitle'}" />
                   9076: <input type="hidden" name="saveState"  value="$env{'form.saveState'}" />
1.411     www      9077: <input type="hidden" name="gradingmechanism" value="$env{'form.gradingmechanism'}" />
                   9078: <input type="hidden" name="pcorrect" value="$env{'form.pcorrect'}" />
                   9079: <input type="hidden" name="pincorrect" value="$env{'form.pincorrect'}" />
1.410     www      9080: ENDHEADER
1.522     www      9081:     if ($env{'form.gradingmechanism'} eq 'given') {
                   9082:        $result.='<input type="hidden" name="correct:given" value="'.$env{'form.givenanswer'}.'" />';
                   9083:     } 
1.408     albertel 9084:     my %responses;
                   9085:     my @questiontitles;
1.405     www      9086:     my $errormsg='';
                   9087:     my $number=0;
                   9088:     if ($env{'form.upfiletype'} eq 'iclicker') {
1.408     albertel 9089: 	($errormsg,$number)=&iclicker_eval(\@questiontitles,\%responses);
1.406     www      9090:     }
1.419     www      9091:     if ($env{'form.upfiletype'} eq 'interwrite') {
                   9092:         ($errormsg,$number)=&interwrite_eval(\@questiontitles,\%responses);
                   9093:     }
1.411     www      9094:     $result.='<br />'.&mt('Found [_1] question(s)',$number).'<br />'.
                   9095:              '<input type="hidden" name="number" value="'.$number.'" />'.
                   9096:              &mt('Awarding [_1] percent for correct and [_2] percent for incorrect responses',
                   9097:                  $env{'form.pcorrect'},$env{'form.pincorrect'}).
                   9098:              '<br />';
1.522     www      9099:     if (($env{'form.gradingmechanism'} eq 'given') && ($number!=$foundgiven)) {
                   9100:        $result.='<span class="LC_error">'.&mt('Number of given answers does not agree with number of questions in file.').'</span>';
                   9101:        return $result.&show_grading_menu_form($symb);
                   9102:     } 
1.414     www      9103: # Remember Question Titles
                   9104: # FIXME: Possibly need delimiter other than ":"
                   9105:     for (my $i=0;$i<$number;$i++) {
                   9106:         $result.='<input type="hidden" name="question:'.$i.'" value="'.
                   9107:                  &HTML::Entities::encode($questiontitles[$i],'"&<>').'" />';
                   9108:     }
1.411     www      9109:     my $correct_count=0;
                   9110:     my $student_count=0;
                   9111:     my $unknown_count=0;
1.414     www      9112: # Match answers with usernames
                   9113: # FIXME: Possibly need delimiter other than ":"
1.409     albertel 9114:     foreach my $id (keys(%responses)) {
1.410     www      9115:        if ($correct_ids{$id}) {
1.414     www      9116:           $result.="\n".'<input type="hidden" name="correct:'.$correct_count.':'.$correct_ids{$id}.'" value="'.$responses{$id}.'" />';
1.411     www      9117:           $correct_count++;
1.410     www      9118:        } elsif ($clicker_ids{$id}) {
1.437     www      9119:           if ($clicker_ids{$id}=~/\,/) {
                   9120: # More than one user with the same clicker!
                   9121:              $result.="\n<hr />".&mt('Clicker registered more than once').": <tt>".$id."</tt><br />";
                   9122:              $result.="\n".'<input type="hidden" name="unknown:'.$id.'" value="'.$responses{$id}.'" />'.
                   9123:                            "<select name='multi".$id."'>";
                   9124:              foreach my $reguser (sort(split(/\,/,$clicker_ids{$id}))) {
                   9125:                  $result.="<option value='".$reguser."'>".&Apache::loncommon::plainname(split(/\:/,$reguser)).' ('.$reguser.')</option>';
                   9126:              }
                   9127:              $result.='</select>';
                   9128:              $unknown_count++;
                   9129:           } else {
                   9130: # Good: found one and only one user with the right clicker
                   9131:              $result.="\n".'<input type="hidden" name="student:'.$clicker_ids{$id}.'" value="'.$responses{$id}.'" />';
                   9132:              $student_count++;
                   9133:           }
1.410     www      9134:        } else {
1.411     www      9135:           $result.="\n<hr />".&mt('Unregistered Clicker')." <tt>".$id."</tt><br />";
                   9136:           $result.="\n".'<input type="hidden" name="unknown:'.$id.'" value="'.$responses{$id}.'" />'.
                   9137:                    "\n".&mt("Username").": <input type='text' name='uname".$id."' />&nbsp;".
                   9138:                    "\n".&mt("Domain").": ".
                   9139:                    &Apache::loncommon::select_dom_form($env{'course.'.$env{'request.course.id'}.'.domain'},'udom'.$id).'&nbsp;'.
                   9140:                    &Apache::loncommon::selectstudent_link('clickeranalysis','uname'.$id,'udom'.$id);
                   9141:           $unknown_count++;
1.410     www      9142:        }
1.405     www      9143:     }
1.412     www      9144:     $result.='<hr />'.
                   9145:              &mt('Found [_1] registered and [_2] unregistered clickers.',$student_count,$unknown_count);
1.521     www      9146:     if (($env{'form.gradingmechanism'} ne 'attendance') && ($env{'form.gradingmechanism'} ne 'given')) {
1.412     www      9147:        if ($correct_count==0) {
                   9148:           $errormsg.="Found no correct answers answers for grading!";
                   9149:        } elsif ($correct_count>1) {
1.414     www      9150:           $result.='<br /><span class="LC_warning">'.&mt("Found [_1] entries for grading!",$correct_count).'</span>';
1.412     www      9151:        }
                   9152:     }
1.428     www      9153:     if ($number<1) {
                   9154:        $errormsg.="Found no questions.";
                   9155:     }
1.412     www      9156:     if ($errormsg) {
                   9157:        $result.='<br /><span class="LC_error">'.&mt($errormsg).'</span>';
                   9158:     } else {
                   9159:        $result.='<br /><input type="submit" name="finalize" value="'.&mt('Finalize Grading').'" />';
                   9160:     }
                   9161:     $result.='</form></td></tr></table>'."\n".
1.410     www      9162:              '</td></tr></table><br /><br />'."\n";
1.404     www      9163:     return $result.&show_grading_menu_form($symb);
1.400     www      9164: }
                   9165: 
1.405     www      9166: sub iclicker_eval {
1.406     www      9167:     my ($questiontitles,$responses)=@_;
1.405     www      9168:     my $number=0;
                   9169:     my $errormsg='';
                   9170:     foreach my $line (split(/[\n\r]/,$env{'form.upfile'})) {
1.410     www      9171:         my %components=&Apache::loncommon::record_sep($line);
                   9172:         my @entries=map {$components{$_}} (sort(keys(%components)));
1.408     albertel 9173: 	if ($entries[0] eq 'Question') {
                   9174: 	    for (my $i=3;$i<$#entries;$i+=6) {
                   9175: 		$$questiontitles[$number]=$entries[$i];
                   9176: 		$number++;
                   9177: 	    }
                   9178: 	}
                   9179: 	if ($entries[0]=~/^\#/) {
                   9180: 	    my $id=$entries[0];
                   9181: 	    my @idresponses;
                   9182: 	    $id=~s/^[\#0]+//;
                   9183: 	    for (my $i=0;$i<$number;$i++) {
                   9184: 		my $idx=3+$i*6;
                   9185: 		push(@idresponses,$entries[$idx]);
                   9186: 	    }
                   9187: 	    $$responses{$id}=join(',',@idresponses);
                   9188: 	}
1.405     www      9189:     }
                   9190:     return ($errormsg,$number);
                   9191: }
                   9192: 
1.419     www      9193: sub interwrite_eval {
                   9194:     my ($questiontitles,$responses)=@_;
                   9195:     my $number=0;
                   9196:     my $errormsg='';
1.420     www      9197:     my $skipline=1;
                   9198:     my $questionnumber=0;
                   9199:     my %idresponses=();
1.419     www      9200:     foreach my $line (split(/[\n\r]/,$env{'form.upfile'})) {
                   9201:         my %components=&Apache::loncommon::record_sep($line);
                   9202:         my @entries=map {$components{$_}} (sort(keys(%components)));
1.420     www      9203:         if ($entries[1] eq 'Time') { $skipline=0; next; }
                   9204:         if ($entries[1] eq 'Response') { $skipline=1; }
                   9205:         next if $skipline;
                   9206:         if ($entries[0]!=$questionnumber) {
                   9207:            $questionnumber=$entries[0];
                   9208:            $$questiontitles[$number]=&mt('Question [_1]',$questionnumber);
                   9209:            $number++;
1.419     www      9210:         }
1.420     www      9211:         my $id=$entries[4];
                   9212:         $id=~s/^[\#0]+//;
1.421     www      9213:         $id=~s/^v\d*\://i;
                   9214:         $id=~s/[\-\:]//g;
1.420     www      9215:         $idresponses{$id}[$number]=$entries[6];
                   9216:     }
1.524     raeburn  9217:     foreach my $id (keys(%idresponses)) {
1.420     www      9218:        $$responses{$id}=join(',',@{$idresponses{$id}});
                   9219:        $$responses{$id}=~s/^\s*\,//;
1.419     www      9220:     }
                   9221:     return ($errormsg,$number);
                   9222: }
                   9223: 
1.414     www      9224: sub assign_clicker_grades {
                   9225:     my ($r)=@_;
                   9226:     my ($symb)=&get_symb($r);
                   9227:     if (!$symb) {return '';}
1.416     www      9228: # See which part we are saving to
1.582     raeburn  9229:     my $res_error;
                   9230:     my ($partlist,$handgrade,$responseType) = &response_type($symb,\$res_error);
                   9231:     if ($res_error) {
                   9232:         return &navmap_errormsg();
                   9233:     }
1.416     www      9234: # FIXME: This should probably look for the first handgradeable part
                   9235:     my $part=$$partlist[0];
                   9236: # Start screen output
1.414     www      9237:     my ($result) = &showResourceInfo($symb,$env{'form.probTitle'});
1.416     www      9238: 
1.414     www      9239:     my $heading=&mt('Assigning grades based on clicker file');
                   9240:     $result.=(<<ENDHEADER);
                   9241: <br /><table width="100%" border="0"><tr><td bgcolor="#777777">
                   9242: <table width="100%" border="0"><tr bgcolor="#e6ffff"><td>
                   9243: <b>$heading</b></td></tr><tr bgcolor=#ffffe6><td>
                   9244: ENDHEADER
                   9245: # Get correct result
                   9246: # FIXME: Possibly need delimiter other than ":"
                   9247:     my @correct=();
1.415     www      9248:     my $gradingmechanism=$env{'form.gradingmechanism'};
                   9249:     my $number=$env{'form.number'};
                   9250:     if ($gradingmechanism ne 'attendance') {
1.414     www      9251:        foreach my $key (keys(%env)) {
                   9252:           if ($key=~/^form\.correct\:/) {
                   9253:              my @input=split(/\,/,$env{$key});
                   9254:              for (my $i=0;$i<=$#input;$i++) {
                   9255:                  if (($correct[$i]) && ($input[$i]) &&
                   9256:                      ($correct[$i] ne $input[$i])) {
                   9257:                     $result.='<br /><span class="LC_warning">'.
                   9258:                              &mt('More than one correct result given for question "[_1]": [_2] versus [_3].',
                   9259:                                  $env{'form.question:'.$i},$correct[$i],$input[$i]).'</span>';
                   9260:                  } elsif ($input[$i]) {
                   9261:                     $correct[$i]=$input[$i];
                   9262:                  }
                   9263:              }
                   9264:           }
                   9265:        }
1.415     www      9266:        for (my $i=0;$i<$number;$i++) {
1.414     www      9267:           if (!$correct[$i]) {
                   9268:              $result.='<br /><span class="LC_error">'.
                   9269:                       &mt('No correct result given for question "[_1]"!',
                   9270:                           $env{'form.question:'.$i}).'</span>';
                   9271:           }
                   9272:        }
                   9273:        $result.='<br />'.&mt("Correct answer: [_1]",join(', ',map { ($_?$_:'-') } @correct));
                   9274:     }
                   9275: # Start grading
1.415     www      9276:     my $pcorrect=$env{'form.pcorrect'};
                   9277:     my $pincorrect=$env{'form.pincorrect'};
1.416     www      9278:     my $storecount=0;
1.415     www      9279:     foreach my $key (keys(%env)) {
1.420     www      9280:        my $user='';
1.415     www      9281:        if ($key=~/^form\.student\:(.*)$/) {
1.420     www      9282:           $user=$1;
                   9283:        }
                   9284:        if ($key=~/^form\.unknown\:(.*)$/) {
                   9285:           my $id=$1;
                   9286:           if (($env{'form.uname'.$id}) && ($env{'form.udom'.$id})) {
                   9287:              $user=$env{'form.uname'.$id}.':'.$env{'form.udom'.$id};
1.437     www      9288:           } elsif ($env{'form.multi'.$id}) {
                   9289:              $user=$env{'form.multi'.$id};
1.420     www      9290:           }
                   9291:        }
                   9292:        if ($user) { 
1.415     www      9293:           my @answer=split(/\,/,$env{$key});
                   9294:           my $sum=0;
1.522     www      9295:           my $realnumber=$number;
1.415     www      9296:           for (my $i=0;$i<$number;$i++) {
1.576     www      9297:              if  ($correct[$i] eq '-') {
                   9298:                 $realnumber--;
                   9299:              } elsif ($answer[$i]) {
1.415     www      9300:                 if ($gradingmechanism eq 'attendance') {
                   9301:                    $sum+=$pcorrect;
1.576     www      9302:                 } elsif ($correct[$i] eq '*') {
1.522     www      9303:                    $sum+=$pcorrect;
1.415     www      9304:                 } else {
                   9305:                    if ($answer[$i] eq $correct[$i]) {
                   9306:                       $sum+=$pcorrect;
                   9307:                    } else {
                   9308:                       $sum+=$pincorrect;
                   9309:                    }
                   9310:                 }
                   9311:              }
                   9312:           }
1.522     www      9313:           my $ave=$sum/(100*$realnumber);
1.416     www      9314: # Store
                   9315:           my ($username,$domain)=split(/\:/,$user);
                   9316:           my %grades=();
                   9317:           $grades{"resource.$part.solved"}='correct_by_override';
                   9318:           $grades{"resource.$part.awarded"}=$ave;
                   9319:           $grades{"resource.regrader"}="$env{'user.name'}:$env{'user.domain'}";
                   9320:           my $returncode=&Apache::lonnet::cstore(\%grades,$symb,
                   9321:                                                  $env{'request.course.id'},
                   9322:                                                  $domain,$username);
                   9323:           if ($returncode ne 'ok') {
                   9324:              $result.="<br /><span class=\"LC_error\">Failed to save student $username:$domain. Message when trying to save was ($returncode)</span>";
                   9325:           } else {
                   9326:              $storecount++;
                   9327:           }
1.415     www      9328:        }
                   9329:     }
                   9330: # We are done
1.549     hauer    9331:     $result.='<br />'.&mt('Successfully stored grades for [quant,_1,student].',$storecount).
1.416     www      9332:              '</td></tr></table>'."\n".
1.414     www      9333:              '</td></tr></table><br /><br />'."\n";
                   9334:     return $result.&show_grading_menu_form($symb);
                   9335: }
                   9336: 
1.582     raeburn  9337: sub navmap_errormsg {
                   9338:     return '<div class="LC_error">'.
                   9339:            &mt('An error occurred retrieving information about resources in the course.').'<br />'.
1.595     raeburn  9340:            &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  9341:            '</div>';
                   9342: }
                   9343: 
1.1       albertel 9344: sub handler {
1.41      ng       9345:     my $request=$_[0];
1.434     albertel 9346:     &reset_caches();
1.257     albertel 9347:     if ($env{'browser.mathml'}) {
1.141     www      9348: 	&Apache::loncommon::content_type($request,'text/xml');
1.41      ng       9349:     } else {
1.141     www      9350: 	&Apache::loncommon::content_type($request,'text/html');
1.41      ng       9351:     }
                   9352:     $request->send_http_header;
1.44      ng       9353:     return '' if $request->header_only;
1.41      ng       9354:     &Apache::loncommon::get_unprocessed_cgi($ENV{'QUERY_STRING'});
1.324     albertel 9355:     my $symb=&get_symb($request,1);
1.160     albertel 9356:     my @commands=&Apache::loncommon::get_env_multiple('form.command');
                   9357:     my $command=$commands[0];
1.447     foxr     9358: 
1.160     albertel 9359:     if ($#commands > 0) {
                   9360: 	&Apache::lonnet::logthis("grades got multiple commands ".join(':',@commands));
                   9361:     }
1.447     foxr     9362: 
1.513     foxr     9363:     $ssi_error = 0;
1.535     raeburn  9364:     my $brcrum = [{href=>"/adm/grades",text=>"Grading"}];
                   9365:     $request->print(&Apache::loncommon::start_page('Grading',undef,
                   9366:                                           {'bread_crumbs' => $brcrum}));
1.324     albertel 9367:     if ($symb eq '' && $command eq '') {
1.257     albertel 9368: 	if ($env{'user.adv'}) {
                   9369: 	    if (($env{'form.codeone'}) && ($env{'form.codetwo'}) &&
                   9370: 		($env{'form.codethree'})) {
                   9371: 		my $token=$env{'form.codeone'}.'*'.$env{'form.codetwo'}.'*'.
                   9372: 		    $env{'form.codethree'};
1.41      ng       9373: 		my ($tsymb,$tuname,$tudom,$tcrsid)=
                   9374: 		    &Apache::lonnet::checkin($token);
                   9375: 		if ($tsymb) {
1.137     albertel 9376: 		    my ($map,$id,$url)=&Apache::lonnet::decode_symb($tsymb);
1.41      ng       9377: 		    if (&Apache::lonnet::allowed('mgr',$tcrsid)) {
1.513     foxr     9378: 			$request->print(&ssi_with_retries('/res/'.$url, $ssi_retries,
1.99      albertel 9379: 					  ('grade_username' => $tuname,
                   9380: 					   'grade_domain' => $tudom,
                   9381: 					   'grade_courseid' => $tcrsid,
                   9382: 					   'grade_symb' => $tsymb)));
1.41      ng       9383: 		    } else {
1.45      ng       9384: 			$request->print('<h3>Not authorized: '.$token.'</h3>');
1.99      albertel 9385: 		    }
1.41      ng       9386: 		} else {
1.45      ng       9387: 		    $request->print('<h3>Not a valid DocID: '.$token.'</h3>');
1.41      ng       9388: 		}
1.14      www      9389: 	    } else {
1.41      ng       9390: 		$request->print(&Apache::lonxml::tokeninputfield());
                   9391: 	    }
                   9392: 	}
                   9393:     } else {
1.285     albertel 9394: 	&init_perm();
1.104     albertel 9395: 	if ($command eq 'submission' && $perm{'vgr'}) {
1.257     albertel 9396: 	    ($env{'form.student'} eq '' ? &listStudents($request) : &submission($request,0,0));
1.103     albertel 9397: 	} elsif ($command eq 'pickStudentPage' && $perm{'vgr'}) {
1.68      ng       9398: 	    &pickStudentPage($request);
1.103     albertel 9399: 	} elsif ($command eq 'displayPage' && $perm{'vgr'}) {
1.68      ng       9400: 	    &displayPage($request);
1.104     albertel 9401: 	} elsif ($command eq 'gradeByPage' && $perm{'mgr'}) {
1.71      ng       9402: 	    &updateGradeByPage($request);
1.104     albertel 9403: 	} elsif ($command eq 'processGroup' && $perm{'vgr'}) {
1.41      ng       9404: 	    &processGroup($request);
1.104     albertel 9405: 	} elsif ($command eq 'gradingmenu' && $perm{'vgr'}) {
1.443     banghart 9406: 	    $request->print(&grading_menu($request));
                   9407: 	} elsif ($command eq 'submit_options' && $perm{'vgr'}) {
                   9408: 	    $request->print(&submit_options($request));
1.104     albertel 9409: 	} elsif ($command eq 'viewgrades' && $perm{'vgr'}) {
1.41      ng       9410: 	    $request->print(&viewgrades($request));
1.104     albertel 9411: 	} elsif ($command eq 'handgrade' && $perm{'mgr'}) {
1.41      ng       9412: 	    $request->print(&processHandGrade($request));
1.106     albertel 9413: 	} elsif ($command eq 'editgrades' && $perm{'mgr'}) {
1.41      ng       9414: 	    $request->print(&editgrades($request));
1.106     albertel 9415: 	} elsif ($command eq 'verify' && $perm{'vgr'}) {
1.41      ng       9416: 	    $request->print(&verifyreceipt($request));
1.400     www      9417:         } elsif ($command eq 'processclicker' && $perm{'mgr'}) {
                   9418:             $request->print(&process_clicker($request));
                   9419:         } elsif ($command eq 'processclickerfile' && $perm{'mgr'}) {
                   9420:             $request->print(&process_clicker_file($request));
1.414     www      9421:         } elsif ($command eq 'assignclickergrades' && $perm{'mgr'}) {
                   9422:             $request->print(&assign_clicker_grades($request));
1.106     albertel 9423: 	} elsif ($command eq 'csvform' && $perm{'mgr'}) {
1.72      ng       9424: 	    $request->print(&upcsvScores_form($request));
1.106     albertel 9425: 	} elsif ($command eq 'csvupload' && $perm{'mgr'}) {
1.41      ng       9426: 	    $request->print(&csvupload($request));
1.106     albertel 9427: 	} elsif ($command eq 'csvuploadmap' && $perm{'mgr'} ) {
1.41      ng       9428: 	    $request->print(&csvuploadmap($request));
1.246     albertel 9429: 	} elsif ($command eq 'csvuploadoptions' && $perm{'mgr'}) {
1.257     albertel 9430: 	    if ($env{'form.associate'} ne 'Reverse Association') {
1.246     albertel 9431: 		$request->print(&csvuploadoptions($request));
1.41      ng       9432: 	    } else {
1.257     albertel 9433: 		if ( $env{'form.upfile_associate'} ne 'reverse' ) {
                   9434: 		    $env{'form.upfile_associate'} = 'reverse';
1.41      ng       9435: 		} else {
1.257     albertel 9436: 		    $env{'form.upfile_associate'} = 'forward';
1.41      ng       9437: 		}
                   9438: 		$request->print(&csvuploadmap($request));
                   9439: 	    }
1.246     albertel 9440: 	} elsif ($command eq 'csvuploadassign' && $perm{'mgr'} ) {
                   9441: 	    $request->print(&csvuploadassign($request));
1.106     albertel 9442: 	} elsif ($command eq 'scantron_selectphase' && $perm{'mgr'}) {
1.75      albertel 9443: 	    $request->print(&scantron_selectphase($request));
1.203     albertel 9444:  	} elsif ($command eq 'scantron_warning' && $perm{'mgr'}) {
                   9445:  	    $request->print(&scantron_do_warning($request));
1.142     albertel 9446: 	} elsif ($command eq 'scantron_validate' && $perm{'mgr'}) {
                   9447: 	    $request->print(&scantron_validate_file($request));
1.106     albertel 9448: 	} elsif ($command eq 'scantron_process' && $perm{'mgr'}) {
1.82      albertel 9449: 	    $request->print(&scantron_process_students($request));
1.157     albertel 9450:  	} elsif ($command eq 'scantronupload' && 
1.257     albertel 9451:  		 (&Apache::lonnet::allowed('usc',$env{'request.role.domain'})||
                   9452: 		  &Apache::lonnet::allowed('usc',$env{'request.course.id'}))) {
1.162     albertel 9453:  	    $request->print(&scantron_upload_scantron_data($request)); 
1.157     albertel 9454:  	} elsif ($command eq 'scantronupload_save' &&
1.257     albertel 9455:  		 (&Apache::lonnet::allowed('usc',$env{'request.role.domain'})||
                   9456: 		  &Apache::lonnet::allowed('usc',$env{'request.course.id'}))) {
1.157     albertel 9457:  	    $request->print(&scantron_upload_scantron_data_save($request));
1.202     albertel 9458:  	} elsif ($command eq 'scantron_download' &&
1.257     albertel 9459: 		 &Apache::lonnet::allowed('usc',$env{'request.course.id'})) {
1.162     albertel 9460:  	    $request->print(&scantron_download_scantron_data($request));
1.523     raeburn  9461:         } elsif ($command eq 'checksubmissions' && $perm{'vgr'}) {
                   9462:             $request->print(&checkscantron_results($request));     
1.106     albertel 9463: 	} elsif ($command) {
1.562     bisitz   9464: 	    $request->print('<p class="LC_error">'.&mt('Access Denied ([_1])',$command).'</p>');
1.26      albertel 9465: 	}
1.2       albertel 9466:     }
1.513     foxr     9467:     if ($ssi_error) {
                   9468: 	&ssi_print_error($request);
                   9469:     }
1.353     albertel 9470:     $request->print(&Apache::loncommon::end_page());
1.434     albertel 9471:     &reset_caches();
1.44      ng       9472:     return '';
                   9473: }
                   9474: 
1.1       albertel 9475: 1;
                   9476: 
1.13      albertel 9477: __END__;
1.531     jms      9478: 
                   9479: 
                   9480: =head1 NAME
                   9481: 
                   9482: Apache::grades
                   9483: 
                   9484: =head1 SYNOPSIS
                   9485: 
                   9486: Handles the viewing of grades.
                   9487: 
                   9488: This is part of the LearningOnline Network with CAPA project
                   9489: described at http://www.lon-capa.org.
                   9490: 
                   9491: =head1 OVERVIEW
                   9492: 
                   9493: Do an ssi with retries:
                   9494: While I'd love to factor out this with the vesrion in lonprintout,
                   9495: 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
                   9496: I'm not quite ready to invent (e.g. an ssi_with_retry object).
                   9497: 
                   9498: At least the logic that drives this has been pulled out into loncommon.
                   9499: 
                   9500: 
                   9501: 
                   9502: ssi_with_retries - Does the server side include of a resource.
                   9503:                      if the ssi call returns an error we'll retry it up to
                   9504:                      the number of times requested by the caller.
                   9505:                      If we still have a proble, no text is appended to the
                   9506:                      output and we set some global variables.
                   9507:                      to indicate to the caller an SSI error occurred.  
                   9508:                      All of this is supposed to deal with the issues described
                   9509:                      in LonCAPA BZ 5631 see:
                   9510:                      http://bugs.lon-capa.org/show_bug.cgi?id=5631
                   9511:                      by informing the user that this happened.
                   9512: 
                   9513: Parameters:
                   9514:   resource   - The resource to include.  This is passed directly, without
                   9515:                interpretation to lonnet::ssi.
                   9516:   form       - The form hash parameters that guide the interpretation of the resource
                   9517:                
                   9518:   retries    - Number of retries allowed before giving up completely.
                   9519: Returns:
                   9520:   On success, returns the rendered resource identified by the resource parameter.
                   9521: Side Effects:
                   9522:   The following global variables can be set:
                   9523:    ssi_error                - If an unrecoverable error occurred this becomes true.
                   9524:                               It is up to the caller to initialize this to false
                   9525:                               if desired.
                   9526:    ssi_error_resource  - If an unrecoverable error occurred, this is the value
                   9527:                               of the resource that could not be rendered by the ssi
                   9528:                               call.
                   9529:    ssi_error_message   - The error string fetched from the ssi response
                   9530:                               in the event of an error.
                   9531: 
                   9532: 
                   9533: =head1 HANDLER SUBROUTINE
                   9534: 
                   9535: ssi_with_retries()
                   9536: 
                   9537: =head1 SUBROUTINES
                   9538: 
                   9539: =over
                   9540: 
                   9541: =item scantron_get_correction() : 
                   9542: 
                   9543:    Builds the interface screen to interact with the operator to fix a
                   9544:    specific error condition in a specific scanline
                   9545: 
                   9546:  Arguments:
                   9547:     $r           - Apache request object
                   9548:     $i           - number of the current scanline
                   9549:     $scan_record - hash ref as returned from &scantron_parse_scanline()
                   9550:     $scan_config - hash ref as returned from &get_scantron_config()
                   9551:     $line        - full contents of the current scanline
                   9552:     $error       - error condition, valid values are
                   9553:                    'incorrectCODE', 'duplicateCODE',
                   9554:                    'doublebubble', 'missingbubble',
                   9555:                    'duplicateID', 'incorrectID'
                   9556:     $arg         - extra information needed
                   9557:        For errors:
                   9558:          - duplicateID   - paper number that this studentID was seen before on
                   9559:          - duplicateCODE - array ref of the paper numbers this CODE was
                   9560:                            seen on before
                   9561:          - incorrectCODE - current incorrect CODE 
                   9562:          - doublebubble  - array ref of the bubble lines that have double
                   9563:                            bubble errors
                   9564:          - missingbubble - array ref of the bubble lines that have missing
                   9565:                            bubble errors
                   9566: 
                   9567: =item  scantron_get_maxbubble() : 
                   9568: 
1.582     raeburn  9569:    Arguments:
                   9570:        $nav_error  - Reference to scalar which is a flag to indicate a
                   9571:                       failure to retrieve a navmap object.
                   9572:        if $nav_error is set to 1 by scantron_get_maxbubble(), the 
                   9573:        calling routine should trap the error condition and display the warning
                   9574:        found in &navmap_errormsg().
                   9575: 
1.531     jms      9576:    Returns the maximum number of bubble lines that are expected to
                   9577:    occur. Does this by walking the selected sequence rendering the
                   9578:    resource and then checking &Apache::lonxml::get_problem_counter()
                   9579:    for what the current value of the problem counter is.
                   9580: 
                   9581:    Caches the results to $env{'form.scantron_maxbubble'},
                   9582:    $env{'form.scantron.bubble_lines.n'}, 
                   9583:    $env{'form.scantron.first_bubble_line.n'} and
                   9584:    $env{"form.scantron.sub_bubblelines.n"}
                   9585:    which are the total number of bubble, lines, the number of bubble
                   9586:    lines for response n and number of the first bubble line for response n,
                   9587:    and a comma separated list of numbers of bubble lines for sub-questions
                   9588:    (for optionresponse, matchresponse, and rankresponse items), for response n.  
                   9589: 
                   9590: 
                   9591: =item  scantron_validate_missingbubbles() : 
                   9592: 
                   9593:    Validates all scanlines in the selected file to not have any
                   9594:     answers that don't have bubbles that have not been verified
                   9595:     to be bubble free.
                   9596: 
                   9597: =item  scantron_process_students() : 
                   9598: 
                   9599:    Routine that does the actual grading of the bubble sheet information.
                   9600: 
                   9601:    The parsed scanline hash is added to %env 
                   9602: 
                   9603:    Then foreach unskipped scanline it does an &Apache::lonnet::ssi()
                   9604:    foreach resource , with the form data of
                   9605: 
                   9606: 	'submitted'     =>'scantron' 
                   9607: 	'grade_target'  =>'grade',
                   9608: 	'grade_username'=> username of student
                   9609: 	'grade_domain'  => domain of student
                   9610: 	'grade_courseid'=> of course
                   9611: 	'grade_symb'    => symb of resource to grade
                   9612: 
                   9613:     This triggers a grading pass. The problem grading code takes care
                   9614:     of converting the bubbled letter information (now in %env) into a
                   9615:     valid submission.
                   9616: 
                   9617: =item  scantron_upload_scantron_data() :
                   9618: 
                   9619:     Creates the screen for adding a new bubble sheet data file to a course.
                   9620: 
                   9621: =item  scantron_upload_scantron_data_save() : 
                   9622: 
                   9623:    Adds a provided bubble information data file to the course if user
                   9624:    has the correct privileges to do so. 
                   9625: 
                   9626: =item  valid_file() :
                   9627: 
                   9628:    Validates that the requested bubble data file exists in the course.
                   9629: 
                   9630: =item  scantron_download_scantron_data() : 
                   9631: 
                   9632:    Shows a list of the three internal files (original, corrected,
                   9633:    skipped) for a specific bubble sheet data file that exists in the
                   9634:    course.
                   9635: 
                   9636: =item  scantron_validate_ID() : 
                   9637: 
                   9638:    Validates all scanlines in the selected file to not have any
1.556     weissno  9639:    invalid or underspecified student/employee IDs
1.531     jms      9640: 
1.582     raeburn  9641: =item navmap_errormsg() :
                   9642: 
                   9643:    Returns HTML mark-up inside a <div></div> with a link to re-initialize the course.
                   9644:    Should be called whenever the request to instantiate a navmap object fails.  
                   9645: 
1.531     jms      9646: =back
                   9647: 
                   9648: =cut

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