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

1.17      albertel    1: # The LearningOnline Network with CAPA
1.13      albertel    2: # The LON-CAPA Grading handler
1.17      albertel    3: #
1.581   ! www         4: # $Id: grades.pm,v 1.580 2009/09/17 18:27:30 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.324     albertel  100:     my ($symb) = @_;
1.439     albertel  101: 
                    102:     my $navmap   = Apache::lonnavmaps::navmap->new();
                    103:     my $res      = $navmap->getBySymb($symb);
                    104:     my $partlist = $res->parts();
                    105:     my $url      = $res->src();
                    106:     my @metakeys = split(/,/,&Apache::lonnet::metadata($url,'keys'));
                    107: 
1.146     albertel  108:     my @stores;
1.439     albertel  109:     foreach my $part (@{ $partlist }) {
1.146     albertel  110: 	foreach my $key (@metakeys) {
                    111: 	    if ($key =~ m/^stores_\Q$part\E_/) { push(@stores,$key); }
                    112: 	}
                    113:     }
                    114:     return @stores;
1.2       albertel  115: }
                    116: 
1.44      ng        117: # --- Get the symbolic name of a problem and the url
1.324     albertel  118: sub get_symb {
1.173     albertel  119:     my ($request,$silent) = @_;
1.257     albertel  120:     (my $url=$env{'form.url'}) =~ s-^http://($ENV{'SERVER_NAME'}|$ENV{'HTTP_HOST'})--;
                    121:     my $symb=($env{'form.symb'} ne '' ? $env{'form.symb'} : (&Apache::lonnet::symbread($url)));
1.173     albertel  122:     if ($symb eq '') { 
                    123: 	if (!$silent) {
                    124: 	    $request->print("Unable to handle ambiguous references:$url:.");
                    125: 	    return ();
                    126: 	}
                    127:     }
1.418     albertel  128:     &Apache::lonenc::check_decrypt(\$symb);
1.324     albertel  129:     return ($symb);
1.32      ng        130: }
                    131: 
1.129     ng        132: #--- Format fullname, username:domain if different for display
                    133: #--- Use anywhere where the student names are listed
                    134: sub nameUserString {
                    135:     my ($type,$fullname,$uname,$udom) = @_;
                    136:     if ($type eq 'header') {
1.485     albertel  137: 	return '<b>&nbsp;'.&mt('Fullname').'&nbsp;</b><span class="LC_internal_info">('.&mt('Username').')</span>';
1.129     ng        138:     } else {
1.398     albertel  139: 	return '&nbsp;'.$fullname.'<span class="LC_internal_info">&nbsp;('.$uname.
                    140: 	    ($env{'user.domain'} eq $udom ? '' : ' ('.$udom.')').')</span>';
1.129     ng        141:     }
                    142: }
                    143: 
1.44      ng        144: #--- Get the partlist and the response type for a given problem. ---
                    145: #--- Indicate if a response type is coded handgraded or not. ---
1.39      ng        146: sub response_type {
1.324     albertel  147:     my ($symb) = shift;
1.377     albertel  148: 
                    149:     my $navmap = Apache::lonnavmaps::navmap->new();
                    150:     my $res = $navmap->getBySymb($symb);
                    151:     my $partlist = $res->parts();
1.392     albertel  152:     my %vPart = 
                    153: 	map { $_ => 1 } (&Apache::loncommon::get_env_multiple('form.vPart'));
1.377     albertel  154:     my (%response_types,%handgrade);
                    155:     foreach my $part (@{ $partlist }) {
1.392     albertel  156: 	next if (%vPart && !exists($vPart{$part}));
                    157: 
1.377     albertel  158: 	my @types = $res->responseType($part);
                    159: 	my @ids = $res->responseIds($part);
                    160: 	for (my $i=0; $i < scalar(@ids); $i++) {
                    161: 	    $response_types{$part}{$ids[$i]} = $types[$i];
                    162: 	    $handgrade{$part.'_'.$ids[$i]} = 
                    163: 		&Apache::lonnet::EXT('resource.'.$part.'_'.$ids[$i].
                    164: 				     '.handgrade',$symb);
1.41      ng        165: 	}
                    166:     }
1.377     albertel  167:     return ($partlist,\%handgrade,\%response_types);
1.39      ng        168: }
                    169: 
1.375     albertel  170: sub flatten_responseType {
                    171:     my ($responseType) = @_;
                    172:     my @part_response_id =
                    173: 	map { 
                    174: 	    my $part = $_;
                    175: 	    map {
                    176: 		[$part,$_]
                    177: 		} sort(keys(%{ $responseType->{$part} }));
                    178: 	} sort(keys(%$responseType));
                    179:     return @part_response_id;
                    180: }
                    181: 
1.207     albertel  182: sub get_display_part {
1.324     albertel  183:     my ($partID,$symb)=@_;
1.207     albertel  184:     my $display=&Apache::lonnet::EXT('resource.'.$partID.'.display',$symb);
                    185:     if (defined($display) and $display ne '') {
1.577     bisitz    186:         $display.= ' (<span class="LC_internal_info">'
                    187:                   .&mt('Part ID: [_1]',$partID).'</span>)';
1.207     albertel  188:     } else {
                    189: 	$display=$partID;
                    190:     }
                    191:     return $display;
                    192: }
1.269     raeburn   193: 
1.118     ng        194: #--- Show resource title
                    195: #--- and parts and response type
                    196: sub showResourceInfo {
1.324     albertel  197:     my ($symb,$probTitle,$checkboxes) = @_;
1.154     albertel  198:     my $col=3;
                    199:     if ($checkboxes) { $col=4; }
1.398     albertel  200:     my $result = '<h3>'.&mt('Current Resource').': '.$probTitle.'</h3>'."\n";
                    201:     $result .='<table border="0">';
1.324     albertel  202:     my ($partlist,$handgrade,$responseType) = &response_type($symb);
1.126     ng        203:     my %resptype = ();
1.122     ng        204:     my $hdgrade='no';
1.154     albertel  205:     my %partsseen;
1.524     raeburn   206:     foreach my $partID (sort(keys(%$responseType))) {
                    207: 	foreach my $resID (sort(keys(%{ $responseType->{$partID} }))) {
1.375     albertel  208: 	    my $handgrade=$$handgrade{$partID.'_'.$resID};
                    209: 	    my $responsetype = $responseType->{$partID}->{$resID};
                    210: 	    $hdgrade = $handgrade if ($handgrade eq 'yes');
                    211: 	    $result.='<tr>';
                    212: 	    if ($checkboxes) {
                    213: 		if (exists($partsseen{$partID})) {
                    214: 		    $result.="<td>&nbsp;</td>";
                    215: 		} else {
1.401     albertel  216: 		    $result.="<td><input type='checkbox' name='vPart' value='$partID' checked='checked' /></td>";
1.375     albertel  217: 		}
                    218: 		$partsseen{$partID}=1;
1.154     albertel  219: 	    }
1.375     albertel  220: 	    my $display_part=&get_display_part($partID,$symb);
1.577     bisitz    221:             $result.='<td><b>'.&mt('Part: [_1]',$display_part).'</b>'.
1.539     riegler   222:                 ' <span class="LC_internal_info">'.$resID.'</span></td>'.
1.577     bisitz    223:                 '<td><b>'.&mt('Type: [_1]',$responsetype).'</b></td></tr>';
1.485     albertel  224: #	    '<td>'.&mt('<b>Handgrade: </b>[_1]',$handgrade).'</td></tr>';
1.154     albertel  225: 	}
1.118     ng        226:     }
                    227:     $result.='</table>'."\n";
1.147     albertel  228:     return $result,$responseType,$hdgrade,$partlist,$handgrade;
1.118     ng        229: }
                    230: 
1.434     albertel  231: sub reset_caches {
                    232:     &reset_analyze_cache();
                    233:     &reset_perm();
                    234: }
                    235: 
                    236: {
                    237:     my %analyze_cache;
1.557     raeburn   238:     my %analyze_cache_formkeys;
1.148     albertel  239: 
1.434     albertel  240:     sub reset_analyze_cache {
                    241: 	undef(%analyze_cache);
1.557     raeburn   242:         undef(%analyze_cache_formkeys);
1.434     albertel  243:     }
                    244: 
                    245:     sub get_analyze {
1.557     raeburn   246: 	my ($symb,$uname,$udom,$no_increment,$add_to_hash)=@_;
1.434     albertel  247: 	my $key = "$symb\0$uname\0$udom";
1.557     raeburn   248: 	if (exists($analyze_cache{$key})) {
                    249:             my $getupdate = 0;
                    250:             if (ref($add_to_hash) eq 'HASH') {
                    251:                 foreach my $item (keys(%{$add_to_hash})) {
                    252:                     if (ref($analyze_cache_formkeys{$key}) eq 'HASH') {
                    253:                         if (!exists($analyze_cache_formkeys{$key}{$item})) {
                    254:                             $getupdate = 1;
                    255:                             last;
                    256:                         }
                    257:                     } else {
                    258:                         $getupdate = 1;
                    259:                     }
                    260:                 }
                    261:             }
                    262:             if (!$getupdate) {
                    263:                 return $analyze_cache{$key};
                    264:             }
                    265:         }
1.434     albertel  266: 
                    267: 	my (undef,undef,$url)=&Apache::lonnet::decode_symb($symb);
                    268: 	$url=&Apache::lonnet::clutter($url);
1.557     raeburn   269:         my %form = ('grade_target'      => 'analyze',
                    270:                     'grade_domain'      => $udom,
                    271:                     'grade_symb'        => $symb,
                    272:                     'grade_courseid'    =>  $env{'request.course.id'},
                    273:                     'grade_username'    => $uname,
                    274:                     'grade_noincrement' => $no_increment);
                    275:         if (ref($add_to_hash)) {
                    276:             %form = (%form,%{$add_to_hash});
                    277:         } 
                    278: 	my $subresult=&ssi_with_retries($url, $ssi_retries,%form);
1.434     albertel  279: 	(undef,$subresult)=split(/_HASH_REF__/,$subresult,2);
                    280: 	my %analyze=&Apache::lonnet::str2hash($subresult);
1.557     raeburn   281:         if (ref($add_to_hash) eq 'HASH') {
                    282:             $analyze_cache_formkeys{$key} = $add_to_hash;
                    283:         } else {
                    284:             $analyze_cache_formkeys{$key} = {};
                    285:         }
1.434     albertel  286: 	return $analyze_cache{$key} = \%analyze;
                    287:     }
                    288: 
                    289:     sub get_order {
1.525     raeburn   290: 	my ($partid,$respid,$symb,$uname,$udom,$no_increment)=@_;
                    291: 	my $analyze = &get_analyze($symb,$uname,$udom,$no_increment);
1.434     albertel  292: 	return $analyze->{"$partid.$respid.shown"};
                    293:     }
                    294: 
                    295:     sub get_radiobutton_correct_foil {
                    296: 	my ($partid,$respid,$symb,$uname,$udom)=@_;
                    297: 	my $analyze = &get_analyze($symb,$uname,$udom);
1.555     raeburn   298:         my $foils = &get_order($partid,$respid,$symb,$uname,$udom);
                    299:         if (ref($foils) eq 'ARRAY') {
                    300: 	    foreach my $foil (@{$foils}) {
                    301: 	        if ($analyze->{"$partid.$respid.foil.value.$foil"} eq 'true') {
                    302: 		    return $foil;
                    303: 	        }
1.434     albertel  304: 	    }
                    305: 	}
                    306:     }
1.554     raeburn   307: 
                    308:     sub scantron_partids_tograde {
1.557     raeburn   309:         my ($resource,$cid,$uname,$udom,$check_for_randomlist) = @_;
1.554     raeburn   310:         my (%analysis,@parts);
                    311:         if (ref($resource)) {
                    312:             my $symb = $resource->symb();
1.557     raeburn   313:             my $add_to_form;
                    314:             if ($check_for_randomlist) {
                    315:                 $add_to_form = { 'check_parts_withrandomlist' => 1,};
                    316:             }
                    317:             my $analyze = &get_analyze($symb,$uname,$udom,undef,$add_to_form);
1.554     raeburn   318:             if (ref($analyze) eq 'HASH') {
                    319:                 %analysis = %{$analyze};
                    320:             }
                    321:             if (ref($analysis{'parts'}) eq 'ARRAY') {
                    322:                 foreach my $part (@{$analysis{'parts'}}) {
                    323:                     my ($id,$respid) = split(/\./,$part);
                    324:                     if (!&Apache::loncommon::check_if_partid_hidden($id,$symb,$udom,$uname)) {
                    325:                         push(@parts,$part);
                    326:                     }
                    327:                 }
                    328:             }
                    329:         }
                    330:         return (\%analysis,\@parts);
                    331:     }
                    332: 
1.148     albertel  333: }
1.434     albertel  334: 
1.118     ng        335: #--- Clean response type for display
1.335     albertel  336: #--- Currently filters option/rank/radiobutton/match/essay/Task
                    337: #        response types only.
1.118     ng        338: sub cleanRecord {
1.336     albertel  339:     my ($answer,$response,$symb,$partid,$respid,$record,$order,$version,
                    340: 	$uname,$udom) = @_;
1.398     albertel  341:     my $grayFont = '<span class="LC_internal_info">';
1.148     albertel  342:     if ($response =~ /^(option|rank)$/) {
                    343: 	my %answer=&Apache::lonnet::str2hash($answer);
                    344: 	my %grading=&Apache::lonnet::str2hash($record->{$version."resource.$partid.$respid.submissiongrading"});
                    345: 	my ($toprow,$bottomrow);
                    346: 	foreach my $foil (@$order) {
                    347: 	    if ($grading{$foil} == 1) {
                    348: 		$toprow.='<td><b>'.$answer{$foil}.'&nbsp;</b></td>';
                    349: 	    } else {
                    350: 		$toprow.='<td><i>'.$answer{$foil}.'&nbsp;</i></td>';
                    351: 	    }
1.398     albertel  352: 	    $bottomrow.='<td>'.$grayFont.$foil.'</span>&nbsp;</td>';
1.148     albertel  353: 	}
                    354: 	return '<blockquote><table border="1">'.
1.466     albertel  355: 	    '<tr valign="top"><td>'.&mt('Answer').'</td>'.$toprow.'</tr>'.
                    356: 	    '<tr valign="top"><td>'.$grayFont.&mt('Option ID').'</span></td>'.
1.148     albertel  357: 	    $grayFont.$bottomrow.'</tr>'.'</table></blockquote>';
                    358:     } elsif ($response eq 'match') {
                    359: 	my %answer=&Apache::lonnet::str2hash($answer);
                    360: 	my %grading=&Apache::lonnet::str2hash($record->{$version."resource.$partid.$respid.submissiongrading"});
                    361: 	my @items=&Apache::lonnet::str2array($record->{$version."resource.$partid.$respid.submissionitems"});
                    362: 	my ($toprow,$middlerow,$bottomrow);
                    363: 	foreach my $foil (@$order) {
                    364: 	    my $item=shift(@items);
                    365: 	    if ($grading{$foil} == 1) {
                    366: 		$toprow.='<td><b>'.$item.'&nbsp;</b></td>';
1.398     albertel  367: 		$middlerow.='<td><b>'.$grayFont.$answer{$foil}.'&nbsp;</span></b></td>';
1.148     albertel  368: 	    } else {
                    369: 		$toprow.='<td><i>'.$item.'&nbsp;</i></td>';
1.398     albertel  370: 		$middlerow.='<td><i>'.$grayFont.$answer{$foil}.'&nbsp;</span></i></td>';
1.148     albertel  371: 	    }
1.398     albertel  372: 	    $bottomrow.='<td>'.$grayFont.$foil.'</span>&nbsp;</td>';
1.118     ng        373: 	}
1.126     ng        374: 	return '<blockquote><table border="1">'.
1.466     albertel  375: 	    '<tr valign="top"><td>'.&mt('Answer').'</td>'.$toprow.'</tr>'.
                    376: 	    '<tr valign="top"><td>'.$grayFont.&mt('Item ID').'</span></td>'.
1.148     albertel  377: 	    $middlerow.'</tr>'.
1.466     albertel  378: 	    '<tr valign="top"><td>'.$grayFont.&mt('Option ID').'</span></td>'.
1.148     albertel  379: 	    $bottomrow.'</tr>'.'</table></blockquote>';
                    380:     } elsif ($response eq 'radiobutton') {
                    381: 	my %answer=&Apache::lonnet::str2hash($answer);
                    382: 	my ($toprow,$bottomrow);
1.434     albertel  383: 	my $correct = 
                    384: 	    &get_radiobutton_correct_foil($partid,$respid,$symb,$uname,$udom);
                    385: 	foreach my $foil (@$order) {
1.148     albertel  386: 	    if (exists($answer{$foil})) {
1.434     albertel  387: 		if ($foil eq $correct) {
1.466     albertel  388: 		    $toprow.='<td><b>'.&mt('true').'</b></td>';
1.148     albertel  389: 		} else {
1.466     albertel  390: 		    $toprow.='<td><i>'.&mt('true').'</i></td>';
1.148     albertel  391: 		}
                    392: 	    } else {
1.466     albertel  393: 		$toprow.='<td>'.&mt('false').'</td>';
1.148     albertel  394: 	    }
1.398     albertel  395: 	    $bottomrow.='<td>'.$grayFont.$foil.'</span>&nbsp;</td>';
1.148     albertel  396: 	}
                    397: 	return '<blockquote><table border="1">'.
1.466     albertel  398: 	    '<tr valign="top"><td>'.&mt('Answer').'</td>'.$toprow.'</tr>'.
                    399: 	    '<tr valign="top"><td>'.$grayFont.&mt('Option ID').'</span></td>'.
1.148     albertel  400: 	    $grayFont.$bottomrow.'</tr>'.'</table></blockquote>';
                    401:     } elsif ($response eq 'essay') {
1.257     albertel  402: 	if (! exists ($env{'form.'.$symb})) {
1.122     ng        403: 	    my (%keyhash) = &Apache::lonnet::dump('nohist_handgrade',
1.257     albertel  404: 						  $env{'course.'.$env{'request.course.id'}.'.domain'},
                    405: 						  $env{'course.'.$env{'request.course.id'}.'.num'});
1.122     ng        406: 
1.257     albertel  407: 	    my $loginuser = $env{'user.name'}.':'.$env{'user.domain'};
                    408: 	    $env{'form.keywords'} = $keyhash{$symb.'_keywords'} ne '' ? $keyhash{$symb.'_keywords'} : '';
                    409: 	    $env{'form.kwclr'}    = $keyhash{$loginuser.'_kwclr'} ne '' ? $keyhash{$loginuser.'_kwclr'} : 'red';
                    410: 	    $env{'form.kwsize'}   = $keyhash{$loginuser.'_kwsize'} ne '' ? $keyhash{$loginuser.'_kwsize'} : '0';
                    411: 	    $env{'form.kwstyle'}  = $keyhash{$loginuser.'_kwstyle'} ne '' ? $keyhash{$loginuser.'_kwstyle'} : '';
                    412: 	    $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        413: 	}
1.166     albertel  414: 	$answer =~ s-\n-<br />-g;
                    415: 	return '<br /><br /><blockquote><tt>'.&keywords_highlight($answer).'</tt></blockquote>';
1.268     albertel  416:     } elsif ( $response eq 'organic') {
                    417: 	my $result='Smile representation: "<tt>'.$answer.'</tt>"';
                    418: 	my $jme=$record->{$version."resource.$partid.$respid.molecule"};
                    419: 	$result.=&Apache::chemresponse::jme_img($jme,$answer,400);
                    420: 	return $result;
1.335     albertel  421:     } elsif ( $response eq 'Task') {
                    422: 	if ( $answer eq 'SUBMITTED') {
                    423: 	    my $files = $record->{$version."resource.$respid.$partid.bridgetask.portfiles"};
1.336     albertel  424: 	    my $result = &Apache::bridgetask::file_list($files,$uname,$udom);
1.335     albertel  425: 	    return $result;
                    426: 	} elsif ( grep(/^\Q$version\E.*?\.instance$/, keys(%{$record})) ) {
                    427: 	    my @matches = grep(/^\Q$version\E.*?\.instance$/,
                    428: 			       keys(%{$record}));
                    429: 	    return join('<br />',($version,@matches));
                    430: 			       
                    431: 			       
                    432: 	} else {
                    433: 	    my $result =
                    434: 		'<p>'
                    435: 		.&mt('Overall result: [_1]',
                    436: 		     $record->{$version."resource.$respid.$partid.status"})
                    437: 		.'</p>';
                    438: 	    
                    439: 	    $result .= '<ul>';
                    440: 	    my @grade = grep(/^\Q${version}resource.$respid.$partid.\E[^.]*[.]status$/,
                    441: 			     keys(%{$record}));
                    442: 	    foreach my $grade (sort(@grade)) {
                    443: 		my ($dim) = ($grade =~/[.]([^.]+)[.]status$/);
                    444: 		$result.= '<li>'.&mt("Dimension: [_1], status [_2] ",
                    445: 				     $dim, $record->{$grade}).
                    446: 			  '</li>';
                    447: 	    }
                    448: 	    $result.='</ul>';
                    449: 	    return $result;
                    450: 	}
1.440     albertel  451:     } elsif ( $response =~ m/(?:numerical|formula)/) {
                    452: 	$answer = 
                    453: 	    &Apache::loncommon::format_previous_attempt_value('submission',
                    454: 							      $answer);
1.122     ng        455:     }
1.118     ng        456:     return $answer;
                    457: }
                    458: 
                    459: #-- A couple of common js functions
                    460: sub commonJSfunctions {
                    461:     my $request = shift;
                    462:     $request->print(<<COMMONJSFUNCTIONS);
                    463: <script type="text/javascript" language="javascript">
                    464:     function radioSelection(radioButton) {
                    465: 	var selection=null;
                    466: 	if (radioButton.length > 1) {
                    467: 	    for (var i=0; i<radioButton.length; i++) {
                    468: 		if (radioButton[i].checked) {
                    469: 		    return radioButton[i].value;
                    470: 		}
                    471: 	    }
                    472: 	} else {
                    473: 	    if (radioButton.checked) return radioButton.value;
                    474: 	}
                    475: 	return selection;
                    476:     }
                    477: 
                    478:     function pullDownSelection(selectOne) {
                    479: 	var selection="";
                    480: 	if (selectOne.length > 1) {
                    481: 	    for (var i=0; i<selectOne.length; i++) {
                    482: 		if (selectOne[i].selected) {
                    483: 		    return selectOne[i].value;
                    484: 		}
                    485: 	    }
                    486: 	} else {
1.138     albertel  487:             // only one value it must be the selected one
                    488: 	    return selectOne.value;
1.118     ng        489: 	}
                    490:     }
                    491: </script>
                    492: COMMONJSFUNCTIONS
                    493: }
                    494: 
1.44      ng        495: #--- Dumps the class list with usernames,list of sections,
                    496: #--- section, ids and fullnames for each user.
                    497: sub getclasslist {
1.449     banghart  498:     my ($getsec,$filterlist,$getgroup) = @_;
1.291     albertel  499:     my @getsec;
1.450     banghart  500:     my @getgroup;
1.442     banghart  501:     my $stu_status = join(':',&Apache::loncommon::get_env_multiple('form.Status'));
1.291     albertel  502:     if (!ref($getsec)) {
                    503: 	if ($getsec ne '' && $getsec ne 'all') {
                    504: 	    @getsec=($getsec);
                    505: 	}
                    506:     } else {
                    507: 	@getsec=@{$getsec};
                    508:     }
                    509:     if (grep(/^all$/,@getsec)) { undef(@getsec); }
1.450     banghart  510:     if (!ref($getgroup)) {
                    511: 	if ($getgroup ne '' && $getgroup ne 'all') {
                    512: 	    @getgroup=($getgroup);
                    513: 	}
                    514:     } else {
                    515: 	@getgroup=@{$getgroup};
                    516:     }
                    517:     if (grep(/^all$/,@getgroup)) { undef(@getgroup); }
1.291     albertel  518: 
1.449     banghart  519:     my ($classlist,$keylist)=&Apache::loncoursedata::get_classlist();
1.49      albertel  520:     # Bail out if we were unable to get the classlist
1.56      matthew   521:     return if (! defined($classlist));
1.449     banghart  522:     &Apache::loncoursedata::get_group_memberships($classlist,$keylist);
1.56      matthew   523:     #
                    524:     my %sections;
                    525:     my %fullnames;
1.205     matthew   526:     foreach my $student (keys(%$classlist)) {
                    527:         my $end      = 
                    528:             $classlist->{$student}->[&Apache::loncoursedata::CL_END()];
                    529:         my $start    = 
                    530:             $classlist->{$student}->[&Apache::loncoursedata::CL_START()];
                    531:         my $id       = 
                    532:             $classlist->{$student}->[&Apache::loncoursedata::CL_ID()];
                    533:         my $section  = 
                    534:             $classlist->{$student}->[&Apache::loncoursedata::CL_SECTION()];
                    535:         my $fullname = 
                    536:             $classlist->{$student}->[&Apache::loncoursedata::CL_FULLNAME()];
                    537:         my $status   = 
                    538:             $classlist->{$student}->[&Apache::loncoursedata::CL_STATUS()];
1.449     banghart  539:         my $group   = 
                    540:             $classlist->{$student}->[&Apache::loncoursedata::CL_GROUP()];
1.76      ng        541: 	# filter students according to status selected
1.442     banghart  542: 	if ($filterlist && (!($stu_status =~ /Any/))) {
                    543: 	    if (!($stu_status =~ $status)) {
1.450     banghart  544: 		delete($classlist->{$student});
1.76      ng        545: 		next;
                    546: 	    }
                    547: 	}
1.450     banghart  548: 	# filter students according to groups selected
1.453     banghart  549: 	my @stu_groups = split(/,/,$group);
1.450     banghart  550: 	if (@getgroup) {
                    551: 	    my $exclude = 1;
1.454     banghart  552: 	    foreach my $grp (@getgroup) {
                    553: 	        foreach my $stu_group (@stu_groups) {
1.453     banghart  554: 	            if ($stu_group eq $grp) {
                    555: 	                $exclude = 0;
                    556:     	            } 
1.450     banghart  557: 	        }
1.453     banghart  558:     	        if (($grp eq 'none') && !$group) {
                    559:         	        $exclude = 0;
                    560:         	}
1.450     banghart  561: 	    }
                    562: 	    if ($exclude) {
                    563: 	        delete($classlist->{$student});
                    564: 	    }
                    565: 	}
1.205     matthew   566: 	$section = ($section ne '' ? $section : 'none');
1.106     albertel  567: 	if (&canview($section)) {
1.291     albertel  568: 	    if (!@getsec || grep(/^\Q$section\E$/,@getsec)) {
1.103     albertel  569: 		$sections{$section}++;
1.450     banghart  570: 		if ($classlist->{$student}) {
                    571: 		    $fullnames{$student}=$fullname;
                    572: 		}
1.103     albertel  573: 	    } else {
1.205     matthew   574: 		delete($classlist->{$student});
1.103     albertel  575: 	    }
                    576: 	} else {
1.205     matthew   577: 	    delete($classlist->{$student});
1.103     albertel  578: 	}
1.44      ng        579:     }
                    580:     my %seen = ();
1.56      matthew   581:     my @sections = sort(keys(%sections));
                    582:     return ($classlist,\@sections,\%fullnames);
1.44      ng        583: }
                    584: 
1.103     albertel  585: sub canmodify {
                    586:     my ($sec)=@_;
                    587:     if ($perm{'mgr'}) {
                    588: 	if (!defined($perm{'mgr_section'})) {
                    589: 	    # can modify whole class
                    590: 	    return 1;
                    591: 	} else {
                    592: 	    if ($sec eq $perm{'mgr_section'}) {
                    593: 		#can modify the requested section
                    594: 		return 1;
                    595: 	    } else {
                    596: 		# can't modify the request section
                    597: 		return 0;
                    598: 	    }
                    599: 	}
                    600:     }
                    601:     #can't modify
                    602:     return 0;
                    603: }
                    604: 
                    605: sub canview {
                    606:     my ($sec)=@_;
                    607:     if ($perm{'vgr'}) {
                    608: 	if (!defined($perm{'vgr_section'})) {
                    609: 	    # can modify whole class
                    610: 	    return 1;
                    611: 	} else {
                    612: 	    if ($sec eq $perm{'vgr_section'}) {
                    613: 		#can modify the requested section
                    614: 		return 1;
                    615: 	    } else {
                    616: 		# can't modify the request section
                    617: 		return 0;
                    618: 	    }
                    619: 	}
                    620:     }
                    621:     #can't modify
                    622:     return 0;
                    623: }
                    624: 
1.44      ng        625: #--- Retrieve the grade status of a student for all the parts
                    626: sub student_gradeStatus {
1.324     albertel  627:     my ($symb,$udom,$uname,$partlist) = @_;
1.257     albertel  628:     my %record     = &Apache::lonnet::restore($symb,$env{'request.course.id'},$udom,$uname);
1.44      ng        629:     my %partstatus = ();
                    630:     foreach (@$partlist) {
1.128     ng        631: 	my ($status,undef)   = split(/_/,$record{"resource.$_.solved"},2);
1.44      ng        632: 	$status              = 'nothing' if ($status eq '');
                    633: 	$partstatus{$_}      = $status;
                    634: 	my $subkey           = "resource.$_.submitted_by";
                    635: 	$partstatus{$subkey} = $record{$subkey} if ($record{$subkey} ne '');
                    636:     }
                    637:     return %partstatus;
                    638: }
                    639: 
1.45      ng        640: # hidden form and javascript that calls the form
                    641: # Use by verifyscript and viewgrades
                    642: # Shows a student's view of problem and submission
                    643: sub jscriptNform {
1.324     albertel  644:     my ($symb) = @_;
1.442     banghart  645:     my $stu_status = join(':',&Apache::loncommon::get_env_multiple('form.Status'));
1.45      ng        646:     my $jscript='<script type="text/javascript" language="javascript">'."\n".
                    647: 	'    function viewOneStudent(user,domain) {'."\n".
                    648: 	'	document.onestudent.student.value = user;'."\n".
                    649: 	'	document.onestudent.userdom.value = domain;'."\n".
                    650: 	'	document.onestudent.submit();'."\n".
                    651: 	'    }'."\n".
                    652: 	'</script>'."\n";
                    653:     $jscript.= '<form action="/adm/grades" method="post" name="onestudent">'."\n".
1.418     albertel  654: 	'<input type="hidden" name="symb"    value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
1.257     albertel  655: 	'<input type="hidden" name="saveState" value="'.$env{'form.saveState'}.'" />'."\n".
                    656: 	'<input type="hidden" name="probTitle" value="'.$env{'form.probTitle'}.'" />'."\n".
1.442     banghart  657: 	'<input type="hidden" name="Status"  value="'.$stu_status.'" />'."\n".
1.45      ng        658: 	'<input type="hidden" name="command" value="submission" />'."\n".
                    659: 	'<input type="hidden" name="student" value="" />'."\n".
                    660: 	'<input type="hidden" name="userdom" value="" />'."\n".
                    661: 	'</form>'."\n";
                    662:     return $jscript;
                    663: }
1.39      ng        664: 
1.447     foxr      665: 
                    666: 
1.315     bowersj2  667: # Given the score (as a number [0-1] and the weight) what is the final
                    668: # point value? This function will round to the nearest tenth, third,
                    669: # or quarter if one of those is within the tolerance of .00001.
1.316     albertel  670: sub compute_points {
1.315     bowersj2  671:     my ($score, $weight) = @_;
                    672:     
                    673:     my $tolerance = .00001;
                    674:     my $points = $score * $weight;
                    675: 
                    676:     # Check for nearness to 1/x.
                    677:     my $check_for_nearness = sub {
                    678:         my ($factor) = @_;
                    679:         my $num = ($points * $factor) + $tolerance;
                    680:         my $floored_num = floor($num);
1.316     albertel  681:         if ($num - $floored_num < 2 * $tolerance * $factor) {
1.315     bowersj2  682:             return $floored_num / $factor;
                    683:         }
                    684:         return $points;
                    685:     };
                    686: 
                    687:     $points = $check_for_nearness->(10);
                    688:     $points = $check_for_nearness->(3);
                    689:     $points = $check_for_nearness->(4);
                    690:     
                    691:     return $points;
                    692: }
                    693: 
1.44      ng        694: #------------------ End of general use routines --------------------
1.87      www       695: 
                    696: #
                    697: # Find most similar essay
                    698: #
                    699: 
                    700: sub most_similar {
1.426     albertel  701:     my ($uname,$udom,$uessay,$old_essays)=@_;
1.87      www       702: 
                    703: # ignore spaces and punctuation
                    704: 
                    705:     $uessay=~s/\W+/ /gs;
                    706: 
1.282     www       707: # ignore empty submissions (occuring when only files are sent)
                    708: 
                    709:     unless ($uessay=~/\w+/) { return ''; }
                    710: 
1.87      www       711: # these will be returned. Do not care if not at least 50 percent similar
1.88      www       712:     my $limit=0.6;
1.87      www       713:     my $sname='';
                    714:     my $sdom='';
                    715:     my $scrsid='';
                    716:     my $sessay='';
                    717: # go through all essays ...
1.426     albertel  718:     foreach my $tkey (keys(%$old_essays)) {
                    719: 	my ($tname,$tdom,$tcrsid)=map {&unescape($_)} (split(/\./,$tkey));
1.87      www       720: # ... except the same student
1.426     albertel  721:         next if (($tname eq $uname) && ($tdom eq $udom));
                    722: 	my $tessay=$old_essays->{$tkey};
                    723: 	$tessay=~s/\W+/ /gs;
1.87      www       724: # String similarity gives up if not even limit
1.426     albertel  725: 	my $tsimilar=&String::Similarity::similarity($uessay,$tessay,$limit);
1.87      www       726: # Found one
1.426     albertel  727: 	if ($tsimilar>$limit) {
                    728: 	    $limit=$tsimilar;
                    729: 	    $sname=$tname;
                    730: 	    $sdom=$tdom;
                    731: 	    $scrsid=$tcrsid;
                    732: 	    $sessay=$old_essays->{$tkey};
                    733: 	}
1.87      www       734:     }
1.88      www       735:     if ($limit>0.6) {
1.87      www       736:        return ($sname,$sdom,$scrsid,$sessay,$limit);
                    737:     } else {
                    738:        return ('','','','',0);
                    739:     }
                    740: }
                    741: 
1.44      ng        742: #-------------------------------------------------------------------
                    743: 
                    744: #------------------------------------ Receipt Verification Routines
1.45      ng        745: #
1.44      ng        746: #--- Check whether a receipt number is valid.---
                    747: sub verifyreceipt {
                    748:     my $request  = shift;
                    749: 
1.257     albertel  750:     my $courseid = $env{'request.course.id'};
1.184     www       751:     my $receipt  = &Apache::lonnet::recprefix($courseid).'-'.
1.257     albertel  752: 	$env{'form.receipt'};
1.44      ng        753:     $receipt     =~ s/[^\-\d]//g;
1.378     albertel  754:     my ($symb)   = &get_symb($request);
1.44      ng        755: 
1.487     albertel  756:     my $title.=
                    757: 	'<h3><span class="LC_info">'.
1.553     biermanm  758: 	&mt('Verifying  Receipt No. [_1]',$receipt).
1.487     albertel  759: 	'</span></h3>'."\n".
                    760: 	'<h4>'.&mt('<b>Resource: </b>[_1]',$env{'form.probTitle'}).
                    761: 	'</h4>'."\n";
1.44      ng        762: 
                    763:     my ($string,$contents,$matches) = ('','',0);
1.56      matthew   764:     my (undef,undef,$fullname) = &getclasslist('all','0');
1.177     albertel  765:     
                    766:     my $receiptparts=0;
1.390     albertel  767:     if ($env{"course.$courseid.receiptalg"} eq 'receipt2' ||
                    768: 	$env{"course.$courseid.receiptalg"} eq 'receipt3') { $receiptparts=1; }
1.177     albertel  769:     my $parts=['0'];
1.324     albertel  770:     if ($receiptparts) { ($parts)=&response_type($symb); }
1.486     albertel  771:     
                    772:     my $header = 
                    773: 	&Apache::loncommon::start_data_table().
                    774: 	&Apache::loncommon::start_data_table_header_row().
1.487     albertel  775: 	'<th>&nbsp;'.&mt('Fullname').'&nbsp;</th>'."\n".
                    776: 	'<th>&nbsp;'.&mt('Username').'&nbsp;</th>'."\n".
                    777: 	'<th>&nbsp;'.&mt('Domain').'&nbsp;</th>';
1.486     albertel  778:     if ($receiptparts) {
1.487     albertel  779: 	$header.='<th>&nbsp;'.&mt('Problem Part').'&nbsp;</th>';
1.486     albertel  780:     }
                    781:     $header.=
                    782: 	&Apache::loncommon::end_data_table_header_row();
                    783: 
1.294     albertel  784:     foreach (sort 
                    785: 	     {
                    786: 		 if (lc($$fullname{$a}) ne lc($$fullname{$b})) {
                    787: 		     return (lc($$fullname{$a}) cmp lc($$fullname{$b}));
                    788: 		 }
                    789: 		 return $a cmp $b;
                    790: 	     } (keys(%$fullname))) {
1.44      ng        791: 	my ($uname,$udom)=split(/\:/);
1.177     albertel  792: 	foreach my $part (@$parts) {
                    793: 	    if ($receipt eq &Apache::lonnet::ireceipt($uname,$udom,$courseid,$symb,$part)) {
1.486     albertel  794: 		$contents.=
                    795: 		    &Apache::loncommon::start_data_table_row().
                    796: 		    '<td>&nbsp;'."\n".
1.177     albertel  797: 		    '<a href="javascript:viewOneStudent(\''.$uname.'\',\''.$udom.
1.417     albertel  798: 		    '\');" target="_self">'.$$fullname{$_}.'</a>&nbsp;</td>'."\n".
1.177     albertel  799: 		    '<td>&nbsp;'.$uname.'&nbsp;</td>'.
                    800: 		    '<td>&nbsp;'.$udom.'&nbsp;</td>';
                    801: 		if ($receiptparts) {
                    802: 		    $contents.='<td>&nbsp;'.$part.'&nbsp;</td>';
                    803: 		}
1.486     albertel  804: 		$contents.= 
                    805: 		    &Apache::loncommon::end_data_table_row()."\n";
1.177     albertel  806: 		
                    807: 		$matches++;
                    808: 	    }
1.44      ng        809: 	}
                    810:     }
                    811:     if ($matches == 0) {
1.487     albertel  812: 	$string = $title.&mt('No match found for the above receipt.');
1.44      ng        813:     } else {
1.324     albertel  814: 	$string = &jscriptNform($symb).$title.
1.487     albertel  815: 	    '<p>'.
                    816: 	    &mt('The above receipt matches the following [numerate,_1,student].',$matches).
                    817: 	    '</p>'.
1.486     albertel  818: 	    $header.
                    819: 	    $contents.
                    820: 	    &Apache::loncommon::end_data_table()."\n";
1.44      ng        821:     }
1.324     albertel  822:     return $string.&show_grading_menu_form($symb);
1.44      ng        823: }
                    824: 
                    825: #--- This is called by a number of programs.
                    826: #--- Called from the Grading Menu - View/Grade an individual student
                    827: #--- Also called directly when one clicks on the subm button 
                    828: #    on the problem page.
1.30      ng        829: sub listStudents {
1.41      ng        830:     my ($request) = shift;
1.49      albertel  831: 
1.324     albertel  832:     my ($symb) = &get_symb($request);
1.257     albertel  833:     my $cdom      = $env{"course.$env{'request.course.id'}.domain"};
                    834:     my $cnum      = $env{"course.$env{'request.course.id'}.num"};
                    835:     my $getsec    = $env{'form.section'} eq '' ? 'all' : $env{'form.section'};
1.449     banghart  836:     my $getgroup  = $env{'form.group'} eq '' ? 'all' : $env{'form.group'};
1.257     albertel  837:     my $submitonly= $env{'form.submitonly'} eq '' ? 'all' : $env{'form.submitonly'};
1.548     bisitz    838:     my $viewgrade = $env{'form.showgrading'} eq 'yes' ? 'View/Grade/Regrade' : 'View';
1.257     albertel  839:     $env{'form.probTitle'} = $env{'form.probTitle'} eq '' ? 
                    840: 	&Apache::lonnet::gettitle($symb) : $env{'form.probTitle'};
1.49      albertel  841: 
1.548     bisitz    842:     my $result='<h3><span class="LC_info">&nbsp;'
                    843: 	.&mt("$viewgrade Submissions for a Student or a Group of Students")
1.485     albertel  844: 	.'</span></h3>';
1.118     ng        845: 
1.324     albertel  846:     my ($table,undef,$hdgrade,$partlist,$handgrade) = &showResourceInfo($symb,$env{'form.probTitle'},($env{'form.showgrading'} eq 'yes'));
1.49      albertel  847: 
1.559     raeburn   848:     my %lt = &Apache::lonlocal::texthash (
                    849: 		'multiple' => 'Please select a student or group of students before clicking on the Next button.',
                    850: 		'single'   => 'Please select the student before clicking on the Next button.',
                    851: 	     );
1.45      ng        852:     $request->print(<<LISTJAVASCRIPT);
                    853: <script type="text/javascript" language="javascript">
1.110     ng        854:     function checkSelect(checkBox) {
                    855: 	var ctr=0;
                    856: 	var sense="";
                    857: 	if (checkBox.length > 1) {
                    858: 	    for (var i=0; i<checkBox.length; i++) {
                    859: 		if (checkBox[i].checked) {
                    860: 		    ctr++;
                    861: 		}
                    862: 	    }
1.485     albertel  863: 	    sense = '$lt{'multiple'}';
1.110     ng        864: 	} else {
                    865: 	    if (checkBox.checked) {
                    866: 		ctr = 1;
                    867: 	    }
1.485     albertel  868: 	    sense = '$lt{'single'}';
1.110     ng        869: 	}
                    870: 	if (ctr == 0) {
1.485     albertel  871: 	    alert(sense);
1.110     ng        872: 	    return false;
                    873: 	}
                    874: 	document.gradesub.submit();
                    875:     }
                    876: 
                    877:     function reLoadList(formname) {
1.112     ng        878: 	if (formname.saveStatusOld.value == pullDownSelection(formname.Status)) {return;}
1.110     ng        879: 	formname.command.value = 'submission';
                    880: 	formname.submit();
                    881:     }
1.45      ng        882: </script>
                    883: LISTJAVASCRIPT
                    884: 
1.118     ng        885:     &commonJSfunctions($request);
1.41      ng        886:     $request->print($result);
1.39      ng        887: 
1.401     albertel  888:     my $checkhdgrade = ($env{'form.handgrade'} eq 'yes' && scalar(@$partlist) > 1 ) ? 'checked="checked"' : '';
                    889:     my $checklastsub = $checkhdgrade eq '' ? 'checked="checked"' : '';
1.154     albertel  890:     my $gradeTable='<form action="/adm/grades" method="post" name="gradesub">'.
1.485     albertel  891: 	"\n".$table;
                    892: 	
1.561     bisitz    893:     $gradeTable .= &Apache::lonhtmlcommon::start_pick_box();
                    894:     $gradeTable .= &Apache::lonhtmlcommon::row_title(&mt('View Problem Text'))
                    895:                   .'<label><input type="radio" name="vProb" value="no" checked="checked" /> '.&mt('no').' </label>'."\n"
                    896:                   .'<label><input type="radio" name="vProb" value="yes" /> '.&mt('one student').' </label>'."\n"
                    897:                   .'<label><input type="radio" name="vProb" value="all" /> '.&mt('all students').' </label><br />'."\n"
                    898:                   .&Apache::lonhtmlcommon::row_closure();
                    899:     $gradeTable .= &Apache::lonhtmlcommon::row_title(&mt('View Answer'))
                    900:                   .'<label><input type="radio" name="vAns" value="no"  /> '.&mt('no').' </label>'."\n"
                    901:                   .'<label><input type="radio" name="vAns" value="yes" /> '.&mt('one student').' </label>'."\n"
                    902:                   .'<label><input type="radio" name="vAns" value="all" checked="checked" /> '.&mt('all students').' </label><br />'."\n"
                    903:                   .&Apache::lonhtmlcommon::row_closure();
1.485     albertel  904: 
                    905:     my $submission_options;
1.257     albertel  906:     if ($env{'form.handgrade'} eq 'yes' && scalar(@$partlist) > 1) {
1.485     albertel  907: 	$submission_options.=
                    908: 	    '<label><input type="radio" name="lastSub" value="hdgrade" '.$checkhdgrade.' /> '.&mt('essay part only').' </label>'."\n";
1.49      albertel  909:     }
1.442     banghart  910:     my $stu_status = join(':',&Apache::loncommon::get_env_multiple('form.Status'));
                    911:     my $saveStatus = $stu_status eq '' ? 'Active' : $stu_status;
1.257     albertel  912:     $env{'form.Status'} = $saveStatus;
1.485     albertel  913:     $submission_options.=
                    914: 	'<label><input type="radio" name="lastSub" value="lastonly" '.$checklastsub.' /> '.&mt('last submission only').' </label>'."\n".
                    915: 	'<label><input type="radio" name="lastSub" value="last" /> '.&mt('last submission &amp; parts info').' </label>'."\n".
                    916: 	'<label><input type="radio" name="lastSub" value="datesub" /> '.&mt('by dates and submissions').' </label>'."\n".
                    917: 	'<label><input type="radio" name="lastSub" value="all" /> '.&mt('all details').'</label>';
1.561     bisitz    918:     $gradeTable .= &Apache::lonhtmlcommon::row_title(&mt('Submissions'))
                    919:                   .$submission_options
                    920:                   .&Apache::lonhtmlcommon::row_closure();
                    921: 
                    922:     $gradeTable .= &Apache::lonhtmlcommon::row_title(&mt('Grading Increments'))
                    923:                   .'<select name="increment">'
                    924:                   .'<option value="1">'.&mt('Whole Points').'</option>'
                    925:                   .'<option value=".5">'.&mt('Half Points').'</option>'
                    926:                   .'<option value=".25">'.&mt('Quarter Points').'</option>'
                    927:                   .'<option value=".1">'.&mt('Tenths of a Point').'</option>'
                    928:                   .'</select>'
                    929:                   .&Apache::lonhtmlcommon::row_closure();
1.485     albertel  930: 
                    931:     $gradeTable .= 
1.432     banghart  932:         &build_section_inputs().
1.45      ng        933: 	'<input type="hidden" name="submitonly"  value="'.$submitonly.'" />'."\n".
1.257     albertel  934: 	'<input type="hidden" name="handgrade"   value="'.$env{'form.handgrade'}.'" /><br />'."\n".
                    935: 	'<input type="hidden" name="showgrading" value="'.$env{'form.showgrading'}.'" /><br />'."\n".
                    936: 	'<input type="hidden" name="saveState"   value="'.$env{'form.saveState'}.'" />'."\n".
                    937: 	'<input type="hidden" name="probTitle"   value="'.$env{'form.probTitle'}.'" />'."\n".
1.418     albertel  938: 	'<input type="hidden" name="symb" value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
1.110     ng        939: 	'<input type="hidden" name="saveStatusOld" value="'.$saveStatus.'" />'."\n";
                    940: 
1.257     albertel  941:     if (exists($env{'form.gradingMenu'}) && exists($env{'form.Status'})) {
1.561     bisitz    942: 	$gradeTable .= '<input type="hidden" name="Status" value="'.$stu_status.'" />'."\n";
1.124     ng        943:     } else {
1.561     bisitz    944:         $gradeTable .= &Apache::lonhtmlcommon::row_title(&mt('Student Status'))
                    945:                       .&Apache::lonhtmlcommon::StatusOptions(
                    946:                            $saveStatus,undef,1,'javascript:reLoadList(this.form);')
                    947:                       .&Apache::lonhtmlcommon::row_closure();
1.124     ng        948:     }
1.112     ng        949: 
1.561     bisitz    950:     $gradeTable .= &Apache::lonhtmlcommon::row_title(&mt('Check For Plagiarism'))
                    951:                   .'<input type="checkbox" name="checkPlag" checked="checked" />'
                    952:                   .&Apache::lonhtmlcommon::row_closure(1)
                    953:                   .&Apache::lonhtmlcommon::end_pick_box();
                    954: 
                    955:     $gradeTable .= '<p>'
                    956:                   .&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"
                    957:                   .'<input type="hidden" name="command" value="processGroup" />'
                    958:                   .'</p>';
1.249     albertel  959: 
                    960: # checkall buttons
                    961:     $gradeTable.=&check_script('gradesub', 'stuinfo');
1.110     ng        962:     $gradeTable.='<input type="button" '."\n".
1.45      ng        963: 	'onClick="javascript:checkSelect(this.form.stuinfo);" '."\n".
1.539     riegler   964: 	'value="'.&mt('Next').' &rarr;" /> <br />'."\n";
1.249     albertel  965:     $gradeTable.=&check_buttons();
1.450     banghart  966:     my ($classlist, undef, $fullname) = &getclasslist($getsec,'1',$getgroup);
1.474     albertel  967:     $gradeTable.= &Apache::loncommon::start_data_table().
                    968: 	&Apache::loncommon::start_data_table_header_row();
1.110     ng        969:     my $loop = 0;
                    970:     while ($loop < 2) {
1.485     albertel  971: 	$gradeTable.='<th>'.&mt('No.').'</th><th>'.&mt('Select').'</th>'.
                    972: 	    '<th>'.&nameUserString('header').'&nbsp;'.&mt('Section/Group').'</th>';
1.301     albertel  973: 	if ($env{'form.showgrading'} eq 'yes' 
                    974: 	    && $submitonly ne 'queued'
                    975: 	    && $submitonly ne 'all') {
1.485     albertel  976: 	    foreach my $part (sort(@$partlist)) {
                    977: 		my $display_part=
                    978: 		    &get_display_part((split(/_/,$part))[0],$symb);
                    979: 		$gradeTable.=
                    980: 		    '<th>'.&mt('Part: [_1] Status',$display_part).'</th>';
1.110     ng        981: 	    }
1.301     albertel  982: 	} elsif ($submitonly eq 'queued') {
1.474     albertel  983: 	    $gradeTable.='<th>'.&mt('Queue Status').'&nbsp;</th>';
1.110     ng        984: 	}
                    985: 	$loop++;
1.126     ng        986: #	$gradeTable.='<td></td>' if ($loop%2 ==1);
1.41      ng        987:     }
1.474     albertel  988:     $gradeTable.=&Apache::loncommon::end_data_table_header_row()."\n";
1.41      ng        989: 
1.45      ng        990:     my $ctr = 0;
1.294     albertel  991:     foreach my $student (sort 
                    992: 			 {
                    993: 			     if (lc($$fullname{$a}) ne lc($$fullname{$b})) {
                    994: 				 return (lc($$fullname{$a}) cmp lc($$fullname{$b}));
                    995: 			     }
                    996: 			     return $a cmp $b;
                    997: 			 }
                    998: 			 (keys(%$fullname))) {
1.41      ng        999: 	my ($uname,$udom) = split(/:/,$student);
1.301     albertel 1000: 
1.110     ng       1001: 	my %status = ();
1.301     albertel 1002: 
                   1003: 	if ($submitonly eq 'queued') {
                   1004: 	    my %queue_status = 
                   1005: 		&Apache::bridgetask::get_student_status($symb,$cdom,$cnum,
                   1006: 							$udom,$uname);
                   1007: 	    next if (!defined($queue_status{'gradingqueue'}));
                   1008: 	    $status{'gradingqueue'} = $queue_status{'gradingqueue'};
                   1009: 	}
                   1010: 
                   1011: 	if ($env{'form.showgrading'} eq 'yes' 
                   1012: 	    && $submitonly ne 'queued'
                   1013: 	    && $submitonly ne 'all') {
1.324     albertel 1014: 	    (%status) =&student_gradeStatus($symb,$udom,$uname,$partlist);
1.145     albertel 1015: 	    my $submitted = 0;
1.164     albertel 1016: 	    my $graded = 0;
1.248     albertel 1017: 	    my $incorrect = 0;
1.110     ng       1018: 	    foreach (keys(%status)) {
1.145     albertel 1019: 		$submitted = 1 if ($status{$_} ne 'nothing');
1.248     albertel 1020: 		$graded = 1 if ($status{$_} =~ /^ungraded/);
                   1021: 		$incorrect = 1 if ($status{$_} =~ /^incorrect/);
                   1022: 		
1.110     ng       1023: 		my ($foo,$partid,$foo1) = split(/\./,$_);
                   1024: 		if ($status{'resource.'.$partid.'.submitted_by'} ne '') {
1.145     albertel 1025: 		    $submitted = 0;
1.150     albertel 1026: 		    my ($part)=split(/\./,$partid);
1.110     ng       1027: 		    $gradeTable.='<input type="hidden" name="'.
1.150     albertel 1028: 			$student.':'.$part.':submitted_by" value="'.
1.110     ng       1029: 			$status{'resource.'.$partid.'.submitted_by'}.'" />';
                   1030: 		}
1.41      ng       1031: 	    }
1.248     albertel 1032: 	    
1.156     albertel 1033: 	    next if (!$submitted && ($submitonly eq 'yes' ||
                   1034: 				     $submitonly eq 'incorrect' ||
                   1035: 				     $submitonly eq 'graded'));
1.248     albertel 1036: 	    next if (!$graded && ($submitonly eq 'graded'));
                   1037: 	    next if (!$incorrect && $submitonly eq 'incorrect');
1.41      ng       1038: 	}
1.34      ng       1039: 
1.45      ng       1040: 	$ctr++;
1.249     albertel 1041: 	my $section = $classlist->{$student}->[&Apache::loncoursedata::CL_SECTION()];
1.452     banghart 1042:         my $group = $classlist->{$student}->[&Apache::loncoursedata::CL_GROUP()];
1.104     albertel 1043: 	if ( $perm{'vgr'} eq 'F' ) {
1.474     albertel 1044: 	    if ($ctr%2 ==1) {
                   1045: 		$gradeTable.= &Apache::loncommon::start_data_table_row();
                   1046: 	    }
1.126     ng       1047: 	    $gradeTable.='<td align="right">'.$ctr.'&nbsp;</td>'.
1.563     bisitz   1048:                '<td align="center"><label><input type="checkbox" name="stuinfo" value="'.
1.249     albertel 1049:                $student.':'.$$fullname{$student}.':::SECTION'.$section.
                   1050: 	       ')&nbsp;" />&nbsp;&nbsp;</label></td>'."\n".'<td>'.
                   1051: 	       &nameUserString(undef,$$fullname{$student},$uname,$udom).
1.474     albertel 1052: 	       '&nbsp;'.$section.($group ne '' ?'/'.$group:'').'</td>'."\n";
1.110     ng       1053: 
1.257     albertel 1054: 	    if ($env{'form.showgrading'} eq 'yes' && $submitonly ne 'all') {
1.524     raeburn  1055: 		foreach (sort(keys(%status))) {
1.485     albertel 1056: 		    next if ($_ =~ /^resource.*?submitted_by$/);
                   1057: 		    $gradeTable.='<td align="center">&nbsp;'.&mt($status{$_}).'&nbsp;</td>'."\n";
1.110     ng       1058: 		}
1.41      ng       1059: 	    }
1.126     ng       1060: #	    $gradeTable.='<td></td>' if ($ctr%2 ==1);
1.474     albertel 1061: 	    if ($ctr%2 ==0) {
                   1062: 		$gradeTable.=&Apache::loncommon::end_data_table_row()."\n";
                   1063: 	    }
1.41      ng       1064: 	}
                   1065:     }
1.110     ng       1066:     if ($ctr%2 ==1) {
1.126     ng       1067: 	$gradeTable.='<td>&nbsp;</td><td>&nbsp;</td><td>&nbsp;</td>';
1.301     albertel 1068: 	    if ($env{'form.showgrading'} eq 'yes' 
                   1069: 		&& $submitonly ne 'queued'
                   1070: 		&& $submitonly ne 'all') {
1.110     ng       1071: 		foreach (@$partlist) {
                   1072: 		    $gradeTable.='<td>&nbsp;</td>';
                   1073: 		}
1.301     albertel 1074: 	    } elsif ($submitonly eq 'queued') {
                   1075: 		$gradeTable.='<td>&nbsp;</td>';
1.110     ng       1076: 	    }
1.474     albertel 1077: 	$gradeTable.=&Apache::loncommon::end_data_table_row();
1.110     ng       1078:     }
                   1079: 
1.474     albertel 1080:     $gradeTable.=&Apache::loncommon::end_data_table()."\n".
1.45      ng       1081: 	'<input type="button" '.
                   1082: 	'onClick="javascript:checkSelect(this.form.stuinfo);" '.
1.539     riegler  1083: 	'value="'.&mt('Next').' &rarr;" /></form>'."\n";
1.45      ng       1084:     if ($ctr == 0) {
1.96      albertel 1085: 	my $num_students=(scalar(keys(%$fullname)));
                   1086: 	if ($num_students eq 0) {
1.485     albertel 1087: 	    $gradeTable='<br />&nbsp;<span class="LC_warning">'.&mt('There are no students currently enrolled.').'</span>';
1.96      albertel 1088: 	} else {
1.171     albertel 1089: 	    my $submissions='submissions';
                   1090: 	    if ($submitonly eq 'incorrect') { $submissions = 'incorrect submissions'; }
                   1091: 	    if ($submitonly eq 'graded'   ) { $submissions = 'ungraded submissions'; }
1.301     albertel 1092: 	    if ($submitonly eq 'queued'   ) { $submissions = 'queued submissions'; }
1.398     albertel 1093: 	    $gradeTable='<br />&nbsp;<span class="LC_warning">'.
1.485     albertel 1094: 		&mt('No '.$submissions.' found for this resource for any students. ([_1] students checked for '.$submissions.')',
                   1095: 		    $num_students).
                   1096: 		'</span><br />';
1.96      albertel 1097: 	}
1.46      ng       1098:     } elsif ($ctr == 1) {
1.474     albertel 1099: 	$gradeTable =~ s/type="checkbox"/type="checkbox" checked="checked"/;
1.45      ng       1100:     }
1.324     albertel 1101:     $gradeTable.=&show_grading_menu_form($symb);
1.45      ng       1102:     $request->print($gradeTable);
1.44      ng       1103:     return '';
1.10      ng       1104: }
                   1105: 
1.44      ng       1106: #---- Called from the listStudents routine
1.249     albertel 1107: 
                   1108: sub check_script {
                   1109:     my ($form, $type)=@_;
                   1110:     my $chkallscript='<script type="text/javascript">
                   1111:     function checkall() {
                   1112:         for (i=0; i<document.forms.'.$form.'.elements.length; i++) {
                   1113:             ele = document.forms.'.$form.'.elements[i];
                   1114:             if (ele.name == "'.$type.'") {
                   1115:             document.forms.'.$form.'.elements[i].checked=true;
                   1116:                                        }
                   1117:         }
                   1118:     }
                   1119: 
                   1120:     function checksec() {
                   1121:         for (i=0; i<document.forms.'.$form.'.elements.length; i++) {
                   1122:             ele = document.forms.'.$form.'.elements[i];
                   1123:            string = document.forms.'.$form.'.chksec.value;
                   1124:            if
                   1125:           (ele.value.indexOf(":::SECTION"+string)>0) {
                   1126:               document.forms.'.$form.'.elements[i].checked=true;
                   1127:             }
                   1128:         }
                   1129:     }
                   1130: 
                   1131: 
                   1132:     function uncheckall() {
                   1133:         for (i=0; i<document.forms.'.$form.'.elements.length; i++) {
                   1134:             ele = document.forms.'.$form.'.elements[i];
                   1135:             if (ele.name == "'.$type.'") {
                   1136:             document.forms.'.$form.'.elements[i].checked=false;
                   1137:                                        }
                   1138:         }
                   1139:     }
                   1140: 
                   1141: </script>'."\n";
                   1142:     return $chkallscript;
                   1143: }
                   1144: 
                   1145: sub check_buttons {
1.485     albertel 1146:     my $buttons.='<input type="button" onclick="checkall()" value="'.&mt('Check All').'" />';
                   1147:     $buttons.='<input type="button" onclick="uncheckall()" value="'.&mt('Uncheck All').'" />&nbsp;';
                   1148:     $buttons.='<input type="button" onclick="checksec()" value="'.&mt('Check Section/Group').'" />';
1.249     albertel 1149:     $buttons.='<input type="text" size="5" name="chksec" />&nbsp;';
                   1150:     return $buttons;
                   1151: }
                   1152: 
1.44      ng       1153: #     Displays the submissions for one student or a group of students
1.34      ng       1154: sub processGroup {
1.41      ng       1155:     my ($request)  = shift;
                   1156:     my $ctr        = 0;
1.155     albertel 1157:     my @stuchecked = &Apache::loncommon::get_env_multiple('form.stuinfo');
1.41      ng       1158:     my $total      = scalar(@stuchecked)-1;
1.45      ng       1159: 
1.396     banghart 1160:     foreach my $student (@stuchecked) {
                   1161: 	my ($uname,$udom,$fullname) = split(/:/,$student);
1.257     albertel 1162: 	$env{'form.student'}        = $uname;
                   1163: 	$env{'form.userdom'}        = $udom;
                   1164: 	$env{'form.fullname'}       = $fullname;
1.41      ng       1165: 	&submission($request,$ctr,$total);
                   1166: 	$ctr++;
                   1167:     }
                   1168:     return '';
1.35      ng       1169: }
1.34      ng       1170: 
1.44      ng       1171: #------------------------------------------------------------------------------------
                   1172: #
                   1173: #-------------------------- Next few routines handles grading by student, essentially
                   1174: #                           handles essay response type problem/part
                   1175: #
                   1176: #--- Javascript to handle the submission page functionality ---
                   1177: sub sub_page_js {
                   1178:     my $request = shift;
1.539     riegler  1179: 	    my $alertmsg = &mt('A number equal or greater than 0 is expected. Entered value = ');
1.44      ng       1180:     $request->print(<<SUBJAVASCRIPT);
                   1181: <script type="text/javascript" language="javascript">
1.71      ng       1182:     function updateRadio(formname,id,weight) {
1.125     ng       1183: 	var gradeBox = formname["GD_BOX"+id];
                   1184: 	var radioButton = formname["RADVAL"+id];
                   1185: 	var oldpts = formname["oldpts"+id].value;
1.72      ng       1186: 	var pts = checkSolved(formname,id) == 'update' ? gradeBox.value : oldpts;
1.71      ng       1187: 	gradeBox.value = pts;
                   1188: 	var resetbox = false;
                   1189: 	if (isNaN(pts) || pts < 0) {
1.539     riegler  1190: 	    alert("$alertmsg"+pts);
1.71      ng       1191: 	    for (var i=0; i<radioButton.length; i++) {
                   1192: 		if (radioButton[i].checked) {
                   1193: 		    gradeBox.value = i;
                   1194: 		    resetbox = true;
                   1195: 		}
                   1196: 	    }
                   1197: 	    if (!resetbox) {
                   1198: 		formtextbox.value = "";
                   1199: 	    }
                   1200: 	    return;
1.44      ng       1201: 	}
1.71      ng       1202: 
                   1203: 	if (pts > weight) {
                   1204: 	    var resp = confirm("You entered a value ("+pts+
                   1205: 			       ") greater than the weight for the part. Accept?");
                   1206: 	    if (resp == false) {
1.125     ng       1207: 		gradeBox.value = oldpts;
1.71      ng       1208: 		return;
                   1209: 	    }
1.44      ng       1210: 	}
1.13      albertel 1211: 
1.71      ng       1212: 	for (var i=0; i<radioButton.length; i++) {
                   1213: 	    radioButton[i].checked=false;
                   1214: 	    if (pts == i && pts != "") {
                   1215: 		radioButton[i].checked=true;
                   1216: 	    }
                   1217: 	}
                   1218: 	updateSelect(formname,id);
1.125     ng       1219: 	formname["stores"+id].value = "0";
1.41      ng       1220:     }
1.5       albertel 1221: 
1.72      ng       1222:     function writeBox(formname,id,pts) {
1.125     ng       1223: 	var gradeBox = formname["GD_BOX"+id];
1.71      ng       1224: 	if (checkSolved(formname,id) == 'update') {
                   1225: 	    gradeBox.value = pts;
                   1226: 	} else {
1.125     ng       1227: 	    var oldpts = formname["oldpts"+id].value;
1.72      ng       1228: 	    gradeBox.value = oldpts;
1.125     ng       1229: 	    var radioButton = formname["RADVAL"+id];
1.71      ng       1230: 	    for (var i=0; i<radioButton.length; i++) {
                   1231: 		radioButton[i].checked=false;
1.72      ng       1232: 		if (i == oldpts) {
1.71      ng       1233: 		    radioButton[i].checked=true;
                   1234: 		}
                   1235: 	    }
1.41      ng       1236: 	}
1.125     ng       1237: 	formname["stores"+id].value = "0";
1.71      ng       1238: 	updateSelect(formname,id);
                   1239: 	return;
1.41      ng       1240:     }
1.44      ng       1241: 
1.71      ng       1242:     function clearRadBox(formname,id) {
                   1243: 	if (checkSolved(formname,id) == 'noupdate') {
                   1244: 	    updateSelect(formname,id);
                   1245: 	    return;
                   1246: 	}
1.125     ng       1247: 	gradeSelect = formname["GD_SEL"+id];
1.71      ng       1248: 	for (var i=0; i<gradeSelect.length; i++) {
                   1249: 	    if (gradeSelect[i].selected) {
                   1250: 		var selectx=i;
                   1251: 	    }
                   1252: 	}
1.125     ng       1253: 	var stores = formname["stores"+id];
1.71      ng       1254: 	if (selectx == stores.value) { return };
1.125     ng       1255: 	var gradeBox = formname["GD_BOX"+id];
1.71      ng       1256: 	gradeBox.value = "";
1.125     ng       1257: 	var radioButton = formname["RADVAL"+id];
1.71      ng       1258: 	for (var i=0; i<radioButton.length; i++) {
                   1259: 	    radioButton[i].checked=false;
                   1260: 	}
                   1261: 	stores.value = selectx;
                   1262:     }
1.5       albertel 1263: 
1.71      ng       1264:     function checkSolved(formname,id) {
1.125     ng       1265: 	if (formname["solved"+id].value == "correct_by_student" && formname.overRideScore.value == 'no') {
1.118     ng       1266: 	    var reply = confirm("This problem has been graded correct by the computer. Do you want to change the score?");
                   1267: 	    if (!reply) {return "noupdate";}
1.120     ng       1268: 	    formname.overRideScore.value = 'yes';
1.41      ng       1269: 	}
1.71      ng       1270: 	return "update";
1.13      albertel 1271:     }
1.71      ng       1272: 
                   1273:     function updateSelect(formname,id) {
1.125     ng       1274: 	formname["GD_SEL"+id][0].selected = true;
1.71      ng       1275: 	return;
1.41      ng       1276:     }
1.33      ng       1277: 
1.121     ng       1278: //=========== Check that a point is assigned for all the parts  ============
1.71      ng       1279:     function checksubmit(formname,val,total,parttot) {
1.121     ng       1280: 	formname.gradeOpt.value = val;
1.71      ng       1281: 	if (val == "Save & Next") {
                   1282: 	    for (i=0;i<=total;i++) {
                   1283: 		for (j=0;j<parttot;j++) {
1.125     ng       1284: 		    var partid = formname["partid"+i+"_"+j].value;
1.127     ng       1285: 		    if (formname["GD_SEL"+i+"_"+partid][0].selected) {
1.125     ng       1286: 			var points = formname["GD_BOX"+i+"_"+partid].value;
1.71      ng       1287: 			if (points == "") {
1.125     ng       1288: 			    var name = formname["name"+i].value;
1.129     ng       1289: 			    var studentID = (name != '' ? name : formname["unamedom"+i].value);
                   1290: 			    var resp = confirm("You did not assign a score for "+studentID+
                   1291: 					       ", part "+partid+". Continue?");
1.71      ng       1292: 			    if (resp == false) {
1.125     ng       1293: 				formname["GD_BOX"+i+"_"+partid].focus();
1.71      ng       1294: 				return false;
                   1295: 			    }
                   1296: 			}
                   1297: 		    }
                   1298: 		    
                   1299: 		}
                   1300: 	    }
                   1301: 	    
                   1302: 	}
1.121     ng       1303: 	if (val == "Grade Student") {
                   1304: 	    formname.showgrading.value = "yes";
                   1305: 	    if (formname.Status.value == "") {
                   1306: 		formname.Status.value = "Active";
                   1307: 	    }
                   1308: 	    formname.studentNo.value = total;
                   1309: 	}
1.120     ng       1310: 	formname.submit();
                   1311:     }
                   1312: 
1.71      ng       1313: //======= Check that a score is assigned for all the problems (page/sequence grading only) =========
                   1314:     function checkSubmitPage(formname,total) {
                   1315: 	noscore = new Array(100);
                   1316: 	var ptr = 0;
                   1317: 	for (i=1;i<total;i++) {
1.125     ng       1318: 	    var partid = formname["q_"+i].value;
1.127     ng       1319: 	    if (formname["GD_SEL"+i+"_"+partid][0].selected) {
1.125     ng       1320: 		var points = formname["GD_BOX"+i+"_"+partid].value;
                   1321: 		var status = formname["solved"+i+"_"+partid].value;
1.71      ng       1322: 		if (points == "" && status != "correct_by_student") {
                   1323: 		    noscore[ptr] = i;
                   1324: 		    ptr++;
                   1325: 		}
                   1326: 	    }
                   1327: 	}
                   1328: 	if (ptr != 0) {
                   1329: 	    var sense = ptr == 1 ? ": " : "s: ";
                   1330: 	    var prolist = "";
                   1331: 	    if (ptr == 1) {
                   1332: 		prolist = noscore[0];
                   1333: 	    } else {
                   1334: 		var i = 0;
                   1335: 		while (i < ptr-1) {
                   1336: 		    prolist += noscore[i]+", ";
                   1337: 		    i++;
                   1338: 		}
                   1339: 		prolist += "and "+noscore[i];
                   1340: 	    }
                   1341: 	    var resp = confirm("You did not assign any score for the following problem"+sense+prolist+". Continue?");
                   1342: 	    if (resp == false) {
                   1343: 		return false;
                   1344: 	    }
                   1345: 	}
1.45      ng       1346: 
1.71      ng       1347: 	formname.submit();
                   1348:     }
                   1349: </script>
                   1350: SUBJAVASCRIPT
                   1351: }
1.45      ng       1352: 
1.71      ng       1353: #--- javascript for essay type problem --
                   1354: sub sub_page_kw_js {
                   1355:     my $request = shift;
1.80      ng       1356:     my $iconpath = $request->dir_config('lonIconsURL');
1.118     ng       1357:     &commonJSfunctions($request);
1.350     albertel 1358: 
1.351     albertel 1359:     my $inner_js_msg_central=<<INNERJS;
1.350     albertel 1360:     <script text="text/javascript">
                   1361:     function checkInput() {
                   1362:       opener.document.SCORE.msgsub.value = opener.checkEntities(document.msgcenter.msgsub.value);
                   1363:       var nmsg   = opener.document.SCORE.savemsgN.value;
                   1364:       var usrctr = document.msgcenter.usrctr.value;
                   1365:       var newval = opener.document.SCORE["newmsg"+usrctr];
                   1366:       newval.value = opener.checkEntities(document.msgcenter.newmsg.value);
                   1367: 
                   1368:       var msgchk = "";
                   1369:       if (document.msgcenter.subchk.checked) {
                   1370:          msgchk = "msgsub,";
                   1371:       }
                   1372:       var includemsg = 0;
                   1373:       for (var i=1; i<=nmsg; i++) {
                   1374:           var opnmsg = opener.document.SCORE["savemsg"+i];
                   1375:           var frmmsg = document.msgcenter["msg"+i];
                   1376:           opnmsg.value = opener.checkEntities(frmmsg.value);
                   1377:           var showflg = opener.document.SCORE["shownOnce"+i];
                   1378:           showflg.value = "1";
                   1379:           var chkbox = document.msgcenter["msgn"+i];
                   1380:           if (chkbox.checked) {
                   1381:              msgchk += "savemsg"+i+",";
                   1382:              includemsg = 1;
                   1383:           }
                   1384:       }
                   1385:       if (document.msgcenter.newmsgchk.checked) {
                   1386:          msgchk += "newmsg"+usrctr;
                   1387:          includemsg = 1;
                   1388:       }
                   1389:       imgformname = opener.document.SCORE["mailicon"+usrctr];
                   1390:       imgformname.src = "$iconpath/"+((includemsg) ? "mailto.gif" : "mailbkgrd.gif");
                   1391:       var includemsg = opener.document.SCORE["includemsg"+usrctr];
                   1392:       includemsg.value = msgchk;
                   1393: 
                   1394:       self.close()
                   1395: 
                   1396:     }
                   1397:     </script>
                   1398: INNERJS
                   1399: 
1.351     albertel 1400:     my $inner_js_highlight_central=<<INNERJS;
                   1401:  <script type="text/javascript">
                   1402:     function updateChoice(flag) {
                   1403:       opener.document.SCORE.kwclr.value = opener.radioSelection(document.hlCenter.kwdclr);
                   1404:       opener.document.SCORE.kwsize.value = opener.radioSelection(document.hlCenter.kwdsize);
                   1405:       opener.document.SCORE.kwstyle.value = opener.radioSelection(document.hlCenter.kwdstyle);
                   1406:       opener.document.SCORE.refresh.value = "on";
                   1407:       if (opener.document.SCORE.keywords.value!=""){
                   1408:          opener.document.SCORE.submit();
                   1409:       }
                   1410:       self.close()
                   1411:     }
                   1412: </script>
                   1413: INNERJS
                   1414: 
                   1415:     my $start_page_msg_central = 
                   1416:         &Apache::loncommon::start_page('Message Central',$inner_js_msg_central,
                   1417: 				       {'js_ready'  => 1,
                   1418: 					'only_body' => 1,
                   1419: 					'bgcolor'   =>'#FFFFFF',});
                   1420:     my $end_page_msg_central = 
                   1421: 	&Apache::loncommon::end_page({'js_ready' => 1});
                   1422: 
                   1423: 
                   1424:     my $start_page_highlight_central = 
                   1425:         &Apache::loncommon::start_page('Highlight Central',
                   1426: 				       $inner_js_highlight_central,
1.350     albertel 1427: 				       {'js_ready'  => 1,
                   1428: 					'only_body' => 1,
                   1429: 					'bgcolor'   =>'#FFFFFF',});
1.351     albertel 1430:     my $end_page_highlight_central = 
1.350     albertel 1431: 	&Apache::loncommon::end_page({'js_ready' => 1});
                   1432: 
1.219     www      1433:     my $docopen=&Apache::lonhtmlcommon::javascript_docopen();
1.236     albertel 1434:     $docopen=~s/^document\.//;
1.539     riegler  1435:     my $alertmsg = &mt('Please select a word or group of words from document and then click this link.');
1.71      ng       1436:     $request->print(<<SUBJAVASCRIPT);
                   1437: <script type="text/javascript" language="javascript">
1.45      ng       1438: 
1.44      ng       1439: //===================== Show list of keywords ====================
1.122     ng       1440:   function keywords(formname) {
                   1441:     var nret = prompt("Keywords list, separated by a space. Add/delete to list if desired.",formname.keywords.value);
1.44      ng       1442:     if (nret==null) return;
1.122     ng       1443:     formname.keywords.value = nret;
1.44      ng       1444: 
1.122     ng       1445:     if (formname.keywords.value != "") {
1.128     ng       1446: 	formname.refresh.value = "on";
1.122     ng       1447: 	formname.submit();
1.44      ng       1448:     }
                   1449:     return;
                   1450:   }
                   1451: 
                   1452: //===================== Script to view submitted by ==================
                   1453:   function viewSubmitter(submitter) {
                   1454:     document.SCORE.refresh.value = "on";
                   1455:     document.SCORE.NCT.value = "1";
                   1456:     document.SCORE.unamedom0.value = submitter;
                   1457:     document.SCORE.submit();
                   1458:     return;
                   1459:   }
                   1460: 
                   1461: //===================== Script to add keyword(s) ==================
                   1462:   function getSel() {
                   1463:     if (document.getSelection) txt = document.getSelection();
                   1464:     else if (document.selection) txt = document.selection.createRange().text;
                   1465:     else return;
                   1466:     var cleantxt = txt.replace(new RegExp('([\\f\\n\\r\\t\\v ])+', 'g')," ");
                   1467:     if (cleantxt=="") {
1.539     riegler  1468: 	alert("$alertmsg");
1.44      ng       1469: 	return;
                   1470:     }
                   1471:     var nret = prompt("Add selection to keyword list? Edit if desired.",cleantxt);
                   1472:     if (nret==null) return;
1.127     ng       1473:     document.SCORE.keywords.value = document.SCORE.keywords.value+" "+nret;
1.44      ng       1474:     if (document.SCORE.keywords.value != "") {
1.127     ng       1475: 	document.SCORE.refresh.value = "on";
1.44      ng       1476: 	document.SCORE.submit();
                   1477:     }
                   1478:     return;
                   1479:   }
                   1480: 
                   1481: //====================== Script for composing message ==============
1.80      ng       1482:    // preload images
                   1483:    img1 = new Image();
                   1484:    img1.src = "$iconpath/mailbkgrd.gif";
                   1485:    img2 = new Image();
                   1486:    img2.src = "$iconpath/mailto.gif";
                   1487: 
1.44      ng       1488:   function msgCenter(msgform,usrctr,fullname) {
                   1489:     var Nmsg  = msgform.savemsgN.value;
                   1490:     savedMsgHeader(Nmsg,usrctr,fullname);
                   1491:     var subject = msgform.msgsub.value;
1.127     ng       1492:     var msgchk = document.SCORE["includemsg"+usrctr].value;
1.44      ng       1493:     re = /msgsub/;
                   1494:     var shwsel = "";
                   1495:     if (re.test(msgchk)) { shwsel = "checked" }
1.123     ng       1496:     subject = (document.SCORE.shownSub.value == 0 ? checkEntities(subject) : subject);
                   1497:     displaySubject(checkEntities(subject),shwsel);
1.44      ng       1498:     for (var i=1; i<=Nmsg; i++) {
1.123     ng       1499: 	var testmsg = "savemsg"+i+",";
                   1500: 	re = new RegExp(testmsg,"g");
1.44      ng       1501: 	shwsel = "";
                   1502: 	if (re.test(msgchk)) { shwsel = "checked" }
1.125     ng       1503: 	var message = document.SCORE["savemsg"+i].value;
1.126     ng       1504: 	message = (document.SCORE["shownOnce"+i].value == 0 ? checkEntities(message) : message);
1.123     ng       1505: 	displaySavedMsg(i,message,shwsel); //I do not get it. w/o checkEntities on saved messages,
                   1506: 	                                   //any &lt; is already converted to <, etc. However, only once!!
1.44      ng       1507:     }
1.125     ng       1508:     newmsg = document.SCORE["newmsg"+usrctr].value;
1.44      ng       1509:     shwsel = "";
                   1510:     re = /newmsg/;
                   1511:     if (re.test(msgchk)) { shwsel = "checked" }
                   1512:     newMsg(newmsg,shwsel);
                   1513:     msgTail(); 
                   1514:     return;
                   1515:   }
                   1516: 
1.123     ng       1517:   function checkEntities(strx) {
                   1518:     if (strx.length == 0) return strx;
                   1519:     var orgStr = ["&", "<", ">", '"']; 
                   1520:     var newStr = ["&amp;", "&lt;", "&gt;", "&quot;"];
                   1521:     var counter = 0;
                   1522:     while (counter < 4) {
                   1523: 	strx = strReplace(strx,orgStr[counter],newStr[counter]);
                   1524: 	counter++;
                   1525:     }
                   1526:     return strx;
                   1527:   }
                   1528: 
                   1529:   function strReplace(strx, orgStr, newStr) {
                   1530:     return strx.split(orgStr).join(newStr);
                   1531:   }
                   1532: 
1.44      ng       1533:   function savedMsgHeader(Nmsg,usrctr,fullname) {
1.76      ng       1534:     var height = 70*Nmsg+250;
1.44      ng       1535:     var scrollbar = "no";
                   1536:     if (height > 600) {
                   1537: 	height = 600;
                   1538: 	scrollbar = "yes";
                   1539:     }
1.118     ng       1540:     var xpos = (screen.width-600)/2;
                   1541:     xpos = (xpos < 0) ? '0' : xpos;
                   1542:     var ypos = (screen.height-height)/2-30;
                   1543:     ypos = (ypos < 0) ? '0' : ypos;
                   1544: 
1.206     albertel 1545:     pWin = window.open('', 'MessageCenter', 'resizable=yes,toolbar=no,location=no,scrollbars='+scrollbar+',screenx='+xpos+',screeny='+ypos+',width=600,height='+height);
1.76      ng       1546:     pWin.focus();
                   1547:     pDoc = pWin.document;
1.219     www      1548:     pDoc.$docopen;
1.351     albertel 1549:     pDoc.write('$start_page_msg_central');
1.76      ng       1550: 
                   1551:     pDoc.write("<form action=\\"inactive\\" name=\\"msgcenter\\">");
                   1552:     pDoc.write("<input value=\\""+usrctr+"\\" name=\\"usrctr\\" type=\\"hidden\\">");
1.465     albertel 1553:     pDoc.write("<h3><span class=\\"LC_info\\">&nbsp;Compose Message for \"+fullname+\"<\\/span><\\/h3><br /><br />");
1.76      ng       1554: 
1.564     bisitz   1555:     pDoc.write('<table border="0" width="100%"><tr><td bgcolor="#777777">');
                   1556:     pDoc.write('<table border="0" width="100%"><tr bgcolor="#DDFFFF">');
1.465     albertel 1557:     pDoc.write("<td><b>Type<\\/b><\\/td><td><b>Include<\\/b><\\/td><td><b>Message<\\/td><\\/tr>");
1.44      ng       1558: }
                   1559:     function displaySubject(msg,shwsel) {
1.76      ng       1560:     pDoc = pWin.document;
                   1561:     pDoc.write("<tr bgcolor=\\"#ffffdd\\">");
1.465     albertel 1562:     pDoc.write("<td>Subject<\\/td>");
                   1563:     pDoc.write("<td align=\\"center\\"><input name=\\"subchk\\" type=\\"checkbox\\"" +shwsel+"><\\/td>");
                   1564:     pDoc.write("<td><input name=\\"msgsub\\" type=\\"text\\" value=\\""+msg+"\\"size=\\"60\\" maxlength=\\"80\\"><\\/td><\\/tr>");
1.44      ng       1565: }
                   1566: 
1.72      ng       1567:   function displaySavedMsg(ctr,msg,shwsel) {
1.76      ng       1568:     pDoc = pWin.document;
                   1569:     pDoc.write("<tr bgcolor=\\"#ffffdd\\">");
1.465     albertel 1570:     pDoc.write("<td align=\\"center\\">"+ctr+"<\\/td>");
                   1571:     pDoc.write("<td align=\\"center\\"><input name=\\"msgn"+ctr+"\\" type=\\"checkbox\\"" +shwsel+"><\\/td>");
                   1572:     pDoc.write("<td><textarea name=\\"msg"+ctr+"\\" cols=\\"60\\" rows=\\"3\\">"+msg+"<\\/textarea><\\/td><\\/tr>");
1.44      ng       1573: }
                   1574: 
                   1575:   function newMsg(newmsg,shwsel) {
1.76      ng       1576:     pDoc = pWin.document;
                   1577:     pDoc.write("<tr bgcolor=\\"#ffffdd\\">");
1.465     albertel 1578:     pDoc.write("<td align=\\"center\\">New<\\/td>");
                   1579:     pDoc.write("<td align=\\"center\\"><input name=\\"newmsgchk\\" type=\\"checkbox\\"" +shwsel+"><\\/td>");
                   1580:     pDoc.write("<td><textarea name=\\"newmsg\\" cols=\\"60\\" rows=\\"3\\" onchange=\\"javascript:this.form.newmsgchk.checked=true\\" >"+newmsg+"<\\/textarea><\\/td><\\/tr>");
1.44      ng       1581: }
                   1582: 
                   1583:   function msgTail() {
1.76      ng       1584:     pDoc = pWin.document;
1.465     albertel 1585:     pDoc.write("<\\/table>");
                   1586:     pDoc.write("<\\/td><\\/tr><\\/table>&nbsp;");
1.76      ng       1587:     pDoc.write("<input type=\\"button\\" value=\\"Save\\" onClick=\\"javascript:checkInput()\\">&nbsp;&nbsp;");
1.326     albertel 1588:     pDoc.write("<input type=\\"button\\" value=\\"Cancel\\" onClick=\\"self.close()\\"><br /><br />");
1.465     albertel 1589:     pDoc.write("<\\/form>");
1.351     albertel 1590:     pDoc.write('$end_page_msg_central');
1.128     ng       1591:     pDoc.close();
1.44      ng       1592: }
                   1593: 
                   1594: //====================== Script for keyword highlight options ==============
                   1595:   function kwhighlight() {
                   1596:     var kwclr    = document.SCORE.kwclr.value;
                   1597:     var kwsize   = document.SCORE.kwsize.value;
                   1598:     var kwstyle  = document.SCORE.kwstyle.value;
                   1599:     var redsel = "";
                   1600:     var grnsel = "";
                   1601:     var blusel = "";
                   1602:     if (kwclr=="red")   {var redsel="checked"};
                   1603:     if (kwclr=="green") {var grnsel="checked"};
                   1604:     if (kwclr=="blue")  {var blusel="checked"};
                   1605:     var sznsel = "";
                   1606:     var sz1sel = "";
                   1607:     var sz2sel = "";
                   1608:     if (kwsize=="0")  {var sznsel="checked"};
                   1609:     if (kwsize=="+1") {var sz1sel="checked"};
                   1610:     if (kwsize=="+2") {var sz2sel="checked"};
                   1611:     var synsel = "";
                   1612:     var syisel = "";
                   1613:     var sybsel = "";
                   1614:     if (kwstyle=="")    {var synsel="checked"};
                   1615:     if (kwstyle=="<i>") {var syisel="checked"};
                   1616:     if (kwstyle=="<b>") {var sybsel="checked"};
                   1617:     highlightCentral();
                   1618:     highlightbody('red','red',redsel,'0','normal',sznsel,'','normal',synsel);
                   1619:     highlightbody('green','green',grnsel,'+1','+1',sz1sel,'<i>','italic',syisel);
                   1620:     highlightbody('blue','blue',blusel,'+2','+2',sz2sel,'<b>','bold',sybsel);
                   1621:     highlightend();
                   1622:     return;
                   1623:   }
                   1624: 
                   1625:   function highlightCentral() {
1.76      ng       1626: //    if (window.hwdWin) window.hwdWin.close();
1.118     ng       1627:     var xpos = (screen.width-400)/2;
                   1628:     xpos = (xpos < 0) ? '0' : xpos;
                   1629:     var ypos = (screen.height-330)/2-30;
                   1630:     ypos = (ypos < 0) ? '0' : ypos;
                   1631: 
1.206     albertel 1632:     hwdWin = window.open('', 'KeywordHighlightCentral', 'resizeable=yes,toolbar=no,location=no,scrollbars=no,width=400,height=300,screenx='+xpos+',screeny='+ypos);
1.76      ng       1633:     hwdWin.focus();
                   1634:     var hDoc = hwdWin.document;
1.219     www      1635:     hDoc.$docopen;
1.351     albertel 1636:     hDoc.write('$start_page_highlight_central');
1.76      ng       1637:     hDoc.write("<form action=\\"inactive\\" name=\\"hlCenter\\">");
1.465     albertel 1638:     hDoc.write("<h3><span class=\\"LC_info\\">&nbsp;Keyword Highlight Options<\\/span><\\/h3><br /><br />");
1.76      ng       1639: 
1.564     bisitz   1640:     hDoc.write('<table border="0" width="100%"><tr><td bgcolor="#777777">');
                   1641:     hDoc.write('<table border="0" width="100%"><tr bgcolor="#DDFFFF">');
1.465     albertel 1642:     hDoc.write("<td><b>Text Color<\\/b><\\/td><td><b>Font Size<\\/b><\\/td><td><b>Font Style<\\/td><\\/tr>");
1.44      ng       1643:   }
                   1644: 
                   1645:   function highlightbody(clrval,clrtxt,clrsel,szval,sztxt,szsel,syval,sytxt,sysel) { 
1.76      ng       1646:     var hDoc = hwdWin.document;
                   1647:     hDoc.write("<tr bgcolor=\\"#ffffdd\\">");
                   1648:     hDoc.write("<td align=\\"left\\">");
1.465     albertel 1649:     hDoc.write("<input name=\\"kwdclr\\" type=\\"radio\\" value=\\""+clrval+"\\" "+clrsel+">&nbsp;"+clrtxt+"<\\/td>");
1.76      ng       1650:     hDoc.write("<td align=\\"left\\">");
1.465     albertel 1651:     hDoc.write("<input name=\\"kwdsize\\" type=\\"radio\\" value=\\""+szval+"\\" "+szsel+">&nbsp;"+sztxt+"<\\/td>");
1.76      ng       1652:     hDoc.write("<td align=\\"left\\">");
1.465     albertel 1653:     hDoc.write("<input name=\\"kwdstyle\\" type=\\"radio\\" value=\\""+syval+"\\" "+sysel+">&nbsp;"+sytxt+"<\\/td>");
                   1654:     hDoc.write("<\\/tr>");
1.44      ng       1655:   }
                   1656: 
                   1657:   function highlightend() { 
1.76      ng       1658:     var hDoc = hwdWin.document;
1.465     albertel 1659:     hDoc.write("<\\/table>");
                   1660:     hDoc.write("<\\/td><\\/tr><\\/table>&nbsp;");
1.76      ng       1661:     hDoc.write("<input type=\\"button\\" value=\\"Save\\" onClick=\\"javascript:updateChoice(1)\\">&nbsp;&nbsp;");
1.326     albertel 1662:     hDoc.write("<input type=\\"button\\" value=\\"Cancel\\" onClick=\\"self.close()\\"><br /><br />");
1.465     albertel 1663:     hDoc.write("<\\/form>");
1.351     albertel 1664:     hDoc.write('$end_page_highlight_central');
1.128     ng       1665:     hDoc.close();
1.44      ng       1666:   }
                   1667: 
                   1668: </script>
                   1669: SUBJAVASCRIPT
                   1670: }
                   1671: 
1.349     albertel 1672: sub get_increment {
1.348     bowersj2 1673:     my $increment = $env{'form.increment'};
                   1674:     if ($increment != 1 && $increment != .5 && $increment != .25 &&
                   1675:         $increment != .1) {
                   1676:         $increment = 1;
                   1677:     }
                   1678:     return $increment;
                   1679: }
                   1680: 
1.71      ng       1681: #--- displays the grading box, used in essay type problem and grading by page/sequence
                   1682: sub gradeBox {
1.322     albertel 1683:     my ($request,$symb,$uname,$udom,$counter,$partid,$record) = @_;
1.381     albertel 1684:     my $checkIcon = '<img alt="'.&mt('Check Mark').
1.485     albertel 1685: 	'" src="'.&Apache::loncommon::lonhttpdurl($request->dir_config('lonIconsURL').'/check.gif').'" height="16" border="0" />';
1.71      ng       1686:     my $wgt    = &Apache::lonnet::EXT('resource.'.$partid.'.weight',$symb,$udom,$uname);
1.466     albertel 1687:     my $wgtmsg = ($wgt > 0) ? &mt('(problem weight)') 
                   1688:                            : '<span class="LC_info">'.&mt('problem weight assigned by computer').'</span>';
1.71      ng       1689:     $wgt       = ($wgt > 0 ? $wgt : '1');
                   1690:     my $score  = ($$record{'resource.'.$partid.'.awarded'} eq '' ?
1.320     albertel 1691: 		  '' : &compute_points($$record{'resource.'.$partid.'.awarded'},$wgt));
1.71      ng       1692:     my $result='<input type="hidden" name="WGT'.$counter.'_'.$partid.'" value="'.$wgt.'" />'."\n";
1.466     albertel 1693:     my $display_part= &get_display_part($partid,$symb);
1.270     albertel 1694:     my %last_resets = &get_last_resets($symb,$env{'request.course.id'},
                   1695: 				       [$partid]);
                   1696:     my $aggtries = $$record{'resource.'.$partid.'.tries'};
1.269     raeburn  1697:     if ($last_resets{$partid}) {
                   1698:         $aggtries = &get_num_tries($record,$last_resets{$partid},$partid);
                   1699:     }
1.485     albertel 1700:     $result.='<table border="0"><tr>';
1.71      ng       1701:     my $ctr = 0;
1.348     bowersj2 1702:     my $thisweight = 0;
1.349     albertel 1703:     my $increment = &get_increment();
1.485     albertel 1704: 
                   1705:     my $radio.='<table border="0"><tr>'."\n";  # display radio buttons in a nice table 10 across
1.348     bowersj2 1706:     while ($thisweight<=$wgt) {
1.532     bisitz   1707: 	$radio.= '<td><span class="LC_nobreak"><label><input type="radio" name="RADVAL'.$counter.'_'.$partid.'" '.
1.71      ng       1708: 	    'onclick="javascript:writeBox(this.form,\''.$counter.'_'.$partid.'\','.
1.348     bowersj2 1709: 	    $thisweight.')" value="'.$thisweight.'" '.
1.401     albertel 1710: 	    ($score eq $thisweight ? 'checked="checked"':'').' /> '.$thisweight."</label></span></td>\n";
1.485     albertel 1711: 	$radio.=(($ctr+1)%10 == 0 ? '</tr><tr>' : '');
1.348     bowersj2 1712:         $thisweight += $increment;
1.71      ng       1713: 	$ctr++;
                   1714:     }
1.485     albertel 1715:     $radio.='</tr></table>';
                   1716: 
                   1717:     my $line.='<input type="text" name="GD_BOX'.$counter.'_'.$partid.'"'.
1.71      ng       1718: 	($score ne ''? ' value = "'.$score.'"':'').' size="4" '.
                   1719: 	'onChange="javascript:updateRadio(this.form,\''.$counter.'_'.$partid.'\','.
                   1720: 	$wgt.')" /></td>'."\n";
1.485     albertel 1721:     $line.='<td>/'.$wgt.' '.$wgtmsg.
1.71      ng       1722: 	($$record{'resource.'.$partid.'.solved'} eq 'correct_by_student' ? '&nbsp;'.$checkIcon : '').
1.540     riegler  1723: 	' </td><td><b>'.&mt('Grade Status').':</b>'."\n";
1.485     albertel 1724:     $line.='<select name="GD_SEL'.$counter.'_'.$partid.'" '.
1.71      ng       1725: 	'onChange="javascript:clearRadBox(this.form,\''.$counter.'_'.$partid.'\')" >'."\n";
                   1726:     if ($$record{'resource.'.$partid.'.solved'} eq 'excused') {
1.485     albertel 1727: 	$line.='<option></option>'.
                   1728: 	    '<option value="excused" selected="selected">'.&mt('excused').'</option>';
1.71      ng       1729:     } else {
1.485     albertel 1730: 	$line.='<option selected="selected"></option>'.
                   1731: 	    '<option value="excused" >'.&mt('excused').'</option>';
1.71      ng       1732:     }
1.485     albertel 1733:     $line.='<option value="reset status">'.&mt('reset status').'</option></select>'."\n";
                   1734: 
                   1735: 
1.540     riegler  1736: 	#&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 1737:     $result .= 
1.580     raeburn  1738: 	    '<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 1739:     $result.='</tr></table>'."\n";
1.71      ng       1740:     $result.='<input type="hidden" name="stores'.$counter.'_'.$partid.'" value="" />'."\n".
                   1741: 	'<input type="hidden" name="oldpts'.$counter.'_'.$partid.'" value="'.$score.'" />'."\n".
                   1742: 	'<input type="hidden" name="solved'.$counter.'_'.$partid.'" value="'.
1.269     raeburn  1743: 	$$record{'resource.'.$partid.'.solved'}.'" />'."\n".
                   1744:         '<input type="hidden" name="totaltries'.$counter.'_'.$partid.'" value="'.
                   1745:         $$record{'resource.'.$partid.'.tries'}.'" />'."\n".
                   1746:         '<input type="hidden" name="aggtries'.$counter.'_'.$partid.'" value="'.
                   1747:         $aggtries.'" />'."\n";
1.323     banghart 1748:     $result.=&handback_box($symb,$uname,$udom,$counter,$partid,$record);
1.318     banghart 1749:     return $result;
                   1750: }
1.322     albertel 1751: 
                   1752: sub handback_box {
1.323     banghart 1753:     my ($symb,$uname,$udom,$counter,$partid,$record) = @_;
1.324     albertel 1754:     my ($partlist,$handgrade,$responseType) = &response_type($symb);
1.323     banghart 1755:     my (@respids);
1.375     albertel 1756:      my @part_response_id = &flatten_responseType($responseType);
                   1757:     foreach my $part_response_id (@part_response_id) {
                   1758:     	my ($part,$resp) = @{ $part_response_id };
1.323     banghart 1759:         if ($part eq $partid) {
1.375     albertel 1760:             push(@respids,$resp);
1.323     banghart 1761:         }
                   1762:     }
1.318     banghart 1763:     my $result;
1.323     banghart 1764:     foreach my $respid (@respids) {
1.322     albertel 1765: 	my $prefix = $counter.'_'.$partid.'_'.$respid.'_';
                   1766: 	my $files=&get_submitted_files($udom,$uname,$partid,$respid,$record);
                   1767: 	next if (!@$files);
                   1768: 	my $file_counter = 1;
1.313     banghart 1769: 	foreach my $file (@$files) {
1.368     banghart 1770: 	    if ($file =~ /\/portfolio\//) {
                   1771:     	        my ($file_path, $file_disp) = ($file =~ m|(.+/)(.+)$|);
                   1772:     	        my ($name,$version,$ext) = &file_name_version_ext($file_disp);
                   1773:     	        $file_disp = "$name.$ext";
                   1774:     	        $file = $file_path.$file_disp;
                   1775:     	        $result.=&mt('Return commented version of [_1] to student.',
                   1776:     			 '<span class="LC_filename">'.$file_disp.'</span>');
                   1777:     	        $result.='<input type="file"   name="'.$prefix.'returndoc'.$file_counter.'" />'."\n";
                   1778:     	        $result.='<input type="hidden" name="'.$prefix.'origdoc'.$file_counter.'" value="'.$file.'" /><br />';
1.485     albertel 1779:     	        $result.='('.&mt('File will be uploaded when you click on Save &amp; Next below.').')<br />';
1.368     banghart 1780:     	        $file_counter++;
                   1781: 	    }
1.322     albertel 1782: 	}
1.313     banghart 1783:     }
1.318     banghart 1784:     return $result;    
1.71      ng       1785: }
1.44      ng       1786: 
1.58      albertel 1787: sub show_problem {
1.382     albertel 1788:     my ($request,$symb,$uname,$udom,$removeform,$viewon,$mode,$form) = @_;
1.144     albertel 1789:     my $rendered;
1.382     albertel 1790:     my %form = ((ref($form) eq 'HASH')? %{$form} : ());
1.329     albertel 1791:     &Apache::lonxml::remember_problem_counter();
1.144     albertel 1792:     if ($mode eq 'both' or $mode eq 'text') {
                   1793: 	$rendered=&Apache::loncommon::get_student_view($symb,$uname,$udom,
1.382     albertel 1794: 						       $env{'request.course.id'},
                   1795: 						       undef,\%form);
1.144     albertel 1796:     }
1.58      albertel 1797:     if ($removeform) {
                   1798: 	$rendered=~s|<form(.*?)>||g;
                   1799: 	$rendered=~s|</form>||g;
1.374     albertel 1800: 	$rendered=~s|(<input[^>]*name\s*=\s*"?)(\w+)("?)|$1would_have_been_$2$3|g;
1.58      albertel 1801:     }
1.144     albertel 1802:     my $companswer;
                   1803:     if ($mode eq 'both' or $mode eq 'answer') {
1.329     albertel 1804: 	&Apache::lonxml::restore_problem_counter();
1.382     albertel 1805: 	$companswer=
                   1806: 	    &Apache::loncommon::get_student_answers($symb,$uname,$udom,
                   1807: 						    $env{'request.course.id'},
                   1808: 						    %form);
1.144     albertel 1809:     }
1.58      albertel 1810:     if ($removeform) {
                   1811: 	$companswer=~s|<form(.*?)>||g;
                   1812: 	$companswer=~s|</form>||g;
1.144     albertel 1813: 	$companswer=~s|name="submit"|name="would_have_been_submit"|g;
1.58      albertel 1814:     }
1.468     albertel 1815:     $rendered=
                   1816: 	'<div class="LC_grade_show_problem_header">'.
                   1817: 	&mt('View of the problem').
                   1818: 	'</div><div class="LC_grade_show_problem_problem">'.
                   1819: 	$rendered.
                   1820: 	'</div>';
                   1821:     $companswer=
                   1822: 	'<div class="LC_grade_show_problem_header">'.
                   1823: 	&mt('Correct answer').
                   1824: 	'</div><div class="LC_grade_show_problem_problem">'.
                   1825: 	$companswer.
                   1826: 	'</div>';
                   1827:     my $result;
1.144     albertel 1828:     if ($mode eq 'both') {
1.468     albertel 1829: 	$result=$rendered.$companswer;
1.144     albertel 1830:     } elsif ($mode eq 'text') {
1.468     albertel 1831: 	$result=$rendered;
1.144     albertel 1832:     } elsif ($mode eq 'answer') {
1.468     albertel 1833: 	$result=$companswer;
1.144     albertel 1834:     }
1.468     albertel 1835:     $result='<div class="LC_grade_show_problem">'.$result.'</div>';
1.71      ng       1836:     return $result;
1.58      albertel 1837: }
1.397     albertel 1838: 
1.396     banghart 1839: sub files_exist {
                   1840:     my ($r, $symb) = @_;
                   1841:     my @students = &Apache::loncommon::get_env_multiple('form.stuinfo');
1.397     albertel 1842: 
1.396     banghart 1843:     foreach my $student (@students) {
                   1844:         my ($uname,$udom,$fullname) = split(/:/,$student);
1.397     albertel 1845:         my %record = &Apache::lonnet::restore($symb,$env{'request.course.id'},
                   1846: 					      $udom,$uname);
1.396     banghart 1847:         my ($string,$timestamp)= &get_last_submission(\%record);
1.397     albertel 1848:         foreach my $submission (@$string) {
                   1849:             my ($partid,$respid) =
                   1850: 		($submission =~ /^resource\.([^\.]*)\.([^\.]*)\.submission/);
                   1851:             my $files=&get_submitted_files($udom,$uname,$partid,$respid,
                   1852: 					   \%record);
                   1853:             return 1 if (@$files);
1.396     banghart 1854:         }
                   1855:     }
1.397     albertel 1856:     return 0;
1.396     banghart 1857: }
1.397     albertel 1858: 
1.394     banghart 1859: sub download_all_link {
                   1860:     my ($r,$symb) = @_;
1.395     albertel 1861:     my $all_students = 
                   1862: 	join("\n", &Apache::loncommon::get_env_multiple('form.stuinfo'));
                   1863: 
                   1864:     my $parts =
                   1865: 	join("\n",&Apache::loncommon::get_env_multiple('form.vPart'));
                   1866: 
1.394     banghart 1867:     my $identifier = &Apache::loncommon::get_cgi_id();
1.514     raeburn  1868:     &Apache::lonnet::appenv({'cgi.'.$identifier.'.students' => $all_students,
                   1869:                              'cgi.'.$identifier.'.symb' => $symb,
                   1870:                              'cgi.'.$identifier.'.parts' => $parts,});
1.395     albertel 1871:     $r->print('<a href="/cgi-bin/multidownload.pl?'.$identifier.'">'.
                   1872: 	      &mt('Download All Submitted Documents').'</a>');
1.394     banghart 1873:     return
                   1874: }
1.395     albertel 1875: 
1.432     banghart 1876: sub build_section_inputs {
                   1877:     my $section_inputs;
                   1878:     if ($env{'form.section'} eq '') {
                   1879:         $section_inputs .= '<input type="hidden" name="section" value="all" />'."\n";
                   1880:     } else {
                   1881:         my @sections = &Apache::loncommon::get_env_multiple('form.section');
1.434     albertel 1882:         foreach my $section (@sections) {
1.432     banghart 1883:             $section_inputs .= '<input type="hidden" name="section" value="'.$section.'" />'."\n";
                   1884:         }
                   1885:     }
                   1886:     return $section_inputs;
                   1887: }
                   1888: 
1.44      ng       1889: # --------------------------- show submissions of a student, option to grade 
                   1890: sub submission {
                   1891:     my ($request,$counter,$total) = @_;
1.257     albertel 1892:     my ($uname,$udom)     = ($env{'form.student'},$env{'form.userdom'});
                   1893:     $udom = ($udom eq '' ? $env{'user.domain'} : $udom); #has form.userdom changed for a student?
                   1894:     my $usec = &Apache::lonnet::getsection($udom,$uname,$env{'request.course.id'});
                   1895:     $env{'form.fullname'} = &Apache::loncommon::plainname($uname,$udom,'lastname') if $env{'form.fullname'} eq '';
1.324     albertel 1896:     my $symb = &get_symb($request); 
                   1897:     if ($symb eq '') { $request->print("Unable to handle ambiguous references:."); return ''; }
1.104     albertel 1898: 
                   1899:     if (!&canview($usec)) {
1.398     albertel 1900: 	$request->print('<span class="LC_warning">Unable to view requested student.('.
                   1901: 			$uname.':'.$udom.' in section '.$usec.' in course id '.
                   1902: 			$env{'request.course.id'}.')</span>');
1.324     albertel 1903: 	$request->print(&show_grading_menu_form($symb));
1.104     albertel 1904: 	return;
                   1905:     }
                   1906: 
1.257     albertel 1907:     if (!$env{'form.lastSub'}) { $env{'form.lastSub'} = 'datesub'; }
                   1908:     if (!$env{'form.vProb'}) { $env{'form.vProb'} = 'yes'; }
                   1909:     if (!$env{'form.vAns'}) { $env{'form.vAns'} = 'yes'; }
                   1910:     my $last = ($env{'form.lastSub'} eq 'last' ? 'last' : '');
1.381     albertel 1911:     my $checkIcon = '<img alt="'.&mt('Check Mark').
                   1912: 	'" src="'.$request->dir_config('lonIconsURL').
1.122     ng       1913: 	'/check.gif" height="16" border="0" />';
1.41      ng       1914: 
1.426     albertel 1915:     my %old_essays;
1.41      ng       1916:     # header info
                   1917:     if ($counter == 0) {
                   1918: 	&sub_page_js($request);
1.257     albertel 1919: 	&sub_page_kw_js($request) if ($env{'form.handgrade'} eq 'yes');
                   1920: 	$env{'form.probTitle'} = $env{'form.probTitle'} eq '' ? 
                   1921: 	    &Apache::lonnet::gettitle($symb) : $env{'form.probTitle'};
1.397     albertel 1922: 	if ($env{'form.handgrade'} eq 'yes' && &files_exist($request, $symb)) {
1.396     banghart 1923: 	    &download_all_link($request, $symb);
                   1924: 	}
1.485     albertel 1925: 	$request->print('<h3>&nbsp;<span class="LC_info">'.&mt('Submission Record').'</span></h3>'."\n".
                   1926: 			'<h4>&nbsp;'.&mt('<b>Resource: </b> [_1]',$env{'form.probTitle'}).'</h4>'."\n");
1.118     ng       1927: 
1.44      ng       1928: 	# option to display problem, only once else it cause problems 
                   1929:         # with the form later since the problem has a form.
1.257     albertel 1930: 	if ($env{'form.vProb'} eq 'yes' or $env{'form.vAns'} eq 'yes') {
1.144     albertel 1931: 	    my $mode;
1.257     albertel 1932: 	    if ($env{'form.vProb'} eq 'yes' && $env{'form.vAns'} eq 'yes') {
1.144     albertel 1933: 		$mode='both';
1.257     albertel 1934: 	    } elsif ($env{'form.vProb'} eq 'yes') {
1.144     albertel 1935: 		$mode='text';
1.257     albertel 1936: 	    } elsif ($env{'form.vAns'} eq 'yes') {
1.144     albertel 1937: 		$mode='answer';
                   1938: 	    }
1.329     albertel 1939: 	    &Apache::lonxml::clear_problem_counter();
1.144     albertel 1940: 	    $request->print(&show_problem($request,$symb,$uname,$udom,0,1,$mode));
1.41      ng       1941: 	}
1.441     www      1942: 
1.44      ng       1943: 	# kwclr is the only variable that is guaranteed to be non blank 
                   1944:         # if this subroutine has been called once.
1.41      ng       1945: 	my %keyhash = ();
1.257     albertel 1946: 	if ($env{'form.kwclr'} eq '' && $env{'form.handgrade'} eq 'yes') {
1.41      ng       1947: 	    %keyhash = &Apache::lonnet::dump('nohist_handgrade',
1.257     albertel 1948: 					     $env{'course.'.$env{'request.course.id'}.'.domain'},
                   1949: 					     $env{'course.'.$env{'request.course.id'}.'.num'});
1.41      ng       1950: 
1.257     albertel 1951: 	    my $loginuser = $env{'user.name'}.':'.$env{'user.domain'};
                   1952: 	    $env{'form.keywords'} = $keyhash{$symb.'_keywords'} ne '' ? $keyhash{$symb.'_keywords'} : '';
                   1953: 	    $env{'form.kwclr'}    = $keyhash{$loginuser.'_kwclr'} ne '' ? $keyhash{$loginuser.'_kwclr'} : 'red';
                   1954: 	    $env{'form.kwsize'}   = $keyhash{$loginuser.'_kwsize'} ne '' ? $keyhash{$loginuser.'_kwsize'} : '0';
                   1955: 	    $env{'form.kwstyle'}  = $keyhash{$loginuser.'_kwstyle'} ne '' ? $keyhash{$loginuser.'_kwstyle'} : '';
                   1956: 	    $env{'form.msgsub'}   = $keyhash{$symb.'_subject'} ne '' ? 
                   1957: 		$keyhash{$symb.'_subject'} : $env{'form.probTitle'};
                   1958: 	    $env{'form.savemsgN'} = $keyhash{$symb.'_savemsgN'} ne '' ? $keyhash{$symb.'_savemsgN'} : '0';
1.41      ng       1959: 	}
1.257     albertel 1960: 	my $overRideScore = $env{'form.overRideScore'} eq '' ? 'no' : $env{'form.overRideScore'};
1.442     banghart 1961: 	my $stu_status = join(':',&Apache::loncommon::get_env_multiple('form.Status'));
1.303     banghart 1962: 	$request->print('<form action="/adm/grades" method="post" name="SCORE" enctype="multipart/form-data">'."\n".
1.41      ng       1963: 			'<input type="hidden" name="command"    value="handgrade" />'."\n".
1.257     albertel 1964: 			'<input type="hidden" name="saveState"  value="'.$env{'form.saveState'}.'" />'."\n".
1.442     banghart 1965: 			'<input type="hidden" name="Status"     value="'.$stu_status.'" />'."\n".
1.120     ng       1966: 			'<input type="hidden" name="overRideScore" value="'.$overRideScore.'" />'."\n".
1.257     albertel 1967: 			'<input type="hidden" name="probTitle"  value="'.$env{'form.probTitle'}.'" />'."\n".
1.41      ng       1968: 			'<input type="hidden" name="refresh"    value="off" />'."\n".
1.120     ng       1969: 			'<input type="hidden" name="studentNo"  value="" />'."\n".
                   1970: 			'<input type="hidden" name="gradeOpt"   value="" />'."\n".
1.418     albertel 1971: 			'<input type="hidden" name="symb"       value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
1.257     albertel 1972: 			'<input type="hidden" name="showgrading" value="'.$env{'form.showgrading'}.'" />'."\n".
                   1973: 			'<input type="hidden" name="vProb"      value="'.$env{'form.vProb'}.'" />'."\n".
                   1974: 			'<input type="hidden" name="vAns"       value="'.$env{'form.vAns'}.'" />'."\n".
                   1975: 			'<input type="hidden" name="lastSub"    value="'.$env{'form.lastSub'}.'" />'."\n".
1.432     banghart 1976: 			&build_section_inputs().
1.326     albertel 1977: 			'<input type="hidden" name="submitonly" value="'.$env{'form.submitonly'}.'" />'."\n".
                   1978: 			'<input type="hidden" name="handgrade"  value="'.$env{'form.handgrade'}.'" />'."\n".
1.41      ng       1979: 			'<input type="hidden" name="NCT"'.
1.257     albertel 1980: 			' value="'.($env{'form.NTSTU'} ne '' ? $env{'form.NTSTU'} : $total+1).'" />'."\n");
                   1981: 	if ($env{'form.handgrade'} eq 'yes') {
                   1982: 	    $request->print('<input type="hidden" name="keywords" value="'.$env{'form.keywords'}.'" />'."\n".
                   1983: 			    '<input type="hidden" name="kwclr"    value="'.$env{'form.kwclr'}.'" />'."\n".
                   1984: 			    '<input type="hidden" name="kwsize"   value="'.$env{'form.kwsize'}.'" />'."\n".
                   1985: 			    '<input type="hidden" name="kwstyle"  value="'.$env{'form.kwstyle'}.'" />'."\n".
                   1986: 			    '<input type="hidden" name="msgsub"   value="'.$env{'form.msgsub'}.'" />'."\n".
1.123     ng       1987: 			    '<input type="hidden" name="shownSub" value="0" />'."\n".
1.257     albertel 1988: 			    '<input type="hidden" name="savemsgN" value="'.$env{'form.savemsgN'}.'" />'."\n");
1.154     albertel 1989: 	    foreach my $partid (&Apache::loncommon::get_env_multiple('form.vPart')) {
                   1990: 		$request->print('<input type="hidden" name="vPart" value="'.$partid.'" />'."\n");
                   1991: 	    }
1.123     ng       1992: 	}
1.41      ng       1993: 	
                   1994: 	my ($cts,$prnmsg) = (1,'');
1.257     albertel 1995: 	while ($cts <= $env{'form.savemsgN'}) {
1.41      ng       1996: 	    $prnmsg.='<input type="hidden" name="savemsg'.$cts.'" value="'.
1.123     ng       1997: 		(!exists($keyhash{$symb.'_savemsg'.$cts}) ? 
1.257     albertel 1998: 		 &Apache::lonfeedback::clear_out_html($env{'form.savemsg'.$cts}) :
1.80      ng       1999: 		 &Apache::lonfeedback::clear_out_html($keyhash{$symb.'_savemsg'.$cts})).
1.123     ng       2000: 		'" />'."\n".
                   2001: 		'<input type="hidden" name="shownOnce'.$cts.'" value="0" />'."\n";
1.41      ng       2002: 	    $cts++;
                   2003: 	}
                   2004: 	$request->print($prnmsg);
1.32      ng       2005: 
1.257     albertel 2006: 	if ($env{'form.handgrade'} eq 'yes' && $env{'form.showgrading'} eq 'yes') {
1.88      www      2007: #
                   2008: # Print out the keyword options line
                   2009: #
1.41      ng       2010: 	    $request->print(<<KEYWORDS);
1.38      ng       2011: &nbsp;<b>Keyword Options:</b>&nbsp;
1.417     albertel 2012: <a href="javascript:keywords(document.SCORE);" target="_self">List</a>&nbsp; &nbsp;
1.38      ng       2013: <a href="#" onMouseDown="javascript:getSel(); return false"
                   2014:  CLASS="page">Paste Selection to List</a>&nbsp; &nbsp;
1.417     albertel 2015: <a href="javascript:kwhighlight();" target="_self">Highlight Attribute</a><br /><br />
1.38      ng       2016: KEYWORDS
1.88      www      2017: #
                   2018: # Load the other essays for similarity check
                   2019: #
1.324     albertel 2020:             my (undef,undef,$essayurl) = &Apache::lonnet::decode_symb($symb);
1.384     albertel 2021: 	    my ($adom,$aname,$apath)=($essayurl=~/^($LONCAPA::domain_re)\/($LONCAPA::username_re)\/(.*)$/);
1.359     www      2022: 	    $apath=&escape($apath);
1.88      www      2023: 	    $apath=~s/\W/\_/gs;
1.426     albertel 2024: 	    %old_essays=&Apache::lonnet::dump('nohist_essay_'.$apath,$adom,$aname);
1.41      ng       2025:         }
                   2026:     }
1.44      ng       2027: 
1.441     www      2028: # This is where output for one specific student would start
1.468     albertel 2029:     my $add_class = ($counter%2) ? 'LC_grade_show_user_odd_row' : '';
1.441     www      2030:     $request->print("\n\n".
1.468     albertel 2031:                     '<div class="LC_grade_show_user '.$add_class.'">'.
                   2032: 		    '<div class="LC_grade_user_name">'.&nameUserString(undef,$env{'form.fullname'},$uname,$udom).'</div>'.
                   2033: 		    '<div class="LC_grade_show_user_body">'."\n");
1.441     www      2034: 
1.257     albertel 2035:     if ($env{'form.vProb'} eq 'all' or $env{'form.vAns'} eq 'all') {
1.144     albertel 2036: 	my $mode;
1.257     albertel 2037: 	if ($env{'form.vProb'} eq 'all' && $env{'form.vAns'} eq 'all') {
1.144     albertel 2038: 	    $mode='both';
1.257     albertel 2039: 	} elsif ($env{'form.vProb'} eq 'all' ) {
1.144     albertel 2040: 	    $mode='text';
1.257     albertel 2041: 	} elsif ($env{'form.vAns'} eq 'all') {
1.144     albertel 2042: 	    $mode='answer';
                   2043: 	}
1.329     albertel 2044: 	&Apache::lonxml::clear_problem_counter();
1.475     albertel 2045: 	$request->print(&show_problem($request,$symb,$uname,$udom,1,1,$mode,{'request.prefix' => 'ctr'.$counter}));
1.58      albertel 2046:     }
1.144     albertel 2047: 
1.257     albertel 2048:     my %record = &Apache::lonnet::restore($symb,$env{'request.course.id'},$udom,$uname);
1.324     albertel 2049:     my ($partlist,$handgrade,$responseType) = &response_type($symb);
1.41      ng       2050: 
1.44      ng       2051:     # Display student info
1.41      ng       2052:     $request->print(($counter == 0 ? '' : '<br />'));
1.468     albertel 2053:     my $result='<div class="LC_grade_submissions">';
                   2054:     
                   2055:     $result.='<div class="LC_grade_submissions_header">';
                   2056:     $result.= &mt('Submissions');
1.45      ng       2057:     $result.='<input type="hidden" name="name'.$counter.
1.257     albertel 2058: 	'" value="'.$env{'form.fullname'}.'" />'."\n";
1.469     albertel 2059:     if ($env{'form.handgrade'} eq 'no') {
                   2060: 	$result.='<span class="LC_grade_check_note">'.
                   2061: 	    &mt('Part(s) graded correct by the computer is marked with a [_1] symbol.',$checkIcon)."</span>\n";
                   2062: 
                   2063:     }
                   2064: 
                   2065: 
1.41      ng       2066: 
1.118     ng       2067:     # If any part of the problem is an essay-response (handgraded), then check for collaborators
1.464     albertel 2068:     my $fullname;
                   2069:     my $col_fullnames = [];
1.257     albertel 2070:     if ($env{'form.handgrade'} eq 'yes') {
1.464     albertel 2071: 	(my $sub_result,$fullname,$col_fullnames)=
                   2072: 	    &check_collaborators($symb,$uname,$udom,\%record,$handgrade,
                   2073: 				 $counter);
                   2074: 	$result.=$sub_result;
1.41      ng       2075:     }
1.44      ng       2076:     $request->print($result."\n");
1.468     albertel 2077:     $request->print('</div>'."\n");
1.44      ng       2078:     # print student answer/submission
                   2079:     # Options are (1) Handgaded submission only
                   2080:     #             (2) Last submission, includes submission that is not handgraded 
                   2081:     #                  (for multi-response type part)
                   2082:     #             (3) Last submission plus the parts info
                   2083:     #             (4) The whole record for this student
1.257     albertel 2084:     if ($env{'form.lastSub'} =~ /^(lastonly|hdgrade)$/) {
1.151     albertel 2085: 	my ($string,$timestamp)= &get_last_submission(\%record);
1.468     albertel 2086: 	
                   2087: 	my $lastsubonly;
                   2088: 
1.151     albertel 2089: 	if ($$timestamp eq '') {
1.468     albertel 2090: 	    $lastsubonly.='<div class="LC_grade_submissions_body">'.$$string[0].'</div>'; 
1.151     albertel 2091: 	} else {
1.468     albertel 2092: 	    $lastsubonly = '<div class="LC_grade_submissions_body"> <b>Date Submitted:</b> '.$$timestamp."\n";
                   2093: 
1.151     albertel 2094: 	    my %seenparts;
1.375     albertel 2095: 	    my @part_response_id = &flatten_responseType($responseType);
                   2096: 	    foreach my $part (@part_response_id) {
1.393     albertel 2097: 		next if ($env{'form.lastSub'} eq 'hdgrade' 
                   2098: 			 && $$handgrade{$$part[0].'_'.$$part[1]} ne 'yes');
                   2099: 
1.375     albertel 2100: 		my ($partid,$respid) = @{ $part };
1.324     albertel 2101: 		my $display_part=&get_display_part($partid,$symb);
1.257     albertel 2102: 		if ($env{"form.$uname:$udom:$partid:submitted_by"}) {
1.151     albertel 2103: 		    if (exists($seenparts{$partid})) { next; }
                   2104: 		    $seenparts{$partid}=1;
1.207     albertel 2105: 		    my $submitby='<b>Part:</b> '.$display_part.
                   2106: 			' <b>Collaborative submission by:</b> '.
1.151     albertel 2107: 			'<a href="javascript:viewSubmitter(\''.
1.257     albertel 2108: 			$env{"form.$uname:$udom:$partid:submitted_by"}.
1.417     albertel 2109: 			'\');" target="_self">'.
1.257     albertel 2110: 			$$fullname{$env{"form.$uname:$udom:$partid:submitted_by"}}.'</a><br />';
1.151     albertel 2111: 		    $request->print($submitby);
                   2112: 		    next;
                   2113: 		}
                   2114: 		my $responsetype = $responseType->{$partid}->{$respid};
                   2115: 		if (!exists($record{"resource.$partid.$respid.submission"})) {
1.577     bisitz   2116:                     $lastsubonly.="\n".'<div class="LC_grade_submission_part">'.
                   2117:                         '<b>'.&mt('Part: [_1]',$display_part).'</b>'.
                   2118:                         ' <span class="LC_internal_info">'.
                   2119:                         '('.&mt('Part ID: [_1]',$respid).')</b>'.
                   2120:                         '</span>&nbsp; &nbsp;'.
1.539     riegler  2121: 			'<span class="LC_warning">'.&mt('Nothing submitted - no attempts.').'</span><br /><br /></div>';
1.151     albertel 2122: 		    next;
                   2123: 		}
1.468     albertel 2124: 		foreach my $submission (@$string) {
                   2125: 		    my ($partid,$respid) = ($submission =~ /^resource\.([^\.]*)\.([^\.]*)\.submission/);
1.375     albertel 2126: 		    if (join('_',@{$part}) ne ($partid.'_'.$respid)) { next; }
1.468     albertel 2127: 		    my ($ressub,$subval) = split(/:/,$submission,2);
1.151     albertel 2128: 		    # Similarity check
                   2129: 		    my $similar='';
1.257     albertel 2130: 		    if($env{'form.checkPlag'}){
1.151     albertel 2131: 			my ($oname,$odom,$ocrsid,$oessay,$osim)=
1.426     albertel 2132: 			    &most_similar($uname,$udom,$subval,\%old_essays);
1.151     albertel 2133: 			if ($osim) {
                   2134: 			    $osim=int($osim*100.0);
1.426     albertel 2135: 			    my %old_course_desc = 
                   2136: 				&Apache::lonnet::coursedescription($ocrsid,
                   2137: 								   {'one_time' => 1});
                   2138: 
                   2139: 			    $similar="<hr /><h3><span class=\"LC_warning\">".
1.574     bisitz   2140: 				&mt('Essay is [_1]% similar to an essay by [_2] in course [_3] (course id [_4]:[_5])',
1.426     albertel 2141: 				    $osim,
1.574     bisitz   2142: 				    &Apache::loncommon::plainname($oname,$odom).' ('.$oname.':'.$odom.')',
1.426     albertel 2143: 				    $old_course_desc{'description'},
1.427     albertel 2144: 				    $old_course_desc{'num'},
1.426     albertel 2145: 				    $old_course_desc{'domain'}).
1.398     albertel 2146: 				'</span></h3><blockquote><i>'.
1.151     albertel 2147: 				&keywords_highlight($oessay).
                   2148: 				'</i></blockquote><hr />';
                   2149: 			}
1.150     albertel 2150: 		    }
1.151     albertel 2151: 		    my $order=&get_order($partid,$respid,$symb,$uname,$udom);
1.257     albertel 2152: 		    if ($env{'form.lastSub'} eq 'lastonly' || 
                   2153: 			($env{'form.lastSub'} eq 'hdgrade' && 
1.377     albertel 2154: 			 $$handgrade{$$part[0].'_'.$$part[1]} eq 'yes')) {
1.324     albertel 2155: 			my $display_part=&get_display_part($partid,$symb);
1.577     bisitz   2156:                         $lastsubonly.='<div class="LC_grade_submission_part">'.
                   2157:                             '<b>'.&mt('Part: [_1]',$display_part).'</b>'.
                   2158:                             ' <span class="LC_internal_info">'.
                   2159:                             '('.&mt('Part ID: [_1]',$respid).')'.
                   2160:                             '</b></span>&nbsp; &nbsp;';
1.313     banghart 2161: 			my $files=&get_submitted_files($udom,$uname,$partid,$respid,\%record);
                   2162: 			if (@$files) {
1.544     raeburn  2163: 			    $lastsubonly.='<br /><span class="LC_warning">'.&mt('Like all files provided by users, this file may contain viruses').'</span><br />';
1.303     banghart 2164: 			    my $file_counter = 0;
1.313     banghart 2165: 			    foreach my $file (@$files) {
1.468     albertel 2166: 			        $file_counter++;
1.232     albertel 2167: 				&Apache::lonnet::allowuploaded('/adm/grades',$file);
1.564     bisitz   2168: 				$lastsubonly.='<br /><a href="'.$file.'?rawmode=1" target="lonGRDs"><img src="'.&Apache::loncommon::icon($file).'" border="0" /> '.$file.'</a>';
1.232     albertel 2169: 			    }
1.236     albertel 2170: 			    $lastsubonly.='<br />';
1.41      ng       2171: 			}
1.468     albertel 2172: 			$lastsubonly.='<b>'.&mt('Submitted Answer:').' </b>'.
1.151     albertel 2173: 			    &cleanRecord($subval,$responsetype,$symb,$partid,
1.555     raeburn  2174: 					 $respid,\%record,$order,undef,$uname,$udom);
1.151     albertel 2175: 			if ($similar) {$lastsubonly.="<br /><br />$similar\n";}
1.468     albertel 2176: 			$lastsubonly.='</div>';
1.41      ng       2177: 		    }
                   2178: 		}
                   2179: 	    }
1.468     albertel 2180: 	    $lastsubonly.='</div>'."\n";
1.151     albertel 2181: 	}
                   2182: 	$request->print($lastsubonly);
1.468     albertel 2183:    } elsif ($env{'form.lastSub'} eq 'datesub') {
1.324     albertel 2184: 	my (undef,$responseType,undef,$parts) = &showResourceInfo($symb);
1.148     albertel 2185: 	$request->print(&displaySubByDates($symb,\%record,$parts,$responseType,$checkIcon,$uname,$udom));
1.257     albertel 2186:     } elsif ($env{'form.lastSub'} =~ /^(last|all)$/) {
1.41      ng       2187: 	$request->print(&Apache::loncommon::get_previous_attempt($symb,$uname,$udom,
1.257     albertel 2188: 								 $env{'request.course.id'},
1.44      ng       2189: 								 $last,'.submission',
                   2190: 								 'Apache::grades::keywords_highlight'));
1.41      ng       2191:     }
1.120     ng       2192: 
1.121     ng       2193:     $request->print('<input type="hidden" name="unamedom'.$counter.'" value="'.$uname.':'
                   2194: 	.$udom.'" />'."\n");
1.44      ng       2195:     # return if view submission with no grading option
1.257     albertel 2196:     if ($env{'form.showgrading'} eq '' || (!&canmodify($usec))) {
1.120     ng       2197: 	my $toGrade.='<input type="button" value="Grade Student" '.
1.121     ng       2198: 	    'onClick="javascript:checksubmit(this.form,\'Grade Student\',\''
1.417     albertel 2199: 	    .$counter.'\');" target="_self" /> &nbsp;'."\n" if (&canmodify($usec));
1.468     albertel 2200: 	$toGrade.='</div>'."\n";
1.257     albertel 2201: 	if (($env{'form.command'} eq 'submission') || 
                   2202: 	    ($env{'form.command'} eq 'processGroup' && $counter == $total)) {
1.324     albertel 2203: 	    $toGrade.='</form>'.&show_grading_menu_form($symb); 
1.169     albertel 2204: 	}
1.180     albertel 2205: 	$request->print($toGrade);
1.41      ng       2206: 	return;
1.180     albertel 2207:     } else {
1.468     albertel 2208: 	$request->print('</div>'."\n");
1.41      ng       2209:     }
1.33      ng       2210: 
1.121     ng       2211:     # essay grading message center
1.257     albertel 2212:     if ($env{'form.handgrade'} eq 'yes') {
1.468     albertel 2213: 	my $result='<div class="LC_grade_message_center">';
                   2214:     
                   2215: 	$result.='<div class="LC_grade_message_center_header">'.
                   2216: 	    &mt('Send Message').'</div><div class="LC_grade_message_center_body">';
1.257     albertel 2217: 	my ($lastname,$givenn) = split(/,/,$env{'form.fullname'});
1.118     ng       2218: 	my $msgfor = $givenn.' '.$lastname;
1.464     albertel 2219: 	if (scalar(@$col_fullnames) > 0) {
                   2220: 	    my $lastone = pop(@$col_fullnames);
                   2221: 	    $msgfor .= ', '.(join ', ',@$col_fullnames).' and '.$lastone.'.';
1.118     ng       2222: 	}
                   2223: 	$msgfor =~ s/\'/\\'/g; #' stupid emacs - no! javascript
1.468     albertel 2224: 	$result.='<input type="hidden" name="includemsg'.$counter.'" value="" />'."\n".
1.121     ng       2225: 	    '<input type="hidden" name="newmsg'.$counter.'" value="" />'."\n";
                   2226: 	$result.='&nbsp;<a href="javascript:msgCenter(document.SCORE,'.$counter.
1.417     albertel 2227: 	    ',\''.$msgfor.'\');" target="_self">'.
1.464     albertel 2228: 	    &mt('Compose message to student').(scalar(@$col_fullnames) >= 1 ? 's' : '').'</a><label> ('.
1.350     albertel 2229: 	    &mt('incl. grades').' <input type="checkbox" name="withgrades'.$counter.'" /></label>)'.
1.118     ng       2230: 	    '<img src="'.$request->dir_config('lonIconsURL').
                   2231: 	    '/mailbkgrd.gif" width="14" height="10" name="mailicon'.$counter.'" />'."\n".
1.298     www      2232: 	    '<br />&nbsp;('.
1.468     albertel 2233: 	    &mt('Message will be sent when you click on Save &amp; Next below.').")\n";
                   2234: 	$result.='</div></div>';
1.121     ng       2235: 	$request->print($result);
1.118     ng       2236:     }
1.41      ng       2237: 
                   2238:     my %seen = ();
                   2239:     my @partlist;
1.129     ng       2240:     my @gradePartRespid;
1.375     albertel 2241:     my @part_response_id = &flatten_responseType($responseType);
1.468     albertel 2242:     $request->print('<div class="LC_grade_assign">'.
                   2243: 		    
                   2244: 		    '<div class="LC_grade_assign_header">'.
                   2245: 		    &mt('Assign Grades').'</div>'.
                   2246: 		    '<div class="LC_grade_assign_body">');
1.375     albertel 2247:     foreach my $part_response_id (@part_response_id) {
                   2248:     	my ($partid,$respid) = @{ $part_response_id };
                   2249: 	my $part_resp = join('_',@{ $part_response_id });
1.322     albertel 2250: 	next if ($seen{$partid} > 0);
1.41      ng       2251: 	$seen{$partid}++;
1.393     albertel 2252: 	next if ($$handgrade{$part_resp} ne 'yes' 
                   2253: 		 && $env{'form.lastSub'} eq 'hdgrade');
1.524     raeburn  2254: 	push(@partlist,$partid);
                   2255: 	push(@gradePartRespid,$partid.'.'.$respid);
1.322     albertel 2256: 	$request->print(&gradeBox($request,$symb,$uname,$udom,$counter,$partid,\%record));
1.41      ng       2257:     }
1.468     albertel 2258:     $request->print('</div></div>');
                   2259: 
                   2260:     $request->print('<div class="LC_grade_info_links">');
                   2261:     if ($perm{'vgr'}) {
                   2262: 	$request->print(
                   2263: 	    &Apache::loncommon::track_student_link(&mt('View recent activity'),
                   2264: 						   $uname,$udom,'check'));
                   2265:     }
                   2266:     if ($perm{'opa'}) {
                   2267: 	$request->print(
                   2268: 	    &Apache::loncommon::pprmlink(&mt('Set/Change parameters'),
                   2269: 					 $uname,$udom,$symb,'check'));
                   2270:     }
                   2271:     $request->print('</div>');
                   2272: 
1.45      ng       2273:     $result='<input type="hidden" name="partlist'.$counter.
                   2274: 	'" value="'.(join ":",@partlist).'" />'."\n";
1.129     ng       2275:     $result.='<input type="hidden" name="gradePartRespid'.
                   2276: 	'" value="'.(join ":",@gradePartRespid).'" />'."\n" if ($counter == 0);
1.45      ng       2277:     my $ctr = 0;
                   2278:     while ($ctr < scalar(@partlist)) {
                   2279: 	$result.='<input type="hidden" name="partid'.$counter.'_'.$ctr.'" value="'.
                   2280: 	    $partlist[$ctr].'" />'."\n";
                   2281: 	$ctr++;
                   2282:     }
1.468     albertel 2283:     $request->print($result.''."\n");
1.41      ng       2284: 
1.441     www      2285: # Done with printing info for one student
                   2286: 
1.468     albertel 2287:     $request->print('</div>');#LC_grade_show_user_body
                   2288:     $request->print('</div>');#LC_grade_show_user
1.441     www      2289: 
                   2290: 
1.41      ng       2291:     # print end of form
                   2292:     if ($counter == $total) {
1.297     www      2293: 	my $endform='<table border="0"><tr><td>'."\n";
1.485     albertel 2294: 	$endform.='<input type="button" value="'.&mt('Save &amp; Next').'" '.
1.119     ng       2295: 	    'onClick="javascript:checksubmit(this.form,\'Save & Next\','.
1.417     albertel 2296: 	    $total.','.scalar(@partlist).');" target="_self" /> &nbsp;'."\n";
1.119     ng       2297: 	my $ntstu ='<select name="NTSTU">'.
                   2298: 	    '<option>1</option><option>2</option>'.
                   2299: 	    '<option>3</option><option>5</option>'.
                   2300: 	    '<option>7</option><option>10</option></select>'."\n";
1.257     albertel 2301: 	my $nsel = ($env{'form.NTSTU'} ne '' ? $env{'form.NTSTU'} : '1');
1.401     albertel 2302: 	$ntstu =~ s/<option>$nsel</<option selected="selected">$nsel</;
1.578     raeburn  2303:         $endform.=&mt('[_1]student(s)',$ntstu);
1.485     albertel 2304: 	$endform.='&nbsp;&nbsp;<input type="button" value="'.&mt('Previous').'" '.
1.417     albertel 2305: 	    'onClick="javascript:checksubmit(this.form,\'Previous\');" target="_self" /> &nbsp;'."\n".
1.485     albertel 2306: 	    '<input type="button" value="'.&mt('Next').'" '.
1.417     albertel 2307: 	    'onClick="javascript:checksubmit(this.form,\'Next\');" target="_self" /> &nbsp;';
1.485     albertel 2308: 	$endform.=&mt('(Next and Previous (student) do not save the scores.)')."\n" ;
1.349     albertel 2309:         $endform.="<input type='hidden' value='".&get_increment().
1.348     bowersj2 2310:             "' name='increment' />";
1.485     albertel 2311: 	$endform.='</td></tr></table></form>';
1.324     albertel 2312: 	$endform.=&show_grading_menu_form($symb);
1.41      ng       2313: 	$request->print($endform);
                   2314:     }
                   2315:     return '';
1.38      ng       2316: }
                   2317: 
1.464     albertel 2318: sub check_collaborators {
                   2319:     my ($symb,$uname,$udom,$record,$handgrade,$counter) = @_;
                   2320:     my ($result,@col_fullnames);
                   2321:     my ($classlist,undef,$fullname) = &getclasslist('all','0');
                   2322:     foreach my $part (keys(%$handgrade)) {
                   2323: 	my $ncol = &Apache::lonnet::EXT('resource.'.$part.
                   2324: 					'.maxcollaborators',
                   2325: 					$symb,$udom,$uname);
                   2326: 	next if ($ncol <= 0);
                   2327: 	$part =~ s/\_/\./g;
                   2328: 	next if ($record->{'resource.'.$part.'.collaborators'} eq '');
                   2329: 	my (@good_collaborators, @bad_collaborators);
                   2330: 	foreach my $possible_collaborator
                   2331: 	    (split(/,?\s+/,$record->{'resource.'.$part.'.collaborators'})) { 
                   2332: 	    $possible_collaborator =~ s/[\$\^\(\)]//g;
                   2333: 	    next if ($possible_collaborator eq '');
                   2334: 	    my ($co_name,$co_dom) = split(/\@|:/,$possible_collaborator);
                   2335: 	    $co_dom = $udom if (! defined($co_dom) || $co_dom =~ /^domain$/i);
                   2336: 	    next if ($co_name eq $uname && $co_dom eq $udom);
                   2337: 	    # Doing this grep allows 'fuzzy' specification
                   2338: 	    my @matches = grep(/^\Q$co_name\E:\Q$co_dom\E$/i, 
                   2339: 			       keys(%$classlist));
                   2340: 	    if (! scalar(@matches)) {
                   2341: 		push(@bad_collaborators, $possible_collaborator);
                   2342: 	    } else {
                   2343: 		push(@good_collaborators, @matches);
                   2344: 	    }
                   2345: 	}
                   2346: 	if (scalar(@good_collaborators) != 0) {
1.466     albertel 2347: 	    $result.='<br />'.&mt('Collaborators: ');
1.464     albertel 2348: 	    foreach my $name (@good_collaborators) {
                   2349: 		my ($lastname,$givenn) = split(/,/,$$fullname{$name});
                   2350: 		push(@col_fullnames, $givenn.' '.$lastname);
                   2351: 		$result.=$fullname->{$name}.'&nbsp; &nbsp; &nbsp;';
                   2352: 	    }
                   2353: 	    $result.='<br />'."\n";
1.466     albertel 2354: 	    my ($part)=split(/\./,$part);
1.464     albertel 2355: 	    $result.='<input type="hidden" name="collaborator'.$counter.
                   2356: 		'" value="'.$part.':'.(join ':',@good_collaborators).'" />'.
                   2357: 		"\n";
                   2358: 	}
                   2359: 	if (scalar(@bad_collaborators) > 0) {
1.466     albertel 2360: 	    $result.='<div class="LC_warning">';
1.464     albertel 2361: 	    $result.=&mt('This student has submitted [quant,_1,invalid collaborator]: [_2]',scalar(@bad_collaborators),join(', ',@bad_collaborators));
                   2362: 	    $result .= '</div>';
                   2363: 	}         
                   2364: 	if (scalar(@bad_collaborators > $ncol)) {
1.466     albertel 2365: 	    $result .= '<div class="LC_warning">';
1.464     albertel 2366: 	    $result .= &mt('This student has submitted too many '.
                   2367: 		'collaborators.  Maximum is [_1].',$ncol);
                   2368: 	    $result .= '</div>';
                   2369: 	}
                   2370:     }
                   2371:     return ($result,$fullname,\@col_fullnames);
                   2372: }
                   2373: 
1.44      ng       2374: #--- Retrieve the last submission for all the parts
1.38      ng       2375: sub get_last_submission {
1.119     ng       2376:     my ($returnhash)=@_;
1.46      ng       2377:     my (@string,$timestamp);
1.119     ng       2378:     if ($$returnhash{'version'}) {
1.46      ng       2379: 	my %lasthash=();
                   2380: 	my ($version);
1.119     ng       2381: 	for ($version=1;$version<=$$returnhash{'version'};$version++) {
1.397     albertel 2382: 	    foreach my $key (sort(split(/\:/,
                   2383: 					$$returnhash{$version.':keys'}))) {
                   2384: 		$lasthash{$key}=$$returnhash{$version.':'.$key};
                   2385: 		$timestamp = 
1.545     raeburn  2386: 		    &Apache::lonlocal::locallocaltime($$returnhash{$version.':timestamp'});
1.46      ng       2387: 	    }
                   2388: 	}
1.397     albertel 2389: 	foreach my $key (keys(%lasthash)) {
                   2390: 	    next if ($key !~ /\.submission$/);
                   2391: 
                   2392: 	    my ($partid,$foo) = split(/submission$/,$key);
                   2393: 	    my $draft  = $lasthash{$partid.'awarddetail'} eq 'DRAFT' ?
1.398     albertel 2394: 		'<span class="LC_warning">Draft Copy</span> ' : '';
1.397     albertel 2395: 	    push(@string, join(':', $key, $draft.$lasthash{$key}));
1.41      ng       2396: 	}
                   2397:     }
1.397     albertel 2398:     if (!@string) {
                   2399: 	$string[0] =
1.539     riegler  2400: 	    '<span class="LC_warning">'.&mt('Nothing submitted - no attempts.').'</span>';
1.397     albertel 2401:     }
                   2402:     return (\@string,\$timestamp);
1.38      ng       2403: }
1.35      ng       2404: 
1.44      ng       2405: #--- High light keywords, with style choosen by user.
1.38      ng       2406: sub keywords_highlight {
1.44      ng       2407:     my $string    = shift;
1.257     albertel 2408:     my $size      = $env{'form.kwsize'} eq '0' ? '' : 'size='.$env{'form.kwsize'};
                   2409:     my $styleon   = $env{'form.kwstyle'} eq ''  ? '' : $env{'form.kwstyle'};
1.41      ng       2410:     (my $styleoff = $styleon) =~ s/\</\<\//;
1.257     albertel 2411:     my @keylist   = split(/[,\s+]/,$env{'form.keywords'});
1.398     albertel 2412:     foreach my $keyword (@keylist) {
                   2413: 	$string =~ s/\b\Q$keyword\E(\b|\.)/<font color\=$env{'form.kwclr'} $size\>$styleon$keyword$styleoff<\/font>/gi;
1.41      ng       2414:     }
                   2415:     return $string;
1.38      ng       2416: }
1.36      ng       2417: 
1.44      ng       2418: #--- Called from submission routine
1.38      ng       2419: sub processHandGrade {
1.41      ng       2420:     my ($request) = shift;
1.324     albertel 2421:     my $symb   = &get_symb($request);
                   2422:     my (undef,undef,$url) = &Apache::lonnet::decode_symb($symb);
1.257     albertel 2423:     my $button = $env{'form.gradeOpt'};
                   2424:     my $ngrade = $env{'form.NCT'};
                   2425:     my $ntstu  = $env{'form.NTSTU'};
1.301     albertel 2426:     my $cdom   = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   2427:     my $cnum   = $env{'course.'.$env{'request.course.id'}.'.num'};
                   2428: 
1.44      ng       2429:     if ($button eq 'Save & Next') {
                   2430: 	my $ctr = 0;
                   2431: 	while ($ctr < $ngrade) {
1.257     albertel 2432: 	    my ($uname,$udom) = split(/:/,$env{'form.unamedom'.$ctr});
1.324     albertel 2433: 	    my ($errorflag,$pts,$wgt) = &saveHandGrade($request,$symb,$uname,$udom,$ctr);
1.71      ng       2434: 	    if ($errorflag eq 'no_score') {
                   2435: 		$ctr++;
                   2436: 		next;
                   2437: 	    }
1.104     albertel 2438: 	    if ($errorflag eq 'not_allowed') {
1.398     albertel 2439: 		$request->print("<span class=\"LC_warning\">Not allowed to modify grades for $uname:$udom</span>");
1.104     albertel 2440: 		$ctr++;
                   2441: 		next;
                   2442: 	    }
1.257     albertel 2443: 	    my $includemsg = $env{'form.includemsg'.$ctr};
1.44      ng       2444: 	    my ($subject,$message,$msgstatus) = ('','','');
1.418     albertel 2445: 	    my $restitle = &Apache::lonnet::gettitle($symb);
                   2446:             my ($feedurl,$showsymb) =
                   2447: 		&get_feedurl_and_symb($symb,$uname,$udom);
                   2448: 	    my $messagetail;
1.62      albertel 2449: 	    if ($includemsg =~ /savemsg|newmsg\Q$ctr\E/) {
1.298     www      2450: 		$subject = $env{'form.msgsub'} if ($includemsg =~ /msgsub/);
1.295     www      2451: 		unless ($subject=~/\w/) { $subject=&mt('Grading Feedback'); }
1.386     raeburn  2452: 		$subject.=' ['.$restitle.']';
1.44      ng       2453: 		my (@msgnum) = split(/,/,$includemsg);
                   2454: 		foreach (@msgnum) {
1.257     albertel 2455: 		    $message.=$env{'form.'.$_} if ($_ =~ /savemsg|newmsg/ && $_ ne '');
1.44      ng       2456: 		}
1.80      ng       2457: 		$message =&Apache::lonfeedback::clear_out_html($message);
1.298     www      2458: 		if ($env{'form.withgrades'.$ctr}) {
                   2459: 		    $message.="\n\nPoint".($pts > 1 ? 's':'').' awarded = '.$pts.' out of '.$wgt;
1.386     raeburn  2460: 		    $messagetail = " for <a href=\"".
1.418     albertel 2461: 		                   $feedurl."?symb=$showsymb\">$env{'form.probTitle'}</a>";
1.386     raeburn  2462: 		}
                   2463: 		$msgstatus = 
                   2464:                     &Apache::lonmsg::user_normal_msg($uname,$udom,$subject,
                   2465: 						     $message.$messagetail,
1.418     albertel 2466:                                                      undef,$feedurl,undef,
1.386     raeburn  2467:                                                      undef,undef,$showsymb,
                   2468:                                                      $restitle);
1.574     bisitz   2469: 		$request->print('<br />'.&mt('Sending message to [_1]',$uname.':'.$udom).': '.
1.296     www      2470: 				$msgstatus);
1.44      ng       2471: 	    }
1.257     albertel 2472: 	    if ($env{'form.collaborator'.$ctr}) {
1.155     albertel 2473: 		my @collabstrs=&Apache::loncommon::get_env_multiple("form.collaborator$ctr");
1.150     albertel 2474: 		foreach my $collabstr (@collabstrs) {
                   2475: 		    my ($part,@collaborators) = split(/:/,$collabstr);
1.310     banghart 2476: 		    foreach my $collaborator (@collaborators) {
1.150     albertel 2477: 			my ($errorflag,$pts,$wgt) = 
1.324     albertel 2478: 			    &saveHandGrade($request,$symb,$collaborator,$udom,$ctr,
1.257     albertel 2479: 					   $env{'form.unamedom'.$ctr},$part);
1.150     albertel 2480: 			if ($errorflag eq 'not_allowed') {
1.362     albertel 2481: 			    $request->print("<span class=\"LC_error\">".&mt('Not allowed to modify grades for [_1]',"$collaborator:$udom")."</span>");
1.150     albertel 2482: 			    next;
1.418     albertel 2483: 			} elsif ($message ne '') {
                   2484: 			    my ($baseurl,$showsymb) = 
                   2485: 				&get_feedurl_and_symb($symb,$collaborator,
                   2486: 						      $udom);
                   2487: 			    if ($env{'form.withgrades'.$ctr}) {
                   2488: 				$messagetail = " for <a href=\"".
1.386     raeburn  2489:                                     $baseurl."?symb=$showsymb\">$env{'form.probTitle'}</a>";
1.150     albertel 2490: 			    }
1.418     albertel 2491: 			    $msgstatus = 
                   2492: 				&Apache::lonmsg::user_normal_msg($collaborator,$udom,$subject,$message.$messagetail,undef,$baseurl,undef,undef,undef,$showsymb,$restitle);
1.104     albertel 2493: 			}
1.44      ng       2494: 		    }
                   2495: 		}
                   2496: 	    }
                   2497: 	    $ctr++;
                   2498: 	}
                   2499:     }
                   2500: 
1.257     albertel 2501:     if ($env{'form.handgrade'} eq 'yes') {
1.119     ng       2502: 	# Keywords sorted in alphabatical order
1.257     albertel 2503: 	my $loginuser = $env{'user.name'}.':'.$env{'user.domain'};
1.119     ng       2504: 	my %keyhash = ();
1.257     albertel 2505: 	$env{'form.keywords'}           =~ s/,\s{0,}|\s+/ /g;
                   2506: 	$env{'form.keywords'}           =~ s/^\s+|\s+$//;
                   2507: 	my (@keywords) = sort(split(/\s+/,$env{'form.keywords'}));
                   2508: 	$env{'form.keywords'} = join(' ',@keywords);
                   2509: 	$keyhash{$symb.'_keywords'}     = $env{'form.keywords'};
                   2510: 	$keyhash{$symb.'_subject'}      = $env{'form.msgsub'};
                   2511: 	$keyhash{$loginuser.'_kwclr'}   = $env{'form.kwclr'};
                   2512: 	$keyhash{$loginuser.'_kwsize'}  = $env{'form.kwsize'};
                   2513: 	$keyhash{$loginuser.'_kwstyle'} = $env{'form.kwstyle'};
1.119     ng       2514: 
                   2515: 	# message center - Order of message gets changed. Blank line is eliminated.
1.257     albertel 2516: 	# New messages are saved in env for the next student.
1.119     ng       2517: 	# All messages are saved in nohist_handgrade.db
                   2518: 	my ($ctr,$idx) = (1,1);
1.257     albertel 2519: 	while ($ctr <= $env{'form.savemsgN'}) {
                   2520: 	    if ($env{'form.savemsg'.$ctr} ne '') {
                   2521: 		$keyhash{$symb.'_savemsg'.$idx} = $env{'form.savemsg'.$ctr};
1.119     ng       2522: 		$idx++;
                   2523: 	    }
                   2524: 	    $ctr++;
1.41      ng       2525: 	}
1.119     ng       2526: 	$ctr = 0;
                   2527: 	while ($ctr < $ngrade) {
1.257     albertel 2528: 	    if ($env{'form.newmsg'.$ctr} ne '') {
                   2529: 		$keyhash{$symb.'_savemsg'.$idx} = $env{'form.newmsg'.$ctr};
                   2530: 		$env{'form.savemsg'.$idx} = $env{'form.newmsg'.$ctr};
1.119     ng       2531: 		$idx++;
                   2532: 	    }
                   2533: 	    $ctr++;
1.41      ng       2534: 	}
1.257     albertel 2535: 	$env{'form.savemsgN'} = --$idx;
                   2536: 	$keyhash{$symb.'_savemsgN'} = $env{'form.savemsgN'};
1.119     ng       2537: 	my $putresult = &Apache::lonnet::put
1.301     albertel 2538: 	    ('nohist_handgrade',\%keyhash,$cdom,$cnum);
1.41      ng       2539:     }
1.44      ng       2540:     # Called by Save & Refresh from Highlight Attribute Window
1.257     albertel 2541:     my (undef,undef,$fullname) = &getclasslist($env{'form.section'},'1');
                   2542:     if ($env{'form.refresh'} eq 'on') {
1.86      ng       2543: 	my ($ctr,$total) = (0,0);
                   2544: 	while ($ctr < $ngrade) {
1.257     albertel 2545: 	    $total++ if  $env{'form.unamedom'.$ctr} ne '';
1.86      ng       2546: 	    $ctr++;
                   2547: 	}
1.257     albertel 2548: 	$env{'form.NTSTU'}=$ngrade;
1.86      ng       2549: 	$ctr = 0;
                   2550: 	while ($ctr < $total) {
1.257     albertel 2551: 	    my $processUser = $env{'form.unamedom'.$ctr};
                   2552: 	    ($env{'form.student'},$env{'form.userdom'}) = split(/:/,$processUser);
                   2553: 	    $env{'form.fullname'} = $$fullname{$processUser};
1.86      ng       2554: 	    &submission($request,$ctr,$total-1);
1.41      ng       2555: 	    $ctr++;
                   2556: 	}
                   2557: 	return '';
                   2558:     }
1.36      ng       2559: 
1.121     ng       2560: # Go directly to grade student - from submission or link from chart page
1.120     ng       2561:     if ($button eq 'Grade Student') {
1.324     albertel 2562: 	(undef,undef,$env{'form.handgrade'},undef,undef) = &showResourceInfo($symb);
1.257     albertel 2563: 	my $processUser = $env{'form.unamedom'.$env{'form.studentNo'}};
                   2564: 	($env{'form.student'},$env{'form.userdom'}) = split(/:/,$processUser);
                   2565: 	$env{'form.fullname'} = $$fullname{$processUser};
1.120     ng       2566: 	&submission($request,0,0);
                   2567: 	return '';
                   2568:     }
                   2569: 
1.44      ng       2570:     # Get the next/previous one or group of students
1.257     albertel 2571:     my $firststu = $env{'form.unamedom0'};
                   2572:     my $laststu = $env{'form.unamedom'.($ngrade-1)};
1.119     ng       2573:     my $ctr = 2;
1.41      ng       2574:     while ($laststu eq '') {
1.257     albertel 2575: 	$laststu  = $env{'form.unamedom'.($ngrade-$ctr)};
1.41      ng       2576: 	$ctr++;
                   2577: 	$laststu = $firststu if ($ctr > $ngrade);
                   2578:     }
1.44      ng       2579: 
1.41      ng       2580:     my (@parsedlist,@nextlist);
                   2581:     my ($nextflg) = 0;
1.524     raeburn  2582:     foreach my $item (sort 
1.294     albertel 2583: 	     {
                   2584: 		 if (lc($$fullname{$a}) ne lc($$fullname{$b})) {
                   2585: 		     return (lc($$fullname{$a}) cmp lc($$fullname{$b}));
                   2586: 		 }
                   2587: 		 return $a cmp $b;
                   2588: 	     } (keys(%$fullname))) {
1.41      ng       2589: 	if ($nextflg == 1 && $button =~ /Next$/) {
1.524     raeburn  2590: 	    push(@parsedlist,$item);
1.41      ng       2591: 	}
1.524     raeburn  2592: 	$nextflg = 1 if ($item eq $laststu);
1.41      ng       2593: 	if ($button eq 'Previous') {
1.524     raeburn  2594: 	    last if ($item eq $firststu);
                   2595: 	    push(@parsedlist,$item);
1.41      ng       2596: 	}
                   2597:     }
                   2598:     $ctr = 0;
                   2599:     @parsedlist = reverse @parsedlist if ($button eq 'Previous');
1.324     albertel 2600:     my ($partlist) = &response_type($symb);
1.41      ng       2601:     foreach my $student (@parsedlist) {
1.257     albertel 2602: 	my $submitonly=$env{'form.submitonly'};
1.41      ng       2603: 	my ($uname,$udom) = split(/:/,$student);
1.301     albertel 2604: 	
                   2605: 	if ($submitonly eq 'queued') {
                   2606: 	    my %queue_status = 
                   2607: 		&Apache::bridgetask::get_student_status($symb,$cdom,$cnum,
                   2608: 							$udom,$uname);
                   2609: 	    next if (!defined($queue_status{'gradingqueue'}));
                   2610: 	}
                   2611: 
1.156     albertel 2612: 	if ($submitonly =~ /^(yes|graded|incorrect)$/) {
1.257     albertel 2613: #	    my %record = &Apache::lonnet::restore($symb,$env{'request.course.id'},$udom,$uname);
1.324     albertel 2614: 	    my %status=&student_gradeStatus($symb,$udom,$uname,$partlist);
1.145     albertel 2615: 	    my $submitted = 0;
1.248     albertel 2616: 	    my $ungraded = 0;
                   2617: 	    my $incorrect = 0;
1.524     raeburn  2618: 	    foreach my $item (keys(%status)) {
                   2619: 		$submitted = 1 if ($status{$item} ne 'nothing');
                   2620: 		$ungraded = 1 if ($status{$item} =~ /^ungraded/);
                   2621: 		$incorrect = 1 if ($status{$item} =~ /^incorrect/);
                   2622: 		my ($foo,$partid,$foo1) = split(/\./,$item);
1.145     albertel 2623: 		if ($status{'resource.'.$partid.'.submitted_by'} ne '') {
                   2624: 		    $submitted = 0;
                   2625: 		}
1.41      ng       2626: 	    }
1.156     albertel 2627: 	    next if (!$submitted && ($submitonly eq 'yes' ||
                   2628: 				     $submitonly eq 'incorrect' ||
                   2629: 				     $submitonly eq 'graded'));
1.248     albertel 2630: 	    next if (!$ungraded && ($submitonly eq 'graded'));
                   2631: 	    next if (!$incorrect && $submitonly eq 'incorrect');
1.41      ng       2632: 	}
1.524     raeburn  2633: 	push(@nextlist,$student) if ($ctr < $ntstu);
1.129     ng       2634: 	last if ($ctr == $ntstu);
1.41      ng       2635: 	$ctr++;
                   2636:     }
1.36      ng       2637: 
1.41      ng       2638:     $ctr = 0;
                   2639:     my $total = scalar(@nextlist)-1;
1.39      ng       2640: 
1.524     raeburn  2641:     foreach (sort(@nextlist)) {
1.41      ng       2642: 	my ($uname,$udom,$submitter) = split(/:/);
1.257     albertel 2643: 	$env{'form.student'}  = $uname;
                   2644: 	$env{'form.userdom'}  = $udom;
                   2645: 	$env{'form.fullname'} = $$fullname{$_};
1.41      ng       2646: 	&submission($request,$ctr,$total);
                   2647: 	$ctr++;
                   2648:     }
                   2649:     if ($total < 0) {
1.485     albertel 2650: 	my $the_end = '<h3><span class="LC_info">'.&mt('LON-CAPA User Message').'</span></h3><br />'."\n";
                   2651: 	$the_end.=&mt('<b>Message: </b> No more students for this section or class.').'<br /><br />'."\n";
                   2652: 	$the_end.=&mt('Click on the button below to return to the grading menu.').'<br /><br />'."\n";
1.324     albertel 2653: 	$the_end.=&show_grading_menu_form($symb);
1.41      ng       2654: 	$request->print($the_end);
                   2655:     }
                   2656:     return '';
1.38      ng       2657: }
1.36      ng       2658: 
1.44      ng       2659: #---- Save the score and award for each student, if changed
1.38      ng       2660: sub saveHandGrade {
1.324     albertel 2661:     my ($request,$symb,$stuname,$domain,$newflg,$submitter,$part) = @_;
1.342     banghart 2662:     my @version_parts;
1.104     albertel 2663:     my $usec = &Apache::lonnet::getsection($domain,$stuname,
1.257     albertel 2664: 					   $env{'request.course.id'});
1.104     albertel 2665:     if (!&canmodify($usec)) { return('not_allowed'); }
1.337     banghart 2666:     my %record = &Apache::lonnet::restore($symb,$env{'request.course.id'},$domain,$stuname);
1.251     banghart 2667:     my @parts_graded;
1.77      ng       2668:     my %newrecord  = ();
                   2669:     my ($pts,$wgt) = ('','');
1.269     raeburn  2670:     my %aggregate = ();
                   2671:     my $aggregateflag = 0;
1.301     albertel 2672:     my @parts = split(/:/,$env{'form.partlist'.$newflg});
                   2673:     foreach my $new_part (@parts) {
1.337     banghart 2674: 	#collaborator ($submi may vary for different parts
1.259     banghart 2675: 	if ($submitter && $new_part ne $part) { next; }
                   2676: 	my $dropMenu = $env{'form.GD_SEL'.$newflg.'_'.$new_part};
1.125     ng       2677: 	if ($dropMenu eq 'excused') {
1.259     banghart 2678: 	    if ($record{'resource.'.$new_part.'.solved'} ne 'excused') {
                   2679: 		$newrecord{'resource.'.$new_part.'.solved'} = 'excused';
                   2680: 		if (exists($record{'resource.'.$new_part.'.awarded'})) {
                   2681: 		    $newrecord{'resource.'.$new_part.'.awarded'} = '';
1.58      albertel 2682: 		}
1.364     banghart 2683: 	        $newrecord{'resource.'.$new_part.'.regrader'}="$env{'user.name'}:$env{'user.domain'}";
1.58      albertel 2684: 	    }
1.125     ng       2685: 	} elsif ($dropMenu eq 'reset status'
1.259     banghart 2686: 		 && exists($record{'resource.'.$new_part.'.solved'})) { #don't bother if no old records -> no attempts
1.524     raeburn  2687: 	    foreach my $key (keys(%record)) {
1.259     banghart 2688: 		if ($key=~/^resource\.\Q$new_part\E\./) { $newrecord{$key} = ''; }
1.197     albertel 2689: 	    }
1.259     banghart 2690: 	    $newrecord{'resource.'.$new_part.'.regrader'}=
1.257     albertel 2691: 		"$env{'user.name'}:$env{'user.domain'}";
1.270     albertel 2692:             my $totaltries = $record{'resource.'.$part.'.tries'};
                   2693: 
                   2694:             my %last_resets = &get_last_resets($symb,$env{'request.course.id'},
                   2695: 					       [$new_part]);
                   2696:             my $aggtries =$totaltries;
1.269     raeburn  2697:             if ($last_resets{$new_part}) {
1.270     albertel 2698:                 $aggtries = &get_num_tries(\%record,$last_resets{$new_part},
                   2699: 					   $new_part);
1.269     raeburn  2700:             }
1.270     albertel 2701: 
                   2702:             my $solvedstatus = $record{'resource.'.$new_part.'.solved'};
1.269     raeburn  2703:             if ($aggtries > 0) {
1.327     albertel 2704:                 &decrement_aggs($symb,$new_part,\%aggregate,$aggtries,$totaltries,$solvedstatus);
1.269     raeburn  2705:                 $aggregateflag = 1;
                   2706:             }
1.125     ng       2707: 	} elsif ($dropMenu eq '') {
1.259     banghart 2708: 	    $pts = ($env{'form.GD_BOX'.$newflg.'_'.$new_part} ne '' ? 
                   2709: 		    $env{'form.GD_BOX'.$newflg.'_'.$new_part} : 
                   2710: 		    $env{'form.RADVAL'.$newflg.'_'.$new_part});
                   2711: 	    if ($pts eq '' && $env{'form.GD_SEL'.$newflg.'_'.$new_part} eq '') {
1.153     albertel 2712: 		next;
                   2713: 	    }
1.259     banghart 2714: 	    $wgt = $env{'form.WGT'.$newflg.'_'.$new_part} eq '' ? 1 : 
                   2715: 		$env{'form.WGT'.$newflg.'_'.$new_part};
1.41      ng       2716: 	    my $partial= $pts/$wgt;
1.259     banghart 2717: 	    if ($partial eq $record{'resource.'.$new_part.'.awarded'}) {
1.153     albertel 2718: 		#do not update score for part if not changed.
1.346     banghart 2719:                 &handback_files($request,$symb,$stuname,$domain,$newflg,$new_part,\%newrecord);
1.153     albertel 2720: 		next;
1.251     banghart 2721: 	    } else {
1.524     raeburn  2722: 	        push(@parts_graded,$new_part);
1.153     albertel 2723: 	    }
1.259     banghart 2724: 	    if ($record{'resource.'.$new_part.'.awarded'} ne $partial) {
                   2725: 		$newrecord{'resource.'.$new_part.'.awarded'}  = $partial;
1.153     albertel 2726: 	    }
1.259     banghart 2727: 	    my $reckey = 'resource.'.$new_part.'.solved';
1.41      ng       2728: 	    if ($partial == 0) {
1.153     albertel 2729: 		if ($record{$reckey} ne 'incorrect_by_override') {
                   2730: 		    $newrecord{$reckey} = 'incorrect_by_override';
                   2731: 		}
1.41      ng       2732: 	    } else {
1.153     albertel 2733: 		if ($record{$reckey} ne 'correct_by_override') {
                   2734: 		    $newrecord{$reckey} = 'correct_by_override';
                   2735: 		}
                   2736: 	    }	    
                   2737: 	    if ($submitter && 
1.259     banghart 2738: 		($record{'resource.'.$new_part.'.submitted_by'} ne $submitter)) {
                   2739: 		$newrecord{'resource.'.$new_part.'.submitted_by'} = $submitter;
1.41      ng       2740: 	    }
1.259     banghart 2741: 	    $newrecord{'resource.'.$new_part.'.regrader'}=
1.257     albertel 2742: 		"$env{'user.name'}:$env{'user.domain'}";
1.41      ng       2743: 	}
1.259     banghart 2744: 	# unless problem has been graded, set flag to version the submitted files
1.305     banghart 2745: 	unless ($record{'resource.'.$new_part.'.solved'} =~ /^correct_/  || 
                   2746: 	        $record{'resource.'.$new_part.'.solved'} eq 'incorrect_by_override' ||
                   2747: 	        $dropMenu eq 'reset status')
                   2748: 	   {
1.524     raeburn  2749: 	    push(@version_parts,$new_part);
1.259     banghart 2750: 	}
1.41      ng       2751:     }
1.301     albertel 2752:     my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   2753:     my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   2754: 
1.344     albertel 2755:     if (%newrecord) {
                   2756:         if (@version_parts) {
1.364     banghart 2757:             my @changed_keys = &version_portfiles(\%record, \@parts_graded, 
                   2758:                                 $env{'request.course.id'}, $symb, $domain, $stuname, \@version_parts);
1.344     albertel 2759: 	    @newrecord{@changed_keys} = @record{@changed_keys};
1.367     albertel 2760: 	    foreach my $new_part (@version_parts) {
                   2761: 		&handback_files($request,$symb,$stuname,$domain,$newflg,
                   2762: 				$new_part,\%newrecord);
                   2763: 	    }
1.259     banghart 2764:         }
1.44      ng       2765: 	&Apache::lonnet::cstore(\%newrecord,$symb,
1.257     albertel 2766: 				$env{'request.course.id'},$domain,$stuname);
1.380     albertel 2767: 	&check_and_remove_from_queue(\@parts,\%record,\%newrecord,$symb,
                   2768: 				     $cdom,$cnum,$domain,$stuname);
1.41      ng       2769:     }
1.269     raeburn  2770:     if ($aggregateflag) {
                   2771:         &Apache::lonnet::cinc('nohist_resourcetracker',\%aggregate,
1.301     albertel 2772: 			      $cdom,$cnum);
1.269     raeburn  2773:     }
1.301     albertel 2774:     return ('',$pts,$wgt);
1.36      ng       2775: }
1.322     albertel 2776: 
1.380     albertel 2777: sub check_and_remove_from_queue {
                   2778:     my ($parts,$record,$newrecord,$symb,$cdom,$cnum,$domain,$stuname) = @_;
                   2779:     my @ungraded_parts;
                   2780:     foreach my $part (@{$parts}) {
                   2781: 	if (    $record->{   'resource.'.$part.'.awarded'} eq ''
                   2782: 	     && $record->{   'resource.'.$part.'.solved' } ne 'excused'
                   2783: 	     && $newrecord->{'resource.'.$part.'.awarded'} eq ''
                   2784: 	     && $newrecord->{'resource.'.$part.'.solved' } ne 'excused'
                   2785: 		) {
                   2786: 	    push(@ungraded_parts, $part);
                   2787: 	}
                   2788:     }
                   2789:     if ( !@ungraded_parts ) {
                   2790: 	&Apache::bridgetask::remove_from_queue('gradingqueue',$symb,$cdom,
                   2791: 					       $cnum,$domain,$stuname);
                   2792:     }
                   2793: }
                   2794: 
1.337     banghart 2795: sub handback_files {
                   2796:     my ($request,$symb,$stuname,$domain,$newflg,$new_part,$newrecord) = @_;
1.517     raeburn  2797:     my $portfolio_root = '/userfiles/portfolio';
1.359     www      2798:     my ($partlist,$handgrade,$responseType) = &response_type($symb);
1.375     albertel 2799: 
                   2800:     my @part_response_id = &flatten_responseType($responseType);
                   2801:     foreach my $part_response_id (@part_response_id) {
                   2802:     	my ($part_id,$resp_id) = @{ $part_response_id };
                   2803: 	my $part_resp = join('_',@{ $part_response_id });
1.337     banghart 2804:             if (($env{'form.'.$newflg.'_'.$part_resp.'_returndoc1'}) && ($new_part == $part_id)) {
                   2805:                 # if multiple files are uploaded names will be 'returndoc2','returndoc3'
                   2806:                 my $file_counter = 1;
1.367     albertel 2807: 		my $file_msg;
1.337     banghart 2808:                 while ($env{'form.'.$newflg.'_'.$part_resp.'_returndoc'.$file_counter}) {
                   2809:                     my $fname=$env{'form.'.$newflg.'_'.$part_resp.'_returndoc'.$file_counter.'.filename'};
1.338     banghart 2810:                     my ($directory,$answer_file) = 
                   2811:                         ($env{'form.'.$newflg.'_'.$part_resp.'_origdoc'.$file_counter} =~ /^(.*?)([^\/]*)$/);
                   2812:                     my ($answer_name,$answer_ver,$answer_ext) =
                   2813: 		        &file_name_version_ext($answer_file);
1.355     banghart 2814: 		    my ($portfolio_path) = ($directory =~ /^.+$stuname\/portfolio(.*)/);
1.517     raeburn  2815:                     my $getpropath = 1;
                   2816: 		    my @dir_list = &Apache::lonnet::dirlist($portfolio_root.$portfolio_path,$domain,$stuname,$getpropath);
1.338     banghart 2817: 		    my $version = &get_next_version($answer_name, $answer_ext, \@dir_list);
1.355     banghart 2818:                     # fix file name
                   2819:                     my ($save_file_name) = (($directory.$answer_name.".$version.".$answer_ext) =~ /^.+\/${stuname}\/(.*)/);
                   2820:                     my $result=&Apache::lonnet::finishuserfileupload($stuname,$domain,
                   2821:             	                                $newflg.'_'.$part_resp.'_returndoc'.$file_counter,
                   2822:             	                                $save_file_name);
1.337     banghart 2823:                     if ($result !~ m|^/uploaded/|) {
1.536     raeburn  2824:                         $request->print('<br /><span class="LC_error">'.
                   2825:                             &mt('An error occurred ([_1]) while trying to upload [_2].',
                   2826:                                 $result,$newflg.'_'.$part_resp.'_returndoc'.$file_counter).
                   2827:                                         '</span>');
1.356     banghart 2828:                     } else {
1.360     banghart 2829:                         # mark the file as read only
                   2830:                         my @files = ($save_file_name);
1.372     albertel 2831:                         my @what = ($symb,$env{'request.course.id'},'handback');
1.360     banghart 2832:                         &Apache::lonnet::mark_as_readonly($domain,$stuname,\@files,\@what);
1.367     albertel 2833: 			if (exists($$newrecord{"resource.$new_part.$resp_id.handback"})) {
                   2834: 			    $$newrecord{"resource.$new_part.$resp_id.handback"}.=',';
                   2835: 			}
                   2836:                         $$newrecord{"resource.$new_part.$resp_id.handback"} .= $save_file_name;
                   2837: 			$file_msg.= "\n".'<br /><span class="LC_filename"><a href="/uploaded/'."$domain/$stuname/".$save_file_name.'">'.$save_file_name."</a></span><br />";
                   2838: 
1.337     banghart 2839:                     }
                   2840:                     $request->print("<br />".$fname." will be the uploaded file name");
1.354     albertel 2841:                     $request->print(" ".$env{'form.'.$newflg.'_'.$part_resp.'_origdoc'.$file_counter});
1.337     banghart 2842:                     $file_counter++;
                   2843:                 }
1.367     albertel 2844: 		my $subject = "File Handed Back by Instructor ";
                   2845: 		my $message = "A file has been returned that was originally submitted in reponse to: <br />";
                   2846: 		$message .= "<strong>".&Apache::lonnet::gettitle($symb)."</strong><br />";
                   2847: 		$message .= ' The returned file(s) are named: '. $file_msg;
                   2848: 		$message .= " and can be found in your portfolio space.";
1.418     albertel 2849: 		my ($feedurl,$showsymb) = 
                   2850: 		    &get_feedurl_and_symb($symb,$domain,$stuname);
1.386     raeburn  2851:                 my $restitle = &Apache::lonnet::gettitle($symb);
                   2852: 		my $msgstatus = 
                   2853:                    &Apache::lonmsg::user_normal_msg($stuname,$domain,$subject.
                   2854: 			 ' (File Returned) ['.$restitle.']',$message,undef,
1.418     albertel 2855:                          $feedurl,undef,undef,undef,$showsymb,$restitle);
1.337     banghart 2856:             }
                   2857:         }
1.338     banghart 2858:     return;
1.337     banghart 2859: }
                   2860: 
1.418     albertel 2861: sub get_feedurl_and_symb {
                   2862:     my ($symb,$uname,$udom) = @_;
                   2863:     my (undef,undef,$url) = &Apache::lonnet::decode_symb($symb);
                   2864:     $url = &Apache::lonnet::clutter($url);
                   2865:     my $encrypturl=&Apache::lonnet::EXT('resource.0.encrypturl',
                   2866: 					$symb,$udom,$uname);
                   2867:     if ($encrypturl =~ /^yes$/i) {
                   2868: 	&Apache::lonenc::encrypted(\$url,1);
                   2869: 	&Apache::lonenc::encrypted(\$symb,1);
                   2870:     }
                   2871:     return ($url,$symb);
                   2872: }
                   2873: 
1.313     banghart 2874: sub get_submitted_files {
                   2875:     my ($udom,$uname,$partid,$respid,$record) = @_;
                   2876:     my @files;
                   2877:     if ($$record{"resource.$partid.$respid.portfiles"}) {
                   2878:         my $file_url = '/uploaded/'.$udom.'/'.$uname.'/portfolio';
                   2879:         foreach my $file (split(',',$$record{"resource.$partid.$respid.portfiles"})) {
                   2880:     	    push(@files,$file_url.$file);
                   2881:         }
                   2882:     }
                   2883:     if ($$record{"resource.$partid.$respid.uploadedurl"}) {
                   2884:         push(@files,$$record{"resource.$partid.$respid.uploadedurl"});
                   2885:     }
                   2886:     return (\@files);
                   2887: }
1.322     albertel 2888: 
1.269     raeburn  2889: # ----------- Provides number of tries since last reset.
                   2890: sub get_num_tries {
                   2891:     my ($record,$last_reset,$part) = @_;
                   2892:     my $timestamp = '';
                   2893:     my $num_tries = 0;
                   2894:     if ($$record{'version'}) {
                   2895:         for (my $version=$$record{'version'};$version>=1;$version--) {
                   2896:             if (exists($$record{$version.':resource.'.$part.'.solved'})) {
                   2897:                 $timestamp = $$record{$version.':timestamp'};
                   2898:                 if ($timestamp > $last_reset) {
                   2899:                     $num_tries ++;
                   2900:                 } else {
                   2901:                     last;
                   2902:                 }
                   2903:             }
                   2904:         }
                   2905:     }
                   2906:     return $num_tries;
                   2907: }
                   2908: 
                   2909: # ----------- Determine decrements required in aggregate totals 
                   2910: sub decrement_aggs {
                   2911:     my ($symb,$part,$aggregate,$aggtries,$totaltries,$solvedstatus) = @_;
                   2912:     my %decrement = (
                   2913:                         attempts => 0,
                   2914:                         users => 0,
                   2915:                         correct => 0
                   2916:                     );
                   2917:     $decrement{'attempts'} = $aggtries;
                   2918:     if ($solvedstatus =~ /^correct/) {
                   2919:         $decrement{'correct'} = 1;
                   2920:     }
                   2921:     if ($aggtries == $totaltries) {
                   2922:         $decrement{'users'} = 1;
                   2923:     }
1.524     raeburn  2924:     foreach my $type (keys(%decrement)) {
1.269     raeburn  2925:         $$aggregate{$symb."\0".$part."\0".$type} = -$decrement{$type};
                   2926:     }
                   2927:     return;
                   2928: }
                   2929: 
                   2930: # ----------- Determine timestamps for last reset of aggregate totals for parts  
                   2931: sub get_last_resets {
1.270     albertel 2932:     my ($symb,$courseid,$partids) =@_;
                   2933:     my %last_resets;
1.269     raeburn  2934:     my $cdom = $env{'course.'.$courseid.'.domain'};
                   2935:     my $cname = $env{'course.'.$courseid.'.num'};
1.271     albertel 2936:     my @keys;
                   2937:     foreach my $part (@{$partids}) {
                   2938: 	push(@keys,"$symb\0$part\0resettime");
                   2939:     }
                   2940:     my %results=&Apache::lonnet::get('nohist_resourcetracker',\@keys,
                   2941: 				     $cdom,$cname);
                   2942:     foreach my $part (@{$partids}) {
                   2943: 	$last_resets{$part}=$results{"$symb\0$part\0resettime"};
1.269     raeburn  2944:     }
1.270     albertel 2945:     return %last_resets;
1.269     raeburn  2946: }
                   2947: 
1.251     banghart 2948: # ----------- Handles creating versions for portfolio files as answers
                   2949: sub version_portfiles {
1.343     banghart 2950:     my ($record, $parts_graded, $courseid, $symb, $domain, $stu_name, $v_flag) = @_;
1.263     banghart 2951:     my $version_parts = join('|',@$v_flag);
1.343     banghart 2952:     my @returned_keys;
1.255     banghart 2953:     my $parts = join('|', @$parts_graded);
1.517     raeburn  2954:     my $portfolio_root = '/userfiles/portfolio';
1.277     albertel 2955:     foreach my $key (keys(%$record)) {
1.259     banghart 2956:         my $new_portfiles;
1.263     banghart 2957:         if ($key =~ /^resource\.($version_parts)\./ && $key =~ /\.portfiles$/ ) {
1.342     banghart 2958:             my @versioned_portfiles;
1.367     albertel 2959:             my @portfiles = split(/\s*,\s*/,$$record{$key});
1.252     banghart 2960:             foreach my $file (@portfiles) {
1.306     banghart 2961:                 &Apache::lonnet::unmark_as_readonly($domain,$stu_name,[$symb,$env{'request.course.id'}],$file);
1.304     albertel 2962:                 my ($directory,$answer_file) =($file =~ /^(.*?)([^\/]*)$/);
                   2963: 		my ($answer_name,$answer_ver,$answer_ext) =
                   2964: 		    &file_name_version_ext($answer_file);
1.517     raeburn  2965:                 my $getpropath = 1;    
                   2966:                 my @dir_list = &Apache::lonnet::dirlist($portfolio_root.$directory,$domain,$stu_name,$getpropath);
1.342     banghart 2967:                 my $version = &get_next_version($answer_name, $answer_ext, \@dir_list);
1.306     banghart 2968:                 my $new_answer = &version_selected_portfile($domain, $stu_name, $directory, $answer_file, $version);
                   2969:                 if ($new_answer ne 'problem getting file') {
1.342     banghart 2970:                     push(@versioned_portfiles, $directory.$new_answer);
1.306     banghart 2971:                     &Apache::lonnet::mark_as_readonly($domain,$stu_name,
1.367     albertel 2972:                         [$directory.$new_answer],
1.306     banghart 2973:                         [$symb,$env{'request.course.id'},'graded']);
1.259     banghart 2974:                 }
1.252     banghart 2975:             }
1.343     banghart 2976:             $$record{$key} = join(',',@versioned_portfiles);
                   2977:             push(@returned_keys,$key);
1.251     banghart 2978:         }
                   2979:     } 
1.343     banghart 2980:     return (@returned_keys);   
1.305     banghart 2981: }
                   2982: 
1.307     banghart 2983: sub get_next_version {
1.341     banghart 2984:     my ($answer_name, $answer_ext, $dir_list) = @_;
1.307     banghart 2985:     my $version;
                   2986:     foreach my $row (@$dir_list) {
                   2987:         my ($file) = split(/\&/,$row,2);
                   2988:         my ($file_name,$file_version,$file_ext) =
                   2989: 	    &file_name_version_ext($file);
                   2990:         if (($file_name eq $answer_name) && 
                   2991: 	    ($file_ext eq $answer_ext)) {
                   2992:                 # gets here if filename and extension match, regardless of version
                   2993:                 if ($file_version ne '') {
                   2994:                 # a versioned file is found  so save it for later
                   2995:                 if ($file_version > $version) {
                   2996: 		    $version = $file_version;
                   2997: 	        }
                   2998:             }
                   2999:         }
                   3000:     } 
                   3001:     $version ++;
                   3002:     return($version);
                   3003: }
                   3004: 
1.305     banghart 3005: sub version_selected_portfile {
1.306     banghart 3006:     my ($domain,$stu_name,$directory,$file_name,$version) = @_;
                   3007:     my ($answer_name,$answer_ver,$answer_ext) =
                   3008:         &file_name_version_ext($file_name);
                   3009:     my $new_answer;
                   3010:     $env{'form.copy'} = &Apache::lonnet::getfile("/uploaded/$domain/$stu_name/portfolio$directory$file_name");
                   3011:     if($env{'form.copy'} eq '-1') {
                   3012:         $new_answer = 'problem getting file';
                   3013:     } else {
                   3014:         $new_answer = $answer_name.'.'.$version.'.'.$answer_ext;
                   3015:         my $copy_result = &Apache::lonnet::finishuserfileupload(
                   3016:                             $stu_name,$domain,'copy',
                   3017: 		        '/portfolio'.$directory.$new_answer);
                   3018:     }    
                   3019:     return ($new_answer);
1.251     banghart 3020: }
                   3021: 
1.304     albertel 3022: sub file_name_version_ext {
                   3023:     my ($file)=@_;
                   3024:     my @file_parts = split(/\./, $file);
                   3025:     my ($name,$version,$ext);
                   3026:     if (@file_parts > 1) {
                   3027: 	$ext=pop(@file_parts);
                   3028: 	if (@file_parts > 1 && $file_parts[-1] =~ /^\d+$/) {
                   3029: 	    $version=pop(@file_parts);
                   3030: 	}
                   3031: 	$name=join('.',@file_parts);
                   3032:     } else {
                   3033: 	$name=join('.',@file_parts);
                   3034:     }
                   3035:     return($name,$version,$ext);
                   3036: }
                   3037: 
1.44      ng       3038: #--------------------------------------------------------------------------------------
                   3039: #
                   3040: #-------------------------- Next few routines handles grading by section or whole class
                   3041: #
                   3042: #--- Javascript to handle grading by section or whole class
1.42      ng       3043: sub viewgrades_js {
                   3044:     my ($request) = shift;
                   3045: 
1.539     riegler  3046:     my $alertmsg = &mt('A number equal or greater than 0 is expected. Entered value = ');
1.41      ng       3047:     $request->print(<<VIEWJAVASCRIPT);
                   3048: <script type="text/javascript" language="javascript">
1.45      ng       3049:    function writePoint(partid,weight,point) {
1.125     ng       3050: 	var radioButton = document.classgrade["RADVAL_"+partid];
                   3051: 	var textbox = document.classgrade["TEXTVAL_"+partid];
1.42      ng       3052: 	if (point == "textval") {
1.125     ng       3053: 	    point = document.classgrade["TEXTVAL_"+partid].value;
1.109     matthew  3054: 	    if (isNaN(point) || parseFloat(point) < 0) {
1.539     riegler  3055: 		alert("$alertmsg"+parseFloat(point));
1.42      ng       3056: 		var resetbox = false;
                   3057: 		for (var i=0; i<radioButton.length; i++) {
                   3058: 		    if (radioButton[i].checked) {
                   3059: 			textbox.value = i;
                   3060: 			resetbox = true;
                   3061: 		    }
                   3062: 		}
                   3063: 		if (!resetbox) {
                   3064: 		    textbox.value = "";
                   3065: 		}
                   3066: 		return;
                   3067: 	    }
1.109     matthew  3068: 	    if (parseFloat(point) > parseFloat(weight)) {
                   3069: 		var resp = confirm("You entered a value ("+parseFloat(point)+
1.44      ng       3070: 				   ") greater than the weight for the part. Accept?");
                   3071: 		if (resp == false) {
                   3072: 		    textbox.value = "";
                   3073: 		    return;
                   3074: 		}
                   3075: 	    }
1.42      ng       3076: 	    for (var i=0; i<radioButton.length; i++) {
                   3077: 		radioButton[i].checked=false;
1.109     matthew  3078: 		if (parseFloat(point) == i) {
1.42      ng       3079: 		    radioButton[i].checked=true;
                   3080: 		}
                   3081: 	    }
1.41      ng       3082: 
1.42      ng       3083: 	} else {
1.125     ng       3084: 	    textbox.value = parseFloat(point);
1.42      ng       3085: 	}
1.41      ng       3086: 	for (i=0;i<document.classgrade.total.value;i++) {
1.125     ng       3087: 	    var user = document.classgrade["ctr"+i].value;
1.289     albertel 3088: 	    user = user.replace(new RegExp(':', 'g'),"_");
1.125     ng       3089: 	    var scorename = document.classgrade["GD_"+user+"_"+partid+"_awarded"];
                   3090: 	    var saveval   = document.classgrade["GD_"+user+"_"+partid+"_solved_s"].value;
                   3091: 	    var selname   = document.classgrade["GD_"+user+"_"+partid+"_solved"];
1.42      ng       3092: 	    if (saveval != "correct") {
                   3093: 		scorename.value = point;
1.43      ng       3094: 		if (selname[0].selected != true) {
                   3095: 		    selname[0].selected = true;
                   3096: 		}
1.42      ng       3097: 	    }
                   3098: 	}
1.125     ng       3099: 	document.classgrade["SELVAL_"+partid][0].selected = true;
1.42      ng       3100:     }
                   3101: 
                   3102:     function writeRadText(partid,weight) {
1.125     ng       3103: 	var selval   = document.classgrade["SELVAL_"+partid];
                   3104: 	var radioButton = document.classgrade["RADVAL_"+partid];
1.265     www      3105:         var override = document.classgrade["FORCE_"+partid].checked;
1.125     ng       3106: 	var textbox = document.classgrade["TEXTVAL_"+partid];
                   3107: 	if (selval[1].selected || selval[2].selected) {
1.42      ng       3108: 	    for (var i=0; i<radioButton.length; i++) {
                   3109: 		radioButton[i].checked=false;
                   3110: 
                   3111: 	    }
                   3112: 	    textbox.value = "";
                   3113: 
                   3114: 	    for (i=0;i<document.classgrade.total.value;i++) {
1.125     ng       3115: 		var user = document.classgrade["ctr"+i].value;
1.289     albertel 3116: 		user = user.replace(new RegExp(':', 'g'),"_");
1.125     ng       3117: 		var scorename = document.classgrade["GD_"+user+"_"+partid+"_awarded"];
                   3118: 		var saveval   = document.classgrade["GD_"+user+"_"+partid+"_solved_s"].value;
                   3119: 		var selname   = document.classgrade["GD_"+user+"_"+partid+"_solved"];
1.265     www      3120: 		if ((saveval != "correct") || override) {
1.42      ng       3121: 		    scorename.value = "";
1.125     ng       3122: 		    if (selval[1].selected) {
                   3123: 			selname[1].selected = true;
                   3124: 		    } else {
                   3125: 			selname[2].selected = true;
                   3126: 			if (Number(document.classgrade["GD_"+user+"_"+partid+"_tries"].value)) 
                   3127: 			{document.classgrade["GD_"+user+"_"+partid+"_tries"].value = '0';}
                   3128: 		    }
1.42      ng       3129: 		}
                   3130: 	    }
1.43      ng       3131: 	} else {
                   3132: 	    for (i=0;i<document.classgrade.total.value;i++) {
1.125     ng       3133: 		var user = document.classgrade["ctr"+i].value;
1.289     albertel 3134: 		user = user.replace(new RegExp(':', 'g'),"_");
1.125     ng       3135: 		var scorename = document.classgrade["GD_"+user+"_"+partid+"_awarded"];
                   3136: 		var saveval   = document.classgrade["GD_"+user+"_"+partid+"_solved_s"].value;
                   3137: 		var selname   = document.classgrade["GD_"+user+"_"+partid+"_solved"];
1.265     www      3138: 		if ((saveval != "correct") || override) {
1.125     ng       3139: 		    scorename.value = document.classgrade["GD_"+user+"_"+partid+"_awarded_s"].value;
1.43      ng       3140: 		    selname[0].selected = true;
                   3141: 		}
                   3142: 	    }
                   3143: 	}	    
1.42      ng       3144:     }
                   3145: 
                   3146:     function changeSelect(partid,user) {
1.125     ng       3147: 	var selval = document.classgrade["GD_"+user+'_'+partid+"_solved"];
                   3148: 	var textbox = document.classgrade["GD_"+user+'_'+partid+"_awarded"];
1.44      ng       3149: 	var point  = textbox.value;
1.125     ng       3150: 	var weight = document.classgrade["weight_"+partid].value;
1.44      ng       3151: 
1.109     matthew  3152: 	if (isNaN(point) || parseFloat(point) < 0) {
1.539     riegler  3153: 	    alert("$alertmsg"+parseFloat(point));
1.44      ng       3154: 	    textbox.value = "";
                   3155: 	    return;
                   3156: 	}
1.109     matthew  3157: 	if (parseFloat(point) > parseFloat(weight)) {
                   3158: 	    var resp = confirm("You entered a value ("+parseFloat(point)+
1.44      ng       3159: 			       ") greater than the weight of the part. Accept?");
                   3160: 	    if (resp == false) {
                   3161: 		textbox.value = "";
                   3162: 		return;
                   3163: 	    }
                   3164: 	}
1.42      ng       3165: 	selval[0].selected = true;
                   3166:     }
                   3167: 
                   3168:     function changeOneScore(partid,user) {
1.125     ng       3169: 	var selval = document.classgrade["GD_"+user+'_'+partid+"_solved"];
                   3170: 	if (selval[1].selected || selval[2].selected) {
                   3171: 	    document.classgrade["GD_"+user+'_'+partid+"_awarded"].value = "";
                   3172: 	    if (selval[2].selected) {
                   3173: 		document.classgrade["GD_"+user+'_'+partid+"_tries"].value = "0";
                   3174: 	    }
1.269     raeburn  3175:         }
1.42      ng       3176:     }
                   3177: 
                   3178:     function resetEntry(numpart) {
                   3179: 	for (ctpart=0;ctpart<numpart;ctpart++) {
1.125     ng       3180: 	    var partid = document.classgrade["partid_"+ctpart].value;
                   3181: 	    var radioButton = document.classgrade["RADVAL_"+partid];
                   3182: 	    var textbox = document.classgrade["TEXTVAL_"+partid];
                   3183: 	    var selval  = document.classgrade["SELVAL_"+partid];
1.42      ng       3184: 	    for (var i=0; i<radioButton.length; i++) {
                   3185: 		radioButton[i].checked=false;
                   3186: 
                   3187: 	    }
                   3188: 	    textbox.value = "";
                   3189: 	    selval[0].selected = true;
                   3190: 
                   3191: 	    for (i=0;i<document.classgrade.total.value;i++) {
1.125     ng       3192: 		var user = document.classgrade["ctr"+i].value;
1.289     albertel 3193: 		user = user.replace(new RegExp(':', 'g'),"_");
1.125     ng       3194: 		var resetscore = document.classgrade["GD_"+user+"_"+partid+"_awarded"];
                   3195: 		resetscore.value = document.classgrade["GD_"+user+"_"+partid+"_awarded_s"].value;
                   3196: 		var resettries = document.classgrade["GD_"+user+"_"+partid+"_tries"];
                   3197: 		resettries.value = document.classgrade["GD_"+user+"_"+partid+"_tries_s"].value;
                   3198: 		var saveselval   = document.classgrade["GD_"+user+"_"+partid+"_solved_s"].value;
                   3199: 		var selname   = document.classgrade["GD_"+user+"_"+partid+"_solved"];
1.42      ng       3200: 		if (saveselval == "excused") {
1.43      ng       3201: 		    if (selname[1].selected == false) { selname[1].selected = true;}
1.42      ng       3202: 		} else {
1.43      ng       3203: 		    if (selname[0].selected == false) {selname[0].selected = true};
1.42      ng       3204: 		}
                   3205: 	    }
1.41      ng       3206: 	}
1.42      ng       3207:     }
                   3208: 
1.41      ng       3209: </script>
                   3210: VIEWJAVASCRIPT
1.42      ng       3211: }
                   3212: 
1.44      ng       3213: #--- show scores for a section or whole class w/ option to change/update a score
1.42      ng       3214: sub viewgrades {
                   3215:     my ($request) = shift;
                   3216:     &viewgrades_js($request);
1.41      ng       3217: 
1.324     albertel 3218:     my ($symb) = &get_symb($request);
1.168     albertel 3219:     #need to make sure we have the correct data for later EXT calls, 
                   3220:     #thus invalidate the cache
                   3221:     &Apache::lonnet::devalidatecourseresdata(
1.257     albertel 3222:                  $env{'course.'.$env{'request.course.id'}.'.num'},
                   3223:                  $env{'course.'.$env{'request.course.id'}.'.domain'});
1.168     albertel 3224:     &Apache::lonnet::clear_EXT_cache_status();
                   3225: 
1.398     albertel 3226:     my $result='<h3><span class="LC_info">'.&mt('Manual Grading').'</span></h3>';
1.485     albertel 3227:     $result.='<h4>'.&mt('<b>Current Resource: </b>[_1]',$env{'form.probTitle'}).'</h4>'."\n";
1.41      ng       3228: 
                   3229:     #view individual student submission form - called using Javascript viewOneStudent
1.324     albertel 3230:     $result.=&jscriptNform($symb);
1.41      ng       3231: 
1.44      ng       3232:     #beginning of class grading form
1.442     banghart 3233:     my $stu_status = join(':',&Apache::loncommon::get_env_multiple('form.Status'));
1.41      ng       3234:     $result.= '<form action="/adm/grades" method="post" name="classgrade">'."\n".
1.418     albertel 3235: 	'<input type="hidden" name="symb"    value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
1.38      ng       3236: 	'<input type="hidden" name="command" value="editgrades" />'."\n".
1.432     banghart 3237: 	&build_section_inputs().
1.257     albertel 3238: 	'<input type="hidden" name="saveState" value="'.$env{'form.saveState'}.'" />'."\n".
1.442     banghart 3239: 	'<input type="hidden" name="Status" value="'.$env{'stu_status'}.'" />'."\n".
1.257     albertel 3240: 	'<input type="hidden" name="probTitle" value="'.$env{'form.probTitle'}.'" />'."\n";
1.72      ng       3241: 
1.560     raeburn  3242:     my ($common_header,$specific_header);
1.257     albertel 3243:     if ($env{'form.section'} eq 'all') {
1.560     raeburn  3244: 	$common_header = &mt('Assign Common Grade to Class');
                   3245:         $specific_header = &mt('Assign Grade to Specific Students in Class');
1.257     albertel 3246:     } elsif ($env{'form.section'} eq 'none') {
1.560     raeburn  3247:         $common_header = &mt('Assign Common Grade to Students in no Section');
                   3248: 	$specific_header = &mt('Assign Grade to Specific Students in no Section');
1.52      albertel 3249:     } else {
1.560     raeburn  3250:         my $section_display = join (", ",&Apache::loncommon::get_env_multiple('form.section'));
                   3251:         $common_header = &mt('Assign Common Grade to Students in Section(s) [_1]',$section_display);
                   3252: 	$specific_header = &mt('Assign Grade to Specific Students in Section(s) [_1]',$section_display);
1.52      albertel 3253:     }
1.560     raeburn  3254:     $result.= '<h3>'.$common_header.'</h3>'.&Apache::loncommon::start_data_table();
1.44      ng       3255:     #radio buttons/text box for assigning points for a section or class.
                   3256:     #handles different parts of a problem
1.375     albertel 3257:     my ($partlist,$handgrade,$responseType) = &response_type($symb);
1.42      ng       3258:     my %weight = ();
                   3259:     my $ctsparts = 0;
1.45      ng       3260:     my %seen = ();
1.375     albertel 3261:     my @part_response_id = &flatten_responseType($responseType);
                   3262:     foreach my $part_response_id (@part_response_id) {
                   3263:     	my ($partid,$respid) = @{ $part_response_id };
                   3264: 	my $part_resp = join('_',@{ $part_response_id });
1.45      ng       3265: 	next if $seen{$partid};
                   3266: 	$seen{$partid}++;
1.375     albertel 3267: 	my $handgrade=$$handgrade{$part_resp};
1.42      ng       3268: 	my $wgt = &Apache::lonnet::EXT('resource.'.$partid.'.weight',$symb);
                   3269: 	$weight{$partid} = $wgt eq '' ? '1' : $wgt;
                   3270: 
1.324     albertel 3271: 	my $display_part=&get_display_part($partid,$symb);
1.485     albertel 3272: 	my $radio.='<table border="0"><tr>';  
1.41      ng       3273: 	my $ctr = 0;
1.42      ng       3274: 	while ($ctr<=$weight{$partid}) { # display radio buttons in a nice table 10 across
1.485     albertel 3275: 	    $radio.= '<td><label><input type="radio" name="RADVAL_'.$partid.'" '.
1.54      albertel 3276: 		'onclick="javascript:writePoint(\''.$partid.'\','.$weight{$partid}.
1.288     albertel 3277: 		','.$ctr.')" />'.$ctr."</label></td>\n";
1.41      ng       3278: 	    $result.=(($ctr+1)%10 == 0 ? '</tr><tr>' : '');
                   3279: 	    $ctr++;
                   3280: 	}
1.485     albertel 3281: 	$radio.='</tr></table>';
                   3282: 	my $line = '<input type="text" name="TEXTVAL_'.
1.54      albertel 3283: 	    $partid.'" size="4" '.'onChange="javascript:writePoint(\''.
                   3284: 		$partid.'\','.$weight{$partid}.',\'textval\')" /> /'.
1.539     riegler  3285: 	    $weight{$partid}.' '.&mt('(problem weight)').'</td>'."\n";
                   3286: 	$line.= '<td><b>'.&mt('Grade Status').':</b><select name="SELVAL_'.$partid.'"'.
1.54      albertel 3287: 	    'onChange="javascript:writeRadText(\''.$partid.'\','.
1.59      albertel 3288: 		$weight{$partid}.')"> '.
1.401     albertel 3289: 	    '<option selected="selected"> </option>'.
1.485     albertel 3290: 	    '<option value="excused">'.&mt('excused').'</option>'.
                   3291: 	    '<option value="reset status">'.&mt('reset status').'</option>'.
                   3292: 	    '</select></td>'.
                   3293:             '<td><label><input type="checkbox" name="FORCE_'.$partid.'" />'.&mt('Override "Correct"').'</label>';
                   3294: 	$line.='<input type="hidden" name="partid_'.
                   3295: 	    $ctsparts.'" value="'.$partid.'" />'."\n";
                   3296: 	$line.='<input type="hidden" name="weight_'.
                   3297: 	    $partid.'" value="'.$weight{$partid}.'" />'."\n";
                   3298: 
                   3299: 	$result.=
                   3300: 	    &Apache::loncommon::start_data_table_row()."\n".
1.577     bisitz   3301: 	    '<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 3302: 	    &Apache::loncommon::end_data_table_row()."\n";
1.42      ng       3303: 	$ctsparts++;
1.41      ng       3304:     }
1.474     albertel 3305:     $result.=&Apache::loncommon::end_data_table()."\n".
1.52      albertel 3306: 	'<input type="hidden" name="totalparts" value="'.$ctsparts.'" />';
1.485     albertel 3307:     $result.='<input type="button" value="'.&mt('Revert to Default').'" '.
1.474     albertel 3308: 	'onClick="javascript:resetEntry('.$ctsparts.');" />';
1.41      ng       3309: 
1.44      ng       3310:     #table listing all the students in a section/class
                   3311:     #header of table
1.560     raeburn  3312:     $result.= '<h3>'.$specific_header.'</h3>'.
                   3313:               &Apache::loncommon::start_data_table().
                   3314: 	      &Apache::loncommon::start_data_table_header_row().
                   3315: 	      '<th>'.&mt('No.').'</th>'.
                   3316: 	      '<th>'.&nameUserString('header')."</th>\n";
1.324     albertel 3317:     my (@parts) = sort(&getpartlist($symb));
                   3318:     my (undef,undef,$url)=&Apache::lonnet::decode_symb($symb);
1.269     raeburn  3319:     my @partids = ();
1.41      ng       3320:     foreach my $part (@parts) {
                   3321: 	my $display=&Apache::lonnet::metadata($url,$part.'.display');
1.539     riegler  3322:         my $narrowtext = &mt('Tries');
                   3323: 	$display =~ s|^Number of Attempts|$narrowtext <br />|; # makes the column narrower
1.41      ng       3324: 	if  (!$display) { $display = &Apache::lonnet::metadata($url,$part.'.name'); }
1.207     albertel 3325: 	my ($partid) = &split_part_type($part);
1.524     raeburn  3326:         push(@partids,$partid);
1.324     albertel 3327: 	my $display_part=&get_display_part($partid,$symb);
1.41      ng       3328: 	if ($display =~ /^Partial Credit Factor/) {
1.485     albertel 3329: 	    $result.='<th>'.
                   3330: 		&mt('Score Part: [_1]<br /> (weight = [_2])',
                   3331: 		    $display_part,$weight{$partid}).'</th>'."\n";
1.41      ng       3332: 	    next;
1.485     albertel 3333: 	    
1.207     albertel 3334: 	} else {
1.485     albertel 3335: 	    if ($display =~ /Problem Status/) {
                   3336: 		my $grade_status_mt = &mt('Grade Status');
                   3337: 		$display =~ s{Problem Status}{$grade_status_mt<br />};
                   3338: 	    }
                   3339: 	    my $part_mt = &mt('Part:');
                   3340: 	    $display =~s{\[Part: \Q$partid\E\]}{$part_mt $display_part};
1.41      ng       3341: 	}
1.485     albertel 3342: 
1.474     albertel 3343: 	$result.='<th>'.$display.'</th>'."\n";
1.41      ng       3344:     }
1.474     albertel 3345:     $result.=&Apache::loncommon::end_data_table_header_row();
1.44      ng       3346: 
1.270     albertel 3347:     my %last_resets = 
                   3348: 	&get_last_resets($symb,$env{'request.course.id'},\@partids);
1.269     raeburn  3349: 
1.41      ng       3350:     #get info for each student
1.44      ng       3351:     #list all the students - with points and grade status
1.257     albertel 3352:     my (undef,undef,$fullname) = &getclasslist($env{'form.section'},'1');
1.41      ng       3353:     my $ctr = 0;
1.294     albertel 3354:     foreach (sort 
                   3355: 	     {
                   3356: 		 if (lc($$fullname{$a}) ne lc($$fullname{$b})) {
                   3357: 		     return (lc($$fullname{$a}) cmp lc($$fullname{$b}));
                   3358: 		 }
                   3359: 		 return $a cmp $b;
                   3360: 	     } (keys(%$fullname))) {
1.126     ng       3361: 	$ctr++;
1.324     albertel 3362: 	$result.=&viewstudentgrade($symb,$env{'request.course.id'},
1.269     raeburn  3363: 				   $_,$$fullname{$_},\@parts,\%weight,$ctr,\%last_resets);
1.41      ng       3364:     }
1.474     albertel 3365:     $result.=&Apache::loncommon::end_data_table();
1.41      ng       3366:     $result.='<input type="hidden" name="total" value="'.$ctr.'" />'."\n";
1.485     albertel 3367:     $result.='<input type="button" value="'.&mt('Save').'" '.
1.417     albertel 3368: 	'onClick="javascript:submit();" target="_self" /></form>'."\n";
1.96      albertel 3369:     if (scalar(%$fullname) eq 0) {
                   3370: 	my $colspan=3+scalar(@parts);
1.433     banghart 3371: 	my $section_display = join (", ",&Apache::loncommon::get_env_multiple('form.section'));
1.442     banghart 3372:         my $stu_status = join(' or ',&Apache::loncommon::get_env_multiple('form.Status'));
1.433     banghart 3373: 	$result='<span class="LC_warning">'.
1.485     albertel 3374: 	    &mt('There are no students in section(s) [_1] with enrollment status [_2] to modify or grade.',
1.442     banghart 3375: 	        $section_display, $stu_status).
1.433     banghart 3376: 	    '</span>';
1.96      albertel 3377:     }
1.324     albertel 3378:     $result.=&show_grading_menu_form($symb);
1.41      ng       3379:     return $result;
                   3380: }
                   3381: 
1.44      ng       3382: #--- call by previous routine to display each student
1.41      ng       3383: sub viewstudentgrade {
1.324     albertel 3384:     my ($symb,$courseid,$student,$fullname,$parts,$weight,$ctr,$last_resets) = @_;
1.44      ng       3385:     my ($uname,$udom) = split(/:/,$student);
                   3386:     my %record=&Apache::lonnet::restore($symb,$courseid,$udom,$uname);
1.269     raeburn  3387:     my %aggregates = (); 
1.474     albertel 3388:     my $result=&Apache::loncommon::start_data_table_row().'<td align="right">'.
1.233     albertel 3389: 	'<input type="hidden" name="ctr'.($ctr-1).'" value="'.$student.'" />'.
                   3390: 	"\n".$ctr.'&nbsp;</td><td>&nbsp;'.
1.44      ng       3391: 	'<a href="javascript:viewOneStudent(\''.$uname.'\',\''.$udom.
1.417     albertel 3392: 	'\');" target="_self">'.$fullname.'</a> '.
1.398     albertel 3393: 	'<span class="LC_internal_info">('.$uname.($env{'user.domain'} eq $udom ? '' : ':'.$udom).')</span></td>'."\n";
1.281     albertel 3394:     $student=~s/:/_/; # colon doen't work in javascript for names
1.63      albertel 3395:     foreach my $apart (@$parts) {
                   3396: 	my ($part,$type) = &split_part_type($apart);
1.41      ng       3397: 	my $score=$record{"resource.$part.$type"};
1.276     albertel 3398:         $result.='<td align="center">';
1.269     raeburn  3399:         my ($aggtries,$totaltries);
                   3400:         unless (exists($aggregates{$part})) {
1.270     albertel 3401: 	    $totaltries = $record{'resource.'.$part.'.tries'};
                   3402: 
                   3403: 	    $aggtries = $totaltries;
1.269     raeburn  3404:             if ($$last_resets{$part}) {  
1.270     albertel 3405:                 $aggtries = &get_num_tries(\%record,$$last_resets{$part},
                   3406: 					   $part);
                   3407:             }
1.269     raeburn  3408:             $result.='<input type="hidden" name="'.
                   3409:                 'GD_'.$student.'_'.$part.'_aggtries" value="'.$aggtries.'" />'."\n";
                   3410:             $result.='<input type="hidden" name="'.
                   3411:                 'GD_'.$student.'_'.$part.'_totaltries" value="'.$totaltries.'" />'."\n";
                   3412:             $aggregates{$part} = 1;
                   3413:         }
1.41      ng       3414: 	if ($type eq 'awarded') {
1.320     albertel 3415: 	    my $pts = $score eq '' ? '' : &compute_points($score,$$weight{$part});
1.42      ng       3416: 	    $result.='<input type="hidden" name="'.
1.89      albertel 3417: 		'GD_'.$student.'_'.$part.'_awarded_s" value="'.$pts.'" />'."\n";
1.233     albertel 3418: 	    $result.='<input type="text" name="'.
1.89      albertel 3419: 		'GD_'.$student.'_'.$part.'_awarded" '.
                   3420: 		'onChange="javascript:changeSelect(\''.$part.'\',\''.$student.
1.44      ng       3421: 		'\')" value="'.$pts.'" size="4" /></td>'."\n";
1.41      ng       3422: 	} elsif ($type eq 'solved') {
                   3423: 	    my ($status,$foo)=split(/_/,$score,2);
                   3424: 	    $status = 'nothing' if ($status eq '');
1.89      albertel 3425: 	    $result.='<input type="hidden" name="'.'GD_'.$student.'_'.
1.54      albertel 3426: 		$part.'_solved_s" value="'.$status.'" />'."\n";
1.233     albertel 3427: 	    $result.='&nbsp;<select name="'.
1.89      albertel 3428: 		'GD_'.$student.'_'.$part.'_solved" '.
                   3429: 		'onChange="javascript:changeOneScore(\''.$part.'\',\''.$student.'\')" >'."\n";
1.485     albertel 3430: 	    $result.= (($status eq 'excused') ? '<option> </option><option selected="selected" value="excused">'.&mt('excused').'</option>' 
                   3431: 		: '<option selected="selected"> </option><option value="excused">'.&mt('excused').'</option>')."\n";
                   3432: 	    $result.='<option value="reset status">'.&mt('reset status').'</option>';
1.126     ng       3433: 	    $result.="</select>&nbsp;</td>\n";
1.122     ng       3434: 	} else {
                   3435: 	    $result.='<input type="hidden" name="'.
                   3436: 		'GD_'.$student.'_'.$part.'_'.$type.'_s" value="'.$score.'" />'.
                   3437: 		    "\n";
1.233     albertel 3438: 	    $result.='<input type="text" name="'.
1.122     ng       3439: 		'GD_'.$student.'_'.$part.'_'.$type.'" '.
                   3440: 		'value="'.$score.'" size="4" /></td>'."\n";
1.41      ng       3441: 	}
                   3442:     }
1.474     albertel 3443:     $result.=&Apache::loncommon::end_data_table_row();
1.41      ng       3444:     return $result;
1.38      ng       3445: }
                   3446: 
1.44      ng       3447: #--- change scores for all the students in a section/class
                   3448: #    record does not get update if unchanged
1.38      ng       3449: sub editgrades {
1.41      ng       3450:     my ($request) = @_;
                   3451: 
1.324     albertel 3452:     my $symb=&get_symb($request);
1.433     banghart 3453:     my $section_display = join (", ",&Apache::loncommon::get_env_multiple('form.section'));
1.477     albertel 3454:     my $title='<h2>'.&mt('Current Grade Status').'</h2>';
                   3455:     $title.='<h4>'.&mt('<b>Current Resource: </b>[_1]',$env{'form.probTitle'}).'</h4>'."\n";
1.433     banghart 3456:     $title.='<h4>'.&mt('<b>Section: </b>[_1]',$section_display).'</h4>'."\n";
1.126     ng       3457: 
1.477     albertel 3458:     my $result= &Apache::loncommon::start_data_table().
                   3459: 	&Apache::loncommon::start_data_table_header_row().
                   3460: 	'<th rowspan="2" valign="middle">'.&mt('No.').'</th>'.
                   3461: 	'<th rowspan="2" valign="middle">'.&nameUserString('header')."</th>\n";
1.43      ng       3462:     my %scoreptr = (
                   3463: 		    'correct'  =>'correct_by_override',
                   3464: 		    'incorrect'=>'incorrect_by_override',
                   3465: 		    'excused'  =>'excused',
                   3466: 		    'ungraded' =>'ungraded_attempted',
                   3467: 		    'nothing'  => '',
                   3468: 		    );
1.257     albertel 3469:     my ($classlist,undef,$fullname) = &getclasslist($env{'form.section'},'0');
1.34      ng       3470: 
1.44      ng       3471:     my (@partid);
                   3472:     my %weight = ();
1.54      albertel 3473:     my %columns = ();
1.44      ng       3474:     my ($i,$ctr,$count,$rec_update) = (0,0,0,0);
1.54      albertel 3475: 
1.324     albertel 3476:     my (@parts) = sort(&getpartlist($symb));
1.54      albertel 3477:     my $header;
1.257     albertel 3478:     while ($ctr < $env{'form.totalparts'}) {
                   3479: 	my $partid = $env{'form.partid_'.$ctr};
1.524     raeburn  3480: 	push(@partid,$partid);
1.257     albertel 3481: 	$weight{$partid} = $env{'form.weight_'.$partid};
1.44      ng       3482: 	$ctr++;
1.54      albertel 3483:     }
1.324     albertel 3484:     my (undef,undef,$url) = &Apache::lonnet::decode_symb($symb);
1.54      albertel 3485:     foreach my $partid (@partid) {
1.478     albertel 3486: 	$header .= '<th align="center">'.&mt('Old Score').'</th>'.
                   3487: 	    '<th align="center">'.&mt('New Score').'</th>';
1.54      albertel 3488: 	$columns{$partid}=2;
                   3489: 	foreach my $stores (@parts) {
                   3490: 	    my ($part,$type) = &split_part_type($stores);
                   3491: 	    if ($part !~ m/^\Q$partid\E/) { next;}
                   3492: 	    if ($type eq 'awarded' || $type eq 'solved') { next; }
                   3493: 	    my $display=&Apache::lonnet::metadata($url,$stores.'.display');
1.551     raeburn  3494: 	    $display =~ s/\[Part: \Q$part\E\]//;
1.539     riegler  3495:             my $narrowtext = &mt('Tries');
                   3496: 	    $display =~ s/Number of Attempts/$narrowtext/;
                   3497: 	    $header .= '<th align="center">'.&mt('Old').' '.$display.'</th>'.
                   3498: 		'<th align="center">'.&mt('New').' '.$display.'</th>';
1.54      albertel 3499: 	    $columns{$partid}+=2;
                   3500: 	}
                   3501:     }
                   3502:     foreach my $partid (@partid) {
1.324     albertel 3503: 	my $display_part=&get_display_part($partid,$symb);
1.478     albertel 3504: 	$result .= '<th colspan="'.$columns{$partid}.'" align="center">'.
                   3505: 	    &mt('Part: [_1] (Weight = [_2])',$display_part,$weight{$partid}).
                   3506: 	    '</th>';
1.54      albertel 3507: 
1.44      ng       3508:     }
1.477     albertel 3509:     $result .= &Apache::loncommon::end_data_table_header_row().
                   3510: 	&Apache::loncommon::start_data_table_header_row().
                   3511: 	$header.
                   3512: 	&Apache::loncommon::end_data_table_header_row();
                   3513:     my @noupdate;
1.126     ng       3514:     my ($updateCtr,$noupdateCtr) = (1,1);
1.257     albertel 3515:     for ($i=0; $i<$env{'form.total'}; $i++) {
1.93      albertel 3516: 	my $line;
1.257     albertel 3517: 	my $user = $env{'form.ctr'.$i};
1.281     albertel 3518: 	my ($uname,$udom)=split(/:/,$user);
1.44      ng       3519: 	my %newrecord;
                   3520: 	my $updateflag = 0;
1.281     albertel 3521: 	$line .= '<td>'.&nameUserString(undef,$$fullname{$user},$uname,$udom).'</td>';
1.108     albertel 3522: 	my $usec=$classlist->{"$uname:$udom"}[5];
1.105     albertel 3523: 	if (!&canmodify($usec)) {
1.126     ng       3524: 	    my $numcols=scalar(@partid)*4+2;
1.477     albertel 3525: 	    push(@noupdate,
1.478     albertel 3526: 		 $line."<td colspan=\"$numcols\"><span class=\"LC_warning\">".
                   3527: 		 &mt('Not allowed to modify student')."</span></td></tr>");
1.105     albertel 3528: 	    next;
                   3529: 	}
1.269     raeburn  3530:         my %aggregate = ();
                   3531:         my $aggregateflag = 0;
1.281     albertel 3532: 	$user=~s/:/_/; # colon doen't work in javascript for names
1.44      ng       3533: 	foreach (@partid) {
1.257     albertel 3534: 	    my $old_aw    = $env{'form.GD_'.$user.'_'.$_.'_awarded_s'};
1.54      albertel 3535: 	    my $old_part_pcr = $old_aw/($weight{$_} ne '0' ? $weight{$_}:1);
                   3536: 	    my $old_part  = $old_aw eq '' ? '' : $old_part_pcr;
1.257     albertel 3537: 	    my $old_score = $scoreptr{$env{'form.GD_'.$user.'_'.$_.'_solved_s'}};
                   3538: 	    my $awarded   = $env{'form.GD_'.$user.'_'.$_.'_awarded'};
1.54      albertel 3539: 	    my $pcr       = $awarded/($weight{$_} ne '0' ? $weight{$_} : 1);
                   3540: 	    my $partial   = $awarded eq '' ? '' : $pcr;
1.44      ng       3541: 	    my $score;
                   3542: 	    if ($partial eq '') {
1.257     albertel 3543: 		$score = $scoreptr{$env{'form.GD_'.$user.'_'.$_.'_solved_s'}};
1.44      ng       3544: 	    } elsif ($partial > 0) {
                   3545: 		$score = 'correct_by_override';
                   3546: 	    } elsif ($partial == 0) {
                   3547: 		$score = 'incorrect_by_override';
                   3548: 	    }
1.257     albertel 3549: 	    my $dropMenu = $env{'form.GD_'.$user.'_'.$_.'_solved'};
1.125     ng       3550: 	    $score = 'excused' if (($dropMenu eq 'excused') && ($score ne 'excused'));
                   3551: 
1.292     albertel 3552: 	    $newrecord{'resource.'.$_.'.regrader'}=
                   3553: 		"$env{'user.name'}:$env{'user.domain'}";
1.125     ng       3554: 	    if ($dropMenu eq 'reset status' &&
                   3555: 		$old_score ne '') { # ignore if no previous attempts => nothing to reset
1.299     albertel 3556: 		$newrecord{'resource.'.$_.'.tries'} = '';
1.125     ng       3557: 		$newrecord{'resource.'.$_.'.solved'} = '';
                   3558: 		$newrecord{'resource.'.$_.'.award'} = '';
1.299     albertel 3559: 		$newrecord{'resource.'.$_.'.awarded'} = '';
1.125     ng       3560: 		$updateflag = 1;
1.269     raeburn  3561:                 if ($env{'form.GD_'.$user.'_'.$_.'_aggtries'} > 0) {
                   3562:                     my $aggtries = $env{'form.GD_'.$user.'_'.$_.'_aggtries'};
                   3563:                     my $totaltries = $env{'form.GD_'.$user.'_'.$_.'_totaltries'};
                   3564:                     my $solvedstatus = $env{'form.GD_'.$user.'_'.$_.'_solved_s'};
                   3565:                     &decrement_aggs($symb,$_,\%aggregate,$aggtries,$totaltries,$solvedstatus);
                   3566:                     $aggregateflag = 1;
                   3567:                 }
1.139     albertel 3568: 	    } elsif (!($old_part eq $partial && $old_score eq $score)) {
                   3569: 		$updateflag = 1;
                   3570: 		$newrecord{'resource.'.$_.'.awarded'}  = $partial if $partial ne '';
                   3571: 		$newrecord{'resource.'.$_.'.solved'}   = $score;
                   3572: 		$rec_update++;
1.125     ng       3573: 	    }
                   3574: 
1.93      albertel 3575: 	    $line .= '<td align="center">'.$old_aw.'&nbsp;</td>'.
1.44      ng       3576: 		'<td align="center">'.$awarded.
                   3577: 		($score eq 'excused' ? $score : '').'&nbsp;</td>';
1.5       albertel 3578: 
1.54      albertel 3579: 
                   3580: 	    my $partid=$_;
                   3581: 	    foreach my $stores (@parts) {
                   3582: 		my ($part,$type) = &split_part_type($stores);
                   3583: 		if ($part !~ m/^\Q$partid\E/) { next;}
                   3584: 		if ($type eq 'awarded' || $type eq 'solved') { next; }
1.257     albertel 3585: 		my $old_aw    = $env{'form.GD_'.$user.'_'.$part.'_'.$type.'_s'};
                   3586: 		my $awarded   = $env{'form.GD_'.$user.'_'.$part.'_'.$type};
1.54      albertel 3587: 		if ($awarded ne '' && $awarded ne $old_aw) {
                   3588: 		    $newrecord{'resource.'.$part.'.'.$type}= $awarded;
1.257     albertel 3589: 		    $newrecord{'resource.'.$part.'.regrader'}="$env{'user.name'}:$env{'user.domain'}";
1.54      albertel 3590: 		    $updateflag=1;
                   3591: 		}
1.93      albertel 3592: 		$line .= '<td align="center">'.$old_aw.'&nbsp;</td>'.
1.54      albertel 3593: 		    '<td align="center">'.$awarded.'&nbsp;</td>';
                   3594: 	    }
1.44      ng       3595: 	}
1.477     albertel 3596: 	$line.="\n";
1.301     albertel 3597: 
                   3598: 	my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   3599: 	my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   3600: 
1.44      ng       3601: 	if ($updateflag) {
                   3602: 	    $count++;
1.257     albertel 3603: 	    &Apache::lonnet::cstore(\%newrecord,$symb,$env{'request.course.id'},
1.89      albertel 3604: 				    $udom,$uname);
1.301     albertel 3605: 
                   3606: 	    if (&Apache::bridgetask::in_queue('gradingqueue',$symb,$cdom,
                   3607: 					      $cnum,$udom,$uname)) {
                   3608: 		# need to figure out if should be in queue.
                   3609: 		my %record =  
                   3610: 		    &Apache::lonnet::restore($symb,$env{'request.course.id'},
                   3611: 					     $udom,$uname);
                   3612: 		my $all_graded = 1;
                   3613: 		my $none_graded = 1;
                   3614: 		foreach my $part (@parts) {
                   3615: 		    if ( $record{'resource.'.$part.'.awarded'} eq '' ) {
                   3616: 			$all_graded = 0;
                   3617: 		    } else {
                   3618: 			$none_graded = 0;
                   3619: 		    }
                   3620: 		}
                   3621: 
                   3622: 		if ($all_graded || $none_graded) {
                   3623: 		    &Apache::bridgetask::remove_from_queue('gradingqueue',
                   3624: 							   $symb,$cdom,$cnum,
                   3625: 							   $udom,$uname);
                   3626: 		}
                   3627: 	    }
                   3628: 
1.477     albertel 3629: 	    $result.=&Apache::loncommon::start_data_table_row().
                   3630: 		'<td align="right">&nbsp;'.$updateCtr.'&nbsp;</td>'.$line.
                   3631: 		&Apache::loncommon::end_data_table_row();
1.126     ng       3632: 	    $updateCtr++;
1.93      albertel 3633: 	} else {
1.477     albertel 3634: 	    push(@noupdate,
                   3635: 		 '<td align="right">&nbsp;'.$noupdateCtr.'&nbsp;</td>'.$line);
1.126     ng       3636: 	    $noupdateCtr++;
1.44      ng       3637: 	}
1.269     raeburn  3638:         if ($aggregateflag) {
                   3639:             &Apache::lonnet::cinc('nohist_resourcetracker',\%aggregate,
1.301     albertel 3640: 				  $cdom,$cnum);
1.269     raeburn  3641:         }
1.93      albertel 3642:     }
1.477     albertel 3643:     if (@noupdate) {
1.126     ng       3644: #	my $numcols=(scalar(@partid)*(scalar(@parts)-1)*2)+3;
                   3645: 	my $numcols=scalar(@partid)*4+2;
1.477     albertel 3646: 	$result .= &Apache::loncommon::start_data_table_row('LC_empty_row').
1.478     albertel 3647: 	    '<td align="center" colspan="'.$numcols.'">'.
                   3648: 	    &mt('No Changes Occurred For the Students Below').
                   3649: 	    '</td>'.
1.477     albertel 3650: 	    &Apache::loncommon::end_data_table_row();
                   3651: 	foreach my $line (@noupdate) {
                   3652: 	    $result.=
                   3653: 		&Apache::loncommon::start_data_table_row().
                   3654: 		$line.
                   3655: 		&Apache::loncommon::end_data_table_row();
                   3656: 	}
1.44      ng       3657:     }
1.477     albertel 3658:     $result .= &Apache::loncommon::end_data_table().
                   3659: 	&show_grading_menu_form($symb);
1.478     albertel 3660:     my $msg = '<p><b>'.
                   3661: 	&mt('Number of records updated = [_1] for [quant,_2,student].',
                   3662: 	    $rec_update,$count).'</b><br />'.
                   3663: 	'<b>'.&mt('Total number of students = [_1]',$env{'form.total'}).
                   3664: 	'</b></p>';
1.44      ng       3665:     return $title.$msg.$result;
1.5       albertel 3666: }
1.54      albertel 3667: 
                   3668: sub split_part_type {
                   3669:     my ($partstr) = @_;
                   3670:     my ($temp,@allparts)=split(/_/,$partstr);
                   3671:     my $type=pop(@allparts);
1.439     albertel 3672:     my $part=join('_',@allparts);
1.54      albertel 3673:     return ($part,$type);
                   3674: }
                   3675: 
1.44      ng       3676: #------------- end of section for handling grading by section/class ---------
                   3677: #
                   3678: #----------------------------------------------------------------------------
                   3679: 
1.5       albertel 3680: 
1.44      ng       3681: #----------------------------------------------------------------------------
                   3682: #
                   3683: #-------------------------- Next few routines handles grading by csv upload
                   3684: #
                   3685: #--- Javascript to handle csv upload
1.27      albertel 3686: sub csvupload_javascript_reverse_associate {
1.573     bisitz   3687:     my $error1=&mt('You need to specify the username or the student/employee ID');
1.246     albertel 3688:     my $error2=&mt('You need to specify at least one grading field');
1.27      albertel 3689:   return(<<ENDPICK);
                   3690:   function verify(vf) {
                   3691:     var foundsomething=0;
                   3692:     var founduname=0;
1.243     albertel 3693:     var foundID=0;
1.27      albertel 3694:     for (i=0;i<=vf.nfields.value;i++) {
                   3695:       tw=eval('vf.f'+i+'.selectedIndex');
1.243     albertel 3696:       if (i==0 && tw!=0) { foundID=1; }
                   3697:       if (i==1 && tw!=0) { founduname=1; }
                   3698:       if (i!=0 && i!=1 && i!=2 && tw!=0) { foundsomething=1; }
1.27      albertel 3699:     }
1.246     albertel 3700:     if (founduname==0 && foundID==0) {
                   3701: 	alert('$error1');
                   3702: 	return;
1.27      albertel 3703:     }
                   3704:     if (foundsomething==0) {
1.246     albertel 3705: 	alert('$error2');
                   3706: 	return;
1.27      albertel 3707:     }
                   3708:     vf.submit();
                   3709:   }
                   3710:   function flip(vf,tf) {
                   3711:     var nw=eval('vf.f'+tf+'.selectedIndex');
                   3712:     var i;
                   3713:     for (i=0;i<=vf.nfields.value;i++) {
                   3714:       //can not pick the same destination field for both name and domain
                   3715:       if (((i ==0)||(i ==1)) && 
                   3716:           ((tf==0)||(tf==1)) && 
                   3717:           (i!=tf) &&
                   3718:           (eval('vf.f'+i+'.selectedIndex')==nw)) {
                   3719:         eval('vf.f'+i+'.selectedIndex=0;')
                   3720:       }
                   3721:     }
                   3722:   }
                   3723: ENDPICK
                   3724: }
                   3725: 
                   3726: sub csvupload_javascript_forward_associate {
1.573     bisitz   3727:     my $error1=&mt('You need to specify the username or the student/employee ID');
1.246     albertel 3728:     my $error2=&mt('You need to specify at least one grading field');
1.27      albertel 3729:   return(<<ENDPICK);
                   3730:   function verify(vf) {
                   3731:     var foundsomething=0;
                   3732:     var founduname=0;
1.243     albertel 3733:     var foundID=0;
1.27      albertel 3734:     for (i=0;i<=vf.nfields.value;i++) {
                   3735:       tw=eval('vf.f'+i+'.selectedIndex');
1.243     albertel 3736:       if (tw==1) { foundID=1; }
                   3737:       if (tw==2) { founduname=1; }
                   3738:       if (tw>3) { foundsomething=1; }
1.27      albertel 3739:     }
1.246     albertel 3740:     if (founduname==0 && foundID==0) {
                   3741: 	alert('$error1');
                   3742: 	return;
1.27      albertel 3743:     }
                   3744:     if (foundsomething==0) {
1.246     albertel 3745: 	alert('$error2');
                   3746: 	return;
1.27      albertel 3747:     }
                   3748:     vf.submit();
                   3749:   }
                   3750:   function flip(vf,tf) {
                   3751:     var nw=eval('vf.f'+tf+'.selectedIndex');
                   3752:     var i;
                   3753:     //can not pick the same destination field twice
                   3754:     for (i=0;i<=vf.nfields.value;i++) {
                   3755:       if ((i!=tf) && (eval('vf.f'+i+'.selectedIndex')==nw)) {
                   3756:         eval('vf.f'+i+'.selectedIndex=0;')
                   3757:       }
                   3758:     }
                   3759:   }
                   3760: ENDPICK
                   3761: }
                   3762: 
1.26      albertel 3763: sub csvuploadmap_header {
1.324     albertel 3764:     my ($request,$symb,$datatoken,$distotal)= @_;
1.41      ng       3765:     my $javascript;
1.257     albertel 3766:     if ($env{'form.upfile_associate'} eq 'reverse') {
1.41      ng       3767: 	$javascript=&csvupload_javascript_reverse_associate();
                   3768:     } else {
                   3769: 	$javascript=&csvupload_javascript_forward_associate();
                   3770:     }
1.45      ng       3771: 
1.324     albertel 3772:     my ($result) = &showResourceInfo($symb,$env{'form.probTitle'});
1.257     albertel 3773:     my $checked=(($env{'form.noFirstLine'})?' checked="checked"':'');
1.245     albertel 3774:     my $ignore=&mt('Ignore First Line');
1.418     albertel 3775:     $symb = &Apache::lonenc::check_encrypt($symb);
1.41      ng       3776:     $request->print(<<ENDPICK);
1.26      albertel 3777: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="gradesupload">
1.398     albertel 3778: <h3><span class="LC_info">Uploading Class Grades</span></h3>
1.45      ng       3779: $result
1.326     albertel 3780: <hr />
1.26      albertel 3781: <h3>Identify fields</h3>
                   3782: Total number of records found in file: $distotal <hr />
                   3783: Enter as many fields as you can. The system will inform you and bring you back
                   3784: to this page if the data selected is insufficient to run your class.<hr />
                   3785: <input type="button" value="Reverse Association" onClick="javascript:this.form.associate.value='Reverse Association';submit(this.form);" />
1.245     albertel 3786: <label><input type="checkbox" name="noFirstLine" $checked />$ignore</label>
1.26      albertel 3787: <input type="hidden" name="associate"  value="" />
                   3788: <input type="hidden" name="phase"      value="three" />
                   3789: <input type="hidden" name="datatoken"  value="$datatoken" />
1.257     albertel 3790: <input type="hidden" name="fileupload" value="$env{'form.fileupload'}" />
                   3791: <input type="hidden" name="upfiletype" value="$env{'form.upfiletype'}" />
1.26      albertel 3792: <input type="hidden" name="upfile_associate" 
1.257     albertel 3793:                                        value="$env{'form.upfile_associate'}" />
1.26      albertel 3794: <input type="hidden" name="symb"       value="$symb" />
1.257     albertel 3795: <input type="hidden" name="saveState"  value="$env{'form.saveState'}" />
                   3796: <input type="hidden" name="probTitle"  value="$env{'form.probTitle'}" />
1.246     albertel 3797: <input type="hidden" name="command"    value="csvuploadoptions" />
1.26      albertel 3798: <hr />
                   3799: <script type="text/javascript" language="Javascript">
                   3800: $javascript
                   3801: </script>
                   3802: ENDPICK
1.118     ng       3803:     return '';
1.26      albertel 3804: 
                   3805: }
                   3806: 
                   3807: sub csvupload_fields {
1.324     albertel 3808:     my ($symb) = @_;
                   3809:     my (@parts) = &getpartlist($symb);
1.556     weissno  3810:     my @fields=(['ID','Student/Employee ID'],
1.243     albertel 3811: 		['username','Student Username'],
                   3812: 		['domain','Student Domain']);
1.324     albertel 3813:     my (undef,undef,$url) = &Apache::lonnet::decode_symb($symb);
1.41      ng       3814:     foreach my $part (sort(@parts)) {
                   3815: 	my @datum;
                   3816: 	my $display=&Apache::lonnet::metadata($url,$part.'.display');
                   3817: 	my $name=$part;
                   3818: 	if  (!$display) { $display = $name; }
                   3819: 	@datum=($name,$display);
1.244     albertel 3820: 	if ($name=~/^stores_(.*)_awarded/) {
                   3821: 	    push(@fields,['stores_'.$1.'_points',"Points [Part: $1]"]);
                   3822: 	}
1.41      ng       3823: 	push(@fields,\@datum);
                   3824:     }
                   3825:     return (@fields);
1.26      albertel 3826: }
                   3827: 
                   3828: sub csvuploadmap_footer {
1.41      ng       3829:     my ($request,$i,$keyfields) =@_;
                   3830:     $request->print(<<ENDPICK);
1.26      albertel 3831: </table>
                   3832: <input type="hidden" name="nfields" value="$i" />
                   3833: <input type="hidden" name="keyfields" value="$keyfields" />
                   3834: <input type="button" onClick="javascript:verify(this.form)" value="Assign Grades" /><br />
                   3835: </form>
                   3836: ENDPICK
                   3837: }
                   3838: 
1.283     albertel 3839: sub checkforfile_js {
1.539     riegler  3840:     my $alertmsg = &mt('Please use the browse button to select a file from your local directory.');
1.86      ng       3841:     my $result =<<CSVFORMJS;
                   3842: <script type="text/javascript" language="javascript">
                   3843:     function checkUpload(formname) {
                   3844: 	if (formname.upfile.value == "") {
1.539     riegler  3845: 	    alert("$alertmsg");
1.86      ng       3846: 	    return false;
                   3847: 	}
                   3848: 	formname.submit();
                   3849:     }
                   3850:     </script>
                   3851: CSVFORMJS
1.283     albertel 3852:     return $result;
                   3853: }
                   3854: 
                   3855: sub upcsvScores_form {
                   3856:     my ($request) = shift;
1.324     albertel 3857:     my ($symb)=&get_symb($request);
1.283     albertel 3858:     if (!$symb) {return '';}
                   3859:     my $result=&checkforfile_js();
1.257     albertel 3860:     $env{'form.probTitle'} = &Apache::lonnet::gettitle($symb);
1.324     albertel 3861:     my ($table) = &showResourceInfo($symb,$env{'form.probTitle'});
1.118     ng       3862:     $result.=$table;
1.326     albertel 3863:     $result.='<br /><table width="100%" border="0"><tr><td bgcolor="#777777">'."\n";
                   3864:     $result.='<table width="100%" border="0"><tr bgcolor="#e6ffff"><td>'."\n";
1.538     schulted 3865:     $result.='&nbsp;<b>'.&mt('Specify a file containing the class scores for current resource.').
                   3866: 	'</b></td></tr>'."\n";
1.86      ng       3867:     $result.='<tr bgcolor=#ffffe6><td>'."\n";
1.370     www      3868:     my $upload=&mt("Upload Scores");
1.86      ng       3869:     my $upfile_select=&Apache::loncommon::upfile_select_html();
1.245     albertel 3870:     my $ignore=&mt('Ignore First Line');
1.418     albertel 3871:     $symb = &Apache::lonenc::check_encrypt($symb);
1.86      ng       3872:     $result.=<<ENDUPFORM;
1.106     albertel 3873: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="gradesupload">
1.86      ng       3874: <input type="hidden" name="symb" value="$symb" />
                   3875: <input type="hidden" name="command" value="csvuploadmap" />
1.257     albertel 3876: <input type="hidden" name="probTitle" value="$env{'form.probTitle'}" />
                   3877: <input type="hidden" name="saveState"  value="$env{'form.saveState'}" />
1.86      ng       3878: $upfile_select
1.370     www      3879: <br /><input type="button" onClick="javascript:checkUpload(this.form);" value="$upload" />
1.283     albertel 3880: <label><input type="checkbox" name="noFirstLine" />$ignore</label>
1.86      ng       3881: </form>
                   3882: ENDUPFORM
1.370     www      3883:     $result.=&Apache::loncommon::help_open_topic("Course_Convert_To_CSV",
                   3884:                            &mt("How do I create a CSV file from a spreadsheet"))
                   3885:     .'</td></tr></table>'."\n";
1.86      ng       3886:     $result.='</td></tr></table><br /><br />'."\n";
1.324     albertel 3887:     $result.=&show_grading_menu_form($symb);
1.86      ng       3888:     return $result;
                   3889: }
                   3890: 
                   3891: 
1.26      albertel 3892: sub csvuploadmap {
1.41      ng       3893:     my ($request)= @_;
1.324     albertel 3894:     my ($symb)=&get_symb($request);
1.41      ng       3895:     if (!$symb) {return '';}
1.72      ng       3896: 
1.41      ng       3897:     my $datatoken;
1.257     albertel 3898:     if (!$env{'form.datatoken'}) {
1.41      ng       3899: 	$datatoken=&Apache::loncommon::upfile_store($request);
1.26      albertel 3900:     } else {
1.257     albertel 3901: 	$datatoken=$env{'form.datatoken'};
1.41      ng       3902: 	&Apache::loncommon::load_tmp_file($request);
1.26      albertel 3903:     }
1.41      ng       3904:     my @records=&Apache::loncommon::upfile_record_sep();
1.257     albertel 3905:     if ($env{'form.noFirstLine'}) { shift(@records); }
1.324     albertel 3906:     &csvuploadmap_header($request,$symb,$datatoken,$#records+1);
1.41      ng       3907:     my ($i,$keyfields);
                   3908:     if (@records) {
1.324     albertel 3909: 	my @fields=&csvupload_fields($symb);
1.45      ng       3910: 
1.257     albertel 3911: 	if ($env{'form.upfile_associate'} eq 'reverse') {	
1.41      ng       3912: 	    &Apache::loncommon::csv_print_samples($request,\@records);
                   3913: 	    $i=&Apache::loncommon::csv_print_select_table($request,\@records,
                   3914: 							  \@fields);
                   3915: 	    foreach (@fields) { $keyfields.=$_->[0].','; }
                   3916: 	    chop($keyfields);
                   3917: 	} else {
                   3918: 	    unshift(@fields,['none','']);
                   3919: 	    $i=&Apache::loncommon::csv_samples_select_table($request,\@records,
                   3920: 							    \@fields);
1.311     banghart 3921:             foreach my $rec (@records) {
                   3922:                 my %temp = &Apache::loncommon::record_sep($rec);
                   3923:                 if (%temp) {
                   3924:                     $keyfields=join(',',sort(keys(%temp)));
                   3925:                     last;
                   3926:                 }
                   3927:             }
1.41      ng       3928: 	}
                   3929:     }
                   3930:     &csvuploadmap_footer($request,$i,$keyfields);
1.324     albertel 3931:     $request->print(&show_grading_menu_form($symb));
1.72      ng       3932: 
1.41      ng       3933:     return '';
1.27      albertel 3934: }
                   3935: 
1.246     albertel 3936: sub csvuploadoptions {
1.41      ng       3937:     my ($request)= @_;
1.324     albertel 3938:     my ($symb)=&get_symb($request);
1.257     albertel 3939:     my $checked=(($env{'form.noFirstLine'})?'1':'0');
1.246     albertel 3940:     my $ignore=&mt('Ignore First Line');
                   3941:     $request->print(<<ENDPICK);
                   3942: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="gradesupload">
1.398     albertel 3943: <h3><span class="LC_info">Uploading Class Grade Options</span></h3>
1.246     albertel 3944: <input type="hidden" name="command"    value="csvuploadassign" />
1.302     albertel 3945: <!--
1.246     albertel 3946: <p>
                   3947: <label>
                   3948:    <input type="checkbox" name="show_full_results" />
                   3949:    Show a table of all changes
                   3950: </label>
                   3951: </p>
1.302     albertel 3952: -->
1.246     albertel 3953: <p>
                   3954: <label>
                   3955:    <input type="checkbox" name="overwite_scores" checked="checked" />
                   3956:    Overwrite any existing score
                   3957: </label>
                   3958: </p>
                   3959: ENDPICK
                   3960:     my %fields=&get_fields();
                   3961:     if (!defined($fields{'domain'})) {
1.257     albertel 3962: 	my $domform = &Apache::loncommon::select_dom_form($env{'request.role.domain'},'default_domain');
1.246     albertel 3963: 	$request->print("\n<p> Users are in domain: ".$domform."</p>\n");
                   3964:     }
1.257     albertel 3965:     foreach my $key (sort(keys(%env))) {
1.246     albertel 3966: 	if ($key !~ /^form\.(.*)$/) { next; }
                   3967: 	my $cleankey=$1;
                   3968: 	if ($cleankey eq 'command') { next; }
                   3969: 	$request->print('<input type="hidden" name="'.$cleankey.
1.257     albertel 3970: 			'"  value="'.$env{$key}.'" />'."\n");
1.246     albertel 3971:     }
                   3972:     # FIXME do a check for any duplicated user ids...
                   3973:     # FIXME do a check for any invalid user ids?...
1.290     albertel 3974:     $request->print('<input type="submit" value="Assign Grades" /><br />
                   3975: <hr /></form>'."\n");
1.324     albertel 3976:     $request->print(&show_grading_menu_form($symb));
1.246     albertel 3977:     return '';
                   3978: }
                   3979: 
                   3980: sub get_fields {
                   3981:     my %fields;
1.257     albertel 3982:     my @keyfields = split(/\,/,$env{'form.keyfields'});
                   3983:     for (my $i=0; $i<=$env{'form.nfields'}; $i++) {
                   3984: 	if ($env{'form.upfile_associate'} eq 'reverse') {
                   3985: 	    if ($env{'form.f'.$i} ne 'none') {
                   3986: 		$fields{$keyfields[$i]}=$env{'form.f'.$i};
1.41      ng       3987: 	    }
                   3988: 	} else {
1.257     albertel 3989: 	    if ($env{'form.f'.$i} ne 'none') {
                   3990: 		$fields{$env{'form.f'.$i}}=$keyfields[$i];
1.41      ng       3991: 	    }
                   3992: 	}
1.27      albertel 3993:     }
1.246     albertel 3994:     return %fields;
                   3995: }
                   3996: 
                   3997: sub csvuploadassign {
                   3998:     my ($request)= @_;
1.324     albertel 3999:     my ($symb)=&get_symb($request);
1.246     albertel 4000:     if (!$symb) {return '';}
1.345     bowersj2 4001:     my $error_msg = '';
1.246     albertel 4002:     &Apache::loncommon::load_tmp_file($request);
                   4003:     my @gradedata = &Apache::loncommon::upfile_record_sep();
1.257     albertel 4004:     if ($env{'form.noFirstLine'}) { shift(@gradedata); }
1.246     albertel 4005:     my %fields=&get_fields();
1.41      ng       4006:     $request->print('<h3>Assigning Grades</h3>');
1.257     albertel 4007:     my $courseid=$env{'request.course.id'};
1.97      albertel 4008:     my ($classlist) = &getclasslist('all',0);
1.106     albertel 4009:     my @notallowed;
1.41      ng       4010:     my @skipped;
                   4011:     my $countdone=0;
                   4012:     foreach my $grade (@gradedata) {
                   4013: 	my %entries=&Apache::loncommon::record_sep($grade);
1.246     albertel 4014: 	my $domain;
                   4015: 	if ($entries{$fields{'domain'}}) {
                   4016: 	    $domain=$entries{$fields{'domain'}};
                   4017: 	} else {
1.257     albertel 4018: 	    $domain=$env{'form.default_domain'};
1.246     albertel 4019: 	}
1.243     albertel 4020: 	$domain=~s/\s//g;
1.41      ng       4021: 	my $username=$entries{$fields{'username'}};
1.160     albertel 4022: 	$username=~s/\s//g;
1.243     albertel 4023: 	if (!$username) {
                   4024: 	    my $id=$entries{$fields{'ID'}};
1.247     albertel 4025: 	    $id=~s/\s//g;
1.243     albertel 4026: 	    my %ids=&Apache::lonnet::idget($domain,$id);
                   4027: 	    $username=$ids{$id};
                   4028: 	}
1.41      ng       4029: 	if (!exists($$classlist{"$username:$domain"})) {
1.247     albertel 4030: 	    my $id=$entries{$fields{'ID'}};
                   4031: 	    $id=~s/\s//g;
                   4032: 	    if ($id) {
                   4033: 		push(@skipped,"$id:$domain");
                   4034: 	    } else {
                   4035: 		push(@skipped,"$username:$domain");
                   4036: 	    }
1.41      ng       4037: 	    next;
                   4038: 	}
1.108     albertel 4039: 	my $usec=$classlist->{"$username:$domain"}[5];
1.106     albertel 4040: 	if (!&canmodify($usec)) {
                   4041: 	    push(@notallowed,"$username:$domain");
                   4042: 	    next;
                   4043: 	}
1.244     albertel 4044: 	my %points;
1.41      ng       4045: 	my %grades;
                   4046: 	foreach my $dest (keys(%fields)) {
1.244     albertel 4047: 	    if ($dest eq 'ID' || $dest eq 'username' ||
                   4048: 		$dest eq 'domain') { next; }
                   4049: 	    if ($entries{$fields{$dest}} =~ /^\s*$/) { next; }
                   4050: 	    if ($dest=~/stores_(.*)_points/) {
                   4051: 		my $part=$1;
                   4052: 		my $wgt =&Apache::lonnet::EXT('resource.'.$part.'.weight',
                   4053: 					      $symb,$domain,$username);
1.345     bowersj2 4054:                 if ($wgt) {
                   4055:                     $entries{$fields{$dest}}=~s/\s//g;
                   4056:                     my $pcr=$entries{$fields{$dest}} / $wgt;
1.463     albertel 4057:                     my $award=($pcr == 0) ? 'incorrect_by_override'
                   4058:                                           : 'correct_by_override';
1.345     bowersj2 4059:                     $grades{"resource.$part.awarded"}=$pcr;
                   4060:                     $grades{"resource.$part.solved"}=$award;
                   4061:                     $points{$part}=1;
                   4062:                 } else {
                   4063:                     $error_msg = "<br />" .
                   4064:                         &mt("Some point values were assigned"
                   4065:                             ." for problems with a weight "
                   4066:                             ."of zero. These values were "
                   4067:                             ."ignored.");
                   4068:                 }
1.244     albertel 4069: 	    } else {
                   4070: 		if ($dest=~/stores_(.*)_awarded/) { if ($points{$1}) {next;} }
                   4071: 		if ($dest=~/stores_(.*)_solved/)  { if ($points{$1}) {next;} }
                   4072: 		my $store_key=$dest;
                   4073: 		$store_key=~s/^stores/resource/;
                   4074: 		$store_key=~s/_/\./g;
                   4075: 		$grades{$store_key}=$entries{$fields{$dest}};
                   4076: 	    }
1.41      ng       4077: 	}
1.508     www      4078: 	if (! %grades) { 
                   4079:            push(@skipped,&mt("[_1]: no data to save","$username:$domain")); 
                   4080:         } else {
                   4081: 	   $grades{"resource.regrader"}="$env{'user.name'}:$env{'user.domain'}";
                   4082: 	   my $result=&Apache::lonnet::cstore(\%grades,$symb,
1.302     albertel 4083: 					   $env{'request.course.id'},
                   4084: 					   $domain,$username);
1.508     www      4085: 	   if ($result eq 'ok') {
                   4086: 	      $request->print('.');
                   4087: 	   } else {
                   4088: 	      $request->print("<p><span class=\"LC_error\">".
                   4089:                               &mt("Failed to save data for student [_1]. Message when trying to save was: [_2]",
                   4090:                                   "$username:$domain",$result)."</span></p>");
                   4091: 	   }
                   4092: 	   $request->rflush();
                   4093: 	   $countdone++;
                   4094:         }
1.41      ng       4095:     }
1.570     www      4096:     $request->print('<br />'.&Apache::lonhtmlcommon::confirm_success(&mt("Saved scores for [quant,_1,student]",$countdone),$countdone==0));
1.41      ng       4097:     if (@skipped) {
1.571     www      4098: 	$request->print('<br />'.&Apache::lonhtmlcommon::confirm_success(&mt('No scores stored for the following username(s):'),1).'<br />');
                   4099:         $request->print(join(', ',@skipped));
1.106     albertel 4100:     }
                   4101:     if (@notallowed) {
1.571     www      4102: 	$request->print('<br />'.&Apache::lonhtmlcommon::confirm_success(&mt('Modification of scores not allowed for the following username(s):'),1).'<br />');
                   4103: 	$request->print(join(', ',@notallowed));
1.41      ng       4104:     }
1.106     albertel 4105:     $request->print("<br />\n");
1.324     albertel 4106:     $request->print(&show_grading_menu_form($symb));
1.345     bowersj2 4107:     return $error_msg;
1.26      albertel 4108: }
1.44      ng       4109: #------------- end of section for handling csv file upload ---------
                   4110: #
                   4111: #-------------------------------------------------------------------
                   4112: #
1.122     ng       4113: #-------------- Next few routines handle grading by page/sequence
1.72      ng       4114: #
                   4115: #--- Select a page/sequence and a student to grade
1.68      ng       4116: sub pickStudentPage {
                   4117:     my ($request) = shift;
                   4118: 
1.539     riegler  4119:     my $alertmsg = &mt('Please select the student you wish to grade.');
1.68      ng       4120:     $request->print(<<LISTJAVASCRIPT);
                   4121: <script type="text/javascript" language="javascript">
                   4122: 
                   4123: function checkPickOne(formname) {
1.76      ng       4124:     if (radioSelection(formname.student) == null) {
1.539     riegler  4125: 	alert("$alertmsg");
1.68      ng       4126: 	return;
                   4127:     }
1.125     ng       4128:     ptr = pullDownSelection(formname.selectpage);
                   4129:     formname.page.value = formname["page"+ptr].value;
                   4130:     formname.title.value = formname["title"+ptr].value;
1.68      ng       4131:     formname.submit();
                   4132: }
                   4133: 
                   4134: </script>
                   4135: LISTJAVASCRIPT
1.118     ng       4136:     &commonJSfunctions($request);
1.324     albertel 4137:     my ($symb) = &get_symb($request);
1.257     albertel 4138:     my $cdom      = $env{"course.$env{'request.course.id'}.domain"};
                   4139:     my $cnum      = $env{"course.$env{'request.course.id'}.num"};
                   4140:     my $getsec    = $env{'form.section'} eq '' ? 'all' : $env{'form.section'};
1.68      ng       4141: 
1.398     albertel 4142:     my $result='<h3><span class="LC_info">&nbsp;'.
1.485     albertel 4143: 	&mt('Manual Grading by Page or Sequence').'</span></h3>';
1.68      ng       4144: 
1.80      ng       4145:     $result.='<form action="/adm/grades" method="post" name="displayPage">'."\n";
1.423     albertel 4146:     my ($titles,$symbx) = &getSymbMap();
1.137     albertel 4147:     my ($curpage) =&Apache::lonnet::decode_symb($symb); 
                   4148: #    my ($curpage,$mapId) =&Apache::lonnet::decode_symb($symb); 
                   4149: #    my $type=($curpage =~ /\.(page|sequence)/);
1.485     albertel 4150:     my $select = '<select name="selectpage">'."\n";
1.70      ng       4151:     my $ctr=0;
1.68      ng       4152:     foreach (@$titles) {
                   4153: 	my ($minder,$showtitle) = ($_ =~ /(\d+)\.(.*)/);
1.485     albertel 4154: 	$select.='<option value="'.$ctr.'" '.
1.401     albertel 4155: 	    ($$symbx{$_} =~ /$curpage$/ ? 'selected="selected"' : '').
1.71      ng       4156: 	    '>'.$showtitle.'</option>'."\n";
1.70      ng       4157: 	$ctr++;
1.68      ng       4158:     }
1.485     albertel 4159:     $select.= '</select>';
1.539     riegler  4160:     $result.='&nbsp;<b>'.&mt('Problems from').':</b> '.$select."<br />\n";
1.485     albertel 4161: 
1.70      ng       4162:     $ctr=0;
                   4163:     foreach (@$titles) {
                   4164: 	my ($minder,$showtitle) = ($_ =~ /(\d+)\.(.*)/);
                   4165: 	$result.='<input type="hidden" name="page'.$ctr.'" value="'.$$symbx{$_}.'" />'."\n";
                   4166: 	$result.='<input type="hidden" name="title'.$ctr.'" value="'.$showtitle.'" />'."\n";
                   4167: 	$ctr++;
                   4168:     }
1.72      ng       4169:     $result.='<input type="hidden" name="page" />'."\n".
                   4170: 	'<input type="hidden" name="title" />'."\n";
1.68      ng       4171: 
1.485     albertel 4172:     my $options =
                   4173: 	'<label><input type="radio" name="vProb" value="no" checked="checked" /> '.&mt('no').' </label>'."\n".
                   4174: 	'<label><input type="radio" name="vProb" value="yes" /> '.&mt('yes').' </label>'."<br />\n";
1.539     riegler  4175:     $result.='&nbsp;<b>'.&mt('View Problem Text').': </b>'.$options;
1.485     albertel 4176: 
                   4177:     $options =
                   4178: 	'<label><input type="radio" name="lastSub" value="none" /> '.&mt('none').' </label>'."\n".
                   4179: 	'<label><input type="radio" name="lastSub" value="datesub" checked="checked" /> '.&mt('by dates and submissions').'</label>'."\n".
                   4180: 	'<label><input type="radio" name="lastSub" value="all" /> '.&mt('all details').' </label>'."\n";
1.539     riegler  4181:     $result.='&nbsp;<b>'.&mt('Submissions').': </b>'.$options;
1.432     banghart 4182:     
                   4183:     $result.=&build_section_inputs();
1.442     banghart 4184:     my $stu_status = join(':',&Apache::loncommon::get_env_multiple('form.Status'));
                   4185:     $result.='<input type="hidden" name="Status"  value="'.$stu_status.'" />'."\n".
1.72      ng       4186: 	'<input type="hidden" name="command" value="displayPage" />'."\n".
1.418     albertel 4187: 	'<input type="hidden" name="symb"    value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
1.257     albertel 4188: 	'<input type="hidden" name="saveState" value="'.$env{'form.saveState'}.'" />'."<br />\n";
1.72      ng       4189: 
1.539     riegler  4190:     $result.='&nbsp;<b>'.&mt('Use CODE').': </b> <input type="text" name="CODE" value="" /> <br />'."\n";
1.382     albertel 4191: 
1.80      ng       4192:     $result.='&nbsp;<input type="button" '.
1.539     riegler  4193: 	'onClick="javascript:checkPickOne(this.form);" value="'.&mt('Next').' &rarr;" /><br />'."\n";
1.72      ng       4194: 
1.68      ng       4195:     $request->print($result);
                   4196: 
1.485     albertel 4197:     my $studentTable.='&nbsp;<b>'.&mt('Select a student you wish to grade and then click on the Next button.').'</b><br />'.
1.484     albertel 4198: 	&Apache::loncommon::start_data_table().
                   4199: 	&Apache::loncommon::start_data_table_header_row().
1.485     albertel 4200: 	'<th align="right">&nbsp;'.&mt('No.').'</th>'.
1.484     albertel 4201: 	'<th>'.&nameUserString('header').'</th>'.
1.485     albertel 4202: 	'<th align="right">&nbsp;'.&mt('No.').'</th>'.
1.484     albertel 4203: 	'<th>'.&nameUserString('header').'</th>'.
                   4204: 	&Apache::loncommon::end_data_table_header_row();
1.68      ng       4205:  
1.76      ng       4206:     my (undef,undef,$fullname) = &getclasslist($getsec,'1');
1.68      ng       4207:     my $ptr = 1;
1.294     albertel 4208:     foreach my $student (sort 
                   4209: 			 {
                   4210: 			     if (lc($$fullname{$a}) ne lc($$fullname{$b})) {
                   4211: 				 return (lc($$fullname{$a}) cmp lc($$fullname{$b}));
                   4212: 			     }
                   4213: 			     return $a cmp $b;
                   4214: 			 } (keys(%$fullname))) {
1.68      ng       4215: 	my ($uname,$udom) = split(/:/,$student);
1.484     albertel 4216: 	$studentTable.=($ptr%2==1 ? &Apache::loncommon::start_data_table_row()
                   4217:                                   : '</td>');
1.126     ng       4218: 	$studentTable.='<td align="right">'.$ptr.'&nbsp;</td>';
1.288     albertel 4219: 	$studentTable.='<td>&nbsp;<label><input type="radio" name="student" value="'.$student.'" /> '
                   4220: 	    .&nameUserString(undef,$$fullname{$student},$uname,$udom)."</label>\n";
1.484     albertel 4221: 	$studentTable.=
                   4222: 	    ($ptr%2 == 0 ? '</td>'.&Apache::loncommon::end_data_table_row() 
                   4223:                          : '');
1.68      ng       4224: 	$ptr++;
                   4225:     }
1.484     albertel 4226:     if ($ptr%2 == 0) {
                   4227: 	$studentTable.='</td><td>&nbsp;</td><td>&nbsp;</td>'.
                   4228: 	    &Apache::loncommon::end_data_table_row();
                   4229:     }
                   4230:     $studentTable.=&Apache::loncommon::end_data_table()."\n";
1.126     ng       4231:     $studentTable.='<input type="button" '.
1.539     riegler  4232: 	'onClick="javascript:checkPickOne(this.form);" value="'.&mt('Next').' &rarr;" /></form>'."\n";
1.68      ng       4233: 
1.324     albertel 4234:     $studentTable.=&show_grading_menu_form($symb);
1.68      ng       4235:     $request->print($studentTable);
                   4236: 
                   4237:     return '';
                   4238: }
                   4239: 
                   4240: sub getSymbMap {
1.132     bowersj2 4241:     my $navmap = Apache::lonnavmaps::navmap->new();
1.68      ng       4242: 
                   4243:     my %symbx = ();
                   4244:     my @titles = ();
1.117     bowersj2 4245:     my $minder = 0;
                   4246: 
                   4247:     # Gather every sequence that has problems.
1.240     albertel 4248:     my @sequences = $navmap->retrieveResources(undef, sub { shift->is_map(); },
                   4249: 					       1,0,1);
1.117     bowersj2 4250:     for my $sequence ($navmap->getById('0.0'), @sequences) {
1.241     albertel 4251: 	if ($navmap->hasResource($sequence, sub { shift->is_problem(); }, 0) ) {
1.381     albertel 4252: 	    my $title = $minder.'.'.
                   4253: 		&HTML::Entities::encode($sequence->compTitle(),'"\'&');
                   4254: 	    push(@titles, $title); # minder in case two titles are identical
                   4255: 	    $symbx{$title} = &HTML::Entities::encode($sequence->symb(),'"\'&');
1.117     bowersj2 4256: 	    $minder++;
1.241     albertel 4257: 	}
1.68      ng       4258:     }
                   4259:     return \@titles,\%symbx;
                   4260: }
                   4261: 
1.72      ng       4262: #
                   4263: #--- Displays a page/sequence w/wo problems, w/wo submissions
1.68      ng       4264: sub displayPage {
                   4265:     my ($request) = shift;
                   4266: 
1.324     albertel 4267:     my ($symb) = &get_symb($request);
1.257     albertel 4268:     my $cdom      = $env{"course.$env{'request.course.id'}.domain"};
                   4269:     my $cnum      = $env{"course.$env{'request.course.id'}.num"};
                   4270:     my $getsec    = $env{'form.section'} eq '' ? 'all' : $env{'form.section'};
                   4271:     my $pageTitle = $env{'form.page'};
1.103     albertel 4272:     my ($classlist,undef,$fullname) = &getclasslist($getsec,'1');
1.257     albertel 4273:     my ($uname,$udom) = split(/:/,$env{'form.student'});
                   4274:     my $usec=$classlist->{$env{'form.student'}}[5];
1.168     albertel 4275: 
                   4276:     #need to make sure we have the correct data for later EXT calls, 
                   4277:     #thus invalidate the cache
                   4278:     &Apache::lonnet::devalidatecourseresdata(
1.257     albertel 4279:                  $env{'course.'.$env{'request.course.id'}.'.num'},
                   4280:                  $env{'course.'.$env{'request.course.id'}.'.domain'});
1.168     albertel 4281:     &Apache::lonnet::clear_EXT_cache_status();
                   4282: 
1.103     albertel 4283:     if (!&canview($usec)) {
1.485     albertel 4284: 	$request->print('<span class="LC_warning">'.&mt('Unable to view requested student. ([_1])',$env{'form.student'}).'</span>');
1.324     albertel 4285: 	$request->print(&show_grading_menu_form($symb));
1.103     albertel 4286: 	return;
                   4287:     }
1.398     albertel 4288:     my $result='<h3><span class="LC_info">&nbsp;'.$env{'form.title'}.'</span></h3>';
1.485     albertel 4289:     $result.='<h3>&nbsp;'.&mt('Student: [_1]',&nameUserString(undef,$$fullname{$env{'form.student'}},$uname,$udom)).
1.129     ng       4290: 	'</h3>'."\n";
1.500     albertel 4291:     $env{'form.CODE'} = uc($env{'form.CODE'});
1.501     foxr     4292:     if (&Apache::lonnet::validCODE(uc($env{'form.CODE'}))) {
1.485     albertel 4293: 	$result.='<h3>&nbsp;'.&mt('CODE: [_1]',$env{'form.CODE'}).'</h3>'."\n";
1.382     albertel 4294:     } else {
                   4295: 	delete($env{'form.CODE'});
                   4296:     }
1.71      ng       4297:     &sub_page_js($request);
                   4298:     $request->print($result);
                   4299: 
1.132     bowersj2 4300:     my $navmap = Apache::lonnavmaps::navmap->new();
1.257     albertel 4301:     my ($mapUrl, $id, $resUrl)=&Apache::lonnet::decode_symb($env{'form.page'});
1.68      ng       4302:     my $map = $navmap->getResourceByUrl($resUrl); # add to navmaps
1.288     albertel 4303:     if (!$map) {
1.485     albertel 4304: 	$request->print('<span class="LC_warning">'.&mt('Unable to view requested sequence. ([_1])',$resUrl).'</span>');
1.324     albertel 4305: 	$request->print(&show_grading_menu_form($symb));
1.288     albertel 4306: 	return; 
                   4307:     }
1.68      ng       4308:     my $iterator = $navmap->getIterator($map->map_start(),
                   4309: 					$map->map_finish());
                   4310: 
1.71      ng       4311:     my $studentTable='<form action="/adm/grades" method="post" name="gradePage">'."\n".
1.72      ng       4312: 	'<input type="hidden" name="command" value="gradeByPage" />'."\n".
1.257     albertel 4313: 	'<input type="hidden" name="fullname" value="'.$$fullname{$env{'form.student'}}.'" />'."\n".
                   4314: 	'<input type="hidden" name="student" value="'.$env{'form.student'}.'" />'."\n".
1.72      ng       4315: 	'<input type="hidden" name="page"    value="'.$pageTitle.'" />'."\n".
1.257     albertel 4316: 	'<input type="hidden" name="title"   value="'.$env{'form.title'}.'" />'."\n".
1.418     albertel 4317: 	'<input type="hidden" name="symb"    value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
1.125     ng       4318: 	'<input type="hidden" name="overRideScore" value="no" />'."\n".
1.257     albertel 4319: 	'<input type="hidden" name="saveState" value="'.$env{'form.saveState'}.'" />'."\n";
1.71      ng       4320: 
1.382     albertel 4321:     if (defined($env{'form.CODE'})) {
                   4322: 	$studentTable.=
                   4323: 	    '<input type="hidden" name="CODE" value="'.$env{'form.CODE'}.'" />'."\n";
                   4324:     }
1.381     albertel 4325:     my $checkIcon = '<img alt="'.&mt('Check Mark').
1.485     albertel 4326: 	'" src="'.&Apache::loncommon::lonhttpdurl($request->dir_config('lonIconsURL').'/check.gif').'" height="16" border="0" />';
1.71      ng       4327: 
1.485     albertel 4328:     $studentTable.='&nbsp;'.&mt('<b>Note:</b> Problems graded correct by the computer are marked with a [_1] symbol.',$checkIcon)."\n".
1.484     albertel 4329: 	&Apache::loncommon::start_data_table().
                   4330: 	&Apache::loncommon::start_data_table_header_row().
                   4331: 	'<th align="center">&nbsp;Prob.&nbsp;</th>'.
1.485     albertel 4332: 	'<th>&nbsp;'.($env{'form.vProb'} eq 'no' ? &mt('Title') : &mt('Problem Text')).'/'.&mt('Grade').'</th>'.
1.484     albertel 4333: 	&Apache::loncommon::end_data_table_header_row();
1.71      ng       4334: 
1.329     albertel 4335:     &Apache::lonxml::clear_problem_counter();
1.196     albertel 4336:     my ($depth,$question,$prob) = (1,1,1);
1.68      ng       4337:     $iterator->next(); # skip the first BEGIN_MAP
                   4338:     my $curRes = $iterator->next(); # for "current resource"
1.101     albertel 4339:     while ($depth > 0) {
1.68      ng       4340:         if($curRes == $iterator->BEGIN_MAP) { $depth++; }
1.100     bowersj2 4341:         if($curRes == $iterator->END_MAP) { $depth--; }
1.68      ng       4342: 
1.385     albertel 4343:         if (ref($curRes) && $curRes->is_problem()) {
1.91      albertel 4344: 	    my $parts = $curRes->parts();
1.68      ng       4345:             my $title = $curRes->compTitle();
1.71      ng       4346: 	    my $symbx = $curRes->symb();
1.484     albertel 4347: 	    $studentTable.=
                   4348: 		&Apache::loncommon::start_data_table_row().
                   4349: 		'<td align="center" valign="top" >'.$prob.
1.485     albertel 4350: 		(scalar(@{$parts}) == 1 ? '' 
                   4351: 		                        : '<br />('.&mt('[_1]&nbsp;parts)',
                   4352: 							scalar(@{$parts}))
                   4353: 		 ).
                   4354: 		 '</td>';
1.71      ng       4355: 	    $studentTable.='<td valign="top">';
1.382     albertel 4356: 	    my %form = ('CODE' => $env{'form.CODE'},);
1.257     albertel 4357: 	    if ($env{'form.vProb'} eq 'yes' ) {
1.144     albertel 4358: 		$studentTable.=&show_problem($request,$symbx,$uname,$udom,1,
1.383     albertel 4359: 					     undef,'both',\%form);
1.71      ng       4360: 	    } else {
1.382     albertel 4361: 		my $companswer = &Apache::loncommon::get_student_answers($symbx,$uname,$udom,$env{'request.course.id'},%form);
1.80      ng       4362: 		$companswer =~ s|<form(.*?)>||g;
                   4363: 		$companswer =~ s|</form>||g;
1.71      ng       4364: #		while ($companswer =~ /(<a href\=\"javascript:newWindow.*?Script Vars<\/a>)/s) { #<a href="javascript:newWindow</a>
1.116     ng       4365: #		    $companswer =~ s/$1/ /ms;
1.326     albertel 4366: #		    $request->print('match='.$1."<br />\n");
1.71      ng       4367: #		}
1.116     ng       4368: #		$companswer =~ s|<table border=\"1\">|<table border=\"0\">|g;
1.539     riegler  4369: 		$studentTable.='&nbsp;<b>'.$title.'</b>&nbsp;<br />&nbsp;<b>'.&mt('Correct answer').':</b><br />'.$companswer;
1.71      ng       4370: 	    }
                   4371: 
1.257     albertel 4372: 	    my %record = &Apache::lonnet::restore($symbx,$env{'request.course.id'},$udom,$uname);
1.125     ng       4373: 
1.257     albertel 4374: 	    if ($env{'form.lastSub'} eq 'datesub') {
1.71      ng       4375: 		if ($record{'version'} eq '') {
1.485     albertel 4376: 		    $studentTable.='<br />&nbsp;<span class="LC_warning">'.&mt('No recorded submission for this problem.').'</span><br />';
1.71      ng       4377: 		} else {
1.116     ng       4378: 		    my %responseType = ();
                   4379: 		    foreach my $partid (@{$parts}) {
1.147     albertel 4380: 			my @responseIds =$curRes->responseIds($partid);
                   4381: 			my @responseType =$curRes->responseType($partid);
                   4382: 			my %responseIds;
                   4383: 			for (my $i=0;$i<=$#responseIds;$i++) {
                   4384: 			    $responseIds{$responseIds[$i]}=$responseType[$i];
                   4385: 			}
                   4386: 			$responseType{$partid} = \%responseIds;
1.116     ng       4387: 		    }
1.148     albertel 4388: 		    $studentTable.= &displaySubByDates($symbx,\%record,$parts,\%responseType,$checkIcon,$uname,$udom);
1.147     albertel 4389: 
1.71      ng       4390: 		}
1.257     albertel 4391: 	    } elsif ($env{'form.lastSub'} eq 'all') {
                   4392: 		my $last = ($env{'form.lastSub'} eq 'last' ? 'last' : '');
1.71      ng       4393: 		$studentTable.=&Apache::loncommon::get_previous_attempt($symbx,$uname,$udom,
1.257     albertel 4394: 									$env{'request.course.id'},
1.71      ng       4395: 									'','.submission');
                   4396:  
                   4397: 	    }
1.103     albertel 4398: 	    if (&canmodify($usec)) {
                   4399: 		foreach my $partid (@{$parts}) {
                   4400: 		    $studentTable.=&gradeBox($request,$symbx,$uname,$udom,$question,$partid,\%record);
                   4401: 		    $studentTable.='<input type="hidden" name="q_'.$question.'" value="'.$partid.'" />'."\n";
                   4402: 		    $question++;
                   4403: 		}
1.196     albertel 4404: 		$prob++;
1.71      ng       4405: 	    }
                   4406: 	    $studentTable.='</td></tr>';
1.68      ng       4407: 
1.103     albertel 4408: 	}
1.68      ng       4409:         $curRes = $iterator->next();
                   4410:     }
                   4411: 
1.485     albertel 4412:     $studentTable.='</table>'."\n".
                   4413: 	'<input type="button" value="'.&mt('Save').'" '.
1.381     albertel 4414: 	'onClick="javascript:checkSubmitPage(this.form,'.$question.');" />'.
1.71      ng       4415: 	'</form>'."\n";
1.324     albertel 4416:     $studentTable.=&show_grading_menu_form($symb);
1.71      ng       4417:     $request->print($studentTable);
                   4418: 
                   4419:     return '';
1.119     ng       4420: }
                   4421: 
                   4422: sub displaySubByDates {
1.148     albertel 4423:     my ($symb,$record,$parts,$responseType,$checkIcon,$uname,$udom) = @_;
1.224     albertel 4424:     my $isCODE=0;
1.335     albertel 4425:     my $isTask = ($symb =~/\.task$/);
1.224     albertel 4426:     if (exists($record->{'resource.CODE'})) { $isCODE=1; }
1.467     albertel 4427:     my $studentTable=&Apache::loncommon::start_data_table().
                   4428: 	&Apache::loncommon::start_data_table_header_row().
                   4429: 	'<th>'.&mt('Date/Time').'</th>'.
                   4430: 	($isCODE?'<th>'.&mt('CODE').'</th>':'').
                   4431: 	'<th>'.&mt('Submission').'</th>'.
                   4432: 	'<th>'.&mt('Status').'</th>'.
                   4433: 	&Apache::loncommon::end_data_table_header_row();
1.119     ng       4434:     my ($version);
                   4435:     my %mark;
1.148     albertel 4436:     my %orders;
1.119     ng       4437:     $mark{'correct_by_student'} = $checkIcon;
1.147     albertel 4438:     if (!exists($$record{'1:timestamp'})) {
1.539     riegler  4439: 	return '<br />&nbsp;<span class="LC_warning">'.&mt('Nothing submitted - no attempts.').'</span><br />';
1.147     albertel 4440:     }
1.335     albertel 4441: 
                   4442:     my $interaction;
1.525     raeburn  4443:     my $no_increment = 1;
1.119     ng       4444:     for ($version=1;$version<=$$record{'version'};$version++) {
1.467     albertel 4445: 	my $timestamp = 
                   4446: 	    &Apache::lonlocal::locallocaltime($$record{$version.':timestamp'});
1.335     albertel 4447: 	if (exists($$record{$version.':resource.0.version'})) {
                   4448: 	    $interaction = $$record{$version.':resource.0.version'};
                   4449: 	}
                   4450: 
                   4451: 	my $where = ($isTask ? "$version:resource.$interaction"
                   4452: 		             : "$version:resource");
1.467     albertel 4453: 	$studentTable.=&Apache::loncommon::start_data_table_row().
                   4454: 	    '<td>'.$timestamp.'</td>';
1.224     albertel 4455: 	if ($isCODE) {
                   4456: 	    $studentTable.='<td>'.$record->{$version.':resource.CODE'}.'</td>';
                   4457: 	}
1.119     ng       4458: 	my @versionKeys = split(/\:/,$$record{$version.':keys'});
                   4459: 	my @displaySub = ();
                   4460: 	foreach my $partid (@{$parts}) {
1.335     albertel 4461: 	    my @matchKey = ($isTask ? sort(grep /^resource\.\d+\.\Q$partid\E\.award$/,@versionKeys)
                   4462: 			            : sort(grep /^resource\.\Q$partid\E\..*?\.submission$/,@versionKeys));
                   4463: 	    
                   4464: 
1.122     ng       4465: #	    next if ($$record{"$version:resource.$partid.solved"} eq '');
1.324     albertel 4466: 	    my $display_part=&get_display_part($partid,$symb);
1.147     albertel 4467: 	    foreach my $matchKey (@matchKey) {
1.198     albertel 4468: 		if (exists($$record{$version.':'.$matchKey}) &&
                   4469: 		    $$record{$version.':'.$matchKey} ne '') {
1.335     albertel 4470: 
                   4471: 		    my ($responseId)= ($isTask ? ($matchKey=~ /^resource\.(.*?)\.\Q$partid\E\.award$/)
                   4472: 				               : ($matchKey=~ /^resource\.\Q$partid\E\.(.*?)\.submission$/));
1.577     bisitz   4473:                     $displaySub[0].='<span class="LC_nobreak"';
                   4474:                     $displaySub[0].='<b>'.&mt('Part: [_1]',$display_part).'</b>'
                   4475:                                    .' <span class="LC_internal_info">'
                   4476:                                    .'('.&mt('Part ID: [_1]',$responseId).')'
                   4477:                                    .'</span>'
                   4478:                                    .' <b>';
1.335     albertel 4479: 		    if ($$record{"$where.$partid.tries"} eq '') {
1.577     bisitz   4480: 			$displaySub[0].=&mt('Trial not counted');
1.147     albertel 4481: 		    } else {
1.577     bisitz   4482: 			$displaySub[0].=&mt('Trial: [_1]',
1.467     albertel 4483: 					    $$record{"$where.$partid.tries"});
1.147     albertel 4484: 		    }
1.335     albertel 4485: 		    my $responseType=($isTask ? 'Task'
                   4486:                                               : $responseType->{$partid}->{$responseId});
1.148     albertel 4487: 		    if (!exists($orders{$partid})) { $orders{$partid}={}; }
                   4488: 		    if (!exists($orders{$partid}->{$responseId})) {
                   4489: 			$orders{$partid}->{$responseId}=
1.525     raeburn  4490: 			    &get_order($partid,$responseId,$symb,$uname,$udom,
                   4491:                                        $no_increment);
1.148     albertel 4492: 		    }
1.577     bisitz   4493: 		    $displaySub[0].='</b></span>'; # /nobreak
                   4494: 		    $displaySub[0].='&nbsp; '.
1.336     albertel 4495: 			&cleanRecord($$record{$version.':'.$matchKey},$responseType,$symb,$partid,$responseId,$record,$orders{$partid}->{$responseId},"$version:",$uname,$udom).'<br />';
1.147     albertel 4496: 		}
                   4497: 	    }
1.335     albertel 4498: 	    if (exists($$record{"$where.$partid.checkedin"})) {
1.485     albertel 4499: 		$displaySub[1].=&mt('Checked in by [_1] into slot [_2]',
                   4500: 				    $$record{"$where.$partid.checkedin"},
                   4501: 				    $$record{"$where.$partid.checkedin.slot"}).
                   4502: 					'<br />';
1.335     albertel 4503: 	    }
                   4504: 	    if (exists $$record{"$where.$partid.award"}) {
1.485     albertel 4505: 		$displaySub[1].='<b>'.&mt('Part:').'</b>&nbsp;'.$display_part.' &nbsp;'.
1.335     albertel 4506: 		    lc($$record{"$where.$partid.award"}).' '.
                   4507: 		    $mark{$$record{"$where.$partid.solved"}}.
1.147     albertel 4508: 		    '<br />';
                   4509: 	    }
1.335     albertel 4510: 	    if (exists $$record{"$where.$partid.regrader"}) {
                   4511: 		$displaySub[2].=$$record{"$where.$partid.regrader"}.
                   4512: 		    ' (<b>'.&mt('Part').':</b> '.$display_part.')';
                   4513: 	    } elsif ($$record{"$version:resource.$partid.regrader"} =~ /\S/) {
                   4514: 		$displaySub[2].=
                   4515: 		    $$record{"$version:resource.$partid.regrader"}.
1.207     albertel 4516: 		    ' (<b>'.&mt('Part').':</b> '.$display_part.')';
1.147     albertel 4517: 	    }
                   4518: 	}
                   4519: 	# needed because old essay regrader has not parts info
                   4520: 	if (exists $$record{"$version:resource.regrader"}) {
                   4521: 	    $displaySub[2].=$$record{"$version:resource.regrader"};
                   4522: 	}
                   4523: 	$studentTable.='<td>'.$displaySub[0].'&nbsp;</td><td>'.$displaySub[1];
                   4524: 	if ($displaySub[2]) {
1.467     albertel 4525: 	    $studentTable.=&mt('Manually graded by [_1]',$displaySub[2]);
1.147     albertel 4526: 	}
1.467     albertel 4527: 	$studentTable.='&nbsp;</td>'.
                   4528: 	    &Apache::loncommon::end_data_table_row();
1.119     ng       4529:     }
1.467     albertel 4530:     $studentTable.=&Apache::loncommon::end_data_table();
1.119     ng       4531:     return $studentTable;
1.71      ng       4532: }
                   4533: 
                   4534: sub updateGradeByPage {
                   4535:     my ($request) = shift;
                   4536: 
1.257     albertel 4537:     my $cdom      = $env{"course.$env{'request.course.id'}.domain"};
                   4538:     my $cnum      = $env{"course.$env{'request.course.id'}.num"};
                   4539:     my $getsec    = $env{'form.section'} eq '' ? 'all' : $env{'form.section'};
                   4540:     my $pageTitle = $env{'form.page'};
1.103     albertel 4541:     my ($classlist,undef,$fullname) = &getclasslist($getsec,'1');
1.257     albertel 4542:     my ($uname,$udom) = split(/:/,$env{'form.student'});
                   4543:     my $usec=$classlist->{$env{'form.student'}}[5];
1.103     albertel 4544:     if (!&canmodify($usec)) {
1.526     raeburn  4545: 	$request->print('<span class="LC_warning">'.&mt('Unable to modify requested student ([_1])',$env{'form.student'}).'</span>');
1.324     albertel 4546: 	$request->print(&show_grading_menu_form($env{'form.symb'}));
1.103     albertel 4547: 	return;
                   4548:     }
1.398     albertel 4549:     my $result='<h3><span class="LC_info">&nbsp;'.$env{'form.title'}.'</span></h3>';
1.526     raeburn  4550:     $result.='<h3>&nbsp;'.&mt('Student: ').&nameUserString(undef,$env{'form.fullname'},$uname,$udom).
1.129     ng       4551: 	'</h3>'."\n";
1.70      ng       4552: 
1.68      ng       4553:     $request->print($result);
                   4554: 
1.132     bowersj2 4555:     my $navmap = Apache::lonnavmaps::navmap->new();
1.257     albertel 4556:     my ($mapUrl, $id, $resUrl) = &Apache::lonnet::decode_symb( $env{'form.page'});
1.71      ng       4557:     my $map = $navmap->getResourceByUrl($resUrl); # add to navmaps
1.288     albertel 4558:     if (!$map) {
1.527     raeburn  4559: 	$request->print('<span class="LC_warning">'.&mt('Unable to grade requested sequence ([_1]).',$resUrl).'</span>');
1.324     albertel 4560: 	my ($symb)=&get_symb($request);
                   4561: 	$request->print(&show_grading_menu_form($symb));
1.288     albertel 4562: 	return; 
                   4563:     }
1.71      ng       4564:     my $iterator = $navmap->getIterator($map->map_start(),
                   4565: 					$map->map_finish());
1.70      ng       4566: 
1.484     albertel 4567:     my $studentTable=
                   4568: 	&Apache::loncommon::start_data_table().
                   4569: 	&Apache::loncommon::start_data_table_header_row().
1.485     albertel 4570: 	'<th align="center">&nbsp;'.&mt('Prob.').'&nbsp;</th>'.
                   4571: 	'<th>&nbsp;'.&mt('Title').'&nbsp;</th>'.
                   4572: 	'<th>&nbsp;'.&mt('Previous Score').'&nbsp;</th>'.
                   4573: 	'<th>&nbsp;'.&mt('New Score').'&nbsp;</th>'.
1.484     albertel 4574: 	&Apache::loncommon::end_data_table_header_row();
1.71      ng       4575: 
                   4576:     $iterator->next(); # skip the first BEGIN_MAP
                   4577:     my $curRes = $iterator->next(); # for "current resource"
1.196     albertel 4578:     my ($depth,$question,$prob,$changeflag)= (1,1,1,0);
1.101     albertel 4579:     while ($depth > 0) {
1.71      ng       4580:         if($curRes == $iterator->BEGIN_MAP) { $depth++; }
1.100     bowersj2 4581:         if($curRes == $iterator->END_MAP) { $depth--; }
1.71      ng       4582: 
1.385     albertel 4583:         if (ref($curRes) && $curRes->is_problem()) {
1.91      albertel 4584: 	    my $parts = $curRes->parts();
1.71      ng       4585:             my $title = $curRes->compTitle();
                   4586: 	    my $symbx = $curRes->symb();
1.484     albertel 4587: 	    $studentTable.=
                   4588: 		&Apache::loncommon::start_data_table_row().
                   4589: 		'<td align="center" valign="top" >'.$prob.
1.485     albertel 4590: 		(scalar(@{$parts}) == 1 ? '' 
1.526     raeburn  4591:                                         : '<br />('.&mt('[quant,_1,&nbsp;part]',scalar(@{$parts}))
                   4592: 		.')').'</td>';
1.71      ng       4593: 	    $studentTable.='<td valign="top">&nbsp;<b>'.$title.'</b>&nbsp;</td>';
                   4594: 
                   4595: 	    my %newrecord=();
                   4596: 	    my @displayPts=();
1.269     raeburn  4597:             my %aggregate = ();
                   4598:             my $aggregateflag = 0;
1.71      ng       4599: 	    foreach my $partid (@{$parts}) {
1.257     albertel 4600: 		my $newpts = $env{'form.GD_BOX'.$question.'_'.$partid};
                   4601: 		my $oldpts = $env{'form.oldpts'.$question.'_'.$partid};
1.71      ng       4602: 
1.257     albertel 4603: 		my $wgt = $env{'form.WGT'.$question.'_'.$partid} != 0 ? 
                   4604: 		    $env{'form.WGT'.$question.'_'.$partid} : 1;
1.71      ng       4605: 		my $partial = $newpts/$wgt;
                   4606: 		my $score;
                   4607: 		if ($partial > 0) {
                   4608: 		    $score = 'correct_by_override';
1.125     ng       4609: 		} elsif ($newpts ne '') { #empty is taken as 0
1.71      ng       4610: 		    $score = 'incorrect_by_override';
                   4611: 		}
1.257     albertel 4612: 		my $dropMenu = $env{'form.GD_SEL'.$question.'_'.$partid};
1.125     ng       4613: 		if ($dropMenu eq 'excused') {
1.71      ng       4614: 		    $partial = '';
                   4615: 		    $score = 'excused';
1.125     ng       4616: 		} elsif ($dropMenu eq 'reset status'
1.257     albertel 4617: 			 && $env{'form.solved'.$question.'_'.$partid} ne '') { #update only if previous record exists
1.125     ng       4618: 		    $newrecord{'resource.'.$partid.'.tries'} = 0;
                   4619: 		    $newrecord{'resource.'.$partid.'.solved'} = '';
                   4620: 		    $newrecord{'resource.'.$partid.'.award'} = '';
                   4621: 		    $newrecord{'resource.'.$partid.'.awarded'} = 0;
1.257     albertel 4622: 		    $newrecord{'resource.'.$partid.'.regrader'} = "$env{'user.name'}:$env{'user.domain'}";
1.125     ng       4623: 		    $changeflag++;
                   4624: 		    $newpts = '';
1.269     raeburn  4625:                     
                   4626:                     my $aggtries =  $env{'form.aggtries'.$question.'_'.$partid};
                   4627:                     my $totaltries = $env{'form.totaltries'.$question.'_'.$partid};
                   4628:                     my $solvedstatus = $env{'form.solved'.$question.'_'.$partid};
                   4629:                     if ($aggtries > 0) {
                   4630:                         &decrement_aggs($symbx,$partid,\%aggregate,$aggtries,$totaltries,$solvedstatus);
                   4631:                         $aggregateflag = 1;
                   4632:                     }
1.71      ng       4633: 		}
1.324     albertel 4634: 		my $display_part=&get_display_part($partid,$curRes->symb());
1.257     albertel 4635: 		my $oldstatus = $env{'form.solved'.$question.'_'.$partid};
1.526     raeburn  4636: 		$displayPts[0].='&nbsp;<b>'.&mt('Part').':</b> '.$display_part.' = '.
1.71      ng       4637: 		    (($oldstatus eq 'excused') ? 'excused' : $oldpts).
1.326     albertel 4638: 		    '&nbsp;<br />';
1.526     raeburn  4639: 		$displayPts[1].='&nbsp;<b>'.&mt('Part').':</b> '.$display_part.' = '.
1.125     ng       4640: 		     (($score eq 'excused') ? 'excused' : $newpts).
1.326     albertel 4641: 		    '&nbsp;<br />';
1.71      ng       4642: 		$question++;
1.380     albertel 4643: 		next if ($dropMenu eq 'reset status' || ($newpts eq $oldpts && $score ne 'excused'));
1.125     ng       4644: 
1.71      ng       4645: 		$newrecord{'resource.'.$partid.'.awarded'}  = $partial if $partial ne '';
1.125     ng       4646: 		$newrecord{'resource.'.$partid.'.solved'}   = $score if $score ne '';
1.257     albertel 4647: 		$newrecord{'resource.'.$partid.'.regrader'} = "$env{'user.name'}:$env{'user.domain'}"
1.125     ng       4648: 		    if (scalar(keys(%newrecord)) > 0);
1.71      ng       4649: 
                   4650: 		$changeflag++;
                   4651: 	    }
                   4652: 	    if (scalar(keys(%newrecord)) > 0) {
1.382     albertel 4653: 		my %record = 
                   4654: 		    &Apache::lonnet::restore($symbx,$env{'request.course.id'},
                   4655: 					     $udom,$uname);
                   4656: 
                   4657: 		if (&Apache::lonnet::validCODE($env{'form.CODE'})) {
                   4658: 		    $newrecord{'resource.CODE'} = $env{'form.CODE'};
                   4659: 		} elsif (&Apache::lonnet::validCODE($record{'resource.CODE'})) {
                   4660: 		    $newrecord{'resource.CODE'} = '';
                   4661: 		}
1.257     albertel 4662: 		&Apache::lonnet::cstore(\%newrecord,$symbx,$env{'request.course.id'},
1.71      ng       4663: 					$udom,$uname);
1.382     albertel 4664: 		%record = &Apache::lonnet::restore($symbx,
                   4665: 						   $env{'request.course.id'},
                   4666: 						   $udom,$uname);
1.380     albertel 4667: 		&check_and_remove_from_queue($parts,\%record,undef,$symbx,
                   4668: 					     $cdom,$cnum,$udom,$uname);
1.71      ng       4669: 	    }
1.380     albertel 4670: 	    
1.269     raeburn  4671:             if ($aggregateflag) {
                   4672:                 &Apache::lonnet::cinc('nohist_resourcetracker',\%aggregate,
                   4673:                       $env{'course.'.$env{'request.course.id'}.'.domain'},
                   4674:                       $env{'course.'.$env{'request.course.id'}.'.num'});
                   4675:             }
1.125     ng       4676: 
1.71      ng       4677: 	    $studentTable.='<td valign="top">'.$displayPts[0].'</td>'.
                   4678: 		'<td valign="top">'.$displayPts[1].'</td>'.
1.484     albertel 4679: 		&Apache::loncommon::end_data_table_row();
1.68      ng       4680: 
1.196     albertel 4681: 	    $prob++;
1.68      ng       4682: 	}
1.71      ng       4683:         $curRes = $iterator->next();
1.68      ng       4684:     }
1.98      albertel 4685: 
1.484     albertel 4686:     $studentTable.=&Apache::loncommon::end_data_table();
1.324     albertel 4687:     $studentTable.=&show_grading_menu_form($env{'form.symb'});
1.526     raeburn  4688:     my $grademsg=($changeflag == 0 ? &mt('No score was changed or updated.') :
                   4689: 		  &mt('The scores were changed for [quant,_1,problem].',
                   4690: 		  $changeflag));
1.76      ng       4691:     $request->print($grademsg.$studentTable);
1.68      ng       4692: 
1.70      ng       4693:     return '';
                   4694: }
                   4695: 
1.72      ng       4696: #-------- end of section for handling grading by page/sequence ---------
                   4697: #
                   4698: #-------------------------------------------------------------------
                   4699: 
1.581   ! www      4700: #-------------------- Bubblesheet (Scantron) Grading -------------------
1.75      albertel 4701: #
                   4702: #------ start of section for handling grading by page/sequence ---------
                   4703: 
1.423     albertel 4704: =pod
                   4705: 
                   4706: =head1 Bubble sheet grading routines
                   4707: 
1.424     albertel 4708:   For this documentation:
                   4709: 
                   4710:    'scanline' refers to the full line of characters
                   4711:    from the file that we are parsing that represents one entire sheet
                   4712: 
                   4713:    'bubble line' refers to the data
                   4714:    representing the line of bubbles that are on the physical bubble sheet
                   4715: 
                   4716: 
                   4717: The overall process is that a scanned in bubble sheet data is uploaded
                   4718: into a course. When a user wants to grade, they select a
                   4719: sequence/folder of resources, a file of bubble sheet info, and pick
                   4720: one of the predefined configurations for what each scanline looks
                   4721: like.
                   4722: 
                   4723: Next each scanline is checked for any errors of either 'missing
1.435     foxr     4724: bubbles' (it's an error because it may have been mis-scanned
1.424     albertel 4725: because too light bubbling), 'double bubble' (each bubble line should
                   4726: have no more that one letter picked), invalid or duplicated CODE,
1.556     weissno  4727: invalid student/employee ID
1.424     albertel 4728: 
                   4729: If the CODE option is used that determines the randomization of the
1.556     weissno  4730: homework problems, either way the student/employee ID is looked up into a
1.424     albertel 4731: username:domain.
                   4732: 
                   4733: During the validation phase the instructor can choose to skip scanlines. 
                   4734: 
1.435     foxr     4735: After the validation phase, there are now 3 bubble sheet files
1.424     albertel 4736: 
                   4737:   scantron_original_filename (unmodified original file)
                   4738:   scantron_corrected_filename (file where the corrected information has replaced the original information)
                   4739:   scantron_skipped_filename (contains the exact text of scanlines that where skipped)
                   4740: 
                   4741: Also there is a separate hash nohist_scantrondata that contains extra
                   4742: correction information that isn't representable in the bubble sheet
                   4743: file (see &scantron_getfile() for more information)
                   4744: 
                   4745: After all scanlines are either valid, marked as valid or skipped, then
                   4746: foreach line foreach problem in the picked sequence, an ssi request is
                   4747: made that simulates a user submitting their selected letter(s) against
                   4748: the homework problem.
1.423     albertel 4749: 
                   4750: =over 4
                   4751: 
                   4752: 
                   4753: 
                   4754: =item defaultFormData
                   4755: 
                   4756:   Returns html hidden inputs used to hold context/default values.
                   4757: 
                   4758:  Arguments:
                   4759:   $symb - $symb of the current resource 
                   4760: 
                   4761: =cut
1.422     foxr     4762: 
1.81      albertel 4763: sub defaultFormData {
1.324     albertel 4764:     my ($symb)=@_;
1.447     foxr     4765:     return '<input type="hidden" name="symb"    value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
1.257     albertel 4766:      '<input type="hidden" name="saveState" value="'.$env{'form.saveState'}.'" />'."\n".
                   4767:      '<input type="hidden" name="probTitle" value="'.$env{'form.probTitle'}.'" />'."\n";
1.81      albertel 4768: }
                   4769: 
1.447     foxr     4770: 
1.423     albertel 4771: =pod 
                   4772: 
                   4773: =item getSequenceDropDown
                   4774: 
                   4775:    Return html dropdown of possible sequences to grade
                   4776:  
                   4777:  Arguments:
                   4778:    $symb - $symb of the current resource 
                   4779: 
                   4780: =cut
1.422     foxr     4781: 
1.75      albertel 4782: sub getSequenceDropDown {
1.423     albertel 4783:     my ($symb)=@_;
1.75      albertel 4784:     my $result='<select name="selectpage">'."\n";
1.423     albertel 4785:     my ($titles,$symbx) = &getSymbMap();
1.137     albertel 4786:     my ($curpage)=&Apache::lonnet::decode_symb($symb); 
1.75      albertel 4787:     my $ctr=0;
                   4788:     foreach (@$titles) {
                   4789: 	my ($minder,$showtitle) = ($_ =~ /(\d+)\.(.*)/);
                   4790: 	$result.='<option value="'.$$symbx{$_}.'" '.
1.401     albertel 4791: 	    ($$symbx{$_} =~ /$curpage$/ ? 'selected="selected"' : '').
1.75      albertel 4792: 	    '>'.$showtitle.'</option>'."\n";
                   4793: 	$ctr++;
                   4794:     }
                   4795:     $result.= '</select>';
                   4796:     return $result;
                   4797: }
                   4798: 
1.495     albertel 4799: my %bubble_lines_per_response;     # no. bubble lines for each response.
1.554     raeburn  4800:                                    # key is zero-based index - 0, 1, 2 ...
1.495     albertel 4801: 
                   4802: my %first_bubble_line;             # First bubble line no. for each bubble.
                   4803: 
1.509     raeburn  4804: my %subdivided_bubble_lines;       # no. bubble lines for optionresponse, 
                   4805:                                    # matchresponse or rankresponse, where 
                   4806:                                    # an individual response can have multiple 
                   4807:                                    # lines
1.503     raeburn  4808: 
                   4809: my %responsetype_per_response;     # responsetype for each response
                   4810: 
1.495     albertel 4811: # Save and restore the bubble lines array to the form env.
                   4812: 
                   4813: 
                   4814: sub save_bubble_lines {
                   4815:     foreach my $line (keys(%bubble_lines_per_response)) {
                   4816: 	$env{"form.scantron.bubblelines.$line"}  = $bubble_lines_per_response{$line};
                   4817: 	$env{"form.scantron.first_bubble_line.$line"} =
                   4818: 	    $first_bubble_line{$line};
1.503     raeburn  4819:         $env{"form.scantron.sub_bubblelines.$line"} = 
                   4820:             $subdivided_bubble_lines{$line};
                   4821:         $env{"form.scantron.responsetype.$line"} =
                   4822:             $responsetype_per_response{$line};
1.495     albertel 4823:     }
                   4824: }
                   4825: 
                   4826: 
                   4827: sub restore_bubble_lines {
                   4828:     my $line = 0;
                   4829:     %bubble_lines_per_response = ();
                   4830:     while ($env{"form.scantron.bubblelines.$line"}) {
                   4831: 	my $value = $env{"form.scantron.bubblelines.$line"};
                   4832: 	$bubble_lines_per_response{$line} = $value;
                   4833: 	$first_bubble_line{$line}  =
                   4834: 	    $env{"form.scantron.first_bubble_line.$line"};
1.503     raeburn  4835:         $subdivided_bubble_lines{$line} =
                   4836:             $env{"form.scantron.sub_bubblelines.$line"};
                   4837:         $responsetype_per_response{$line} =
                   4838:             $env{"form.scantron.responsetype.$line"};
1.495     albertel 4839: 	$line++;
                   4840:     }
                   4841: }
                   4842: 
                   4843: #  Given the parsed scanline, get the response for 
                   4844: #  'answer' number n:
                   4845: 
                   4846: sub get_response_bubbles {
                   4847:     my ($parsed_line, $response)  = @_;
                   4848: 
                   4849:     my $bubble_line = $first_bubble_line{$response-1} +1;
                   4850:     my $bubble_lines= $bubble_lines_per_response{$response-1};
                   4851:     
                   4852:     my $selected = "";
                   4853: 
                   4854:     for (my $bline = 0; $bline < $bubble_lines; $bline++) {
                   4855: 	$selected .= $$parsed_line{"scantron.$bubble_line.answer"}.":";
                   4856: 	$bubble_line++;
                   4857:     }
                   4858:     return $selected;
                   4859: }
1.423     albertel 4860: 
                   4861: =pod 
                   4862: 
                   4863: =item scantron_filenames
                   4864: 
                   4865:    Returns a list of the scantron files in the current course 
                   4866: 
                   4867: =cut
1.422     foxr     4868: 
1.202     albertel 4869: sub scantron_filenames {
1.257     albertel 4870:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
                   4871:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
1.517     raeburn  4872:     my $getpropath = 1;
1.157     albertel 4873:     my @files=&Apache::lonnet::dirlist('userfiles',$cdom,$cname,
1.517     raeburn  4874:                                        $getpropath);
1.202     albertel 4875:     my @possiblenames;
1.201     albertel 4876:     foreach my $filename (sort(@files)) {
1.157     albertel 4877: 	($filename)=split(/&/,$filename);
                   4878: 	if ($filename!~/^scantron_orig_/) { next ; }
                   4879: 	$filename=~s/^scantron_orig_//;
1.202     albertel 4880: 	push(@possiblenames,$filename);
                   4881:     }
                   4882:     return @possiblenames;
                   4883: }
                   4884: 
1.423     albertel 4885: =pod 
                   4886: 
                   4887: =item scantron_uploads
                   4888: 
                   4889:    Returns  html drop-down list of scantron files in current course.
                   4890: 
                   4891:  Arguments:
                   4892:    $file2grade - filename to set as selected in the dropdown
                   4893: 
                   4894: =cut
1.422     foxr     4895: 
1.202     albertel 4896: sub scantron_uploads {
1.209     ng       4897:     my ($file2grade) = @_;
1.202     albertel 4898:     my $result=	'<select name="scantron_selectfile">';
                   4899:     $result.="<option></option>";
                   4900:     foreach my $filename (sort(&scantron_filenames())) {
1.401     albertel 4901: 	$result.="<option".($filename eq $file2grade ? ' selected="selected"':'').">$filename</option>\n";
1.81      albertel 4902:     }
                   4903:     $result.="</select>";
                   4904:     return $result;
                   4905: }
                   4906: 
1.423     albertel 4907: =pod 
                   4908: 
                   4909: =item scantron_scantab
                   4910: 
                   4911:   Returns html drop down of the scantron formats in the scantronformat.tab
                   4912:   file.
                   4913: 
                   4914: =cut
1.422     foxr     4915: 
1.82      albertel 4916: sub scantron_scantab {
                   4917:     my $result='<select name="scantron_format">'."\n";
1.191     albertel 4918:     $result.='<option></option>'."\n";
1.518     raeburn  4919:     my @lines = &get_scantronformat_file();
                   4920:     if (@lines > 0) {
                   4921:         foreach my $line (@lines) {
                   4922:             next if (($line =~ /^\#/) || ($line eq ''));
                   4923: 	    my ($name,$descrip)=split(/:/,$line);
                   4924: 	    $result.='<option value="'.$name.'">'.$descrip.'</option>'."\n";
                   4925:         }
1.82      albertel 4926:     }
                   4927:     $result.='</select>'."\n";
1.518     raeburn  4928:     return $result;
                   4929: }
                   4930: 
                   4931: =pod
                   4932: 
                   4933: =item get_scantronformat_file
                   4934: 
                   4935:   Returns an array containing lines from the scantron format file for
                   4936:   the domain of the course.
                   4937: 
                   4938:   If a url for a custom.tab file is listed in domain's configuration.db, 
                   4939:   lines are from this file.
                   4940: 
                   4941:   Otherwise, if a default.tab has been published in RES space by the 
                   4942:   domainconfig user, lines are from this file.
                   4943: 
                   4944:   Otherwise, fall back to getting lines from the legacy file on the
1.519     raeburn  4945:   local server:  /home/httpd/lonTabs/default_scantronformat.tab    
1.82      albertel 4946: 
1.518     raeburn  4947: =cut
                   4948: 
                   4949: sub get_scantronformat_file {
                   4950:     my $cdom= $env{'course.'.$env{'request.course.id'}.'.domain'};
                   4951:     my %domconfig = &Apache::lonnet::get_dom('configuration',['scantron'],$cdom);
                   4952:     my $gottab = 0;
                   4953:     my @lines;
                   4954:     if (ref($domconfig{'scantron'}) eq 'HASH') {
                   4955:         if ($domconfig{'scantron'}{'scantronformat'} ne '') {
                   4956:             my $formatfile = &Apache::lonnet::getfile($Apache::lonnet::perlvar{'lonDocRoot'}.$domconfig{'scantron'}{'scantronformat'});
                   4957:             if ($formatfile ne '-1') {
                   4958:                 @lines = split("\n",$formatfile,-1);
                   4959:                 $gottab = 1;
                   4960:             }
                   4961:         }
                   4962:     }
                   4963:     if (!$gottab) {
                   4964:         my $confname = $cdom.'-domainconfig';
                   4965:         my $default = $Apache::lonnet::perlvar{'lonDocRoot'}.'/res/'.$cdom.'/'.$confname.'/default.tab';
                   4966:         my $formatfile =  &Apache::lonnet::getfile($default);
                   4967:         if ($formatfile ne '-1') {
                   4968:             @lines = split("\n",$formatfile,-1);
                   4969:             $gottab = 1;
                   4970:         }
                   4971:     }
                   4972:     if (!$gottab) {
1.519     raeburn  4973:         my @domains = &Apache::lonnet::current_machine_domains();
                   4974:         if (grep(/^\Q$cdom\E$/,@domains)) {
                   4975:             my $fh=Apache::File->new($Apache::lonnet::perlvar{'lonTabDir'}.'/scantronformat.tab');
                   4976:             @lines = <$fh>;
                   4977:             close($fh);
                   4978:         } else {
                   4979:             my $fh=Apache::File->new($Apache::lonnet::perlvar{'lonTabDir'}.'/default_scantronformat.tab');
                   4980:             @lines = <$fh>;
                   4981:             close($fh);
                   4982:         }
1.518     raeburn  4983:     }
                   4984:     return @lines;
1.82      albertel 4985: }
                   4986: 
1.423     albertel 4987: =pod 
                   4988: 
                   4989: =item scantron_CODElist
                   4990: 
                   4991:   Returns html drop down of the saved CODE lists from current course,
                   4992:   generated from earlier printings.
                   4993: 
                   4994: =cut
1.422     foxr     4995: 
1.186     albertel 4996: sub scantron_CODElist {
1.257     albertel 4997:     my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   4998:     my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
1.186     albertel 4999:     my @names=&Apache::lonnet::getkeys('CODEs',$cdom,$cnum);
                   5000:     my $namechoice='<option></option>';
1.225     albertel 5001:     foreach my $name (sort {uc($a) cmp uc($b)} @names) {
1.191     albertel 5002: 	if ($name =~ /^error: 2 /) { next; }
1.278     albertel 5003: 	if ($name =~ /^type\0/) { next; }
1.186     albertel 5004: 	$namechoice.='<option value="'.$name.'">'.$name.'</option>';
                   5005:     }
                   5006:     $namechoice='<select name="scantron_CODElist">'.$namechoice.'</select>';
                   5007:     return $namechoice;
                   5008: }
                   5009: 
1.423     albertel 5010: =pod 
                   5011: 
                   5012: =item scantron_CODEunique
                   5013: 
                   5014:   Returns the html for "Each CODE to be used once" radio.
                   5015: 
                   5016: =cut
1.422     foxr     5017: 
1.186     albertel 5018: sub scantron_CODEunique {
1.532     bisitz   5019:     my $result='<span class="LC_nobreak">
1.272     albertel 5020:                  <label><input type="radio" name="scantron_CODEunique"
1.423     albertel 5021:                         value="yes" checked="checked" />'.&mt('Yes').' </label>
1.381     albertel 5022:                 </span>
1.532     bisitz   5023:                 <span class="LC_nobreak">
1.272     albertel 5024:                  <label><input type="radio" name="scantron_CODEunique"
1.423     albertel 5025:                         value="no" />'.&mt('No').' </label>
1.381     albertel 5026:                 </span>';
1.186     albertel 5027:     return $result;
                   5028: }
1.423     albertel 5029: 
                   5030: =pod 
                   5031: 
                   5032: =item scantron_selectphase
                   5033: 
                   5034:   Generates the initial screen to start the bubble sheet process.
                   5035:   Allows for - starting a grading run.
1.424     albertel 5036:              - downloading existing scan data (original, corrected
1.423     albertel 5037:                                                 or skipped info)
                   5038: 
                   5039:              - uploading new scan data
                   5040: 
                   5041:  Arguments:
                   5042:   $r          - The Apache request object
                   5043:   $file2grade - name of the file that contain the scanned data to score
                   5044: 
                   5045: =cut
1.186     albertel 5046: 
1.75      albertel 5047: sub scantron_selectphase {
1.209     ng       5048:     my ($r,$file2grade) = @_;
1.324     albertel 5049:     my ($symb)=&get_symb($r);
1.75      albertel 5050:     if (!$symb) {return '';}
1.423     albertel 5051:     my $sequence_selector=&getSequenceDropDown($symb);
1.324     albertel 5052:     my $default_form_data=&defaultFormData($symb);
                   5053:     my $grading_menu_button=&show_grading_menu_form($symb);
1.209     ng       5054:     my $file_selector=&scantron_uploads($file2grade);
1.82      albertel 5055:     my $format_selector=&scantron_scantab();
1.186     albertel 5056:     my $CODE_selector=&scantron_CODElist();
                   5057:     my $CODE_unique=&scantron_CODEunique();
1.75      albertel 5058:     my $result;
1.422     foxr     5059: 
1.513     foxr     5060:     $ssi_error = 0;
                   5061: 
1.422     foxr     5062:     # Chunk of form to prompt for a file to grade and how:
                   5063: 
1.489     albertel 5064:     $result.= '
                   5065:     <br />
                   5066:     <form method="post" enctype="multipart/form-data" action="/adm/grades" name="scantron_process">
                   5067:     <input type="hidden" name="command" value="scantron_warning" />
                   5068:     '.$default_form_data.'
                   5069:     '.&Apache::loncommon::start_data_table('LC_scantron_action').'
                   5070:        '.&Apache::loncommon::start_data_table_header_row().'
                   5071:             <th colspan="2">
1.492     albertel 5072:               &nbsp;'.&mt('Specify file and which Folder/Sequence to grade').'
1.489     albertel 5073:             </th>
                   5074:        '.&Apache::loncommon::end_data_table_header_row().'
                   5075:        '.&Apache::loncommon::start_data_table_row().'
1.492     albertel 5076:             <td> '.&mt('Sequence to grade:').' </td><td> '.$sequence_selector.' </td>
1.489     albertel 5077:        '.&Apache::loncommon::end_data_table_row().'
                   5078:        '.&Apache::loncommon::start_data_table_row().'
1.572     www      5079:             <td> '.&mt('Filename of bubblesheet data file:').' </td><td> '.$file_selector.' </td>
1.489     albertel 5080:        '.&Apache::loncommon::end_data_table_row().'
                   5081:        '.&Apache::loncommon::start_data_table_row().'
1.572     www      5082:             <td> '.&mt('Format of bubblesheet data file:').' </td><td> '.$format_selector.' </td>
1.489     albertel 5083:        '.&Apache::loncommon::end_data_table_row().'
                   5084:        '.&Apache::loncommon::start_data_table_row().'
1.492     albertel 5085:             <td> '.&mt('Saved CODEs to validate against:').' </td><td> '.$CODE_selector.' </td>
1.489     albertel 5086:        '.&Apache::loncommon::end_data_table_row().'
                   5087:        '.&Apache::loncommon::start_data_table_row().'
1.492     albertel 5088:             <td> '.&mt('Each CODE is only to be used once:').'</td><td> '.$CODE_unique.' </td>
1.489     albertel 5089:        '.&Apache::loncommon::end_data_table_row().'
                   5090:        '.&Apache::loncommon::start_data_table_row().'
1.492     albertel 5091: 	    <td> '.&mt('Options:').' </td>
1.187     albertel 5092:             <td>
1.492     albertel 5093: 	       <label><input type="checkbox" name="scantron_options_redo" value="redo_skipped"/> '.&mt('Do only previously skipped records').'</label> <br />
                   5094:                <label><input type="checkbox" name="scantron_options_ignore" value="ignore_corrections"/> '.&mt('Remove all existing corrections').'</label> <br />
                   5095:                <label><input type="checkbox" name="scantron_options_hidden" value="ignore_hidden"/> '.&mt('Skip hidden resources when grading').'</label>
1.187     albertel 5096: 	    </td>
1.489     albertel 5097:        '.&Apache::loncommon::end_data_table_row().'
                   5098:        '.&Apache::loncommon::start_data_table_row().'
1.174     albertel 5099:             <td colspan="2">
1.572     www      5100:               <input type="submit" value="'.&mt('Grading: Validate Bubblesheet Records').'" />
1.162     albertel 5101:             </td>
1.489     albertel 5102:        '.&Apache::loncommon::end_data_table_row().'
                   5103:     '.&Apache::loncommon::end_data_table().'
                   5104:     </form>
                   5105: ';
1.162     albertel 5106:    
                   5107:     $r->print($result);
                   5108: 
1.257     albertel 5109:     if (&Apache::lonnet::allowed('usc',$env{'request.role.domain'}) ||
                   5110:         &Apache::lonnet::allowed('usc',$env{'request.course.id'})) {
1.162     albertel 5111: 
1.422     foxr     5112: 	# Chunk of form to prompt for a scantron file upload.
                   5113: 
1.489     albertel 5114:         $r->print('
                   5115:     <br />
                   5116:     '.&Apache::loncommon::start_data_table('LC_scantron_action').'
                   5117:        '.&Apache::loncommon::start_data_table_header_row().'
                   5118:             <th>
1.572     www      5119:               &nbsp;'.&mt('Specify a bubblesheet data file to upload.').'
1.489     albertel 5120:             </th>
                   5121:        '.&Apache::loncommon::end_data_table_header_row().'
                   5122:        '.&Apache::loncommon::start_data_table_row().'
1.162     albertel 5123:             <td>
1.489     albertel 5124: ');
1.324     albertel 5125:     my $default_form_data=&defaultFormData(&get_symb($r,1));
1.257     albertel 5126:     my $cdom= $env{'course.'.$env{'request.course.id'}.'.domain'};
                   5127:     my $cnum= $env{'course.'.$env{'request.course.id'}.'.num'};
1.492     albertel 5128:     $r->print('
1.174     albertel 5129:               <script type="text/javascript" language="javascript">
                   5130:     function checkUpload(formname) {
                   5131: 	if (formname.upfile.value == "") {
1.492     albertel 5132: 	    alert("'.&mt('Please use the browse button to select a file from your local directory.').'");
1.174     albertel 5133: 	    return false;
                   5134: 	}
                   5135: 	formname.submit();
                   5136:     }
                   5137:               </script>
                   5138: 
1.492     albertel 5139:               <form enctype="multipart/form-data" action="/adm/grades" name="rules" method="post">
                   5140:                 '.$default_form_data.'
                   5141:                 <input name="courseid" type="hidden" value="'.$cnum.'" />
                   5142:                 <input name="domainid" type="hidden" value="'.$cdom.'" />
                   5143:                 <input name="command" value="scantronupload_save" type="hidden" />
                   5144:                 '.&mt('File to upload: [_1]','<input type="file" name="upfile" size="50" />').'
1.174     albertel 5145:                 <br />
1.572     www      5146:                 <input type="button" onClick="javascript:checkUpload(this.form);" value="'.&mt('Upload Bubblesheet Data').'" />
1.174     albertel 5147:               </form>
1.492     albertel 5148: ');
1.162     albertel 5149: 
1.489     albertel 5150:         $r->print('
1.162     albertel 5151:             </td>
1.489     albertel 5152:        '.&Apache::loncommon::end_data_table_row().'
                   5153:        '.&Apache::loncommon::end_data_table().'
                   5154: ');
1.162     albertel 5155:     }
1.422     foxr     5156: 
                   5157:     # Chunk of the form that prompts to view a scoring office file,
                   5158:     # corrected file, skipped records in a file.
                   5159: 
1.489     albertel 5160:     $r->print('
                   5161:    <br />
                   5162:    <form action="/adm/grades" name="scantron_download">
                   5163:      '.$default_form_data.'
                   5164:      <input type="hidden" name="command" value="scantron_download" />
                   5165:      '.&Apache::loncommon::start_data_table('LC_scantron_action').'
                   5166:        '.&Apache::loncommon::start_data_table_header_row().'
                   5167:               <th>
1.492     albertel 5168:                 &nbsp;'.&mt('Download a scoring office file').'
1.489     albertel 5169:               </th>
                   5170:        '.&Apache::loncommon::end_data_table_header_row().'
                   5171:        '.&Apache::loncommon::start_data_table_row().'
1.492     albertel 5172:               <td> '.&mt('Filename of scoring office file: [_1]',$file_selector).' 
1.489     albertel 5173:                 <br />
1.492     albertel 5174:                 <input type="submit" value="'.&mt('Download: Show List of Associated Files').'" />
1.489     albertel 5175:        '.&Apache::loncommon::end_data_table_row().'
                   5176:      '.&Apache::loncommon::end_data_table().'
                   5177:    </form>
                   5178:    <br />
                   5179: ');
1.162     albertel 5180: 
1.457     banghart 5181:     &Apache::lonpickcode::code_list($r,2);
1.523     raeburn  5182: 
1.528     raeburn  5183:     $r->print('<br /><form method="post" name="checkscantron">'.
1.523     raeburn  5184:              $default_form_data."\n".
                   5185:              &Apache::loncommon::start_data_table('LC_scantron_action')."\n".
                   5186:              &Apache::loncommon::start_data_table_header_row()."\n".
                   5187:              '<th colspan="2">
1.572     www      5188:               &nbsp;'.&mt('Review bubblesheet data and submissions for a previously graded folder/sequence')."\n".
1.523     raeburn  5189:              '</th>'."\n".
                   5190:               &Apache::loncommon::end_data_table_header_row()."\n".
                   5191:               &Apache::loncommon::start_data_table_row()."\n".
                   5192:               '<td> '.&mt('Graded folder/sequence:').' </td>'."\n".
                   5193:               '<td> '.$sequence_selector.' </td>'.
                   5194:               &Apache::loncommon::end_data_table_row()."\n".
                   5195:               &Apache::loncommon::start_data_table_row()."\n".
                   5196:               '<td> '.&mt('Filename of scoring office file:').' </td>'."\n".
                   5197:               '<td> '.$file_selector.' </td>'."\n".
                   5198:               &Apache::loncommon::end_data_table_row()."\n".
                   5199:               &Apache::loncommon::start_data_table_row()."\n".
                   5200:               '<td> '.&mt('Format of data file:').' </td>'."\n".
                   5201:               '<td> '.$format_selector.' </td>'."\n".
                   5202:               &Apache::loncommon::end_data_table_row()."\n".
                   5203:               &Apache::loncommon::start_data_table_row()."\n".
1.557     raeburn  5204:               '<td> '.&mt('Options').' </td>'."\n".
                   5205:               '<td> <label><input type="checkbox" name="scantron_options_hidden" value="ignore_hidden"/> '.&mt('Skip hidden resources').'</label></td>'.
                   5206:               &Apache::loncommon::end_data_table_row()."\n".
                   5207:               &Apache::loncommon::start_data_table_row()."\n".
1.523     raeburn  5208:               '<td colspan="2">'."\n".
                   5209:               '<input type="hidden" name="command" value="checksubmissions" />'."\n".
1.575     www      5210:               '<input type="submit" value="'.&mt('Review Bubblesheet Data and Submission Records').'" />'."\n".
1.523     raeburn  5211:               '</td>'."\n".
                   5212:               &Apache::loncommon::end_data_table_row()."\n".
                   5213:               &Apache::loncommon::end_data_table()."\n".
                   5214:               '</form><br />');
1.457     banghart 5215:     $r->print($grading_menu_button);
1.523     raeburn  5216:     return;
1.75      albertel 5217: }
                   5218: 
1.423     albertel 5219: =pod
                   5220: 
                   5221: =item get_scantron_config
                   5222: 
                   5223:    Parse and return the scantron configuration line selected as a
                   5224:    hash of configuration file fields.
                   5225: 
                   5226:  Arguments:
                   5227:     which - the name of the configuration to parse from the file.
                   5228: 
                   5229: 
                   5230:  Returns:
                   5231:             If the named configuration is not in the file, an empty
                   5232:             hash is returned.
                   5233:     a hash with the fields
                   5234:       name         - internal name for the this configuration setup
                   5235:       description  - text to display to operator that describes this config
                   5236:       CODElocation - if 0 or the string 'none'
                   5237:                           - no CODE exists for this config
                   5238:                      if -1 || the string 'letter'
                   5239:                           - a CODE exists for this config and is
                   5240:                             a string of letters
                   5241:                      Unsupported value (but planned for future support)
                   5242:                           if a positive integer
                   5243:                                - The CODE exists as the first n items from
                   5244:                                  the question section of the form
                   5245:                           if the string 'number'
                   5246:                                - The CODE exists for this config and is
                   5247:                                  a string of numbers
                   5248:       CODEstart   - (only matter if a CODE exists) column in the line where
                   5249:                      the CODE starts
                   5250:       CODElength  - length of the CODE
1.573     bisitz   5251:       IDstart     - column where the student/employee ID starts
1.556     weissno  5252:       IDlength    - length of the student/employee ID info
1.423     albertel 5253:       Qstart      - column where the information from the bubbled
                   5254:                     'questions' start
                   5255:       Qlength     - number of columns comprising a single bubble line from
                   5256:                     the sheet. (usually either 1 or 10)
1.424     albertel 5257:       Qon         - either a single character representing the character used
1.423     albertel 5258:                     to signal a bubble was chosen in the positional setup, or
                   5259:                     the string 'letter' if the letter of the chosen bubble is
                   5260:                     in the final, or 'number' if a number representing the
                   5261:                     chosen bubble is in the file (1->A 0->J)
1.424     albertel 5262:       Qoff        - the character used to represent that a bubble was
                   5263:                     left blank
1.423     albertel 5264:       PaperID     - if the scanning process generates a unique number for each
                   5265:                     sheet scanned the column that this ID number starts in
                   5266:       PaperIDlength - number of columns that comprise the unique ID number
                   5267:                       for the sheet of paper
1.424     albertel 5268:       FirstName   - column that the first name starts in
1.423     albertel 5269:       FirstNameLength - number of columns that the first name spans
                   5270:  
                   5271:       LastName    - column that the last name starts in
                   5272:       LastNameLength - number of columns that the last name spans
                   5273: 
                   5274: =cut
1.422     foxr     5275: 
1.82      albertel 5276: sub get_scantron_config {
                   5277:     my ($which) = @_;
1.518     raeburn  5278:     my @lines = &get_scantronformat_file();
1.82      albertel 5279:     my %config;
1.157     albertel 5280:     #FIXME probably should move to XML it has already gotten a bit much now
1.518     raeburn  5281:     foreach my $line (@lines) {
1.82      albertel 5282: 	my ($name,$descrip)=split(/:/,$line);
                   5283: 	if ($name ne $which ) { next; }
                   5284: 	chomp($line);
                   5285: 	my @config=split(/:/,$line);
                   5286: 	$config{'name'}=$config[0];
                   5287: 	$config{'description'}=$config[1];
                   5288: 	$config{'CODElocation'}=$config[2];
                   5289: 	$config{'CODEstart'}=$config[3];
                   5290: 	$config{'CODElength'}=$config[4];
                   5291: 	$config{'IDstart'}=$config[5];
                   5292: 	$config{'IDlength'}=$config[6];
                   5293: 	$config{'Qstart'}=$config[7];
1.497     foxr     5294:  	$config{'Qlength'}=$config[8];
1.82      albertel 5295: 	$config{'Qoff'}=$config[9];
                   5296: 	$config{'Qon'}=$config[10];
1.157     albertel 5297: 	$config{'PaperID'}=$config[11];
                   5298: 	$config{'PaperIDlength'}=$config[12];
                   5299: 	$config{'FirstName'}=$config[13];
                   5300: 	$config{'FirstNamelength'}=$config[14];
                   5301: 	$config{'LastName'}=$config[15];
                   5302: 	$config{'LastNamelength'}=$config[16];
1.82      albertel 5303: 	last;
                   5304:     }
                   5305:     return %config;
                   5306: }
                   5307: 
1.423     albertel 5308: =pod 
                   5309: 
                   5310: =item username_to_idmap
                   5311: 
1.556     weissno  5312:     creates a hash keyed by student/employee ID with values of the corresponding
1.423     albertel 5313:     student username:domain.
                   5314: 
                   5315:   Arguments:
                   5316: 
                   5317:     $classlist - reference to the class list hash. This is a hash
                   5318:                  keyed by student name:domain  whose elements are references
1.424     albertel 5319:                  to arrays containing various chunks of information
1.423     albertel 5320:                  about the student. (See loncoursedata for more info).
                   5321: 
                   5322:   Returns
                   5323:     %idmap - the constructed hash
                   5324: 
                   5325: =cut
                   5326: 
1.82      albertel 5327: sub username_to_idmap {
                   5328:     my ($classlist)= @_;
                   5329:     my %idmap;
                   5330:     foreach my $student (keys(%$classlist)) {
                   5331: 	$idmap{$classlist->{$student}->[&Apache::loncoursedata::CL_ID]}=
                   5332: 	    $student;
                   5333:     }
                   5334:     return %idmap;
                   5335: }
1.423     albertel 5336: 
                   5337: =pod
                   5338: 
1.424     albertel 5339: =item scantron_fixup_scanline
1.423     albertel 5340: 
                   5341:    Process a requested correction to a scanline.
                   5342: 
                   5343:   Arguments:
                   5344:     $scantron_config   - hash from &get_scantron_config()
                   5345:     $scan_data         - hash of correction information 
                   5346:                           (see &scantron_getfile())
                   5347:     $line              - existing scanline
                   5348:     $whichline         - line number of the passed in scanline
                   5349:     $field             - type of change to process 
                   5350:                          (either 
1.573     bisitz   5351:                           'ID'     -> correct the student/employee ID
1.423     albertel 5352:                           'CODE'   -> correct the CODE
                   5353:                           'answer' -> fixup the submitted answers)
                   5354:     
                   5355:    $args               - hash of additional info,
                   5356:                           - 'ID' 
                   5357:                                'newid' -> studentID to use in replacement
1.424     albertel 5358:                                           of existing one
1.423     albertel 5359:                           - 'CODE' 
                   5360:                                'CODE_ignore_dup' - set to true if duplicates
                   5361:                                                    should be ignored.
                   5362: 	                       'CODE' - is new code or 'use_unfound'
1.424     albertel 5363:                                         if the existing unfound code should
1.423     albertel 5364:                                         be used as is
                   5365:                           - 'answer'
                   5366:                                'response' - new answer or 'none' if blank
                   5367:                                'question' - the bubble line to change
1.503     raeburn  5368:                                'questionnum' - the question identifier,
                   5369:                                                may include subquestion. 
1.423     albertel 5370: 
                   5371:   Returns:
                   5372:     $line - the modified scanline
                   5373: 
                   5374:   Side effects: 
                   5375:     $scan_data - may be updated
                   5376: 
                   5377: =cut
                   5378: 
1.82      albertel 5379: 
1.157     albertel 5380: sub scantron_fixup_scanline {
                   5381:     my ($scantron_config,$scan_data,$line,$whichline,$field,$args)=@_;
                   5382:     if ($field eq 'ID') {
                   5383: 	if (length($args->{'newid'}) > $$scantron_config{'IDlength'}) {
1.186     albertel 5384: 	    return ($line,1,'New value too large');
1.157     albertel 5385: 	}
                   5386: 	if (length($args->{'newid'}) < $$scantron_config{'IDlength'}) {
                   5387: 	    $args->{'newid'}=sprintf('%-'.$$scantron_config{'IDlength'}.'s',
                   5388: 				     $args->{'newid'});
                   5389: 	}
                   5390: 	substr($line,$$scantron_config{'IDstart'}-1,
                   5391: 	       $$scantron_config{'IDlength'})=$args->{'newid'};
                   5392: 	if ($args->{'newid'}=~/^\s*$/) {
                   5393: 	    &scan_data($scan_data,"$whichline.user",
                   5394: 		       $args->{'username'}.':'.$args->{'domain'});
                   5395: 	}
1.186     albertel 5396:     } elsif ($field eq 'CODE') {
1.192     albertel 5397: 	if ($args->{'CODE_ignore_dup'}) {
                   5398: 	    &scan_data($scan_data,"$whichline.CODE_ignore_dup",'1');
                   5399: 	}
                   5400: 	&scan_data($scan_data,"$whichline.useCODE",'1');
                   5401: 	if ($args->{'CODE'} ne 'use_unfound') {
1.191     albertel 5402: 	    if (length($args->{'CODE'}) > $$scantron_config{'CODElength'}) {
                   5403: 		return ($line,1,'New CODE value too large');
                   5404: 	    }
                   5405: 	    if (length($args->{'CODE'}) < $$scantron_config{'CODElength'}) {
                   5406: 		$args->{'CODE'}=sprintf('%-'.$$scantron_config{'CODElength'}.'s',$args->{'CODE'});
                   5407: 	    }
                   5408: 	    substr($line,$$scantron_config{'CODEstart'}-1,
                   5409: 		   $$scantron_config{'CODElength'})=$args->{'CODE'};
1.186     albertel 5410: 	}
1.157     albertel 5411:     } elsif ($field eq 'answer') {
1.497     foxr     5412: 	my $length=$scantron_config->{'Qlength'};
1.157     albertel 5413: 	my $off=$scantron_config->{'Qoff'};
                   5414: 	my $on=$scantron_config->{'Qon'};
1.497     foxr     5415: 	my $answer=${off}x$length;
                   5416: 	if ($args->{'response'} eq 'none') {
                   5417: 	    &scan_data($scan_data,
1.503     raeburn  5418: 		       "$whichline.no_bubble.".$args->{'questionnum'},'1');
1.497     foxr     5419: 	} else {
                   5420: 	    if ($on eq 'letter') {
                   5421: 		my @alphabet=('A'..'Z');
                   5422: 		$answer=$alphabet[$args->{'response'}];
                   5423: 	    } elsif ($on eq 'number') {
                   5424: 		$answer=$args->{'response'}+1;
                   5425: 		if ($answer == 10) { $answer = '0'; }
1.274     albertel 5426: 	    } else {
1.497     foxr     5427: 		substr($answer,$args->{'response'},1)=$on;
1.274     albertel 5428: 	    }
1.497     foxr     5429: 	    &scan_data($scan_data,
1.503     raeburn  5430: 		       "$whichline.no_bubble.".$args->{'questionnum'},undef,'1');
1.157     albertel 5431: 	}
1.497     foxr     5432: 	my $where=$length*($args->{'question'}-1)+$scantron_config->{'Qstart'};
                   5433: 	substr($line,$where-1,$length)=$answer;
1.157     albertel 5434:     }
                   5435:     return $line;
                   5436: }
1.423     albertel 5437: 
                   5438: =pod
                   5439: 
                   5440: =item scan_data
                   5441: 
                   5442:     Edit or look up  an item in the scan_data hash.
                   5443: 
                   5444:   Arguments:
                   5445:     $scan_data  - The hash (see scantron_getfile)
                   5446:     $key        - shorthand of the key to edit (actual key is
1.424     albertel 5447:                   scantronfilename_key).
1.423     albertel 5448:     $data        - New value of the hash entry.
                   5449:     $delete      - If true, the entry is removed from the hash.
                   5450: 
                   5451:   Returns:
                   5452:     The new value of the hash table field (undefined if deleted).
                   5453: 
                   5454: =cut
                   5455: 
                   5456: 
1.157     albertel 5457: sub scan_data {
                   5458:     my ($scan_data,$key,$value,$delete)=@_;
1.257     albertel 5459:     my $filename=$env{'form.scantron_selectfile'};
1.157     albertel 5460:     if (defined($value)) {
                   5461: 	$scan_data->{$filename.'_'.$key} = $value;
                   5462:     }
                   5463:     if ($delete) { delete($scan_data->{$filename.'_'.$key}); }
                   5464:     return $scan_data->{$filename.'_'.$key};
                   5465: }
1.423     albertel 5466: 
1.495     albertel 5467: # ----- These first few routines are general use routines.----
                   5468: 
                   5469: # Return the number of occurences of a pattern in a string.
                   5470: 
                   5471: sub occurence_count {
                   5472:     my ($string, $pattern) = @_;
                   5473: 
                   5474:     my @matches = ($string =~ /$pattern/g);
                   5475: 
                   5476:     return scalar(@matches);
                   5477: }
                   5478: 
                   5479: 
                   5480: # Take a string known to have digits and convert all the
                   5481: # digits into letters in the range J,A..I.
                   5482: 
                   5483: sub digits_to_letters {
                   5484:     my ($input) = @_;
                   5485: 
                   5486:     my @alphabet = ('J', 'A'..'I');
                   5487: 
                   5488:     my @input    = split(//, $input);
                   5489:     my $output ='';
                   5490:     for (my $i = 0; $i < scalar(@input); $i++) {
                   5491: 	if ($input[$i] =~ /\d/) {
                   5492: 	    $output .= $alphabet[$input[$i]];
                   5493: 	} else {
                   5494: 	    $output .= $input[$i];
                   5495: 	}
                   5496:     }
                   5497:     return $output;
                   5498: }
                   5499: 
1.423     albertel 5500: =pod 
                   5501: 
                   5502: =item scantron_parse_scanline
                   5503: 
                   5504:   Decodes a scanline from the selected scantron file
                   5505: 
                   5506:  Arguments:
                   5507:     line             - The text of the scantron file line to process
                   5508:     whichline        - Line number
                   5509:     scantron_config  - Hash describing the format of the scantron lines.
                   5510:     scan_data        - Hash of extra information about the scanline
                   5511:                        (see scantron_getfile for more information)
                   5512:     just_header      - True if should not process question answers but only
                   5513:                        the stuff to the left of the answers.
                   5514:  Returns:
                   5515:    Hash containing the result of parsing the scanline
                   5516: 
                   5517:    Keys are all proceeded by the string 'scantron.'
                   5518: 
                   5519:        CODE    - the CODE in use for this scanline
                   5520:        useCODE - 1 if the CODE is invalid but it usage has been forced
                   5521:                  by the operator
                   5522:        CODE_ignore_dup - 1 if the CODE is a duplicated use when unique
                   5523:                             CODEs were selected, but the usage has been
                   5524:                             forced by the operator
1.556     weissno  5525:        ID  - student/employee ID
1.423     albertel 5526:        PaperID - if used, the ID number printed on the sheet when the 
                   5527:                  paper was scanned
                   5528:        FirstName - first name from the sheet
                   5529:        LastName  - last name from the sheet
                   5530: 
                   5531:      if just_header was not true these key may also exist
                   5532: 
1.447     foxr     5533:        missingerror - a list of bubble ranges that are considered to be answers
                   5534:                       to a single question that don't have any bubbles filled in.
                   5535:                       Of the form questionnumber:firstbubblenumber:count.
                   5536:        doubleerror  - a list of bubble ranges that are considered to be answers
                   5537:                       to a single question that have more than one bubble filled in.
                   5538:                       Of the form questionnumber::firstbubblenumber:count
                   5539:    
                   5540:                 In the above, count is the number of bubble responses in the
                   5541:                 input line needed to represent the possible answers to the question.
                   5542:                 e.g. a radioresponse with 15 choices in an answer sheet with 10 choices
                   5543:                 per line would have count = 2.
                   5544: 
1.423     albertel 5545:        maxquest     - the number of the last bubble line that was parsed
                   5546: 
                   5547:        (<number> starts at 1)
                   5548:        <number>.answer - zero or more letters representing the selected
                   5549:                          letters from the scanline for the bubble line 
                   5550:                          <number>.
                   5551:                          if blank there was either no bubble or there where
                   5552:                          multiple bubbles, (consult the keys missingerror and
                   5553:                          doubleerror if this is an error condition)
                   5554: 
                   5555: =cut
                   5556: 
1.82      albertel 5557: sub scantron_parse_scanline {
1.423     albertel 5558:     my ($line,$whichline,$scantron_config,$scan_data,$just_header)=@_;
1.470     foxr     5559: 
1.82      albertel 5560:     my %record;
1.550     raeburn  5561:     my $lastpos = $env{'form.scantron_maxbubble'}*$$scantron_config{'Qlength'};
                   5562:     my $questions=substr($line,$$scantron_config{'Qstart'}-1,$lastpos);  # Answers
1.422     foxr     5563:     my $data=substr($line,0,$$scantron_config{'Qstart'}-1);     # earlier stuff
1.278     albertel 5564:     if (!($$scantron_config{'CODElocation'} eq 0 ||
                   5565: 	  $$scantron_config{'CODElocation'} eq 'none')) {
                   5566: 	if ($$scantron_config{'CODElocation'} < 0 ||
                   5567: 	    $$scantron_config{'CODElocation'} eq 'letter' ||
                   5568: 	    $$scantron_config{'CODElocation'} eq 'number') {
1.191     albertel 5569: 	    $record{'scantron.CODE'}=substr($data,
                   5570: 					    $$scantron_config{'CODEstart'}-1,
1.83      albertel 5571: 					    $$scantron_config{'CODElength'});
1.191     albertel 5572: 	    if (&scan_data($scan_data,"$whichline.useCODE")) {
                   5573: 		$record{'scantron.useCODE'}=1;
                   5574: 	    }
1.192     albertel 5575: 	    if (&scan_data($scan_data,"$whichline.CODE_ignore_dup")) {
                   5576: 		$record{'scantron.CODE_ignore_dup'}=1;
                   5577: 	    }
1.82      albertel 5578: 	} else {
                   5579: 	    #FIXME interpret first N questions
                   5580: 	}
                   5581:     }
1.83      albertel 5582:     $record{'scantron.ID'}=substr($data,$$scantron_config{'IDstart'}-1,
                   5583: 				  $$scantron_config{'IDlength'});
1.157     albertel 5584:     $record{'scantron.PaperID'}=
                   5585: 	substr($data,$$scantron_config{'PaperID'}-1,
                   5586: 	       $$scantron_config{'PaperIDlength'});
                   5587:     $record{'scantron.FirstName'}=
                   5588: 	substr($data,$$scantron_config{'FirstName'}-1,
                   5589: 	       $$scantron_config{'FirstNamelength'});
                   5590:     $record{'scantron.LastName'}=
                   5591: 	substr($data,$$scantron_config{'LastName'}-1,
                   5592: 	       $$scantron_config{'LastNamelength'});
1.423     albertel 5593:     if ($just_header) { return \%record; }
1.194     albertel 5594: 
1.82      albertel 5595:     my @alphabet=('A'..'Z');
                   5596:     my $questnum=0;
1.447     foxr     5597:     my $ansnum  =1;		# Multiple 'answer lines'/question.
                   5598: 
1.470     foxr     5599:     chomp($questions);		# Get rid of any trailing \n.
                   5600:     $questions =~ s/\r$//;      # Get rid of trailing \r too (MAC or Win uploads).
                   5601:     while (length($questions)) {
1.447     foxr     5602: 	my $answers_needed = $bubble_lines_per_response{$questnum};
1.503     raeburn  5603:         my $answer_length  = ($$scantron_config{'Qlength'} * $answers_needed)
                   5604:                              || 1;
                   5605:         $questnum++;
                   5606:         my $quest_id = $questnum;
                   5607:         my $currentquest = substr($questions,0,$answer_length);
                   5608:         $questions       = substr($questions,$answer_length);
                   5609:         if (length($currentquest) < $answer_length) { next; }
                   5610: 
                   5611:         if ($subdivided_bubble_lines{$questnum-1} =~ /,/) {
                   5612:             my $subquestnum = 1;
                   5613:             my $subquestions = $currentquest;
                   5614:             my @subanswers_needed = 
                   5615:                 split(/,/,$subdivided_bubble_lines{$questnum-1});  
                   5616:             foreach my $subans (@subanswers_needed) {
                   5617:                 my $subans_length =
                   5618:                     ($$scantron_config{'Qlength'} * $subans)  || 1;
                   5619:                 my $currsubquest = substr($subquestions,0,$subans_length);
                   5620:                 $subquestions   = substr($subquestions,$subans_length);
                   5621:                 $quest_id = "$questnum.$subquestnum";
                   5622:                 if (($$scantron_config{'Qon'} eq 'letter') ||
                   5623:                     ($$scantron_config{'Qon'} eq 'number')) {
                   5624:                     $ansnum = &scantron_validator_lettnum($ansnum, 
                   5625:                         $questnum,$quest_id,$subans,$currsubquest,$whichline,
                   5626:                         \@alphabet,\%record,$scantron_config,$scan_data);
                   5627:                 } else {
                   5628:                     $ansnum = &scantron_validator_positional($ansnum,
                   5629:                         $questnum,$quest_id,$subans,$currsubquest,$whichline,                        \@alphabet,\%record,$scantron_config,$scan_data);
                   5630:                 }
                   5631:                 $subquestnum ++;
                   5632:             }
                   5633:         } else {
                   5634:             if (($$scantron_config{'Qon'} eq 'letter') ||
                   5635:                 ($$scantron_config{'Qon'} eq 'number')) {
                   5636:                 $ansnum = &scantron_validator_lettnum($ansnum,$questnum,
                   5637:                     $quest_id,$answers_needed,$currentquest,$whichline,
                   5638:                     \@alphabet,\%record,$scantron_config,$scan_data);
                   5639:             } else {
                   5640:                 $ansnum = &scantron_validator_positional($ansnum,$questnum,
                   5641:                     $quest_id,$answers_needed,$currentquest,$whichline,
                   5642:                     \@alphabet,\%record,$scantron_config,$scan_data);
                   5643:             }
                   5644:         }
                   5645:     }
                   5646:     $record{'scantron.maxquest'}=$questnum;
                   5647:     return \%record;
                   5648: }
1.447     foxr     5649: 
1.503     raeburn  5650: sub scantron_validator_lettnum {
                   5651:     my ($ansnum,$questnum,$quest_id,$answers_needed,$currquest,$whichline,
                   5652:         $alphabet,$record,$scantron_config,$scan_data) = @_;
                   5653: 
                   5654:     # Qon 'letter' implies for each slot in currquest we have:
                   5655:     #    ? or * for doubles, a letter in A-Z for a bubble, and
                   5656:     #    about anything else (esp. a value of Qoff) for missing
                   5657:     #    bubbles.
                   5658:     #
                   5659:     # Qon 'number' implies each slot gives a digit that indexes the
                   5660:     #    bubbles filled, or Qoff, or a non-number for unbubbled lines,
                   5661:     #    and * or ? for double bubbles on a single line.
                   5662:     #
1.447     foxr     5663: 
1.503     raeburn  5664:     my $matchon;
                   5665:     if ($$scantron_config{'Qon'} eq 'letter') {
                   5666:         $matchon = '[A-Z]';
                   5667:     } elsif ($$scantron_config{'Qon'} eq 'number') {
                   5668:         $matchon = '\d';
                   5669:     }
                   5670:     my $occurrences = 0;
                   5671:     if (($responsetype_per_response{$questnum-1} eq 'essayresponse') ||
                   5672:         ($responsetype_per_response{$questnum-1} eq 'formularesponse') ||
1.510     raeburn  5673:         ($responsetype_per_response{$questnum-1} eq 'stringresponse') ||
                   5674:         ($responsetype_per_response{$questnum-1} eq 'imageresponse') ||
                   5675:         ($responsetype_per_response{$questnum-1} eq 'reactionresponse') ||
                   5676:         ($responsetype_per_response{$questnum-1} eq 'organicresponse')) {
1.503     raeburn  5677:         my @singlelines = split('',$currquest);
                   5678:         foreach my $entry (@singlelines) {
                   5679:             $occurrences = &occurence_count($entry,$matchon);
                   5680:             if ($occurrences > 1) {
                   5681:                 last;
                   5682:             }
                   5683:         } 
                   5684:     } else {
                   5685:         $occurrences = &occurence_count($currquest,$matchon); 
                   5686:     }
                   5687:     if (($currquest =~ /\?/ || $currquest =~ /\*/) || ($occurrences > 1)) {
                   5688:         push(@{$record->{'scantron.doubleerror'}},$quest_id);
                   5689:         for (my $ans=0; $ans<$answers_needed; $ans++) {
                   5690:             my $bubble = substr($currquest,$ans,1);
                   5691:             if ($bubble =~ /$matchon/ ) {
                   5692:                 if ($$scantron_config{'Qon'} eq 'number') {
                   5693:                     if ($bubble == 0) {
                   5694:                         $bubble = 10; 
                   5695:                     }
                   5696:                     $record->{"scantron.$ansnum.answer"} = 
                   5697:                         $alphabet->[$bubble-1];
                   5698:                 } else {
                   5699:                     $record->{"scantron.$ansnum.answer"} = $bubble;
                   5700:                 }
                   5701:             } else {
                   5702:                 $record->{"scantron.$ansnum.answer"}='';
                   5703:             }
                   5704:             $ansnum++;
                   5705:         }
                   5706:     } elsif (!defined($currquest)
                   5707:             || (&occurence_count($currquest, $$scantron_config{'Qoff'}) == length($currquest))
                   5708:             || (&occurence_count($currquest,$matchon) == 0)) {
                   5709:         for (my $ans=0; $ans<$answers_needed; $ans++ ) {
                   5710:             $record->{"scantron.$ansnum.answer"}='';
                   5711:             $ansnum++;
                   5712:         }
                   5713:         if (!&scan_data($scan_data,"$whichline.no_bubble.$quest_id")) {
                   5714:             push(@{$record->{'scantron.missingerror'}},$quest_id);
                   5715:         }
                   5716:     } else {
                   5717:         if ($$scantron_config{'Qon'} eq 'number') {
                   5718:             $currquest = &digits_to_letters($currquest);            
                   5719:         }
                   5720:         for (my $ans=0; $ans<$answers_needed; $ans++) {
                   5721:             my $bubble = substr($currquest,$ans,1);
                   5722:             $record->{"scantron.$ansnum.answer"} = $bubble;
                   5723:             $ansnum++;
                   5724:         }
                   5725:     }
                   5726:     return $ansnum;
                   5727: }
1.447     foxr     5728: 
1.503     raeburn  5729: sub scantron_validator_positional {
                   5730:     my ($ansnum,$questnum,$quest_id,$answers_needed,$currquest,
                   5731:         $whichline,$alphabet,$record,$scantron_config,$scan_data) = @_;
1.447     foxr     5732: 
1.503     raeburn  5733:     # Otherwise there's a positional notation;
                   5734:     # each bubble line requires Qlength items, and there are filled in
                   5735:     # bubbles for each case where there 'Qon' characters.
                   5736:     #
1.447     foxr     5737: 
1.503     raeburn  5738:     my @array=split($$scantron_config{'Qon'},$currquest,-1);
1.447     foxr     5739: 
1.503     raeburn  5740:     # If the split only gives us one element.. the full length of the
                   5741:     # answer string, no bubbles are filled in:
1.447     foxr     5742: 
1.507     raeburn  5743:     if ($answers_needed eq '') {
                   5744:         return;
                   5745:     }
                   5746: 
1.503     raeburn  5747:     if (length($array[0]) eq $$scantron_config{'Qlength'}*$answers_needed) {
                   5748:         for (my $ans=0; $ans<$answers_needed; $ans++ ) {
                   5749:             $record->{"scantron.$ansnum.answer"}='';
                   5750:             $ansnum++;
                   5751:         }
                   5752:         if (!&scan_data($scan_data,"$whichline.no_bubble.$quest_id")) {
                   5753:             push(@{$record->{"scantron.missingerror"}},$quest_id);
                   5754:         }
                   5755:     } elsif (scalar(@array) == 2) {
                   5756:         my $location = length($array[0]);
                   5757:         my $line_num = int($location / $$scantron_config{'Qlength'});
                   5758:         my $bubble   = $alphabet->[$location % $$scantron_config{'Qlength'}];
                   5759:         for (my $ans=0; $ans<$answers_needed; $ans++) {
                   5760:             if ($ans eq $line_num) {
                   5761:                 $record->{"scantron.$ansnum.answer"} = $bubble;
                   5762:             } else {
                   5763:                 $record->{"scantron.$ansnum.answer"} = ' ';
                   5764:             }
                   5765:             $ansnum++;
                   5766:          }
                   5767:     } else {
                   5768:         #  If there's more than one instance of a bubble character
                   5769:         #  That's a double bubble; with positional notation we can
                   5770:         #  record all the bubbles filled in as well as the
                   5771:         #  fact this response consists of multiple bubbles.
                   5772:         #
                   5773:         if (($responsetype_per_response{$questnum-1} eq 'essayresponse') ||
                   5774:             ($responsetype_per_response{$questnum-1} eq 'formularesponse') ||
1.510     raeburn  5775:             ($responsetype_per_response{$questnum-1} eq 'stringresponse') ||
                   5776:             ($responsetype_per_response{$questnum-1} eq 'imageresponse') ||
                   5777:             ($responsetype_per_response{$questnum-1} eq 'reactionresponse') ||
                   5778:             ($responsetype_per_response{$questnum-1} eq 'organicresponse')) {
1.503     raeburn  5779:             my $doubleerror = 0;
                   5780:             while (($currquest >= $$scantron_config{'Qlength'}) && 
                   5781:                    (!$doubleerror)) {
                   5782:                my $currline = substr($currquest,0,$$scantron_config{'Qlength'});
                   5783:                $currquest = substr($currquest,$$scantron_config{'Qlength'});
                   5784:                my @currarray = split($$scantron_config{'Qon'},$currline,-1);
                   5785:                if (length(@currarray) > 2) {
                   5786:                    $doubleerror = 1;
                   5787:                } 
                   5788:             }
                   5789:             if ($doubleerror) {
                   5790:                 push(@{$record->{'scantron.doubleerror'}},$quest_id);
                   5791:             }
                   5792:         } else {
                   5793:             push(@{$record->{'scantron.doubleerror'}},$quest_id);
                   5794:         }
                   5795:         my $item = $ansnum;
                   5796:         for (my $ans=0; $ans<$answers_needed; $ans++) {
                   5797:             $record->{"scantron.$item.answer"} = '';
                   5798:             $item ++;
                   5799:         }
1.447     foxr     5800: 
1.503     raeburn  5801:         my @ans=@array;
                   5802:         my $i=0;
                   5803:         my $increment = 0;
                   5804:         while ($#ans) {
                   5805:             $i+=length($ans[0]) + $increment;
                   5806:             my $line   = int($i/$$scantron_config{'Qlength'} + $ansnum);
                   5807:             my $bubble = $i%$$scantron_config{'Qlength'};
                   5808:             $record->{"scantron.$line.answer"}.=$alphabet->[$bubble];
                   5809:             shift(@ans);
                   5810:             $increment = 1;
                   5811:         }
                   5812:         $ansnum += $answers_needed;
1.82      albertel 5813:     }
1.503     raeburn  5814:     return $ansnum;
1.82      albertel 5815: }
                   5816: 
1.423     albertel 5817: =pod
                   5818: 
                   5819: =item scantron_add_delay
                   5820: 
                   5821:    Adds an error message that occurred during the grading phase to a
                   5822:    queue of messages to be shown after grading pass is complete
                   5823: 
                   5824:  Arguments:
1.424     albertel 5825:    $delayqueue  - arrary ref of hash ref of error messages
1.423     albertel 5826:    $scanline    - the scanline that caused the error
                   5827:    $errormesage - the error message
                   5828:    $errorcode   - a numeric code for the error
                   5829: 
                   5830:  Side Effects:
1.424     albertel 5831:    updates the $delayqueue to have a new hash ref of the error
1.423     albertel 5832: 
                   5833: =cut
                   5834: 
1.82      albertel 5835: sub scantron_add_delay {
1.140     albertel 5836:     my ($delayqueue,$scanline,$errormessage,$errorcode)=@_;
                   5837:     push(@$delayqueue,
                   5838: 	 {'line' => $scanline, 'emsg' => $errormessage,
                   5839: 	  'ecode' => $errorcode }
                   5840: 	 );
1.82      albertel 5841: }
                   5842: 
1.423     albertel 5843: =pod
                   5844: 
                   5845: =item scantron_find_student
                   5846: 
1.424     albertel 5847:    Finds the username for the current scanline
                   5848: 
                   5849:   Arguments:
                   5850:    $scantron_record - hash result from scantron_parse_scanline
                   5851:    $scan_data       - hash of correction information 
                   5852:                       (see &scantron_getfile() form more information)
                   5853:    $idmap           - hash from &username_to_idmap()
                   5854:    $line            - number of current scanline
                   5855:  
                   5856:   Returns:
                   5857:    Either 'username:domain' or undef if unknown
                   5858: 
1.423     albertel 5859: =cut
                   5860: 
1.82      albertel 5861: sub scantron_find_student {
1.157     albertel 5862:     my ($scantron_record,$scan_data,$idmap,$line)=@_;
1.83      albertel 5863:     my $scanID=$$scantron_record{'scantron.ID'};
1.157     albertel 5864:     if ($scanID =~ /^\s*$/) {
                   5865:  	return &scan_data($scan_data,"$line.user");
                   5866:     }
1.83      albertel 5867:     foreach my $id (keys(%$idmap)) {
1.157     albertel 5868:  	if (lc($id) eq lc($scanID)) {
                   5869:  	    return $$idmap{$id};
                   5870:  	}
1.83      albertel 5871:     }
                   5872:     return undef;
                   5873: }
                   5874: 
1.423     albertel 5875: =pod
                   5876: 
                   5877: =item scantron_filter
                   5878: 
1.424     albertel 5879:    Filter sub for lonnavmaps, filters out hidden resources if ignore
                   5880:    hidden resources was selected
                   5881: 
1.423     albertel 5882: =cut
                   5883: 
1.83      albertel 5884: sub scantron_filter {
                   5885:     my ($curres)=@_;
1.331     albertel 5886: 
                   5887:     if (ref($curres) && $curres->is_problem()) {
                   5888: 	# if the user has asked to not have either hidden
                   5889: 	# or 'randomout' controlled resources to be graded
                   5890: 	# don't include them
                   5891: 	if ($env{'form.scantron_options_hidden'} eq 'ignore_hidden'
                   5892: 	    && $curres->randomout) {
                   5893: 	    return 0;
                   5894: 	}
1.83      albertel 5895: 	return 1;
                   5896:     }
                   5897:     return 0;
1.82      albertel 5898: }
                   5899: 
1.423     albertel 5900: =pod
                   5901: 
                   5902: =item scantron_process_corrections
                   5903: 
1.424     albertel 5904:    Gets correction information out of submitted form data and corrects
                   5905:    the scanline
                   5906: 
1.423     albertel 5907: =cut
                   5908: 
1.157     albertel 5909: sub scantron_process_corrections {
                   5910:     my ($r) = @_;
1.257     albertel 5911:     my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
1.157     albertel 5912:     my ($scanlines,$scan_data)=&scantron_getfile();
                   5913:     my $classlist=&Apache::loncoursedata::get_classlist();
1.257     albertel 5914:     my $which=$env{'form.scantron_line'};
1.200     albertel 5915:     my $line=&scantron_get_line($scanlines,$scan_data,$which);
1.157     albertel 5916:     my ($skip,$err,$errmsg);
1.257     albertel 5917:     if ($env{'form.scantron_skip_record'}) {
1.157     albertel 5918: 	$skip=1;
1.257     albertel 5919:     } elsif ($env{'form.scantron_corrections'} =~ /^(duplicate|incorrect)ID$/) {
                   5920: 	my $newstudent=$env{'form.scantron_username'}.':'.
                   5921: 	    $env{'form.scantron_domain'};
1.157     albertel 5922: 	my $newid=$classlist->{$newstudent}->[&Apache::loncoursedata::CL_ID];
                   5923: 	($line,$err,$errmsg)=
                   5924: 	    &scantron_fixup_scanline(\%scantron_config,$scan_data,$line,$which,
                   5925: 				     'ID',{'newid'=>$newid,
1.257     albertel 5926: 				    'username'=>$env{'form.scantron_username'},
                   5927: 				    'domain'=>$env{'form.scantron_domain'}});
                   5928:     } elsif ($env{'form.scantron_corrections'} =~ /^(duplicate|incorrect)CODE$/) {
                   5929: 	my $resolution=$env{'form.scantron_CODE_resolution'};
1.190     albertel 5930: 	my $newCODE;
1.192     albertel 5931: 	my %args;
1.190     albertel 5932: 	if      ($resolution eq 'use_unfound') {
1.191     albertel 5933: 	    $newCODE='use_unfound';
1.190     albertel 5934: 	} elsif ($resolution eq 'use_found') {
1.257     albertel 5935: 	    $newCODE=$env{'form.scantron_CODE_selectedvalue'};
1.190     albertel 5936: 	} elsif ($resolution eq 'use_typed') {
1.257     albertel 5937: 	    $newCODE=$env{'form.scantron_CODE_newvalue'};
1.194     albertel 5938: 	} elsif ($resolution =~ /^use_closest_(\d+)/) {
1.257     albertel 5939: 	    $newCODE=$env{"form.scantron_CODE_closest_$1"};
1.190     albertel 5940: 	}
1.257     albertel 5941: 	if ($env{'form.scantron_corrections'} eq 'duplicateCODE') {
1.192     albertel 5942: 	    $args{'CODE_ignore_dup'}=1;
                   5943: 	}
                   5944: 	$args{'CODE'}=$newCODE;
1.186     albertel 5945: 	($line,$err,$errmsg)=
                   5946: 	    &scantron_fixup_scanline(\%scantron_config,$scan_data,$line,$which,
1.192     albertel 5947: 				     'CODE',\%args);
1.257     albertel 5948:     } elsif ($env{'form.scantron_corrections'} =~ /^(missing|double)bubble$/) {
                   5949: 	foreach my $question (split(',',$env{'form.scantron_questions'})) {
1.157     albertel 5950: 	    ($line,$err,$errmsg)=
                   5951: 		&scantron_fixup_scanline(\%scantron_config,$scan_data,$line,
                   5952: 					 $which,'answer',
                   5953: 					 { 'question'=>$question,
1.503     raeburn  5954: 		      		   'response'=>$env{"form.scantron_correct_Q_$question"},
                   5955:                                    'questionnum'=>$env{"form.scantron_questionnum_Q_$question"}});
1.157     albertel 5956: 	    if ($err) { last; }
                   5957: 	}
                   5958:     }
                   5959:     if ($err) {
1.398     albertel 5960: 	$r->print("<span class=\"LC_warning\">Unable to accept last correction, an error occurred :$errmsg:</span>");
1.157     albertel 5961:     } else {
1.200     albertel 5962: 	&scantron_put_line($scanlines,$scan_data,$which,$line,$skip);
1.157     albertel 5963: 	&scantron_putfile($scanlines,$scan_data);
                   5964:     }
                   5965: }
                   5966: 
1.423     albertel 5967: =pod
                   5968: 
                   5969: =item reset_skipping_status
                   5970: 
1.424     albertel 5971:    Forgets the current set of remember skipped scanlines (and thus
                   5972:    reverts back to considering all lines in the
                   5973:    scantron_skipped_<filename> file)
                   5974: 
1.423     albertel 5975: =cut
                   5976: 
1.200     albertel 5977: sub reset_skipping_status {
                   5978:     my ($scanlines,$scan_data)=&scantron_getfile();
                   5979:     &scan_data($scan_data,'remember_skipping',undef,1);
                   5980:     &scantron_putfile(undef,$scan_data);
                   5981: }
                   5982: 
1.423     albertel 5983: =pod
                   5984: 
                   5985: =item start_skipping
                   5986: 
1.424     albertel 5987:    Marks a scanline to be skipped. 
                   5988: 
1.423     albertel 5989: =cut
                   5990: 
1.376     albertel 5991: sub start_skipping {
1.200     albertel 5992:     my ($scan_data,$i)=@_;
                   5993:     my %remembered=split(':',&scan_data($scan_data,'remember_skipping'));
1.376     albertel 5994:     if ($env{'form.scantron_options_redo'} =~ /^redo_/) {
                   5995: 	$remembered{$i}=2;
                   5996:     } else {
                   5997: 	$remembered{$i}=1;
                   5998:     }
1.200     albertel 5999:     &scan_data($scan_data,'remember_skipping',join(':',%remembered));
                   6000: }
                   6001: 
1.423     albertel 6002: =pod
                   6003: 
                   6004: =item should_be_skipped
                   6005: 
1.424     albertel 6006:    Checks whether a scanline should be skipped.
                   6007: 
1.423     albertel 6008: =cut
                   6009: 
1.200     albertel 6010: sub should_be_skipped {
1.376     albertel 6011:     my ($scanlines,$scan_data,$i)=@_;
1.257     albertel 6012:     if ($env{'form.scantron_options_redo'} !~ /^redo_/) {
1.200     albertel 6013: 	# not redoing old skips
1.376     albertel 6014: 	if ($scanlines->{'skipped'}[$i]) { return 1; }
1.200     albertel 6015: 	return 0;
                   6016:     }
                   6017:     my %remembered=split(':',&scan_data($scan_data,'remember_skipping'));
1.376     albertel 6018: 
                   6019:     if (exists($remembered{$i}) && $remembered{$i} != 2 ) {
                   6020: 	return 0;
                   6021:     }
1.200     albertel 6022:     return 1;
                   6023: }
                   6024: 
1.423     albertel 6025: =pod
                   6026: 
                   6027: =item remember_current_skipped
                   6028: 
1.424     albertel 6029:    Discovers what scanlines are in the scantron_skipped_<filename>
                   6030:    file and remembers them into scan_data for later use.
                   6031: 
1.423     albertel 6032: =cut
                   6033: 
1.200     albertel 6034: sub remember_current_skipped {
                   6035:     my ($scanlines,$scan_data)=&scantron_getfile();
                   6036:     my %to_remember;
                   6037:     for (my $i=0;$i<=$scanlines->{'count'};$i++) {
                   6038: 	if ($scanlines->{'skipped'}[$i]) {
                   6039: 	    $to_remember{$i}=1;
                   6040: 	}
                   6041:     }
1.376     albertel 6042: 
1.200     albertel 6043:     &scan_data($scan_data,'remember_skipping',join(':',%to_remember));
                   6044:     &scantron_putfile(undef,$scan_data);
                   6045: }
                   6046: 
1.423     albertel 6047: =pod
                   6048: 
                   6049: =item check_for_error
                   6050: 
1.424     albertel 6051:     Checks if there was an error when attempting to remove a specific
                   6052:     scantron_.. bubble sheet data file. Prints out an error if
                   6053:     something went wrong.
                   6054: 
1.423     albertel 6055: =cut
                   6056: 
1.200     albertel 6057: sub check_for_error {
                   6058:     my ($r,$result)=@_;
                   6059:     if ($result ne 'ok' && $result ne 'not_found' ) {
1.492     albertel 6060: 	$r->print(&mt("An error occurred ([_1]) when trying to remove the existing corrections.",$result));
1.200     albertel 6061:     }
                   6062: }
1.157     albertel 6063: 
1.423     albertel 6064: =pod
                   6065: 
                   6066: =item scantron_warning_screen
                   6067: 
1.424     albertel 6068:    Interstitial screen to make sure the operator has selected the
                   6069:    correct options before we start the validation phase.
                   6070: 
1.423     albertel 6071: =cut
                   6072: 
1.203     albertel 6073: sub scantron_warning_screen {
                   6074:     my ($button_text)=@_;
1.257     albertel 6075:     my $title=&Apache::lonnet::gettitle($env{'form.selectpage'});
1.284     albertel 6076:     my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
1.373     albertel 6077:     my $CODElist;
1.284     albertel 6078:     if ($scantron_config{'CODElocation'} &&
                   6079: 	$scantron_config{'CODEstart'} &&
                   6080: 	$scantron_config{'CODElength'}) {
                   6081: 	$CODElist=$env{'form.scantron_CODElist'};
1.398     albertel 6082: 	if ($env{'form.scantron_CODElist'} eq '') { $CODElist='<span class="LC_warning">None</span>'; }
1.284     albertel 6083: 	$CODElist=
1.492     albertel 6084: 	    '<tr><td><b>'.&mt('List of CODES to validate against:').'</b></td><td><tt>'.
1.373     albertel 6085: 	    $env{'form.scantron_CODElist'}.'</tt></td></tr>';
1.284     albertel 6086:     }
1.492     albertel 6087:     return ('
1.203     albertel 6088: <p>
1.492     albertel 6089: <span class="LC_warning">
                   6090: '.&mt('Please double check the information below before clicking on \'[_1]\'',&mt($button_text)).'</span>
1.203     albertel 6091: </p>
                   6092: <table>
1.492     albertel 6093: <tr><td><b>'.&mt('Sequence to be Graded:').'</b></td><td>'.$title.'</td></tr>
                   6094: <tr><td><b>'.&mt('Data File that will be used:').'</b></td><td><tt>'.$env{'form.scantron_selectfile'}.'</tt></td></tr>
                   6095: '.$CODElist.'
1.203     albertel 6096: </table>
                   6097: <br />
1.492     albertel 6098: <p> '.&mt('If this information is correct, please click on \'[_1]\'.',&mt($button_text)).'</p>
                   6099: <p> '.&mt('If something is incorrect, please click the \'Grading Menu\' button to start over.').'</p>
1.203     albertel 6100: 
                   6101: <br />
1.492     albertel 6102: ');
1.203     albertel 6103: }
                   6104: 
1.423     albertel 6105: =pod
                   6106: 
                   6107: =item scantron_do_warning
                   6108: 
1.424     albertel 6109:    Check if the operator has picked something for all required
                   6110:    fields. Error out if something is missing.
                   6111: 
1.423     albertel 6112: =cut
                   6113: 
1.203     albertel 6114: sub scantron_do_warning {
                   6115:     my ($r)=@_;
1.324     albertel 6116:     my ($symb)=&get_symb($r);
1.203     albertel 6117:     if (!$symb) {return '';}
1.324     albertel 6118:     my $default_form_data=&defaultFormData($symb);
1.203     albertel 6119:     $r->print(&scantron_form_start().$default_form_data);
1.257     albertel 6120:     if ( $env{'form.selectpage'} eq '' ||
                   6121: 	 $env{'form.scantron_selectfile'} eq '' ||
                   6122: 	 $env{'form.scantron_format'} eq '' ) {
1.492     albertel 6123: 	$r->print("<p>".&mt('You have forgetten to specify some information. Please go Back and try again.')."</p>");
1.257     albertel 6124: 	if ( $env{'form.selectpage'} eq '') {
1.492     albertel 6125: 	    $r->print('<p><span class="LC_error">'.&mt('You have not selected a Sequence to grade').'</span></p>');
1.237     albertel 6126: 	} 
1.257     albertel 6127: 	if ( $env{'form.scantron_selectfile'} eq '') {
1.492     albertel 6128: 	    $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 6129: 	} 
1.257     albertel 6130: 	if ( $env{'form.scantron_format'} eq '') {
1.492     albertel 6131: 	    $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 6132: 	} 
                   6133:     } else {
1.265     www      6134: 	my $warning=&scantron_warning_screen('Grading: Validate Records');
1.492     albertel 6135: 	$r->print('
                   6136: '.$warning.'
                   6137: <input type="submit" name="submit" value="'.&mt('Grading: Validate Records').'" />
1.203     albertel 6138: <input type="hidden" name="command" value="scantron_validate" />
1.492     albertel 6139: ');
1.237     albertel 6140:     }
1.352     albertel 6141:     $r->print("</form><br />".&show_grading_menu_form($symb));
1.203     albertel 6142:     return '';
                   6143: }
                   6144: 
1.423     albertel 6145: =pod
                   6146: 
                   6147: =item scantron_form_start
                   6148: 
1.424     albertel 6149:     html hidden input for remembering all selected grading options
                   6150: 
1.423     albertel 6151: =cut
                   6152: 
1.203     albertel 6153: sub scantron_form_start {
                   6154:     my ($max_bubble)=@_;
                   6155:     my $result= <<SCANTRONFORM;
                   6156: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="scantronupload">
1.257     albertel 6157:   <input type="hidden" name="selectpage" value="$env{'form.selectpage'}" />
                   6158:   <input type="hidden" name="scantron_format" value="$env{'form.scantron_format'}" />
                   6159:   <input type="hidden" name="scantron_selectfile" value="$env{'form.scantron_selectfile'}" />
1.218     albertel 6160:   <input type="hidden" name="scantron_maxbubble" value="$max_bubble" />
1.257     albertel 6161:   <input type="hidden" name="scantron_CODElist" value="$env{'form.scantron_CODElist'}" />
                   6162:   <input type="hidden" name="scantron_CODEunique" value="$env{'form.scantron_CODEunique'}" />
                   6163:   <input type="hidden" name="scantron_options_redo" value="$env{'form.scantron_options_redo'}" />
                   6164:   <input type="hidden" name="scantron_options_ignore" value="$env{'form.scantron_options_ignore'}" />
1.331     albertel 6165:   <input type="hidden" name="scantron_options_hidden" value="$env{'form.scantron_options_hidden'}" />
1.203     albertel 6166: SCANTRONFORM
1.447     foxr     6167: 
                   6168:   my $line = 0;
                   6169:     while (defined($env{"form.scantron.bubblelines.$line"})) {
                   6170:        my $chunk =
                   6171: 	   '<input type="hidden" name="scantron.bubblelines.'.$line.'" value="'.$env{"form.scantron.bubblelines.$line"}.'" />'."\n";
1.448     foxr     6172:        $chunk .=
                   6173: 	   '<input type="hidden" name="scantron.first_bubble_line.'.$line.'" value="'.$env{"form.scantron.first_bubble_line.$line"}.'" />'."\n";
1.503     raeburn  6174:        $chunk .= 
                   6175:            '<input type="hidden" name="scantron.sub_bubblelines.'.$line.'" value="'.$env{"form.scantron.sub_bubblelines.$line"}.'" />'."\n";
1.504     raeburn  6176:        $chunk .=
                   6177:            '<input type="hidden" name="scantron.responsetype.'.$line.'" value="'.$env{"form.scantron.responsetype.$line"}.'" />'."\n";
1.447     foxr     6178:        $result .= $chunk;
                   6179:        $line++;
                   6180:    }
1.203     albertel 6181:     return $result;
                   6182: }
                   6183: 
1.423     albertel 6184: =pod
                   6185: 
                   6186: =item scantron_validate_file
                   6187: 
1.424     albertel 6188:     Dispatch routine for doing validation of a bubble sheet data file.
                   6189: 
                   6190:     Also processes any necessary information resets that need to
                   6191:     occur before validation begins (ignore previous corrections,
                   6192:     restarting the skipped records processing)
                   6193: 
1.423     albertel 6194: =cut
                   6195: 
1.157     albertel 6196: sub scantron_validate_file {
                   6197:     my ($r) = @_;
1.324     albertel 6198:     my ($symb)=&get_symb($r);
1.157     albertel 6199:     if (!$symb) {return '';}
1.324     albertel 6200:     my $default_form_data=&defaultFormData($symb);
1.200     albertel 6201:     
                   6202:     # do the detection of only doing skipped records first befroe we delete
1.424     albertel 6203:     # them when doing the corrections reset
1.257     albertel 6204:     if ($env{'form.scantron_options_redo'} ne 'redo_skipped_ready') {
1.200     albertel 6205: 	&reset_skipping_status();
                   6206:     }
1.257     albertel 6207:     if ($env{'form.scantron_options_redo'} eq 'redo_skipped') {
1.200     albertel 6208: 	&remember_current_skipped();
1.257     albertel 6209: 	$env{'form.scantron_options_redo'}='redo_skipped_ready';
1.200     albertel 6210:     }
                   6211: 
1.257     albertel 6212:     if ($env{'form.scantron_options_ignore'} eq 'ignore_corrections') {
1.200     albertel 6213: 	&check_for_error($r,&scantron_remove_file('corrected'));
                   6214: 	&check_for_error($r,&scantron_remove_file('skipped'));
                   6215: 	&check_for_error($r,&scantron_remove_scan_data());
1.257     albertel 6216: 	$env{'form.scantron_options_ignore'}='done';
1.192     albertel 6217:     }
1.200     albertel 6218: 
1.257     albertel 6219:     if ($env{'form.scantron_corrections'}) {
1.157     albertel 6220: 	&scantron_process_corrections($r);
                   6221:     }
1.503     raeburn  6222:     $r->print('<p>'.&mt('Gathering necessary information.').'</p>');$r->rflush();
1.157     albertel 6223:     #get the student pick code ready
                   6224:     $r->print(&Apache::loncommon::studentbrowser_javascript());
1.330     albertel 6225:     my $max_bubble=&scantron_get_maxbubble();
1.203     albertel 6226:     my $result=&scantron_form_start($max_bubble).$default_form_data;
1.157     albertel 6227:     $r->print($result);
                   6228:     
1.334     albertel 6229:     my @validate_phases=( 'sequence',
                   6230: 			  'ID',
1.157     albertel 6231: 			  'CODE',
                   6232: 			  'doublebubble',
                   6233: 			  'missingbubbles');
1.257     albertel 6234:     if (!$env{'form.validatepass'}) {
                   6235: 	$env{'form.validatepass'} = 0;
1.157     albertel 6236:     }
1.257     albertel 6237:     my $currentphase=$env{'form.validatepass'};
1.157     albertel 6238: 
1.448     foxr     6239: 
1.157     albertel 6240:     my $stop=0;
                   6241:     while (!$stop && $currentphase < scalar(@validate_phases)) {
1.503     raeburn  6242: 	$r->print(&mt('Validating '.$validate_phases[$currentphase]).'<br />');
1.157     albertel 6243: 	$r->rflush();
                   6244: 	my $which="scantron_validate_".$validate_phases[$currentphase];
                   6245: 	{
                   6246: 	    no strict 'refs';
                   6247: 	    ($stop,$currentphase)=&$which($r,$currentphase);
                   6248: 	}
                   6249:     }
                   6250:     if (!$stop) {
1.203     albertel 6251: 	my $warning=&scantron_warning_screen('Start Grading');
1.542     raeburn  6252: 	$r->print(&mt('Validation process complete.').'<br />'.
                   6253:                   $warning.
                   6254:                   &mt('Perform verification for each student after storage of submissions?').
                   6255:                   '&nbsp;<span class="LC_nobreak"><label>'.
                   6256:                   '<input type="radio" name="verifyrecord" value="1" />'.&mt('Yes').'</label>'.
                   6257:                   ('&nbsp;'x3).'<label>'.
                   6258:                   '<input type="radio" name="verifyrecord" value="0" checked="checked" />'.&mt('No').
                   6259:                   '</label></span><br />'.
                   6260:                   &mt('Grading will take longer if you use verification.').'<br />'.
1.572     www      6261:                   &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  6262:                   '<input type="submit" name="submit" value="'.&mt('Start Grading').'" />'.
                   6263:                   '<input type="hidden" name="command" value="scantron_process" />'."\n");
1.157     albertel 6264:     } else {
                   6265: 	$r->print('<input type="hidden" name="command" value="scantron_validate" />');
                   6266: 	$r->print("<input type='hidden' name='validatepass' value='".$currentphase."' />");
                   6267:     }
                   6268:     if ($stop) {
1.334     albertel 6269: 	if ($validate_phases[$currentphase] eq 'sequence') {
1.539     riegler  6270: 	    $r->print('<input type="submit" name="submit" value="'.&mt('Ignore').' &rarr; " />');
1.492     albertel 6271: 	    $r->print(' '.&mt('this error').' <br />');
1.334     albertel 6272: 
1.492     albertel 6273: 	    $r->print(" <p>".&mt("Or click the 'Grading Menu' button to start over.")."</p>");
1.334     albertel 6274: 	} else {
1.503     raeburn  6275:             if ($validate_phases[$currentphase] eq 'doublebubble' || $validate_phases[$currentphase] eq 'missingbubbles') {
1.539     riegler  6276: 	        $r->print('<input type="button" name="submitbutton" value="'.&mt('Continue').' &rarr;" onclick="javascript:verify_bubble_radio(this.form)" />');
1.503     raeburn  6277:             } else {
1.539     riegler  6278:                 $r->print('<input type="submit" name="submit" value="'.&mt('Continue').' &rarr;" />');
1.503     raeburn  6279:             }
1.492     albertel 6280: 	    $r->print(' '.&mt('using corrected info').' <br />');
                   6281: 	    $r->print("<input type='submit' value='".&mt("Skip")."' name='scantron_skip_record' />");
                   6282: 	    $r->print(" ".&mt("this scanline saving it for later."));
1.334     albertel 6283: 	}
1.157     albertel 6284:     }
1.352     albertel 6285:     $r->print(" </form><br />".&show_grading_menu_form($symb));
1.157     albertel 6286:     return '';
                   6287: }
                   6288: 
1.423     albertel 6289: 
                   6290: =pod
                   6291: 
                   6292: =item scantron_remove_file
                   6293: 
1.424     albertel 6294:    Removes the requested bubble sheet data file, makes sure that
                   6295:    scantron_original_<filename> is never removed
                   6296: 
                   6297: 
1.423     albertel 6298: =cut
                   6299: 
1.200     albertel 6300: sub scantron_remove_file {
1.192     albertel 6301:     my ($which)=@_;
1.257     albertel 6302:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   6303:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1.192     albertel 6304:     my $file='scantron_';
1.200     albertel 6305:     if ($which eq 'corrected' || $which eq 'skipped') {
                   6306: 	$file.=$which.'_';
1.192     albertel 6307:     } else {
                   6308: 	return 'refused';
                   6309:     }
1.257     albertel 6310:     $file.=$env{'form.scantron_selectfile'};
1.200     albertel 6311:     return &Apache::lonnet::removeuserfile($cname,$cdom,$file);
                   6312: }
                   6313: 
1.423     albertel 6314: 
                   6315: =pod
                   6316: 
                   6317: =item scantron_remove_scan_data
                   6318: 
1.424     albertel 6319:    Removes all scan_data correction for the requested bubble sheet
                   6320:    data file.  (In the case that both the are doing skipped records we need
                   6321:    to remember the old skipped lines for the time being so that element
                   6322:    persists for a while.)
                   6323: 
1.423     albertel 6324: =cut
                   6325: 
1.200     albertel 6326: sub scantron_remove_scan_data {
1.257     albertel 6327:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   6328:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1.192     albertel 6329:     my @keys=&Apache::lonnet::getkeys('nohist_scantrondata',$cdom,$cname);
                   6330:     my @todelete;
1.257     albertel 6331:     my $filename=$env{'form.scantron_selectfile'};
1.192     albertel 6332:     foreach my $key (@keys) {
                   6333: 	if ($key=~/^\Q$filename\E_/) {
1.257     albertel 6334: 	    if ($env{'form.scantron_options_redo'} eq 'redo_skipped_ready' &&
1.200     albertel 6335: 		$key=~/remember_skipping/) {
                   6336: 		next;
                   6337: 	    }
1.192     albertel 6338: 	    push(@todelete,$key);
                   6339: 	}
                   6340:     }
1.200     albertel 6341:     my $result;
1.192     albertel 6342:     if (@todelete) {
1.491     albertel 6343: 	$result = &Apache::lonnet::del('nohist_scantrondata',
                   6344: 				       \@todelete,$cdom,$cname);
                   6345:     } else {
                   6346: 	$result = 'ok';
1.192     albertel 6347:     }
                   6348:     return $result;
                   6349: }
                   6350: 
1.423     albertel 6351: 
                   6352: =pod
                   6353: 
                   6354: =item scantron_getfile
                   6355: 
1.424     albertel 6356:     Fetches the requested bubble sheet data file (all 3 versions), and
                   6357:     the scan_data hash
                   6358:   
                   6359:   Arguments:
                   6360:     None
                   6361: 
                   6362:   Returns:
                   6363:     2 hash references
                   6364: 
                   6365:      - first one has 
                   6366:          orig      -
                   6367:          corrected -
                   6368:          skipped   -  each of which points to an array ref of the specified
                   6369:                       file broken up into individual lines
                   6370:          count     - number of scanlines
                   6371:  
                   6372:      - second is the scan_data hash possible keys are
1.425     albertel 6373:        ($number refers to scanline numbered $number and thus the key affects
                   6374:         only that scanline
                   6375:         $bubline refers to the specific bubble line element and the aspects
                   6376:         refers to that specific bubble line element)
                   6377: 
                   6378:        $number.user - username:domain to use
                   6379:        $number.CODE_ignore_dup 
                   6380:                     - ignore the duplicate CODE error 
                   6381:        $number.useCODE
                   6382:                     - use the CODE in the scanline as is
                   6383:        $number.no_bubble.$bubline
                   6384:                     - it is valid that there is no bubbled in bubble
                   6385:                       at $number $bubline
                   6386:        remember_skipping
                   6387:                     - a frozen hash containing keys of $number and values
                   6388:                       of either 
                   6389:                         1 - we are on a 'do skipped records pass' and plan
                   6390:                             on processing this line
                   6391:                         2 - we are on a 'do skipped records pass' and this
                   6392:                             scanline has been marked to skip yet again
1.424     albertel 6393: 
1.423     albertel 6394: =cut
                   6395: 
1.157     albertel 6396: sub scantron_getfile {
1.200     albertel 6397:     #FIXME really would prefer a scantron directory
1.257     albertel 6398:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   6399:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1.157     albertel 6400:     my $lines;
                   6401:     $lines=&Apache::lonnet::getfile('/uploaded/'.$cdom.'/'.$cname.'/'.
1.257     albertel 6402: 		       'scantron_orig_'.$env{'form.scantron_selectfile'});
1.157     albertel 6403:     my %scanlines;
                   6404:     $scanlines{'orig'}=[(split("\n",$lines,-1))];
                   6405:     my $temp=$scanlines{'orig'};
                   6406:     $scanlines{'count'}=$#$temp;
                   6407: 
                   6408:     $lines=&Apache::lonnet::getfile('/uploaded/'.$cdom.'/'.$cname.'/'.
1.257     albertel 6409: 		       'scantron_corrected_'.$env{'form.scantron_selectfile'});
1.157     albertel 6410:     if ($lines eq '-1') {
                   6411: 	$scanlines{'corrected'}=[];
                   6412:     } else {
                   6413: 	$scanlines{'corrected'}=[(split("\n",$lines,-1))];
                   6414:     }
                   6415:     $lines=&Apache::lonnet::getfile('/uploaded/'.$cdom.'/'.$cname.'/'.
1.257     albertel 6416: 		       'scantron_skipped_'.$env{'form.scantron_selectfile'});
1.157     albertel 6417:     if ($lines eq '-1') {
                   6418: 	$scanlines{'skipped'}=[];
                   6419:     } else {
                   6420: 	$scanlines{'skipped'}=[(split("\n",$lines,-1))];
                   6421:     }
1.175     albertel 6422:     my @tmp=&Apache::lonnet::dump('nohist_scantrondata',$cdom,$cname);
1.157     albertel 6423:     if ($tmp[0] =~ /^(error:|no_such_host)/) { @tmp=(); }
                   6424:     my %scan_data = @tmp;
                   6425:     return (\%scanlines,\%scan_data);
                   6426: }
                   6427: 
1.423     albertel 6428: =pod
                   6429: 
                   6430: =item lonnet_putfile
                   6431: 
1.424     albertel 6432:    Wrapper routine to call &Apache::lonnet::finishuserfileupload
                   6433: 
                   6434:  Arguments:
                   6435:    $contents - data to store
                   6436:    $filename - filename to store $contents into
                   6437: 
                   6438:  Returns:
                   6439:    result value from &Apache::lonnet::finishuserfileupload
                   6440: 
1.423     albertel 6441: =cut
                   6442: 
1.157     albertel 6443: sub lonnet_putfile {
                   6444:     my ($contents,$filename)=@_;
1.257     albertel 6445:     my $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   6446:     my $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
                   6447:     $env{'form.sillywaytopassafilearound'}=$contents;
1.275     albertel 6448:     &Apache::lonnet::finishuserfileupload($docuname,$docudom,'sillywaytopassafilearound',$filename);
1.157     albertel 6449: 
                   6450: }
                   6451: 
1.423     albertel 6452: =pod
                   6453: 
                   6454: =item scantron_putfile
                   6455: 
1.424     albertel 6456:     Stores the current version of the bubble sheet data files, and the
                   6457:     scan_data hash. (Does not modify the original version only the
                   6458:     corrected and skipped versions.
                   6459: 
                   6460:  Arguments:
                   6461:     $scanlines - hash ref that looks like the first return value from
                   6462:                  &scantron_getfile()
                   6463:     $scan_data - hash ref that looks like the second return value from
                   6464:                  &scantron_getfile()
                   6465: 
1.423     albertel 6466: =cut
                   6467: 
1.157     albertel 6468: sub scantron_putfile {
                   6469:     my ($scanlines,$scan_data) = @_;
1.200     albertel 6470:     #FIXME really would prefer a scantron directory
1.257     albertel 6471:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   6472:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1.200     albertel 6473:     if ($scanlines) {
                   6474: 	my $prefix='scantron_';
1.157     albertel 6475: # no need to update orig, shouldn't change
                   6476: #   &lonnet_putfile(join("\n",@{$scanlines->{'orig'}}),$prefix.'orig_'.
1.257     albertel 6477: #		    $env{'form.scantron_selectfile'});
1.200     albertel 6478: 	&lonnet_putfile(join("\n",@{$scanlines->{'corrected'}}),
                   6479: 			$prefix.'corrected_'.
1.257     albertel 6480: 			$env{'form.scantron_selectfile'});
1.200     albertel 6481: 	&lonnet_putfile(join("\n",@{$scanlines->{'skipped'}}),
                   6482: 			$prefix.'skipped_'.
1.257     albertel 6483: 			$env{'form.scantron_selectfile'});
1.200     albertel 6484:     }
1.175     albertel 6485:     &Apache::lonnet::put('nohist_scantrondata',$scan_data,$cdom,$cname);
1.157     albertel 6486: }
                   6487: 
1.423     albertel 6488: =pod
                   6489: 
                   6490: =item scantron_get_line
                   6491: 
1.424     albertel 6492:    Returns the correct version of the scanline
                   6493: 
                   6494:  Arguments:
                   6495:     $scanlines - hash ref that looks like the first return value from
                   6496:                  &scantron_getfile()
                   6497:     $scan_data - hash ref that looks like the second return value from
                   6498:                  &scantron_getfile()
                   6499:     $i         - number of the requested line (starts at 0)
                   6500: 
                   6501:  Returns:
                   6502:    A scanline, (either the original or the corrected one if it
                   6503:    exists), or undef if the requested scanline should be
                   6504:    skipped. (Either because it's an skipped scanline, or it's an
                   6505:    unskipped scanline and we are not doing a 'do skipped scanlines'
                   6506:    pass.
                   6507: 
1.423     albertel 6508: =cut
                   6509: 
1.157     albertel 6510: sub scantron_get_line {
1.200     albertel 6511:     my ($scanlines,$scan_data,$i)=@_;
1.376     albertel 6512:     if (&should_be_skipped($scanlines,$scan_data,$i)) { return undef; }
                   6513:     #if ($scanlines->{'skipped'}[$i]) { return undef; }
1.157     albertel 6514:     if ($scanlines->{'corrected'}[$i]) {return $scanlines->{'corrected'}[$i];}
                   6515:     return $scanlines->{'orig'}[$i]; 
                   6516: }
                   6517: 
1.423     albertel 6518: =pod
                   6519: 
                   6520: =item scantron_todo_count
                   6521: 
1.424     albertel 6522:     Counts the number of scanlines that need processing.
                   6523: 
                   6524:  Arguments:
                   6525:     $scanlines - hash ref that looks like the first return value from
                   6526:                  &scantron_getfile()
                   6527:     $scan_data - hash ref that looks like the second return value from
                   6528:                  &scantron_getfile()
                   6529: 
                   6530:  Returns:
                   6531:     $count - number of scanlines to process
                   6532: 
1.423     albertel 6533: =cut
                   6534: 
1.200     albertel 6535: sub get_todo_count {
                   6536:     my ($scanlines,$scan_data)=@_;
                   6537:     my $count=0;
                   6538:     for (my $i=0;$i<=$scanlines->{'count'};$i++) {
                   6539: 	my $line=&scantron_get_line($scanlines,$scan_data,$i);
                   6540: 	if ($line=~/^[\s\cz]*$/) { next; }
                   6541: 	$count++;
                   6542:     }
                   6543:     return $count;
                   6544: }
                   6545: 
1.423     albertel 6546: =pod
                   6547: 
                   6548: =item scantron_put_line
                   6549: 
1.424     albertel 6550:     Updates the 'corrected' or 'skipped' versions of the bubble sheet
                   6551:     data file.
                   6552: 
                   6553:  Arguments:
                   6554:     $scanlines - hash ref that looks like the first return value from
                   6555:                  &scantron_getfile()
                   6556:     $scan_data - hash ref that looks like the second return value from
                   6557:                  &scantron_getfile()
                   6558:     $i         - line number to update
                   6559:     $newline   - contents of the updated scanline
                   6560:     $skip      - if true make the line for skipping and update the
                   6561:                  'skipped' file
                   6562: 
1.423     albertel 6563: =cut
                   6564: 
1.157     albertel 6565: sub scantron_put_line {
1.200     albertel 6566:     my ($scanlines,$scan_data,$i,$newline,$skip)=@_;
1.157     albertel 6567:     if ($skip) {
                   6568: 	$scanlines->{'skipped'}[$i]=$newline;
1.376     albertel 6569: 	&start_skipping($scan_data,$i);
1.157     albertel 6570: 	return;
                   6571:     }
                   6572:     $scanlines->{'corrected'}[$i]=$newline;
                   6573: }
                   6574: 
1.423     albertel 6575: =pod
                   6576: 
                   6577: =item scantron_clear_skip
                   6578: 
1.424     albertel 6579:    Remove a line from the 'skipped' file
                   6580: 
                   6581:  Arguments:
                   6582:     $scanlines - hash ref that looks like the first return value from
                   6583:                  &scantron_getfile()
                   6584:     $scan_data - hash ref that looks like the second return value from
                   6585:                  &scantron_getfile()
                   6586:     $i         - line number to update
                   6587: 
1.423     albertel 6588: =cut
                   6589: 
1.376     albertel 6590: sub scantron_clear_skip {
                   6591:     my ($scanlines,$scan_data,$i)=@_;
                   6592:     if (exists($scanlines->{'skipped'}[$i])) {
                   6593: 	undef($scanlines->{'skipped'}[$i]);
                   6594: 	return 1;
                   6595:     }
                   6596:     return 0;
                   6597: }
                   6598: 
1.423     albertel 6599: =pod
                   6600: 
                   6601: =item scantron_filter_not_exam
                   6602: 
1.424     albertel 6603:    Filter routine used by &Apache::lonnavmaps::retrieveResources(), to
                   6604:    filter out resources that are not marked as 'exam' mode
                   6605: 
1.423     albertel 6606: =cut
                   6607: 
1.334     albertel 6608: sub scantron_filter_not_exam {
                   6609:     my ($curres)=@_;
                   6610:     
                   6611:     if (ref($curres) && $curres->is_problem() && !$curres->is_exam()) {
                   6612: 	# if the user has asked to not have either hidden
                   6613: 	# or 'randomout' controlled resources to be graded
                   6614: 	# don't include them
                   6615: 	if ($env{'form.scantron_options_hidden'} eq 'ignore_hidden'
                   6616: 	    && $curres->randomout) {
                   6617: 	    return 0;
                   6618: 	}
                   6619: 	return 1;
                   6620:     }
                   6621:     return 0;
                   6622: }
                   6623: 
1.423     albertel 6624: =pod
                   6625: 
                   6626: =item scantron_validate_sequence
                   6627: 
1.424     albertel 6628:     Validates the selected sequence, checking for resource that are
                   6629:     not set to exam mode.
                   6630: 
1.423     albertel 6631: =cut
                   6632: 
1.334     albertel 6633: sub scantron_validate_sequence {
                   6634:     my ($r,$currentphase) = @_;
                   6635: 
                   6636:     my $navmap=Apache::lonnavmaps::navmap->new();
                   6637:     my (undef,undef,$sequence)=
                   6638: 	&Apache::lonnet::decode_symb($env{'form.selectpage'});
                   6639: 
                   6640:     my $map=$navmap->getResourceByUrl($sequence);
                   6641: 
                   6642:     $r->print('<input type="hidden" name="validate_sequence_exam"
                   6643:                                     value="ignore" />');
                   6644:     if ($env{'form.validate_sequence_exam'} ne 'ignore') {
                   6645: 	my @resources=
                   6646: 	    $navmap->retrieveResources($map,\&scantron_filter_not_exam,1,0);
                   6647: 	if (@resources) {
1.357     banghart 6648: 	    $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 6649: 	    return (1,$currentphase);
                   6650: 	}
                   6651:     }
                   6652: 
                   6653:     return (0,$currentphase+1);
                   6654: }
                   6655: 
1.423     albertel 6656: 
                   6657: 
1.157     albertel 6658: sub scantron_validate_ID {
                   6659:     my ($r,$currentphase) = @_;
                   6660:     
                   6661:     #get student info
                   6662:     my $classlist=&Apache::loncoursedata::get_classlist();
                   6663:     my %idmap=&username_to_idmap($classlist);
                   6664: 
                   6665:     #get scantron line setup
1.257     albertel 6666:     my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
1.157     albertel 6667:     my ($scanlines,$scan_data)=&scantron_getfile();
1.447     foxr     6668:     
                   6669:     &scantron_get_maxbubble();	# parse needs the bubble_lines.. array.
1.157     albertel 6670: 
                   6671:     my %found=('ids'=>{},'usernames'=>{});
                   6672:     for (my $i=0;$i<=$scanlines->{'count'};$i++) {
1.200     albertel 6673: 	my $line=&scantron_get_line($scanlines,$scan_data,$i);
1.157     albertel 6674: 	if ($line=~/^[\s\cz]*$/) { next; }
                   6675: 	my $scan_record=&scantron_parse_scanline($line,$i,\%scantron_config,
                   6676: 						 $scan_data);
                   6677: 	my $id=$$scan_record{'scantron.ID'};
                   6678: 	my $found;
                   6679: 	foreach my $checkid (keys(%idmap)) {
                   6680: 	    if (lc($checkid) eq lc($id)) { $found=$checkid;last; }
                   6681: 	}
                   6682: 	if ($found) {
                   6683: 	    my $username=$idmap{$found};
                   6684: 	    if ($found{'ids'}{$found}) {
                   6685: 		&scantron_get_correction($r,$i,$scan_record,\%scantron_config,
                   6686: 					 $line,'duplicateID',$found);
1.194     albertel 6687: 		return(1,$currentphase);
1.157     albertel 6688: 	    } elsif ($found{'usernames'}{$username}) {
                   6689: 		&scantron_get_correction($r,$i,$scan_record,\%scantron_config,
                   6690: 					 $line,'duplicateID',$username);
1.194     albertel 6691: 		return(1,$currentphase);
1.157     albertel 6692: 	    }
1.186     albertel 6693: 	    #FIXME store away line we previously saw the ID on to use above
1.157     albertel 6694: 	    $found{'ids'}{$found}++;
                   6695: 	    $found{'usernames'}{$username}++;
                   6696: 	} else {
                   6697: 	    if ($id =~ /^\s*$/) {
1.158     albertel 6698: 		my $username=&scan_data($scan_data,"$i.user");
1.157     albertel 6699: 		if (defined($username) && $found{'usernames'}{$username}) {
                   6700: 		    &scantron_get_correction($r,$i,$scan_record,
                   6701: 					     \%scantron_config,
                   6702: 					     $line,'duplicateID',$username);
1.194     albertel 6703: 		    return(1,$currentphase);
1.157     albertel 6704: 		} elsif (!defined($username)) {
                   6705: 		    &scantron_get_correction($r,$i,$scan_record,
                   6706: 					     \%scantron_config,
                   6707: 					     $line,'incorrectID');
1.194     albertel 6708: 		    return(1,$currentphase);
1.157     albertel 6709: 		}
                   6710: 		$found{'usernames'}{$username}++;
                   6711: 	    } else {
                   6712: 		&scantron_get_correction($r,$i,$scan_record,\%scantron_config,
                   6713: 					 $line,'incorrectID');
1.194     albertel 6714: 		return(1,$currentphase);
1.157     albertel 6715: 	    }
                   6716: 	}
                   6717:     }
                   6718: 
                   6719:     return (0,$currentphase+1);
                   6720: }
                   6721: 
1.423     albertel 6722: 
1.157     albertel 6723: sub scantron_get_correction {
                   6724:     my ($r,$i,$scan_record,$scan_config,$line,$error,$arg)=@_;
1.454     banghart 6725: #FIXME in the case of a duplicated ID the previous line, probably need
1.157     albertel 6726: #to show both the current line and the previous one and allow skipping
                   6727: #the previous one or the current one
                   6728: 
1.333     albertel 6729:     if ( $$scan_record{'scantron.PaperID'} =~ /\S/) {
1.492     albertel 6730: 	$r->print("<p>".&mt("<b>An error was detected ($error)</b>".
                   6731: 			    " for PaperID <tt>[_1]</tt>",
                   6732: 			    $$scan_record{'scantron.PaperID'})."</p> \n");
1.157     albertel 6733:     } else {
1.492     albertel 6734: 	$r->print("<p>".&mt("<b>An error was detected ($error)</b>".
                   6735: 			    " in scanline [_1] <pre>[_2]</pre>",
                   6736: 			    $i,$line)."</p> \n");
                   6737:     }
                   6738:     my $message="<p>".&mt("The ID on the form is  <tt>[_1]</tt><br />".
                   6739: 			  "The name on the paper is [_2],[_3]",
                   6740: 			  $$scan_record{'scantron.ID'},
                   6741: 			  $$scan_record{'scantron.LastName'},
                   6742: 			  $$scan_record{'scantron.FirstName'})."</p>";
1.242     albertel 6743: 
1.157     albertel 6744:     $r->print('<input type="hidden" name="scantron_corrections" value="'.$error.'" />'."\n");
                   6745:     $r->print('<input type="hidden" name="scantron_line" value="'.$i.'" />'."\n");
1.503     raeburn  6746:                            # Array populated for doublebubble or
                   6747:     my @lines_to_correct;  # missingbubble errors to build javascript
                   6748:                            # to validate radio button checking   
                   6749: 
1.157     albertel 6750:     if ($error =~ /ID$/) {
1.186     albertel 6751: 	if ($error eq 'incorrectID') {
1.492     albertel 6752: 	    $r->print("<p>".&mt("The encoded ID is not in the classlist").
                   6753: 		      "</p>\n");
1.157     albertel 6754: 	} elsif ($error eq 'duplicateID') {
1.492     albertel 6755: 	    $r->print("<p>".&mt("The encoded ID has also been used by a previous paper [_1]",$arg)."</p>\n");
1.157     albertel 6756: 	}
1.242     albertel 6757: 	$r->print($message);
1.492     albertel 6758: 	$r->print("<p>".&mt("How should I handle this?")." <br /> \n");
1.157     albertel 6759: 	$r->print("\n<ul><li> ");
                   6760: 	#FIXME it would be nice if this sent back the user ID and
                   6761: 	#could do partial userID matches
                   6762: 	$r->print(&Apache::loncommon::selectstudent_link('scantronupload',
                   6763: 				       'scantron_username','scantron_domain'));
                   6764: 	$r->print(": <input type='text' name='scantron_username' value='' />");
                   6765: 	$r->print("\n@".
1.257     albertel 6766: 		 &Apache::loncommon::select_dom_form($env{'request.role.domain'},'scantron_domain'));
1.157     albertel 6767: 
                   6768: 	$r->print('</li>');
1.186     albertel 6769:     } elsif ($error =~ /CODE$/) {
                   6770: 	if ($error eq 'incorrectCODE') {
1.492     albertel 6771: 	    $r->print("<p>".&mt("The encoded CODE is not in the list of possible CODEs.")."</p>\n");
1.186     albertel 6772: 	} elsif ($error eq 'duplicateCODE') {
1.492     albertel 6773: 	    $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 6774: 	}
1.492     albertel 6775: 	$r->print("<p>".&mt("The CODE on the form is  <tt>'[_1]'</tt>",
                   6776: 			    $$scan_record{'scantron.CODE'})."<br />\n");
1.242     albertel 6777: 	$r->print($message);
1.492     albertel 6778: 	$r->print("<p>".&mt("How should I handle this?")." <br /> \n");
1.187     albertel 6779: 	$r->print("\n<br /> ");
1.194     albertel 6780: 	my $i=0;
1.273     albertel 6781: 	if ($error eq 'incorrectCODE' 
                   6782: 	    && $$scan_record{'scantron.CODE'}=~/\S/ ) {
1.194     albertel 6783: 	    my ($max,$closest)=&scantron_get_closely_matching_CODEs($arg,$$scan_record{'scantron.CODE'});
1.278     albertel 6784: 	    if ($closest > 0) {
                   6785: 		foreach my $testcode (@{$closest}) {
                   6786: 		    my $checked='';
1.569     bisitz   6787: 		    if (!$i) { $checked=' checked="checked"'; }
1.492     albertel 6788: 		    $r->print("
                   6789:    <label>
1.569     bisitz   6790:        <input type='radio' name='scantron_CODE_resolution' value='use_closest_$i'$checked />
1.492     albertel 6791:        ".&mt("Use the similar CODE [_1] instead.",
                   6792: 	    "<b><tt>".$testcode."</tt></b>")."
                   6793:     </label>
                   6794:     <input type='hidden' name='scantron_CODE_closest_$i' value='$testcode' />");
1.278     albertel 6795: 		    $r->print("\n<br />");
                   6796: 		    $i++;
                   6797: 		}
1.194     albertel 6798: 	    }
                   6799: 	}
1.273     albertel 6800: 	if ($$scan_record{'scantron.CODE'}=~/\S/ ) {
1.569     bisitz   6801: 	    my $checked; if (!$i) { $checked=' checked="checked"'; }
1.492     albertel 6802: 	    $r->print("
                   6803:     <label>
1.569     bisitz   6804:         <input type='radio' name='scantron_CODE_resolution' value='use_unfound'$checked />
1.492     albertel 6805:        ".&mt("Use the CODE [_1] that is was on the paper, ignoring the error.",
                   6806: 	     "<b><tt>".$$scan_record{'scantron.CODE'}."</tt></b>")."
                   6807:     </label>");
1.273     albertel 6808: 	    $r->print("\n<br />");
                   6809: 	}
1.194     albertel 6810: 
1.188     albertel 6811: 	$r->print(<<ENDSCRIPT);
                   6812: <script type="text/javascript">
                   6813: function change_radio(field) {
1.190     albertel 6814:     var slct=document.scantronupload.scantron_CODE_resolution;
1.188     albertel 6815:     var i;
                   6816:     for (i=0;i<slct.length;i++) {
                   6817:         if (slct[i].value==field) { slct[i].checked=true; }
                   6818:     }
                   6819: }
                   6820: </script>
                   6821: ENDSCRIPT
1.187     albertel 6822: 	my $href="/adm/pickcode?".
1.359     www      6823: 	   "form=".&escape("scantronupload").
                   6824: 	   "&scantron_format=".&escape($env{'form.scantron_format'}).
                   6825: 	   "&scantron_CODElist=".&escape($env{'form.scantron_CODElist'}).
                   6826: 	   "&curCODE=".&escape($$scan_record{'scantron.CODE'}).
                   6827: 	   "&scantron_selectfile=".&escape($env{'form.scantron_selectfile'});
1.332     albertel 6828: 	if ($env{'form.scantron_CODElist'} =~ /\S/) { 
1.492     albertel 6829: 	    $r->print("
                   6830:     <label>
                   6831:        <input type='radio' name='scantron_CODE_resolution' value='use_found' />
                   6832:        ".&mt("[_1]Select[_2] a CODE from the list of all CODEs and use it.",
                   6833: 	     "<a target='_blank' href='$href'>","</a>")."
                   6834:     </label> 
1.558     bisitz   6835:     ".&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 6836: 	    $r->print("\n<br />");
                   6837: 	}
1.492     albertel 6838: 	$r->print("
                   6839:     <label>
                   6840:        <input type='radio' name='scantron_CODE_resolution' value='use_typed' />
                   6841:        ".&mt("Use [_1] as the CODE.",
                   6842: 	     "</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 6843: 	$r->print("\n<br /><br />");
1.157     albertel 6844:     } elsif ($error eq 'doublebubble') {
1.503     raeburn  6845: 	$r->print("<p>".&mt("There have been multiple bubbles scanned for some question(s)")."</p>\n");
1.497     foxr     6846: 
                   6847: 	# The form field scantron_questions is acutally a list of line numbers.
                   6848: 	# represented by this form so:
                   6849: 
                   6850: 	my $line_list = &questions_to_line_list($arg);
                   6851: 
1.157     albertel 6852: 	$r->print('<input type="hidden" name="scantron_questions" value="'.
1.497     foxr     6853: 		  $line_list.'" />');
1.242     albertel 6854: 	$r->print($message);
1.492     albertel 6855: 	$r->print("<p>".&mt("Please indicate which bubble should be used for grading")."</p>");
1.157     albertel 6856: 	foreach my $question (@{$arg}) {
1.503     raeburn  6857: 	    my @linenums = &prompt_for_corrections($r,$question,$scan_config,
                   6858:                                                    $scan_record, $error);
1.524     raeburn  6859:             push(@lines_to_correct,@linenums);
1.157     albertel 6860: 	}
1.503     raeburn  6861:         $r->print(&verify_bubbles_checked(@lines_to_correct));
1.157     albertel 6862:     } elsif ($error eq 'missingbubble') {
1.492     albertel 6863: 	$r->print("<p>".&mt("There have been <b>no</b> bubbles scanned for some question(s)")."</p>\n");
1.242     albertel 6864: 	$r->print($message);
1.492     albertel 6865: 	$r->print("<p>".&mt("Please indicate which bubble should be used for grading.")."</p>");
1.503     raeburn  6866: 	$r->print(&mt("Some questions have no scanned bubbles.")."\n");
1.497     foxr     6867: 
1.503     raeburn  6868: 	# The form field scantron_questions is actually a list of line numbers not
1.497     foxr     6869: 	# a list of question numbers. Therefore:
                   6870: 	#
                   6871: 	
                   6872: 	my $line_list = &questions_to_line_list($arg);
                   6873: 
1.157     albertel 6874: 	$r->print('<input type="hidden" name="scantron_questions" value="'.
1.497     foxr     6875: 		  $line_list.'" />');
1.157     albertel 6876: 	foreach my $question (@{$arg}) {
1.503     raeburn  6877: 	    my @linenums = &prompt_for_corrections($r,$question,$scan_config,
                   6878:                                                    $scan_record, $error);
1.524     raeburn  6879:             push(@lines_to_correct,@linenums);
1.157     albertel 6880: 	}
1.503     raeburn  6881:         $r->print(&verify_bubbles_checked(@lines_to_correct));
1.157     albertel 6882:     } else {
                   6883: 	$r->print("\n<ul>");
                   6884:     }
                   6885:     $r->print("\n</li></ul>");
1.497     foxr     6886: }
                   6887: 
1.503     raeburn  6888: sub verify_bubbles_checked {
                   6889:     my (@ansnums) = @_;
                   6890:     my $ansnumstr = join('","',@ansnums);
                   6891:     my $warning = &mt("A bubble or 'No bubble' selection has not been made for one or more lines.");
                   6892:     my $output = (<<ENDSCRIPT);
                   6893: <script type="text/javascript">
                   6894: function verify_bubble_radio(form) {
                   6895:     var ansnumArray = new Array ("$ansnumstr");
                   6896:     var need_bubble_count = 0;
                   6897:     for (var i=0; i<ansnumArray.length; i++) {
                   6898:         if (form.elements["scantron_correct_Q_"+ansnumArray[i]].length > 1) {
                   6899:             var bubble_picked = 0; 
                   6900:             for (var j=0; j<form.elements["scantron_correct_Q_"+ansnumArray[i]].length; j++) {
                   6901:                 if (form.elements["scantron_correct_Q_"+ansnumArray[i]][j].checked == true) {
                   6902:                     bubble_picked = 1;
                   6903:                 }
                   6904:             }
                   6905:             if (bubble_picked == 0) {
                   6906:                 need_bubble_count ++;
                   6907:             }
                   6908:         }
                   6909:     }
                   6910:     if (need_bubble_count) {
                   6911:         alert("$warning");
                   6912:         return;
                   6913:     }
                   6914:     form.submit(); 
                   6915: }
                   6916: </script>
                   6917: ENDSCRIPT
                   6918:     return $output;
                   6919: }
                   6920: 
1.497     foxr     6921: =pod
                   6922: 
                   6923: =item  questions_to_line_list
1.157     albertel 6924: 
1.497     foxr     6925: Converts a list of questions into a string of comma separated
                   6926: line numbers in the answer sheet used by the questions.  This is
                   6927: used to fill in the scantron_questions form field.
                   6928: 
                   6929:   Arguments:
                   6930:      questions    - Reference to an array of questions.
                   6931: 
                   6932: =cut
                   6933: 
                   6934: 
                   6935: sub questions_to_line_list {
                   6936:     my ($questions) = @_;
                   6937:     my @lines;
                   6938: 
1.503     raeburn  6939:     foreach my $item (@{$questions}) {
                   6940:         my $question = $item;
                   6941:         my ($first,$count,$last);
                   6942:         if ($item =~ /^(\d+)\.(\d+)$/) {
                   6943:             $question = $1;
                   6944:             my $subquestion = $2;
                   6945:             $first = $first_bubble_line{$question-1} + 1;
                   6946:             my @subans = split(/,/,$subdivided_bubble_lines{$question-1});
                   6947:             my $subcount = 1;
                   6948:             while ($subcount<$subquestion) {
                   6949:                 $first += $subans[$subcount-1];
                   6950:                 $subcount ++;
                   6951:             }
                   6952:             $count = $subans[$subquestion-1];
                   6953:         } else {
                   6954: 	    $first   = $first_bubble_line{$question-1} + 1;
                   6955: 	    $count   = $bubble_lines_per_response{$question-1};
                   6956:         }
1.506     raeburn  6957:         $last = $first+$count-1;
1.503     raeburn  6958:         push(@lines, ($first..$last));
1.497     foxr     6959:     }
                   6960:     return join(',', @lines);
                   6961: }
                   6962: 
                   6963: =pod 
                   6964: 
                   6965: =item prompt_for_corrections
                   6966: 
                   6967: Prompts for a potentially multiline correction to the
                   6968: user's bubbling (factors out common code from scantron_get_correction
                   6969: for multi and missing bubble cases).
                   6970: 
                   6971:  Arguments:
                   6972:    $r           - Apache request object.
                   6973:    $question    - The question number to prompt for.
                   6974:    $scan_config - The scantron file configuration hash.
                   6975:    $scan_record - Reference to the hash that has the the parsed scanlines.
1.503     raeburn  6976:    $error       - Type of error
1.497     foxr     6977: 
                   6978:  Implicit inputs:
                   6979:    %bubble_lines_per_response   - Starting line numbers for each question.
                   6980:                                   Numbered from 0 (but question numbers are from
                   6981:                                   1.
                   6982:    %first_bubble_line           - Starting bubble line for each question.
1.509     raeburn  6983:    %subdivided_bubble_lines     - optionresponse, matchresponse and rankresponse 
                   6984:                                   type problems render as separate sub-questions, 
1.503     raeburn  6985:                                   in exam mode. This hash contains a 
                   6986:                                   comma-separated list of the lines per 
                   6987:                                   sub-question.
1.510     raeburn  6988:    %responsetype_per_response   - essayresponse, formularesponse,
                   6989:                                   stringresponse, imageresponse, reactionresponse,
                   6990:                                   and organicresponse type problem parts can have
1.503     raeburn  6991:                                   multiple lines per response if the weight
                   6992:                                   assigned exceeds 10.  In this case, only
                   6993:                                   one bubble per line is permitted, but more 
                   6994:                                   than one line might contain bubbles, e.g.
                   6995:                                   bubbling of: line 1 - J, line 2 - J, 
                   6996:                                   line 3 - B would assign 22 points.  
1.497     foxr     6997: 
                   6998: =cut
                   6999: 
                   7000: sub prompt_for_corrections {
1.503     raeburn  7001:     my ($r, $question, $scan_config, $scan_record, $error) = @_;
                   7002:     my ($current_line,$lines);
                   7003:     my @linenums;
                   7004:     my $questionnum = $question;
                   7005:     if ($question =~ /^(\d+)\.(\d+)$/) {
                   7006:         $question = $1;
                   7007:         $current_line = $first_bubble_line{$question-1} + 1 ;
                   7008:         my $subquestion = $2;
                   7009:         my @subans = split(/,/,$subdivided_bubble_lines{$question-1});
                   7010:         my $subcount = 1;
                   7011:         while ($subcount<$subquestion) {
                   7012:             $current_line += $subans[$subcount-1];
                   7013:             $subcount ++;
                   7014:         }
                   7015:         $lines = $subans[$subquestion-1];
                   7016:     } else {
                   7017:         $current_line = $first_bubble_line{$question-1} + 1 ;
                   7018:         $lines        = $bubble_lines_per_response{$question-1};
                   7019:     }
1.497     foxr     7020:     if ($lines > 1) {
1.503     raeburn  7021:         $r->print(&mt('The group of bubble lines below responds to a single question.').'<br />');
                   7022:         if (($responsetype_per_response{$question-1} eq 'essayresponse') ||
                   7023:             ($responsetype_per_response{$question-1} eq 'formularesponse') ||
1.510     raeburn  7024:             ($responsetype_per_response{$question-1} eq 'stringresponse') ||
                   7025:             ($responsetype_per_response{$question-1} eq 'imageresponse') ||
                   7026:             ($responsetype_per_response{$question-1} eq 'reactionresponse') ||
                   7027:             ($responsetype_per_response{$question-1} eq 'organicresponse')) {
1.572     www      7028:             $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  7029:         } else {
                   7030:             $r->print(&mt("Select at most one bubble in a single line and select 'No Bubble' in all the other lines. ")."<br />");
                   7031:         }
1.497     foxr     7032:     }
                   7033:     for (my $i =0; $i < $lines; $i++) {
1.503     raeburn  7034:         my $selected = $$scan_record{"scantron.$current_line.answer"};
                   7035: 	&scantron_bubble_selector($r,$scan_config,$current_line, 
                   7036: 	        		  $questionnum,$error,split('', $selected));
1.524     raeburn  7037:         push(@linenums,$current_line);
1.497     foxr     7038: 	$current_line++;
                   7039:     }
                   7040:     if ($lines > 1) {
                   7041: 	$r->print("<hr /><br />");
                   7042:     }
1.503     raeburn  7043:     return @linenums;
1.157     albertel 7044: }
1.423     albertel 7045: 
                   7046: =pod
                   7047: 
                   7048: =item scantron_bubble_selector
                   7049:   
                   7050:    Generates the html radiobuttons to correct a single bubble line
1.424     albertel 7051:    possibly showing the existing the selected bubbles if known
1.423     albertel 7052: 
                   7053:  Arguments:
                   7054:     $r           - Apache request object
                   7055:     $scan_config - hash from &get_scantron_config()
1.497     foxr     7056:     $line        - Number of the line being displayed.
1.503     raeburn  7057:     $questionnum - Question number (may include subquestion)
                   7058:     $error       - Type of error.
1.497     foxr     7059:     @selected    - Array of bubbles picked on this line.
1.423     albertel 7060: 
                   7061: =cut
                   7062: 
1.157     albertel 7063: sub scantron_bubble_selector {
1.503     raeburn  7064:     my ($r,$scan_config,$line,$questionnum,$error,@selected)=@_;
1.157     albertel 7065:     my $max=$$scan_config{'Qlength'};
1.274     albertel 7066: 
                   7067:     my $scmode=$$scan_config{'Qon'};
                   7068:     if ($scmode eq 'number' || $scmode eq 'letter') { $max=10; }	     
                   7069: 
1.157     albertel 7070:     my @alphabet=('A'..'Z');
1.503     raeburn  7071:     $r->print(&Apache::loncommon::start_data_table().
                   7072:               &Apache::loncommon::start_data_table_row());
                   7073:     $r->print('<td rowspan="2" class="LC_leftcol_header">'.$line.'</td>');
1.497     foxr     7074:     for (my $i=0;$i<$max+1;$i++) {
                   7075: 	$r->print("\n".'<td align="center">');
                   7076: 	if ($selected[0] eq $alphabet[$i]) { $r->print('X'); shift(@selected) }
                   7077: 	else { $r->print('&nbsp;'); }
                   7078: 	$r->print('</td>');
                   7079:     }
1.503     raeburn  7080:     $r->print(&Apache::loncommon::end_data_table_row().
                   7081:               &Apache::loncommon::start_data_table_row());
1.497     foxr     7082:     for (my $i=0;$i<$max;$i++) {
                   7083: 	$r->print("\n".
                   7084: 		  '<td><label><input type="radio" name="scantron_correct_Q_'.
                   7085: 		  $line.'" value="'.$i.'" />'.$alphabet[$i]."</label></td>");
                   7086:     }
1.503     raeburn  7087:     my $nobub_checked = ' ';
                   7088:     if ($error eq 'missingbubble') {
                   7089:         $nobub_checked = ' checked = "checked" ';
                   7090:     }
                   7091:     $r->print("\n".'<td><label><input type="radio" name="scantron_correct_Q_'.
                   7092: 	      $line.'" value="none"'.$nobub_checked.'/>'.&mt('No bubble').
                   7093:               '</label>'."\n".'<input type="hidden" name="scantron_questionnum_Q_'.
                   7094:               $line.'" value="'.$questionnum.'" /></td>');
                   7095:     $r->print(&Apache::loncommon::end_data_table_row().
                   7096:               &Apache::loncommon::end_data_table());
1.157     albertel 7097: }
                   7098: 
1.423     albertel 7099: =pod
                   7100: 
                   7101: =item num_matches
                   7102: 
1.424     albertel 7103:    Counts the number of characters that are the same between the two arguments.
                   7104: 
                   7105:  Arguments:
                   7106:    $orig - CODE from the scanline
                   7107:    $code - CODE to match against
                   7108: 
                   7109:  Returns:
                   7110:    $count - integer count of the number of same characters between the
                   7111:             two arguments
                   7112: 
1.423     albertel 7113: =cut
                   7114: 
1.194     albertel 7115: sub num_matches {
                   7116:     my ($orig,$code) = @_;
                   7117:     my @code=split(//,$code);
                   7118:     my @orig=split(//,$orig);
                   7119:     my $same=0;
                   7120:     for (my $i=0;$i<scalar(@code);$i++) {
                   7121: 	if ($code[$i] eq $orig[$i]) { $same++; }
                   7122:     }
                   7123:     return $same;
                   7124: }
                   7125: 
1.423     albertel 7126: =pod
                   7127: 
                   7128: =item scantron_get_closely_matching_CODEs
                   7129: 
1.424     albertel 7130:    Cycles through all CODEs and finds the set that has the greatest
                   7131:    number of same characters as the provided CODE
                   7132: 
                   7133:  Arguments:
                   7134:    $allcodes - hash ref returned by &get_codes()
                   7135:    $CODE     - CODE from the current scanline
                   7136: 
                   7137:  Returns:
                   7138:    2 element list
                   7139:     - first elements is number of how closely matching the best fit is 
                   7140:       (5 means best set has 5 matching characters)
                   7141:     - second element is an arrary ref containing the set of valid CODEs
                   7142:       that best fit the passed in CODE
                   7143: 
1.423     albertel 7144: =cut
                   7145: 
1.194     albertel 7146: sub scantron_get_closely_matching_CODEs {
                   7147:     my ($allcodes,$CODE)=@_;
                   7148:     my @CODEs;
                   7149:     foreach my $testcode (sort(keys(%{$allcodes}))) {
                   7150: 	push(@{$CODEs[&num_matches($CODE,$testcode)]},$testcode);
                   7151:     }
                   7152: 
                   7153:     return ($#CODEs,$CODEs[-1]);
                   7154: }
                   7155: 
1.423     albertel 7156: =pod
                   7157: 
                   7158: =item get_codes
                   7159: 
1.424     albertel 7160:    Builds a hash which has keys of all of the valid CODEs from the selected
                   7161:    set of remembered CODEs.
                   7162: 
                   7163:  Arguments:
                   7164:   $old_name - name of the set of remembered CODEs
                   7165:   $cdom     - domain of the course
                   7166:   $cnum     - internal course name
                   7167: 
                   7168:  Returns:
                   7169:   %allcodes - keys are the valid CODEs, values are all 1
                   7170: 
1.423     albertel 7171: =cut
                   7172: 
1.194     albertel 7173: sub get_codes {
1.280     foxr     7174:     my ($old_name, $cdom, $cnum) = @_;
                   7175:     if (!$old_name) {
                   7176: 	$old_name=$env{'form.scantron_CODElist'};
                   7177:     }
                   7178:     if (!$cdom) {
                   7179: 	$cdom =$env{'course.'.$env{'request.course.id'}.'.domain'};
                   7180:     }
                   7181:     if (!$cnum) {
                   7182: 	$cnum =$env{'course.'.$env{'request.course.id'}.'.num'};
                   7183:     }
1.278     albertel 7184:     my %result=&Apache::lonnet::get('CODEs',[$old_name,"type\0$old_name"],
                   7185: 				    $cdom,$cnum);
                   7186:     my %allcodes;
                   7187:     if ($result{"type\0$old_name"} eq 'number') {
                   7188: 	%allcodes=map {($_,1)} split(',',$result{$old_name});
                   7189:     } else {
                   7190: 	%allcodes=map {(&Apache::lonprintout::num_to_letters($_),1)} split(',',$result{$old_name});
                   7191:     }
1.194     albertel 7192:     return %allcodes;
                   7193: }
                   7194: 
1.423     albertel 7195: =pod
                   7196: 
                   7197: =item scantron_validate_CODE
                   7198: 
1.424     albertel 7199:    Validates all scanlines in the selected file to not have any
                   7200:    invalid or underspecified CODEs and that none of the codes are
                   7201:    duplicated if this was requested.
                   7202: 
1.423     albertel 7203: =cut
                   7204: 
1.157     albertel 7205: sub scantron_validate_CODE {
                   7206:     my ($r,$currentphase) = @_;
1.257     albertel 7207:     my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
1.186     albertel 7208:     if ($scantron_config{'CODElocation'} &&
                   7209: 	$scantron_config{'CODEstart'} &&
                   7210: 	$scantron_config{'CODElength'}) {
1.257     albertel 7211: 	if (!defined($env{'form.scantron_CODElist'})) {
1.186     albertel 7212: 	    &FIXME_blow_up()
                   7213: 	}
                   7214:     } else {
                   7215: 	return (0,$currentphase+1);
                   7216:     }
                   7217:     
                   7218:     my %usedCODEs;
                   7219: 
1.194     albertel 7220:     my %allcodes=&get_codes();
1.186     albertel 7221: 
1.447     foxr     7222:     &scantron_get_maxbubble();	# parse needs the lines per response array.
                   7223: 
1.186     albertel 7224:     my ($scanlines,$scan_data)=&scantron_getfile();
                   7225:     for (my $i=0;$i<=$scanlines->{'count'};$i++) {
1.200     albertel 7226: 	my $line=&scantron_get_line($scanlines,$scan_data,$i);
1.186     albertel 7227: 	if ($line=~/^[\s\cz]*$/) { next; }
                   7228: 	my $scan_record=&scantron_parse_scanline($line,$i,\%scantron_config,
                   7229: 						 $scan_data);
                   7230: 	my $CODE=$$scan_record{'scantron.CODE'};
                   7231: 	my $error=0;
1.224     albertel 7232: 	if (!&Apache::lonnet::validCODE($CODE)) {
                   7233: 	    &scantron_get_correction($r,$i,$scan_record,
                   7234: 				     \%scantron_config,
                   7235: 				     $line,'incorrectCODE',\%allcodes);
                   7236: 	    return(1,$currentphase);
                   7237: 	}
1.221     albertel 7238: 	if (%allcodes && !exists($allcodes{$CODE}) 
                   7239: 	    && !$$scan_record{'scantron.useCODE'}) {
1.186     albertel 7240: 	    &scantron_get_correction($r,$i,$scan_record,
                   7241: 				     \%scantron_config,
1.194     albertel 7242: 				     $line,'incorrectCODE',\%allcodes);
                   7243: 	    return(1,$currentphase);
1.186     albertel 7244: 	}
1.214     albertel 7245: 	if (exists($usedCODEs{$CODE}) 
1.257     albertel 7246: 	    && $env{'form.scantron_CODEunique'} eq 'yes'
1.192     albertel 7247: 	    && !$$scan_record{'scantron.CODE_ignore_dup'}) {
1.186     albertel 7248: 	    &scantron_get_correction($r,$i,$scan_record,
                   7249: 				     \%scantron_config,
1.194     albertel 7250: 				     $line,'duplicateCODE',$usedCODEs{$CODE});
                   7251: 	    return(1,$currentphase);
1.186     albertel 7252: 	}
1.524     raeburn  7253: 	push(@{$usedCODEs{$CODE}},$$scan_record{'scantron.PaperID'});
1.186     albertel 7254:     }
1.157     albertel 7255:     return (0,$currentphase+1);
                   7256: }
                   7257: 
1.423     albertel 7258: =pod
                   7259: 
                   7260: =item scantron_validate_doublebubble
                   7261: 
1.424     albertel 7262:    Validates all scanlines in the selected file to not have any
                   7263:    bubble lines with multiple bubbles marked.
                   7264: 
1.423     albertel 7265: =cut
                   7266: 
1.157     albertel 7267: sub scantron_validate_doublebubble {
                   7268:     my ($r,$currentphase) = @_;
                   7269:     #get student info
                   7270:     my $classlist=&Apache::loncoursedata::get_classlist();
                   7271:     my %idmap=&username_to_idmap($classlist);
                   7272: 
                   7273:     #get scantron line setup
1.257     albertel 7274:     my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
1.157     albertel 7275:     my ($scanlines,$scan_data)=&scantron_getfile();
1.447     foxr     7276:     &scantron_get_maxbubble();	# parse needs the bubble line array.
                   7277: 
1.157     albertel 7278:     for (my $i=0;$i<=$scanlines->{'count'};$i++) {
1.200     albertel 7279: 	my $line=&scantron_get_line($scanlines,$scan_data,$i);
1.157     albertel 7280: 	if ($line=~/^[\s\cz]*$/) { next; }
                   7281: 	my $scan_record=&scantron_parse_scanline($line,$i,\%scantron_config,
                   7282: 						 $scan_data);
                   7283: 	if (!defined($$scan_record{'scantron.doubleerror'})) { next; }
                   7284: 	&scantron_get_correction($r,$i,$scan_record,\%scantron_config,$line,
                   7285: 				 'doublebubble',
                   7286: 				 $$scan_record{'scantron.doubleerror'});
                   7287:     	return (1,$currentphase);
                   7288:     }
                   7289:     return (0,$currentphase+1);
                   7290: }
                   7291: 
1.423     albertel 7292: 
1.503     raeburn  7293: sub scantron_get_maxbubble {
1.257     albertel 7294:     if (defined($env{'form.scantron_maxbubble'}) &&
                   7295: 	$env{'form.scantron_maxbubble'}) {
1.447     foxr     7296: 	&restore_bubble_lines();
1.257     albertel 7297: 	return $env{'form.scantron_maxbubble'};
1.191     albertel 7298:     }
1.330     albertel 7299: 
1.447     foxr     7300:     my (undef, undef, $sequence) =
1.257     albertel 7301: 	&Apache::lonnet::decode_symb($env{'form.selectpage'});
1.330     albertel 7302: 
1.447     foxr     7303:     my $navmap=Apache::lonnavmaps::navmap->new();
1.191     albertel 7304:     my $map=$navmap->getResourceByUrl($sequence);
                   7305:     my @resources=$navmap->retrieveResources($map,\&scantron_filter,1,0);
1.330     albertel 7306: 
                   7307:     &Apache::lonxml::clear_problem_counter();
                   7308: 
1.557     raeburn  7309:     my $uname       = $env{'user.name'};
                   7310:     my $udom        = $env{'user.domain'};
1.435     foxr     7311:     my $cid         = $env{'request.course.id'};
                   7312:     my $total_lines = 0;
                   7313:     %bubble_lines_per_response = ();
1.447     foxr     7314:     %first_bubble_line         = ();
1.503     raeburn  7315:     %subdivided_bubble_lines   = ();
                   7316:     %responsetype_per_response = ();
1.554     raeburn  7317: 
1.447     foxr     7318:     my $response_number = 0;
                   7319:     my $bubble_line     = 0;
1.191     albertel 7320:     foreach my $resource (@resources) {
1.542     raeburn  7321:         my ($analysis,$parts) = &scantron_partids_tograde($resource,$cid,$uname,$udom);
                   7322:         if ((ref($analysis) eq 'HASH') && (ref($parts) eq 'ARRAY')) {
                   7323: 	    foreach my $part_id (@{$parts}) {
                   7324:                 my $lines;
                   7325: 
                   7326: 	        # TODO - make this a persistent hash not an array.
                   7327: 
                   7328:                 # optionresponse, matchresponse and rankresponse type items 
                   7329:                 # render as separate sub-questions in exam mode.
                   7330:                 if (($analysis->{$part_id.'.type'} eq 'optionresponse') ||
                   7331:                     ($analysis->{$part_id.'.type'} eq 'matchresponse') ||
                   7332:                     ($analysis->{$part_id.'.type'} eq 'rankresponse')) {
                   7333:                     my ($numbub,$numshown);
                   7334:                     if ($analysis->{$part_id.'.type'} eq 'optionresponse') {
                   7335:                         if (ref($analysis->{$part_id.'.options'}) eq 'ARRAY') {
                   7336:                             $numbub = scalar(@{$analysis->{$part_id.'.options'}});
                   7337:                         }
                   7338:                     } elsif ($analysis->{$part_id.'.type'} eq 'matchresponse') {
                   7339:                         if (ref($analysis->{$part_id.'.items'}) eq 'ARRAY') {
                   7340:                             $numbub = scalar(@{$analysis->{$part_id.'.items'}});
                   7341:                         }
                   7342:                     } elsif ($analysis->{$part_id.'.type'} eq 'rankresponse') {
                   7343:                         if (ref($analysis->{$part_id.'.foils'}) eq 'ARRAY') {
                   7344:                             $numbub = scalar(@{$analysis->{$part_id.'.foils'}});
                   7345:                         }
                   7346:                     }
                   7347:                     if (ref($analysis->{$part_id.'.shown'}) eq 'ARRAY') {
                   7348:                         $numshown = scalar(@{$analysis->{$part_id.'.shown'}});
                   7349:                     }
                   7350:                     my $bubbles_per_line = 10;
                   7351:                     my $inner_bubble_lines = int($numbub/$bubbles_per_line);
                   7352:                     if (($numbub % $bubbles_per_line) != 0) {
                   7353:                         $inner_bubble_lines++;
                   7354:                     }
                   7355:                     for (my $i=0; $i<$numshown; $i++) {
                   7356:                         $subdivided_bubble_lines{$response_number} .= 
                   7357:                             $inner_bubble_lines.',';
                   7358:                     }
                   7359:                     $subdivided_bubble_lines{$response_number} =~ s/,$//;
                   7360:                     $lines = $numshown * $inner_bubble_lines;
                   7361:                 } else {
                   7362:                     $lines = $analysis->{"$part_id.bubble_lines"};
                   7363:                 } 
                   7364: 
                   7365:                 $first_bubble_line{$response_number} = $bubble_line;
                   7366: 	        $bubble_lines_per_response{$response_number} = $lines;
                   7367:                 $responsetype_per_response{$response_number} = 
                   7368:                     $analysis->{$part_id.'.type'};
                   7369: 	        $response_number++;
                   7370: 
                   7371: 	        $bubble_line +=  $lines;
                   7372: 	        $total_lines +=  $lines;
                   7373: 	    }
                   7374:         }
                   7375:     }
1.552     raeburn  7376:     &Apache::lonnet::delenv('scantron.');
1.542     raeburn  7377: 
                   7378:     &save_bubble_lines();
                   7379:     $env{'form.scantron_maxbubble'} =
                   7380: 	$total_lines;
                   7381:     return $env{'form.scantron_maxbubble'};
                   7382: }
1.523     raeburn  7383: 
1.157     albertel 7384: sub scantron_validate_missingbubbles {
                   7385:     my ($r,$currentphase) = @_;
                   7386:     #get student info
                   7387:     my $classlist=&Apache::loncoursedata::get_classlist();
                   7388:     my %idmap=&username_to_idmap($classlist);
                   7389: 
                   7390:     #get scantron line setup
1.257     albertel 7391:     my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
1.157     albertel 7392:     my ($scanlines,$scan_data)=&scantron_getfile();
1.191     albertel 7393:     my $max_bubble=&scantron_get_maxbubble();
1.157     albertel 7394:     if (!$max_bubble) { $max_bubble=2**31; }
                   7395:     for (my $i=0;$i<=$scanlines->{'count'};$i++) {
1.200     albertel 7396: 	my $line=&scantron_get_line($scanlines,$scan_data,$i);
1.157     albertel 7397: 	if ($line=~/^[\s\cz]*$/) { next; }
                   7398: 	my $scan_record=&scantron_parse_scanline($line,$i,\%scantron_config,
                   7399: 						 $scan_data);
                   7400: 	if (!defined($$scan_record{'scantron.missingerror'})) { next; }
                   7401: 	my @to_correct;
1.470     foxr     7402: 	
                   7403: 	# Probably here's where the error is...
                   7404: 
1.157     albertel 7405: 	foreach my $missing (@{$$scan_record{'scantron.missingerror'}}) {
1.505     raeburn  7406:             my $lastbubble;
                   7407:             if ($missing =~ /^(\d+)\.(\d+)$/) {
                   7408:                my $question = $1;
                   7409:                my $subquestion = $2;
                   7410:                if (!defined($first_bubble_line{$question -1})) { next; }
                   7411:                my $first = $first_bubble_line{$question-1};
                   7412:                my @subans = split(/,/,$subdivided_bubble_lines{$question-1});
                   7413:                my $subcount = 1;
                   7414:                while ($subcount<$subquestion) {
                   7415:                    $first += $subans[$subcount-1];
                   7416:                    $subcount ++;
                   7417:                }
                   7418:                my $count = $subans[$subquestion-1];
                   7419:                $lastbubble = $first + $count;
                   7420:             } else {
                   7421:                 if (!defined($first_bubble_line{$missing - 1})) { next; }
                   7422:                 $lastbubble = $first_bubble_line{$missing - 1} + $bubble_lines_per_response{$missing - 1};
                   7423:             }
                   7424:             if ($lastbubble > $max_bubble) { next; }
1.157     albertel 7425: 	    push(@to_correct,$missing);
                   7426: 	}
                   7427: 	if (@to_correct) {
                   7428: 	    &scantron_get_correction($r,$i,$scan_record,\%scantron_config,
                   7429: 				     $line,'missingbubble',\@to_correct);
                   7430: 	    return (1,$currentphase);
                   7431: 	}
                   7432: 
                   7433:     }
                   7434:     return (0,$currentphase+1);
                   7435: }
                   7436: 
1.423     albertel 7437: 
1.82      albertel 7438: sub scantron_process_students {
1.75      albertel 7439:     my ($r) = @_;
1.513     foxr     7440: 
1.257     albertel 7441:     my (undef,undef,$sequence)=&Apache::lonnet::decode_symb($env{'form.selectpage'});
1.324     albertel 7442:     my ($symb)=&get_symb($r);
1.513     foxr     7443:     if (!$symb) {
                   7444: 	return '';
                   7445:     }
1.324     albertel 7446:     my $default_form_data=&defaultFormData($symb);
1.82      albertel 7447: 
1.257     albertel 7448:     my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
1.157     albertel 7449:     my ($scanlines,$scan_data)=&scantron_getfile();
1.82      albertel 7450:     my $classlist=&Apache::loncoursedata::get_classlist();
                   7451:     my %idmap=&username_to_idmap($classlist);
1.132     bowersj2 7452:     my $navmap=Apache::lonnavmaps::navmap->new();
1.83      albertel 7453:     my $map=$navmap->getResourceByUrl($sequence);
                   7454:     my @resources=$navmap->retrieveResources($map,\&scantron_filter,1,0);
1.557     raeburn  7455:     my (%grader_partids_by_symb,%grader_randomlists_by_symb);
                   7456:     &graders_resources_pass(\@resources,\%grader_partids_by_symb,
                   7457:                             \%grader_randomlists_by_symb);
                   7458:     foreach my $resource (@resources) {
                   7459:         my $ressymb = $resource->symb();
                   7460:         my ($analysis,$parts) =
                   7461:             &scantron_partids_tograde($resource,$env{'request.course.id'},
                   7462:                                       $env{'user.name'},$env{'user.domain'},1);
                   7463:         $grader_partids_by_symb{$ressymb} = $parts;
                   7464:         if (ref($analysis) eq 'HASH') {
                   7465:             if (ref($analysis->{'parts_withrandomlist'}) eq 'ARRAY') {
                   7466:                 $grader_randomlists_by_symb{$ressymb} = 
                   7467:                     $analysis->{'parts_withrandomlist'};
                   7468:             }
                   7469:         }
                   7470:     }
                   7471: 
1.554     raeburn  7472:     my ($uname,$udom);
1.82      albertel 7473:     my $result= <<SCANTRONFORM;
1.81      albertel 7474: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="scantronupload">
                   7475:   <input type="hidden" name="command" value="scantron_configphase" />
                   7476:   $default_form_data
                   7477: SCANTRONFORM
1.82      albertel 7478:     $r->print($result);
                   7479: 
                   7480:     my @delayqueue;
1.542     raeburn  7481:     my (%completedstudents,%scandata);
1.140     albertel 7482:     
1.520     www      7483:     my $lock=&Apache::lonnet::set_lock(&mt('Grading bubblesheet exam'));
1.200     albertel 7484:     my $count=&get_todo_count($scanlines,$scan_data);
1.575     www      7485:     my %prog_state=&Apache::lonhtmlcommon::Create_PrgWin($r,'Bubblesheet Status',
                   7486:  				    'Bubblesheet Progress',$count,
1.195     albertel 7487: 				    'inline',undef,'scantronupload');
1.140     albertel 7488:     &Apache::lonhtmlcommon::Update_PrgWin($r,\%prog_state,
                   7489: 					  'Processing first student');
1.542     raeburn  7490:     $r->print('<br />');
1.140     albertel 7491:     my $start=&Time::HiRes::time();
1.158     albertel 7492:     my $i=-1;
1.542     raeburn  7493:     my $started;
1.447     foxr     7494: 
                   7495:     &scantron_get_maxbubble();	# Need the bubble lines array to parse.
1.513     foxr     7496: 
                   7497:     # If an ssi failed in scantron_get_maxbubble, put an error message out to
                   7498:     # the user and return.
                   7499: 
                   7500:     if ($ssi_error) {
                   7501: 	$r->print("</form>");
                   7502: 	&ssi_print_error($r);
                   7503: 	$r->print(&show_grading_menu_form($symb));
1.520     www      7504:         &Apache::lonnet::remove_lock($lock);
1.513     foxr     7505: 	return '';		# Dunno why the other returns return '' rather than just returning.
                   7506:     }
1.447     foxr     7507: 
1.542     raeburn  7508:     my %lettdig = &letter_to_digits();
                   7509:     my $numletts = scalar(keys(%lettdig));
                   7510: 
1.157     albertel 7511:     while ($i<$scanlines->{'count'}) {
                   7512:  	($uname,$udom)=('','');
                   7513:  	$i++;
1.200     albertel 7514:  	my $line=&scantron_get_line($scanlines,$scan_data,$i);
1.157     albertel 7515:  	if ($line=~/^[\s\cz]*$/) { next; }
1.200     albertel 7516: 	if ($started) {
                   7517: 	    &Apache::lonhtmlcommon::Increment_PrgWin($r,\%prog_state,
                   7518: 						     'last student');
                   7519: 	}
                   7520: 	$started=1;
1.157     albertel 7521:  	my $scan_record=&scantron_parse_scanline($line,$i,\%scantron_config,
                   7522:  						 $scan_data);
                   7523:  	unless ($uname=&scantron_find_student($scan_record,$scan_data,
                   7524:  					      \%idmap,$i)) {
                   7525:   	    &scantron_add_delay(\@delayqueue,$line,
                   7526:  				'Unable to find a student that matches',1);
                   7527:  	    next;
                   7528:   	}
                   7529:  	if (exists $completedstudents{$uname}) {
                   7530:  	    &scantron_add_delay(\@delayqueue,$line,
                   7531:  				'Student '.$uname.' has multiple sheets',2);
                   7532:  	    next;
                   7533:  	}
                   7534:   	($uname,$udom)=split(/:/,$uname);
1.330     albertel 7535: 
1.554     raeburn  7536:         my %partids_by_symb;
                   7537:         foreach my $resource (@resources) {
                   7538:             my $ressymb = $resource->symb();
1.557     raeburn  7539:             if ((exists($grader_randomlists_by_symb{$ressymb})) ||
                   7540:                 (ref($grader_partids_by_symb{$ressymb}) ne 'ARRAY')) {
                   7541:                 my ($analysis,$parts) =
                   7542:                     &scantron_partids_tograde($resource,$env{'request.course.id'},$uname,$udom);
                   7543:                 $partids_by_symb{$ressymb} = $parts;
                   7544:             } else {
                   7545:                 $partids_by_symb{$ressymb} = $grader_partids_by_symb{$ressymb};
                   7546:             }
1.554     raeburn  7547:         }
                   7548: 
1.330     albertel 7549: 	&Apache::lonxml::clear_problem_counter();
1.514     raeburn  7550:   	&Apache::lonnet::appenv($scan_record);
1.376     albertel 7551: 
                   7552: 	if (&scantron_clear_skip($scanlines,$scan_data,$i)) {
                   7553: 	    &scantron_putfile($scanlines,$scan_data);
                   7554: 	}
1.161     albertel 7555: 	
1.542     raeburn  7556:         my $scancode;
                   7557:         if ((exists($scan_record->{'scantron.CODE'})) &&
                   7558:             (&Apache::lonnet::validCODE($scan_record->{'scantron.CODE'}))) {
                   7559:             $scancode = $scan_record->{'scantron.CODE'};
                   7560:         } else {
                   7561:             $scancode = '';
                   7562:         }
                   7563: 
                   7564:         if (&grade_student_bubbles($r,$uname,$udom,$scan_record,$scancode,
1.554     raeburn  7565:                                    \@resources,\%partids_by_symb) eq 'ssi_error') {
1.542     raeburn  7566:             $ssi_error = 0; # So end of handler error message does not trigger.
                   7567:             $r->print("</form>");
                   7568:             &ssi_print_error($r);
                   7569:             $r->print(&show_grading_menu_form($symb));
                   7570:             &Apache::lonnet::remove_lock($lock);
                   7571:             return '';      # Why return ''?  Beats me.
                   7572:         }
1.513     foxr     7573: 
1.140     albertel 7574: 	$completedstudents{$uname}={'line'=>$line};
1.542     raeburn  7575:         if ($env{'form.verifyrecord'}) {
                   7576:             my $lastpos = $env{'form.scantron_maxbubble'}*$scantron_config{'Qlength'};
                   7577:             my $studentdata = substr($line,$scantron_config{'Qstart'}-1,$lastpos);
                   7578:             chomp($studentdata);
                   7579:             $studentdata =~ s/\r$//;
                   7580:             my $studentrecord = '';
                   7581:             my $counter = -1;
                   7582:             foreach my $resource (@resources) {
1.554     raeburn  7583:                 my $ressymb = $resource->symb();
1.542     raeburn  7584:                 ($counter,my $recording) =
                   7585:                     &verify_scantron_grading($resource,$udom,$uname,$env{'request.course.id'},
1.554     raeburn  7586:                                              $counter,$studentdata,$partids_by_symb{$ressymb},
1.542     raeburn  7587:                                              \%scantron_config,\%lettdig,$numletts);
                   7588:                 $studentrecord .= $recording;
                   7589:             }
                   7590:             if ($studentrecord ne $studentdata) {
1.554     raeburn  7591:                 &Apache::lonxml::clear_problem_counter();
                   7592:                 if (&grade_student_bubbles($r,$uname,$udom,$scan_record,$scancode,
                   7593:                                            \@resources,\%partids_by_symb) eq 'ssi_error') {
                   7594:                     $ssi_error = 0; # So end of handler error message does not trigger.
                   7595:                     $r->print("</form>");
                   7596:                     &ssi_print_error($r);
                   7597:                     $r->print(&show_grading_menu_form($symb));
                   7598:                     &Apache::lonnet::remove_lock($lock);
                   7599:                     delete($completedstudents{$uname});
                   7600:                     return '';
                   7601:                 }
1.542     raeburn  7602:                 $counter = -1;
                   7603:                 $studentrecord = '';
                   7604:                 foreach my $resource (@resources) {
1.554     raeburn  7605:                     my $ressymb = $resource->symb();
1.542     raeburn  7606:                     ($counter,my $recording) =
                   7607:                         &verify_scantron_grading($resource,$udom,$uname,$env{'request.course.id'},
1.554     raeburn  7608:                                                  $counter,$studentdata,$partids_by_symb{$ressymb},
1.542     raeburn  7609:                                                  \%scantron_config,\%lettdig,$numletts);
                   7610:                     $studentrecord .= $recording;
                   7611:                 }
                   7612:                 if ($studentrecord ne $studentdata) {
                   7613:                     $r->print('<p><span class="LC_error">');
                   7614:                     if ($scancode eq '') {
                   7615:                         $r->print(&mt('Mismatch grading bubble sheet for user: [_1] with ID: [_2].',
                   7616:                                   $uname.':'.$udom,$scan_record->{'scantron.ID'}));
                   7617:                     } else {
                   7618:                         $r->print(&mt('Mismatch grading bubble sheet for user: [_1] with ID: [_2] and CODE: [_3].',
                   7619:                                   $uname.':'.$udom,$scan_record->{'scantron.ID'},$scancode));
                   7620:                     }
                   7621:                     $r->print('</span><br />'.&Apache::loncommon::start_data_table()."\n".
                   7622:                               &Apache::loncommon::start_data_table_header_row()."\n".
                   7623:                               '<th>'.&mt('Source').'</th><th>'.&mt('Bubbled responses').'</th>'.
                   7624:                               &Apache::loncommon::end_data_table_header_row()."\n".
                   7625:                               &Apache::loncommon::start_data_table_row().
                   7626:                               '<td>'.&mt('Bubble Sheet').'</td>'.
                   7627:                               '<td><span class="LC_nobreak">'.$studentdata.'</span></td>'.
                   7628:                               &Apache::loncommon::end_data_table_row().
                   7629:                               &Apache::loncommon::start_data_table_row().
                   7630:                               '<td>Stored submissions</td>'.
                   7631:                               '<td><span class="LC_nobreak">'.$studentrecord.'</span></td>'."\n".
                   7632:                               &Apache::loncommon::end_data_table_row().
                   7633:                               &Apache::loncommon::end_data_table().'</p>');
                   7634:                 } else {
                   7635:                     $r->print('<br /><span class="LC_warning">'.
                   7636:                              &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 />'.
                   7637:                              &mt("As a consequence, this user's submission history records two tries.").
                   7638:                                  '</span><br />');
                   7639:                 }
                   7640:             }
                   7641:         }
1.543     raeburn  7642:         if (&Apache::loncommon::connection_aborted($r)) { last; }
1.140     albertel 7643:     } continue {
1.330     albertel 7644: 	&Apache::lonxml::clear_problem_counter();
1.552     raeburn  7645: 	&Apache::lonnet::delenv('scantron.');
1.82      albertel 7646:     }
1.140     albertel 7647:     &Apache::lonhtmlcommon::Close_PrgWin($r,\%prog_state);
1.520     www      7648:     &Apache::lonnet::remove_lock($lock);
1.172     albertel 7649: #    my $lasttime = &Time::HiRes::time()-$start;
                   7650: #    $r->print("<p>took $lasttime</p>");
1.140     albertel 7651: 
1.200     albertel 7652:     $r->print("</form>");
1.324     albertel 7653:     $r->print(&show_grading_menu_form($symb));
1.157     albertel 7654:     return '';
1.75      albertel 7655: }
1.157     albertel 7656: 
1.557     raeburn  7657: sub graders_resources_pass {
                   7658:     my ($resources,$grader_partids_by_symb,$grader_randomlists_by_symb) = @_;
                   7659:     if ((ref($resources) eq 'ARRAY') && (ref($grader_partids_by_symb)) && 
                   7660:         (ref($grader_randomlists_by_symb) eq 'HASH')) {
                   7661:         foreach my $resource (@{$resources}) {
                   7662:             my $ressymb = $resource->symb();
                   7663:             my ($analysis,$parts) =
                   7664:                 &scantron_partids_tograde($resource,$env{'request.course.id'},
                   7665:                                           $env{'user.name'},$env{'user.domain'},1);
                   7666:             $grader_partids_by_symb->{$ressymb} = $parts;
                   7667:             if (ref($analysis) eq 'HASH') {
                   7668:                 if (ref($analysis->{'parts_withrandomlist'}) eq 'ARRAY') {
                   7669:                     $grader_randomlists_by_symb->{$ressymb} =
                   7670:                         $analysis->{'parts_withrandomlist'};
                   7671:                 }
                   7672:             }
                   7673:         }
                   7674:     }
                   7675:     return;
                   7676: }
                   7677: 
1.542     raeburn  7678: sub grade_student_bubbles {
1.554     raeburn  7679:     my ($r,$uname,$udom,$scan_record,$scancode,$resources,$parts) = @_;
                   7680:     if (ref($resources) eq 'ARRAY') {
                   7681:         my $count = 0;
                   7682:         foreach my $resource (@{$resources}) {
                   7683:             my $ressymb = $resource->symb();
                   7684:             my %form = ('submitted'      => 'scantron',
                   7685:                         'grade_target'   => 'grade',
                   7686:                         'grade_username' => $uname,
                   7687:                         'grade_domain'   => $udom,
                   7688:                         'grade_courseid' => $env{'request.course.id'},
                   7689:                         'grade_symb'     => $ressymb,
                   7690:                         'CODE'           => $scancode
                   7691:                        );
                   7692:             if (ref($parts) eq 'HASH') {
                   7693:                 if (ref($parts->{$ressymb}) eq 'ARRAY') {
                   7694:                     foreach my $part (@{$parts->{$ressymb}}) {
                   7695:                         $form{'scantron_questnum_start.'.$part} =
                   7696:                             1+$env{'form.scantron.first_bubble_line.'.$count};
                   7697:                         $count++;
                   7698:                     }
                   7699:                 }
                   7700:             }
                   7701:             my $result=&ssi_with_retries($resource->src(),$ssi_retries,%form);
                   7702:             return 'ssi_error' if ($ssi_error);
                   7703:             last if (&Apache::loncommon::connection_aborted($r));
                   7704:         }
1.542     raeburn  7705:     }
                   7706:     return;
                   7707: }
                   7708: 
1.157     albertel 7709: sub scantron_upload_scantron_data {
                   7710:     my ($r)=@_;
1.565     raeburn  7711:     my $dom = $env{'request.role.domain'};
                   7712:     my $domdesc = &Apache::lonnet::domain($dom,'description');
                   7713:     $r->print(&Apache::loncommon::coursebrowser_javascript($dom));
1.157     albertel 7714:     my $select_link=&Apache::loncommon::selectcourse_link('rules','courseid',
1.181     albertel 7715: 							  'domainid',
1.565     raeburn  7716: 							  'coursename',$dom);
                   7717:     my $syllabuslink = '<a href="javascript:ToSyllabus();">'.&mt('Syllabus').'</a>'.
                   7718:                        ('&nbsp'x2).&mt('(shows course personnel)'); 
1.324     albertel 7719:     my $default_form_data=&defaultFormData(&get_symb($r,1));
1.579     raeburn  7720:     my $nofile_alert = &mt('Please use the browse button to select a file from your local directory.');
                   7721:     my $nocourseid_alert = &mt("Please use the 'Select Course' link to open a separate window where you can search for a course to which a file can be uploaded.");
1.492     albertel 7722:     $r->print('
1.157     albertel 7723: <script type="text/javascript" language="javascript">
                   7724:     function checkUpload(formname) {
                   7725: 	if (formname.upfile.value == "") {
1.579     raeburn  7726: 	    alert("'.$nofile_alert.'");
1.157     albertel 7727: 	    return false;
                   7728: 	}
1.565     raeburn  7729:         if (formname.courseid.value == "") {
1.579     raeburn  7730:             alert("'.$nocourseid_alert.'");
1.565     raeburn  7731:             return false;
                   7732:         }
1.157     albertel 7733: 	formname.submit();
                   7734:     }
1.565     raeburn  7735: 
                   7736:     function ToSyllabus() {
                   7737:         var cdom = '."'$dom'".';
                   7738:         var cnum = document.rules.courseid.value;
                   7739:         if (cdom == "" || cdom == null) {
                   7740:             return;
                   7741:         }
                   7742:         if (cnum == "" || cnum == null) {
                   7743:            return;
                   7744:         }
                   7745:         syllwin=window.open("/public/"+cdom+"/"+cnum+"/syllabus","LONCAPASyllabus",
                   7746:                             "height=350,width=350,scrollbars=yes,menubar=no");
                   7747:         return;
                   7748:     }
                   7749: 
1.157     albertel 7750: </script>
                   7751: 
1.566     raeburn  7752: <h3>'.&mt('Send scanned bubblesheet data to a course').'</h3>
                   7753: 
1.492     albertel 7754: <form enctype="multipart/form-data" action="/adm/grades" name="rules" method="post">
1.565     raeburn  7755: '.$default_form_data.
                   7756:   &Apache::lonhtmlcommon::start_pick_box().
                   7757:   &Apache::lonhtmlcommon::row_title(&mt('Course ID')).
                   7758:   '<input name="courseid" type="text" size="30" />'.$select_link.
                   7759:   &Apache::lonhtmlcommon::row_closure().
                   7760:   &Apache::lonhtmlcommon::row_title(&mt('Course Name')).
                   7761:   '<input name="coursename" type="text" size="30" />'.$syllabuslink.
                   7762:   &Apache::lonhtmlcommon::row_closure().
                   7763:   &Apache::lonhtmlcommon::row_title(&mt('Domain')).
                   7764:   '<input name="domainid" type="hidden" />'.$domdesc.
                   7765:   &Apache::lonhtmlcommon::row_closure().
                   7766:   &Apache::lonhtmlcommon::row_title(&mt('File to upload')).
                   7767:   '<input type="file" name="upfile" size="50" />'.
                   7768:   &Apache::lonhtmlcommon::row_closure(1).
                   7769:   &Apache::lonhtmlcommon::end_pick_box().'<br />
                   7770: 
1.492     albertel 7771: <input name="command" value="scantronupload_save" type="hidden" />
1.575     www      7772: <input type="button" onClick="javascript:checkUpload(this.form);" value="'.&mt('Upload Bubblesheet Data').'" />
1.157     albertel 7773: </form>
1.492     albertel 7774: ');
1.157     albertel 7775:     return '';
                   7776: }
                   7777: 
1.423     albertel 7778: 
1.157     albertel 7779: sub scantron_upload_scantron_data_save {
                   7780:     my($r)=@_;
1.324     albertel 7781:     my ($symb)=&get_symb($r,1);
1.182     albertel 7782:     my $doanotherupload=
                   7783: 	'<br /><form action="/adm/grades" method="post">'."\n".
                   7784: 	'<input type="hidden" name="command" value="scantronupload" />'."\n".
1.492     albertel 7785: 	'<input type="submit" name="submit" value="'.&mt('Do Another Upload').'" />'."\n".
1.182     albertel 7786: 	'</form>'."\n";
1.257     albertel 7787:     if (!&Apache::lonnet::allowed('usc',$env{'form.domainid'}) &&
1.162     albertel 7788: 	!&Apache::lonnet::allowed('usc',
1.257     albertel 7789: 			    $env{'form.domainid'}.'_'.$env{'form.courseid'})) {
1.575     www      7790: 	$r->print(&mt("You are not allowed to upload bubblesheet data to the requested course.")."<br />");
1.182     albertel 7791: 	if ($symb) {
1.324     albertel 7792: 	    $r->print(&show_grading_menu_form($symb));
1.182     albertel 7793: 	} else {
                   7794: 	    $r->print($doanotherupload);
                   7795: 	}
1.162     albertel 7796: 	return '';
                   7797:     }
1.257     albertel 7798:     my %coursedata=&Apache::lonnet::coursedescription($env{'form.domainid'}.'_'.$env{'form.courseid'});
1.568     raeburn  7799:     my $uploadedfile;
1.567     raeburn  7800:     $r->print('<h3>'.&mt("Uploading file to [_1]",$coursedata{'description'}).'</h3>');
1.257     albertel 7801:     if (length($env{'form.upfile'}) < 2) {
1.568     raeburn  7802:         $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 7803:     } else {
1.568     raeburn  7804:         my $result = 
                   7805:             &Apache::lonnet::userfileupload('upfile','','scantron','','','',
                   7806:                                             $env{'form.courseid'},$env{'form.domainid'});
                   7807: 	if ($result =~ m{^/uploaded/}) {
1.567     raeburn  7808: 	    $r->print(&mt('[_1]Success:[_2] Successfully uploaded [_3] bytes of data into location: [_4]',
                   7809:                           '<span class="LC_success">','</span>',(length($env{'form.upfile'})-1),
                   7810: 			  '<span class="LC_filename">'.$result.'</span>'));
1.568     raeburn  7811:             ($uploadedfile) = ($result =~ m{/([^/]+)$});
1.567     raeburn  7812:             $r->print(&validate_uploaded_scantron_file($env{'form.domainid'},
1.568     raeburn  7813:                                                        $env{'form.courseid'},$uploadedfile));
1.210     albertel 7814: 	} else {
1.567     raeburn  7815: 	    $r->print(&mt('[_1]Error:[_2] An error ([_3]) occurred when attempting to upload the file, [_4]',
                   7816:                           '<span class="LC_error">','</span>',$result,
1.568     raeburn  7817: 			  '<span class="LC_filename">'.&HTML::Entities::encode($env{'form.upfile.filename'},'<>&"').'</span>'));
1.183     albertel 7818: 	}
                   7819:     }
1.174     albertel 7820:     if ($symb) {
1.209     ng       7821: 	$r->print(&scantron_selectphase($r,$uploadedfile));
1.174     albertel 7822:     } else {
1.182     albertel 7823: 	$r->print($doanotherupload);
1.174     albertel 7824:     }
1.157     albertel 7825:     return '';
                   7826: }
                   7827: 
1.567     raeburn  7828: sub validate_uploaded_scantron_file {
                   7829:     my ($cdom,$cname,$fname) = @_;
                   7830:     my $scanlines=&Apache::lonnet::getfile('/uploaded/'.$cdom.'/'.$cname.'/'.$fname);
                   7831:     my @lines;
                   7832:     if ($scanlines ne '-1') {
                   7833:         @lines=split("\n",$scanlines,-1);
                   7834:     }
                   7835:     my $output;
                   7836:     if (@lines) {
                   7837:         my (%counts,$max_match_format);
                   7838:         my ($max_match_count,$max_match_pct) = (0,0);
                   7839:         my $classlist = &Apache::loncoursedata::get_classlist($cdom,$cname);
                   7840:         my %idmap = &username_to_idmap($classlist);
                   7841:         foreach my $key (keys(%idmap)) {
                   7842:             my $lckey = lc($key);
                   7843:             $idmap{$lckey} = $idmap{$key};
                   7844:         }
                   7845:         my %unique_formats;
                   7846:         my @formatlines = &get_scantronformat_file();
                   7847:         foreach my $line (@formatlines) {
                   7848:             chomp($line);
                   7849:             my @config = split(/:/,$line);
                   7850:             my $idstart = $config[5];
                   7851:             my $idlength = $config[6];
                   7852:             if (($idstart ne '') && ($idlength > 0)) {
                   7853:                 if (ref($unique_formats{$idstart.':'.$idlength}) eq 'ARRAY') {
                   7854:                     push(@{$unique_formats{$idstart.':'.$idlength}},$config[0].':'.$config[1]); 
                   7855:                 } else {
                   7856:                     $unique_formats{$idstart.':'.$idlength} = [$config[0].':'.$config[1]];
                   7857:                 }
                   7858:             }
                   7859:         }
                   7860:         foreach my $key (keys(%unique_formats)) {
                   7861:             my ($idstart,$idlength) = split(':',$key);
                   7862:             %{$counts{$key}} = (
                   7863:                                'found'   => 0,
                   7864:                                'total'   => 0,
                   7865:                               );
                   7866:             foreach my $line (@lines) {
                   7867:                 next if ($line =~ /^#/);
                   7868:                 next if ($line =~ /^[\s\cz]*$/);
                   7869:                 my $id = substr($line,$idstart-1,$idlength);
                   7870:                 $id = lc($id);
                   7871:                 if (exists($idmap{$id})) {
                   7872:                     $counts{$key}{'found'} ++;
                   7873:                 }
                   7874:                 $counts{$key}{'total'} ++;
                   7875:             }
                   7876:             if ($counts{$key}{'total'}) {
                   7877:                 my $percent_match = (100*$counts{$key}{'found'})/($counts{$key}{'total'});
                   7878:                 if (($max_match_format eq '') || ($percent_match > $max_match_pct)) {
                   7879:                     $max_match_pct = $percent_match;
                   7880:                     $max_match_format = $key;
                   7881:                     $max_match_count = $counts{$key}{'total'};
                   7882:                 }
                   7883:             }
                   7884:         }
                   7885:         if (ref($unique_formats{$max_match_format}) eq 'ARRAY') {
                   7886:             my $format_descs;
                   7887:             my $numwithformat = @{$unique_formats{$max_match_format}};
                   7888:             for (my $i=0; $i<$numwithformat; $i++) {
                   7889:                 my ($name,$desc) = split(':',$unique_formats{$max_match_format}[$i]);
                   7890:                 if ($i<$numwithformat-2) {
                   7891:                     $format_descs .= '"<i>'.$desc.'</i>", ';
                   7892:                 } elsif ($i==$numwithformat-2) {
                   7893:                     $format_descs .= '"<i>'.$desc.'</i>" '.&mt('and').' ';
                   7894:                 } elsif ($i==$numwithformat-1) {
                   7895:                     $format_descs .= '"<i>'.$desc.'</i>"';
                   7896:                 }
                   7897:             }
                   7898:             my $showpct = sprintf("%.0f",$max_match_pct).'%';
                   7899:             $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).
                   7900:                        '<br />'.&mt('A low percentage of matches results from one of the following:').'<ul>'.
                   7901:                        '<li>'.&mt('The file was uploaded to the wrong course').'</li>'.
                   7902:                        '<li>'.&mt('The data are not in the format expected for the domain: [_1]',
                   7903:                                   '<i>'.$cdom.'</i>').'</li>'.
                   7904:                        '<li>'.&mt('Students did not bubble their IDs, or mis-bubbled them').'</li>'.
                   7905:                        '<li>'.&mt('The course roster is not up to date').'</li>'.
                   7906:                        '</ul>';
                   7907:         }
                   7908:     } else {
                   7909:         $output = '<span class="LC_warning">'.&mt('Uploaded file contained no data').'</span>';
                   7910:     }
                   7911:     return $output;
                   7912: }
                   7913: 
1.202     albertel 7914: sub valid_file {
                   7915:     my ($requested_file)=@_;
                   7916:     foreach my $filename (sort(&scantron_filenames())) {
                   7917: 	if ($requested_file eq $filename) { return 1; }
                   7918:     }
                   7919:     return 0;
                   7920: }
                   7921: 
                   7922: sub scantron_download_scantron_data {
                   7923:     my ($r)=@_;
1.324     albertel 7924:     my $default_form_data=&defaultFormData(&get_symb($r,1));
1.257     albertel 7925:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   7926:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
                   7927:     my $file=$env{'form.scantron_selectfile'};
1.202     albertel 7928:     if (! &valid_file($file)) {
1.492     albertel 7929: 	$r->print('
1.202     albertel 7930: 	<p>
1.492     albertel 7931: 	    '.&mt('The requested file name was invalid.').'
1.202     albertel 7932:         </p>
1.492     albertel 7933: ');
1.324     albertel 7934: 	$r->print(&show_grading_menu_form(&get_symb($r,1)));
1.202     albertel 7935: 	return;
                   7936:     }
                   7937:     my $orig='/uploaded/'.$cdom.'/'.$cname.'/scantron_orig_'.$file;
                   7938:     my $corrected='/uploaded/'.$cdom.'/'.$cname.'/scantron_corrected_'.$file;
                   7939:     my $skipped='/uploaded/'.$cdom.'/'.$cname.'/scantron_skipped_'.$file;
                   7940:     &Apache::lonnet::allowuploaded('/adm/grades',$orig);
                   7941:     &Apache::lonnet::allowuploaded('/adm/grades',$corrected);
                   7942:     &Apache::lonnet::allowuploaded('/adm/grades',$skipped);
1.492     albertel 7943:     $r->print('
1.202     albertel 7944:     <p>
1.492     albertel 7945: 	'.&mt('[_1]Original[_2] file as uploaded by the scantron office.',
                   7946: 	      '<a href="'.$orig.'">','</a>').'
1.202     albertel 7947:     </p>
                   7948:     <p>
1.492     albertel 7949: 	'.&mt('[_1]Corrections[_2], a file of corrected records that were used in grading.',
                   7950: 	      '<a href="'.$corrected.'">','</a>').'
1.202     albertel 7951:     </p>
                   7952:     <p>
1.492     albertel 7953: 	'.&mt('[_1]Skipped[_2], a file of records that were skipped.',
                   7954: 	      '<a href="'.$skipped.'">','</a>').'
1.202     albertel 7955:     </p>
1.492     albertel 7956: ');
1.324     albertel 7957:     $r->print(&show_grading_menu_form(&get_symb($r,1)));
1.202     albertel 7958:     return '';
                   7959: }
1.157     albertel 7960: 
1.523     raeburn  7961: sub checkscantron_results {
                   7962:     my ($r) = @_;
                   7963:     my ($symb)=&get_symb($r);
                   7964:     if (!$symb) {return '';}
                   7965:     my $grading_menu_button=&show_grading_menu_form($symb);
                   7966:     my $cid = $env{'request.course.id'};
1.542     raeburn  7967:     my %lettdig = &letter_to_digits();
1.523     raeburn  7968:     my $numletts = scalar(keys(%lettdig));
                   7969:     my $cnum = $env{'course.'.$cid.'.num'};
                   7970:     my $cdom = $env{'course.'.$cid.'.domain'};
                   7971:     my (undef, undef, $sequence) = &Apache::lonnet::decode_symb($env{'form.selectpage'});
                   7972:     my %record;
                   7973:     my %scantron_config =
                   7974:         &Apache::grades::get_scantron_config($env{'form.scantron_format'});
                   7975:     my ($scanlines,$scan_data)=&Apache::grades::scantron_getfile();
                   7976:     my $classlist=&Apache::loncoursedata::get_classlist();
                   7977:     my %idmap=&Apache::grades::username_to_idmap($classlist);
                   7978:     my $navmap=Apache::lonnavmaps::navmap->new();
                   7979:     my $map=$navmap->getResourceByUrl($sequence);
1.557     raeburn  7980:     my @resources=$navmap->retrieveResources($map,\&scantron_filter,1,0);
                   7981:     my (%grader_partids_by_symb,%grader_randomlists_by_symb);
                   7982:     &graders_resources_pass(\@resources,\%grader_partids_by_symb,                             \%grader_randomlists_by_symb);
                   7983: 
1.554     raeburn  7984:     my ($uname,$udom);
1.523     raeburn  7985:     my (%scandata,%lastname,%bylast);
                   7986:     $r->print('
                   7987: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="checkscantron">'."\n");
                   7988: 
                   7989:     my @delayqueue;
                   7990:     my %completedstudents;
                   7991: 
                   7992:     my $count=&Apache::grades::get_todo_count($scanlines,$scan_data);
1.581   ! www      7993:     my %prog_state=&Apache::lonhtmlcommon::Create_PrgWin($r,'Bubblesheet/Submissions Comparison Status',
        !          7994:                                     'Progress of Bubblesheet Data/Submission Records Comparison',$count,
1.523     raeburn  7995:                                     'inline',undef,'checkscantron');
1.546     raeburn  7996:     my ($username,$domain,$started);
1.523     raeburn  7997: 
1.557     raeburn  7998:     &scantron_get_maxbubble();  # Need the bubble lines array to parse.
1.523     raeburn  7999: 
                   8000:     &Apache::lonhtmlcommon::Update_PrgWin($r,\%prog_state,
                   8001:                                           'Processing first student');
                   8002:     my $start=&Time::HiRes::time();
                   8003:     my $i=-1;
                   8004: 
                   8005:     while ($i<$scanlines->{'count'}) {
                   8006:         ($username,$domain,$uname)=('','','');
                   8007:         $i++;
                   8008:         my $line=&Apache::grades::scantron_get_line($scanlines,$scan_data,$i);
                   8009:         if ($line=~/^[\s\cz]*$/) { next; }
                   8010:         if ($started) {
                   8011:             &Apache::lonhtmlcommon::Increment_PrgWin($r,\%prog_state,
                   8012:                                                      'last student');
                   8013:         }
                   8014:         $started=1;
                   8015:         my $scan_record=
                   8016:             &Apache::grades::scantron_parse_scanline($line,$i,\%scantron_config,
                   8017:                                                      $scan_data);
                   8018:         unless ($uname=&Apache::grades::scantron_find_student($scan_record,$scan_data,
                   8019:                                                               \%idmap,$i)) {
                   8020:             &Apache::grades::scantron_add_delay(\@delayqueue,$line,
                   8021:                                 'Unable to find a student that matches',1);
                   8022:             next;
                   8023:         }
                   8024:         if (exists $completedstudents{$uname}) {
                   8025:             &Apache::grades::scantron_add_delay(\@delayqueue,$line,
                   8026:                                 'Student '.$uname.' has multiple sheets',2);
                   8027:             next;
                   8028:         }
                   8029:         my $pid = $scan_record->{'scantron.ID'};
                   8030:         $lastname{$pid} = $scan_record->{'scantron.LastName'};
                   8031:         push(@{$bylast{$lastname{$pid}}},$pid);
                   8032:         my $lastpos = $env{'form.scantron_maxbubble'}*$scantron_config{'Qlength'};
                   8033:         $scandata{$pid} = substr($line,$scantron_config{'Qstart'}-1,$lastpos);
                   8034:         chomp($scandata{$pid});
                   8035:         $scandata{$pid} =~ s/\r$//;
                   8036:         ($username,$domain)=split(/:/,$uname);
                   8037:         my $counter = -1;
                   8038:         foreach my $resource (@resources) {
1.557     raeburn  8039:             my $parts;
1.554     raeburn  8040:             my $ressymb = $resource->symb();
1.557     raeburn  8041:             if ((exists($grader_randomlists_by_symb{$ressymb})) ||
                   8042:                 (ref($grader_partids_by_symb{$ressymb}) ne 'ARRAY')) {
                   8043:                 (my $analysis,$parts) =
                   8044:                     &scantron_partids_tograde($resource,$env{'request.course.id'},$username,$domain);
                   8045:             } else {
                   8046:                 $parts = $grader_partids_by_symb{$ressymb};
                   8047:             }
1.542     raeburn  8048:             ($counter,my $recording) =
                   8049:                 &verify_scantron_grading($resource,$domain,$username,$cid,$counter,
1.554     raeburn  8050:                                          $scandata{$pid},$parts,
1.542     raeburn  8051:                                          \%scantron_config,\%lettdig,$numletts);
                   8052:             $record{$pid} .= $recording;
1.523     raeburn  8053:         }
                   8054:     }
                   8055:     &Apache::lonhtmlcommon::Close_PrgWin($r,\%prog_state);
                   8056:     $r->print('<br />');
                   8057:     my ($okstudents,$badstudents,$numstudents,$passed,$failed);
                   8058:     $passed = 0;
                   8059:     $failed = 0;
                   8060:     $numstudents = 0;
                   8061:     foreach my $last (sort(keys(%bylast))) {
                   8062:         if (ref($bylast{$last}) eq 'ARRAY') {
                   8063:             foreach my $pid (sort(@{$bylast{$last}})) {
                   8064:                 my $showscandata = $scandata{$pid};
                   8065:                 my $showrecord = $record{$pid};
                   8066:                 $showscandata =~ s/\s/&nbsp;/g;
                   8067:                 $showrecord =~ s/\s/&nbsp;/g;
                   8068:                 if ($scandata{$pid} eq $record{$pid}) {
                   8069:                     my $css_class = ($passed % 2)?'LC_odd_row':'LC_even_row';
                   8070:                     $okstudents .= '<tr class="'.$css_class.'">'.
1.581   ! www      8071: '<td>'.&mt('Bubblesheet').'</td><td>'.$showscandata.'</td><td rowspan="2">'.$last.'</td><td rowspan="2">'.$pid.'</td>'."\n".
1.523     raeburn  8072: '</tr>'."\n".
                   8073: '<tr class="'.$css_class.'">'."\n".
                   8074: '<td>Submissions</td><td>'.$showrecord.'</td></tr>'."\n";
                   8075:                     $passed ++;
                   8076:                 } else {
                   8077:                     my $css_class = ($failed % 2)?'LC_odd_row':'LC_even_row';
1.581   ! www      8078:                     $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  8079: '</tr>'."\n".
                   8080: '<tr class="'.$css_class.'">'."\n".
                   8081: '<td>Submissions</td><td><span class="LC_nobreak">'.$record{$pid}.'</span></td>'."\n".
                   8082: '</tr>'."\n";
                   8083:                     $failed ++;
                   8084:                 }
                   8085:                 $numstudents ++;
                   8086:             }
                   8087:         }
                   8088:     }
1.572     www      8089:     $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  8090:     $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>');
                   8091:     if ($passed) {
1.572     www      8092:         $r->print(&mt('Students with exact correspondence between bubblesheet data and submissions are as follows:').'<br /><br />');
1.523     raeburn  8093:         $r->print(&Apache::loncommon::start_data_table()."\n".
                   8094:                  &Apache::loncommon::start_data_table_header_row()."\n".
                   8095:                  '<th>'.&mt('Source').'</th><th>'.&mt('Bubble records').'</th><th>'.&mt('Name').'</th><th>'.&mt('ID').'</th>'.
                   8096:                  &Apache::loncommon::end_data_table_header_row()."\n".
                   8097:                  $okstudents."\n".
                   8098:                  &Apache::loncommon::end_data_table().'<br />');
                   8099:     }
                   8100:     if ($failed) {
1.572     www      8101:         $r->print(&mt('Students with differences between bubblesheet data and submissions are as follows:').'<br /><br />');
1.523     raeburn  8102:         $r->print(&Apache::loncommon::start_data_table()."\n".
                   8103:                  &Apache::loncommon::start_data_table_header_row()."\n".
                   8104:                  '<th>'.&mt('Source').'</th><th>'.&mt('Bubble records').'</th><th>'.&mt('Name').'</th><th>'.&mt('ID').'</th>'.
                   8105:                  &Apache::loncommon::end_data_table_header_row()."\n".
                   8106:                  $badstudents."\n".
                   8107:                  &Apache::loncommon::end_data_table()).'<br />'.
1.572     www      8108:                  &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  8109:     }
                   8110:     $r->print('</form><br />'.$grading_menu_button);
                   8111:     return;
                   8112: }
                   8113: 
1.542     raeburn  8114: sub verify_scantron_grading {
1.554     raeburn  8115:     my ($resource,$domain,$username,$cid,$counter,$scandata,$partids,
1.542     raeburn  8116:         $scantron_config,$lettdig,$numletts) = @_;
                   8117:     my ($record,%expected,%startpos);
                   8118:     return ($counter,$record) if (!ref($resource));
                   8119:     return ($counter,$record) if (!$resource->is_problem());
                   8120:     my $symb = $resource->symb();
1.554     raeburn  8121:     return ($counter,$record) if (ref($partids) ne 'ARRAY');
                   8122:     foreach my $part_id (@{$partids}) {
1.542     raeburn  8123:         $counter ++;
                   8124:         $expected{$part_id} = 0;
                   8125:         if ($env{"form.scantron.sub_bubblelines.$counter"}) {
                   8126:             my @sub_lines = split(/,/,$env{"form.scantron.sub_bubblelines.$counter"});
                   8127:             foreach my $item (@sub_lines) {
                   8128:                 $expected{$part_id} += $item;
                   8129:             }
                   8130:         } else {
                   8131:             $expected{$part_id} = $env{"form.scantron.bubblelines.$counter"};
                   8132:         }
                   8133:         $startpos{$part_id} = $env{"form.scantron.first_bubble_line.$counter"};
                   8134:     }
                   8135:     if ($symb) {
                   8136:         my %recorded;
                   8137:         my (%returnhash) = &Apache::lonnet::restore($symb,$cid,$domain,$username);
                   8138:         if ($returnhash{'version'}) {
                   8139:             my %lasthash=();
                   8140:             my $version;
                   8141:             for ($version=1;$version<=$returnhash{'version'};$version++) {
                   8142:                 foreach my $key (sort(split(/\:/,$returnhash{$version.':keys'}))) {
                   8143:                     $lasthash{$key}=$returnhash{$version.':'.$key};
                   8144:                 }
                   8145:             }
                   8146:             foreach my $key (keys(%lasthash)) {
                   8147:                 if ($key =~ /\.scantron$/) {
                   8148:                     my $value = &unescape($lasthash{$key});
                   8149:                     my ($part_id) = ($key =~ /^resource\.(.+)\.scantron$/);
                   8150:                     if ($value eq '') {
                   8151:                         for (my $i=0; $i<$expected{$part_id}; $i++) {
                   8152:                             for (my $j=0; $j<$scantron_config->{'length'}; $j++) {
                   8153:                                 $recorded{$part_id} .= $scantron_config->{'Qoff'};
                   8154:                             }
                   8155:                         }
                   8156:                     } else {
                   8157:                         my @tocheck;
                   8158:                         my @items = split(//,$value);
                   8159:                         if (($scantron_config->{'Qon'} eq 'letter') ||
                   8160:                             ($scantron_config->{'Qon'} eq 'number')) {
                   8161:                             if (@items < $expected{$part_id}) {
                   8162:                                 my $fragment = substr($scandata,$startpos{$part_id},$expected{$part_id});
                   8163:                                 my @singles = split(//,$fragment);
                   8164:                                 foreach my $pos (@singles) {
                   8165:                                     if ($pos eq ' ') {
                   8166:                                         push(@tocheck,$pos);
                   8167:                                     } else {
                   8168:                                         my $next = shift(@items);
                   8169:                                         push(@tocheck,$next);
                   8170:                                     }
                   8171:                                 }
                   8172:                             } else {
                   8173:                                 @tocheck = @items;
                   8174:                             }
                   8175:                             foreach my $letter (@tocheck) {
                   8176:                                 if ($scantron_config->{'Qon'} eq 'letter') {
                   8177:                                     if ($letter !~ /^[A-J]$/) {
                   8178:                                         $letter = $scantron_config->{'Qoff'};
                   8179:                                     }
                   8180:                                     $recorded{$part_id} .= $letter;
                   8181:                                 } elsif ($scantron_config->{'Qon'} eq 'number') {
                   8182:                                     my $digit;
                   8183:                                     if ($letter !~ /^[A-J]$/) {
                   8184:                                         $digit = $scantron_config->{'Qoff'};
                   8185:                                     } else {
                   8186:                                         $digit = $lettdig->{$letter};
                   8187:                                     }
                   8188:                                     $recorded{$part_id} .= $digit;
                   8189:                                 }
                   8190:                             }
                   8191:                         } else {
                   8192:                             @tocheck = @items;
                   8193:                             for (my $i=0; $i<$expected{$part_id}; $i++) {
                   8194:                                 my $curr_sub = shift(@tocheck);
                   8195:                                 my $digit;
                   8196:                                 if ($curr_sub =~ /^[A-J]$/) {
                   8197:                                     $digit = $lettdig->{$curr_sub}-1;
                   8198:                                 }
                   8199:                                 if ($curr_sub eq 'J') {
                   8200:                                     $digit += scalar($numletts);
                   8201:                                 }
                   8202:                                 for (my $j=0; $j<$scantron_config->{'Qlength'}; $j++) {
                   8203:                                     if ($j == $digit) {
                   8204:                                         $recorded{$part_id} .= $scantron_config->{'Qon'};
                   8205:                                     } else {
                   8206:                                         $recorded{$part_id} .= $scantron_config->{'Qoff'};
                   8207:                                     }
                   8208:                                 }
                   8209:                             }
                   8210:                         }
                   8211:                     }
                   8212:                 }
                   8213:             }
                   8214:         }
1.554     raeburn  8215:         foreach my $part_id (@{$partids}) {
1.542     raeburn  8216:             if ($recorded{$part_id} eq '') {
                   8217:                 for (my $i=0; $i<$expected{$part_id}; $i++) {
                   8218:                     for (my $j=0; $j<$scantron_config->{'Qlength'}; $j++) {
                   8219:                         $recorded{$part_id} .= $scantron_config->{'Qoff'};
                   8220:                     }
                   8221:                 }
                   8222:             }
                   8223:             $record .= $recorded{$part_id};
                   8224:         }
                   8225:     }
                   8226:     return ($counter,$record);
                   8227: }
                   8228: 
                   8229: sub letter_to_digits { 
                   8230:     my %lettdig = (
                   8231:                     A => 1,
                   8232:                     B => 2,
                   8233:                     C => 3,
                   8234:                     D => 4,
                   8235:                     E => 5,
                   8236:                     F => 6,
                   8237:                     G => 7,
                   8238:                     H => 8,
                   8239:                     I => 9,
                   8240:                     J => 0,
                   8241:                   );
                   8242:     return %lettdig;
                   8243: }
                   8244: 
1.423     albertel 8245: 
1.75      albertel 8246: #-------- end of section for handling grading scantron forms -------
                   8247: #
                   8248: #-------------------------------------------------------------------
                   8249: 
1.72      ng       8250: #-------------------------- Menu interface -------------------------
                   8251: #
                   8252: #--- Show a Grading Menu button - Calls the next routine ---
                   8253: sub show_grading_menu_form {
1.324     albertel 8254:     my ($symb)=@_;
1.125     ng       8255:     my $result.='<br /><form action="/adm/grades" method="post">'."\n".
1.418     albertel 8256: 	'<input type="hidden" name="symb" value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
1.257     albertel 8257: 	'<input type="hidden" name="saveState"  value="'.$env{'form.saveState'}.'" />'."\n".
1.72      ng       8258: 	'<input type="hidden" name="command" value="gradingmenu" />'."\n".
1.478     albertel 8259: 	'<input type="submit" name="submit" value="'.&mt('Grading Menu').'" />'."\n".
1.72      ng       8260: 	'</form>'."\n";
                   8261:     return $result;
                   8262: }
                   8263: 
1.77      ng       8264: # -- Retrieve choices for grading form
                   8265: sub savedState {
                   8266:     my %savedState = ();
1.257     albertel 8267:     if ($env{'form.saveState'}) {
                   8268: 	foreach (split(/:/,$env{'form.saveState'})) {
1.77      ng       8269: 	    my ($key,$value) = split(/=/,$_,2);
                   8270: 	    $savedState{$key} = $value;
                   8271: 	}
                   8272:     }
                   8273:     return \%savedState;
                   8274: }
1.76      ng       8275: 
1.443     banghart 8276: sub grading_menu {
                   8277:     my ($request) = @_;
                   8278:     my ($symb)=&get_symb($request);
                   8279:     if (!$symb) {return '';}
                   8280:     my $probTitle = &Apache::lonnet::gettitle($symb);
                   8281:     my ($table,undef,$hdgrade) = &showResourceInfo($symb,$probTitle);
                   8282: 
1.444     banghart 8283:     $request->print($table);
1.443     banghart 8284:     my %fields = ('symb'=>&Apache::lonenc::check_encrypt($symb),
                   8285:                   'handgrade'=>$hdgrade,
                   8286:                   'probTitle'=>$probTitle,
                   8287:                   'command'=>'submit_options',
                   8288:                   'saveState'=>"",
                   8289:                   'gradingMenu'=>1,
                   8290:                   'showgrading'=>"yes");
1.538     schulted 8291:     
                   8292:     my $url1 = &Apache::lonhtmlcommon::build_url('grades/',\%fields);
                   8293:     
1.443     banghart 8294:     $fields{'command'} = 'csvform';
1.538     schulted 8295:     my $url2 = &Apache::lonhtmlcommon::build_url('grades/',\%fields);
                   8296:     
1.443     banghart 8297:     $fields{'command'} = 'processclicker';
1.538     schulted 8298:     my $url3 = &Apache::lonhtmlcommon::build_url('grades/',\%fields);
                   8299:     
1.443     banghart 8300:     $fields{'command'} = 'scantron_selectphase';
1.538     schulted 8301:     my $url4 = &Apache::lonhtmlcommon::build_url('grades/',\%fields);
                   8302:     
                   8303:     my @menu = ({	categorytitle=>'Course Grading',
                   8304:             items =>[
                   8305:                         {	linktext => 'Manual Grading/View Submissions',
                   8306:                     		url => $url1,
                   8307:                     		permission => 'F',
                   8308:                     		icon => 'edit-find-replace.png',
                   8309:                     		linktitle => 'Start the process of hand grading submissions.'
                   8310:                         },
                   8311:                 	    {	linktext => 'Upload Scores',
                   8312:                     		url => $url2,
                   8313:                     		permission => 'F',
                   8314:                     		icon => 'uploadscores.png',
                   8315:                     		linktitle => 'Specify a file containing the class scores for current resource.'
                   8316:                 	    },
                   8317:                 	    {	linktext => 'Process Clicker',
                   8318:                     		url => $url3,
                   8319:                     		permission => 'F',
                   8320:                     		icon => 'addClickerInfoFile.png',
                   8321:                     		linktitle => 'Specify a file containing the clicker information for this resource.'
                   8322:                 	    },
1.581   ! www      8323:                 	    {	linktext => 'Grade/Manage/Review Bubblesheet Forms',
1.538     schulted 8324:                     		url => $url4,
                   8325:                     		permission => 'F',
                   8326:                     		icon => 'stat.png',
                   8327:                     		linktitle => 'Grade scantron exams, upload/download scantron data files, and review previously graded scantron exams.'
                   8328:                 	    }
                   8329:                     ]
                   8330:             });
                   8331: 
                   8332:     #$fields{'command'} = 'verify';
                   8333:     #$url = &Apache::lonhtmlcommon::build_url('grades/',\%fields);
1.443     banghart 8334:     #
                   8335:     # Create the menu
                   8336:     my $Str;
1.444     banghart 8337:     # $Str .= '<h2>'.&mt('Please select a grading task').'</h2>';
1.445     banghart 8338:     $Str .= '<form method="post" action="" name="gradingMenu">';
                   8339:     $Str .= '<input type="hidden" name="command" value="" />'.
                   8340:     	'<input type="hidden" name="symb"        value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
                   8341: 	'<input type="hidden" name="handgrade"   value="'.$hdgrade.'" />'."\n".
1.476     albertel 8342: 	'<input type="hidden" name="probTitle"   value="'.$probTitle.'" />'."\n".
1.445     banghart 8343: 	'<input type="hidden" name="saveState"   value="" />'."\n".
                   8344: 	'<input type="hidden" name="gradingMenu" value="1" />'."\n".
                   8345: 	'<input type="hidden" name="showgrading" value="yes" />'."\n";
                   8346: 
1.538     schulted 8347:     $Str .= Apache::lonhtmlcommon::generate_menu(@menu);
                   8348:     #$menudata->{'jscript'}
                   8349:     $Str .='<hr /><input type="button" value="'.&mt('Verify Receipt').'" '.
                   8350:         ' onClick="javascript:checkChoice(document.forms.gradingMenu,\'5\',\'verify\')" '.
                   8351:         ' /> '.
                   8352:         &Apache::lonnet::recprefix($env{'request.course.id'}).
                   8353:         '-<input type="text" name="receipt" size="4" onChange="javascript:checkReceiptNo(this.form,\'OK\')" />';
                   8354: 
1.444     banghart 8355:     $Str .="</form>\n";
1.539     riegler  8356:     my $receiptalert = &mt("Please enter a receipt number given by a student in the receipt box.");
1.443     banghart 8357:     $request->print(<<GRADINGMENUJS);
                   8358: <script type="text/javascript" language="javascript">
                   8359:     function checkChoice(formname,val,cmdx) {
                   8360: 	if (val <= 2) {
                   8361: 	    var cmd = radioSelection(formname.radioChoice);
                   8362: 	    var cmdsave = cmd;
                   8363: 	} else {
                   8364: 	    cmd = cmdx;
                   8365: 	    cmdsave = 'submission';
                   8366: 	}
                   8367: 	formname.command.value = cmd;
                   8368: 	if (val < 5) formname.submit();
                   8369: 	if (val == 5) {
1.458     banghart 8370: 	    if (!checkReceiptNo(formname,'notOK')) { 
                   8371: 	        return false;
                   8372: 	    } else {
                   8373: 	        formname.submit();
                   8374: 	    }
1.445     banghart 8375: 	}
                   8376:     }
1.443     banghart 8377: 
                   8378:     function checkReceiptNo(formname,nospace) {
                   8379: 	var receiptNo = formname.receipt.value;
                   8380: 	var checkOpt = false;
                   8381: 	if (nospace == "OK" && isNaN(receiptNo)) {checkOpt = true;}
                   8382: 	if (nospace == "notOK" && (isNaN(receiptNo) || receiptNo == "")) {checkOpt = true;}
                   8383: 	if (checkOpt) {
1.539     riegler  8384: 	    alert("$receiptalert");
1.443     banghart 8385: 	    formname.receipt.value = "";
                   8386: 	    formname.receipt.focus();
                   8387: 	    return false;
                   8388: 	}
                   8389: 	return true;
                   8390:     }
                   8391: </script>
                   8392: GRADINGMENUJS
                   8393:     &commonJSfunctions($request);
                   8394:     return $Str;    
                   8395: }
                   8396: 
                   8397: 
                   8398: #--- Displays the submissions first page -------
                   8399: sub submit_options {
1.72      ng       8400:     my ($request) = @_;
1.324     albertel 8401:     my ($symb)=&get_symb($request);
1.72      ng       8402:     if (!$symb) {return '';}
1.76      ng       8403:     my $probTitle = &Apache::lonnet::gettitle($symb);
1.72      ng       8404: 
1.539     riegler  8405:     my $receiptalert = &mt("Please enter a receipt number given by a student in the receipt box."); 
1.72      ng       8406:     $request->print(<<GRADINGMENUJS);
                   8407: <script type="text/javascript" language="javascript">
1.116     ng       8408:     function checkChoice(formname,val,cmdx) {
                   8409: 	if (val <= 2) {
                   8410: 	    var cmd = radioSelection(formname.radioChoice);
1.118     ng       8411: 	    var cmdsave = cmd;
1.116     ng       8412: 	} else {
                   8413: 	    cmd = cmdx;
1.118     ng       8414: 	    cmdsave = 'submission';
1.116     ng       8415: 	}
                   8416: 	formname.command.value = cmd;
1.118     ng       8417: 	formname.saveState.value = "saveCmd="+cmdsave+":saveSec="+pullDownSelection(formname.section)+
1.145     albertel 8418: 	    ":saveSub="+pullDownSelection(formname.submitonly)+":saveStatus="+pullDownSelection(formname.Status);
1.116     ng       8419: 	if (val < 5) formname.submit();
                   8420: 	if (val == 5) {
1.72      ng       8421: 	    if (!checkReceiptNo(formname,'notOK')) { return false;}
                   8422: 	    formname.submit();
                   8423: 	}
1.238     albertel 8424: 	if (val < 7) formname.submit();
1.72      ng       8425:     }
                   8426: 
                   8427:     function checkReceiptNo(formname,nospace) {
                   8428: 	var receiptNo = formname.receipt.value;
                   8429: 	var checkOpt = false;
                   8430: 	if (nospace == "OK" && isNaN(receiptNo)) {checkOpt = true;}
                   8431: 	if (nospace == "notOK" && (isNaN(receiptNo) || receiptNo == "")) {checkOpt = true;}
                   8432: 	if (checkOpt) {
1.539     riegler  8433: 	    alert("$receiptalert");
1.72      ng       8434: 	    formname.receipt.value = "";
                   8435: 	    formname.receipt.focus();
                   8436: 	    return false;
                   8437: 	}
                   8438: 	return true;
                   8439:     }
                   8440: </script>
                   8441: GRADINGMENUJS
1.118     ng       8442:     &commonJSfunctions($request);
1.324     albertel 8443:     my ($table,undef,$hdgrade) = &showResourceInfo($symb,$probTitle);
1.473     albertel 8444:     my $result;
1.76      ng       8445:     my (undef,$sections) = &getclasslist('all','0');
1.77      ng       8446:     my $savedState = &savedState();
1.118     ng       8447:     my $saveCmd = ($$savedState{'saveCmd'} eq '' ? 'submission' : $$savedState{'saveCmd'});
1.77      ng       8448:     my $saveSec = ($$savedState{'saveSec'} eq '' ? 'all' : $$savedState{'saveSec'});
1.118     ng       8449:     my $saveSub = ($$savedState{'saveSub'} eq '' ? 'all' : $$savedState{'saveSub'});
1.77      ng       8450:     my $saveStatus = ($$savedState{'saveStatus'} eq '' ? 'Active' : $$savedState{'saveStatus'});
1.72      ng       8451: 
1.533     bisitz   8452:     # Preselect sections
                   8453:     my $selsec="";
                   8454:     if (ref($sections)) {
                   8455:         foreach my $section (sort(@$sections)) {
                   8456:             $selsec.='<option value="'.$section.'" '.
                   8457:                 ($saveSec eq $section ? 'selected="selected"':'').'>'.$section.'</option>'."\n";
                   8458:         }
                   8459:     }
                   8460: 
1.72      ng       8461:     $result.='<form action="/adm/grades" method="post" name="gradingMenu">'."\n".
1.418     albertel 8462: 	'<input type="hidden" name="symb"        value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
1.72      ng       8463: 	'<input type="hidden" name="handgrade"   value="'.$hdgrade.'" />'."\n".
                   8464: 	'<input type="hidden" name="probTitle"   value="'.$probTitle.'" />'."\n".
1.116     ng       8465: 	'<input type="hidden" name="command"     value="" />'."\n".
1.77      ng       8466: 	'<input type="hidden" name="saveState"   value="" />'."\n".
1.124     ng       8467: 	'<input type="hidden" name="gradingMenu" value="1" />'."\n".
1.72      ng       8468: 	'<input type="hidden" name="showgrading" value="yes" />'."\n";
                   8469: 
1.472     albertel 8470:     $result.='
1.533     bisitz   8471: <h2>
                   8472:   '.&mt('Grade Current Resource').'
                   8473: </h2>
                   8474: <div>
                   8475:   '.$table.'
                   8476: </div>
                   8477: 
1.537     harmsja  8478: <div class="LC_columnSection">
                   8479:   
1.533     bisitz   8480:     <fieldset>
                   8481:       <legend>
                   8482:        '.&mt('Sections').'
                   8483:       </legend>
                   8484:       <select name="section" multiple="multiple" size="5">'."\n";
                   8485:     $result.= $selsec;
1.401     albertel 8486:     $result.= '<option value="all" '.($saveSec eq 'all' ? 'selected="selected"' : ''). '>all</option></select> &nbsp; ';
1.472     albertel 8487:     $result.='
1.533     bisitz   8488:     </fieldset>
1.537     harmsja  8489:   
1.533     bisitz   8490:     <fieldset>
                   8491:       <legend>
                   8492:         '.&mt('Groups').'
                   8493:       </legend>
                   8494:       '.&Apache::lonstatistics::GroupSelect('group','multiple',5).'
                   8495:     </fieldset>
1.537     harmsja  8496:   
1.533     bisitz   8497:     <fieldset>
                   8498:       <legend>
                   8499:         '.&mt('Access Status').'
                   8500:       </legend>
                   8501:       '.&Apache::lonhtmlcommon::StatusOptions($saveStatus,undef,5,undef,'mult').'
                   8502:     </fieldset>
1.537     harmsja  8503:   
1.533     bisitz   8504:     <fieldset>
                   8505:       <legend>
                   8506:         '.&mt('Submission Status').'
                   8507:       </legend>
                   8508:       <select name="submitonly" size="5">
1.473     albertel 8509: 	         <option value="yes" '.      ($saveSub eq 'yes'       ? 'selected="selected"' : '').'>'.&mt('with submissions').'</option>
                   8510: 	         <option value="queued" '.   ($saveSub eq 'queued'    ? 'selected="selected"' : '').'>'.&mt('in grading queue').'</option>
                   8511: 	         <option value="graded" '.   ($saveSub eq 'graded'    ? 'selected="selected"' : '').'>'.&mt('with ungraded submissions').'</option>
                   8512: 	         <option value="incorrect" '.($saveSub eq 'incorrect' ? 'selected="selected"' : '').'>'.&mt('with incorrect submissions').'</option>
                   8513:                  <option value="all" '.      ($saveSub eq 'all'       ? 'selected="selected"' : '').'>'.&mt('with any status').'</option>
1.533     bisitz   8514:       </select>
                   8515:     </fieldset>
1.537     harmsja  8516:   
1.533     bisitz   8517: </div>
                   8518: 
                   8519: <br />
                   8520:           <div>
                   8521:             <div>
1.473     albertel 8522:               <label>
                   8523:                 <input type="radio" name="radioChoice" value="submission" '.
                   8524:                   ($saveCmd eq 'submission' ? 'checked="checked"' : '').' /> '.
                   8525:              &mt('Select individual students to grade and view submissions.').'
                   8526: 	      </label> 
                   8527:             </div>
1.533     bisitz   8528:             <div>
1.473     albertel 8529: 	      <label>
                   8530:                 <input type="radio" name="radioChoice" value="viewgrades" '.
                   8531:                   ($saveCmd eq 'viewgrades' ? 'checked="checked"' : '').' /> '.
                   8532:                     &mt('Grade all selected students in a grading table.').'
                   8533:               </label>
                   8534:             </div>
1.533     bisitz   8535:             <div>
1.539     riegler  8536: 	      <input type="button" onClick="javascript:checkChoice(this.form,\'2\');" value="'.&mt('Next').' &rarr;" />
1.473     albertel 8537:             </div>
1.472     albertel 8538:           </div>
1.533     bisitz   8539: 
                   8540: 
1.473     albertel 8541:         <h2>
                   8542:          '.&mt('Grade Complete Folder for One Student').'
                   8543:         </h2>
1.533     bisitz   8544:         <div>
                   8545:             <div>
1.473     albertel 8546:               <label>
                   8547:                 <input type="radio" name="radioChoice" value="pickStudentPage" '.
                   8548: 	  ($saveCmd eq 'pickStudentPage' ? 'checked="checked"' : '').' /> '.
                   8549:   &mt('The <b>complete</b> page/sequence/folder: For one student').'
                   8550:               </label>
                   8551:             </div>
1.533     bisitz   8552:             <div>
1.539     riegler  8553: 	      <input type="button" onClick="javascript:checkChoice(this.form,\'2\');" value="'.&mt('Next').' &rarr;" />
1.473     albertel 8554:             </div>
1.472     albertel 8555:         </div>
                   8556:   </form>';
1.499     albertel 8557:     $result .= &show_grading_menu_form($symb);
1.44      ng       8558:     return $result;
1.2       albertel 8559: }
                   8560: 
1.285     albertel 8561: sub reset_perm {
                   8562:     undef(%perm);
                   8563: }
                   8564: 
                   8565: sub init_perm {
                   8566:     &reset_perm();
1.300     albertel 8567:     foreach my $test_perm ('vgr','mgr','opa') {
                   8568: 
                   8569: 	my $scope = $env{'request.course.id'};
                   8570: 	if (!($perm{$test_perm}=&Apache::lonnet::allowed($test_perm,$scope))) {
                   8571: 
                   8572: 	    $scope .= '/'.$env{'request.course.sec'};
                   8573: 	    if ( $perm{$test_perm}=
                   8574: 		 &Apache::lonnet::allowed($test_perm,$scope)) {
                   8575: 		$perm{$test_perm.'_section'}=$env{'request.course.sec'};
                   8576: 	    } else {
                   8577: 		delete($perm{$test_perm});
                   8578: 	    }
1.285     albertel 8579: 	}
                   8580:     }
                   8581: }
                   8582: 
1.400     www      8583: sub gather_clicker_ids {
1.408     albertel 8584:     my %clicker_ids;
1.400     www      8585: 
                   8586:     my $classlist = &Apache::loncoursedata::get_classlist();
                   8587: 
                   8588:     # Set up a couple variables.
1.407     albertel 8589:     my $username_idx = &Apache::loncoursedata::CL_SNAME();
                   8590:     my $domain_idx   = &Apache::loncoursedata::CL_SDOM();
1.438     www      8591:     my $status_idx   = &Apache::loncoursedata::CL_STATUS();
1.400     www      8592: 
1.407     albertel 8593:     foreach my $student (keys(%$classlist)) {
1.438     www      8594:         if ($classlist->{$student}->[$status_idx] ne 'Active') { next; }
1.407     albertel 8595:         my $username = $classlist->{$student}->[$username_idx];
                   8596:         my $domain   = $classlist->{$student}->[$domain_idx];
1.400     www      8597:         my $clickers =
1.408     albertel 8598: 	    (&Apache::lonnet::userenvironment($domain,$username,'clickers'))[1];
1.400     www      8599:         foreach my $id (split(/\,/,$clickers)) {
1.414     www      8600:             $id=~s/^[\#0]+//;
1.421     www      8601:             $id=~s/[\-\:]//g;
1.407     albertel 8602:             if (exists($clicker_ids{$id})) {
1.408     albertel 8603: 		$clicker_ids{$id}.=','.$username.':'.$domain;
1.400     www      8604:             } else {
1.408     albertel 8605: 		$clicker_ids{$id}=$username.':'.$domain;
1.400     www      8606:             }
                   8607:         }
                   8608:     }
1.407     albertel 8609:     return %clicker_ids;
1.400     www      8610: }
                   8611: 
1.402     www      8612: sub gather_adv_clicker_ids {
1.408     albertel 8613:     my %clicker_ids;
1.402     www      8614:     my $cnum=$env{'course.'.$env{'request.course.id'}.'.num'};
                   8615:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
                   8616:     my %coursepersonnel=&Apache::lonnet::get_course_adv_roles($cdom.'/'.$cnum);
1.409     albertel 8617:     foreach my $element (sort(keys(%coursepersonnel))) {
1.402     www      8618:         foreach my $person (split(/\,/,$coursepersonnel{$element})) {
                   8619:             my ($puname,$pudom)=split(/\:/,$person);
                   8620:             my $clickers =
1.408     albertel 8621: 		(&Apache::lonnet::userenvironment($pudom,$puname,'clickers'))[1];
1.405     www      8622:             foreach my $id (split(/\,/,$clickers)) {
1.414     www      8623: 		$id=~s/^[\#0]+//;
1.421     www      8624:                 $id=~s/[\-\:]//g;
1.408     albertel 8625: 		if (exists($clicker_ids{$id})) {
                   8626: 		    $clicker_ids{$id}.=','.$puname.':'.$pudom;
                   8627: 		} else {
                   8628: 		    $clicker_ids{$id}=$puname.':'.$pudom;
                   8629: 		}
1.405     www      8630:             }
1.402     www      8631:         }
                   8632:     }
1.407     albertel 8633:     return %clicker_ids;
1.402     www      8634: }
                   8635: 
1.413     www      8636: sub clicker_grading_parameters {
                   8637:     return ('gradingmechanism' => 'scalar',
                   8638:             'upfiletype' => 'scalar',
                   8639:             'specificid' => 'scalar',
                   8640:             'pcorrect' => 'scalar',
                   8641:             'pincorrect' => 'scalar');
                   8642: }
                   8643: 
1.400     www      8644: sub process_clicker {
                   8645:     my ($r)=@_;
                   8646:     my ($symb)=&get_symb($r);
                   8647:     if (!$symb) {return '';}
                   8648:     my $result=&checkforfile_js();
                   8649:     $env{'form.probTitle'} = &Apache::lonnet::gettitle($symb);
                   8650:     my ($table) = &showResourceInfo($symb,$env{'form.probTitle'});
                   8651:     $result.=$table;
                   8652:     $result.='<br /><table width="100%" border="0"><tr><td bgcolor="#777777">'."\n";
                   8653:     $result.='<table width="100%" border="0"><tr bgcolor="#e6ffff"><td>'."\n";
1.538     schulted 8654:     $result.='&nbsp;<b>'.&mt('Specify a file containing the clicker information for this resource.').
                   8655:         '</b></td></tr>'."\n";
1.400     www      8656:     $result.='<tr bgcolor=#ffffe6><td>'."\n";
1.413     www      8657: # Attempt to restore parameters from last session, set defaults if not present
                   8658:     my %Saveable_Parameters=&clicker_grading_parameters();
                   8659:     &Apache::loncommon::restore_course_settings('grades_clicker',
                   8660:                                                  \%Saveable_Parameters);
                   8661:     if (!$env{'form.pcorrect'}) { $env{'form.pcorrect'}=100; }
                   8662:     if (!$env{'form.pincorrect'}) { $env{'form.pincorrect'}=100; }
                   8663:     if (!$env{'form.gradingmechanism'}) { $env{'form.gradingmechanism'}='attendance'; }
                   8664:     if (!$env{'form.upfiletype'}) { $env{'form.upfiletype'}='iclicker'; }
                   8665: 
                   8666:     my %checked;
1.521     www      8667:     foreach my $gradingmechanism ('attendance','personnel','specific','given') {
1.413     www      8668:        if ($env{'form.gradingmechanism'} eq $gradingmechanism) {
1.569     bisitz   8669:           $checked{$gradingmechanism}=' checked="checked"';
1.413     www      8670:        }
                   8671:     }
                   8672: 
1.400     www      8673:     my $upload=&mt("Upload File");
                   8674:     my $type=&mt("Type");
1.402     www      8675:     my $attendance=&mt("Award points just for participation");
                   8676:     my $personnel=&mt("Correctness determined from response by course personnel");
1.414     www      8677:     my $specific=&mt("Correctness determined from response with clicker ID(s)"); 
1.521     www      8678:     my $given=&mt("Correctness determined from given list of answers").' '.
                   8679:               '<font size="-2"><tt>('.&mt("Provide comma-separated list. Use '*' for any answer correct, '-' for skip").')</tt></font>';
1.402     www      8680:     my $pcorrect=&mt("Percentage points for correct solution");
                   8681:     my $pincorrect=&mt("Percentage points for incorrect solution");
1.413     www      8682:     my $selectform=&Apache::loncommon::select_form($env{'form.upfiletype'},'upfiletype',
1.419     www      8683: 						   ('iclicker' => 'i>clicker',
                   8684:                                                     'interwrite' => 'interwrite PRS'));
1.418     albertel 8685:     $symb = &Apache::lonenc::check_encrypt($symb);
1.400     www      8686:     $result.=<<ENDUPFORM;
1.402     www      8687: <script type="text/javascript">
                   8688: function sanitycheck() {
                   8689: // Accept only integer percentages
                   8690:    document.forms.gradesupload.pcorrect.value=Math.round(document.forms.gradesupload.pcorrect.value);
                   8691:    document.forms.gradesupload.pincorrect.value=Math.round(document.forms.gradesupload.pincorrect.value);
                   8692: // Find out grading choice
                   8693:    for (i=0; i<document.forms.gradesupload.gradingmechanism.length; i++) {
                   8694:       if (document.forms.gradesupload.gradingmechanism[i].checked) {
                   8695:          gradingchoice=document.forms.gradesupload.gradingmechanism[i].value;
                   8696:       }
                   8697:    }
                   8698: // By default, new choice equals user selection
                   8699:    newgradingchoice=gradingchoice;
                   8700: // Not good to give more points for false answers than correct ones
                   8701:    if (Math.round(document.forms.gradesupload.pcorrect.value)<Math.round(document.forms.gradesupload.pincorrect.value)) {
                   8702:       document.forms.gradesupload.pcorrect.value=document.forms.gradesupload.pincorrect.value;
                   8703:    }
                   8704: // If new choice is attendance only, and old choice was correctness-based, restore defaults
                   8705:    if ((gradingchoice=='attendance') && (document.forms.gradesupload.waschecked.value!='attendance')) {
                   8706:       document.forms.gradesupload.pcorrect.value=100;
                   8707:       document.forms.gradesupload.pincorrect.value=100;
                   8708:    }
                   8709: // If the values are different, cannot be attendance only
                   8710:    if ((Math.round(document.forms.gradesupload.pcorrect.value)!=Math.round(document.forms.gradesupload.pincorrect.value)) &&
                   8711:        (gradingchoice=='attendance')) {
                   8712:        newgradingchoice='personnel';
                   8713:    }
                   8714: // Change grading choice to new one
                   8715:    for (i=0; i<document.forms.gradesupload.gradingmechanism.length; i++) {
                   8716:       if (document.forms.gradesupload.gradingmechanism[i].value==newgradingchoice) {
                   8717:          document.forms.gradesupload.gradingmechanism[i].checked=true;
                   8718:       } else {
                   8719:          document.forms.gradesupload.gradingmechanism[i].checked=false;
                   8720:       }
                   8721:    }
                   8722: // Remember the old state
                   8723:    document.forms.gradesupload.waschecked.value=newgradingchoice;
                   8724: }
                   8725: </script>
1.400     www      8726: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="gradesupload">
                   8727: <input type="hidden" name="symb" value="$symb" />
                   8728: <input type="hidden" name="command" value="processclickerfile" />
                   8729: <input type="hidden" name="probTitle" value="$env{'form.probTitle'}" />
                   8730: <input type="hidden" name="saveState"  value="$env{'form.saveState'}" />
                   8731: <input type="file" name="upfile" size="50" />
                   8732: <br /><label>$type: $selectform</label>
1.569     bisitz   8733: <br /><label><input type="radio" name="gradingmechanism" value="attendance"$checked{'attendance'} onClick="sanitycheck()" />$attendance </label>
                   8734: <br /><label><input type="radio" name="gradingmechanism" value="personnel"$checked{'personnel'} onClick="sanitycheck()" />$personnel</label>
                   8735: <br /><label><input type="radio" name="gradingmechanism" value="specific"$checked{'specific'} onClick="sanitycheck()" />$specific </label>
1.414     www      8736: <input type="text" name="specificid" value="$env{'form.specificid'}" size="20" />
1.569     bisitz   8737: <br /><label><input type="radio" name="gradingmechanism" value="given"$checked{'given'} onClick="sanitycheck()" />$given </label>
1.521     www      8738: <br />&nbsp;&nbsp;&nbsp;
                   8739: <input type="text" name="givenanswer" size="50" />
1.413     www      8740: <input type="hidden" name="waschecked" value="$env{'form.gradingmechanism'}" />
                   8741: <br /><label>$pcorrect: <input type="text" name="pcorrect" size="4" value="$env{'form.pcorrect'}" onChange="sanitycheck()" /></label>
                   8742: <br /><label>$pincorrect: <input type="text" name="pincorrect" size="4" value="$env{'form.pincorrect'}" onChange="sanitycheck()" /></label>
1.400     www      8743: <br /><input type="button" onClick="javascript:checkUpload(this.form);" value="$upload" />
                   8744: </form>
                   8745: ENDUPFORM
                   8746:     $result.='</td></tr></table>'."\n".
                   8747:              '</td></tr></table><br /><br />'."\n";
                   8748:     $result.=&show_grading_menu_form($symb);
                   8749:     return $result;
                   8750: }
                   8751: 
                   8752: sub process_clicker_file {
                   8753:     my ($r)=@_;
                   8754:     my ($symb)=&get_symb($r);
                   8755:     if (!$symb) {return '';}
1.413     www      8756: 
                   8757:     my %Saveable_Parameters=&clicker_grading_parameters();
                   8758:     &Apache::loncommon::store_course_settings('grades_clicker',
                   8759:                                               \%Saveable_Parameters);
                   8760: 
1.400     www      8761:     my ($result) = &showResourceInfo($symb,$env{'form.probTitle'});
1.404     www      8762:     if (($env{'form.gradingmechanism'} eq 'specific') && ($env{'form.specificid'}!~/\w/)) {
1.408     albertel 8763: 	$result.='<span class="LC_error">'.&mt('You need to specify a clicker ID for the correct answer').'</span>';
                   8764: 	return $result.&show_grading_menu_form($symb);
1.404     www      8765:     }
1.522     www      8766:     if (($env{'form.gradingmechanism'} eq 'given') && ($env{'form.givenanswer'}!~/\S/)) {
1.521     www      8767:         $result.='<span class="LC_error">'.&mt('You need to specify the correct answer').'</span>';
                   8768:         return $result.&show_grading_menu_form($symb);
                   8769:     }
1.522     www      8770:     my $foundgiven=0;
1.521     www      8771:     if ($env{'form.gradingmechanism'} eq 'given') {
                   8772:         $env{'form.givenanswer'}=~s/^\s*//gs;
                   8773:         $env{'form.givenanswer'}=~s/\s*$//gs;
                   8774:         $env{'form.givenanswer'}=~s/[^a-zA-Z0-9\.\*\-]+/\,/g;
                   8775:         $env{'form.givenanswer'}=uc($env{'form.givenanswer'});
1.522     www      8776:         my @answers=split(/\,/,$env{'form.givenanswer'});
                   8777:         $foundgiven=$#answers+1;
1.521     www      8778:     }
1.407     albertel 8779:     my %clicker_ids=&gather_clicker_ids();
1.408     albertel 8780:     my %correct_ids;
1.404     www      8781:     if ($env{'form.gradingmechanism'} eq 'personnel') {
1.408     albertel 8782: 	%correct_ids=&gather_adv_clicker_ids();
1.404     www      8783:     }
                   8784:     if ($env{'form.gradingmechanism'} eq 'specific') {
1.414     www      8785: 	foreach my $correct_id (split(/[\s\,]/,$env{'form.specificid'})) {;
                   8786: 	   $correct_id=~tr/a-z/A-Z/;
                   8787: 	   $correct_id=~s/\s//gs;
                   8788: 	   $correct_id=~s/^[\#0]+//;
1.421     www      8789:            $correct_id=~s/[\-\:]//g;
1.414     www      8790:            if ($correct_id) {
                   8791: 	      $correct_ids{$correct_id}='specified';
                   8792:            }
                   8793:         }
1.400     www      8794:     }
1.404     www      8795:     if ($env{'form.gradingmechanism'} eq 'attendance') {
1.408     albertel 8796: 	$result.=&mt('Score based on attendance only');
1.521     www      8797:     } elsif ($env{'form.gradingmechanism'} eq 'given') {
1.522     www      8798:         $result.=&mt('Score based on [_1] ([_2] answers)','<tt>'.$env{'form.givenanswer'}.'</tt>',$foundgiven);
1.404     www      8799:     } else {
1.408     albertel 8800: 	my $number=0;
1.411     www      8801: 	$result.='<p><b>'.&mt('Correctness determined by the following IDs').'</b>';
1.408     albertel 8802: 	foreach my $id (sort(keys(%correct_ids))) {
1.411     www      8803: 	    $result.='<br /><tt>'.$id.'</tt> - ';
1.408     albertel 8804: 	    if ($correct_ids{$id} eq 'specified') {
                   8805: 		$result.=&mt('specified');
                   8806: 	    } else {
                   8807: 		my ($uname,$udom)=split(/\:/,$correct_ids{$id});
                   8808: 		$result.=&Apache::loncommon::plainname($uname,$udom);
                   8809: 	    }
                   8810: 	    $number++;
                   8811: 	}
1.411     www      8812:         $result.="</p>\n";
1.408     albertel 8813: 	if ($number==0) {
                   8814: 	    $result.='<span class="LC_error">'.&mt('No IDs found to determine correct answer').'</span>';
                   8815: 	    return $result.&show_grading_menu_form($symb);
                   8816: 	}
1.404     www      8817:     }
1.405     www      8818:     if (length($env{'form.upfile'}) < 2) {
1.407     albertel 8819:         $result.=&mt('[_1] Error: [_2] The file you attempted to upload, [_3] contained no information. Please check that you entered the correct filename.',
                   8820: 		     '<span class="LC_error">',
                   8821: 		     '</span>',
                   8822: 		     '<span class="LC_filename">'.&HTML::Entities::encode($env{'form.upfile.filename'},'<>&"').'</span>');
1.405     www      8823:         return $result.&show_grading_menu_form($symb);
                   8824:     }
1.410     www      8825: 
                   8826: # Were able to get all the info needed, now analyze the file
                   8827: 
1.411     www      8828:     $result.=&Apache::loncommon::studentbrowser_javascript();
1.418     albertel 8829:     $symb = &Apache::lonenc::check_encrypt($symb);
1.410     www      8830:     my $heading=&mt('Scanning clicker file');
                   8831:     $result.=(<<ENDHEADER);
                   8832: <br /><table width="100%" border="0"><tr><td bgcolor="#777777">
                   8833: <table width="100%" border="0"><tr bgcolor="#e6ffff"><td>
                   8834: <b>$heading</b></td></tr><tr bgcolor=#ffffe6><td>
                   8835: <form method="post" action="/adm/grades" name="clickeranalysis">
                   8836: <input type="hidden" name="symb" value="$symb" />
                   8837: <input type="hidden" name="command" value="assignclickergrades" />
                   8838: <input type="hidden" name="probTitle" value="$env{'form.probTitle'}" />
                   8839: <input type="hidden" name="saveState"  value="$env{'form.saveState'}" />
1.411     www      8840: <input type="hidden" name="gradingmechanism" value="$env{'form.gradingmechanism'}" />
                   8841: <input type="hidden" name="pcorrect" value="$env{'form.pcorrect'}" />
                   8842: <input type="hidden" name="pincorrect" value="$env{'form.pincorrect'}" />
1.410     www      8843: ENDHEADER
1.522     www      8844:     if ($env{'form.gradingmechanism'} eq 'given') {
                   8845:        $result.='<input type="hidden" name="correct:given" value="'.$env{'form.givenanswer'}.'" />';
                   8846:     } 
1.408     albertel 8847:     my %responses;
                   8848:     my @questiontitles;
1.405     www      8849:     my $errormsg='';
                   8850:     my $number=0;
                   8851:     if ($env{'form.upfiletype'} eq 'iclicker') {
1.408     albertel 8852: 	($errormsg,$number)=&iclicker_eval(\@questiontitles,\%responses);
1.406     www      8853:     }
1.419     www      8854:     if ($env{'form.upfiletype'} eq 'interwrite') {
                   8855:         ($errormsg,$number)=&interwrite_eval(\@questiontitles,\%responses);
                   8856:     }
1.411     www      8857:     $result.='<br />'.&mt('Found [_1] question(s)',$number).'<br />'.
                   8858:              '<input type="hidden" name="number" value="'.$number.'" />'.
                   8859:              &mt('Awarding [_1] percent for correct and [_2] percent for incorrect responses',
                   8860:                  $env{'form.pcorrect'},$env{'form.pincorrect'}).
                   8861:              '<br />';
1.522     www      8862:     if (($env{'form.gradingmechanism'} eq 'given') && ($number!=$foundgiven)) {
                   8863:        $result.='<span class="LC_error">'.&mt('Number of given answers does not agree with number of questions in file.').'</span>';
                   8864:        return $result.&show_grading_menu_form($symb);
                   8865:     } 
1.414     www      8866: # Remember Question Titles
                   8867: # FIXME: Possibly need delimiter other than ":"
                   8868:     for (my $i=0;$i<$number;$i++) {
                   8869:         $result.='<input type="hidden" name="question:'.$i.'" value="'.
                   8870:                  &HTML::Entities::encode($questiontitles[$i],'"&<>').'" />';
                   8871:     }
1.411     www      8872:     my $correct_count=0;
                   8873:     my $student_count=0;
                   8874:     my $unknown_count=0;
1.414     www      8875: # Match answers with usernames
                   8876: # FIXME: Possibly need delimiter other than ":"
1.409     albertel 8877:     foreach my $id (keys(%responses)) {
1.410     www      8878:        if ($correct_ids{$id}) {
1.414     www      8879:           $result.="\n".'<input type="hidden" name="correct:'.$correct_count.':'.$correct_ids{$id}.'" value="'.$responses{$id}.'" />';
1.411     www      8880:           $correct_count++;
1.410     www      8881:        } elsif ($clicker_ids{$id}) {
1.437     www      8882:           if ($clicker_ids{$id}=~/\,/) {
                   8883: # More than one user with the same clicker!
                   8884:              $result.="\n<hr />".&mt('Clicker registered more than once').": <tt>".$id."</tt><br />";
                   8885:              $result.="\n".'<input type="hidden" name="unknown:'.$id.'" value="'.$responses{$id}.'" />'.
                   8886:                            "<select name='multi".$id."'>";
                   8887:              foreach my $reguser (sort(split(/\,/,$clicker_ids{$id}))) {
                   8888:                  $result.="<option value='".$reguser."'>".&Apache::loncommon::plainname(split(/\:/,$reguser)).' ('.$reguser.')</option>';
                   8889:              }
                   8890:              $result.='</select>';
                   8891:              $unknown_count++;
                   8892:           } else {
                   8893: # Good: found one and only one user with the right clicker
                   8894:              $result.="\n".'<input type="hidden" name="student:'.$clicker_ids{$id}.'" value="'.$responses{$id}.'" />';
                   8895:              $student_count++;
                   8896:           }
1.410     www      8897:        } else {
1.411     www      8898:           $result.="\n<hr />".&mt('Unregistered Clicker')." <tt>".$id."</tt><br />";
                   8899:           $result.="\n".'<input type="hidden" name="unknown:'.$id.'" value="'.$responses{$id}.'" />'.
                   8900:                    "\n".&mt("Username").": <input type='text' name='uname".$id."' />&nbsp;".
                   8901:                    "\n".&mt("Domain").": ".
                   8902:                    &Apache::loncommon::select_dom_form($env{'course.'.$env{'request.course.id'}.'.domain'},'udom'.$id).'&nbsp;'.
                   8903:                    &Apache::loncommon::selectstudent_link('clickeranalysis','uname'.$id,'udom'.$id);
                   8904:           $unknown_count++;
1.410     www      8905:        }
1.405     www      8906:     }
1.412     www      8907:     $result.='<hr />'.
                   8908:              &mt('Found [_1] registered and [_2] unregistered clickers.',$student_count,$unknown_count);
1.521     www      8909:     if (($env{'form.gradingmechanism'} ne 'attendance') && ($env{'form.gradingmechanism'} ne 'given')) {
1.412     www      8910:        if ($correct_count==0) {
                   8911:           $errormsg.="Found no correct answers answers for grading!";
                   8912:        } elsif ($correct_count>1) {
1.414     www      8913:           $result.='<br /><span class="LC_warning">'.&mt("Found [_1] entries for grading!",$correct_count).'</span>';
1.412     www      8914:        }
                   8915:     }
1.428     www      8916:     if ($number<1) {
                   8917:        $errormsg.="Found no questions.";
                   8918:     }
1.412     www      8919:     if ($errormsg) {
                   8920:        $result.='<br /><span class="LC_error">'.&mt($errormsg).'</span>';
                   8921:     } else {
                   8922:        $result.='<br /><input type="submit" name="finalize" value="'.&mt('Finalize Grading').'" />';
                   8923:     }
                   8924:     $result.='</form></td></tr></table>'."\n".
1.410     www      8925:              '</td></tr></table><br /><br />'."\n";
1.404     www      8926:     return $result.&show_grading_menu_form($symb);
1.400     www      8927: }
                   8928: 
1.405     www      8929: sub iclicker_eval {
1.406     www      8930:     my ($questiontitles,$responses)=@_;
1.405     www      8931:     my $number=0;
                   8932:     my $errormsg='';
                   8933:     foreach my $line (split(/[\n\r]/,$env{'form.upfile'})) {
1.410     www      8934:         my %components=&Apache::loncommon::record_sep($line);
                   8935:         my @entries=map {$components{$_}} (sort(keys(%components)));
1.408     albertel 8936: 	if ($entries[0] eq 'Question') {
                   8937: 	    for (my $i=3;$i<$#entries;$i+=6) {
                   8938: 		$$questiontitles[$number]=$entries[$i];
                   8939: 		$number++;
                   8940: 	    }
                   8941: 	}
                   8942: 	if ($entries[0]=~/^\#/) {
                   8943: 	    my $id=$entries[0];
                   8944: 	    my @idresponses;
                   8945: 	    $id=~s/^[\#0]+//;
                   8946: 	    for (my $i=0;$i<$number;$i++) {
                   8947: 		my $idx=3+$i*6;
                   8948: 		push(@idresponses,$entries[$idx]);
                   8949: 	    }
                   8950: 	    $$responses{$id}=join(',',@idresponses);
                   8951: 	}
1.405     www      8952:     }
                   8953:     return ($errormsg,$number);
                   8954: }
                   8955: 
1.419     www      8956: sub interwrite_eval {
                   8957:     my ($questiontitles,$responses)=@_;
                   8958:     my $number=0;
                   8959:     my $errormsg='';
1.420     www      8960:     my $skipline=1;
                   8961:     my $questionnumber=0;
                   8962:     my %idresponses=();
1.419     www      8963:     foreach my $line (split(/[\n\r]/,$env{'form.upfile'})) {
                   8964:         my %components=&Apache::loncommon::record_sep($line);
                   8965:         my @entries=map {$components{$_}} (sort(keys(%components)));
1.420     www      8966:         if ($entries[1] eq 'Time') { $skipline=0; next; }
                   8967:         if ($entries[1] eq 'Response') { $skipline=1; }
                   8968:         next if $skipline;
                   8969:         if ($entries[0]!=$questionnumber) {
                   8970:            $questionnumber=$entries[0];
                   8971:            $$questiontitles[$number]=&mt('Question [_1]',$questionnumber);
                   8972:            $number++;
1.419     www      8973:         }
1.420     www      8974:         my $id=$entries[4];
                   8975:         $id=~s/^[\#0]+//;
1.421     www      8976:         $id=~s/^v\d*\://i;
                   8977:         $id=~s/[\-\:]//g;
1.420     www      8978:         $idresponses{$id}[$number]=$entries[6];
                   8979:     }
1.524     raeburn  8980:     foreach my $id (keys(%idresponses)) {
1.420     www      8981:        $$responses{$id}=join(',',@{$idresponses{$id}});
                   8982:        $$responses{$id}=~s/^\s*\,//;
1.419     www      8983:     }
                   8984:     return ($errormsg,$number);
                   8985: }
                   8986: 
1.414     www      8987: sub assign_clicker_grades {
                   8988:     my ($r)=@_;
                   8989:     my ($symb)=&get_symb($r);
                   8990:     if (!$symb) {return '';}
1.416     www      8991: # See which part we are saving to
                   8992:     my ($partlist,$handgrade,$responseType) = &response_type($symb);
                   8993: # FIXME: This should probably look for the first handgradeable part
                   8994:     my $part=$$partlist[0];
                   8995: # Start screen output
1.414     www      8996:     my ($result) = &showResourceInfo($symb,$env{'form.probTitle'});
1.416     www      8997: 
1.414     www      8998:     my $heading=&mt('Assigning grades based on clicker file');
                   8999:     $result.=(<<ENDHEADER);
                   9000: <br /><table width="100%" border="0"><tr><td bgcolor="#777777">
                   9001: <table width="100%" border="0"><tr bgcolor="#e6ffff"><td>
                   9002: <b>$heading</b></td></tr><tr bgcolor=#ffffe6><td>
                   9003: ENDHEADER
                   9004: # Get correct result
                   9005: # FIXME: Possibly need delimiter other than ":"
                   9006:     my @correct=();
1.415     www      9007:     my $gradingmechanism=$env{'form.gradingmechanism'};
                   9008:     my $number=$env{'form.number'};
                   9009:     if ($gradingmechanism ne 'attendance') {
1.414     www      9010:        foreach my $key (keys(%env)) {
                   9011:           if ($key=~/^form\.correct\:/) {
                   9012:              my @input=split(/\,/,$env{$key});
                   9013:              for (my $i=0;$i<=$#input;$i++) {
                   9014:                  if (($correct[$i]) && ($input[$i]) &&
                   9015:                      ($correct[$i] ne $input[$i])) {
                   9016:                     $result.='<br /><span class="LC_warning">'.
                   9017:                              &mt('More than one correct result given for question "[_1]": [_2] versus [_3].',
                   9018:                                  $env{'form.question:'.$i},$correct[$i],$input[$i]).'</span>';
                   9019:                  } elsif ($input[$i]) {
                   9020:                     $correct[$i]=$input[$i];
                   9021:                  }
                   9022:              }
                   9023:           }
                   9024:        }
1.415     www      9025:        for (my $i=0;$i<$number;$i++) {
1.414     www      9026:           if (!$correct[$i]) {
                   9027:              $result.='<br /><span class="LC_error">'.
                   9028:                       &mt('No correct result given for question "[_1]"!',
                   9029:                           $env{'form.question:'.$i}).'</span>';
                   9030:           }
                   9031:        }
                   9032:        $result.='<br />'.&mt("Correct answer: [_1]",join(', ',map { ($_?$_:'-') } @correct));
                   9033:     }
                   9034: # Start grading
1.415     www      9035:     my $pcorrect=$env{'form.pcorrect'};
                   9036:     my $pincorrect=$env{'form.pincorrect'};
1.416     www      9037:     my $storecount=0;
1.415     www      9038:     foreach my $key (keys(%env)) {
1.420     www      9039:        my $user='';
1.415     www      9040:        if ($key=~/^form\.student\:(.*)$/) {
1.420     www      9041:           $user=$1;
                   9042:        }
                   9043:        if ($key=~/^form\.unknown\:(.*)$/) {
                   9044:           my $id=$1;
                   9045:           if (($env{'form.uname'.$id}) && ($env{'form.udom'.$id})) {
                   9046:              $user=$env{'form.uname'.$id}.':'.$env{'form.udom'.$id};
1.437     www      9047:           } elsif ($env{'form.multi'.$id}) {
                   9048:              $user=$env{'form.multi'.$id};
1.420     www      9049:           }
                   9050:        }
                   9051:        if ($user) { 
1.415     www      9052:           my @answer=split(/\,/,$env{$key});
                   9053:           my $sum=0;
1.522     www      9054:           my $realnumber=$number;
1.415     www      9055:           for (my $i=0;$i<$number;$i++) {
1.576     www      9056:              if  ($correct[$i] eq '-') {
                   9057:                 $realnumber--;
                   9058:              } elsif ($answer[$i]) {
1.415     www      9059:                 if ($gradingmechanism eq 'attendance') {
                   9060:                    $sum+=$pcorrect;
1.576     www      9061:                 } elsif ($correct[$i] eq '*') {
1.522     www      9062:                    $sum+=$pcorrect;
1.415     www      9063:                 } else {
                   9064:                    if ($answer[$i] eq $correct[$i]) {
                   9065:                       $sum+=$pcorrect;
                   9066:                    } else {
                   9067:                       $sum+=$pincorrect;
                   9068:                    }
                   9069:                 }
                   9070:              }
                   9071:           }
1.522     www      9072:           my $ave=$sum/(100*$realnumber);
1.416     www      9073: # Store
                   9074:           my ($username,$domain)=split(/\:/,$user);
                   9075:           my %grades=();
                   9076:           $grades{"resource.$part.solved"}='correct_by_override';
                   9077:           $grades{"resource.$part.awarded"}=$ave;
                   9078:           $grades{"resource.regrader"}="$env{'user.name'}:$env{'user.domain'}";
                   9079:           my $returncode=&Apache::lonnet::cstore(\%grades,$symb,
                   9080:                                                  $env{'request.course.id'},
                   9081:                                                  $domain,$username);
                   9082:           if ($returncode ne 'ok') {
                   9083:              $result.="<br /><span class=\"LC_error\">Failed to save student $username:$domain. Message when trying to save was ($returncode)</span>";
                   9084:           } else {
                   9085:              $storecount++;
                   9086:           }
1.415     www      9087:        }
                   9088:     }
                   9089: # We are done
1.549     hauer    9090:     $result.='<br />'.&mt('Successfully stored grades for [quant,_1,student].',$storecount).
1.416     www      9091:              '</td></tr></table>'."\n".
1.414     www      9092:              '</td></tr></table><br /><br />'."\n";
                   9093:     return $result.&show_grading_menu_form($symb);
                   9094: }
                   9095: 
1.1       albertel 9096: sub handler {
1.41      ng       9097:     my $request=$_[0];
1.434     albertel 9098:     &reset_caches();
1.257     albertel 9099:     if ($env{'browser.mathml'}) {
1.141     www      9100: 	&Apache::loncommon::content_type($request,'text/xml');
1.41      ng       9101:     } else {
1.141     www      9102: 	&Apache::loncommon::content_type($request,'text/html');
1.41      ng       9103:     }
                   9104:     $request->send_http_header;
1.44      ng       9105:     return '' if $request->header_only;
1.41      ng       9106:     &Apache::loncommon::get_unprocessed_cgi($ENV{'QUERY_STRING'});
1.324     albertel 9107:     my $symb=&get_symb($request,1);
1.160     albertel 9108:     my @commands=&Apache::loncommon::get_env_multiple('form.command');
                   9109:     my $command=$commands[0];
1.447     foxr     9110: 
1.160     albertel 9111:     if ($#commands > 0) {
                   9112: 	&Apache::lonnet::logthis("grades got multiple commands ".join(':',@commands));
                   9113:     }
1.447     foxr     9114: 
1.513     foxr     9115:     $ssi_error = 0;
1.535     raeburn  9116:     my $brcrum = [{href=>"/adm/grades",text=>"Grading"}];
                   9117:     $request->print(&Apache::loncommon::start_page('Grading',undef,
                   9118:                                           {'bread_crumbs' => $brcrum}));
1.324     albertel 9119:     if ($symb eq '' && $command eq '') {
1.257     albertel 9120: 	if ($env{'user.adv'}) {
                   9121: 	    if (($env{'form.codeone'}) && ($env{'form.codetwo'}) &&
                   9122: 		($env{'form.codethree'})) {
                   9123: 		my $token=$env{'form.codeone'}.'*'.$env{'form.codetwo'}.'*'.
                   9124: 		    $env{'form.codethree'};
1.41      ng       9125: 		my ($tsymb,$tuname,$tudom,$tcrsid)=
                   9126: 		    &Apache::lonnet::checkin($token);
                   9127: 		if ($tsymb) {
1.137     albertel 9128: 		    my ($map,$id,$url)=&Apache::lonnet::decode_symb($tsymb);
1.41      ng       9129: 		    if (&Apache::lonnet::allowed('mgr',$tcrsid)) {
1.513     foxr     9130: 			$request->print(&ssi_with_retries('/res/'.$url, $ssi_retries,
1.99      albertel 9131: 					  ('grade_username' => $tuname,
                   9132: 					   'grade_domain' => $tudom,
                   9133: 					   'grade_courseid' => $tcrsid,
                   9134: 					   'grade_symb' => $tsymb)));
1.41      ng       9135: 		    } else {
1.45      ng       9136: 			$request->print('<h3>Not authorized: '.$token.'</h3>');
1.99      albertel 9137: 		    }
1.41      ng       9138: 		} else {
1.45      ng       9139: 		    $request->print('<h3>Not a valid DocID: '.$token.'</h3>');
1.41      ng       9140: 		}
1.14      www      9141: 	    } else {
1.41      ng       9142: 		$request->print(&Apache::lonxml::tokeninputfield());
                   9143: 	    }
                   9144: 	}
                   9145:     } else {
1.285     albertel 9146: 	&init_perm();
1.104     albertel 9147: 	if ($command eq 'submission' && $perm{'vgr'}) {
1.257     albertel 9148: 	    ($env{'form.student'} eq '' ? &listStudents($request) : &submission($request,0,0));
1.103     albertel 9149: 	} elsif ($command eq 'pickStudentPage' && $perm{'vgr'}) {
1.68      ng       9150: 	    &pickStudentPage($request);
1.103     albertel 9151: 	} elsif ($command eq 'displayPage' && $perm{'vgr'}) {
1.68      ng       9152: 	    &displayPage($request);
1.104     albertel 9153: 	} elsif ($command eq 'gradeByPage' && $perm{'mgr'}) {
1.71      ng       9154: 	    &updateGradeByPage($request);
1.104     albertel 9155: 	} elsif ($command eq 'processGroup' && $perm{'vgr'}) {
1.41      ng       9156: 	    &processGroup($request);
1.104     albertel 9157: 	} elsif ($command eq 'gradingmenu' && $perm{'vgr'}) {
1.443     banghart 9158: 	    $request->print(&grading_menu($request));
                   9159: 	} elsif ($command eq 'submit_options' && $perm{'vgr'}) {
                   9160: 	    $request->print(&submit_options($request));
1.104     albertel 9161: 	} elsif ($command eq 'viewgrades' && $perm{'vgr'}) {
1.41      ng       9162: 	    $request->print(&viewgrades($request));
1.104     albertel 9163: 	} elsif ($command eq 'handgrade' && $perm{'mgr'}) {
1.41      ng       9164: 	    $request->print(&processHandGrade($request));
1.106     albertel 9165: 	} elsif ($command eq 'editgrades' && $perm{'mgr'}) {
1.41      ng       9166: 	    $request->print(&editgrades($request));
1.106     albertel 9167: 	} elsif ($command eq 'verify' && $perm{'vgr'}) {
1.41      ng       9168: 	    $request->print(&verifyreceipt($request));
1.400     www      9169:         } elsif ($command eq 'processclicker' && $perm{'mgr'}) {
                   9170:             $request->print(&process_clicker($request));
                   9171:         } elsif ($command eq 'processclickerfile' && $perm{'mgr'}) {
                   9172:             $request->print(&process_clicker_file($request));
1.414     www      9173:         } elsif ($command eq 'assignclickergrades' && $perm{'mgr'}) {
                   9174:             $request->print(&assign_clicker_grades($request));
1.106     albertel 9175: 	} elsif ($command eq 'csvform' && $perm{'mgr'}) {
1.72      ng       9176: 	    $request->print(&upcsvScores_form($request));
1.106     albertel 9177: 	} elsif ($command eq 'csvupload' && $perm{'mgr'}) {
1.41      ng       9178: 	    $request->print(&csvupload($request));
1.106     albertel 9179: 	} elsif ($command eq 'csvuploadmap' && $perm{'mgr'} ) {
1.41      ng       9180: 	    $request->print(&csvuploadmap($request));
1.246     albertel 9181: 	} elsif ($command eq 'csvuploadoptions' && $perm{'mgr'}) {
1.257     albertel 9182: 	    if ($env{'form.associate'} ne 'Reverse Association') {
1.246     albertel 9183: 		$request->print(&csvuploadoptions($request));
1.41      ng       9184: 	    } else {
1.257     albertel 9185: 		if ( $env{'form.upfile_associate'} ne 'reverse' ) {
                   9186: 		    $env{'form.upfile_associate'} = 'reverse';
1.41      ng       9187: 		} else {
1.257     albertel 9188: 		    $env{'form.upfile_associate'} = 'forward';
1.41      ng       9189: 		}
                   9190: 		$request->print(&csvuploadmap($request));
                   9191: 	    }
1.246     albertel 9192: 	} elsif ($command eq 'csvuploadassign' && $perm{'mgr'} ) {
                   9193: 	    $request->print(&csvuploadassign($request));
1.106     albertel 9194: 	} elsif ($command eq 'scantron_selectphase' && $perm{'mgr'}) {
1.75      albertel 9195: 	    $request->print(&scantron_selectphase($request));
1.203     albertel 9196:  	} elsif ($command eq 'scantron_warning' && $perm{'mgr'}) {
                   9197:  	    $request->print(&scantron_do_warning($request));
1.142     albertel 9198: 	} elsif ($command eq 'scantron_validate' && $perm{'mgr'}) {
                   9199: 	    $request->print(&scantron_validate_file($request));
1.106     albertel 9200: 	} elsif ($command eq 'scantron_process' && $perm{'mgr'}) {
1.82      albertel 9201: 	    $request->print(&scantron_process_students($request));
1.157     albertel 9202:  	} elsif ($command eq 'scantronupload' && 
1.257     albertel 9203:  		 (&Apache::lonnet::allowed('usc',$env{'request.role.domain'})||
                   9204: 		  &Apache::lonnet::allowed('usc',$env{'request.course.id'}))) {
1.162     albertel 9205:  	    $request->print(&scantron_upload_scantron_data($request)); 
1.157     albertel 9206:  	} elsif ($command eq 'scantronupload_save' &&
1.257     albertel 9207:  		 (&Apache::lonnet::allowed('usc',$env{'request.role.domain'})||
                   9208: 		  &Apache::lonnet::allowed('usc',$env{'request.course.id'}))) {
1.157     albertel 9209:  	    $request->print(&scantron_upload_scantron_data_save($request));
1.202     albertel 9210:  	} elsif ($command eq 'scantron_download' &&
1.257     albertel 9211: 		 &Apache::lonnet::allowed('usc',$env{'request.course.id'})) {
1.162     albertel 9212:  	    $request->print(&scantron_download_scantron_data($request));
1.523     raeburn  9213:         } elsif ($command eq 'checksubmissions' && $perm{'vgr'}) {
                   9214:             $request->print(&checkscantron_results($request));     
1.106     albertel 9215: 	} elsif ($command) {
1.562     bisitz   9216: 	    $request->print('<p class="LC_error">'.&mt('Access Denied ([_1])',$command).'</p>');
1.26      albertel 9217: 	}
1.2       albertel 9218:     }
1.513     foxr     9219:     if ($ssi_error) {
                   9220: 	&ssi_print_error($request);
                   9221:     }
1.353     albertel 9222:     $request->print(&Apache::loncommon::end_page());
1.434     albertel 9223:     &reset_caches();
1.44      ng       9224:     return '';
                   9225: }
                   9226: 
1.1       albertel 9227: 1;
                   9228: 
1.13      albertel 9229: __END__;
1.531     jms      9230: 
                   9231: 
                   9232: =head1 NAME
                   9233: 
                   9234: Apache::grades
                   9235: 
                   9236: =head1 SYNOPSIS
                   9237: 
                   9238: Handles the viewing of grades.
                   9239: 
                   9240: This is part of the LearningOnline Network with CAPA project
                   9241: described at http://www.lon-capa.org.
                   9242: 
                   9243: =head1 OVERVIEW
                   9244: 
                   9245: Do an ssi with retries:
                   9246: While I'd love to factor out this with the vesrion in lonprintout,
                   9247: 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
                   9248: I'm not quite ready to invent (e.g. an ssi_with_retry object).
                   9249: 
                   9250: At least the logic that drives this has been pulled out into loncommon.
                   9251: 
                   9252: 
                   9253: 
                   9254: ssi_with_retries - Does the server side include of a resource.
                   9255:                      if the ssi call returns an error we'll retry it up to
                   9256:                      the number of times requested by the caller.
                   9257:                      If we still have a proble, no text is appended to the
                   9258:                      output and we set some global variables.
                   9259:                      to indicate to the caller an SSI error occurred.  
                   9260:                      All of this is supposed to deal with the issues described
                   9261:                      in LonCAPA BZ 5631 see:
                   9262:                      http://bugs.lon-capa.org/show_bug.cgi?id=5631
                   9263:                      by informing the user that this happened.
                   9264: 
                   9265: Parameters:
                   9266:   resource   - The resource to include.  This is passed directly, without
                   9267:                interpretation to lonnet::ssi.
                   9268:   form       - The form hash parameters that guide the interpretation of the resource
                   9269:                
                   9270:   retries    - Number of retries allowed before giving up completely.
                   9271: Returns:
                   9272:   On success, returns the rendered resource identified by the resource parameter.
                   9273: Side Effects:
                   9274:   The following global variables can be set:
                   9275:    ssi_error                - If an unrecoverable error occurred this becomes true.
                   9276:                               It is up to the caller to initialize this to false
                   9277:                               if desired.
                   9278:    ssi_error_resource  - If an unrecoverable error occurred, this is the value
                   9279:                               of the resource that could not be rendered by the ssi
                   9280:                               call.
                   9281:    ssi_error_message   - The error string fetched from the ssi response
                   9282:                               in the event of an error.
                   9283: 
                   9284: 
                   9285: =head1 HANDLER SUBROUTINE
                   9286: 
                   9287: ssi_with_retries()
                   9288: 
                   9289: =head1 SUBROUTINES
                   9290: 
                   9291: =over
                   9292: 
                   9293: =item scantron_get_correction() : 
                   9294: 
                   9295:    Builds the interface screen to interact with the operator to fix a
                   9296:    specific error condition in a specific scanline
                   9297: 
                   9298:  Arguments:
                   9299:     $r           - Apache request object
                   9300:     $i           - number of the current scanline
                   9301:     $scan_record - hash ref as returned from &scantron_parse_scanline()
                   9302:     $scan_config - hash ref as returned from &get_scantron_config()
                   9303:     $line        - full contents of the current scanline
                   9304:     $error       - error condition, valid values are
                   9305:                    'incorrectCODE', 'duplicateCODE',
                   9306:                    'doublebubble', 'missingbubble',
                   9307:                    'duplicateID', 'incorrectID'
                   9308:     $arg         - extra information needed
                   9309:        For errors:
                   9310:          - duplicateID   - paper number that this studentID was seen before on
                   9311:          - duplicateCODE - array ref of the paper numbers this CODE was
                   9312:                            seen on before
                   9313:          - incorrectCODE - current incorrect CODE 
                   9314:          - doublebubble  - array ref of the bubble lines that have double
                   9315:                            bubble errors
                   9316:          - missingbubble - array ref of the bubble lines that have missing
                   9317:                            bubble errors
                   9318: 
                   9319: =item  scantron_get_maxbubble() : 
                   9320: 
                   9321:    Returns the maximum number of bubble lines that are expected to
                   9322:    occur. Does this by walking the selected sequence rendering the
                   9323:    resource and then checking &Apache::lonxml::get_problem_counter()
                   9324:    for what the current value of the problem counter is.
                   9325: 
                   9326:    Caches the results to $env{'form.scantron_maxbubble'},
                   9327:    $env{'form.scantron.bubble_lines.n'}, 
                   9328:    $env{'form.scantron.first_bubble_line.n'} and
                   9329:    $env{"form.scantron.sub_bubblelines.n"}
                   9330:    which are the total number of bubble, lines, the number of bubble
                   9331:    lines for response n and number of the first bubble line for response n,
                   9332:    and a comma separated list of numbers of bubble lines for sub-questions
                   9333:    (for optionresponse, matchresponse, and rankresponse items), for response n.  
                   9334: 
                   9335: 
                   9336: =item  scantron_validate_missingbubbles() : 
                   9337: 
                   9338:    Validates all scanlines in the selected file to not have any
                   9339:     answers that don't have bubbles that have not been verified
                   9340:     to be bubble free.
                   9341: 
                   9342: =item  scantron_process_students() : 
                   9343: 
                   9344:    Routine that does the actual grading of the bubble sheet information.
                   9345: 
                   9346:    The parsed scanline hash is added to %env 
                   9347: 
                   9348:    Then foreach unskipped scanline it does an &Apache::lonnet::ssi()
                   9349:    foreach resource , with the form data of
                   9350: 
                   9351: 	'submitted'     =>'scantron' 
                   9352: 	'grade_target'  =>'grade',
                   9353: 	'grade_username'=> username of student
                   9354: 	'grade_domain'  => domain of student
                   9355: 	'grade_courseid'=> of course
                   9356: 	'grade_symb'    => symb of resource to grade
                   9357: 
                   9358:     This triggers a grading pass. The problem grading code takes care
                   9359:     of converting the bubbled letter information (now in %env) into a
                   9360:     valid submission.
                   9361: 
                   9362: =item  scantron_upload_scantron_data() :
                   9363: 
                   9364:     Creates the screen for adding a new bubble sheet data file to a course.
                   9365: 
                   9366: =item  scantron_upload_scantron_data_save() : 
                   9367: 
                   9368:    Adds a provided bubble information data file to the course if user
                   9369:    has the correct privileges to do so. 
                   9370: 
                   9371: =item  valid_file() :
                   9372: 
                   9373:    Validates that the requested bubble data file exists in the course.
                   9374: 
                   9375: =item  scantron_download_scantron_data() : 
                   9376: 
                   9377:    Shows a list of the three internal files (original, corrected,
                   9378:    skipped) for a specific bubble sheet data file that exists in the
                   9379:    course.
                   9380: 
                   9381: =item  scantron_validate_ID() : 
                   9382: 
                   9383:    Validates all scanlines in the selected file to not have any
1.556     weissno  9384:    invalid or underspecified student/employee IDs
1.531     jms      9385: 
                   9386: =back
                   9387: 
                   9388: =cut

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