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

1.17      albertel    1: # The LearningOnline Network with CAPA
1.13      albertel    2: # The LON-CAPA Grading handler
1.17      albertel    3: #
1.559   ! raeburn     4: # $Id: grades.pm,v 1.558 2009/03/18 12:26:21 bisitz 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.398     albertel  186: 	$display.= " (<span class=\"LC_internal_info\">id $partID</span>)";
1.207     albertel  187:     } else {
                    188: 	$display=$partID;
                    189:     }
                    190:     return $display;
                    191: }
1.269     raeburn   192: 
1.118     ng        193: #--- Show resource title
                    194: #--- and parts and response type
                    195: sub showResourceInfo {
1.324     albertel  196:     my ($symb,$probTitle,$checkboxes) = @_;
1.154     albertel  197:     my $col=3;
                    198:     if ($checkboxes) { $col=4; }
1.398     albertel  199:     my $result = '<h3>'.&mt('Current Resource').': '.$probTitle.'</h3>'."\n";
                    200:     $result .='<table border="0">';
1.324     albertel  201:     my ($partlist,$handgrade,$responseType) = &response_type($symb);
1.126     ng        202:     my %resptype = ();
1.122     ng        203:     my $hdgrade='no';
1.154     albertel  204:     my %partsseen;
1.524     raeburn   205:     foreach my $partID (sort(keys(%$responseType))) {
                    206: 	foreach my $resID (sort(keys(%{ $responseType->{$partID} }))) {
1.375     albertel  207: 	    my $handgrade=$$handgrade{$partID.'_'.$resID};
                    208: 	    my $responsetype = $responseType->{$partID}->{$resID};
                    209: 	    $hdgrade = $handgrade if ($handgrade eq 'yes');
                    210: 	    $result.='<tr>';
                    211: 	    if ($checkboxes) {
                    212: 		if (exists($partsseen{$partID})) {
                    213: 		    $result.="<td>&nbsp;</td>";
                    214: 		} else {
1.401     albertel  215: 		    $result.="<td><input type='checkbox' name='vPart' value='$partID' checked='checked' /></td>";
1.375     albertel  216: 		}
                    217: 		$partsseen{$partID}=1;
1.154     albertel  218: 	    }
1.375     albertel  219: 	    my $display_part=&get_display_part($partID,$symb);
1.539     riegler   220: 	    $result.='<td><b>'.&mt('Part').': </b>'.$display_part.
                    221:                 ' <span class="LC_internal_info">'.$resID.'</span></td>'.
                    222: 		'<td><b>'.&mt('Type').': </b>'.$responsetype.'</td></tr>';
1.485     albertel  223: #	    '<td>'.&mt('<b>Handgrade: </b>[_1]',$handgrade).'</td></tr>';
1.154     albertel  224: 	}
1.118     ng        225:     }
                    226:     $result.='</table>'."\n";
1.147     albertel  227:     return $result,$responseType,$hdgrade,$partlist,$handgrade;
1.118     ng        228: }
                    229: 
1.434     albertel  230: sub reset_caches {
                    231:     &reset_analyze_cache();
                    232:     &reset_perm();
                    233: }
                    234: 
                    235: {
                    236:     my %analyze_cache;
1.557     raeburn   237:     my %analyze_cache_formkeys;
1.148     albertel  238: 
1.434     albertel  239:     sub reset_analyze_cache {
                    240: 	undef(%analyze_cache);
1.557     raeburn   241:         undef(%analyze_cache_formkeys);
1.434     albertel  242:     }
                    243: 
                    244:     sub get_analyze {
1.557     raeburn   245: 	my ($symb,$uname,$udom,$no_increment,$add_to_hash)=@_;
1.434     albertel  246: 	my $key = "$symb\0$uname\0$udom";
1.557     raeburn   247: 	if (exists($analyze_cache{$key})) {
                    248:             my $getupdate = 0;
                    249:             if (ref($add_to_hash) eq 'HASH') {
                    250:                 foreach my $item (keys(%{$add_to_hash})) {
                    251:                     if (ref($analyze_cache_formkeys{$key}) eq 'HASH') {
                    252:                         if (!exists($analyze_cache_formkeys{$key}{$item})) {
                    253:                             $getupdate = 1;
                    254:                             last;
                    255:                         }
                    256:                     } else {
                    257:                         $getupdate = 1;
                    258:                     }
                    259:                 }
                    260:             }
                    261:             if (!$getupdate) {
                    262:                 return $analyze_cache{$key};
                    263:             }
                    264:         }
1.434     albertel  265: 
                    266: 	my (undef,undef,$url)=&Apache::lonnet::decode_symb($symb);
                    267: 	$url=&Apache::lonnet::clutter($url);
1.557     raeburn   268:         my %form = ('grade_target'      => 'analyze',
                    269:                     'grade_domain'      => $udom,
                    270:                     'grade_symb'        => $symb,
                    271:                     'grade_courseid'    =>  $env{'request.course.id'},
                    272:                     'grade_username'    => $uname,
                    273:                     'grade_noincrement' => $no_increment);
                    274:         if (ref($add_to_hash)) {
                    275:             %form = (%form,%{$add_to_hash});
                    276:         } 
                    277: 	my $subresult=&ssi_with_retries($url, $ssi_retries,%form);
1.434     albertel  278: 	(undef,$subresult)=split(/_HASH_REF__/,$subresult,2);
                    279: 	my %analyze=&Apache::lonnet::str2hash($subresult);
1.557     raeburn   280:         if (ref($add_to_hash) eq 'HASH') {
                    281:             $analyze_cache_formkeys{$key} = $add_to_hash;
                    282:         } else {
                    283:             $analyze_cache_formkeys{$key} = {};
                    284:         }
1.434     albertel  285: 	return $analyze_cache{$key} = \%analyze;
                    286:     }
                    287: 
                    288:     sub get_order {
1.525     raeburn   289: 	my ($partid,$respid,$symb,$uname,$udom,$no_increment)=@_;
                    290: 	my $analyze = &get_analyze($symb,$uname,$udom,$no_increment);
1.434     albertel  291: 	return $analyze->{"$partid.$respid.shown"};
                    292:     }
                    293: 
                    294:     sub get_radiobutton_correct_foil {
                    295: 	my ($partid,$respid,$symb,$uname,$udom)=@_;
                    296: 	my $analyze = &get_analyze($symb,$uname,$udom);
1.555     raeburn   297:         my $foils = &get_order($partid,$respid,$symb,$uname,$udom);
                    298:         if (ref($foils) eq 'ARRAY') {
                    299: 	    foreach my $foil (@{$foils}) {
                    300: 	        if ($analyze->{"$partid.$respid.foil.value.$foil"} eq 'true') {
                    301: 		    return $foil;
                    302: 	        }
1.434     albertel  303: 	    }
                    304: 	}
                    305:     }
1.554     raeburn   306: 
                    307:     sub scantron_partids_tograde {
1.557     raeburn   308:         my ($resource,$cid,$uname,$udom,$check_for_randomlist) = @_;
1.554     raeburn   309:         my (%analysis,@parts);
                    310:         if (ref($resource)) {
                    311:             my $symb = $resource->symb();
1.557     raeburn   312:             my $add_to_form;
                    313:             if ($check_for_randomlist) {
                    314:                 $add_to_form = { 'check_parts_withrandomlist' => 1,};
                    315:             }
                    316:             my $analyze = &get_analyze($symb,$uname,$udom,undef,$add_to_form);
1.554     raeburn   317:             if (ref($analyze) eq 'HASH') {
                    318:                 %analysis = %{$analyze};
                    319:             }
                    320:             if (ref($analysis{'parts'}) eq 'ARRAY') {
                    321:                 foreach my $part (@{$analysis{'parts'}}) {
                    322:                     my ($id,$respid) = split(/\./,$part);
                    323:                     if (!&Apache::loncommon::check_if_partid_hidden($id,$symb,$udom,$uname)) {
                    324:                         push(@parts,$part);
                    325:                     }
                    326:                 }
                    327:             }
                    328:         }
                    329:         return (\%analysis,\@parts);
                    330:     }
                    331: 
1.148     albertel  332: }
1.434     albertel  333: 
1.118     ng        334: #--- Clean response type for display
1.335     albertel  335: #--- Currently filters option/rank/radiobutton/match/essay/Task
                    336: #        response types only.
1.118     ng        337: sub cleanRecord {
1.336     albertel  338:     my ($answer,$response,$symb,$partid,$respid,$record,$order,$version,
                    339: 	$uname,$udom) = @_;
1.398     albertel  340:     my $grayFont = '<span class="LC_internal_info">';
1.148     albertel  341:     if ($response =~ /^(option|rank)$/) {
                    342: 	my %answer=&Apache::lonnet::str2hash($answer);
                    343: 	my %grading=&Apache::lonnet::str2hash($record->{$version."resource.$partid.$respid.submissiongrading"});
                    344: 	my ($toprow,$bottomrow);
                    345: 	foreach my $foil (@$order) {
                    346: 	    if ($grading{$foil} == 1) {
                    347: 		$toprow.='<td><b>'.$answer{$foil}.'&nbsp;</b></td>';
                    348: 	    } else {
                    349: 		$toprow.='<td><i>'.$answer{$foil}.'&nbsp;</i></td>';
                    350: 	    }
1.398     albertel  351: 	    $bottomrow.='<td>'.$grayFont.$foil.'</span>&nbsp;</td>';
1.148     albertel  352: 	}
                    353: 	return '<blockquote><table border="1">'.
1.466     albertel  354: 	    '<tr valign="top"><td>'.&mt('Answer').'</td>'.$toprow.'</tr>'.
                    355: 	    '<tr valign="top"><td>'.$grayFont.&mt('Option ID').'</span></td>'.
1.148     albertel  356: 	    $grayFont.$bottomrow.'</tr>'.'</table></blockquote>';
                    357:     } elsif ($response eq 'match') {
                    358: 	my %answer=&Apache::lonnet::str2hash($answer);
                    359: 	my %grading=&Apache::lonnet::str2hash($record->{$version."resource.$partid.$respid.submissiongrading"});
                    360: 	my @items=&Apache::lonnet::str2array($record->{$version."resource.$partid.$respid.submissionitems"});
                    361: 	my ($toprow,$middlerow,$bottomrow);
                    362: 	foreach my $foil (@$order) {
                    363: 	    my $item=shift(@items);
                    364: 	    if ($grading{$foil} == 1) {
                    365: 		$toprow.='<td><b>'.$item.'&nbsp;</b></td>';
1.398     albertel  366: 		$middlerow.='<td><b>'.$grayFont.$answer{$foil}.'&nbsp;</span></b></td>';
1.148     albertel  367: 	    } else {
                    368: 		$toprow.='<td><i>'.$item.'&nbsp;</i></td>';
1.398     albertel  369: 		$middlerow.='<td><i>'.$grayFont.$answer{$foil}.'&nbsp;</span></i></td>';
1.148     albertel  370: 	    }
1.398     albertel  371: 	    $bottomrow.='<td>'.$grayFont.$foil.'</span>&nbsp;</td>';
1.118     ng        372: 	}
1.126     ng        373: 	return '<blockquote><table border="1">'.
1.466     albertel  374: 	    '<tr valign="top"><td>'.&mt('Answer').'</td>'.$toprow.'</tr>'.
                    375: 	    '<tr valign="top"><td>'.$grayFont.&mt('Item ID').'</span></td>'.
1.148     albertel  376: 	    $middlerow.'</tr>'.
1.466     albertel  377: 	    '<tr valign="top"><td>'.$grayFont.&mt('Option ID').'</span></td>'.
1.148     albertel  378: 	    $bottomrow.'</tr>'.'</table></blockquote>';
                    379:     } elsif ($response eq 'radiobutton') {
                    380: 	my %answer=&Apache::lonnet::str2hash($answer);
                    381: 	my ($toprow,$bottomrow);
1.434     albertel  382: 	my $correct = 
                    383: 	    &get_radiobutton_correct_foil($partid,$respid,$symb,$uname,$udom);
                    384: 	foreach my $foil (@$order) {
1.148     albertel  385: 	    if (exists($answer{$foil})) {
1.434     albertel  386: 		if ($foil eq $correct) {
1.466     albertel  387: 		    $toprow.='<td><b>'.&mt('true').'</b></td>';
1.148     albertel  388: 		} else {
1.466     albertel  389: 		    $toprow.='<td><i>'.&mt('true').'</i></td>';
1.148     albertel  390: 		}
                    391: 	    } else {
1.466     albertel  392: 		$toprow.='<td>'.&mt('false').'</td>';
1.148     albertel  393: 	    }
1.398     albertel  394: 	    $bottomrow.='<td>'.$grayFont.$foil.'</span>&nbsp;</td>';
1.148     albertel  395: 	}
                    396: 	return '<blockquote><table border="1">'.
1.466     albertel  397: 	    '<tr valign="top"><td>'.&mt('Answer').'</td>'.$toprow.'</tr>'.
                    398: 	    '<tr valign="top"><td>'.$grayFont.&mt('Option ID').'</span></td>'.
1.148     albertel  399: 	    $grayFont.$bottomrow.'</tr>'.'</table></blockquote>';
                    400:     } elsif ($response eq 'essay') {
1.257     albertel  401: 	if (! exists ($env{'form.'.$symb})) {
1.122     ng        402: 	    my (%keyhash) = &Apache::lonnet::dump('nohist_handgrade',
1.257     albertel  403: 						  $env{'course.'.$env{'request.course.id'}.'.domain'},
                    404: 						  $env{'course.'.$env{'request.course.id'}.'.num'});
1.122     ng        405: 
1.257     albertel  406: 	    my $loginuser = $env{'user.name'}.':'.$env{'user.domain'};
                    407: 	    $env{'form.keywords'} = $keyhash{$symb.'_keywords'} ne '' ? $keyhash{$symb.'_keywords'} : '';
                    408: 	    $env{'form.kwclr'}    = $keyhash{$loginuser.'_kwclr'} ne '' ? $keyhash{$loginuser.'_kwclr'} : 'red';
                    409: 	    $env{'form.kwsize'}   = $keyhash{$loginuser.'_kwsize'} ne '' ? $keyhash{$loginuser.'_kwsize'} : '0';
                    410: 	    $env{'form.kwstyle'}  = $keyhash{$loginuser.'_kwstyle'} ne '' ? $keyhash{$loginuser.'_kwstyle'} : '';
                    411: 	    $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        412: 	}
1.166     albertel  413: 	$answer =~ s-\n-<br />-g;
                    414: 	return '<br /><br /><blockquote><tt>'.&keywords_highlight($answer).'</tt></blockquote>';
1.268     albertel  415:     } elsif ( $response eq 'organic') {
                    416: 	my $result='Smile representation: "<tt>'.$answer.'</tt>"';
                    417: 	my $jme=$record->{$version."resource.$partid.$respid.molecule"};
                    418: 	$result.=&Apache::chemresponse::jme_img($jme,$answer,400);
                    419: 	return $result;
1.335     albertel  420:     } elsif ( $response eq 'Task') {
                    421: 	if ( $answer eq 'SUBMITTED') {
                    422: 	    my $files = $record->{$version."resource.$respid.$partid.bridgetask.portfiles"};
1.336     albertel  423: 	    my $result = &Apache::bridgetask::file_list($files,$uname,$udom);
1.335     albertel  424: 	    return $result;
                    425: 	} elsif ( grep(/^\Q$version\E.*?\.instance$/, keys(%{$record})) ) {
                    426: 	    my @matches = grep(/^\Q$version\E.*?\.instance$/,
                    427: 			       keys(%{$record}));
                    428: 	    return join('<br />',($version,@matches));
                    429: 			       
                    430: 			       
                    431: 	} else {
                    432: 	    my $result =
                    433: 		'<p>'
                    434: 		.&mt('Overall result: [_1]',
                    435: 		     $record->{$version."resource.$respid.$partid.status"})
                    436: 		.'</p>';
                    437: 	    
                    438: 	    $result .= '<ul>';
                    439: 	    my @grade = grep(/^\Q${version}resource.$respid.$partid.\E[^.]*[.]status$/,
                    440: 			     keys(%{$record}));
                    441: 	    foreach my $grade (sort(@grade)) {
                    442: 		my ($dim) = ($grade =~/[.]([^.]+)[.]status$/);
                    443: 		$result.= '<li>'.&mt("Dimension: [_1], status [_2] ",
                    444: 				     $dim, $record->{$grade}).
                    445: 			  '</li>';
                    446: 	    }
                    447: 	    $result.='</ul>';
                    448: 	    return $result;
                    449: 	}
1.440     albertel  450:     } elsif ( $response =~ m/(?:numerical|formula)/) {
                    451: 	$answer = 
                    452: 	    &Apache::loncommon::format_previous_attempt_value('submission',
                    453: 							      $answer);
1.122     ng        454:     }
1.118     ng        455:     return $answer;
                    456: }
                    457: 
                    458: #-- A couple of common js functions
                    459: sub commonJSfunctions {
                    460:     my $request = shift;
                    461:     $request->print(<<COMMONJSFUNCTIONS);
                    462: <script type="text/javascript" language="javascript">
                    463:     function radioSelection(radioButton) {
                    464: 	var selection=null;
                    465: 	if (radioButton.length > 1) {
                    466: 	    for (var i=0; i<radioButton.length; i++) {
                    467: 		if (radioButton[i].checked) {
                    468: 		    return radioButton[i].value;
                    469: 		}
                    470: 	    }
                    471: 	} else {
                    472: 	    if (radioButton.checked) return radioButton.value;
                    473: 	}
                    474: 	return selection;
                    475:     }
                    476: 
                    477:     function pullDownSelection(selectOne) {
                    478: 	var selection="";
                    479: 	if (selectOne.length > 1) {
                    480: 	    for (var i=0; i<selectOne.length; i++) {
                    481: 		if (selectOne[i].selected) {
                    482: 		    return selectOne[i].value;
                    483: 		}
                    484: 	    }
                    485: 	} else {
1.138     albertel  486:             // only one value it must be the selected one
                    487: 	    return selectOne.value;
1.118     ng        488: 	}
                    489:     }
                    490: </script>
                    491: COMMONJSFUNCTIONS
                    492: }
                    493: 
1.44      ng        494: #--- Dumps the class list with usernames,list of sections,
                    495: #--- section, ids and fullnames for each user.
                    496: sub getclasslist {
1.449     banghart  497:     my ($getsec,$filterlist,$getgroup) = @_;
1.291     albertel  498:     my @getsec;
1.450     banghart  499:     my @getgroup;
1.442     banghart  500:     my $stu_status = join(':',&Apache::loncommon::get_env_multiple('form.Status'));
1.291     albertel  501:     if (!ref($getsec)) {
                    502: 	if ($getsec ne '' && $getsec ne 'all') {
                    503: 	    @getsec=($getsec);
                    504: 	}
                    505:     } else {
                    506: 	@getsec=@{$getsec};
                    507:     }
                    508:     if (grep(/^all$/,@getsec)) { undef(@getsec); }
1.450     banghart  509:     if (!ref($getgroup)) {
                    510: 	if ($getgroup ne '' && $getgroup ne 'all') {
                    511: 	    @getgroup=($getgroup);
                    512: 	}
                    513:     } else {
                    514: 	@getgroup=@{$getgroup};
                    515:     }
                    516:     if (grep(/^all$/,@getgroup)) { undef(@getgroup); }
1.291     albertel  517: 
1.449     banghart  518:     my ($classlist,$keylist)=&Apache::loncoursedata::get_classlist();
1.49      albertel  519:     # Bail out if we were unable to get the classlist
1.56      matthew   520:     return if (! defined($classlist));
1.449     banghart  521:     &Apache::loncoursedata::get_group_memberships($classlist,$keylist);
1.56      matthew   522:     #
                    523:     my %sections;
                    524:     my %fullnames;
1.205     matthew   525:     foreach my $student (keys(%$classlist)) {
                    526:         my $end      = 
                    527:             $classlist->{$student}->[&Apache::loncoursedata::CL_END()];
                    528:         my $start    = 
                    529:             $classlist->{$student}->[&Apache::loncoursedata::CL_START()];
                    530:         my $id       = 
                    531:             $classlist->{$student}->[&Apache::loncoursedata::CL_ID()];
                    532:         my $section  = 
                    533:             $classlist->{$student}->[&Apache::loncoursedata::CL_SECTION()];
                    534:         my $fullname = 
                    535:             $classlist->{$student}->[&Apache::loncoursedata::CL_FULLNAME()];
                    536:         my $status   = 
                    537:             $classlist->{$student}->[&Apache::loncoursedata::CL_STATUS()];
1.449     banghart  538:         my $group   = 
                    539:             $classlist->{$student}->[&Apache::loncoursedata::CL_GROUP()];
1.76      ng        540: 	# filter students according to status selected
1.442     banghart  541: 	if ($filterlist && (!($stu_status =~ /Any/))) {
                    542: 	    if (!($stu_status =~ $status)) {
1.450     banghart  543: 		delete($classlist->{$student});
1.76      ng        544: 		next;
                    545: 	    }
                    546: 	}
1.450     banghart  547: 	# filter students according to groups selected
1.453     banghart  548: 	my @stu_groups = split(/,/,$group);
1.450     banghart  549: 	if (@getgroup) {
                    550: 	    my $exclude = 1;
1.454     banghart  551: 	    foreach my $grp (@getgroup) {
                    552: 	        foreach my $stu_group (@stu_groups) {
1.453     banghart  553: 	            if ($stu_group eq $grp) {
                    554: 	                $exclude = 0;
                    555:     	            } 
1.450     banghart  556: 	        }
1.453     banghart  557:     	        if (($grp eq 'none') && !$group) {
                    558:         	        $exclude = 0;
                    559:         	}
1.450     banghart  560: 	    }
                    561: 	    if ($exclude) {
                    562: 	        delete($classlist->{$student});
                    563: 	    }
                    564: 	}
1.205     matthew   565: 	$section = ($section ne '' ? $section : 'none');
1.106     albertel  566: 	if (&canview($section)) {
1.291     albertel  567: 	    if (!@getsec || grep(/^\Q$section\E$/,@getsec)) {
1.103     albertel  568: 		$sections{$section}++;
1.450     banghart  569: 		if ($classlist->{$student}) {
                    570: 		    $fullnames{$student}=$fullname;
                    571: 		}
1.103     albertel  572: 	    } else {
1.205     matthew   573: 		delete($classlist->{$student});
1.103     albertel  574: 	    }
                    575: 	} else {
1.205     matthew   576: 	    delete($classlist->{$student});
1.103     albertel  577: 	}
1.44      ng        578:     }
                    579:     my %seen = ();
1.56      matthew   580:     my @sections = sort(keys(%sections));
                    581:     return ($classlist,\@sections,\%fullnames);
1.44      ng        582: }
                    583: 
1.103     albertel  584: sub canmodify {
                    585:     my ($sec)=@_;
                    586:     if ($perm{'mgr'}) {
                    587: 	if (!defined($perm{'mgr_section'})) {
                    588: 	    # can modify whole class
                    589: 	    return 1;
                    590: 	} else {
                    591: 	    if ($sec eq $perm{'mgr_section'}) {
                    592: 		#can modify the requested section
                    593: 		return 1;
                    594: 	    } else {
                    595: 		# can't modify the request section
                    596: 		return 0;
                    597: 	    }
                    598: 	}
                    599:     }
                    600:     #can't modify
                    601:     return 0;
                    602: }
                    603: 
                    604: sub canview {
                    605:     my ($sec)=@_;
                    606:     if ($perm{'vgr'}) {
                    607: 	if (!defined($perm{'vgr_section'})) {
                    608: 	    # can modify whole class
                    609: 	    return 1;
                    610: 	} else {
                    611: 	    if ($sec eq $perm{'vgr_section'}) {
                    612: 		#can modify the requested section
                    613: 		return 1;
                    614: 	    } else {
                    615: 		# can't modify the request section
                    616: 		return 0;
                    617: 	    }
                    618: 	}
                    619:     }
                    620:     #can't modify
                    621:     return 0;
                    622: }
                    623: 
1.44      ng        624: #--- Retrieve the grade status of a student for all the parts
                    625: sub student_gradeStatus {
1.324     albertel  626:     my ($symb,$udom,$uname,$partlist) = @_;
1.257     albertel  627:     my %record     = &Apache::lonnet::restore($symb,$env{'request.course.id'},$udom,$uname);
1.44      ng        628:     my %partstatus = ();
                    629:     foreach (@$partlist) {
1.128     ng        630: 	my ($status,undef)   = split(/_/,$record{"resource.$_.solved"},2);
1.44      ng        631: 	$status              = 'nothing' if ($status eq '');
                    632: 	$partstatus{$_}      = $status;
                    633: 	my $subkey           = "resource.$_.submitted_by";
                    634: 	$partstatus{$subkey} = $record{$subkey} if ($record{$subkey} ne '');
                    635:     }
                    636:     return %partstatus;
                    637: }
                    638: 
1.45      ng        639: # hidden form and javascript that calls the form
                    640: # Use by verifyscript and viewgrades
                    641: # Shows a student's view of problem and submission
                    642: sub jscriptNform {
1.324     albertel  643:     my ($symb) = @_;
1.442     banghart  644:     my $stu_status = join(':',&Apache::loncommon::get_env_multiple('form.Status'));
1.45      ng        645:     my $jscript='<script type="text/javascript" language="javascript">'."\n".
                    646: 	'    function viewOneStudent(user,domain) {'."\n".
                    647: 	'	document.onestudent.student.value = user;'."\n".
                    648: 	'	document.onestudent.userdom.value = domain;'."\n".
                    649: 	'	document.onestudent.submit();'."\n".
                    650: 	'    }'."\n".
                    651: 	'</script>'."\n";
                    652:     $jscript.= '<form action="/adm/grades" method="post" name="onestudent">'."\n".
1.418     albertel  653: 	'<input type="hidden" name="symb"    value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
1.257     albertel  654: 	'<input type="hidden" name="saveState" value="'.$env{'form.saveState'}.'" />'."\n".
                    655: 	'<input type="hidden" name="probTitle" value="'.$env{'form.probTitle'}.'" />'."\n".
1.442     banghart  656: 	'<input type="hidden" name="Status"  value="'.$stu_status.'" />'."\n".
1.45      ng        657: 	'<input type="hidden" name="command" value="submission" />'."\n".
                    658: 	'<input type="hidden" name="student" value="" />'."\n".
                    659: 	'<input type="hidden" name="userdom" value="" />'."\n".
                    660: 	'</form>'."\n";
                    661:     return $jscript;
                    662: }
1.39      ng        663: 
1.447     foxr      664: 
                    665: 
1.315     bowersj2  666: # Given the score (as a number [0-1] and the weight) what is the final
                    667: # point value? This function will round to the nearest tenth, third,
                    668: # or quarter if one of those is within the tolerance of .00001.
1.316     albertel  669: sub compute_points {
1.315     bowersj2  670:     my ($score, $weight) = @_;
                    671:     
                    672:     my $tolerance = .00001;
                    673:     my $points = $score * $weight;
                    674: 
                    675:     # Check for nearness to 1/x.
                    676:     my $check_for_nearness = sub {
                    677:         my ($factor) = @_;
                    678:         my $num = ($points * $factor) + $tolerance;
                    679:         my $floored_num = floor($num);
1.316     albertel  680:         if ($num - $floored_num < 2 * $tolerance * $factor) {
1.315     bowersj2  681:             return $floored_num / $factor;
                    682:         }
                    683:         return $points;
                    684:     };
                    685: 
                    686:     $points = $check_for_nearness->(10);
                    687:     $points = $check_for_nearness->(3);
                    688:     $points = $check_for_nearness->(4);
                    689:     
                    690:     return $points;
                    691: }
                    692: 
1.44      ng        693: #------------------ End of general use routines --------------------
1.87      www       694: 
                    695: #
                    696: # Find most similar essay
                    697: #
                    698: 
                    699: sub most_similar {
1.426     albertel  700:     my ($uname,$udom,$uessay,$old_essays)=@_;
1.87      www       701: 
                    702: # ignore spaces and punctuation
                    703: 
                    704:     $uessay=~s/\W+/ /gs;
                    705: 
1.282     www       706: # ignore empty submissions (occuring when only files are sent)
                    707: 
                    708:     unless ($uessay=~/\w+/) { return ''; }
                    709: 
1.87      www       710: # these will be returned. Do not care if not at least 50 percent similar
1.88      www       711:     my $limit=0.6;
1.87      www       712:     my $sname='';
                    713:     my $sdom='';
                    714:     my $scrsid='';
                    715:     my $sessay='';
                    716: # go through all essays ...
1.426     albertel  717:     foreach my $tkey (keys(%$old_essays)) {
                    718: 	my ($tname,$tdom,$tcrsid)=map {&unescape($_)} (split(/\./,$tkey));
1.87      www       719: # ... except the same student
1.426     albertel  720:         next if (($tname eq $uname) && ($tdom eq $udom));
                    721: 	my $tessay=$old_essays->{$tkey};
                    722: 	$tessay=~s/\W+/ /gs;
1.87      www       723: # String similarity gives up if not even limit
1.426     albertel  724: 	my $tsimilar=&String::Similarity::similarity($uessay,$tessay,$limit);
1.87      www       725: # Found one
1.426     albertel  726: 	if ($tsimilar>$limit) {
                    727: 	    $limit=$tsimilar;
                    728: 	    $sname=$tname;
                    729: 	    $sdom=$tdom;
                    730: 	    $scrsid=$tcrsid;
                    731: 	    $sessay=$old_essays->{$tkey};
                    732: 	}
1.87      www       733:     }
1.88      www       734:     if ($limit>0.6) {
1.87      www       735:        return ($sname,$sdom,$scrsid,$sessay,$limit);
                    736:     } else {
                    737:        return ('','','','',0);
                    738:     }
                    739: }
                    740: 
1.44      ng        741: #-------------------------------------------------------------------
                    742: 
                    743: #------------------------------------ Receipt Verification Routines
1.45      ng        744: #
1.44      ng        745: #--- Check whether a receipt number is valid.---
                    746: sub verifyreceipt {
                    747:     my $request  = shift;
                    748: 
1.257     albertel  749:     my $courseid = $env{'request.course.id'};
1.184     www       750:     my $receipt  = &Apache::lonnet::recprefix($courseid).'-'.
1.257     albertel  751: 	$env{'form.receipt'};
1.44      ng        752:     $receipt     =~ s/[^\-\d]//g;
1.378     albertel  753:     my ($symb)   = &get_symb($request);
1.44      ng        754: 
1.487     albertel  755:     my $title.=
                    756: 	'<h3><span class="LC_info">'.
1.553     biermanm  757: 	&mt('Verifying  Receipt No. [_1]',$receipt).
1.487     albertel  758: 	'</span></h3>'."\n".
                    759: 	'<h4>'.&mt('<b>Resource: </b>[_1]',$env{'form.probTitle'}).
                    760: 	'</h4>'."\n";
1.44      ng        761: 
                    762:     my ($string,$contents,$matches) = ('','',0);
1.56      matthew   763:     my (undef,undef,$fullname) = &getclasslist('all','0');
1.177     albertel  764:     
                    765:     my $receiptparts=0;
1.390     albertel  766:     if ($env{"course.$courseid.receiptalg"} eq 'receipt2' ||
                    767: 	$env{"course.$courseid.receiptalg"} eq 'receipt3') { $receiptparts=1; }
1.177     albertel  768:     my $parts=['0'];
1.324     albertel  769:     if ($receiptparts) { ($parts)=&response_type($symb); }
1.486     albertel  770:     
                    771:     my $header = 
                    772: 	&Apache::loncommon::start_data_table().
                    773: 	&Apache::loncommon::start_data_table_header_row().
1.487     albertel  774: 	'<th>&nbsp;'.&mt('Fullname').'&nbsp;</th>'."\n".
                    775: 	'<th>&nbsp;'.&mt('Username').'&nbsp;</th>'."\n".
                    776: 	'<th>&nbsp;'.&mt('Domain').'&nbsp;</th>';
1.486     albertel  777:     if ($receiptparts) {
1.487     albertel  778: 	$header.='<th>&nbsp;'.&mt('Problem Part').'&nbsp;</th>';
1.486     albertel  779:     }
                    780:     $header.=
                    781: 	&Apache::loncommon::end_data_table_header_row();
                    782: 
1.294     albertel  783:     foreach (sort 
                    784: 	     {
                    785: 		 if (lc($$fullname{$a}) ne lc($$fullname{$b})) {
                    786: 		     return (lc($$fullname{$a}) cmp lc($$fullname{$b}));
                    787: 		 }
                    788: 		 return $a cmp $b;
                    789: 	     } (keys(%$fullname))) {
1.44      ng        790: 	my ($uname,$udom)=split(/\:/);
1.177     albertel  791: 	foreach my $part (@$parts) {
                    792: 	    if ($receipt eq &Apache::lonnet::ireceipt($uname,$udom,$courseid,$symb,$part)) {
1.486     albertel  793: 		$contents.=
                    794: 		    &Apache::loncommon::start_data_table_row().
                    795: 		    '<td>&nbsp;'."\n".
1.177     albertel  796: 		    '<a href="javascript:viewOneStudent(\''.$uname.'\',\''.$udom.
1.417     albertel  797: 		    '\');" target="_self">'.$$fullname{$_}.'</a>&nbsp;</td>'."\n".
1.177     albertel  798: 		    '<td>&nbsp;'.$uname.'&nbsp;</td>'.
                    799: 		    '<td>&nbsp;'.$udom.'&nbsp;</td>';
                    800: 		if ($receiptparts) {
                    801: 		    $contents.='<td>&nbsp;'.$part.'&nbsp;</td>';
                    802: 		}
1.486     albertel  803: 		$contents.= 
                    804: 		    &Apache::loncommon::end_data_table_row()."\n";
1.177     albertel  805: 		
                    806: 		$matches++;
                    807: 	    }
1.44      ng        808: 	}
                    809:     }
                    810:     if ($matches == 0) {
1.487     albertel  811: 	$string = $title.&mt('No match found for the above receipt.');
1.44      ng        812:     } else {
1.324     albertel  813: 	$string = &jscriptNform($symb).$title.
1.487     albertel  814: 	    '<p>'.
                    815: 	    &mt('The above receipt matches the following [numerate,_1,student].',$matches).
                    816: 	    '</p>'.
1.486     albertel  817: 	    $header.
                    818: 	    $contents.
                    819: 	    &Apache::loncommon::end_data_table()."\n";
1.44      ng        820:     }
1.324     albertel  821:     return $string.&show_grading_menu_form($symb);
1.44      ng        822: }
                    823: 
                    824: #--- This is called by a number of programs.
                    825: #--- Called from the Grading Menu - View/Grade an individual student
                    826: #--- Also called directly when one clicks on the subm button 
                    827: #    on the problem page.
1.30      ng        828: sub listStudents {
1.41      ng        829:     my ($request) = shift;
1.49      albertel  830: 
1.324     albertel  831:     my ($symb) = &get_symb($request);
1.257     albertel  832:     my $cdom      = $env{"course.$env{'request.course.id'}.domain"};
                    833:     my $cnum      = $env{"course.$env{'request.course.id'}.num"};
                    834:     my $getsec    = $env{'form.section'} eq '' ? 'all' : $env{'form.section'};
1.449     banghart  835:     my $getgroup  = $env{'form.group'} eq '' ? 'all' : $env{'form.group'};
1.257     albertel  836:     my $submitonly= $env{'form.submitonly'} eq '' ? 'all' : $env{'form.submitonly'};
1.548     bisitz    837:     my $viewgrade = $env{'form.showgrading'} eq 'yes' ? 'View/Grade/Regrade' : 'View';
1.257     albertel  838:     $env{'form.probTitle'} = $env{'form.probTitle'} eq '' ? 
                    839: 	&Apache::lonnet::gettitle($symb) : $env{'form.probTitle'};
1.49      albertel  840: 
1.548     bisitz    841:     my $result='<h3><span class="LC_info">&nbsp;'
                    842: 	.&mt("$viewgrade Submissions for a Student or a Group of Students")
1.485     albertel  843: 	.'</span></h3>';
1.118     ng        844: 
1.324     albertel  845:     my ($table,undef,$hdgrade,$partlist,$handgrade) = &showResourceInfo($symb,$env{'form.probTitle'},($env{'form.showgrading'} eq 'yes'));
1.49      albertel  846: 
1.559   ! raeburn   847:     my %lt = &Apache::lonlocal::texthash (
        !           848: 		'multiple' => 'Please select a student or group of students before clicking on the Next button.',
        !           849: 		'single'   => 'Please select the student before clicking on the Next button.',
        !           850: 	     );
1.45      ng        851:     $request->print(<<LISTJAVASCRIPT);
                    852: <script type="text/javascript" language="javascript">
1.110     ng        853:     function checkSelect(checkBox) {
                    854: 	var ctr=0;
                    855: 	var sense="";
                    856: 	if (checkBox.length > 1) {
                    857: 	    for (var i=0; i<checkBox.length; i++) {
                    858: 		if (checkBox[i].checked) {
                    859: 		    ctr++;
                    860: 		}
                    861: 	    }
1.485     albertel  862: 	    sense = '$lt{'multiple'}';
1.110     ng        863: 	} else {
                    864: 	    if (checkBox.checked) {
                    865: 		ctr = 1;
                    866: 	    }
1.485     albertel  867: 	    sense = '$lt{'single'}';
1.110     ng        868: 	}
                    869: 	if (ctr == 0) {
1.485     albertel  870: 	    alert(sense);
1.110     ng        871: 	    return false;
                    872: 	}
                    873: 	document.gradesub.submit();
                    874:     }
                    875: 
                    876:     function reLoadList(formname) {
1.112     ng        877: 	if (formname.saveStatusOld.value == pullDownSelection(formname.Status)) {return;}
1.110     ng        878: 	formname.command.value = 'submission';
                    879: 	formname.submit();
                    880:     }
1.45      ng        881: </script>
                    882: LISTJAVASCRIPT
                    883: 
1.118     ng        884:     &commonJSfunctions($request);
1.41      ng        885:     $request->print($result);
1.39      ng        886: 
1.401     albertel  887:     my $checkhdgrade = ($env{'form.handgrade'} eq 'yes' && scalar(@$partlist) > 1 ) ? 'checked="checked"' : '';
                    888:     my $checklastsub = $checkhdgrade eq '' ? 'checked="checked"' : '';
1.154     albertel  889:     my $gradeTable='<form action="/adm/grades" method="post" name="gradesub">'.
1.485     albertel  890: 	"\n".$table;
                    891: 	
                    892:     $gradeTable .= 
1.539     riegler   893: 	'&nbsp;<b>'.&mt('View Problem Text').': </b>'.
1.485     albertel  894: 	    '<label><input type="radio" name="vProb" value="no" checked="checked" /> '.&mt('no').' </label>'."\n".
                    895: 	    '<label><input type="radio" name="vProb" value="yes" /> '.&mt('one student').' </label>'."\n".
1.539     riegler   896: 	    '<label><input type="radio" name="vProb" value="all" /> '.&mt('all students').' </label><br />'."\n";
1.485     albertel  897:     $gradeTable .= 
1.539     riegler   898: 	'&nbsp;<b>'.&mt('View Answer').': </b>'.
1.485     albertel  899: 	    '<label><input type="radio" name="vAns" value="no"  /> '.&mt('no').' </label>'."\n".
                    900: 	    '<label><input type="radio" name="vAns" value="yes" /> '.&mt('one student').' </label>'."\n".
1.539     riegler   901: 	    '<label><input type="radio" name="vAns" value="all" checked="checked" /> '.&mt('all students').' </label><br />'."\n";
1.485     albertel  902: 
                    903:     my $submission_options;
1.257     albertel  904:     if ($env{'form.handgrade'} eq 'yes' && scalar(@$partlist) > 1) {
1.485     albertel  905: 	$submission_options.=
                    906: 	    '<label><input type="radio" name="lastSub" value="hdgrade" '.$checkhdgrade.' /> '.&mt('essay part only').' </label>'."\n";
1.49      albertel  907:     }
1.442     banghart  908:     my $stu_status = join(':',&Apache::loncommon::get_env_multiple('form.Status'));
                    909:     my $saveStatus = $stu_status eq '' ? 'Active' : $stu_status;
1.257     albertel  910:     $env{'form.Status'} = $saveStatus;
1.485     albertel  911:     $submission_options.=
                    912: 	'<label><input type="radio" name="lastSub" value="lastonly" '.$checklastsub.' /> '.&mt('last submission only').' </label>'."\n".
                    913: 	'<label><input type="radio" name="lastSub" value="last" /> '.&mt('last submission &amp; parts info').' </label>'."\n".
                    914: 	'<label><input type="radio" name="lastSub" value="datesub" /> '.&mt('by dates and submissions').' </label>'."\n".
                    915: 	'<label><input type="radio" name="lastSub" value="all" /> '.&mt('all details').'</label>';
                    916:     $gradeTable .= 
1.539     riegler   917: 	'&nbsp;<b>'.&mt('Submissions').': </b>'.$submission_options.'<br />'."\n";
1.485     albertel  918: 
                    919:     $gradeTable .= 
1.539     riegler   920:         '&nbsp;<b>'.&mt('Grading Increments').': </b>'.
1.485     albertel  921: 	    '<select name="increment">'.
                    922: 	    '<option value="1">'.&mt('Whole Points').'</option>'.
                    923: 	    '<option value=".5">'.&mt('Half Points').'</option>'.
                    924: 	    '<option value=".25">'.&mt('Quarter Points').'</option>'.
                    925: 	    '<option value=".1">'.&mt('Tenths of a Point').'</option>'.
1.539     riegler   926: 	    '</select>';
1.485     albertel  927:     
                    928:     $gradeTable .= 
1.432     banghart  929:         &build_section_inputs().
1.45      ng        930: 	'<input type="hidden" name="submitonly"  value="'.$submitonly.'" />'."\n".
1.257     albertel  931: 	'<input type="hidden" name="handgrade"   value="'.$env{'form.handgrade'}.'" /><br />'."\n".
                    932: 	'<input type="hidden" name="showgrading" value="'.$env{'form.showgrading'}.'" /><br />'."\n".
                    933: 	'<input type="hidden" name="saveState"   value="'.$env{'form.saveState'}.'" />'."\n".
                    934: 	'<input type="hidden" name="probTitle"   value="'.$env{'form.probTitle'}.'" />'."\n".
1.418     albertel  935: 	'<input type="hidden" name="symb" value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
1.110     ng        936: 	'<input type="hidden" name="saveStatusOld" value="'.$saveStatus.'" />'."\n";
                    937: 
1.257     albertel  938:     if (exists($env{'form.gradingMenu'}) && exists($env{'form.Status'})) {
1.442     banghart  939: 	$gradeTable.='<input type="hidden" name="Status"   value="'.$stu_status.'" />'."\n";
1.124     ng        940:     } else {
1.485     albertel  941: 	$gradeTable.=&mt('<b>Student Status:</b> [_1]',
                    942: 			 &Apache::lonhtmlcommon::StatusOptions($saveStatus,undef,1,'javascript:reLoadList(this.form);')).'<br />';
1.124     ng        943:     }
1.112     ng        944: 
1.548     bisitz    945:     $gradeTable.=&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.").'<br />'."\n".
1.110     ng        946: 	'<input type="hidden" name="command" value="processGroup" />'."\n";
1.249     albertel  947: 
                    948: # checkall buttons
                    949:     $gradeTable.=&check_script('gradesub', 'stuinfo');
1.110     ng        950:     $gradeTable.='<input type="button" '."\n".
1.45      ng        951: 	'onClick="javascript:checkSelect(this.form.stuinfo);" '."\n".
1.539     riegler   952: 	'value="'.&mt('Next').' &rarr;" /> <br />'."\n";
1.249     albertel  953:     $gradeTable.=&check_buttons();
1.485     albertel  954:     $gradeTable.='<label><input type="checkbox" name="checkPlag" checked="checked" />'.&mt('Check For Plagiarism').'</label>';
1.450     banghart  955:     my ($classlist, undef, $fullname) = &getclasslist($getsec,'1',$getgroup);
1.474     albertel  956:     $gradeTable.= &Apache::loncommon::start_data_table().
                    957: 	&Apache::loncommon::start_data_table_header_row();
1.110     ng        958:     my $loop = 0;
                    959:     while ($loop < 2) {
1.485     albertel  960: 	$gradeTable.='<th>'.&mt('No.').'</th><th>'.&mt('Select').'</th>'.
                    961: 	    '<th>'.&nameUserString('header').'&nbsp;'.&mt('Section/Group').'</th>';
1.301     albertel  962: 	if ($env{'form.showgrading'} eq 'yes' 
                    963: 	    && $submitonly ne 'queued'
                    964: 	    && $submitonly ne 'all') {
1.485     albertel  965: 	    foreach my $part (sort(@$partlist)) {
                    966: 		my $display_part=
                    967: 		    &get_display_part((split(/_/,$part))[0],$symb);
                    968: 		$gradeTable.=
                    969: 		    '<th>'.&mt('Part: [_1] Status',$display_part).'</th>';
1.110     ng        970: 	    }
1.301     albertel  971: 	} elsif ($submitonly eq 'queued') {
1.474     albertel  972: 	    $gradeTable.='<th>'.&mt('Queue Status').'&nbsp;</th>';
1.110     ng        973: 	}
                    974: 	$loop++;
1.126     ng        975: #	$gradeTable.='<td></td>' if ($loop%2 ==1);
1.41      ng        976:     }
1.474     albertel  977:     $gradeTable.=&Apache::loncommon::end_data_table_header_row()."\n";
1.41      ng        978: 
1.45      ng        979:     my $ctr = 0;
1.294     albertel  980:     foreach my $student (sort 
                    981: 			 {
                    982: 			     if (lc($$fullname{$a}) ne lc($$fullname{$b})) {
                    983: 				 return (lc($$fullname{$a}) cmp lc($$fullname{$b}));
                    984: 			     }
                    985: 			     return $a cmp $b;
                    986: 			 }
                    987: 			 (keys(%$fullname))) {
1.41      ng        988: 	my ($uname,$udom) = split(/:/,$student);
1.301     albertel  989: 
1.110     ng        990: 	my %status = ();
1.301     albertel  991: 
                    992: 	if ($submitonly eq 'queued') {
                    993: 	    my %queue_status = 
                    994: 		&Apache::bridgetask::get_student_status($symb,$cdom,$cnum,
                    995: 							$udom,$uname);
                    996: 	    next if (!defined($queue_status{'gradingqueue'}));
                    997: 	    $status{'gradingqueue'} = $queue_status{'gradingqueue'};
                    998: 	}
                    999: 
                   1000: 	if ($env{'form.showgrading'} eq 'yes' 
                   1001: 	    && $submitonly ne 'queued'
                   1002: 	    && $submitonly ne 'all') {
1.324     albertel 1003: 	    (%status) =&student_gradeStatus($symb,$udom,$uname,$partlist);
1.145     albertel 1004: 	    my $submitted = 0;
1.164     albertel 1005: 	    my $graded = 0;
1.248     albertel 1006: 	    my $incorrect = 0;
1.110     ng       1007: 	    foreach (keys(%status)) {
1.145     albertel 1008: 		$submitted = 1 if ($status{$_} ne 'nothing');
1.248     albertel 1009: 		$graded = 1 if ($status{$_} =~ /^ungraded/);
                   1010: 		$incorrect = 1 if ($status{$_} =~ /^incorrect/);
                   1011: 		
1.110     ng       1012: 		my ($foo,$partid,$foo1) = split(/\./,$_);
                   1013: 		if ($status{'resource.'.$partid.'.submitted_by'} ne '') {
1.145     albertel 1014: 		    $submitted = 0;
1.150     albertel 1015: 		    my ($part)=split(/\./,$partid);
1.110     ng       1016: 		    $gradeTable.='<input type="hidden" name="'.
1.150     albertel 1017: 			$student.':'.$part.':submitted_by" value="'.
1.110     ng       1018: 			$status{'resource.'.$partid.'.submitted_by'}.'" />';
                   1019: 		}
1.41      ng       1020: 	    }
1.248     albertel 1021: 	    
1.156     albertel 1022: 	    next if (!$submitted && ($submitonly eq 'yes' ||
                   1023: 				     $submitonly eq 'incorrect' ||
                   1024: 				     $submitonly eq 'graded'));
1.248     albertel 1025: 	    next if (!$graded && ($submitonly eq 'graded'));
                   1026: 	    next if (!$incorrect && $submitonly eq 'incorrect');
1.41      ng       1027: 	}
1.34      ng       1028: 
1.45      ng       1029: 	$ctr++;
1.249     albertel 1030: 	my $section = $classlist->{$student}->[&Apache::loncoursedata::CL_SECTION()];
1.452     banghart 1031:         my $group = $classlist->{$student}->[&Apache::loncoursedata::CL_GROUP()];
1.104     albertel 1032: 	if ( $perm{'vgr'} eq 'F' ) {
1.474     albertel 1033: 	    if ($ctr%2 ==1) {
                   1034: 		$gradeTable.= &Apache::loncommon::start_data_table_row();
                   1035: 	    }
1.126     ng       1036: 	    $gradeTable.='<td align="right">'.$ctr.'&nbsp;</td>'.
1.249     albertel 1037:                '<td align="center"><label><input type=checkbox name="stuinfo" value="'.
                   1038:                $student.':'.$$fullname{$student}.':::SECTION'.$section.
                   1039: 	       ')&nbsp;" />&nbsp;&nbsp;</label></td>'."\n".'<td>'.
                   1040: 	       &nameUserString(undef,$$fullname{$student},$uname,$udom).
1.474     albertel 1041: 	       '&nbsp;'.$section.($group ne '' ?'/'.$group:'').'</td>'."\n";
1.110     ng       1042: 
1.257     albertel 1043: 	    if ($env{'form.showgrading'} eq 'yes' && $submitonly ne 'all') {
1.524     raeburn  1044: 		foreach (sort(keys(%status))) {
1.485     albertel 1045: 		    next if ($_ =~ /^resource.*?submitted_by$/);
                   1046: 		    $gradeTable.='<td align="center">&nbsp;'.&mt($status{$_}).'&nbsp;</td>'."\n";
1.110     ng       1047: 		}
1.41      ng       1048: 	    }
1.126     ng       1049: #	    $gradeTable.='<td></td>' if ($ctr%2 ==1);
1.474     albertel 1050: 	    if ($ctr%2 ==0) {
                   1051: 		$gradeTable.=&Apache::loncommon::end_data_table_row()."\n";
                   1052: 	    }
1.41      ng       1053: 	}
                   1054:     }
1.110     ng       1055:     if ($ctr%2 ==1) {
1.126     ng       1056: 	$gradeTable.='<td>&nbsp;</td><td>&nbsp;</td><td>&nbsp;</td>';
1.301     albertel 1057: 	    if ($env{'form.showgrading'} eq 'yes' 
                   1058: 		&& $submitonly ne 'queued'
                   1059: 		&& $submitonly ne 'all') {
1.110     ng       1060: 		foreach (@$partlist) {
                   1061: 		    $gradeTable.='<td>&nbsp;</td>';
                   1062: 		}
1.301     albertel 1063: 	    } elsif ($submitonly eq 'queued') {
                   1064: 		$gradeTable.='<td>&nbsp;</td>';
1.110     ng       1065: 	    }
1.474     albertel 1066: 	$gradeTable.=&Apache::loncommon::end_data_table_row();
1.110     ng       1067:     }
                   1068: 
1.474     albertel 1069:     $gradeTable.=&Apache::loncommon::end_data_table()."\n".
1.45      ng       1070: 	'<input type="button" '.
                   1071: 	'onClick="javascript:checkSelect(this.form.stuinfo);" '.
1.539     riegler  1072: 	'value="'.&mt('Next').' &rarr;" /></form>'."\n";
1.45      ng       1073:     if ($ctr == 0) {
1.96      albertel 1074: 	my $num_students=(scalar(keys(%$fullname)));
                   1075: 	if ($num_students eq 0) {
1.485     albertel 1076: 	    $gradeTable='<br />&nbsp;<span class="LC_warning">'.&mt('There are no students currently enrolled.').'</span>';
1.96      albertel 1077: 	} else {
1.171     albertel 1078: 	    my $submissions='submissions';
                   1079: 	    if ($submitonly eq 'incorrect') { $submissions = 'incorrect submissions'; }
                   1080: 	    if ($submitonly eq 'graded'   ) { $submissions = 'ungraded submissions'; }
1.301     albertel 1081: 	    if ($submitonly eq 'queued'   ) { $submissions = 'queued submissions'; }
1.398     albertel 1082: 	    $gradeTable='<br />&nbsp;<span class="LC_warning">'.
1.485     albertel 1083: 		&mt('No '.$submissions.' found for this resource for any students. ([_1] students checked for '.$submissions.')',
                   1084: 		    $num_students).
                   1085: 		'</span><br />';
1.96      albertel 1086: 	}
1.46      ng       1087:     } elsif ($ctr == 1) {
1.474     albertel 1088: 	$gradeTable =~ s/type="checkbox"/type="checkbox" checked="checked"/;
1.45      ng       1089:     }
1.324     albertel 1090:     $gradeTable.=&show_grading_menu_form($symb);
1.45      ng       1091:     $request->print($gradeTable);
1.44      ng       1092:     return '';
1.10      ng       1093: }
                   1094: 
1.44      ng       1095: #---- Called from the listStudents routine
1.249     albertel 1096: 
                   1097: sub check_script {
                   1098:     my ($form, $type)=@_;
                   1099:     my $chkallscript='<script type="text/javascript">
                   1100:     function checkall() {
                   1101:         for (i=0; i<document.forms.'.$form.'.elements.length; i++) {
                   1102:             ele = document.forms.'.$form.'.elements[i];
                   1103:             if (ele.name == "'.$type.'") {
                   1104:             document.forms.'.$form.'.elements[i].checked=true;
                   1105:                                        }
                   1106:         }
                   1107:     }
                   1108: 
                   1109:     function checksec() {
                   1110:         for (i=0; i<document.forms.'.$form.'.elements.length; i++) {
                   1111:             ele = document.forms.'.$form.'.elements[i];
                   1112:            string = document.forms.'.$form.'.chksec.value;
                   1113:            if
                   1114:           (ele.value.indexOf(":::SECTION"+string)>0) {
                   1115:               document.forms.'.$form.'.elements[i].checked=true;
                   1116:             }
                   1117:         }
                   1118:     }
                   1119: 
                   1120: 
                   1121:     function uncheckall() {
                   1122:         for (i=0; i<document.forms.'.$form.'.elements.length; i++) {
                   1123:             ele = document.forms.'.$form.'.elements[i];
                   1124:             if (ele.name == "'.$type.'") {
                   1125:             document.forms.'.$form.'.elements[i].checked=false;
                   1126:                                        }
                   1127:         }
                   1128:     }
                   1129: 
                   1130: </script>'."\n";
                   1131:     return $chkallscript;
                   1132: }
                   1133: 
                   1134: sub check_buttons {
1.485     albertel 1135:     my $buttons.='<input type="button" onclick="checkall()" value="'.&mt('Check All').'" />';
                   1136:     $buttons.='<input type="button" onclick="uncheckall()" value="'.&mt('Uncheck All').'" />&nbsp;';
                   1137:     $buttons.='<input type="button" onclick="checksec()" value="'.&mt('Check Section/Group').'" />';
1.249     albertel 1138:     $buttons.='<input type="text" size="5" name="chksec" />&nbsp;';
                   1139:     return $buttons;
                   1140: }
                   1141: 
1.44      ng       1142: #     Displays the submissions for one student or a group of students
1.34      ng       1143: sub processGroup {
1.41      ng       1144:     my ($request)  = shift;
                   1145:     my $ctr        = 0;
1.155     albertel 1146:     my @stuchecked = &Apache::loncommon::get_env_multiple('form.stuinfo');
1.41      ng       1147:     my $total      = scalar(@stuchecked)-1;
1.45      ng       1148: 
1.396     banghart 1149:     foreach my $student (@stuchecked) {
                   1150: 	my ($uname,$udom,$fullname) = split(/:/,$student);
1.257     albertel 1151: 	$env{'form.student'}        = $uname;
                   1152: 	$env{'form.userdom'}        = $udom;
                   1153: 	$env{'form.fullname'}       = $fullname;
1.41      ng       1154: 	&submission($request,$ctr,$total);
                   1155: 	$ctr++;
                   1156:     }
                   1157:     return '';
1.35      ng       1158: }
1.34      ng       1159: 
1.44      ng       1160: #------------------------------------------------------------------------------------
                   1161: #
                   1162: #-------------------------- Next few routines handles grading by student, essentially
                   1163: #                           handles essay response type problem/part
                   1164: #
                   1165: #--- Javascript to handle the submission page functionality ---
                   1166: sub sub_page_js {
                   1167:     my $request = shift;
1.539     riegler  1168: 	    my $alertmsg = &mt('A number equal or greater than 0 is expected. Entered value = ');
1.44      ng       1169:     $request->print(<<SUBJAVASCRIPT);
                   1170: <script type="text/javascript" language="javascript">
1.71      ng       1171:     function updateRadio(formname,id,weight) {
1.125     ng       1172: 	var gradeBox = formname["GD_BOX"+id];
                   1173: 	var radioButton = formname["RADVAL"+id];
                   1174: 	var oldpts = formname["oldpts"+id].value;
1.72      ng       1175: 	var pts = checkSolved(formname,id) == 'update' ? gradeBox.value : oldpts;
1.71      ng       1176: 	gradeBox.value = pts;
                   1177: 	var resetbox = false;
                   1178: 	if (isNaN(pts) || pts < 0) {
1.539     riegler  1179: 	    alert("$alertmsg"+pts);
1.71      ng       1180: 	    for (var i=0; i<radioButton.length; i++) {
                   1181: 		if (radioButton[i].checked) {
                   1182: 		    gradeBox.value = i;
                   1183: 		    resetbox = true;
                   1184: 		}
                   1185: 	    }
                   1186: 	    if (!resetbox) {
                   1187: 		formtextbox.value = "";
                   1188: 	    }
                   1189: 	    return;
1.44      ng       1190: 	}
1.71      ng       1191: 
                   1192: 	if (pts > weight) {
                   1193: 	    var resp = confirm("You entered a value ("+pts+
                   1194: 			       ") greater than the weight for the part. Accept?");
                   1195: 	    if (resp == false) {
1.125     ng       1196: 		gradeBox.value = oldpts;
1.71      ng       1197: 		return;
                   1198: 	    }
1.44      ng       1199: 	}
1.13      albertel 1200: 
1.71      ng       1201: 	for (var i=0; i<radioButton.length; i++) {
                   1202: 	    radioButton[i].checked=false;
                   1203: 	    if (pts == i && pts != "") {
                   1204: 		radioButton[i].checked=true;
                   1205: 	    }
                   1206: 	}
                   1207: 	updateSelect(formname,id);
1.125     ng       1208: 	formname["stores"+id].value = "0";
1.41      ng       1209:     }
1.5       albertel 1210: 
1.72      ng       1211:     function writeBox(formname,id,pts) {
1.125     ng       1212: 	var gradeBox = formname["GD_BOX"+id];
1.71      ng       1213: 	if (checkSolved(formname,id) == 'update') {
                   1214: 	    gradeBox.value = pts;
                   1215: 	} else {
1.125     ng       1216: 	    var oldpts = formname["oldpts"+id].value;
1.72      ng       1217: 	    gradeBox.value = oldpts;
1.125     ng       1218: 	    var radioButton = formname["RADVAL"+id];
1.71      ng       1219: 	    for (var i=0; i<radioButton.length; i++) {
                   1220: 		radioButton[i].checked=false;
1.72      ng       1221: 		if (i == oldpts) {
1.71      ng       1222: 		    radioButton[i].checked=true;
                   1223: 		}
                   1224: 	    }
1.41      ng       1225: 	}
1.125     ng       1226: 	formname["stores"+id].value = "0";
1.71      ng       1227: 	updateSelect(formname,id);
                   1228: 	return;
1.41      ng       1229:     }
1.44      ng       1230: 
1.71      ng       1231:     function clearRadBox(formname,id) {
                   1232: 	if (checkSolved(formname,id) == 'noupdate') {
                   1233: 	    updateSelect(formname,id);
                   1234: 	    return;
                   1235: 	}
1.125     ng       1236: 	gradeSelect = formname["GD_SEL"+id];
1.71      ng       1237: 	for (var i=0; i<gradeSelect.length; i++) {
                   1238: 	    if (gradeSelect[i].selected) {
                   1239: 		var selectx=i;
                   1240: 	    }
                   1241: 	}
1.125     ng       1242: 	var stores = formname["stores"+id];
1.71      ng       1243: 	if (selectx == stores.value) { return };
1.125     ng       1244: 	var gradeBox = formname["GD_BOX"+id];
1.71      ng       1245: 	gradeBox.value = "";
1.125     ng       1246: 	var radioButton = formname["RADVAL"+id];
1.71      ng       1247: 	for (var i=0; i<radioButton.length; i++) {
                   1248: 	    radioButton[i].checked=false;
                   1249: 	}
                   1250: 	stores.value = selectx;
                   1251:     }
1.5       albertel 1252: 
1.71      ng       1253:     function checkSolved(formname,id) {
1.125     ng       1254: 	if (formname["solved"+id].value == "correct_by_student" && formname.overRideScore.value == 'no') {
1.118     ng       1255: 	    var reply = confirm("This problem has been graded correct by the computer. Do you want to change the score?");
                   1256: 	    if (!reply) {return "noupdate";}
1.120     ng       1257: 	    formname.overRideScore.value = 'yes';
1.41      ng       1258: 	}
1.71      ng       1259: 	return "update";
1.13      albertel 1260:     }
1.71      ng       1261: 
                   1262:     function updateSelect(formname,id) {
1.125     ng       1263: 	formname["GD_SEL"+id][0].selected = true;
1.71      ng       1264: 	return;
1.41      ng       1265:     }
1.33      ng       1266: 
1.121     ng       1267: //=========== Check that a point is assigned for all the parts  ============
1.71      ng       1268:     function checksubmit(formname,val,total,parttot) {
1.121     ng       1269: 	formname.gradeOpt.value = val;
1.71      ng       1270: 	if (val == "Save & Next") {
                   1271: 	    for (i=0;i<=total;i++) {
                   1272: 		for (j=0;j<parttot;j++) {
1.125     ng       1273: 		    var partid = formname["partid"+i+"_"+j].value;
1.127     ng       1274: 		    if (formname["GD_SEL"+i+"_"+partid][0].selected) {
1.125     ng       1275: 			var points = formname["GD_BOX"+i+"_"+partid].value;
1.71      ng       1276: 			if (points == "") {
1.125     ng       1277: 			    var name = formname["name"+i].value;
1.129     ng       1278: 			    var studentID = (name != '' ? name : formname["unamedom"+i].value);
                   1279: 			    var resp = confirm("You did not assign a score for "+studentID+
                   1280: 					       ", part "+partid+". Continue?");
1.71      ng       1281: 			    if (resp == false) {
1.125     ng       1282: 				formname["GD_BOX"+i+"_"+partid].focus();
1.71      ng       1283: 				return false;
                   1284: 			    }
                   1285: 			}
                   1286: 		    }
                   1287: 		    
                   1288: 		}
                   1289: 	    }
                   1290: 	    
                   1291: 	}
1.121     ng       1292: 	if (val == "Grade Student") {
                   1293: 	    formname.showgrading.value = "yes";
                   1294: 	    if (formname.Status.value == "") {
                   1295: 		formname.Status.value = "Active";
                   1296: 	    }
                   1297: 	    formname.studentNo.value = total;
                   1298: 	}
1.120     ng       1299: 	formname.submit();
                   1300:     }
                   1301: 
1.71      ng       1302: //======= Check that a score is assigned for all the problems (page/sequence grading only) =========
                   1303:     function checkSubmitPage(formname,total) {
                   1304: 	noscore = new Array(100);
                   1305: 	var ptr = 0;
                   1306: 	for (i=1;i<total;i++) {
1.125     ng       1307: 	    var partid = formname["q_"+i].value;
1.127     ng       1308: 	    if (formname["GD_SEL"+i+"_"+partid][0].selected) {
1.125     ng       1309: 		var points = formname["GD_BOX"+i+"_"+partid].value;
                   1310: 		var status = formname["solved"+i+"_"+partid].value;
1.71      ng       1311: 		if (points == "" && status != "correct_by_student") {
                   1312: 		    noscore[ptr] = i;
                   1313: 		    ptr++;
                   1314: 		}
                   1315: 	    }
                   1316: 	}
                   1317: 	if (ptr != 0) {
                   1318: 	    var sense = ptr == 1 ? ": " : "s: ";
                   1319: 	    var prolist = "";
                   1320: 	    if (ptr == 1) {
                   1321: 		prolist = noscore[0];
                   1322: 	    } else {
                   1323: 		var i = 0;
                   1324: 		while (i < ptr-1) {
                   1325: 		    prolist += noscore[i]+", ";
                   1326: 		    i++;
                   1327: 		}
                   1328: 		prolist += "and "+noscore[i];
                   1329: 	    }
                   1330: 	    var resp = confirm("You did not assign any score for the following problem"+sense+prolist+". Continue?");
                   1331: 	    if (resp == false) {
                   1332: 		return false;
                   1333: 	    }
                   1334: 	}
1.45      ng       1335: 
1.71      ng       1336: 	formname.submit();
                   1337:     }
                   1338: </script>
                   1339: SUBJAVASCRIPT
                   1340: }
1.45      ng       1341: 
1.71      ng       1342: #--- javascript for essay type problem --
                   1343: sub sub_page_kw_js {
                   1344:     my $request = shift;
1.80      ng       1345:     my $iconpath = $request->dir_config('lonIconsURL');
1.118     ng       1346:     &commonJSfunctions($request);
1.350     albertel 1347: 
1.351     albertel 1348:     my $inner_js_msg_central=<<INNERJS;
1.350     albertel 1349:     <script text="text/javascript">
                   1350:     function checkInput() {
                   1351:       opener.document.SCORE.msgsub.value = opener.checkEntities(document.msgcenter.msgsub.value);
                   1352:       var nmsg   = opener.document.SCORE.savemsgN.value;
                   1353:       var usrctr = document.msgcenter.usrctr.value;
                   1354:       var newval = opener.document.SCORE["newmsg"+usrctr];
                   1355:       newval.value = opener.checkEntities(document.msgcenter.newmsg.value);
                   1356: 
                   1357:       var msgchk = "";
                   1358:       if (document.msgcenter.subchk.checked) {
                   1359:          msgchk = "msgsub,";
                   1360:       }
                   1361:       var includemsg = 0;
                   1362:       for (var i=1; i<=nmsg; i++) {
                   1363:           var opnmsg = opener.document.SCORE["savemsg"+i];
                   1364:           var frmmsg = document.msgcenter["msg"+i];
                   1365:           opnmsg.value = opener.checkEntities(frmmsg.value);
                   1366:           var showflg = opener.document.SCORE["shownOnce"+i];
                   1367:           showflg.value = "1";
                   1368:           var chkbox = document.msgcenter["msgn"+i];
                   1369:           if (chkbox.checked) {
                   1370:              msgchk += "savemsg"+i+",";
                   1371:              includemsg = 1;
                   1372:           }
                   1373:       }
                   1374:       if (document.msgcenter.newmsgchk.checked) {
                   1375:          msgchk += "newmsg"+usrctr;
                   1376:          includemsg = 1;
                   1377:       }
                   1378:       imgformname = opener.document.SCORE["mailicon"+usrctr];
                   1379:       imgformname.src = "$iconpath/"+((includemsg) ? "mailto.gif" : "mailbkgrd.gif");
                   1380:       var includemsg = opener.document.SCORE["includemsg"+usrctr];
                   1381:       includemsg.value = msgchk;
                   1382: 
                   1383:       self.close()
                   1384: 
                   1385:     }
                   1386:     </script>
                   1387: INNERJS
                   1388: 
1.351     albertel 1389:     my $inner_js_highlight_central=<<INNERJS;
                   1390:  <script type="text/javascript">
                   1391:     function updateChoice(flag) {
                   1392:       opener.document.SCORE.kwclr.value = opener.radioSelection(document.hlCenter.kwdclr);
                   1393:       opener.document.SCORE.kwsize.value = opener.radioSelection(document.hlCenter.kwdsize);
                   1394:       opener.document.SCORE.kwstyle.value = opener.radioSelection(document.hlCenter.kwdstyle);
                   1395:       opener.document.SCORE.refresh.value = "on";
                   1396:       if (opener.document.SCORE.keywords.value!=""){
                   1397:          opener.document.SCORE.submit();
                   1398:       }
                   1399:       self.close()
                   1400:     }
                   1401: </script>
                   1402: INNERJS
                   1403: 
                   1404:     my $start_page_msg_central = 
                   1405:         &Apache::loncommon::start_page('Message Central',$inner_js_msg_central,
                   1406: 				       {'js_ready'  => 1,
                   1407: 					'only_body' => 1,
                   1408: 					'bgcolor'   =>'#FFFFFF',});
                   1409:     my $end_page_msg_central = 
                   1410: 	&Apache::loncommon::end_page({'js_ready' => 1});
                   1411: 
                   1412: 
                   1413:     my $start_page_highlight_central = 
                   1414:         &Apache::loncommon::start_page('Highlight Central',
                   1415: 				       $inner_js_highlight_central,
1.350     albertel 1416: 				       {'js_ready'  => 1,
                   1417: 					'only_body' => 1,
                   1418: 					'bgcolor'   =>'#FFFFFF',});
1.351     albertel 1419:     my $end_page_highlight_central = 
1.350     albertel 1420: 	&Apache::loncommon::end_page({'js_ready' => 1});
                   1421: 
1.219     www      1422:     my $docopen=&Apache::lonhtmlcommon::javascript_docopen();
1.236     albertel 1423:     $docopen=~s/^document\.//;
1.539     riegler  1424:     my $alertmsg = &mt('Please select a word or group of words from document and then click this link.');
1.71      ng       1425:     $request->print(<<SUBJAVASCRIPT);
                   1426: <script type="text/javascript" language="javascript">
1.45      ng       1427: 
1.44      ng       1428: //===================== Show list of keywords ====================
1.122     ng       1429:   function keywords(formname) {
                   1430:     var nret = prompt("Keywords list, separated by a space. Add/delete to list if desired.",formname.keywords.value);
1.44      ng       1431:     if (nret==null) return;
1.122     ng       1432:     formname.keywords.value = nret;
1.44      ng       1433: 
1.122     ng       1434:     if (formname.keywords.value != "") {
1.128     ng       1435: 	formname.refresh.value = "on";
1.122     ng       1436: 	formname.submit();
1.44      ng       1437:     }
                   1438:     return;
                   1439:   }
                   1440: 
                   1441: //===================== Script to view submitted by ==================
                   1442:   function viewSubmitter(submitter) {
                   1443:     document.SCORE.refresh.value = "on";
                   1444:     document.SCORE.NCT.value = "1";
                   1445:     document.SCORE.unamedom0.value = submitter;
                   1446:     document.SCORE.submit();
                   1447:     return;
                   1448:   }
                   1449: 
                   1450: //===================== Script to add keyword(s) ==================
                   1451:   function getSel() {
                   1452:     if (document.getSelection) txt = document.getSelection();
                   1453:     else if (document.selection) txt = document.selection.createRange().text;
                   1454:     else return;
                   1455:     var cleantxt = txt.replace(new RegExp('([\\f\\n\\r\\t\\v ])+', 'g')," ");
                   1456:     if (cleantxt=="") {
1.539     riegler  1457: 	alert("$alertmsg");
1.44      ng       1458: 	return;
                   1459:     }
                   1460:     var nret = prompt("Add selection to keyword list? Edit if desired.",cleantxt);
                   1461:     if (nret==null) return;
1.127     ng       1462:     document.SCORE.keywords.value = document.SCORE.keywords.value+" "+nret;
1.44      ng       1463:     if (document.SCORE.keywords.value != "") {
1.127     ng       1464: 	document.SCORE.refresh.value = "on";
1.44      ng       1465: 	document.SCORE.submit();
                   1466:     }
                   1467:     return;
                   1468:   }
                   1469: 
                   1470: //====================== Script for composing message ==============
1.80      ng       1471:    // preload images
                   1472:    img1 = new Image();
                   1473:    img1.src = "$iconpath/mailbkgrd.gif";
                   1474:    img2 = new Image();
                   1475:    img2.src = "$iconpath/mailto.gif";
                   1476: 
1.44      ng       1477:   function msgCenter(msgform,usrctr,fullname) {
                   1478:     var Nmsg  = msgform.savemsgN.value;
                   1479:     savedMsgHeader(Nmsg,usrctr,fullname);
                   1480:     var subject = msgform.msgsub.value;
1.127     ng       1481:     var msgchk = document.SCORE["includemsg"+usrctr].value;
1.44      ng       1482:     re = /msgsub/;
                   1483:     var shwsel = "";
                   1484:     if (re.test(msgchk)) { shwsel = "checked" }
1.123     ng       1485:     subject = (document.SCORE.shownSub.value == 0 ? checkEntities(subject) : subject);
                   1486:     displaySubject(checkEntities(subject),shwsel);
1.44      ng       1487:     for (var i=1; i<=Nmsg; i++) {
1.123     ng       1488: 	var testmsg = "savemsg"+i+",";
                   1489: 	re = new RegExp(testmsg,"g");
1.44      ng       1490: 	shwsel = "";
                   1491: 	if (re.test(msgchk)) { shwsel = "checked" }
1.125     ng       1492: 	var message = document.SCORE["savemsg"+i].value;
1.126     ng       1493: 	message = (document.SCORE["shownOnce"+i].value == 0 ? checkEntities(message) : message);
1.123     ng       1494: 	displaySavedMsg(i,message,shwsel); //I do not get it. w/o checkEntities on saved messages,
                   1495: 	                                   //any &lt; is already converted to <, etc. However, only once!!
1.44      ng       1496:     }
1.125     ng       1497:     newmsg = document.SCORE["newmsg"+usrctr].value;
1.44      ng       1498:     shwsel = "";
                   1499:     re = /newmsg/;
                   1500:     if (re.test(msgchk)) { shwsel = "checked" }
                   1501:     newMsg(newmsg,shwsel);
                   1502:     msgTail(); 
                   1503:     return;
                   1504:   }
                   1505: 
1.123     ng       1506:   function checkEntities(strx) {
                   1507:     if (strx.length == 0) return strx;
                   1508:     var orgStr = ["&", "<", ">", '"']; 
                   1509:     var newStr = ["&amp;", "&lt;", "&gt;", "&quot;"];
                   1510:     var counter = 0;
                   1511:     while (counter < 4) {
                   1512: 	strx = strReplace(strx,orgStr[counter],newStr[counter]);
                   1513: 	counter++;
                   1514:     }
                   1515:     return strx;
                   1516:   }
                   1517: 
                   1518:   function strReplace(strx, orgStr, newStr) {
                   1519:     return strx.split(orgStr).join(newStr);
                   1520:   }
                   1521: 
1.44      ng       1522:   function savedMsgHeader(Nmsg,usrctr,fullname) {
1.76      ng       1523:     var height = 70*Nmsg+250;
1.44      ng       1524:     var scrollbar = "no";
                   1525:     if (height > 600) {
                   1526: 	height = 600;
                   1527: 	scrollbar = "yes";
                   1528:     }
1.118     ng       1529:     var xpos = (screen.width-600)/2;
                   1530:     xpos = (xpos < 0) ? '0' : xpos;
                   1531:     var ypos = (screen.height-height)/2-30;
                   1532:     ypos = (ypos < 0) ? '0' : ypos;
                   1533: 
1.206     albertel 1534:     pWin = window.open('', 'MessageCenter', 'resizable=yes,toolbar=no,location=no,scrollbars='+scrollbar+',screenx='+xpos+',screeny='+ypos+',width=600,height='+height);
1.76      ng       1535:     pWin.focus();
                   1536:     pDoc = pWin.document;
1.219     www      1537:     pDoc.$docopen;
1.351     albertel 1538:     pDoc.write('$start_page_msg_central');
1.76      ng       1539: 
                   1540:     pDoc.write("<form action=\\"inactive\\" name=\\"msgcenter\\">");
                   1541:     pDoc.write("<input value=\\""+usrctr+"\\" name=\\"usrctr\\" type=\\"hidden\\">");
1.465     albertel 1542:     pDoc.write("<h3><span class=\\"LC_info\\">&nbsp;Compose Message for \"+fullname+\"<\\/span><\\/h3><br /><br />");
1.76      ng       1543: 
                   1544:     pDoc.write("<table border=0 width=100%><tr><td bgcolor=\\"#777777\\">");
                   1545:     pDoc.write("<table border=0 width=100%><tr bgcolor=\\"#ddffff\\">");
1.465     albertel 1546:     pDoc.write("<td><b>Type<\\/b><\\/td><td><b>Include<\\/b><\\/td><td><b>Message<\\/td><\\/tr>");
1.44      ng       1547: }
                   1548:     function displaySubject(msg,shwsel) {
1.76      ng       1549:     pDoc = pWin.document;
                   1550:     pDoc.write("<tr bgcolor=\\"#ffffdd\\">");
1.465     albertel 1551:     pDoc.write("<td>Subject<\\/td>");
                   1552:     pDoc.write("<td align=\\"center\\"><input name=\\"subchk\\" type=\\"checkbox\\"" +shwsel+"><\\/td>");
                   1553:     pDoc.write("<td><input name=\\"msgsub\\" type=\\"text\\" value=\\""+msg+"\\"size=\\"60\\" maxlength=\\"80\\"><\\/td><\\/tr>");
1.44      ng       1554: }
                   1555: 
1.72      ng       1556:   function displaySavedMsg(ctr,msg,shwsel) {
1.76      ng       1557:     pDoc = pWin.document;
                   1558:     pDoc.write("<tr bgcolor=\\"#ffffdd\\">");
1.465     albertel 1559:     pDoc.write("<td align=\\"center\\">"+ctr+"<\\/td>");
                   1560:     pDoc.write("<td align=\\"center\\"><input name=\\"msgn"+ctr+"\\" type=\\"checkbox\\"" +shwsel+"><\\/td>");
                   1561:     pDoc.write("<td><textarea name=\\"msg"+ctr+"\\" cols=\\"60\\" rows=\\"3\\">"+msg+"<\\/textarea><\\/td><\\/tr>");
1.44      ng       1562: }
                   1563: 
                   1564:   function newMsg(newmsg,shwsel) {
1.76      ng       1565:     pDoc = pWin.document;
                   1566:     pDoc.write("<tr bgcolor=\\"#ffffdd\\">");
1.465     albertel 1567:     pDoc.write("<td align=\\"center\\">New<\\/td>");
                   1568:     pDoc.write("<td align=\\"center\\"><input name=\\"newmsgchk\\" type=\\"checkbox\\"" +shwsel+"><\\/td>");
                   1569:     pDoc.write("<td><textarea name=\\"newmsg\\" cols=\\"60\\" rows=\\"3\\" onchange=\\"javascript:this.form.newmsgchk.checked=true\\" >"+newmsg+"<\\/textarea><\\/td><\\/tr>");
1.44      ng       1570: }
                   1571: 
                   1572:   function msgTail() {
1.76      ng       1573:     pDoc = pWin.document;
1.465     albertel 1574:     pDoc.write("<\\/table>");
                   1575:     pDoc.write("<\\/td><\\/tr><\\/table>&nbsp;");
1.76      ng       1576:     pDoc.write("<input type=\\"button\\" value=\\"Save\\" onClick=\\"javascript:checkInput()\\">&nbsp;&nbsp;");
1.326     albertel 1577:     pDoc.write("<input type=\\"button\\" value=\\"Cancel\\" onClick=\\"self.close()\\"><br /><br />");
1.465     albertel 1578:     pDoc.write("<\\/form>");
1.351     albertel 1579:     pDoc.write('$end_page_msg_central');
1.128     ng       1580:     pDoc.close();
1.44      ng       1581: }
                   1582: 
                   1583: //====================== Script for keyword highlight options ==============
                   1584:   function kwhighlight() {
                   1585:     var kwclr    = document.SCORE.kwclr.value;
                   1586:     var kwsize   = document.SCORE.kwsize.value;
                   1587:     var kwstyle  = document.SCORE.kwstyle.value;
                   1588:     var redsel = "";
                   1589:     var grnsel = "";
                   1590:     var blusel = "";
                   1591:     if (kwclr=="red")   {var redsel="checked"};
                   1592:     if (kwclr=="green") {var grnsel="checked"};
                   1593:     if (kwclr=="blue")  {var blusel="checked"};
                   1594:     var sznsel = "";
                   1595:     var sz1sel = "";
                   1596:     var sz2sel = "";
                   1597:     if (kwsize=="0")  {var sznsel="checked"};
                   1598:     if (kwsize=="+1") {var sz1sel="checked"};
                   1599:     if (kwsize=="+2") {var sz2sel="checked"};
                   1600:     var synsel = "";
                   1601:     var syisel = "";
                   1602:     var sybsel = "";
                   1603:     if (kwstyle=="")    {var synsel="checked"};
                   1604:     if (kwstyle=="<i>") {var syisel="checked"};
                   1605:     if (kwstyle=="<b>") {var sybsel="checked"};
                   1606:     highlightCentral();
                   1607:     highlightbody('red','red',redsel,'0','normal',sznsel,'','normal',synsel);
                   1608:     highlightbody('green','green',grnsel,'+1','+1',sz1sel,'<i>','italic',syisel);
                   1609:     highlightbody('blue','blue',blusel,'+2','+2',sz2sel,'<b>','bold',sybsel);
                   1610:     highlightend();
                   1611:     return;
                   1612:   }
                   1613: 
                   1614:   function highlightCentral() {
1.76      ng       1615: //    if (window.hwdWin) window.hwdWin.close();
1.118     ng       1616:     var xpos = (screen.width-400)/2;
                   1617:     xpos = (xpos < 0) ? '0' : xpos;
                   1618:     var ypos = (screen.height-330)/2-30;
                   1619:     ypos = (ypos < 0) ? '0' : ypos;
                   1620: 
1.206     albertel 1621:     hwdWin = window.open('', 'KeywordHighlightCentral', 'resizeable=yes,toolbar=no,location=no,scrollbars=no,width=400,height=300,screenx='+xpos+',screeny='+ypos);
1.76      ng       1622:     hwdWin.focus();
                   1623:     var hDoc = hwdWin.document;
1.219     www      1624:     hDoc.$docopen;
1.351     albertel 1625:     hDoc.write('$start_page_highlight_central');
1.76      ng       1626:     hDoc.write("<form action=\\"inactive\\" name=\\"hlCenter\\">");
1.465     albertel 1627:     hDoc.write("<h3><span class=\\"LC_info\\">&nbsp;Keyword Highlight Options<\\/span><\\/h3><br /><br />");
1.76      ng       1628: 
                   1629:     hDoc.write("<table border=0 width=100%><tr><td bgcolor=\\"#777777\\">");
                   1630:     hDoc.write("<table border=0 width=100%><tr bgcolor=\\"#ddffff\\">");
1.465     albertel 1631:     hDoc.write("<td><b>Text Color<\\/b><\\/td><td><b>Font Size<\\/b><\\/td><td><b>Font Style<\\/td><\\/tr>");
1.44      ng       1632:   }
                   1633: 
                   1634:   function highlightbody(clrval,clrtxt,clrsel,szval,sztxt,szsel,syval,sytxt,sysel) { 
1.76      ng       1635:     var hDoc = hwdWin.document;
                   1636:     hDoc.write("<tr bgcolor=\\"#ffffdd\\">");
                   1637:     hDoc.write("<td align=\\"left\\">");
1.465     albertel 1638:     hDoc.write("<input name=\\"kwdclr\\" type=\\"radio\\" value=\\""+clrval+"\\" "+clrsel+">&nbsp;"+clrtxt+"<\\/td>");
1.76      ng       1639:     hDoc.write("<td align=\\"left\\">");
1.465     albertel 1640:     hDoc.write("<input name=\\"kwdsize\\" type=\\"radio\\" value=\\""+szval+"\\" "+szsel+">&nbsp;"+sztxt+"<\\/td>");
1.76      ng       1641:     hDoc.write("<td align=\\"left\\">");
1.465     albertel 1642:     hDoc.write("<input name=\\"kwdstyle\\" type=\\"radio\\" value=\\""+syval+"\\" "+sysel+">&nbsp;"+sytxt+"<\\/td>");
                   1643:     hDoc.write("<\\/tr>");
1.44      ng       1644:   }
                   1645: 
                   1646:   function highlightend() { 
1.76      ng       1647:     var hDoc = hwdWin.document;
1.465     albertel 1648:     hDoc.write("<\\/table>");
                   1649:     hDoc.write("<\\/td><\\/tr><\\/table>&nbsp;");
1.76      ng       1650:     hDoc.write("<input type=\\"button\\" value=\\"Save\\" onClick=\\"javascript:updateChoice(1)\\">&nbsp;&nbsp;");
1.326     albertel 1651:     hDoc.write("<input type=\\"button\\" value=\\"Cancel\\" onClick=\\"self.close()\\"><br /><br />");
1.465     albertel 1652:     hDoc.write("<\\/form>");
1.351     albertel 1653:     hDoc.write('$end_page_highlight_central');
1.128     ng       1654:     hDoc.close();
1.44      ng       1655:   }
                   1656: 
                   1657: </script>
                   1658: SUBJAVASCRIPT
                   1659: }
                   1660: 
1.349     albertel 1661: sub get_increment {
1.348     bowersj2 1662:     my $increment = $env{'form.increment'};
                   1663:     if ($increment != 1 && $increment != .5 && $increment != .25 &&
                   1664:         $increment != .1) {
                   1665:         $increment = 1;
                   1666:     }
                   1667:     return $increment;
                   1668: }
                   1669: 
1.71      ng       1670: #--- displays the grading box, used in essay type problem and grading by page/sequence
                   1671: sub gradeBox {
1.322     albertel 1672:     my ($request,$symb,$uname,$udom,$counter,$partid,$record) = @_;
1.381     albertel 1673:     my $checkIcon = '<img alt="'.&mt('Check Mark').
1.485     albertel 1674: 	'" src="'.&Apache::loncommon::lonhttpdurl($request->dir_config('lonIconsURL').'/check.gif').'" height="16" border="0" />';
1.71      ng       1675:     my $wgt    = &Apache::lonnet::EXT('resource.'.$partid.'.weight',$symb,$udom,$uname);
1.466     albertel 1676:     my $wgtmsg = ($wgt > 0) ? &mt('(problem weight)') 
                   1677:                            : '<span class="LC_info">'.&mt('problem weight assigned by computer').'</span>';
1.71      ng       1678:     $wgt       = ($wgt > 0 ? $wgt : '1');
                   1679:     my $score  = ($$record{'resource.'.$partid.'.awarded'} eq '' ?
1.320     albertel 1680: 		  '' : &compute_points($$record{'resource.'.$partid.'.awarded'},$wgt));
1.71      ng       1681:     my $result='<input type="hidden" name="WGT'.$counter.'_'.$partid.'" value="'.$wgt.'" />'."\n";
1.466     albertel 1682:     my $display_part= &get_display_part($partid,$symb);
1.270     albertel 1683:     my %last_resets = &get_last_resets($symb,$env{'request.course.id'},
                   1684: 				       [$partid]);
                   1685:     my $aggtries = $$record{'resource.'.$partid.'.tries'};
1.269     raeburn  1686:     if ($last_resets{$partid}) {
                   1687:         $aggtries = &get_num_tries($record,$last_resets{$partid},$partid);
                   1688:     }
1.485     albertel 1689:     $result.='<table border="0"><tr>';
1.71      ng       1690:     my $ctr = 0;
1.348     bowersj2 1691:     my $thisweight = 0;
1.349     albertel 1692:     my $increment = &get_increment();
1.485     albertel 1693: 
                   1694:     my $radio.='<table border="0"><tr>'."\n";  # display radio buttons in a nice table 10 across
1.348     bowersj2 1695:     while ($thisweight<=$wgt) {
1.532     bisitz   1696: 	$radio.= '<td><span class="LC_nobreak"><label><input type="radio" name="RADVAL'.$counter.'_'.$partid.'" '.
1.71      ng       1697: 	    'onclick="javascript:writeBox(this.form,\''.$counter.'_'.$partid.'\','.
1.348     bowersj2 1698: 	    $thisweight.')" value="'.$thisweight.'" '.
1.401     albertel 1699: 	    ($score eq $thisweight ? 'checked="checked"':'').' /> '.$thisweight."</label></span></td>\n";
1.485     albertel 1700: 	$radio.=(($ctr+1)%10 == 0 ? '</tr><tr>' : '');
1.348     bowersj2 1701:         $thisweight += $increment;
1.71      ng       1702: 	$ctr++;
                   1703:     }
1.485     albertel 1704:     $radio.='</tr></table>';
                   1705: 
                   1706:     my $line.='<input type="text" name="GD_BOX'.$counter.'_'.$partid.'"'.
1.71      ng       1707: 	($score ne ''? ' value = "'.$score.'"':'').' size="4" '.
                   1708: 	'onChange="javascript:updateRadio(this.form,\''.$counter.'_'.$partid.'\','.
                   1709: 	$wgt.')" /></td>'."\n";
1.485     albertel 1710:     $line.='<td>/'.$wgt.' '.$wgtmsg.
1.71      ng       1711: 	($$record{'resource.'.$partid.'.solved'} eq 'correct_by_student' ? '&nbsp;'.$checkIcon : '').
1.540     riegler  1712: 	' </td><td><b>'.&mt('Grade Status').':</b>'."\n";
1.485     albertel 1713:     $line.='<select name="GD_SEL'.$counter.'_'.$partid.'" '.
1.71      ng       1714: 	'onChange="javascript:clearRadBox(this.form,\''.$counter.'_'.$partid.'\')" >'."\n";
                   1715:     if ($$record{'resource.'.$partid.'.solved'} eq 'excused') {
1.485     albertel 1716: 	$line.='<option></option>'.
                   1717: 	    '<option value="excused" selected="selected">'.&mt('excused').'</option>';
1.71      ng       1718:     } else {
1.485     albertel 1719: 	$line.='<option selected="selected"></option>'.
                   1720: 	    '<option value="excused" >'.&mt('excused').'</option>';
1.71      ng       1721:     }
1.485     albertel 1722:     $line.='<option value="reset status">'.&mt('reset status').'</option></select>'."\n";
                   1723: 
                   1724: 
1.540     riegler  1725: 	#&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 1726:     $result .= 
1.540     riegler  1727: 	    '<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 1728:     
                   1729:     $result.='</tr></table>'."\n";
1.71      ng       1730:     $result.='<input type="hidden" name="stores'.$counter.'_'.$partid.'" value="" />'."\n".
                   1731: 	'<input type="hidden" name="oldpts'.$counter.'_'.$partid.'" value="'.$score.'" />'."\n".
                   1732: 	'<input type="hidden" name="solved'.$counter.'_'.$partid.'" value="'.
1.269     raeburn  1733: 	$$record{'resource.'.$partid.'.solved'}.'" />'."\n".
                   1734:         '<input type="hidden" name="totaltries'.$counter.'_'.$partid.'" value="'.
                   1735:         $$record{'resource.'.$partid.'.tries'}.'" />'."\n".
                   1736:         '<input type="hidden" name="aggtries'.$counter.'_'.$partid.'" value="'.
                   1737:         $aggtries.'" />'."\n";
1.323     banghart 1738:     $result.=&handback_box($symb,$uname,$udom,$counter,$partid,$record);
1.318     banghart 1739:     return $result;
                   1740: }
1.322     albertel 1741: 
                   1742: sub handback_box {
1.323     banghart 1743:     my ($symb,$uname,$udom,$counter,$partid,$record) = @_;
1.324     albertel 1744:     my ($partlist,$handgrade,$responseType) = &response_type($symb);
1.323     banghart 1745:     my (@respids);
1.375     albertel 1746:      my @part_response_id = &flatten_responseType($responseType);
                   1747:     foreach my $part_response_id (@part_response_id) {
                   1748:     	my ($part,$resp) = @{ $part_response_id };
1.323     banghart 1749:         if ($part eq $partid) {
1.375     albertel 1750:             push(@respids,$resp);
1.323     banghart 1751:         }
                   1752:     }
1.318     banghart 1753:     my $result;
1.323     banghart 1754:     foreach my $respid (@respids) {
1.322     albertel 1755: 	my $prefix = $counter.'_'.$partid.'_'.$respid.'_';
                   1756: 	my $files=&get_submitted_files($udom,$uname,$partid,$respid,$record);
                   1757: 	next if (!@$files);
                   1758: 	my $file_counter = 1;
1.313     banghart 1759: 	foreach my $file (@$files) {
1.368     banghart 1760: 	    if ($file =~ /\/portfolio\//) {
                   1761:     	        my ($file_path, $file_disp) = ($file =~ m|(.+/)(.+)$|);
                   1762:     	        my ($name,$version,$ext) = &file_name_version_ext($file_disp);
                   1763:     	        $file_disp = "$name.$ext";
                   1764:     	        $file = $file_path.$file_disp;
                   1765:     	        $result.=&mt('Return commented version of [_1] to student.',
                   1766:     			 '<span class="LC_filename">'.$file_disp.'</span>');
                   1767:     	        $result.='<input type="file"   name="'.$prefix.'returndoc'.$file_counter.'" />'."\n";
                   1768:     	        $result.='<input type="hidden" name="'.$prefix.'origdoc'.$file_counter.'" value="'.$file.'" /><br />';
1.485     albertel 1769:     	        $result.='('.&mt('File will be uploaded when you click on Save &amp; Next below.').')<br />';
1.368     banghart 1770:     	        $file_counter++;
                   1771: 	    }
1.322     albertel 1772: 	}
1.313     banghart 1773:     }
1.318     banghart 1774:     return $result;    
1.71      ng       1775: }
1.44      ng       1776: 
1.58      albertel 1777: sub show_problem {
1.382     albertel 1778:     my ($request,$symb,$uname,$udom,$removeform,$viewon,$mode,$form) = @_;
1.144     albertel 1779:     my $rendered;
1.382     albertel 1780:     my %form = ((ref($form) eq 'HASH')? %{$form} : ());
1.329     albertel 1781:     &Apache::lonxml::remember_problem_counter();
1.144     albertel 1782:     if ($mode eq 'both' or $mode eq 'text') {
                   1783: 	$rendered=&Apache::loncommon::get_student_view($symb,$uname,$udom,
1.382     albertel 1784: 						       $env{'request.course.id'},
                   1785: 						       undef,\%form);
1.144     albertel 1786:     }
1.58      albertel 1787:     if ($removeform) {
                   1788: 	$rendered=~s|<form(.*?)>||g;
                   1789: 	$rendered=~s|</form>||g;
1.374     albertel 1790: 	$rendered=~s|(<input[^>]*name\s*=\s*"?)(\w+)("?)|$1would_have_been_$2$3|g;
1.58      albertel 1791:     }
1.144     albertel 1792:     my $companswer;
                   1793:     if ($mode eq 'both' or $mode eq 'answer') {
1.329     albertel 1794: 	&Apache::lonxml::restore_problem_counter();
1.382     albertel 1795: 	$companswer=
                   1796: 	    &Apache::loncommon::get_student_answers($symb,$uname,$udom,
                   1797: 						    $env{'request.course.id'},
                   1798: 						    %form);
1.144     albertel 1799:     }
1.58      albertel 1800:     if ($removeform) {
                   1801: 	$companswer=~s|<form(.*?)>||g;
                   1802: 	$companswer=~s|</form>||g;
1.144     albertel 1803: 	$companswer=~s|name="submit"|name="would_have_been_submit"|g;
1.58      albertel 1804:     }
1.468     albertel 1805:     $rendered=
                   1806: 	'<div class="LC_grade_show_problem_header">'.
                   1807: 	&mt('View of the problem').
                   1808: 	'</div><div class="LC_grade_show_problem_problem">'.
                   1809: 	$rendered.
                   1810: 	'</div>';
                   1811:     $companswer=
                   1812: 	'<div class="LC_grade_show_problem_header">'.
                   1813: 	&mt('Correct answer').
                   1814: 	'</div><div class="LC_grade_show_problem_problem">'.
                   1815: 	$companswer.
                   1816: 	'</div>';
                   1817:     my $result;
1.144     albertel 1818:     if ($mode eq 'both') {
1.468     albertel 1819: 	$result=$rendered.$companswer;
1.144     albertel 1820:     } elsif ($mode eq 'text') {
1.468     albertel 1821: 	$result=$rendered;
1.144     albertel 1822:     } elsif ($mode eq 'answer') {
1.468     albertel 1823: 	$result=$companswer;
1.144     albertel 1824:     }
1.468     albertel 1825:     $result='<div class="LC_grade_show_problem">'.$result.'</div>';
1.71      ng       1826:     return $result;
1.58      albertel 1827: }
1.397     albertel 1828: 
1.396     banghart 1829: sub files_exist {
                   1830:     my ($r, $symb) = @_;
                   1831:     my @students = &Apache::loncommon::get_env_multiple('form.stuinfo');
1.397     albertel 1832: 
1.396     banghart 1833:     foreach my $student (@students) {
                   1834:         my ($uname,$udom,$fullname) = split(/:/,$student);
1.397     albertel 1835:         my %record = &Apache::lonnet::restore($symb,$env{'request.course.id'},
                   1836: 					      $udom,$uname);
1.396     banghart 1837:         my ($string,$timestamp)= &get_last_submission(\%record);
1.397     albertel 1838:         foreach my $submission (@$string) {
                   1839:             my ($partid,$respid) =
                   1840: 		($submission =~ /^resource\.([^\.]*)\.([^\.]*)\.submission/);
                   1841:             my $files=&get_submitted_files($udom,$uname,$partid,$respid,
                   1842: 					   \%record);
                   1843:             return 1 if (@$files);
1.396     banghart 1844:         }
                   1845:     }
1.397     albertel 1846:     return 0;
1.396     banghart 1847: }
1.397     albertel 1848: 
1.394     banghart 1849: sub download_all_link {
                   1850:     my ($r,$symb) = @_;
1.395     albertel 1851:     my $all_students = 
                   1852: 	join("\n", &Apache::loncommon::get_env_multiple('form.stuinfo'));
                   1853: 
                   1854:     my $parts =
                   1855: 	join("\n",&Apache::loncommon::get_env_multiple('form.vPart'));
                   1856: 
1.394     banghart 1857:     my $identifier = &Apache::loncommon::get_cgi_id();
1.514     raeburn  1858:     &Apache::lonnet::appenv({'cgi.'.$identifier.'.students' => $all_students,
                   1859:                              'cgi.'.$identifier.'.symb' => $symb,
                   1860:                              'cgi.'.$identifier.'.parts' => $parts,});
1.395     albertel 1861:     $r->print('<a href="/cgi-bin/multidownload.pl?'.$identifier.'">'.
                   1862: 	      &mt('Download All Submitted Documents').'</a>');
1.394     banghart 1863:     return
                   1864: }
1.395     albertel 1865: 
1.432     banghart 1866: sub build_section_inputs {
                   1867:     my $section_inputs;
                   1868:     if ($env{'form.section'} eq '') {
                   1869:         $section_inputs .= '<input type="hidden" name="section" value="all" />'."\n";
                   1870:     } else {
                   1871:         my @sections = &Apache::loncommon::get_env_multiple('form.section');
1.434     albertel 1872:         foreach my $section (@sections) {
1.432     banghart 1873:             $section_inputs .= '<input type="hidden" name="section" value="'.$section.'" />'."\n";
                   1874:         }
                   1875:     }
                   1876:     return $section_inputs;
                   1877: }
                   1878: 
1.44      ng       1879: # --------------------------- show submissions of a student, option to grade 
                   1880: sub submission {
                   1881:     my ($request,$counter,$total) = @_;
1.257     albertel 1882:     my ($uname,$udom)     = ($env{'form.student'},$env{'form.userdom'});
                   1883:     $udom = ($udom eq '' ? $env{'user.domain'} : $udom); #has form.userdom changed for a student?
                   1884:     my $usec = &Apache::lonnet::getsection($udom,$uname,$env{'request.course.id'});
                   1885:     $env{'form.fullname'} = &Apache::loncommon::plainname($uname,$udom,'lastname') if $env{'form.fullname'} eq '';
1.324     albertel 1886:     my $symb = &get_symb($request); 
                   1887:     if ($symb eq '') { $request->print("Unable to handle ambiguous references:."); return ''; }
1.104     albertel 1888: 
                   1889:     if (!&canview($usec)) {
1.398     albertel 1890: 	$request->print('<span class="LC_warning">Unable to view requested student.('.
                   1891: 			$uname.':'.$udom.' in section '.$usec.' in course id '.
                   1892: 			$env{'request.course.id'}.')</span>');
1.324     albertel 1893: 	$request->print(&show_grading_menu_form($symb));
1.104     albertel 1894: 	return;
                   1895:     }
                   1896: 
1.257     albertel 1897:     if (!$env{'form.lastSub'}) { $env{'form.lastSub'} = 'datesub'; }
                   1898:     if (!$env{'form.vProb'}) { $env{'form.vProb'} = 'yes'; }
                   1899:     if (!$env{'form.vAns'}) { $env{'form.vAns'} = 'yes'; }
                   1900:     my $last = ($env{'form.lastSub'} eq 'last' ? 'last' : '');
1.381     albertel 1901:     my $checkIcon = '<img alt="'.&mt('Check Mark').
                   1902: 	'" src="'.$request->dir_config('lonIconsURL').
1.122     ng       1903: 	'/check.gif" height="16" border="0" />';
1.41      ng       1904: 
1.426     albertel 1905:     my %old_essays;
1.41      ng       1906:     # header info
                   1907:     if ($counter == 0) {
                   1908: 	&sub_page_js($request);
1.257     albertel 1909: 	&sub_page_kw_js($request) if ($env{'form.handgrade'} eq 'yes');
                   1910: 	$env{'form.probTitle'} = $env{'form.probTitle'} eq '' ? 
                   1911: 	    &Apache::lonnet::gettitle($symb) : $env{'form.probTitle'};
1.397     albertel 1912: 	if ($env{'form.handgrade'} eq 'yes' && &files_exist($request, $symb)) {
1.396     banghart 1913: 	    &download_all_link($request, $symb);
                   1914: 	}
1.485     albertel 1915: 	$request->print('<h3>&nbsp;<span class="LC_info">'.&mt('Submission Record').'</span></h3>'."\n".
                   1916: 			'<h4>&nbsp;'.&mt('<b>Resource: </b> [_1]',$env{'form.probTitle'}).'</h4>'."\n");
1.118     ng       1917: 
1.44      ng       1918: 	# option to display problem, only once else it cause problems 
                   1919:         # with the form later since the problem has a form.
1.257     albertel 1920: 	if ($env{'form.vProb'} eq 'yes' or $env{'form.vAns'} eq 'yes') {
1.144     albertel 1921: 	    my $mode;
1.257     albertel 1922: 	    if ($env{'form.vProb'} eq 'yes' && $env{'form.vAns'} eq 'yes') {
1.144     albertel 1923: 		$mode='both';
1.257     albertel 1924: 	    } elsif ($env{'form.vProb'} eq 'yes') {
1.144     albertel 1925: 		$mode='text';
1.257     albertel 1926: 	    } elsif ($env{'form.vAns'} eq 'yes') {
1.144     albertel 1927: 		$mode='answer';
                   1928: 	    }
1.329     albertel 1929: 	    &Apache::lonxml::clear_problem_counter();
1.144     albertel 1930: 	    $request->print(&show_problem($request,$symb,$uname,$udom,0,1,$mode));
1.41      ng       1931: 	}
1.441     www      1932: 
1.44      ng       1933: 	# kwclr is the only variable that is guaranteed to be non blank 
                   1934:         # if this subroutine has been called once.
1.41      ng       1935: 	my %keyhash = ();
1.257     albertel 1936: 	if ($env{'form.kwclr'} eq '' && $env{'form.handgrade'} eq 'yes') {
1.41      ng       1937: 	    %keyhash = &Apache::lonnet::dump('nohist_handgrade',
1.257     albertel 1938: 					     $env{'course.'.$env{'request.course.id'}.'.domain'},
                   1939: 					     $env{'course.'.$env{'request.course.id'}.'.num'});
1.41      ng       1940: 
1.257     albertel 1941: 	    my $loginuser = $env{'user.name'}.':'.$env{'user.domain'};
                   1942: 	    $env{'form.keywords'} = $keyhash{$symb.'_keywords'} ne '' ? $keyhash{$symb.'_keywords'} : '';
                   1943: 	    $env{'form.kwclr'}    = $keyhash{$loginuser.'_kwclr'} ne '' ? $keyhash{$loginuser.'_kwclr'} : 'red';
                   1944: 	    $env{'form.kwsize'}   = $keyhash{$loginuser.'_kwsize'} ne '' ? $keyhash{$loginuser.'_kwsize'} : '0';
                   1945: 	    $env{'form.kwstyle'}  = $keyhash{$loginuser.'_kwstyle'} ne '' ? $keyhash{$loginuser.'_kwstyle'} : '';
                   1946: 	    $env{'form.msgsub'}   = $keyhash{$symb.'_subject'} ne '' ? 
                   1947: 		$keyhash{$symb.'_subject'} : $env{'form.probTitle'};
                   1948: 	    $env{'form.savemsgN'} = $keyhash{$symb.'_savemsgN'} ne '' ? $keyhash{$symb.'_savemsgN'} : '0';
1.41      ng       1949: 	}
1.257     albertel 1950: 	my $overRideScore = $env{'form.overRideScore'} eq '' ? 'no' : $env{'form.overRideScore'};
1.442     banghart 1951: 	my $stu_status = join(':',&Apache::loncommon::get_env_multiple('form.Status'));
1.303     banghart 1952: 	$request->print('<form action="/adm/grades" method="post" name="SCORE" enctype="multipart/form-data">'."\n".
1.41      ng       1953: 			'<input type="hidden" name="command"    value="handgrade" />'."\n".
1.257     albertel 1954: 			'<input type="hidden" name="saveState"  value="'.$env{'form.saveState'}.'" />'."\n".
1.442     banghart 1955: 			'<input type="hidden" name="Status"     value="'.$stu_status.'" />'."\n".
1.120     ng       1956: 			'<input type="hidden" name="overRideScore" value="'.$overRideScore.'" />'."\n".
1.257     albertel 1957: 			'<input type="hidden" name="probTitle"  value="'.$env{'form.probTitle'}.'" />'."\n".
1.41      ng       1958: 			'<input type="hidden" name="refresh"    value="off" />'."\n".
1.120     ng       1959: 			'<input type="hidden" name="studentNo"  value="" />'."\n".
                   1960: 			'<input type="hidden" name="gradeOpt"   value="" />'."\n".
1.418     albertel 1961: 			'<input type="hidden" name="symb"       value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
1.257     albertel 1962: 			'<input type="hidden" name="showgrading" value="'.$env{'form.showgrading'}.'" />'."\n".
                   1963: 			'<input type="hidden" name="vProb"      value="'.$env{'form.vProb'}.'" />'."\n".
                   1964: 			'<input type="hidden" name="vAns"       value="'.$env{'form.vAns'}.'" />'."\n".
                   1965: 			'<input type="hidden" name="lastSub"    value="'.$env{'form.lastSub'}.'" />'."\n".
1.432     banghart 1966: 			&build_section_inputs().
1.326     albertel 1967: 			'<input type="hidden" name="submitonly" value="'.$env{'form.submitonly'}.'" />'."\n".
                   1968: 			'<input type="hidden" name="handgrade"  value="'.$env{'form.handgrade'}.'" />'."\n".
1.41      ng       1969: 			'<input type="hidden" name="NCT"'.
1.257     albertel 1970: 			' value="'.($env{'form.NTSTU'} ne '' ? $env{'form.NTSTU'} : $total+1).'" />'."\n");
                   1971: 	if ($env{'form.handgrade'} eq 'yes') {
                   1972: 	    $request->print('<input type="hidden" name="keywords" value="'.$env{'form.keywords'}.'" />'."\n".
                   1973: 			    '<input type="hidden" name="kwclr"    value="'.$env{'form.kwclr'}.'" />'."\n".
                   1974: 			    '<input type="hidden" name="kwsize"   value="'.$env{'form.kwsize'}.'" />'."\n".
                   1975: 			    '<input type="hidden" name="kwstyle"  value="'.$env{'form.kwstyle'}.'" />'."\n".
                   1976: 			    '<input type="hidden" name="msgsub"   value="'.$env{'form.msgsub'}.'" />'."\n".
1.123     ng       1977: 			    '<input type="hidden" name="shownSub" value="0" />'."\n".
1.257     albertel 1978: 			    '<input type="hidden" name="savemsgN" value="'.$env{'form.savemsgN'}.'" />'."\n");
1.154     albertel 1979: 	    foreach my $partid (&Apache::loncommon::get_env_multiple('form.vPart')) {
                   1980: 		$request->print('<input type="hidden" name="vPart" value="'.$partid.'" />'."\n");
                   1981: 	    }
1.123     ng       1982: 	}
1.41      ng       1983: 	
                   1984: 	my ($cts,$prnmsg) = (1,'');
1.257     albertel 1985: 	while ($cts <= $env{'form.savemsgN'}) {
1.41      ng       1986: 	    $prnmsg.='<input type="hidden" name="savemsg'.$cts.'" value="'.
1.123     ng       1987: 		(!exists($keyhash{$symb.'_savemsg'.$cts}) ? 
1.257     albertel 1988: 		 &Apache::lonfeedback::clear_out_html($env{'form.savemsg'.$cts}) :
1.80      ng       1989: 		 &Apache::lonfeedback::clear_out_html($keyhash{$symb.'_savemsg'.$cts})).
1.123     ng       1990: 		'" />'."\n".
                   1991: 		'<input type="hidden" name="shownOnce'.$cts.'" value="0" />'."\n";
1.41      ng       1992: 	    $cts++;
                   1993: 	}
                   1994: 	$request->print($prnmsg);
1.32      ng       1995: 
1.257     albertel 1996: 	if ($env{'form.handgrade'} eq 'yes' && $env{'form.showgrading'} eq 'yes') {
1.88      www      1997: #
                   1998: # Print out the keyword options line
                   1999: #
1.41      ng       2000: 	    $request->print(<<KEYWORDS);
1.38      ng       2001: &nbsp;<b>Keyword Options:</b>&nbsp;
1.417     albertel 2002: <a href="javascript:keywords(document.SCORE);" target="_self">List</a>&nbsp; &nbsp;
1.38      ng       2003: <a href="#" onMouseDown="javascript:getSel(); return false"
                   2004:  CLASS="page">Paste Selection to List</a>&nbsp; &nbsp;
1.417     albertel 2005: <a href="javascript:kwhighlight();" target="_self">Highlight Attribute</a><br /><br />
1.38      ng       2006: KEYWORDS
1.88      www      2007: #
                   2008: # Load the other essays for similarity check
                   2009: #
1.324     albertel 2010:             my (undef,undef,$essayurl) = &Apache::lonnet::decode_symb($symb);
1.384     albertel 2011: 	    my ($adom,$aname,$apath)=($essayurl=~/^($LONCAPA::domain_re)\/($LONCAPA::username_re)\/(.*)$/);
1.359     www      2012: 	    $apath=&escape($apath);
1.88      www      2013: 	    $apath=~s/\W/\_/gs;
1.426     albertel 2014: 	    %old_essays=&Apache::lonnet::dump('nohist_essay_'.$apath,$adom,$aname);
1.41      ng       2015:         }
                   2016:     }
1.44      ng       2017: 
1.441     www      2018: # This is where output for one specific student would start
1.468     albertel 2019:     my $add_class = ($counter%2) ? 'LC_grade_show_user_odd_row' : '';
1.441     www      2020:     $request->print("\n\n".
1.468     albertel 2021:                     '<div class="LC_grade_show_user '.$add_class.'">'.
                   2022: 		    '<div class="LC_grade_user_name">'.&nameUserString(undef,$env{'form.fullname'},$uname,$udom).'</div>'.
                   2023: 		    '<div class="LC_grade_show_user_body">'."\n");
1.441     www      2024: 
1.257     albertel 2025:     if ($env{'form.vProb'} eq 'all' or $env{'form.vAns'} eq 'all') {
1.144     albertel 2026: 	my $mode;
1.257     albertel 2027: 	if ($env{'form.vProb'} eq 'all' && $env{'form.vAns'} eq 'all') {
1.144     albertel 2028: 	    $mode='both';
1.257     albertel 2029: 	} elsif ($env{'form.vProb'} eq 'all' ) {
1.144     albertel 2030: 	    $mode='text';
1.257     albertel 2031: 	} elsif ($env{'form.vAns'} eq 'all') {
1.144     albertel 2032: 	    $mode='answer';
                   2033: 	}
1.329     albertel 2034: 	&Apache::lonxml::clear_problem_counter();
1.475     albertel 2035: 	$request->print(&show_problem($request,$symb,$uname,$udom,1,1,$mode,{'request.prefix' => 'ctr'.$counter}));
1.58      albertel 2036:     }
1.144     albertel 2037: 
1.257     albertel 2038:     my %record = &Apache::lonnet::restore($symb,$env{'request.course.id'},$udom,$uname);
1.324     albertel 2039:     my ($partlist,$handgrade,$responseType) = &response_type($symb);
1.41      ng       2040: 
1.44      ng       2041:     # Display student info
1.41      ng       2042:     $request->print(($counter == 0 ? '' : '<br />'));
1.468     albertel 2043:     my $result='<div class="LC_grade_submissions">';
                   2044:     
                   2045:     $result.='<div class="LC_grade_submissions_header">';
                   2046:     $result.= &mt('Submissions');
1.45      ng       2047:     $result.='<input type="hidden" name="name'.$counter.
1.257     albertel 2048: 	'" value="'.$env{'form.fullname'}.'" />'."\n";
1.469     albertel 2049:     if ($env{'form.handgrade'} eq 'no') {
                   2050: 	$result.='<span class="LC_grade_check_note">'.
                   2051: 	    &mt('Part(s) graded correct by the computer is marked with a [_1] symbol.',$checkIcon)."</span>\n";
                   2052: 
                   2053:     }
                   2054: 
                   2055: 
1.41      ng       2056: 
1.118     ng       2057:     # If any part of the problem is an essay-response (handgraded), then check for collaborators
1.464     albertel 2058:     my $fullname;
                   2059:     my $col_fullnames = [];
1.257     albertel 2060:     if ($env{'form.handgrade'} eq 'yes') {
1.464     albertel 2061: 	(my $sub_result,$fullname,$col_fullnames)=
                   2062: 	    &check_collaborators($symb,$uname,$udom,\%record,$handgrade,
                   2063: 				 $counter);
                   2064: 	$result.=$sub_result;
1.41      ng       2065:     }
1.44      ng       2066:     $request->print($result."\n");
1.468     albertel 2067:     $request->print('</div>'."\n");
1.44      ng       2068:     # print student answer/submission
                   2069:     # Options are (1) Handgaded submission only
                   2070:     #             (2) Last submission, includes submission that is not handgraded 
                   2071:     #                  (for multi-response type part)
                   2072:     #             (3) Last submission plus the parts info
                   2073:     #             (4) The whole record for this student
1.257     albertel 2074:     if ($env{'form.lastSub'} =~ /^(lastonly|hdgrade)$/) {
1.151     albertel 2075: 	my ($string,$timestamp)= &get_last_submission(\%record);
1.468     albertel 2076: 	
                   2077: 	my $lastsubonly;
                   2078: 
1.151     albertel 2079: 	if ($$timestamp eq '') {
1.468     albertel 2080: 	    $lastsubonly.='<div class="LC_grade_submissions_body">'.$$string[0].'</div>'; 
1.151     albertel 2081: 	} else {
1.468     albertel 2082: 	    $lastsubonly = '<div class="LC_grade_submissions_body"> <b>Date Submitted:</b> '.$$timestamp."\n";
                   2083: 
1.151     albertel 2084: 	    my %seenparts;
1.375     albertel 2085: 	    my @part_response_id = &flatten_responseType($responseType);
                   2086: 	    foreach my $part (@part_response_id) {
1.393     albertel 2087: 		next if ($env{'form.lastSub'} eq 'hdgrade' 
                   2088: 			 && $$handgrade{$$part[0].'_'.$$part[1]} ne 'yes');
                   2089: 
1.375     albertel 2090: 		my ($partid,$respid) = @{ $part };
1.324     albertel 2091: 		my $display_part=&get_display_part($partid,$symb);
1.257     albertel 2092: 		if ($env{"form.$uname:$udom:$partid:submitted_by"}) {
1.151     albertel 2093: 		    if (exists($seenparts{$partid})) { next; }
                   2094: 		    $seenparts{$partid}=1;
1.207     albertel 2095: 		    my $submitby='<b>Part:</b> '.$display_part.
                   2096: 			' <b>Collaborative submission by:</b> '.
1.151     albertel 2097: 			'<a href="javascript:viewSubmitter(\''.
1.257     albertel 2098: 			$env{"form.$uname:$udom:$partid:submitted_by"}.
1.417     albertel 2099: 			'\');" target="_self">'.
1.257     albertel 2100: 			$$fullname{$env{"form.$uname:$udom:$partid:submitted_by"}}.'</a><br />';
1.151     albertel 2101: 		    $request->print($submitby);
                   2102: 		    next;
                   2103: 		}
                   2104: 		my $responsetype = $responseType->{$partid}->{$respid};
                   2105: 		if (!exists($record{"resource.$partid.$respid.submission"})) {
1.468     albertel 2106: 		    $lastsubonly.="\n".'<div class="LC_grade_submission_part"><b>Part:</b> '.
1.398     albertel 2107: 			$display_part.' <span class="LC_internal_info">( ID '.$respid.
                   2108: 			' )</span>&nbsp; &nbsp;'.
1.539     riegler  2109: 			'<span class="LC_warning">'.&mt('Nothing submitted - no attempts.').'</span><br /><br /></div>';
1.151     albertel 2110: 		    next;
                   2111: 		}
1.468     albertel 2112: 		foreach my $submission (@$string) {
                   2113: 		    my ($partid,$respid) = ($submission =~ /^resource\.([^\.]*)\.([^\.]*)\.submission/);
1.375     albertel 2114: 		    if (join('_',@{$part}) ne ($partid.'_'.$respid)) { next; }
1.468     albertel 2115: 		    my ($ressub,$subval) = split(/:/,$submission,2);
1.151     albertel 2116: 		    # Similarity check
                   2117: 		    my $similar='';
1.257     albertel 2118: 		    if($env{'form.checkPlag'}){
1.151     albertel 2119: 			my ($oname,$odom,$ocrsid,$oessay,$osim)=
1.426     albertel 2120: 			    &most_similar($uname,$udom,$subval,\%old_essays);
1.151     albertel 2121: 			if ($osim) {
                   2122: 			    $osim=int($osim*100.0);
1.426     albertel 2123: 			    my %old_course_desc = 
                   2124: 				&Apache::lonnet::coursedescription($ocrsid,
                   2125: 								   {'one_time' => 1});
                   2126: 
                   2127: 			    $similar="<hr /><h3><span class=\"LC_warning\">".
1.427     albertel 2128: 				&mt('Essay is [_1]% similar to an essay by [_2] ([_3]:[_4]) in course [_5] (course id [_6]:[_7])',
1.426     albertel 2129: 				    $osim,
                   2130: 				    &Apache::loncommon::plainname($oname,$odom),
1.427     albertel 2131: 				    $oname,$odom,
1.426     albertel 2132: 				    $old_course_desc{'description'},
1.427     albertel 2133: 				    $old_course_desc{'num'},
1.426     albertel 2134: 				    $old_course_desc{'domain'}).
1.398     albertel 2135: 				'</span></h3><blockquote><i>'.
1.151     albertel 2136: 				&keywords_highlight($oessay).
                   2137: 				'</i></blockquote><hr />';
                   2138: 			}
1.150     albertel 2139: 		    }
1.151     albertel 2140: 		    my $order=&get_order($partid,$respid,$symb,$uname,$udom);
1.257     albertel 2141: 		    if ($env{'form.lastSub'} eq 'lastonly' || 
                   2142: 			($env{'form.lastSub'} eq 'hdgrade' && 
1.377     albertel 2143: 			 $$handgrade{$$part[0].'_'.$$part[1]} eq 'yes')) {
1.324     albertel 2144: 			my $display_part=&get_display_part($partid,$symb);
1.468     albertel 2145: 			$lastsubonly.='<div class="LC_grade_submission_part"><b>Part:</b> '.
1.403     albertel 2146: 			    $display_part.' <span class="LC_internal_info">( ID '.$respid.
1.398     albertel 2147: 			    ' )</span>&nbsp; &nbsp;';
1.313     banghart 2148: 			my $files=&get_submitted_files($udom,$uname,$partid,$respid,\%record);
                   2149: 			if (@$files) {
1.544     raeburn  2150: 			    $lastsubonly.='<br /><span class="LC_warning">'.&mt('Like all files provided by users, this file may contain viruses').'</span><br />';
1.303     banghart 2151: 			    my $file_counter = 0;
1.313     banghart 2152: 			    foreach my $file (@$files) {
1.468     albertel 2153: 			        $file_counter++;
1.232     albertel 2154: 				&Apache::lonnet::allowuploaded('/adm/grades',$file);
1.335     albertel 2155: 				$lastsubonly.='<br /><a href="'.$file.'?rawmode=1" target="lonGRDs"><img src="'.&Apache::loncommon::icon($file).'" border=0"> '.$file.'</a>';
1.232     albertel 2156: 			    }
1.236     albertel 2157: 			    $lastsubonly.='<br />';
1.41      ng       2158: 			}
1.468     albertel 2159: 			$lastsubonly.='<b>'.&mt('Submitted Answer:').' </b>'.
1.151     albertel 2160: 			    &cleanRecord($subval,$responsetype,$symb,$partid,
1.555     raeburn  2161: 					 $respid,\%record,$order,undef,$uname,$udom);
1.151     albertel 2162: 			if ($similar) {$lastsubonly.="<br /><br />$similar\n";}
1.468     albertel 2163: 			$lastsubonly.='</div>';
1.41      ng       2164: 		    }
                   2165: 		}
                   2166: 	    }
1.468     albertel 2167: 	    $lastsubonly.='</div>'."\n";
1.151     albertel 2168: 	}
                   2169: 	$request->print($lastsubonly);
1.468     albertel 2170:    } elsif ($env{'form.lastSub'} eq 'datesub') {
1.324     albertel 2171: 	my (undef,$responseType,undef,$parts) = &showResourceInfo($symb);
1.148     albertel 2172: 	$request->print(&displaySubByDates($symb,\%record,$parts,$responseType,$checkIcon,$uname,$udom));
1.257     albertel 2173:     } elsif ($env{'form.lastSub'} =~ /^(last|all)$/) {
1.41      ng       2174: 	$request->print(&Apache::loncommon::get_previous_attempt($symb,$uname,$udom,
1.257     albertel 2175: 								 $env{'request.course.id'},
1.44      ng       2176: 								 $last,'.submission',
                   2177: 								 'Apache::grades::keywords_highlight'));
1.41      ng       2178:     }
1.120     ng       2179: 
1.121     ng       2180:     $request->print('<input type="hidden" name="unamedom'.$counter.'" value="'.$uname.':'
                   2181: 	.$udom.'" />'."\n");
1.44      ng       2182:     # return if view submission with no grading option
1.257     albertel 2183:     if ($env{'form.showgrading'} eq '' || (!&canmodify($usec))) {
1.120     ng       2184: 	my $toGrade.='<input type="button" value="Grade Student" '.
1.121     ng       2185: 	    'onClick="javascript:checksubmit(this.form,\'Grade Student\',\''
1.417     albertel 2186: 	    .$counter.'\');" target="_self" /> &nbsp;'."\n" if (&canmodify($usec));
1.468     albertel 2187: 	$toGrade.='</div>'."\n";
1.257     albertel 2188: 	if (($env{'form.command'} eq 'submission') || 
                   2189: 	    ($env{'form.command'} eq 'processGroup' && $counter == $total)) {
1.324     albertel 2190: 	    $toGrade.='</form>'.&show_grading_menu_form($symb); 
1.169     albertel 2191: 	}
1.180     albertel 2192: 	$request->print($toGrade);
1.41      ng       2193: 	return;
1.180     albertel 2194:     } else {
1.468     albertel 2195: 	$request->print('</div>'."\n");
1.41      ng       2196:     }
1.33      ng       2197: 
1.121     ng       2198:     # essay grading message center
1.257     albertel 2199:     if ($env{'form.handgrade'} eq 'yes') {
1.468     albertel 2200: 	my $result='<div class="LC_grade_message_center">';
                   2201:     
                   2202: 	$result.='<div class="LC_grade_message_center_header">'.
                   2203: 	    &mt('Send Message').'</div><div class="LC_grade_message_center_body">';
1.257     albertel 2204: 	my ($lastname,$givenn) = split(/,/,$env{'form.fullname'});
1.118     ng       2205: 	my $msgfor = $givenn.' '.$lastname;
1.464     albertel 2206: 	if (scalar(@$col_fullnames) > 0) {
                   2207: 	    my $lastone = pop(@$col_fullnames);
                   2208: 	    $msgfor .= ', '.(join ', ',@$col_fullnames).' and '.$lastone.'.';
1.118     ng       2209: 	}
                   2210: 	$msgfor =~ s/\'/\\'/g; #' stupid emacs - no! javascript
1.468     albertel 2211: 	$result.='<input type="hidden" name="includemsg'.$counter.'" value="" />'."\n".
1.121     ng       2212: 	    '<input type="hidden" name="newmsg'.$counter.'" value="" />'."\n";
                   2213: 	$result.='&nbsp;<a href="javascript:msgCenter(document.SCORE,'.$counter.
1.417     albertel 2214: 	    ',\''.$msgfor.'\');" target="_self">'.
1.464     albertel 2215: 	    &mt('Compose message to student').(scalar(@$col_fullnames) >= 1 ? 's' : '').'</a><label> ('.
1.350     albertel 2216: 	    &mt('incl. grades').' <input type="checkbox" name="withgrades'.$counter.'" /></label>)'.
1.118     ng       2217: 	    '<img src="'.$request->dir_config('lonIconsURL').
                   2218: 	    '/mailbkgrd.gif" width="14" height="10" name="mailicon'.$counter.'" />'."\n".
1.298     www      2219: 	    '<br />&nbsp;('.
1.468     albertel 2220: 	    &mt('Message will be sent when you click on Save &amp; Next below.').")\n";
                   2221: 	$result.='</div></div>';
1.121     ng       2222: 	$request->print($result);
1.118     ng       2223:     }
1.41      ng       2224: 
                   2225:     my %seen = ();
                   2226:     my @partlist;
1.129     ng       2227:     my @gradePartRespid;
1.375     albertel 2228:     my @part_response_id = &flatten_responseType($responseType);
1.468     albertel 2229:     $request->print('<div class="LC_grade_assign">'.
                   2230: 		    
                   2231: 		    '<div class="LC_grade_assign_header">'.
                   2232: 		    &mt('Assign Grades').'</div>'.
                   2233: 		    '<div class="LC_grade_assign_body">');
1.375     albertel 2234:     foreach my $part_response_id (@part_response_id) {
                   2235:     	my ($partid,$respid) = @{ $part_response_id };
                   2236: 	my $part_resp = join('_',@{ $part_response_id });
1.322     albertel 2237: 	next if ($seen{$partid} > 0);
1.41      ng       2238: 	$seen{$partid}++;
1.393     albertel 2239: 	next if ($$handgrade{$part_resp} ne 'yes' 
                   2240: 		 && $env{'form.lastSub'} eq 'hdgrade');
1.524     raeburn  2241: 	push(@partlist,$partid);
                   2242: 	push(@gradePartRespid,$partid.'.'.$respid);
1.322     albertel 2243: 	$request->print(&gradeBox($request,$symb,$uname,$udom,$counter,$partid,\%record));
1.41      ng       2244:     }
1.468     albertel 2245:     $request->print('</div></div>');
                   2246: 
                   2247:     $request->print('<div class="LC_grade_info_links">');
                   2248:     if ($perm{'vgr'}) {
                   2249: 	$request->print(
                   2250: 	    &Apache::loncommon::track_student_link(&mt('View recent activity'),
                   2251: 						   $uname,$udom,'check'));
                   2252:     }
                   2253:     if ($perm{'opa'}) {
                   2254: 	$request->print(
                   2255: 	    &Apache::loncommon::pprmlink(&mt('Set/Change parameters'),
                   2256: 					 $uname,$udom,$symb,'check'));
                   2257:     }
                   2258:     $request->print('</div>');
                   2259: 
1.45      ng       2260:     $result='<input type="hidden" name="partlist'.$counter.
                   2261: 	'" value="'.(join ":",@partlist).'" />'."\n";
1.129     ng       2262:     $result.='<input type="hidden" name="gradePartRespid'.
                   2263: 	'" value="'.(join ":",@gradePartRespid).'" />'."\n" if ($counter == 0);
1.45      ng       2264:     my $ctr = 0;
                   2265:     while ($ctr < scalar(@partlist)) {
                   2266: 	$result.='<input type="hidden" name="partid'.$counter.'_'.$ctr.'" value="'.
                   2267: 	    $partlist[$ctr].'" />'."\n";
                   2268: 	$ctr++;
                   2269:     }
1.468     albertel 2270:     $request->print($result.''."\n");
1.41      ng       2271: 
1.441     www      2272: # Done with printing info for one student
                   2273: 
1.468     albertel 2274:     $request->print('</div>');#LC_grade_show_user_body
                   2275:     $request->print('</div>');#LC_grade_show_user
1.441     www      2276: 
                   2277: 
1.41      ng       2278:     # print end of form
                   2279:     if ($counter == $total) {
1.297     www      2280: 	my $endform='<table border="0"><tr><td>'."\n";
1.485     albertel 2281: 	$endform.='<input type="button" value="'.&mt('Save &amp; Next').'" '.
1.119     ng       2282: 	    'onClick="javascript:checksubmit(this.form,\'Save & Next\','.
1.417     albertel 2283: 	    $total.','.scalar(@partlist).');" target="_self" /> &nbsp;'."\n";
1.119     ng       2284: 	my $ntstu ='<select name="NTSTU">'.
                   2285: 	    '<option>1</option><option>2</option>'.
                   2286: 	    '<option>3</option><option>5</option>'.
                   2287: 	    '<option>7</option><option>10</option></select>'."\n";
1.257     albertel 2288: 	my $nsel = ($env{'form.NTSTU'} ne '' ? $env{'form.NTSTU'} : '1');
1.401     albertel 2289: 	$ntstu =~ s/<option>$nsel</<option selected="selected">$nsel</;
1.549     hauer    2290: 	$endform.=&mt('[quant,_1,student]',$ntstu);
1.485     albertel 2291: 	$endform.='&nbsp;&nbsp;<input type="button" value="'.&mt('Previous').'" '.
1.417     albertel 2292: 	    'onClick="javascript:checksubmit(this.form,\'Previous\');" target="_self" /> &nbsp;'."\n".
1.485     albertel 2293: 	    '<input type="button" value="'.&mt('Next').'" '.
1.417     albertel 2294: 	    'onClick="javascript:checksubmit(this.form,\'Next\');" target="_self" /> &nbsp;';
1.485     albertel 2295: 	$endform.=&mt('(Next and Previous (student) do not save the scores.)')."\n" ;
1.349     albertel 2296:         $endform.="<input type='hidden' value='".&get_increment().
1.348     bowersj2 2297:             "' name='increment' />";
1.485     albertel 2298: 	$endform.='</td></tr></table></form>';
1.324     albertel 2299: 	$endform.=&show_grading_menu_form($symb);
1.41      ng       2300: 	$request->print($endform);
                   2301:     }
                   2302:     return '';
1.38      ng       2303: }
                   2304: 
1.464     albertel 2305: sub check_collaborators {
                   2306:     my ($symb,$uname,$udom,$record,$handgrade,$counter) = @_;
                   2307:     my ($result,@col_fullnames);
                   2308:     my ($classlist,undef,$fullname) = &getclasslist('all','0');
                   2309:     foreach my $part (keys(%$handgrade)) {
                   2310: 	my $ncol = &Apache::lonnet::EXT('resource.'.$part.
                   2311: 					'.maxcollaborators',
                   2312: 					$symb,$udom,$uname);
                   2313: 	next if ($ncol <= 0);
                   2314: 	$part =~ s/\_/\./g;
                   2315: 	next if ($record->{'resource.'.$part.'.collaborators'} eq '');
                   2316: 	my (@good_collaborators, @bad_collaborators);
                   2317: 	foreach my $possible_collaborator
                   2318: 	    (split(/,?\s+/,$record->{'resource.'.$part.'.collaborators'})) { 
                   2319: 	    $possible_collaborator =~ s/[\$\^\(\)]//g;
                   2320: 	    next if ($possible_collaborator eq '');
                   2321: 	    my ($co_name,$co_dom) = split(/\@|:/,$possible_collaborator);
                   2322: 	    $co_dom = $udom if (! defined($co_dom) || $co_dom =~ /^domain$/i);
                   2323: 	    next if ($co_name eq $uname && $co_dom eq $udom);
                   2324: 	    # Doing this grep allows 'fuzzy' specification
                   2325: 	    my @matches = grep(/^\Q$co_name\E:\Q$co_dom\E$/i, 
                   2326: 			       keys(%$classlist));
                   2327: 	    if (! scalar(@matches)) {
                   2328: 		push(@bad_collaborators, $possible_collaborator);
                   2329: 	    } else {
                   2330: 		push(@good_collaborators, @matches);
                   2331: 	    }
                   2332: 	}
                   2333: 	if (scalar(@good_collaborators) != 0) {
1.466     albertel 2334: 	    $result.='<br />'.&mt('Collaborators: ');
1.464     albertel 2335: 	    foreach my $name (@good_collaborators) {
                   2336: 		my ($lastname,$givenn) = split(/,/,$$fullname{$name});
                   2337: 		push(@col_fullnames, $givenn.' '.$lastname);
                   2338: 		$result.=$fullname->{$name}.'&nbsp; &nbsp; &nbsp;';
                   2339: 	    }
                   2340: 	    $result.='<br />'."\n";
1.466     albertel 2341: 	    my ($part)=split(/\./,$part);
1.464     albertel 2342: 	    $result.='<input type="hidden" name="collaborator'.$counter.
                   2343: 		'" value="'.$part.':'.(join ':',@good_collaborators).'" />'.
                   2344: 		"\n";
                   2345: 	}
                   2346: 	if (scalar(@bad_collaborators) > 0) {
1.466     albertel 2347: 	    $result.='<div class="LC_warning">';
1.464     albertel 2348: 	    $result.=&mt('This student has submitted [quant,_1,invalid collaborator]: [_2]',scalar(@bad_collaborators),join(', ',@bad_collaborators));
                   2349: 	    $result .= '</div>';
                   2350: 	}         
                   2351: 	if (scalar(@bad_collaborators > $ncol)) {
1.466     albertel 2352: 	    $result .= '<div class="LC_warning">';
1.464     albertel 2353: 	    $result .= &mt('This student has submitted too many '.
                   2354: 		'collaborators.  Maximum is [_1].',$ncol);
                   2355: 	    $result .= '</div>';
                   2356: 	}
                   2357:     }
                   2358:     return ($result,$fullname,\@col_fullnames);
                   2359: }
                   2360: 
1.44      ng       2361: #--- Retrieve the last submission for all the parts
1.38      ng       2362: sub get_last_submission {
1.119     ng       2363:     my ($returnhash)=@_;
1.46      ng       2364:     my (@string,$timestamp);
1.119     ng       2365:     if ($$returnhash{'version'}) {
1.46      ng       2366: 	my %lasthash=();
                   2367: 	my ($version);
1.119     ng       2368: 	for ($version=1;$version<=$$returnhash{'version'};$version++) {
1.397     albertel 2369: 	    foreach my $key (sort(split(/\:/,
                   2370: 					$$returnhash{$version.':keys'}))) {
                   2371: 		$lasthash{$key}=$$returnhash{$version.':'.$key};
                   2372: 		$timestamp = 
1.545     raeburn  2373: 		    &Apache::lonlocal::locallocaltime($$returnhash{$version.':timestamp'});
1.46      ng       2374: 	    }
                   2375: 	}
1.397     albertel 2376: 	foreach my $key (keys(%lasthash)) {
                   2377: 	    next if ($key !~ /\.submission$/);
                   2378: 
                   2379: 	    my ($partid,$foo) = split(/submission$/,$key);
                   2380: 	    my $draft  = $lasthash{$partid.'awarddetail'} eq 'DRAFT' ?
1.398     albertel 2381: 		'<span class="LC_warning">Draft Copy</span> ' : '';
1.397     albertel 2382: 	    push(@string, join(':', $key, $draft.$lasthash{$key}));
1.41      ng       2383: 	}
                   2384:     }
1.397     albertel 2385:     if (!@string) {
                   2386: 	$string[0] =
1.539     riegler  2387: 	    '<span class="LC_warning">'.&mt('Nothing submitted - no attempts.').'</span>';
1.397     albertel 2388:     }
                   2389:     return (\@string,\$timestamp);
1.38      ng       2390: }
1.35      ng       2391: 
1.44      ng       2392: #--- High light keywords, with style choosen by user.
1.38      ng       2393: sub keywords_highlight {
1.44      ng       2394:     my $string    = shift;
1.257     albertel 2395:     my $size      = $env{'form.kwsize'} eq '0' ? '' : 'size='.$env{'form.kwsize'};
                   2396:     my $styleon   = $env{'form.kwstyle'} eq ''  ? '' : $env{'form.kwstyle'};
1.41      ng       2397:     (my $styleoff = $styleon) =~ s/\</\<\//;
1.257     albertel 2398:     my @keylist   = split(/[,\s+]/,$env{'form.keywords'});
1.398     albertel 2399:     foreach my $keyword (@keylist) {
                   2400: 	$string =~ s/\b\Q$keyword\E(\b|\.)/<font color\=$env{'form.kwclr'} $size\>$styleon$keyword$styleoff<\/font>/gi;
1.41      ng       2401:     }
                   2402:     return $string;
1.38      ng       2403: }
1.36      ng       2404: 
1.44      ng       2405: #--- Called from submission routine
1.38      ng       2406: sub processHandGrade {
1.41      ng       2407:     my ($request) = shift;
1.324     albertel 2408:     my $symb   = &get_symb($request);
                   2409:     my (undef,undef,$url) = &Apache::lonnet::decode_symb($symb);
1.257     albertel 2410:     my $button = $env{'form.gradeOpt'};
                   2411:     my $ngrade = $env{'form.NCT'};
                   2412:     my $ntstu  = $env{'form.NTSTU'};
1.301     albertel 2413:     my $cdom   = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   2414:     my $cnum   = $env{'course.'.$env{'request.course.id'}.'.num'};
                   2415: 
1.44      ng       2416:     if ($button eq 'Save & Next') {
                   2417: 	my $ctr = 0;
                   2418: 	while ($ctr < $ngrade) {
1.257     albertel 2419: 	    my ($uname,$udom) = split(/:/,$env{'form.unamedom'.$ctr});
1.324     albertel 2420: 	    my ($errorflag,$pts,$wgt) = &saveHandGrade($request,$symb,$uname,$udom,$ctr);
1.71      ng       2421: 	    if ($errorflag eq 'no_score') {
                   2422: 		$ctr++;
                   2423: 		next;
                   2424: 	    }
1.104     albertel 2425: 	    if ($errorflag eq 'not_allowed') {
1.398     albertel 2426: 		$request->print("<span class=\"LC_warning\">Not allowed to modify grades for $uname:$udom</span>");
1.104     albertel 2427: 		$ctr++;
                   2428: 		next;
                   2429: 	    }
1.257     albertel 2430: 	    my $includemsg = $env{'form.includemsg'.$ctr};
1.44      ng       2431: 	    my ($subject,$message,$msgstatus) = ('','','');
1.418     albertel 2432: 	    my $restitle = &Apache::lonnet::gettitle($symb);
                   2433:             my ($feedurl,$showsymb) =
                   2434: 		&get_feedurl_and_symb($symb,$uname,$udom);
                   2435: 	    my $messagetail;
1.62      albertel 2436: 	    if ($includemsg =~ /savemsg|newmsg\Q$ctr\E/) {
1.298     www      2437: 		$subject = $env{'form.msgsub'} if ($includemsg =~ /msgsub/);
1.295     www      2438: 		unless ($subject=~/\w/) { $subject=&mt('Grading Feedback'); }
1.386     raeburn  2439: 		$subject.=' ['.$restitle.']';
1.44      ng       2440: 		my (@msgnum) = split(/,/,$includemsg);
                   2441: 		foreach (@msgnum) {
1.257     albertel 2442: 		    $message.=$env{'form.'.$_} if ($_ =~ /savemsg|newmsg/ && $_ ne '');
1.44      ng       2443: 		}
1.80      ng       2444: 		$message =&Apache::lonfeedback::clear_out_html($message);
1.298     www      2445: 		if ($env{'form.withgrades'.$ctr}) {
                   2446: 		    $message.="\n\nPoint".($pts > 1 ? 's':'').' awarded = '.$pts.' out of '.$wgt;
1.386     raeburn  2447: 		    $messagetail = " for <a href=\"".
1.418     albertel 2448: 		                   $feedurl."?symb=$showsymb\">$env{'form.probTitle'}</a>";
1.386     raeburn  2449: 		}
                   2450: 		$msgstatus = 
                   2451:                     &Apache::lonmsg::user_normal_msg($uname,$udom,$subject,
                   2452: 						     $message.$messagetail,
1.418     albertel 2453:                                                      undef,$feedurl,undef,
1.386     raeburn  2454:                                                      undef,undef,$showsymb,
                   2455:                                                      $restitle);
                   2456: 		$request->print('<br />'.&mt('Sending message to [_1]:[_2]',$uname,$udom).': '.
1.296     www      2457: 				$msgstatus);
1.44      ng       2458: 	    }
1.257     albertel 2459: 	    if ($env{'form.collaborator'.$ctr}) {
1.155     albertel 2460: 		my @collabstrs=&Apache::loncommon::get_env_multiple("form.collaborator$ctr");
1.150     albertel 2461: 		foreach my $collabstr (@collabstrs) {
                   2462: 		    my ($part,@collaborators) = split(/:/,$collabstr);
1.310     banghart 2463: 		    foreach my $collaborator (@collaborators) {
1.150     albertel 2464: 			my ($errorflag,$pts,$wgt) = 
1.324     albertel 2465: 			    &saveHandGrade($request,$symb,$collaborator,$udom,$ctr,
1.257     albertel 2466: 					   $env{'form.unamedom'.$ctr},$part);
1.150     albertel 2467: 			if ($errorflag eq 'not_allowed') {
1.362     albertel 2468: 			    $request->print("<span class=\"LC_error\">".&mt('Not allowed to modify grades for [_1]',"$collaborator:$udom")."</span>");
1.150     albertel 2469: 			    next;
1.418     albertel 2470: 			} elsif ($message ne '') {
                   2471: 			    my ($baseurl,$showsymb) = 
                   2472: 				&get_feedurl_and_symb($symb,$collaborator,
                   2473: 						      $udom);
                   2474: 			    if ($env{'form.withgrades'.$ctr}) {
                   2475: 				$messagetail = " for <a href=\"".
1.386     raeburn  2476:                                     $baseurl."?symb=$showsymb\">$env{'form.probTitle'}</a>";
1.150     albertel 2477: 			    }
1.418     albertel 2478: 			    $msgstatus = 
                   2479: 				&Apache::lonmsg::user_normal_msg($collaborator,$udom,$subject,$message.$messagetail,undef,$baseurl,undef,undef,undef,$showsymb,$restitle);
1.104     albertel 2480: 			}
1.44      ng       2481: 		    }
                   2482: 		}
                   2483: 	    }
                   2484: 	    $ctr++;
                   2485: 	}
                   2486:     }
                   2487: 
1.257     albertel 2488:     if ($env{'form.handgrade'} eq 'yes') {
1.119     ng       2489: 	# Keywords sorted in alphabatical order
1.257     albertel 2490: 	my $loginuser = $env{'user.name'}.':'.$env{'user.domain'};
1.119     ng       2491: 	my %keyhash = ();
1.257     albertel 2492: 	$env{'form.keywords'}           =~ s/,\s{0,}|\s+/ /g;
                   2493: 	$env{'form.keywords'}           =~ s/^\s+|\s+$//;
                   2494: 	my (@keywords) = sort(split(/\s+/,$env{'form.keywords'}));
                   2495: 	$env{'form.keywords'} = join(' ',@keywords);
                   2496: 	$keyhash{$symb.'_keywords'}     = $env{'form.keywords'};
                   2497: 	$keyhash{$symb.'_subject'}      = $env{'form.msgsub'};
                   2498: 	$keyhash{$loginuser.'_kwclr'}   = $env{'form.kwclr'};
                   2499: 	$keyhash{$loginuser.'_kwsize'}  = $env{'form.kwsize'};
                   2500: 	$keyhash{$loginuser.'_kwstyle'} = $env{'form.kwstyle'};
1.119     ng       2501: 
                   2502: 	# message center - Order of message gets changed. Blank line is eliminated.
1.257     albertel 2503: 	# New messages are saved in env for the next student.
1.119     ng       2504: 	# All messages are saved in nohist_handgrade.db
                   2505: 	my ($ctr,$idx) = (1,1);
1.257     albertel 2506: 	while ($ctr <= $env{'form.savemsgN'}) {
                   2507: 	    if ($env{'form.savemsg'.$ctr} ne '') {
                   2508: 		$keyhash{$symb.'_savemsg'.$idx} = $env{'form.savemsg'.$ctr};
1.119     ng       2509: 		$idx++;
                   2510: 	    }
                   2511: 	    $ctr++;
1.41      ng       2512: 	}
1.119     ng       2513: 	$ctr = 0;
                   2514: 	while ($ctr < $ngrade) {
1.257     albertel 2515: 	    if ($env{'form.newmsg'.$ctr} ne '') {
                   2516: 		$keyhash{$symb.'_savemsg'.$idx} = $env{'form.newmsg'.$ctr};
                   2517: 		$env{'form.savemsg'.$idx} = $env{'form.newmsg'.$ctr};
1.119     ng       2518: 		$idx++;
                   2519: 	    }
                   2520: 	    $ctr++;
1.41      ng       2521: 	}
1.257     albertel 2522: 	$env{'form.savemsgN'} = --$idx;
                   2523: 	$keyhash{$symb.'_savemsgN'} = $env{'form.savemsgN'};
1.119     ng       2524: 	my $putresult = &Apache::lonnet::put
1.301     albertel 2525: 	    ('nohist_handgrade',\%keyhash,$cdom,$cnum);
1.41      ng       2526:     }
1.44      ng       2527:     # Called by Save & Refresh from Highlight Attribute Window
1.257     albertel 2528:     my (undef,undef,$fullname) = &getclasslist($env{'form.section'},'1');
                   2529:     if ($env{'form.refresh'} eq 'on') {
1.86      ng       2530: 	my ($ctr,$total) = (0,0);
                   2531: 	while ($ctr < $ngrade) {
1.257     albertel 2532: 	    $total++ if  $env{'form.unamedom'.$ctr} ne '';
1.86      ng       2533: 	    $ctr++;
                   2534: 	}
1.257     albertel 2535: 	$env{'form.NTSTU'}=$ngrade;
1.86      ng       2536: 	$ctr = 0;
                   2537: 	while ($ctr < $total) {
1.257     albertel 2538: 	    my $processUser = $env{'form.unamedom'.$ctr};
                   2539: 	    ($env{'form.student'},$env{'form.userdom'}) = split(/:/,$processUser);
                   2540: 	    $env{'form.fullname'} = $$fullname{$processUser};
1.86      ng       2541: 	    &submission($request,$ctr,$total-1);
1.41      ng       2542: 	    $ctr++;
                   2543: 	}
                   2544: 	return '';
                   2545:     }
1.36      ng       2546: 
1.121     ng       2547: # Go directly to grade student - from submission or link from chart page
1.120     ng       2548:     if ($button eq 'Grade Student') {
1.324     albertel 2549: 	(undef,undef,$env{'form.handgrade'},undef,undef) = &showResourceInfo($symb);
1.257     albertel 2550: 	my $processUser = $env{'form.unamedom'.$env{'form.studentNo'}};
                   2551: 	($env{'form.student'},$env{'form.userdom'}) = split(/:/,$processUser);
                   2552: 	$env{'form.fullname'} = $$fullname{$processUser};
1.120     ng       2553: 	&submission($request,0,0);
                   2554: 	return '';
                   2555:     }
                   2556: 
1.44      ng       2557:     # Get the next/previous one or group of students
1.257     albertel 2558:     my $firststu = $env{'form.unamedom0'};
                   2559:     my $laststu = $env{'form.unamedom'.($ngrade-1)};
1.119     ng       2560:     my $ctr = 2;
1.41      ng       2561:     while ($laststu eq '') {
1.257     albertel 2562: 	$laststu  = $env{'form.unamedom'.($ngrade-$ctr)};
1.41      ng       2563: 	$ctr++;
                   2564: 	$laststu = $firststu if ($ctr > $ngrade);
                   2565:     }
1.44      ng       2566: 
1.41      ng       2567:     my (@parsedlist,@nextlist);
                   2568:     my ($nextflg) = 0;
1.524     raeburn  2569:     foreach my $item (sort 
1.294     albertel 2570: 	     {
                   2571: 		 if (lc($$fullname{$a}) ne lc($$fullname{$b})) {
                   2572: 		     return (lc($$fullname{$a}) cmp lc($$fullname{$b}));
                   2573: 		 }
                   2574: 		 return $a cmp $b;
                   2575: 	     } (keys(%$fullname))) {
1.41      ng       2576: 	if ($nextflg == 1 && $button =~ /Next$/) {
1.524     raeburn  2577: 	    push(@parsedlist,$item);
1.41      ng       2578: 	}
1.524     raeburn  2579: 	$nextflg = 1 if ($item eq $laststu);
1.41      ng       2580: 	if ($button eq 'Previous') {
1.524     raeburn  2581: 	    last if ($item eq $firststu);
                   2582: 	    push(@parsedlist,$item);
1.41      ng       2583: 	}
                   2584:     }
                   2585:     $ctr = 0;
                   2586:     @parsedlist = reverse @parsedlist if ($button eq 'Previous');
1.324     albertel 2587:     my ($partlist) = &response_type($symb);
1.41      ng       2588:     foreach my $student (@parsedlist) {
1.257     albertel 2589: 	my $submitonly=$env{'form.submitonly'};
1.41      ng       2590: 	my ($uname,$udom) = split(/:/,$student);
1.301     albertel 2591: 	
                   2592: 	if ($submitonly eq 'queued') {
                   2593: 	    my %queue_status = 
                   2594: 		&Apache::bridgetask::get_student_status($symb,$cdom,$cnum,
                   2595: 							$udom,$uname);
                   2596: 	    next if (!defined($queue_status{'gradingqueue'}));
                   2597: 	}
                   2598: 
1.156     albertel 2599: 	if ($submitonly =~ /^(yes|graded|incorrect)$/) {
1.257     albertel 2600: #	    my %record = &Apache::lonnet::restore($symb,$env{'request.course.id'},$udom,$uname);
1.324     albertel 2601: 	    my %status=&student_gradeStatus($symb,$udom,$uname,$partlist);
1.145     albertel 2602: 	    my $submitted = 0;
1.248     albertel 2603: 	    my $ungraded = 0;
                   2604: 	    my $incorrect = 0;
1.524     raeburn  2605: 	    foreach my $item (keys(%status)) {
                   2606: 		$submitted = 1 if ($status{$item} ne 'nothing');
                   2607: 		$ungraded = 1 if ($status{$item} =~ /^ungraded/);
                   2608: 		$incorrect = 1 if ($status{$item} =~ /^incorrect/);
                   2609: 		my ($foo,$partid,$foo1) = split(/\./,$item);
1.145     albertel 2610: 		if ($status{'resource.'.$partid.'.submitted_by'} ne '') {
                   2611: 		    $submitted = 0;
                   2612: 		}
1.41      ng       2613: 	    }
1.156     albertel 2614: 	    next if (!$submitted && ($submitonly eq 'yes' ||
                   2615: 				     $submitonly eq 'incorrect' ||
                   2616: 				     $submitonly eq 'graded'));
1.248     albertel 2617: 	    next if (!$ungraded && ($submitonly eq 'graded'));
                   2618: 	    next if (!$incorrect && $submitonly eq 'incorrect');
1.41      ng       2619: 	}
1.524     raeburn  2620: 	push(@nextlist,$student) if ($ctr < $ntstu);
1.129     ng       2621: 	last if ($ctr == $ntstu);
1.41      ng       2622: 	$ctr++;
                   2623:     }
1.36      ng       2624: 
1.41      ng       2625:     $ctr = 0;
                   2626:     my $total = scalar(@nextlist)-1;
1.39      ng       2627: 
1.524     raeburn  2628:     foreach (sort(@nextlist)) {
1.41      ng       2629: 	my ($uname,$udom,$submitter) = split(/:/);
1.257     albertel 2630: 	$env{'form.student'}  = $uname;
                   2631: 	$env{'form.userdom'}  = $udom;
                   2632: 	$env{'form.fullname'} = $$fullname{$_};
1.41      ng       2633: 	&submission($request,$ctr,$total);
                   2634: 	$ctr++;
                   2635:     }
                   2636:     if ($total < 0) {
1.485     albertel 2637: 	my $the_end = '<h3><span class="LC_info">'.&mt('LON-CAPA User Message').'</span></h3><br />'."\n";
                   2638: 	$the_end.=&mt('<b>Message: </b> No more students for this section or class.').'<br /><br />'."\n";
                   2639: 	$the_end.=&mt('Click on the button below to return to the grading menu.').'<br /><br />'."\n";
1.324     albertel 2640: 	$the_end.=&show_grading_menu_form($symb);
1.41      ng       2641: 	$request->print($the_end);
                   2642:     }
                   2643:     return '';
1.38      ng       2644: }
1.36      ng       2645: 
1.44      ng       2646: #---- Save the score and award for each student, if changed
1.38      ng       2647: sub saveHandGrade {
1.324     albertel 2648:     my ($request,$symb,$stuname,$domain,$newflg,$submitter,$part) = @_;
1.342     banghart 2649:     my @version_parts;
1.104     albertel 2650:     my $usec = &Apache::lonnet::getsection($domain,$stuname,
1.257     albertel 2651: 					   $env{'request.course.id'});
1.104     albertel 2652:     if (!&canmodify($usec)) { return('not_allowed'); }
1.337     banghart 2653:     my %record = &Apache::lonnet::restore($symb,$env{'request.course.id'},$domain,$stuname);
1.251     banghart 2654:     my @parts_graded;
1.77      ng       2655:     my %newrecord  = ();
                   2656:     my ($pts,$wgt) = ('','');
1.269     raeburn  2657:     my %aggregate = ();
                   2658:     my $aggregateflag = 0;
1.301     albertel 2659:     my @parts = split(/:/,$env{'form.partlist'.$newflg});
                   2660:     foreach my $new_part (@parts) {
1.337     banghart 2661: 	#collaborator ($submi may vary for different parts
1.259     banghart 2662: 	if ($submitter && $new_part ne $part) { next; }
                   2663: 	my $dropMenu = $env{'form.GD_SEL'.$newflg.'_'.$new_part};
1.125     ng       2664: 	if ($dropMenu eq 'excused') {
1.259     banghart 2665: 	    if ($record{'resource.'.$new_part.'.solved'} ne 'excused') {
                   2666: 		$newrecord{'resource.'.$new_part.'.solved'} = 'excused';
                   2667: 		if (exists($record{'resource.'.$new_part.'.awarded'})) {
                   2668: 		    $newrecord{'resource.'.$new_part.'.awarded'} = '';
1.58      albertel 2669: 		}
1.364     banghart 2670: 	        $newrecord{'resource.'.$new_part.'.regrader'}="$env{'user.name'}:$env{'user.domain'}";
1.58      albertel 2671: 	    }
1.125     ng       2672: 	} elsif ($dropMenu eq 'reset status'
1.259     banghart 2673: 		 && exists($record{'resource.'.$new_part.'.solved'})) { #don't bother if no old records -> no attempts
1.524     raeburn  2674: 	    foreach my $key (keys(%record)) {
1.259     banghart 2675: 		if ($key=~/^resource\.\Q$new_part\E\./) { $newrecord{$key} = ''; }
1.197     albertel 2676: 	    }
1.259     banghart 2677: 	    $newrecord{'resource.'.$new_part.'.regrader'}=
1.257     albertel 2678: 		"$env{'user.name'}:$env{'user.domain'}";
1.270     albertel 2679:             my $totaltries = $record{'resource.'.$part.'.tries'};
                   2680: 
                   2681:             my %last_resets = &get_last_resets($symb,$env{'request.course.id'},
                   2682: 					       [$new_part]);
                   2683:             my $aggtries =$totaltries;
1.269     raeburn  2684:             if ($last_resets{$new_part}) {
1.270     albertel 2685:                 $aggtries = &get_num_tries(\%record,$last_resets{$new_part},
                   2686: 					   $new_part);
1.269     raeburn  2687:             }
1.270     albertel 2688: 
                   2689:             my $solvedstatus = $record{'resource.'.$new_part.'.solved'};
1.269     raeburn  2690:             if ($aggtries > 0) {
1.327     albertel 2691:                 &decrement_aggs($symb,$new_part,\%aggregate,$aggtries,$totaltries,$solvedstatus);
1.269     raeburn  2692:                 $aggregateflag = 1;
                   2693:             }
1.125     ng       2694: 	} elsif ($dropMenu eq '') {
1.259     banghart 2695: 	    $pts = ($env{'form.GD_BOX'.$newflg.'_'.$new_part} ne '' ? 
                   2696: 		    $env{'form.GD_BOX'.$newflg.'_'.$new_part} : 
                   2697: 		    $env{'form.RADVAL'.$newflg.'_'.$new_part});
                   2698: 	    if ($pts eq '' && $env{'form.GD_SEL'.$newflg.'_'.$new_part} eq '') {
1.153     albertel 2699: 		next;
                   2700: 	    }
1.259     banghart 2701: 	    $wgt = $env{'form.WGT'.$newflg.'_'.$new_part} eq '' ? 1 : 
                   2702: 		$env{'form.WGT'.$newflg.'_'.$new_part};
1.41      ng       2703: 	    my $partial= $pts/$wgt;
1.259     banghart 2704: 	    if ($partial eq $record{'resource.'.$new_part.'.awarded'}) {
1.153     albertel 2705: 		#do not update score for part if not changed.
1.346     banghart 2706:                 &handback_files($request,$symb,$stuname,$domain,$newflg,$new_part,\%newrecord);
1.153     albertel 2707: 		next;
1.251     banghart 2708: 	    } else {
1.524     raeburn  2709: 	        push(@parts_graded,$new_part);
1.153     albertel 2710: 	    }
1.259     banghart 2711: 	    if ($record{'resource.'.$new_part.'.awarded'} ne $partial) {
                   2712: 		$newrecord{'resource.'.$new_part.'.awarded'}  = $partial;
1.153     albertel 2713: 	    }
1.259     banghart 2714: 	    my $reckey = 'resource.'.$new_part.'.solved';
1.41      ng       2715: 	    if ($partial == 0) {
1.153     albertel 2716: 		if ($record{$reckey} ne 'incorrect_by_override') {
                   2717: 		    $newrecord{$reckey} = 'incorrect_by_override';
                   2718: 		}
1.41      ng       2719: 	    } else {
1.153     albertel 2720: 		if ($record{$reckey} ne 'correct_by_override') {
                   2721: 		    $newrecord{$reckey} = 'correct_by_override';
                   2722: 		}
                   2723: 	    }	    
                   2724: 	    if ($submitter && 
1.259     banghart 2725: 		($record{'resource.'.$new_part.'.submitted_by'} ne $submitter)) {
                   2726: 		$newrecord{'resource.'.$new_part.'.submitted_by'} = $submitter;
1.41      ng       2727: 	    }
1.259     banghart 2728: 	    $newrecord{'resource.'.$new_part.'.regrader'}=
1.257     albertel 2729: 		"$env{'user.name'}:$env{'user.domain'}";
1.41      ng       2730: 	}
1.259     banghart 2731: 	# unless problem has been graded, set flag to version the submitted files
1.305     banghart 2732: 	unless ($record{'resource.'.$new_part.'.solved'} =~ /^correct_/  || 
                   2733: 	        $record{'resource.'.$new_part.'.solved'} eq 'incorrect_by_override' ||
                   2734: 	        $dropMenu eq 'reset status')
                   2735: 	   {
1.524     raeburn  2736: 	    push(@version_parts,$new_part);
1.259     banghart 2737: 	}
1.41      ng       2738:     }
1.301     albertel 2739:     my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   2740:     my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   2741: 
1.344     albertel 2742:     if (%newrecord) {
                   2743:         if (@version_parts) {
1.364     banghart 2744:             my @changed_keys = &version_portfiles(\%record, \@parts_graded, 
                   2745:                                 $env{'request.course.id'}, $symb, $domain, $stuname, \@version_parts);
1.344     albertel 2746: 	    @newrecord{@changed_keys} = @record{@changed_keys};
1.367     albertel 2747: 	    foreach my $new_part (@version_parts) {
                   2748: 		&handback_files($request,$symb,$stuname,$domain,$newflg,
                   2749: 				$new_part,\%newrecord);
                   2750: 	    }
1.259     banghart 2751:         }
1.44      ng       2752: 	&Apache::lonnet::cstore(\%newrecord,$symb,
1.257     albertel 2753: 				$env{'request.course.id'},$domain,$stuname);
1.380     albertel 2754: 	&check_and_remove_from_queue(\@parts,\%record,\%newrecord,$symb,
                   2755: 				     $cdom,$cnum,$domain,$stuname);
1.41      ng       2756:     }
1.269     raeburn  2757:     if ($aggregateflag) {
                   2758:         &Apache::lonnet::cinc('nohist_resourcetracker',\%aggregate,
1.301     albertel 2759: 			      $cdom,$cnum);
1.269     raeburn  2760:     }
1.301     albertel 2761:     return ('',$pts,$wgt);
1.36      ng       2762: }
1.322     albertel 2763: 
1.380     albertel 2764: sub check_and_remove_from_queue {
                   2765:     my ($parts,$record,$newrecord,$symb,$cdom,$cnum,$domain,$stuname) = @_;
                   2766:     my @ungraded_parts;
                   2767:     foreach my $part (@{$parts}) {
                   2768: 	if (    $record->{   'resource.'.$part.'.awarded'} eq ''
                   2769: 	     && $record->{   'resource.'.$part.'.solved' } ne 'excused'
                   2770: 	     && $newrecord->{'resource.'.$part.'.awarded'} eq ''
                   2771: 	     && $newrecord->{'resource.'.$part.'.solved' } ne 'excused'
                   2772: 		) {
                   2773: 	    push(@ungraded_parts, $part);
                   2774: 	}
                   2775:     }
                   2776:     if ( !@ungraded_parts ) {
                   2777: 	&Apache::bridgetask::remove_from_queue('gradingqueue',$symb,$cdom,
                   2778: 					       $cnum,$domain,$stuname);
                   2779:     }
                   2780: }
                   2781: 
1.337     banghart 2782: sub handback_files {
                   2783:     my ($request,$symb,$stuname,$domain,$newflg,$new_part,$newrecord) = @_;
1.517     raeburn  2784:     my $portfolio_root = '/userfiles/portfolio';
1.359     www      2785:     my ($partlist,$handgrade,$responseType) = &response_type($symb);
1.375     albertel 2786: 
                   2787:     my @part_response_id = &flatten_responseType($responseType);
                   2788:     foreach my $part_response_id (@part_response_id) {
                   2789:     	my ($part_id,$resp_id) = @{ $part_response_id };
                   2790: 	my $part_resp = join('_',@{ $part_response_id });
1.337     banghart 2791:             if (($env{'form.'.$newflg.'_'.$part_resp.'_returndoc1'}) && ($new_part == $part_id)) {
                   2792:                 # if multiple files are uploaded names will be 'returndoc2','returndoc3'
                   2793:                 my $file_counter = 1;
1.367     albertel 2794: 		my $file_msg;
1.337     banghart 2795:                 while ($env{'form.'.$newflg.'_'.$part_resp.'_returndoc'.$file_counter}) {
                   2796:                     my $fname=$env{'form.'.$newflg.'_'.$part_resp.'_returndoc'.$file_counter.'.filename'};
1.338     banghart 2797:                     my ($directory,$answer_file) = 
                   2798:                         ($env{'form.'.$newflg.'_'.$part_resp.'_origdoc'.$file_counter} =~ /^(.*?)([^\/]*)$/);
                   2799:                     my ($answer_name,$answer_ver,$answer_ext) =
                   2800: 		        &file_name_version_ext($answer_file);
1.355     banghart 2801: 		    my ($portfolio_path) = ($directory =~ /^.+$stuname\/portfolio(.*)/);
1.517     raeburn  2802:                     my $getpropath = 1;
                   2803: 		    my @dir_list = &Apache::lonnet::dirlist($portfolio_root.$portfolio_path,$domain,$stuname,$getpropath);
1.338     banghart 2804: 		    my $version = &get_next_version($answer_name, $answer_ext, \@dir_list);
1.355     banghart 2805:                     # fix file name
                   2806:                     my ($save_file_name) = (($directory.$answer_name.".$version.".$answer_ext) =~ /^.+\/${stuname}\/(.*)/);
                   2807:                     my $result=&Apache::lonnet::finishuserfileupload($stuname,$domain,
                   2808:             	                                $newflg.'_'.$part_resp.'_returndoc'.$file_counter,
                   2809:             	                                $save_file_name);
1.337     banghart 2810:                     if ($result !~ m|^/uploaded/|) {
1.536     raeburn  2811:                         $request->print('<br /><span class="LC_error">'.
                   2812:                             &mt('An error occurred ([_1]) while trying to upload [_2].',
                   2813:                                 $result,$newflg.'_'.$part_resp.'_returndoc'.$file_counter).
                   2814:                                         '</span>');
1.356     banghart 2815:                     } else {
1.360     banghart 2816:                         # mark the file as read only
                   2817:                         my @files = ($save_file_name);
1.372     albertel 2818:                         my @what = ($symb,$env{'request.course.id'},'handback');
1.360     banghart 2819:                         &Apache::lonnet::mark_as_readonly($domain,$stuname,\@files,\@what);
1.367     albertel 2820: 			if (exists($$newrecord{"resource.$new_part.$resp_id.handback"})) {
                   2821: 			    $$newrecord{"resource.$new_part.$resp_id.handback"}.=',';
                   2822: 			}
                   2823:                         $$newrecord{"resource.$new_part.$resp_id.handback"} .= $save_file_name;
                   2824: 			$file_msg.= "\n".'<br /><span class="LC_filename"><a href="/uploaded/'."$domain/$stuname/".$save_file_name.'">'.$save_file_name."</a></span><br />";
                   2825: 
1.337     banghart 2826:                     }
                   2827:                     $request->print("<br />".$fname." will be the uploaded file name");
1.354     albertel 2828:                     $request->print(" ".$env{'form.'.$newflg.'_'.$part_resp.'_origdoc'.$file_counter});
1.337     banghart 2829:                     $file_counter++;
                   2830:                 }
1.367     albertel 2831: 		my $subject = "File Handed Back by Instructor ";
                   2832: 		my $message = "A file has been returned that was originally submitted in reponse to: <br />";
                   2833: 		$message .= "<strong>".&Apache::lonnet::gettitle($symb)."</strong><br />";
                   2834: 		$message .= ' The returned file(s) are named: '. $file_msg;
                   2835: 		$message .= " and can be found in your portfolio space.";
1.418     albertel 2836: 		my ($feedurl,$showsymb) = 
                   2837: 		    &get_feedurl_and_symb($symb,$domain,$stuname);
1.386     raeburn  2838:                 my $restitle = &Apache::lonnet::gettitle($symb);
                   2839: 		my $msgstatus = 
                   2840:                    &Apache::lonmsg::user_normal_msg($stuname,$domain,$subject.
                   2841: 			 ' (File Returned) ['.$restitle.']',$message,undef,
1.418     albertel 2842:                          $feedurl,undef,undef,undef,$showsymb,$restitle);
1.337     banghart 2843:             }
                   2844:         }
1.338     banghart 2845:     return;
1.337     banghart 2846: }
                   2847: 
1.418     albertel 2848: sub get_feedurl_and_symb {
                   2849:     my ($symb,$uname,$udom) = @_;
                   2850:     my (undef,undef,$url) = &Apache::lonnet::decode_symb($symb);
                   2851:     $url = &Apache::lonnet::clutter($url);
                   2852:     my $encrypturl=&Apache::lonnet::EXT('resource.0.encrypturl',
                   2853: 					$symb,$udom,$uname);
                   2854:     if ($encrypturl =~ /^yes$/i) {
                   2855: 	&Apache::lonenc::encrypted(\$url,1);
                   2856: 	&Apache::lonenc::encrypted(\$symb,1);
                   2857:     }
                   2858:     return ($url,$symb);
                   2859: }
                   2860: 
1.313     banghart 2861: sub get_submitted_files {
                   2862:     my ($udom,$uname,$partid,$respid,$record) = @_;
                   2863:     my @files;
                   2864:     if ($$record{"resource.$partid.$respid.portfiles"}) {
                   2865:         my $file_url = '/uploaded/'.$udom.'/'.$uname.'/portfolio';
                   2866:         foreach my $file (split(',',$$record{"resource.$partid.$respid.portfiles"})) {
                   2867:     	    push(@files,$file_url.$file);
                   2868:         }
                   2869:     }
                   2870:     if ($$record{"resource.$partid.$respid.uploadedurl"}) {
                   2871:         push(@files,$$record{"resource.$partid.$respid.uploadedurl"});
                   2872:     }
                   2873:     return (\@files);
                   2874: }
1.322     albertel 2875: 
1.269     raeburn  2876: # ----------- Provides number of tries since last reset.
                   2877: sub get_num_tries {
                   2878:     my ($record,$last_reset,$part) = @_;
                   2879:     my $timestamp = '';
                   2880:     my $num_tries = 0;
                   2881:     if ($$record{'version'}) {
                   2882:         for (my $version=$$record{'version'};$version>=1;$version--) {
                   2883:             if (exists($$record{$version.':resource.'.$part.'.solved'})) {
                   2884:                 $timestamp = $$record{$version.':timestamp'};
                   2885:                 if ($timestamp > $last_reset) {
                   2886:                     $num_tries ++;
                   2887:                 } else {
                   2888:                     last;
                   2889:                 }
                   2890:             }
                   2891:         }
                   2892:     }
                   2893:     return $num_tries;
                   2894: }
                   2895: 
                   2896: # ----------- Determine decrements required in aggregate totals 
                   2897: sub decrement_aggs {
                   2898:     my ($symb,$part,$aggregate,$aggtries,$totaltries,$solvedstatus) = @_;
                   2899:     my %decrement = (
                   2900:                         attempts => 0,
                   2901:                         users => 0,
                   2902:                         correct => 0
                   2903:                     );
                   2904:     $decrement{'attempts'} = $aggtries;
                   2905:     if ($solvedstatus =~ /^correct/) {
                   2906:         $decrement{'correct'} = 1;
                   2907:     }
                   2908:     if ($aggtries == $totaltries) {
                   2909:         $decrement{'users'} = 1;
                   2910:     }
1.524     raeburn  2911:     foreach my $type (keys(%decrement)) {
1.269     raeburn  2912:         $$aggregate{$symb."\0".$part."\0".$type} = -$decrement{$type};
                   2913:     }
                   2914:     return;
                   2915: }
                   2916: 
                   2917: # ----------- Determine timestamps for last reset of aggregate totals for parts  
                   2918: sub get_last_resets {
1.270     albertel 2919:     my ($symb,$courseid,$partids) =@_;
                   2920:     my %last_resets;
1.269     raeburn  2921:     my $cdom = $env{'course.'.$courseid.'.domain'};
                   2922:     my $cname = $env{'course.'.$courseid.'.num'};
1.271     albertel 2923:     my @keys;
                   2924:     foreach my $part (@{$partids}) {
                   2925: 	push(@keys,"$symb\0$part\0resettime");
                   2926:     }
                   2927:     my %results=&Apache::lonnet::get('nohist_resourcetracker',\@keys,
                   2928: 				     $cdom,$cname);
                   2929:     foreach my $part (@{$partids}) {
                   2930: 	$last_resets{$part}=$results{"$symb\0$part\0resettime"};
1.269     raeburn  2931:     }
1.270     albertel 2932:     return %last_resets;
1.269     raeburn  2933: }
                   2934: 
1.251     banghart 2935: # ----------- Handles creating versions for portfolio files as answers
                   2936: sub version_portfiles {
1.343     banghart 2937:     my ($record, $parts_graded, $courseid, $symb, $domain, $stu_name, $v_flag) = @_;
1.263     banghart 2938:     my $version_parts = join('|',@$v_flag);
1.343     banghart 2939:     my @returned_keys;
1.255     banghart 2940:     my $parts = join('|', @$parts_graded);
1.517     raeburn  2941:     my $portfolio_root = '/userfiles/portfolio';
1.277     albertel 2942:     foreach my $key (keys(%$record)) {
1.259     banghart 2943:         my $new_portfiles;
1.263     banghart 2944:         if ($key =~ /^resource\.($version_parts)\./ && $key =~ /\.portfiles$/ ) {
1.342     banghart 2945:             my @versioned_portfiles;
1.367     albertel 2946:             my @portfiles = split(/\s*,\s*/,$$record{$key});
1.252     banghart 2947:             foreach my $file (@portfiles) {
1.306     banghart 2948:                 &Apache::lonnet::unmark_as_readonly($domain,$stu_name,[$symb,$env{'request.course.id'}],$file);
1.304     albertel 2949:                 my ($directory,$answer_file) =($file =~ /^(.*?)([^\/]*)$/);
                   2950: 		my ($answer_name,$answer_ver,$answer_ext) =
                   2951: 		    &file_name_version_ext($answer_file);
1.517     raeburn  2952:                 my $getpropath = 1;    
                   2953:                 my @dir_list = &Apache::lonnet::dirlist($portfolio_root.$directory,$domain,$stu_name,$getpropath);
1.342     banghart 2954:                 my $version = &get_next_version($answer_name, $answer_ext, \@dir_list);
1.306     banghart 2955:                 my $new_answer = &version_selected_portfile($domain, $stu_name, $directory, $answer_file, $version);
                   2956:                 if ($new_answer ne 'problem getting file') {
1.342     banghart 2957:                     push(@versioned_portfiles, $directory.$new_answer);
1.306     banghart 2958:                     &Apache::lonnet::mark_as_readonly($domain,$stu_name,
1.367     albertel 2959:                         [$directory.$new_answer],
1.306     banghart 2960:                         [$symb,$env{'request.course.id'},'graded']);
1.259     banghart 2961:                 }
1.252     banghart 2962:             }
1.343     banghart 2963:             $$record{$key} = join(',',@versioned_portfiles);
                   2964:             push(@returned_keys,$key);
1.251     banghart 2965:         }
                   2966:     } 
1.343     banghart 2967:     return (@returned_keys);   
1.305     banghart 2968: }
                   2969: 
1.307     banghart 2970: sub get_next_version {
1.341     banghart 2971:     my ($answer_name, $answer_ext, $dir_list) = @_;
1.307     banghart 2972:     my $version;
                   2973:     foreach my $row (@$dir_list) {
                   2974:         my ($file) = split(/\&/,$row,2);
                   2975:         my ($file_name,$file_version,$file_ext) =
                   2976: 	    &file_name_version_ext($file);
                   2977:         if (($file_name eq $answer_name) && 
                   2978: 	    ($file_ext eq $answer_ext)) {
                   2979:                 # gets here if filename and extension match, regardless of version
                   2980:                 if ($file_version ne '') {
                   2981:                 # a versioned file is found  so save it for later
                   2982:                 if ($file_version > $version) {
                   2983: 		    $version = $file_version;
                   2984: 	        }
                   2985:             }
                   2986:         }
                   2987:     } 
                   2988:     $version ++;
                   2989:     return($version);
                   2990: }
                   2991: 
1.305     banghart 2992: sub version_selected_portfile {
1.306     banghart 2993:     my ($domain,$stu_name,$directory,$file_name,$version) = @_;
                   2994:     my ($answer_name,$answer_ver,$answer_ext) =
                   2995:         &file_name_version_ext($file_name);
                   2996:     my $new_answer;
                   2997:     $env{'form.copy'} = &Apache::lonnet::getfile("/uploaded/$domain/$stu_name/portfolio$directory$file_name");
                   2998:     if($env{'form.copy'} eq '-1') {
                   2999:         $new_answer = 'problem getting file';
                   3000:     } else {
                   3001:         $new_answer = $answer_name.'.'.$version.'.'.$answer_ext;
                   3002:         my $copy_result = &Apache::lonnet::finishuserfileupload(
                   3003:                             $stu_name,$domain,'copy',
                   3004: 		        '/portfolio'.$directory.$new_answer);
                   3005:     }    
                   3006:     return ($new_answer);
1.251     banghart 3007: }
                   3008: 
1.304     albertel 3009: sub file_name_version_ext {
                   3010:     my ($file)=@_;
                   3011:     my @file_parts = split(/\./, $file);
                   3012:     my ($name,$version,$ext);
                   3013:     if (@file_parts > 1) {
                   3014: 	$ext=pop(@file_parts);
                   3015: 	if (@file_parts > 1 && $file_parts[-1] =~ /^\d+$/) {
                   3016: 	    $version=pop(@file_parts);
                   3017: 	}
                   3018: 	$name=join('.',@file_parts);
                   3019:     } else {
                   3020: 	$name=join('.',@file_parts);
                   3021:     }
                   3022:     return($name,$version,$ext);
                   3023: }
                   3024: 
1.44      ng       3025: #--------------------------------------------------------------------------------------
                   3026: #
                   3027: #-------------------------- Next few routines handles grading by section or whole class
                   3028: #
                   3029: #--- Javascript to handle grading by section or whole class
1.42      ng       3030: sub viewgrades_js {
                   3031:     my ($request) = shift;
                   3032: 
1.539     riegler  3033:     my $alertmsg = &mt('A number equal or greater than 0 is expected. Entered value = ');
1.41      ng       3034:     $request->print(<<VIEWJAVASCRIPT);
                   3035: <script type="text/javascript" language="javascript">
1.45      ng       3036:    function writePoint(partid,weight,point) {
1.125     ng       3037: 	var radioButton = document.classgrade["RADVAL_"+partid];
                   3038: 	var textbox = document.classgrade["TEXTVAL_"+partid];
1.42      ng       3039: 	if (point == "textval") {
1.125     ng       3040: 	    point = document.classgrade["TEXTVAL_"+partid].value;
1.109     matthew  3041: 	    if (isNaN(point) || parseFloat(point) < 0) {
1.539     riegler  3042: 		alert("$alertmsg"+parseFloat(point));
1.42      ng       3043: 		var resetbox = false;
                   3044: 		for (var i=0; i<radioButton.length; i++) {
                   3045: 		    if (radioButton[i].checked) {
                   3046: 			textbox.value = i;
                   3047: 			resetbox = true;
                   3048: 		    }
                   3049: 		}
                   3050: 		if (!resetbox) {
                   3051: 		    textbox.value = "";
                   3052: 		}
                   3053: 		return;
                   3054: 	    }
1.109     matthew  3055: 	    if (parseFloat(point) > parseFloat(weight)) {
                   3056: 		var resp = confirm("You entered a value ("+parseFloat(point)+
1.44      ng       3057: 				   ") greater than the weight for the part. Accept?");
                   3058: 		if (resp == false) {
                   3059: 		    textbox.value = "";
                   3060: 		    return;
                   3061: 		}
                   3062: 	    }
1.42      ng       3063: 	    for (var i=0; i<radioButton.length; i++) {
                   3064: 		radioButton[i].checked=false;
1.109     matthew  3065: 		if (parseFloat(point) == i) {
1.42      ng       3066: 		    radioButton[i].checked=true;
                   3067: 		}
                   3068: 	    }
1.41      ng       3069: 
1.42      ng       3070: 	} else {
1.125     ng       3071: 	    textbox.value = parseFloat(point);
1.42      ng       3072: 	}
1.41      ng       3073: 	for (i=0;i<document.classgrade.total.value;i++) {
1.125     ng       3074: 	    var user = document.classgrade["ctr"+i].value;
1.289     albertel 3075: 	    user = user.replace(new RegExp(':', 'g'),"_");
1.125     ng       3076: 	    var scorename = document.classgrade["GD_"+user+"_"+partid+"_awarded"];
                   3077: 	    var saveval   = document.classgrade["GD_"+user+"_"+partid+"_solved_s"].value;
                   3078: 	    var selname   = document.classgrade["GD_"+user+"_"+partid+"_solved"];
1.42      ng       3079: 	    if (saveval != "correct") {
                   3080: 		scorename.value = point;
1.43      ng       3081: 		if (selname[0].selected != true) {
                   3082: 		    selname[0].selected = true;
                   3083: 		}
1.42      ng       3084: 	    }
                   3085: 	}
1.125     ng       3086: 	document.classgrade["SELVAL_"+partid][0].selected = true;
1.42      ng       3087:     }
                   3088: 
                   3089:     function writeRadText(partid,weight) {
1.125     ng       3090: 	var selval   = document.classgrade["SELVAL_"+partid];
                   3091: 	var radioButton = document.classgrade["RADVAL_"+partid];
1.265     www      3092:         var override = document.classgrade["FORCE_"+partid].checked;
1.125     ng       3093: 	var textbox = document.classgrade["TEXTVAL_"+partid];
                   3094: 	if (selval[1].selected || selval[2].selected) {
1.42      ng       3095: 	    for (var i=0; i<radioButton.length; i++) {
                   3096: 		radioButton[i].checked=false;
                   3097: 
                   3098: 	    }
                   3099: 	    textbox.value = "";
                   3100: 
                   3101: 	    for (i=0;i<document.classgrade.total.value;i++) {
1.125     ng       3102: 		var user = document.classgrade["ctr"+i].value;
1.289     albertel 3103: 		user = user.replace(new RegExp(':', 'g'),"_");
1.125     ng       3104: 		var scorename = document.classgrade["GD_"+user+"_"+partid+"_awarded"];
                   3105: 		var saveval   = document.classgrade["GD_"+user+"_"+partid+"_solved_s"].value;
                   3106: 		var selname   = document.classgrade["GD_"+user+"_"+partid+"_solved"];
1.265     www      3107: 		if ((saveval != "correct") || override) {
1.42      ng       3108: 		    scorename.value = "";
1.125     ng       3109: 		    if (selval[1].selected) {
                   3110: 			selname[1].selected = true;
                   3111: 		    } else {
                   3112: 			selname[2].selected = true;
                   3113: 			if (Number(document.classgrade["GD_"+user+"_"+partid+"_tries"].value)) 
                   3114: 			{document.classgrade["GD_"+user+"_"+partid+"_tries"].value = '0';}
                   3115: 		    }
1.42      ng       3116: 		}
                   3117: 	    }
1.43      ng       3118: 	} else {
                   3119: 	    for (i=0;i<document.classgrade.total.value;i++) {
1.125     ng       3120: 		var user = document.classgrade["ctr"+i].value;
1.289     albertel 3121: 		user = user.replace(new RegExp(':', 'g'),"_");
1.125     ng       3122: 		var scorename = document.classgrade["GD_"+user+"_"+partid+"_awarded"];
                   3123: 		var saveval   = document.classgrade["GD_"+user+"_"+partid+"_solved_s"].value;
                   3124: 		var selname   = document.classgrade["GD_"+user+"_"+partid+"_solved"];
1.265     www      3125: 		if ((saveval != "correct") || override) {
1.125     ng       3126: 		    scorename.value = document.classgrade["GD_"+user+"_"+partid+"_awarded_s"].value;
1.43      ng       3127: 		    selname[0].selected = true;
                   3128: 		}
                   3129: 	    }
                   3130: 	}	    
1.42      ng       3131:     }
                   3132: 
                   3133:     function changeSelect(partid,user) {
1.125     ng       3134: 	var selval = document.classgrade["GD_"+user+'_'+partid+"_solved"];
                   3135: 	var textbox = document.classgrade["GD_"+user+'_'+partid+"_awarded"];
1.44      ng       3136: 	var point  = textbox.value;
1.125     ng       3137: 	var weight = document.classgrade["weight_"+partid].value;
1.44      ng       3138: 
1.109     matthew  3139: 	if (isNaN(point) || parseFloat(point) < 0) {
1.539     riegler  3140: 	    alert("$alertmsg"+parseFloat(point));
1.44      ng       3141: 	    textbox.value = "";
                   3142: 	    return;
                   3143: 	}
1.109     matthew  3144: 	if (parseFloat(point) > parseFloat(weight)) {
                   3145: 	    var resp = confirm("You entered a value ("+parseFloat(point)+
1.44      ng       3146: 			       ") greater than the weight of the part. Accept?");
                   3147: 	    if (resp == false) {
                   3148: 		textbox.value = "";
                   3149: 		return;
                   3150: 	    }
                   3151: 	}
1.42      ng       3152: 	selval[0].selected = true;
                   3153:     }
                   3154: 
                   3155:     function changeOneScore(partid,user) {
1.125     ng       3156: 	var selval = document.classgrade["GD_"+user+'_'+partid+"_solved"];
                   3157: 	if (selval[1].selected || selval[2].selected) {
                   3158: 	    document.classgrade["GD_"+user+'_'+partid+"_awarded"].value = "";
                   3159: 	    if (selval[2].selected) {
                   3160: 		document.classgrade["GD_"+user+'_'+partid+"_tries"].value = "0";
                   3161: 	    }
1.269     raeburn  3162:         }
1.42      ng       3163:     }
                   3164: 
                   3165:     function resetEntry(numpart) {
                   3166: 	for (ctpart=0;ctpart<numpart;ctpart++) {
1.125     ng       3167: 	    var partid = document.classgrade["partid_"+ctpart].value;
                   3168: 	    var radioButton = document.classgrade["RADVAL_"+partid];
                   3169: 	    var textbox = document.classgrade["TEXTVAL_"+partid];
                   3170: 	    var selval  = document.classgrade["SELVAL_"+partid];
1.42      ng       3171: 	    for (var i=0; i<radioButton.length; i++) {
                   3172: 		radioButton[i].checked=false;
                   3173: 
                   3174: 	    }
                   3175: 	    textbox.value = "";
                   3176: 	    selval[0].selected = true;
                   3177: 
                   3178: 	    for (i=0;i<document.classgrade.total.value;i++) {
1.125     ng       3179: 		var user = document.classgrade["ctr"+i].value;
1.289     albertel 3180: 		user = user.replace(new RegExp(':', 'g'),"_");
1.125     ng       3181: 		var resetscore = document.classgrade["GD_"+user+"_"+partid+"_awarded"];
                   3182: 		resetscore.value = document.classgrade["GD_"+user+"_"+partid+"_awarded_s"].value;
                   3183: 		var resettries = document.classgrade["GD_"+user+"_"+partid+"_tries"];
                   3184: 		resettries.value = document.classgrade["GD_"+user+"_"+partid+"_tries_s"].value;
                   3185: 		var saveselval   = document.classgrade["GD_"+user+"_"+partid+"_solved_s"].value;
                   3186: 		var selname   = document.classgrade["GD_"+user+"_"+partid+"_solved"];
1.42      ng       3187: 		if (saveselval == "excused") {
1.43      ng       3188: 		    if (selname[1].selected == false) { selname[1].selected = true;}
1.42      ng       3189: 		} else {
1.43      ng       3190: 		    if (selname[0].selected == false) {selname[0].selected = true};
1.42      ng       3191: 		}
                   3192: 	    }
1.41      ng       3193: 	}
1.42      ng       3194:     }
                   3195: 
1.41      ng       3196: </script>
                   3197: VIEWJAVASCRIPT
1.42      ng       3198: }
                   3199: 
1.44      ng       3200: #--- show scores for a section or whole class w/ option to change/update a score
1.42      ng       3201: sub viewgrades {
                   3202:     my ($request) = shift;
                   3203:     &viewgrades_js($request);
1.41      ng       3204: 
1.324     albertel 3205:     my ($symb) = &get_symb($request);
1.168     albertel 3206:     #need to make sure we have the correct data for later EXT calls, 
                   3207:     #thus invalidate the cache
                   3208:     &Apache::lonnet::devalidatecourseresdata(
1.257     albertel 3209:                  $env{'course.'.$env{'request.course.id'}.'.num'},
                   3210:                  $env{'course.'.$env{'request.course.id'}.'.domain'});
1.168     albertel 3211:     &Apache::lonnet::clear_EXT_cache_status();
                   3212: 
1.398     albertel 3213:     my $result='<h3><span class="LC_info">'.&mt('Manual Grading').'</span></h3>';
1.485     albertel 3214:     $result.='<h4>'.&mt('<b>Current Resource: </b>[_1]',$env{'form.probTitle'}).'</h4>'."\n";
1.41      ng       3215: 
                   3216:     #view individual student submission form - called using Javascript viewOneStudent
1.324     albertel 3217:     $result.=&jscriptNform($symb);
1.41      ng       3218: 
1.44      ng       3219:     #beginning of class grading form
1.442     banghart 3220:     my $stu_status = join(':',&Apache::loncommon::get_env_multiple('form.Status'));
1.41      ng       3221:     $result.= '<form action="/adm/grades" method="post" name="classgrade">'."\n".
1.418     albertel 3222: 	'<input type="hidden" name="symb"    value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
1.38      ng       3223: 	'<input type="hidden" name="command" value="editgrades" />'."\n".
1.432     banghart 3224: 	&build_section_inputs().
1.257     albertel 3225: 	'<input type="hidden" name="saveState" value="'.$env{'form.saveState'}.'" />'."\n".
1.442     banghart 3226: 	'<input type="hidden" name="Status" value="'.$env{'stu_status'}.'" />'."\n".
1.257     albertel 3227: 	'<input type="hidden" name="probTitle" value="'.$env{'form.probTitle'}.'" />'."\n";
1.72      ng       3228: 
1.126     ng       3229:     my $sectionClass;
1.430     banghart 3230:     my $section_display = join (", ",&Apache::loncommon::get_env_multiple('form.section'));
1.257     albertel 3231:     if ($env{'form.section'} eq 'all') {
1.539     riegler  3232: 	$sectionClass=&mt('Class');
1.257     albertel 3233:     } elsif ($env{'form.section'} eq 'none') {
1.539     riegler  3234: 	$sectionClass=&mt('Students in no Section');
1.52      albertel 3235:     } else {
1.539     riegler  3236: 	$sectionClass=&mt('Students in Section(s) [_1]');
1.52      albertel 3237:     }
1.485     albertel 3238:     $result.=
                   3239: 	'<h3>'.
1.539     riegler  3240: 	&mt("Assign Common Grade to [_1]",$sectionClass,$section_display).'</h3>';
1.474     albertel 3241:     $result.= &Apache::loncommon::start_data_table();
1.44      ng       3242:     #radio buttons/text box for assigning points for a section or class.
                   3243:     #handles different parts of a problem
1.375     albertel 3244:     my ($partlist,$handgrade,$responseType) = &response_type($symb);
1.42      ng       3245:     my %weight = ();
                   3246:     my $ctsparts = 0;
1.45      ng       3247:     my %seen = ();
1.375     albertel 3248:     my @part_response_id = &flatten_responseType($responseType);
                   3249:     foreach my $part_response_id (@part_response_id) {
                   3250:     	my ($partid,$respid) = @{ $part_response_id };
                   3251: 	my $part_resp = join('_',@{ $part_response_id });
1.45      ng       3252: 	next if $seen{$partid};
                   3253: 	$seen{$partid}++;
1.375     albertel 3254: 	my $handgrade=$$handgrade{$part_resp};
1.42      ng       3255: 	my $wgt = &Apache::lonnet::EXT('resource.'.$partid.'.weight',$symb);
                   3256: 	$weight{$partid} = $wgt eq '' ? '1' : $wgt;
                   3257: 
1.324     albertel 3258: 	my $display_part=&get_display_part($partid,$symb);
1.485     albertel 3259: 	my $radio.='<table border="0"><tr>';  
1.41      ng       3260: 	my $ctr = 0;
1.42      ng       3261: 	while ($ctr<=$weight{$partid}) { # display radio buttons in a nice table 10 across
1.485     albertel 3262: 	    $radio.= '<td><label><input type="radio" name="RADVAL_'.$partid.'" '.
1.54      albertel 3263: 		'onclick="javascript:writePoint(\''.$partid.'\','.$weight{$partid}.
1.288     albertel 3264: 		','.$ctr.')" />'.$ctr."</label></td>\n";
1.41      ng       3265: 	    $result.=(($ctr+1)%10 == 0 ? '</tr><tr>' : '');
                   3266: 	    $ctr++;
                   3267: 	}
1.485     albertel 3268: 	$radio.='</tr></table>';
                   3269: 	my $line = '<input type="text" name="TEXTVAL_'.
1.54      albertel 3270: 	    $partid.'" size="4" '.'onChange="javascript:writePoint(\''.
                   3271: 		$partid.'\','.$weight{$partid}.',\'textval\')" /> /'.
1.539     riegler  3272: 	    $weight{$partid}.' '.&mt('(problem weight)').'</td>'."\n";
                   3273: 	$line.= '<td><b>'.&mt('Grade Status').':</b><select name="SELVAL_'.$partid.'"'.
1.54      albertel 3274: 	    'onChange="javascript:writeRadText(\''.$partid.'\','.
1.59      albertel 3275: 		$weight{$partid}.')"> '.
1.401     albertel 3276: 	    '<option selected="selected"> </option>'.
1.485     albertel 3277: 	    '<option value="excused">'.&mt('excused').'</option>'.
                   3278: 	    '<option value="reset status">'.&mt('reset status').'</option>'.
                   3279: 	    '</select></td>'.
                   3280:             '<td><label><input type="checkbox" name="FORCE_'.$partid.'" />'.&mt('Override "Correct"').'</label>';
                   3281: 	$line.='<input type="hidden" name="partid_'.
                   3282: 	    $ctsparts.'" value="'.$partid.'" />'."\n";
                   3283: 	$line.='<input type="hidden" name="weight_'.
                   3284: 	    $partid.'" value="'.$weight{$partid}.'" />'."\n";
                   3285: 
                   3286: 	$result.=
                   3287: 	    &Apache::loncommon::start_data_table_row()."\n".
1.539     riegler  3288: 	    '<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 3289: 	    &Apache::loncommon::end_data_table_row()."\n";
1.42      ng       3290: 	$ctsparts++;
1.41      ng       3291:     }
1.474     albertel 3292:     $result.=&Apache::loncommon::end_data_table()."\n".
1.52      albertel 3293: 	'<input type="hidden" name="totalparts" value="'.$ctsparts.'" />';
1.485     albertel 3294:     $result.='<input type="button" value="'.&mt('Revert to Default').'" '.
1.474     albertel 3295: 	'onClick="javascript:resetEntry('.$ctsparts.');" />';
1.41      ng       3296: 
1.44      ng       3297:     #table listing all the students in a section/class
                   3298:     #header of table
1.539     riegler  3299:     $result.= '<h3>'.&mt('Assign Grade to Specific Students in ').$sectionClass,
                   3300: 			 $section_display.'</h3>';
1.474     albertel 3301:     $result.= &Apache::loncommon::start_data_table().
                   3302: 	&Apache::loncommon::start_data_table_header_row().
1.485     albertel 3303: 	'<th>'.&mt('No.').'</th>'.
1.474     albertel 3304: 	'<th>'.&nameUserString('header')."</th>\n";
1.324     albertel 3305:     my (@parts) = sort(&getpartlist($symb));
                   3306:     my (undef,undef,$url)=&Apache::lonnet::decode_symb($symb);
1.269     raeburn  3307:     my @partids = ();
1.41      ng       3308:     foreach my $part (@parts) {
                   3309: 	my $display=&Apache::lonnet::metadata($url,$part.'.display');
1.539     riegler  3310:         my $narrowtext = &mt('Tries');
                   3311: 	$display =~ s|^Number of Attempts|$narrowtext <br />|; # makes the column narrower
1.41      ng       3312: 	if  (!$display) { $display = &Apache::lonnet::metadata($url,$part.'.name'); }
1.207     albertel 3313: 	my ($partid) = &split_part_type($part);
1.524     raeburn  3314:         push(@partids,$partid);
1.324     albertel 3315: 	my $display_part=&get_display_part($partid,$symb);
1.41      ng       3316: 	if ($display =~ /^Partial Credit Factor/) {
1.485     albertel 3317: 	    $result.='<th>'.
                   3318: 		&mt('Score Part: [_1]<br /> (weight = [_2])',
                   3319: 		    $display_part,$weight{$partid}).'</th>'."\n";
1.41      ng       3320: 	    next;
1.485     albertel 3321: 	    
1.207     albertel 3322: 	} else {
1.485     albertel 3323: 	    if ($display =~ /Problem Status/) {
                   3324: 		my $grade_status_mt = &mt('Grade Status');
                   3325: 		$display =~ s{Problem Status}{$grade_status_mt<br />};
                   3326: 	    }
                   3327: 	    my $part_mt = &mt('Part:');
                   3328: 	    $display =~s{\[Part: \Q$partid\E\]}{$part_mt $display_part};
1.41      ng       3329: 	}
1.485     albertel 3330: 
1.474     albertel 3331: 	$result.='<th>'.$display.'</th>'."\n";
1.41      ng       3332:     }
1.474     albertel 3333:     $result.=&Apache::loncommon::end_data_table_header_row();
1.44      ng       3334: 
1.270     albertel 3335:     my %last_resets = 
                   3336: 	&get_last_resets($symb,$env{'request.course.id'},\@partids);
1.269     raeburn  3337: 
1.41      ng       3338:     #get info for each student
1.44      ng       3339:     #list all the students - with points and grade status
1.257     albertel 3340:     my (undef,undef,$fullname) = &getclasslist($env{'form.section'},'1');
1.41      ng       3341:     my $ctr = 0;
1.294     albertel 3342:     foreach (sort 
                   3343: 	     {
                   3344: 		 if (lc($$fullname{$a}) ne lc($$fullname{$b})) {
                   3345: 		     return (lc($$fullname{$a}) cmp lc($$fullname{$b}));
                   3346: 		 }
                   3347: 		 return $a cmp $b;
                   3348: 	     } (keys(%$fullname))) {
1.126     ng       3349: 	$ctr++;
1.324     albertel 3350: 	$result.=&viewstudentgrade($symb,$env{'request.course.id'},
1.269     raeburn  3351: 				   $_,$$fullname{$_},\@parts,\%weight,$ctr,\%last_resets);
1.41      ng       3352:     }
1.474     albertel 3353:     $result.=&Apache::loncommon::end_data_table();
1.41      ng       3354:     $result.='<input type="hidden" name="total" value="'.$ctr.'" />'."\n";
1.485     albertel 3355:     $result.='<input type="button" value="'.&mt('Save').'" '.
1.417     albertel 3356: 	'onClick="javascript:submit();" target="_self" /></form>'."\n";
1.96      albertel 3357:     if (scalar(%$fullname) eq 0) {
                   3358: 	my $colspan=3+scalar(@parts);
1.433     banghart 3359: 	my $section_display = join (", ",&Apache::loncommon::get_env_multiple('form.section'));
1.442     banghart 3360:         my $stu_status = join(' or ',&Apache::loncommon::get_env_multiple('form.Status'));
1.433     banghart 3361: 	$result='<span class="LC_warning">'.
1.485     albertel 3362: 	    &mt('There are no students in section(s) [_1] with enrollment status [_2] to modify or grade.',
1.442     banghart 3363: 	        $section_display, $stu_status).
1.433     banghart 3364: 	    '</span>';
1.96      albertel 3365:     }
1.324     albertel 3366:     $result.=&show_grading_menu_form($symb);
1.41      ng       3367:     return $result;
                   3368: }
                   3369: 
1.44      ng       3370: #--- call by previous routine to display each student
1.41      ng       3371: sub viewstudentgrade {
1.324     albertel 3372:     my ($symb,$courseid,$student,$fullname,$parts,$weight,$ctr,$last_resets) = @_;
1.44      ng       3373:     my ($uname,$udom) = split(/:/,$student);
                   3374:     my %record=&Apache::lonnet::restore($symb,$courseid,$udom,$uname);
1.269     raeburn  3375:     my %aggregates = (); 
1.474     albertel 3376:     my $result=&Apache::loncommon::start_data_table_row().'<td align="right">'.
1.233     albertel 3377: 	'<input type="hidden" name="ctr'.($ctr-1).'" value="'.$student.'" />'.
                   3378: 	"\n".$ctr.'&nbsp;</td><td>&nbsp;'.
1.44      ng       3379: 	'<a href="javascript:viewOneStudent(\''.$uname.'\',\''.$udom.
1.417     albertel 3380: 	'\');" target="_self">'.$fullname.'</a> '.
1.398     albertel 3381: 	'<span class="LC_internal_info">('.$uname.($env{'user.domain'} eq $udom ? '' : ':'.$udom).')</span></td>'."\n";
1.281     albertel 3382:     $student=~s/:/_/; # colon doen't work in javascript for names
1.63      albertel 3383:     foreach my $apart (@$parts) {
                   3384: 	my ($part,$type) = &split_part_type($apart);
1.41      ng       3385: 	my $score=$record{"resource.$part.$type"};
1.276     albertel 3386:         $result.='<td align="center">';
1.269     raeburn  3387:         my ($aggtries,$totaltries);
                   3388:         unless (exists($aggregates{$part})) {
1.270     albertel 3389: 	    $totaltries = $record{'resource.'.$part.'.tries'};
                   3390: 
                   3391: 	    $aggtries = $totaltries;
1.269     raeburn  3392:             if ($$last_resets{$part}) {  
1.270     albertel 3393:                 $aggtries = &get_num_tries(\%record,$$last_resets{$part},
                   3394: 					   $part);
                   3395:             }
1.269     raeburn  3396:             $result.='<input type="hidden" name="'.
                   3397:                 'GD_'.$student.'_'.$part.'_aggtries" value="'.$aggtries.'" />'."\n";
                   3398:             $result.='<input type="hidden" name="'.
                   3399:                 'GD_'.$student.'_'.$part.'_totaltries" value="'.$totaltries.'" />'."\n";
                   3400:             $aggregates{$part} = 1;
                   3401:         }
1.41      ng       3402: 	if ($type eq 'awarded') {
1.320     albertel 3403: 	    my $pts = $score eq '' ? '' : &compute_points($score,$$weight{$part});
1.42      ng       3404: 	    $result.='<input type="hidden" name="'.
1.89      albertel 3405: 		'GD_'.$student.'_'.$part.'_awarded_s" value="'.$pts.'" />'."\n";
1.233     albertel 3406: 	    $result.='<input type="text" name="'.
1.89      albertel 3407: 		'GD_'.$student.'_'.$part.'_awarded" '.
                   3408: 		'onChange="javascript:changeSelect(\''.$part.'\',\''.$student.
1.44      ng       3409: 		'\')" value="'.$pts.'" size="4" /></td>'."\n";
1.41      ng       3410: 	} elsif ($type eq 'solved') {
                   3411: 	    my ($status,$foo)=split(/_/,$score,2);
                   3412: 	    $status = 'nothing' if ($status eq '');
1.89      albertel 3413: 	    $result.='<input type="hidden" name="'.'GD_'.$student.'_'.
1.54      albertel 3414: 		$part.'_solved_s" value="'.$status.'" />'."\n";
1.233     albertel 3415: 	    $result.='&nbsp;<select name="'.
1.89      albertel 3416: 		'GD_'.$student.'_'.$part.'_solved" '.
                   3417: 		'onChange="javascript:changeOneScore(\''.$part.'\',\''.$student.'\')" >'."\n";
1.485     albertel 3418: 	    $result.= (($status eq 'excused') ? '<option> </option><option selected="selected" value="excused">'.&mt('excused').'</option>' 
                   3419: 		: '<option selected="selected"> </option><option value="excused">'.&mt('excused').'</option>')."\n";
                   3420: 	    $result.='<option value="reset status">'.&mt('reset status').'</option>';
1.126     ng       3421: 	    $result.="</select>&nbsp;</td>\n";
1.122     ng       3422: 	} else {
                   3423: 	    $result.='<input type="hidden" name="'.
                   3424: 		'GD_'.$student.'_'.$part.'_'.$type.'_s" value="'.$score.'" />'.
                   3425: 		    "\n";
1.233     albertel 3426: 	    $result.='<input type="text" name="'.
1.122     ng       3427: 		'GD_'.$student.'_'.$part.'_'.$type.'" '.
                   3428: 		'value="'.$score.'" size="4" /></td>'."\n";
1.41      ng       3429: 	}
                   3430:     }
1.474     albertel 3431:     $result.=&Apache::loncommon::end_data_table_row();
1.41      ng       3432:     return $result;
1.38      ng       3433: }
                   3434: 
1.44      ng       3435: #--- change scores for all the students in a section/class
                   3436: #    record does not get update if unchanged
1.38      ng       3437: sub editgrades {
1.41      ng       3438:     my ($request) = @_;
                   3439: 
1.324     albertel 3440:     my $symb=&get_symb($request);
1.433     banghart 3441:     my $section_display = join (", ",&Apache::loncommon::get_env_multiple('form.section'));
1.477     albertel 3442:     my $title='<h2>'.&mt('Current Grade Status').'</h2>';
                   3443:     $title.='<h4>'.&mt('<b>Current Resource: </b>[_1]',$env{'form.probTitle'}).'</h4>'."\n";
1.433     banghart 3444:     $title.='<h4>'.&mt('<b>Section: </b>[_1]',$section_display).'</h4>'."\n";
1.126     ng       3445: 
1.477     albertel 3446:     my $result= &Apache::loncommon::start_data_table().
                   3447: 	&Apache::loncommon::start_data_table_header_row().
                   3448: 	'<th rowspan="2" valign="middle">'.&mt('No.').'</th>'.
                   3449: 	'<th rowspan="2" valign="middle">'.&nameUserString('header')."</th>\n";
1.43      ng       3450:     my %scoreptr = (
                   3451: 		    'correct'  =>'correct_by_override',
                   3452: 		    'incorrect'=>'incorrect_by_override',
                   3453: 		    'excused'  =>'excused',
                   3454: 		    'ungraded' =>'ungraded_attempted',
                   3455: 		    'nothing'  => '',
                   3456: 		    );
1.257     albertel 3457:     my ($classlist,undef,$fullname) = &getclasslist($env{'form.section'},'0');
1.34      ng       3458: 
1.44      ng       3459:     my (@partid);
                   3460:     my %weight = ();
1.54      albertel 3461:     my %columns = ();
1.44      ng       3462:     my ($i,$ctr,$count,$rec_update) = (0,0,0,0);
1.54      albertel 3463: 
1.324     albertel 3464:     my (@parts) = sort(&getpartlist($symb));
1.54      albertel 3465:     my $header;
1.257     albertel 3466:     while ($ctr < $env{'form.totalparts'}) {
                   3467: 	my $partid = $env{'form.partid_'.$ctr};
1.524     raeburn  3468: 	push(@partid,$partid);
1.257     albertel 3469: 	$weight{$partid} = $env{'form.weight_'.$partid};
1.44      ng       3470: 	$ctr++;
1.54      albertel 3471:     }
1.324     albertel 3472:     my (undef,undef,$url) = &Apache::lonnet::decode_symb($symb);
1.54      albertel 3473:     foreach my $partid (@partid) {
1.478     albertel 3474: 	$header .= '<th align="center">'.&mt('Old Score').'</th>'.
                   3475: 	    '<th align="center">'.&mt('New Score').'</th>';
1.54      albertel 3476: 	$columns{$partid}=2;
                   3477: 	foreach my $stores (@parts) {
                   3478: 	    my ($part,$type) = &split_part_type($stores);
                   3479: 	    if ($part !~ m/^\Q$partid\E/) { next;}
                   3480: 	    if ($type eq 'awarded' || $type eq 'solved') { next; }
                   3481: 	    my $display=&Apache::lonnet::metadata($url,$stores.'.display');
1.551     raeburn  3482: 	    $display =~ s/\[Part: \Q$part\E\]//;
1.539     riegler  3483:             my $narrowtext = &mt('Tries');
                   3484: 	    $display =~ s/Number of Attempts/$narrowtext/;
                   3485: 	    $header .= '<th align="center">'.&mt('Old').' '.$display.'</th>'.
                   3486: 		'<th align="center">'.&mt('New').' '.$display.'</th>';
1.54      albertel 3487: 	    $columns{$partid}+=2;
                   3488: 	}
                   3489:     }
                   3490:     foreach my $partid (@partid) {
1.324     albertel 3491: 	my $display_part=&get_display_part($partid,$symb);
1.478     albertel 3492: 	$result .= '<th colspan="'.$columns{$partid}.'" align="center">'.
                   3493: 	    &mt('Part: [_1] (Weight = [_2])',$display_part,$weight{$partid}).
                   3494: 	    '</th>';
1.54      albertel 3495: 
1.44      ng       3496:     }
1.477     albertel 3497:     $result .= &Apache::loncommon::end_data_table_header_row().
                   3498: 	&Apache::loncommon::start_data_table_header_row().
                   3499: 	$header.
                   3500: 	&Apache::loncommon::end_data_table_header_row();
                   3501:     my @noupdate;
1.126     ng       3502:     my ($updateCtr,$noupdateCtr) = (1,1);
1.257     albertel 3503:     for ($i=0; $i<$env{'form.total'}; $i++) {
1.93      albertel 3504: 	my $line;
1.257     albertel 3505: 	my $user = $env{'form.ctr'.$i};
1.281     albertel 3506: 	my ($uname,$udom)=split(/:/,$user);
1.44      ng       3507: 	my %newrecord;
                   3508: 	my $updateflag = 0;
1.281     albertel 3509: 	$line .= '<td>'.&nameUserString(undef,$$fullname{$user},$uname,$udom).'</td>';
1.108     albertel 3510: 	my $usec=$classlist->{"$uname:$udom"}[5];
1.105     albertel 3511: 	if (!&canmodify($usec)) {
1.126     ng       3512: 	    my $numcols=scalar(@partid)*4+2;
1.477     albertel 3513: 	    push(@noupdate,
1.478     albertel 3514: 		 $line."<td colspan=\"$numcols\"><span class=\"LC_warning\">".
                   3515: 		 &mt('Not allowed to modify student')."</span></td></tr>");
1.105     albertel 3516: 	    next;
                   3517: 	}
1.269     raeburn  3518:         my %aggregate = ();
                   3519:         my $aggregateflag = 0;
1.281     albertel 3520: 	$user=~s/:/_/; # colon doen't work in javascript for names
1.44      ng       3521: 	foreach (@partid) {
1.257     albertel 3522: 	    my $old_aw    = $env{'form.GD_'.$user.'_'.$_.'_awarded_s'};
1.54      albertel 3523: 	    my $old_part_pcr = $old_aw/($weight{$_} ne '0' ? $weight{$_}:1);
                   3524: 	    my $old_part  = $old_aw eq '' ? '' : $old_part_pcr;
1.257     albertel 3525: 	    my $old_score = $scoreptr{$env{'form.GD_'.$user.'_'.$_.'_solved_s'}};
                   3526: 	    my $awarded   = $env{'form.GD_'.$user.'_'.$_.'_awarded'};
1.54      albertel 3527: 	    my $pcr       = $awarded/($weight{$_} ne '0' ? $weight{$_} : 1);
                   3528: 	    my $partial   = $awarded eq '' ? '' : $pcr;
1.44      ng       3529: 	    my $score;
                   3530: 	    if ($partial eq '') {
1.257     albertel 3531: 		$score = $scoreptr{$env{'form.GD_'.$user.'_'.$_.'_solved_s'}};
1.44      ng       3532: 	    } elsif ($partial > 0) {
                   3533: 		$score = 'correct_by_override';
                   3534: 	    } elsif ($partial == 0) {
                   3535: 		$score = 'incorrect_by_override';
                   3536: 	    }
1.257     albertel 3537: 	    my $dropMenu = $env{'form.GD_'.$user.'_'.$_.'_solved'};
1.125     ng       3538: 	    $score = 'excused' if (($dropMenu eq 'excused') && ($score ne 'excused'));
                   3539: 
1.292     albertel 3540: 	    $newrecord{'resource.'.$_.'.regrader'}=
                   3541: 		"$env{'user.name'}:$env{'user.domain'}";
1.125     ng       3542: 	    if ($dropMenu eq 'reset status' &&
                   3543: 		$old_score ne '') { # ignore if no previous attempts => nothing to reset
1.299     albertel 3544: 		$newrecord{'resource.'.$_.'.tries'} = '';
1.125     ng       3545: 		$newrecord{'resource.'.$_.'.solved'} = '';
                   3546: 		$newrecord{'resource.'.$_.'.award'} = '';
1.299     albertel 3547: 		$newrecord{'resource.'.$_.'.awarded'} = '';
1.125     ng       3548: 		$updateflag = 1;
1.269     raeburn  3549:                 if ($env{'form.GD_'.$user.'_'.$_.'_aggtries'} > 0) {
                   3550:                     my $aggtries = $env{'form.GD_'.$user.'_'.$_.'_aggtries'};
                   3551:                     my $totaltries = $env{'form.GD_'.$user.'_'.$_.'_totaltries'};
                   3552:                     my $solvedstatus = $env{'form.GD_'.$user.'_'.$_.'_solved_s'};
                   3553:                     &decrement_aggs($symb,$_,\%aggregate,$aggtries,$totaltries,$solvedstatus);
                   3554:                     $aggregateflag = 1;
                   3555:                 }
1.139     albertel 3556: 	    } elsif (!($old_part eq $partial && $old_score eq $score)) {
                   3557: 		$updateflag = 1;
                   3558: 		$newrecord{'resource.'.$_.'.awarded'}  = $partial if $partial ne '';
                   3559: 		$newrecord{'resource.'.$_.'.solved'}   = $score;
                   3560: 		$rec_update++;
1.125     ng       3561: 	    }
                   3562: 
1.93      albertel 3563: 	    $line .= '<td align="center">'.$old_aw.'&nbsp;</td>'.
1.44      ng       3564: 		'<td align="center">'.$awarded.
                   3565: 		($score eq 'excused' ? $score : '').'&nbsp;</td>';
1.5       albertel 3566: 
1.54      albertel 3567: 
                   3568: 	    my $partid=$_;
                   3569: 	    foreach my $stores (@parts) {
                   3570: 		my ($part,$type) = &split_part_type($stores);
                   3571: 		if ($part !~ m/^\Q$partid\E/) { next;}
                   3572: 		if ($type eq 'awarded' || $type eq 'solved') { next; }
1.257     albertel 3573: 		my $old_aw    = $env{'form.GD_'.$user.'_'.$part.'_'.$type.'_s'};
                   3574: 		my $awarded   = $env{'form.GD_'.$user.'_'.$part.'_'.$type};
1.54      albertel 3575: 		if ($awarded ne '' && $awarded ne $old_aw) {
                   3576: 		    $newrecord{'resource.'.$part.'.'.$type}= $awarded;
1.257     albertel 3577: 		    $newrecord{'resource.'.$part.'.regrader'}="$env{'user.name'}:$env{'user.domain'}";
1.54      albertel 3578: 		    $updateflag=1;
                   3579: 		}
1.93      albertel 3580: 		$line .= '<td align="center">'.$old_aw.'&nbsp;</td>'.
1.54      albertel 3581: 		    '<td align="center">'.$awarded.'&nbsp;</td>';
                   3582: 	    }
1.44      ng       3583: 	}
1.477     albertel 3584: 	$line.="\n";
1.301     albertel 3585: 
                   3586: 	my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   3587: 	my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   3588: 
1.44      ng       3589: 	if ($updateflag) {
                   3590: 	    $count++;
1.257     albertel 3591: 	    &Apache::lonnet::cstore(\%newrecord,$symb,$env{'request.course.id'},
1.89      albertel 3592: 				    $udom,$uname);
1.301     albertel 3593: 
                   3594: 	    if (&Apache::bridgetask::in_queue('gradingqueue',$symb,$cdom,
                   3595: 					      $cnum,$udom,$uname)) {
                   3596: 		# need to figure out if should be in queue.
                   3597: 		my %record =  
                   3598: 		    &Apache::lonnet::restore($symb,$env{'request.course.id'},
                   3599: 					     $udom,$uname);
                   3600: 		my $all_graded = 1;
                   3601: 		my $none_graded = 1;
                   3602: 		foreach my $part (@parts) {
                   3603: 		    if ( $record{'resource.'.$part.'.awarded'} eq '' ) {
                   3604: 			$all_graded = 0;
                   3605: 		    } else {
                   3606: 			$none_graded = 0;
                   3607: 		    }
                   3608: 		}
                   3609: 
                   3610: 		if ($all_graded || $none_graded) {
                   3611: 		    &Apache::bridgetask::remove_from_queue('gradingqueue',
                   3612: 							   $symb,$cdom,$cnum,
                   3613: 							   $udom,$uname);
                   3614: 		}
                   3615: 	    }
                   3616: 
1.477     albertel 3617: 	    $result.=&Apache::loncommon::start_data_table_row().
                   3618: 		'<td align="right">&nbsp;'.$updateCtr.'&nbsp;</td>'.$line.
                   3619: 		&Apache::loncommon::end_data_table_row();
1.126     ng       3620: 	    $updateCtr++;
1.93      albertel 3621: 	} else {
1.477     albertel 3622: 	    push(@noupdate,
                   3623: 		 '<td align="right">&nbsp;'.$noupdateCtr.'&nbsp;</td>'.$line);
1.126     ng       3624: 	    $noupdateCtr++;
1.44      ng       3625: 	}
1.269     raeburn  3626:         if ($aggregateflag) {
                   3627:             &Apache::lonnet::cinc('nohist_resourcetracker',\%aggregate,
1.301     albertel 3628: 				  $cdom,$cnum);
1.269     raeburn  3629:         }
1.93      albertel 3630:     }
1.477     albertel 3631:     if (@noupdate) {
1.126     ng       3632: #	my $numcols=(scalar(@partid)*(scalar(@parts)-1)*2)+3;
                   3633: 	my $numcols=scalar(@partid)*4+2;
1.477     albertel 3634: 	$result .= &Apache::loncommon::start_data_table_row('LC_empty_row').
1.478     albertel 3635: 	    '<td align="center" colspan="'.$numcols.'">'.
                   3636: 	    &mt('No Changes Occurred For the Students Below').
                   3637: 	    '</td>'.
1.477     albertel 3638: 	    &Apache::loncommon::end_data_table_row();
                   3639: 	foreach my $line (@noupdate) {
                   3640: 	    $result.=
                   3641: 		&Apache::loncommon::start_data_table_row().
                   3642: 		$line.
                   3643: 		&Apache::loncommon::end_data_table_row();
                   3644: 	}
1.44      ng       3645:     }
1.477     albertel 3646:     $result .= &Apache::loncommon::end_data_table().
                   3647: 	&show_grading_menu_form($symb);
1.478     albertel 3648:     my $msg = '<p><b>'.
                   3649: 	&mt('Number of records updated = [_1] for [quant,_2,student].',
                   3650: 	    $rec_update,$count).'</b><br />'.
                   3651: 	'<b>'.&mt('Total number of students = [_1]',$env{'form.total'}).
                   3652: 	'</b></p>';
1.44      ng       3653:     return $title.$msg.$result;
1.5       albertel 3654: }
1.54      albertel 3655: 
                   3656: sub split_part_type {
                   3657:     my ($partstr) = @_;
                   3658:     my ($temp,@allparts)=split(/_/,$partstr);
                   3659:     my $type=pop(@allparts);
1.439     albertel 3660:     my $part=join('_',@allparts);
1.54      albertel 3661:     return ($part,$type);
                   3662: }
                   3663: 
1.44      ng       3664: #------------- end of section for handling grading by section/class ---------
                   3665: #
                   3666: #----------------------------------------------------------------------------
                   3667: 
1.5       albertel 3668: 
1.44      ng       3669: #----------------------------------------------------------------------------
                   3670: #
                   3671: #-------------------------- Next few routines handles grading by csv upload
                   3672: #
                   3673: #--- Javascript to handle csv upload
1.27      albertel 3674: sub csvupload_javascript_reverse_associate {
1.246     albertel 3675:     my $error1=&mt('You need to specify the username or ID');
                   3676:     my $error2=&mt('You need to specify at least one grading field');
1.27      albertel 3677:   return(<<ENDPICK);
                   3678:   function verify(vf) {
                   3679:     var foundsomething=0;
                   3680:     var founduname=0;
1.243     albertel 3681:     var foundID=0;
1.27      albertel 3682:     for (i=0;i<=vf.nfields.value;i++) {
                   3683:       tw=eval('vf.f'+i+'.selectedIndex');
1.243     albertel 3684:       if (i==0 && tw!=0) { foundID=1; }
                   3685:       if (i==1 && tw!=0) { founduname=1; }
                   3686:       if (i!=0 && i!=1 && i!=2 && tw!=0) { foundsomething=1; }
1.27      albertel 3687:     }
1.246     albertel 3688:     if (founduname==0 && foundID==0) {
                   3689: 	alert('$error1');
                   3690: 	return;
1.27      albertel 3691:     }
                   3692:     if (foundsomething==0) {
1.246     albertel 3693: 	alert('$error2');
                   3694: 	return;
1.27      albertel 3695:     }
                   3696:     vf.submit();
                   3697:   }
                   3698:   function flip(vf,tf) {
                   3699:     var nw=eval('vf.f'+tf+'.selectedIndex');
                   3700:     var i;
                   3701:     for (i=0;i<=vf.nfields.value;i++) {
                   3702:       //can not pick the same destination field for both name and domain
                   3703:       if (((i ==0)||(i ==1)) && 
                   3704:           ((tf==0)||(tf==1)) && 
                   3705:           (i!=tf) &&
                   3706:           (eval('vf.f'+i+'.selectedIndex')==nw)) {
                   3707:         eval('vf.f'+i+'.selectedIndex=0;')
                   3708:       }
                   3709:     }
                   3710:   }
                   3711: ENDPICK
                   3712: }
                   3713: 
                   3714: sub csvupload_javascript_forward_associate {
1.246     albertel 3715:     my $error1=&mt('You need to specify the username or ID');
                   3716:     my $error2=&mt('You need to specify at least one grading field');
1.27      albertel 3717:   return(<<ENDPICK);
                   3718:   function verify(vf) {
                   3719:     var foundsomething=0;
                   3720:     var founduname=0;
1.243     albertel 3721:     var foundID=0;
1.27      albertel 3722:     for (i=0;i<=vf.nfields.value;i++) {
                   3723:       tw=eval('vf.f'+i+'.selectedIndex');
1.243     albertel 3724:       if (tw==1) { foundID=1; }
                   3725:       if (tw==2) { founduname=1; }
                   3726:       if (tw>3) { foundsomething=1; }
1.27      albertel 3727:     }
1.246     albertel 3728:     if (founduname==0 && foundID==0) {
                   3729: 	alert('$error1');
                   3730: 	return;
1.27      albertel 3731:     }
                   3732:     if (foundsomething==0) {
1.246     albertel 3733: 	alert('$error2');
                   3734: 	return;
1.27      albertel 3735:     }
                   3736:     vf.submit();
                   3737:   }
                   3738:   function flip(vf,tf) {
                   3739:     var nw=eval('vf.f'+tf+'.selectedIndex');
                   3740:     var i;
                   3741:     //can not pick the same destination field twice
                   3742:     for (i=0;i<=vf.nfields.value;i++) {
                   3743:       if ((i!=tf) && (eval('vf.f'+i+'.selectedIndex')==nw)) {
                   3744:         eval('vf.f'+i+'.selectedIndex=0;')
                   3745:       }
                   3746:     }
                   3747:   }
                   3748: ENDPICK
                   3749: }
                   3750: 
1.26      albertel 3751: sub csvuploadmap_header {
1.324     albertel 3752:     my ($request,$symb,$datatoken,$distotal)= @_;
1.41      ng       3753:     my $javascript;
1.257     albertel 3754:     if ($env{'form.upfile_associate'} eq 'reverse') {
1.41      ng       3755: 	$javascript=&csvupload_javascript_reverse_associate();
                   3756:     } else {
                   3757: 	$javascript=&csvupload_javascript_forward_associate();
                   3758:     }
1.45      ng       3759: 
1.324     albertel 3760:     my ($result) = &showResourceInfo($symb,$env{'form.probTitle'});
1.257     albertel 3761:     my $checked=(($env{'form.noFirstLine'})?' checked="checked"':'');
1.245     albertel 3762:     my $ignore=&mt('Ignore First Line');
1.418     albertel 3763:     $symb = &Apache::lonenc::check_encrypt($symb);
1.41      ng       3764:     $request->print(<<ENDPICK);
1.26      albertel 3765: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="gradesupload">
1.398     albertel 3766: <h3><span class="LC_info">Uploading Class Grades</span></h3>
1.45      ng       3767: $result
1.326     albertel 3768: <hr />
1.26      albertel 3769: <h3>Identify fields</h3>
                   3770: Total number of records found in file: $distotal <hr />
                   3771: Enter as many fields as you can. The system will inform you and bring you back
                   3772: to this page if the data selected is insufficient to run your class.<hr />
                   3773: <input type="button" value="Reverse Association" onClick="javascript:this.form.associate.value='Reverse Association';submit(this.form);" />
1.245     albertel 3774: <label><input type="checkbox" name="noFirstLine" $checked />$ignore</label>
1.26      albertel 3775: <input type="hidden" name="associate"  value="" />
                   3776: <input type="hidden" name="phase"      value="three" />
                   3777: <input type="hidden" name="datatoken"  value="$datatoken" />
1.257     albertel 3778: <input type="hidden" name="fileupload" value="$env{'form.fileupload'}" />
                   3779: <input type="hidden" name="upfiletype" value="$env{'form.upfiletype'}" />
1.26      albertel 3780: <input type="hidden" name="upfile_associate" 
1.257     albertel 3781:                                        value="$env{'form.upfile_associate'}" />
1.26      albertel 3782: <input type="hidden" name="symb"       value="$symb" />
1.257     albertel 3783: <input type="hidden" name="saveState"  value="$env{'form.saveState'}" />
                   3784: <input type="hidden" name="probTitle"  value="$env{'form.probTitle'}" />
1.246     albertel 3785: <input type="hidden" name="command"    value="csvuploadoptions" />
1.26      albertel 3786: <hr />
                   3787: <script type="text/javascript" language="Javascript">
                   3788: $javascript
                   3789: </script>
                   3790: ENDPICK
1.118     ng       3791:     return '';
1.26      albertel 3792: 
                   3793: }
                   3794: 
                   3795: sub csvupload_fields {
1.324     albertel 3796:     my ($symb) = @_;
                   3797:     my (@parts) = &getpartlist($symb);
1.556     weissno  3798:     my @fields=(['ID','Student/Employee ID'],
1.243     albertel 3799: 		['username','Student Username'],
                   3800: 		['domain','Student Domain']);
1.324     albertel 3801:     my (undef,undef,$url) = &Apache::lonnet::decode_symb($symb);
1.41      ng       3802:     foreach my $part (sort(@parts)) {
                   3803: 	my @datum;
                   3804: 	my $display=&Apache::lonnet::metadata($url,$part.'.display');
                   3805: 	my $name=$part;
                   3806: 	if  (!$display) { $display = $name; }
                   3807: 	@datum=($name,$display);
1.244     albertel 3808: 	if ($name=~/^stores_(.*)_awarded/) {
                   3809: 	    push(@fields,['stores_'.$1.'_points',"Points [Part: $1]"]);
                   3810: 	}
1.41      ng       3811: 	push(@fields,\@datum);
                   3812:     }
                   3813:     return (@fields);
1.26      albertel 3814: }
                   3815: 
                   3816: sub csvuploadmap_footer {
1.41      ng       3817:     my ($request,$i,$keyfields) =@_;
                   3818:     $request->print(<<ENDPICK);
1.26      albertel 3819: </table>
                   3820: <input type="hidden" name="nfields" value="$i" />
                   3821: <input type="hidden" name="keyfields" value="$keyfields" />
                   3822: <input type="button" onClick="javascript:verify(this.form)" value="Assign Grades" /><br />
                   3823: </form>
                   3824: ENDPICK
                   3825: }
                   3826: 
1.283     albertel 3827: sub checkforfile_js {
1.539     riegler  3828:     my $alertmsg = &mt('Please use the browse button to select a file from your local directory.');
1.86      ng       3829:     my $result =<<CSVFORMJS;
                   3830: <script type="text/javascript" language="javascript">
                   3831:     function checkUpload(formname) {
                   3832: 	if (formname.upfile.value == "") {
1.539     riegler  3833: 	    alert("$alertmsg");
1.86      ng       3834: 	    return false;
                   3835: 	}
                   3836: 	formname.submit();
                   3837:     }
                   3838:     </script>
                   3839: CSVFORMJS
1.283     albertel 3840:     return $result;
                   3841: }
                   3842: 
                   3843: sub upcsvScores_form {
                   3844:     my ($request) = shift;
1.324     albertel 3845:     my ($symb)=&get_symb($request);
1.283     albertel 3846:     if (!$symb) {return '';}
                   3847:     my $result=&checkforfile_js();
1.257     albertel 3848:     $env{'form.probTitle'} = &Apache::lonnet::gettitle($symb);
1.324     albertel 3849:     my ($table) = &showResourceInfo($symb,$env{'form.probTitle'});
1.118     ng       3850:     $result.=$table;
1.326     albertel 3851:     $result.='<br /><table width="100%" border="0"><tr><td bgcolor="#777777">'."\n";
                   3852:     $result.='<table width="100%" border="0"><tr bgcolor="#e6ffff"><td>'."\n";
1.538     schulted 3853:     $result.='&nbsp;<b>'.&mt('Specify a file containing the class scores for current resource.').
                   3854: 	'</b></td></tr>'."\n";
1.86      ng       3855:     $result.='<tr bgcolor=#ffffe6><td>'."\n";
1.370     www      3856:     my $upload=&mt("Upload Scores");
1.86      ng       3857:     my $upfile_select=&Apache::loncommon::upfile_select_html();
1.245     albertel 3858:     my $ignore=&mt('Ignore First Line');
1.418     albertel 3859:     $symb = &Apache::lonenc::check_encrypt($symb);
1.86      ng       3860:     $result.=<<ENDUPFORM;
1.106     albertel 3861: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="gradesupload">
1.86      ng       3862: <input type="hidden" name="symb" value="$symb" />
                   3863: <input type="hidden" name="command" value="csvuploadmap" />
1.257     albertel 3864: <input type="hidden" name="probTitle" value="$env{'form.probTitle'}" />
                   3865: <input type="hidden" name="saveState"  value="$env{'form.saveState'}" />
1.86      ng       3866: $upfile_select
1.370     www      3867: <br /><input type="button" onClick="javascript:checkUpload(this.form);" value="$upload" />
1.283     albertel 3868: <label><input type="checkbox" name="noFirstLine" />$ignore</label>
1.86      ng       3869: </form>
                   3870: ENDUPFORM
1.370     www      3871:     $result.=&Apache::loncommon::help_open_topic("Course_Convert_To_CSV",
                   3872:                            &mt("How do I create a CSV file from a spreadsheet"))
                   3873:     .'</td></tr></table>'."\n";
1.86      ng       3874:     $result.='</td></tr></table><br /><br />'."\n";
1.324     albertel 3875:     $result.=&show_grading_menu_form($symb);
1.86      ng       3876:     return $result;
                   3877: }
                   3878: 
                   3879: 
1.26      albertel 3880: sub csvuploadmap {
1.41      ng       3881:     my ($request)= @_;
1.324     albertel 3882:     my ($symb)=&get_symb($request);
1.41      ng       3883:     if (!$symb) {return '';}
1.72      ng       3884: 
1.41      ng       3885:     my $datatoken;
1.257     albertel 3886:     if (!$env{'form.datatoken'}) {
1.41      ng       3887: 	$datatoken=&Apache::loncommon::upfile_store($request);
1.26      albertel 3888:     } else {
1.257     albertel 3889: 	$datatoken=$env{'form.datatoken'};
1.41      ng       3890: 	&Apache::loncommon::load_tmp_file($request);
1.26      albertel 3891:     }
1.41      ng       3892:     my @records=&Apache::loncommon::upfile_record_sep();
1.257     albertel 3893:     if ($env{'form.noFirstLine'}) { shift(@records); }
1.324     albertel 3894:     &csvuploadmap_header($request,$symb,$datatoken,$#records+1);
1.41      ng       3895:     my ($i,$keyfields);
                   3896:     if (@records) {
1.324     albertel 3897: 	my @fields=&csvupload_fields($symb);
1.45      ng       3898: 
1.257     albertel 3899: 	if ($env{'form.upfile_associate'} eq 'reverse') {	
1.41      ng       3900: 	    &Apache::loncommon::csv_print_samples($request,\@records);
                   3901: 	    $i=&Apache::loncommon::csv_print_select_table($request,\@records,
                   3902: 							  \@fields);
                   3903: 	    foreach (@fields) { $keyfields.=$_->[0].','; }
                   3904: 	    chop($keyfields);
                   3905: 	} else {
                   3906: 	    unshift(@fields,['none','']);
                   3907: 	    $i=&Apache::loncommon::csv_samples_select_table($request,\@records,
                   3908: 							    \@fields);
1.311     banghart 3909:             foreach my $rec (@records) {
                   3910:                 my %temp = &Apache::loncommon::record_sep($rec);
                   3911:                 if (%temp) {
                   3912:                     $keyfields=join(',',sort(keys(%temp)));
                   3913:                     last;
                   3914:                 }
                   3915:             }
1.41      ng       3916: 	}
                   3917:     }
                   3918:     &csvuploadmap_footer($request,$i,$keyfields);
1.324     albertel 3919:     $request->print(&show_grading_menu_form($symb));
1.72      ng       3920: 
1.41      ng       3921:     return '';
1.27      albertel 3922: }
                   3923: 
1.246     albertel 3924: sub csvuploadoptions {
1.41      ng       3925:     my ($request)= @_;
1.324     albertel 3926:     my ($symb)=&get_symb($request);
1.257     albertel 3927:     my $checked=(($env{'form.noFirstLine'})?'1':'0');
1.246     albertel 3928:     my $ignore=&mt('Ignore First Line');
                   3929:     $request->print(<<ENDPICK);
                   3930: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="gradesupload">
1.398     albertel 3931: <h3><span class="LC_info">Uploading Class Grade Options</span></h3>
1.246     albertel 3932: <input type="hidden" name="command"    value="csvuploadassign" />
1.302     albertel 3933: <!--
1.246     albertel 3934: <p>
                   3935: <label>
                   3936:    <input type="checkbox" name="show_full_results" />
                   3937:    Show a table of all changes
                   3938: </label>
                   3939: </p>
1.302     albertel 3940: -->
1.246     albertel 3941: <p>
                   3942: <label>
                   3943:    <input type="checkbox" name="overwite_scores" checked="checked" />
                   3944:    Overwrite any existing score
                   3945: </label>
                   3946: </p>
                   3947: ENDPICK
                   3948:     my %fields=&get_fields();
                   3949:     if (!defined($fields{'domain'})) {
1.257     albertel 3950: 	my $domform = &Apache::loncommon::select_dom_form($env{'request.role.domain'},'default_domain');
1.246     albertel 3951: 	$request->print("\n<p> Users are in domain: ".$domform."</p>\n");
                   3952:     }
1.257     albertel 3953:     foreach my $key (sort(keys(%env))) {
1.246     albertel 3954: 	if ($key !~ /^form\.(.*)$/) { next; }
                   3955: 	my $cleankey=$1;
                   3956: 	if ($cleankey eq 'command') { next; }
                   3957: 	$request->print('<input type="hidden" name="'.$cleankey.
1.257     albertel 3958: 			'"  value="'.$env{$key}.'" />'."\n");
1.246     albertel 3959:     }
                   3960:     # FIXME do a check for any duplicated user ids...
                   3961:     # FIXME do a check for any invalid user ids?...
1.290     albertel 3962:     $request->print('<input type="submit" value="Assign Grades" /><br />
                   3963: <hr /></form>'."\n");
1.324     albertel 3964:     $request->print(&show_grading_menu_form($symb));
1.246     albertel 3965:     return '';
                   3966: }
                   3967: 
                   3968: sub get_fields {
                   3969:     my %fields;
1.257     albertel 3970:     my @keyfields = split(/\,/,$env{'form.keyfields'});
                   3971:     for (my $i=0; $i<=$env{'form.nfields'}; $i++) {
                   3972: 	if ($env{'form.upfile_associate'} eq 'reverse') {
                   3973: 	    if ($env{'form.f'.$i} ne 'none') {
                   3974: 		$fields{$keyfields[$i]}=$env{'form.f'.$i};
1.41      ng       3975: 	    }
                   3976: 	} else {
1.257     albertel 3977: 	    if ($env{'form.f'.$i} ne 'none') {
                   3978: 		$fields{$env{'form.f'.$i}}=$keyfields[$i];
1.41      ng       3979: 	    }
                   3980: 	}
1.27      albertel 3981:     }
1.246     albertel 3982:     return %fields;
                   3983: }
                   3984: 
                   3985: sub csvuploadassign {
                   3986:     my ($request)= @_;
1.324     albertel 3987:     my ($symb)=&get_symb($request);
1.246     albertel 3988:     if (!$symb) {return '';}
1.345     bowersj2 3989:     my $error_msg = '';
1.246     albertel 3990:     &Apache::loncommon::load_tmp_file($request);
                   3991:     my @gradedata = &Apache::loncommon::upfile_record_sep();
1.257     albertel 3992:     if ($env{'form.noFirstLine'}) { shift(@gradedata); }
1.246     albertel 3993:     my %fields=&get_fields();
1.41      ng       3994:     $request->print('<h3>Assigning Grades</h3>');
1.257     albertel 3995:     my $courseid=$env{'request.course.id'};
1.97      albertel 3996:     my ($classlist) = &getclasslist('all',0);
1.106     albertel 3997:     my @notallowed;
1.41      ng       3998:     my @skipped;
                   3999:     my $countdone=0;
                   4000:     foreach my $grade (@gradedata) {
                   4001: 	my %entries=&Apache::loncommon::record_sep($grade);
1.246     albertel 4002: 	my $domain;
                   4003: 	if ($entries{$fields{'domain'}}) {
                   4004: 	    $domain=$entries{$fields{'domain'}};
                   4005: 	} else {
1.257     albertel 4006: 	    $domain=$env{'form.default_domain'};
1.246     albertel 4007: 	}
1.243     albertel 4008: 	$domain=~s/\s//g;
1.41      ng       4009: 	my $username=$entries{$fields{'username'}};
1.160     albertel 4010: 	$username=~s/\s//g;
1.243     albertel 4011: 	if (!$username) {
                   4012: 	    my $id=$entries{$fields{'ID'}};
1.247     albertel 4013: 	    $id=~s/\s//g;
1.243     albertel 4014: 	    my %ids=&Apache::lonnet::idget($domain,$id);
                   4015: 	    $username=$ids{$id};
                   4016: 	}
1.41      ng       4017: 	if (!exists($$classlist{"$username:$domain"})) {
1.247     albertel 4018: 	    my $id=$entries{$fields{'ID'}};
                   4019: 	    $id=~s/\s//g;
                   4020: 	    if ($id) {
                   4021: 		push(@skipped,"$id:$domain");
                   4022: 	    } else {
                   4023: 		push(@skipped,"$username:$domain");
                   4024: 	    }
1.41      ng       4025: 	    next;
                   4026: 	}
1.108     albertel 4027: 	my $usec=$classlist->{"$username:$domain"}[5];
1.106     albertel 4028: 	if (!&canmodify($usec)) {
                   4029: 	    push(@notallowed,"$username:$domain");
                   4030: 	    next;
                   4031: 	}
1.244     albertel 4032: 	my %points;
1.41      ng       4033: 	my %grades;
                   4034: 	foreach my $dest (keys(%fields)) {
1.244     albertel 4035: 	    if ($dest eq 'ID' || $dest eq 'username' ||
                   4036: 		$dest eq 'domain') { next; }
                   4037: 	    if ($entries{$fields{$dest}} =~ /^\s*$/) { next; }
                   4038: 	    if ($dest=~/stores_(.*)_points/) {
                   4039: 		my $part=$1;
                   4040: 		my $wgt =&Apache::lonnet::EXT('resource.'.$part.'.weight',
                   4041: 					      $symb,$domain,$username);
1.345     bowersj2 4042:                 if ($wgt) {
                   4043:                     $entries{$fields{$dest}}=~s/\s//g;
                   4044:                     my $pcr=$entries{$fields{$dest}} / $wgt;
1.463     albertel 4045:                     my $award=($pcr == 0) ? 'incorrect_by_override'
                   4046:                                           : 'correct_by_override';
1.345     bowersj2 4047:                     $grades{"resource.$part.awarded"}=$pcr;
                   4048:                     $grades{"resource.$part.solved"}=$award;
                   4049:                     $points{$part}=1;
                   4050:                 } else {
                   4051:                     $error_msg = "<br />" .
                   4052:                         &mt("Some point values were assigned"
                   4053:                             ." for problems with a weight "
                   4054:                             ."of zero. These values were "
                   4055:                             ."ignored.");
                   4056:                 }
1.244     albertel 4057: 	    } else {
                   4058: 		if ($dest=~/stores_(.*)_awarded/) { if ($points{$1}) {next;} }
                   4059: 		if ($dest=~/stores_(.*)_solved/)  { if ($points{$1}) {next;} }
                   4060: 		my $store_key=$dest;
                   4061: 		$store_key=~s/^stores/resource/;
                   4062: 		$store_key=~s/_/\./g;
                   4063: 		$grades{$store_key}=$entries{$fields{$dest}};
                   4064: 	    }
1.41      ng       4065: 	}
1.508     www      4066: 	if (! %grades) { 
                   4067:            push(@skipped,&mt("[_1]: no data to save","$username:$domain")); 
                   4068:         } else {
                   4069: 	   $grades{"resource.regrader"}="$env{'user.name'}:$env{'user.domain'}";
                   4070: 	   my $result=&Apache::lonnet::cstore(\%grades,$symb,
1.302     albertel 4071: 					   $env{'request.course.id'},
                   4072: 					   $domain,$username);
1.508     www      4073: 	   if ($result eq 'ok') {
                   4074: 	      $request->print('.');
                   4075: 	   } else {
                   4076: 	      $request->print("<p><span class=\"LC_error\">".
                   4077:                               &mt("Failed to save data for student [_1]. Message when trying to save was: [_2]",
                   4078:                                   "$username:$domain",$result)."</span></p>");
                   4079: 	   }
                   4080: 	   $request->rflush();
                   4081: 	   $countdone++;
                   4082:         }
1.41      ng       4083:     }
1.508     www      4084:     $request->print('<br /><span class="LC_info">'.&mt("Saved [_1] students",$countdone)."</span>\n");
1.41      ng       4085:     if (@skipped) {
1.508     www      4086: 	$request->print('<p><span class="LC_warning">'.&mt('Skipped Students').'</span></p>');
1.106     albertel 4087: 	foreach my $student (@skipped) { $request->print("$student<br />\n"); }
                   4088:     }
                   4089:     if (@notallowed) {
1.508     www      4090: 	$request->print('<p><span class="LC_error">'.&mt('Students Not Allowed to Modify').'</span></p>');
1.106     albertel 4091: 	foreach my $student (@notallowed) { $request->print("$student<br />\n"); }
1.41      ng       4092:     }
1.106     albertel 4093:     $request->print("<br />\n");
1.324     albertel 4094:     $request->print(&show_grading_menu_form($symb));
1.345     bowersj2 4095:     return $error_msg;
1.26      albertel 4096: }
1.44      ng       4097: #------------- end of section for handling csv file upload ---------
                   4098: #
                   4099: #-------------------------------------------------------------------
                   4100: #
1.122     ng       4101: #-------------- Next few routines handle grading by page/sequence
1.72      ng       4102: #
                   4103: #--- Select a page/sequence and a student to grade
1.68      ng       4104: sub pickStudentPage {
                   4105:     my ($request) = shift;
                   4106: 
1.539     riegler  4107:     my $alertmsg = &mt('Please select the student you wish to grade.');
1.68      ng       4108:     $request->print(<<LISTJAVASCRIPT);
                   4109: <script type="text/javascript" language="javascript">
                   4110: 
                   4111: function checkPickOne(formname) {
1.76      ng       4112:     if (radioSelection(formname.student) == null) {
1.539     riegler  4113: 	alert("$alertmsg");
1.68      ng       4114: 	return;
                   4115:     }
1.125     ng       4116:     ptr = pullDownSelection(formname.selectpage);
                   4117:     formname.page.value = formname["page"+ptr].value;
                   4118:     formname.title.value = formname["title"+ptr].value;
1.68      ng       4119:     formname.submit();
                   4120: }
                   4121: 
                   4122: </script>
                   4123: LISTJAVASCRIPT
1.118     ng       4124:     &commonJSfunctions($request);
1.324     albertel 4125:     my ($symb) = &get_symb($request);
1.257     albertel 4126:     my $cdom      = $env{"course.$env{'request.course.id'}.domain"};
                   4127:     my $cnum      = $env{"course.$env{'request.course.id'}.num"};
                   4128:     my $getsec    = $env{'form.section'} eq '' ? 'all' : $env{'form.section'};
1.68      ng       4129: 
1.398     albertel 4130:     my $result='<h3><span class="LC_info">&nbsp;'.
1.485     albertel 4131: 	&mt('Manual Grading by Page or Sequence').'</span></h3>';
1.68      ng       4132: 
1.80      ng       4133:     $result.='<form action="/adm/grades" method="post" name="displayPage">'."\n";
1.423     albertel 4134:     my ($titles,$symbx) = &getSymbMap();
1.137     albertel 4135:     my ($curpage) =&Apache::lonnet::decode_symb($symb); 
                   4136: #    my ($curpage,$mapId) =&Apache::lonnet::decode_symb($symb); 
                   4137: #    my $type=($curpage =~ /\.(page|sequence)/);
1.485     albertel 4138:     my $select = '<select name="selectpage">'."\n";
1.70      ng       4139:     my $ctr=0;
1.68      ng       4140:     foreach (@$titles) {
                   4141: 	my ($minder,$showtitle) = ($_ =~ /(\d+)\.(.*)/);
1.485     albertel 4142: 	$select.='<option value="'.$ctr.'" '.
1.401     albertel 4143: 	    ($$symbx{$_} =~ /$curpage$/ ? 'selected="selected"' : '').
1.71      ng       4144: 	    '>'.$showtitle.'</option>'."\n";
1.70      ng       4145: 	$ctr++;
1.68      ng       4146:     }
1.485     albertel 4147:     $select.= '</select>';
1.539     riegler  4148:     $result.='&nbsp;<b>'.&mt('Problems from').':</b> '.$select."<br />\n";
1.485     albertel 4149: 
1.70      ng       4150:     $ctr=0;
                   4151:     foreach (@$titles) {
                   4152: 	my ($minder,$showtitle) = ($_ =~ /(\d+)\.(.*)/);
                   4153: 	$result.='<input type="hidden" name="page'.$ctr.'" value="'.$$symbx{$_}.'" />'."\n";
                   4154: 	$result.='<input type="hidden" name="title'.$ctr.'" value="'.$showtitle.'" />'."\n";
                   4155: 	$ctr++;
                   4156:     }
1.72      ng       4157:     $result.='<input type="hidden" name="page" />'."\n".
                   4158: 	'<input type="hidden" name="title" />'."\n";
1.68      ng       4159: 
1.485     albertel 4160:     my $options =
                   4161: 	'<label><input type="radio" name="vProb" value="no" checked="checked" /> '.&mt('no').' </label>'."\n".
                   4162: 	'<label><input type="radio" name="vProb" value="yes" /> '.&mt('yes').' </label>'."<br />\n";
1.539     riegler  4163:     $result.='&nbsp;<b>'.&mt('View Problem Text').': </b>'.$options;
1.485     albertel 4164: 
                   4165:     $options =
                   4166: 	'<label><input type="radio" name="lastSub" value="none" /> '.&mt('none').' </label>'."\n".
                   4167: 	'<label><input type="radio" name="lastSub" value="datesub" checked="checked" /> '.&mt('by dates and submissions').'</label>'."\n".
                   4168: 	'<label><input type="radio" name="lastSub" value="all" /> '.&mt('all details').' </label>'."\n";
1.539     riegler  4169:     $result.='&nbsp;<b>'.&mt('Submissions').': </b>'.$options;
1.432     banghart 4170:     
                   4171:     $result.=&build_section_inputs();
1.442     banghart 4172:     my $stu_status = join(':',&Apache::loncommon::get_env_multiple('form.Status'));
                   4173:     $result.='<input type="hidden" name="Status"  value="'.$stu_status.'" />'."\n".
1.72      ng       4174: 	'<input type="hidden" name="command" value="displayPage" />'."\n".
1.418     albertel 4175: 	'<input type="hidden" name="symb"    value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
1.257     albertel 4176: 	'<input type="hidden" name="saveState" value="'.$env{'form.saveState'}.'" />'."<br />\n";
1.72      ng       4177: 
1.539     riegler  4178:     $result.='&nbsp;<b>'.&mt('Use CODE').': </b> <input type="text" name="CODE" value="" /> <br />'."\n";
1.382     albertel 4179: 
1.80      ng       4180:     $result.='&nbsp;<input type="button" '.
1.539     riegler  4181: 	'onClick="javascript:checkPickOne(this.form);" value="'.&mt('Next').' &rarr;" /><br />'."\n";
1.72      ng       4182: 
1.68      ng       4183:     $request->print($result);
                   4184: 
1.485     albertel 4185:     my $studentTable.='&nbsp;<b>'.&mt('Select a student you wish to grade and then click on the Next button.').'</b><br />'.
1.484     albertel 4186: 	&Apache::loncommon::start_data_table().
                   4187: 	&Apache::loncommon::start_data_table_header_row().
1.485     albertel 4188: 	'<th align="right">&nbsp;'.&mt('No.').'</th>'.
1.484     albertel 4189: 	'<th>'.&nameUserString('header').'</th>'.
1.485     albertel 4190: 	'<th align="right">&nbsp;'.&mt('No.').'</th>'.
1.484     albertel 4191: 	'<th>'.&nameUserString('header').'</th>'.
                   4192: 	&Apache::loncommon::end_data_table_header_row();
1.68      ng       4193:  
1.76      ng       4194:     my (undef,undef,$fullname) = &getclasslist($getsec,'1');
1.68      ng       4195:     my $ptr = 1;
1.294     albertel 4196:     foreach my $student (sort 
                   4197: 			 {
                   4198: 			     if (lc($$fullname{$a}) ne lc($$fullname{$b})) {
                   4199: 				 return (lc($$fullname{$a}) cmp lc($$fullname{$b}));
                   4200: 			     }
                   4201: 			     return $a cmp $b;
                   4202: 			 } (keys(%$fullname))) {
1.68      ng       4203: 	my ($uname,$udom) = split(/:/,$student);
1.484     albertel 4204: 	$studentTable.=($ptr%2==1 ? &Apache::loncommon::start_data_table_row()
                   4205:                                   : '</td>');
1.126     ng       4206: 	$studentTable.='<td align="right">'.$ptr.'&nbsp;</td>';
1.288     albertel 4207: 	$studentTable.='<td>&nbsp;<label><input type="radio" name="student" value="'.$student.'" /> '
                   4208: 	    .&nameUserString(undef,$$fullname{$student},$uname,$udom)."</label>\n";
1.484     albertel 4209: 	$studentTable.=
                   4210: 	    ($ptr%2 == 0 ? '</td>'.&Apache::loncommon::end_data_table_row() 
                   4211:                          : '');
1.68      ng       4212: 	$ptr++;
                   4213:     }
1.484     albertel 4214:     if ($ptr%2 == 0) {
                   4215: 	$studentTable.='</td><td>&nbsp;</td><td>&nbsp;</td>'.
                   4216: 	    &Apache::loncommon::end_data_table_row();
                   4217:     }
                   4218:     $studentTable.=&Apache::loncommon::end_data_table()."\n";
1.126     ng       4219:     $studentTable.='<input type="button" '.
1.539     riegler  4220: 	'onClick="javascript:checkPickOne(this.form);" value="'.&mt('Next').' &rarr;" /></form>'."\n";
1.68      ng       4221: 
1.324     albertel 4222:     $studentTable.=&show_grading_menu_form($symb);
1.68      ng       4223:     $request->print($studentTable);
                   4224: 
                   4225:     return '';
                   4226: }
                   4227: 
                   4228: sub getSymbMap {
1.132     bowersj2 4229:     my $navmap = Apache::lonnavmaps::navmap->new();
1.68      ng       4230: 
                   4231:     my %symbx = ();
                   4232:     my @titles = ();
1.117     bowersj2 4233:     my $minder = 0;
                   4234: 
                   4235:     # Gather every sequence that has problems.
1.240     albertel 4236:     my @sequences = $navmap->retrieveResources(undef, sub { shift->is_map(); },
                   4237: 					       1,0,1);
1.117     bowersj2 4238:     for my $sequence ($navmap->getById('0.0'), @sequences) {
1.241     albertel 4239: 	if ($navmap->hasResource($sequence, sub { shift->is_problem(); }, 0) ) {
1.381     albertel 4240: 	    my $title = $minder.'.'.
                   4241: 		&HTML::Entities::encode($sequence->compTitle(),'"\'&');
                   4242: 	    push(@titles, $title); # minder in case two titles are identical
                   4243: 	    $symbx{$title} = &HTML::Entities::encode($sequence->symb(),'"\'&');
1.117     bowersj2 4244: 	    $minder++;
1.241     albertel 4245: 	}
1.68      ng       4246:     }
                   4247:     return \@titles,\%symbx;
                   4248: }
                   4249: 
1.72      ng       4250: #
                   4251: #--- Displays a page/sequence w/wo problems, w/wo submissions
1.68      ng       4252: sub displayPage {
                   4253:     my ($request) = shift;
                   4254: 
1.324     albertel 4255:     my ($symb) = &get_symb($request);
1.257     albertel 4256:     my $cdom      = $env{"course.$env{'request.course.id'}.domain"};
                   4257:     my $cnum      = $env{"course.$env{'request.course.id'}.num"};
                   4258:     my $getsec    = $env{'form.section'} eq '' ? 'all' : $env{'form.section'};
                   4259:     my $pageTitle = $env{'form.page'};
1.103     albertel 4260:     my ($classlist,undef,$fullname) = &getclasslist($getsec,'1');
1.257     albertel 4261:     my ($uname,$udom) = split(/:/,$env{'form.student'});
                   4262:     my $usec=$classlist->{$env{'form.student'}}[5];
1.168     albertel 4263: 
                   4264:     #need to make sure we have the correct data for later EXT calls, 
                   4265:     #thus invalidate the cache
                   4266:     &Apache::lonnet::devalidatecourseresdata(
1.257     albertel 4267:                  $env{'course.'.$env{'request.course.id'}.'.num'},
                   4268:                  $env{'course.'.$env{'request.course.id'}.'.domain'});
1.168     albertel 4269:     &Apache::lonnet::clear_EXT_cache_status();
                   4270: 
1.103     albertel 4271:     if (!&canview($usec)) {
1.485     albertel 4272: 	$request->print('<span class="LC_warning">'.&mt('Unable to view requested student. ([_1])',$env{'form.student'}).'</span>');
1.324     albertel 4273: 	$request->print(&show_grading_menu_form($symb));
1.103     albertel 4274: 	return;
                   4275:     }
1.398     albertel 4276:     my $result='<h3><span class="LC_info">&nbsp;'.$env{'form.title'}.'</span></h3>';
1.485     albertel 4277:     $result.='<h3>&nbsp;'.&mt('Student: [_1]',&nameUserString(undef,$$fullname{$env{'form.student'}},$uname,$udom)).
1.129     ng       4278: 	'</h3>'."\n";
1.500     albertel 4279:     $env{'form.CODE'} = uc($env{'form.CODE'});
1.501     foxr     4280:     if (&Apache::lonnet::validCODE(uc($env{'form.CODE'}))) {
1.485     albertel 4281: 	$result.='<h3>&nbsp;'.&mt('CODE: [_1]',$env{'form.CODE'}).'</h3>'."\n";
1.382     albertel 4282:     } else {
                   4283: 	delete($env{'form.CODE'});
                   4284:     }
1.71      ng       4285:     &sub_page_js($request);
                   4286:     $request->print($result);
                   4287: 
1.132     bowersj2 4288:     my $navmap = Apache::lonnavmaps::navmap->new();
1.257     albertel 4289:     my ($mapUrl, $id, $resUrl)=&Apache::lonnet::decode_symb($env{'form.page'});
1.68      ng       4290:     my $map = $navmap->getResourceByUrl($resUrl); # add to navmaps
1.288     albertel 4291:     if (!$map) {
1.485     albertel 4292: 	$request->print('<span class="LC_warning">'.&mt('Unable to view requested sequence. ([_1])',$resUrl).'</span>');
1.324     albertel 4293: 	$request->print(&show_grading_menu_form($symb));
1.288     albertel 4294: 	return; 
                   4295:     }
1.68      ng       4296:     my $iterator = $navmap->getIterator($map->map_start(),
                   4297: 					$map->map_finish());
                   4298: 
1.71      ng       4299:     my $studentTable='<form action="/adm/grades" method="post" name="gradePage">'."\n".
1.72      ng       4300: 	'<input type="hidden" name="command" value="gradeByPage" />'."\n".
1.257     albertel 4301: 	'<input type="hidden" name="fullname" value="'.$$fullname{$env{'form.student'}}.'" />'."\n".
                   4302: 	'<input type="hidden" name="student" value="'.$env{'form.student'}.'" />'."\n".
1.72      ng       4303: 	'<input type="hidden" name="page"    value="'.$pageTitle.'" />'."\n".
1.257     albertel 4304: 	'<input type="hidden" name="title"   value="'.$env{'form.title'}.'" />'."\n".
1.418     albertel 4305: 	'<input type="hidden" name="symb"    value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
1.125     ng       4306: 	'<input type="hidden" name="overRideScore" value="no" />'."\n".
1.257     albertel 4307: 	'<input type="hidden" name="saveState" value="'.$env{'form.saveState'}.'" />'."\n";
1.71      ng       4308: 
1.382     albertel 4309:     if (defined($env{'form.CODE'})) {
                   4310: 	$studentTable.=
                   4311: 	    '<input type="hidden" name="CODE" value="'.$env{'form.CODE'}.'" />'."\n";
                   4312:     }
1.381     albertel 4313:     my $checkIcon = '<img alt="'.&mt('Check Mark').
1.485     albertel 4314: 	'" src="'.&Apache::loncommon::lonhttpdurl($request->dir_config('lonIconsURL').'/check.gif').'" height="16" border="0" />';
1.71      ng       4315: 
1.485     albertel 4316:     $studentTable.='&nbsp;'.&mt('<b>Note:</b> Problems graded correct by the computer are marked with a [_1] symbol.',$checkIcon)."\n".
1.484     albertel 4317: 	&Apache::loncommon::start_data_table().
                   4318: 	&Apache::loncommon::start_data_table_header_row().
                   4319: 	'<th align="center">&nbsp;Prob.&nbsp;</th>'.
1.485     albertel 4320: 	'<th>&nbsp;'.($env{'form.vProb'} eq 'no' ? &mt('Title') : &mt('Problem Text')).'/'.&mt('Grade').'</th>'.
1.484     albertel 4321: 	&Apache::loncommon::end_data_table_header_row();
1.71      ng       4322: 
1.329     albertel 4323:     &Apache::lonxml::clear_problem_counter();
1.196     albertel 4324:     my ($depth,$question,$prob) = (1,1,1);
1.68      ng       4325:     $iterator->next(); # skip the first BEGIN_MAP
                   4326:     my $curRes = $iterator->next(); # for "current resource"
1.101     albertel 4327:     while ($depth > 0) {
1.68      ng       4328:         if($curRes == $iterator->BEGIN_MAP) { $depth++; }
1.100     bowersj2 4329:         if($curRes == $iterator->END_MAP) { $depth--; }
1.68      ng       4330: 
1.385     albertel 4331:         if (ref($curRes) && $curRes->is_problem()) {
1.91      albertel 4332: 	    my $parts = $curRes->parts();
1.68      ng       4333:             my $title = $curRes->compTitle();
1.71      ng       4334: 	    my $symbx = $curRes->symb();
1.484     albertel 4335: 	    $studentTable.=
                   4336: 		&Apache::loncommon::start_data_table_row().
                   4337: 		'<td align="center" valign="top" >'.$prob.
1.485     albertel 4338: 		(scalar(@{$parts}) == 1 ? '' 
                   4339: 		                        : '<br />('.&mt('[_1]&nbsp;parts)',
                   4340: 							scalar(@{$parts}))
                   4341: 		 ).
                   4342: 		 '</td>';
1.71      ng       4343: 	    $studentTable.='<td valign="top">';
1.382     albertel 4344: 	    my %form = ('CODE' => $env{'form.CODE'},);
1.257     albertel 4345: 	    if ($env{'form.vProb'} eq 'yes' ) {
1.144     albertel 4346: 		$studentTable.=&show_problem($request,$symbx,$uname,$udom,1,
1.383     albertel 4347: 					     undef,'both',\%form);
1.71      ng       4348: 	    } else {
1.382     albertel 4349: 		my $companswer = &Apache::loncommon::get_student_answers($symbx,$uname,$udom,$env{'request.course.id'},%form);
1.80      ng       4350: 		$companswer =~ s|<form(.*?)>||g;
                   4351: 		$companswer =~ s|</form>||g;
1.71      ng       4352: #		while ($companswer =~ /(<a href\=\"javascript:newWindow.*?Script Vars<\/a>)/s) { #<a href="javascript:newWindow</a>
1.116     ng       4353: #		    $companswer =~ s/$1/ /ms;
1.326     albertel 4354: #		    $request->print('match='.$1."<br />\n");
1.71      ng       4355: #		}
1.116     ng       4356: #		$companswer =~ s|<table border=\"1\">|<table border=\"0\">|g;
1.539     riegler  4357: 		$studentTable.='&nbsp;<b>'.$title.'</b>&nbsp;<br />&nbsp;<b>'.&mt('Correct answer').':</b><br />'.$companswer;
1.71      ng       4358: 	    }
                   4359: 
1.257     albertel 4360: 	    my %record = &Apache::lonnet::restore($symbx,$env{'request.course.id'},$udom,$uname);
1.125     ng       4361: 
1.257     albertel 4362: 	    if ($env{'form.lastSub'} eq 'datesub') {
1.71      ng       4363: 		if ($record{'version'} eq '') {
1.485     albertel 4364: 		    $studentTable.='<br />&nbsp;<span class="LC_warning">'.&mt('No recorded submission for this problem.').'</span><br />';
1.71      ng       4365: 		} else {
1.116     ng       4366: 		    my %responseType = ();
                   4367: 		    foreach my $partid (@{$parts}) {
1.147     albertel 4368: 			my @responseIds =$curRes->responseIds($partid);
                   4369: 			my @responseType =$curRes->responseType($partid);
                   4370: 			my %responseIds;
                   4371: 			for (my $i=0;$i<=$#responseIds;$i++) {
                   4372: 			    $responseIds{$responseIds[$i]}=$responseType[$i];
                   4373: 			}
                   4374: 			$responseType{$partid} = \%responseIds;
1.116     ng       4375: 		    }
1.148     albertel 4376: 		    $studentTable.= &displaySubByDates($symbx,\%record,$parts,\%responseType,$checkIcon,$uname,$udom);
1.147     albertel 4377: 
1.71      ng       4378: 		}
1.257     albertel 4379: 	    } elsif ($env{'form.lastSub'} eq 'all') {
                   4380: 		my $last = ($env{'form.lastSub'} eq 'last' ? 'last' : '');
1.71      ng       4381: 		$studentTable.=&Apache::loncommon::get_previous_attempt($symbx,$uname,$udom,
1.257     albertel 4382: 									$env{'request.course.id'},
1.71      ng       4383: 									'','.submission');
                   4384:  
                   4385: 	    }
1.103     albertel 4386: 	    if (&canmodify($usec)) {
                   4387: 		foreach my $partid (@{$parts}) {
                   4388: 		    $studentTable.=&gradeBox($request,$symbx,$uname,$udom,$question,$partid,\%record);
                   4389: 		    $studentTable.='<input type="hidden" name="q_'.$question.'" value="'.$partid.'" />'."\n";
                   4390: 		    $question++;
                   4391: 		}
1.196     albertel 4392: 		$prob++;
1.71      ng       4393: 	    }
                   4394: 	    $studentTable.='</td></tr>';
1.68      ng       4395: 
1.103     albertel 4396: 	}
1.68      ng       4397:         $curRes = $iterator->next();
                   4398:     }
                   4399: 
1.485     albertel 4400:     $studentTable.='</table>'."\n".
                   4401: 	'<input type="button" value="'.&mt('Save').'" '.
1.381     albertel 4402: 	'onClick="javascript:checkSubmitPage(this.form,'.$question.');" />'.
1.71      ng       4403: 	'</form>'."\n";
1.324     albertel 4404:     $studentTable.=&show_grading_menu_form($symb);
1.71      ng       4405:     $request->print($studentTable);
                   4406: 
                   4407:     return '';
1.119     ng       4408: }
                   4409: 
                   4410: sub displaySubByDates {
1.148     albertel 4411:     my ($symb,$record,$parts,$responseType,$checkIcon,$uname,$udom) = @_;
1.224     albertel 4412:     my $isCODE=0;
1.335     albertel 4413:     my $isTask = ($symb =~/\.task$/);
1.224     albertel 4414:     if (exists($record->{'resource.CODE'})) { $isCODE=1; }
1.467     albertel 4415:     my $studentTable=&Apache::loncommon::start_data_table().
                   4416: 	&Apache::loncommon::start_data_table_header_row().
                   4417: 	'<th>'.&mt('Date/Time').'</th>'.
                   4418: 	($isCODE?'<th>'.&mt('CODE').'</th>':'').
                   4419: 	'<th>'.&mt('Submission').'</th>'.
                   4420: 	'<th>'.&mt('Status').'</th>'.
                   4421: 	&Apache::loncommon::end_data_table_header_row();
1.119     ng       4422:     my ($version);
                   4423:     my %mark;
1.148     albertel 4424:     my %orders;
1.119     ng       4425:     $mark{'correct_by_student'} = $checkIcon;
1.147     albertel 4426:     if (!exists($$record{'1:timestamp'})) {
1.539     riegler  4427: 	return '<br />&nbsp;<span class="LC_warning">'.&mt('Nothing submitted - no attempts.').'</span><br />';
1.147     albertel 4428:     }
1.335     albertel 4429: 
                   4430:     my $interaction;
1.525     raeburn  4431:     my $no_increment = 1;
1.119     ng       4432:     for ($version=1;$version<=$$record{'version'};$version++) {
1.467     albertel 4433: 	my $timestamp = 
                   4434: 	    &Apache::lonlocal::locallocaltime($$record{$version.':timestamp'});
1.335     albertel 4435: 	if (exists($$record{$version.':resource.0.version'})) {
                   4436: 	    $interaction = $$record{$version.':resource.0.version'};
                   4437: 	}
                   4438: 
                   4439: 	my $where = ($isTask ? "$version:resource.$interaction"
                   4440: 		             : "$version:resource");
1.467     albertel 4441: 	$studentTable.=&Apache::loncommon::start_data_table_row().
                   4442: 	    '<td>'.$timestamp.'</td>';
1.224     albertel 4443: 	if ($isCODE) {
                   4444: 	    $studentTable.='<td>'.$record->{$version.':resource.CODE'}.'</td>';
                   4445: 	}
1.119     ng       4446: 	my @versionKeys = split(/\:/,$$record{$version.':keys'});
                   4447: 	my @displaySub = ();
                   4448: 	foreach my $partid (@{$parts}) {
1.335     albertel 4449: 	    my @matchKey = ($isTask ? sort(grep /^resource\.\d+\.\Q$partid\E\.award$/,@versionKeys)
                   4450: 			            : sort(grep /^resource\.\Q$partid\E\..*?\.submission$/,@versionKeys));
                   4451: 	    
                   4452: 
1.122     ng       4453: #	    next if ($$record{"$version:resource.$partid.solved"} eq '');
1.324     albertel 4454: 	    my $display_part=&get_display_part($partid,$symb);
1.147     albertel 4455: 	    foreach my $matchKey (@matchKey) {
1.198     albertel 4456: 		if (exists($$record{$version.':'.$matchKey}) &&
                   4457: 		    $$record{$version.':'.$matchKey} ne '') {
1.335     albertel 4458: 
                   4459: 		    my ($responseId)= ($isTask ? ($matchKey=~ /^resource\.(.*?)\.\Q$partid\E\.award$/)
                   4460: 				               : ($matchKey=~ /^resource\.\Q$partid\E\.(.*?)\.submission$/));
1.467     albertel 4461: 		    $displaySub[0].='<b>'.&mt('Part:').'</b>&nbsp;'.$display_part.'&nbsp;';
                   4462: 		    $displaySub[0].='<span class="LC_internal_info">('.&mt('ID').'&nbsp;'.
1.398     albertel 4463: 			$responseId.')</span>&nbsp;<b>';
1.335     albertel 4464: 		    if ($$record{"$where.$partid.tries"} eq '') {
1.467     albertel 4465: 			$displaySub[0].=&mt('Trial&nbsp;not&nbsp;counted');
1.147     albertel 4466: 		    } else {
1.467     albertel 4467: 			$displaySub[0].=&mt('Trial&nbsp;[_1]',
                   4468: 					    $$record{"$where.$partid.tries"});
1.147     albertel 4469: 		    }
1.335     albertel 4470: 		    my $responseType=($isTask ? 'Task'
                   4471:                                               : $responseType->{$partid}->{$responseId});
1.148     albertel 4472: 		    if (!exists($orders{$partid})) { $orders{$partid}={}; }
                   4473: 		    if (!exists($orders{$partid}->{$responseId})) {
                   4474: 			$orders{$partid}->{$responseId}=
1.525     raeburn  4475: 			    &get_order($partid,$responseId,$symb,$uname,$udom,
                   4476:                                        $no_increment);
1.148     albertel 4477: 		    }
1.147     albertel 4478: 		    $displaySub[0].='</b>&nbsp; '.
1.336     albertel 4479: 			&cleanRecord($$record{$version.':'.$matchKey},$responseType,$symb,$partid,$responseId,$record,$orders{$partid}->{$responseId},"$version:",$uname,$udom).'<br />';
1.147     albertel 4480: 		}
                   4481: 	    }
1.335     albertel 4482: 	    if (exists($$record{"$where.$partid.checkedin"})) {
1.485     albertel 4483: 		$displaySub[1].=&mt('Checked in by [_1] into slot [_2]',
                   4484: 				    $$record{"$where.$partid.checkedin"},
                   4485: 				    $$record{"$where.$partid.checkedin.slot"}).
                   4486: 					'<br />';
1.335     albertel 4487: 	    }
                   4488: 	    if (exists $$record{"$where.$partid.award"}) {
1.485     albertel 4489: 		$displaySub[1].='<b>'.&mt('Part:').'</b>&nbsp;'.$display_part.' &nbsp;'.
1.335     albertel 4490: 		    lc($$record{"$where.$partid.award"}).' '.
                   4491: 		    $mark{$$record{"$where.$partid.solved"}}.
1.147     albertel 4492: 		    '<br />';
                   4493: 	    }
1.335     albertel 4494: 	    if (exists $$record{"$where.$partid.regrader"}) {
                   4495: 		$displaySub[2].=$$record{"$where.$partid.regrader"}.
                   4496: 		    ' (<b>'.&mt('Part').':</b> '.$display_part.')';
                   4497: 	    } elsif ($$record{"$version:resource.$partid.regrader"} =~ /\S/) {
                   4498: 		$displaySub[2].=
                   4499: 		    $$record{"$version:resource.$partid.regrader"}.
1.207     albertel 4500: 		    ' (<b>'.&mt('Part').':</b> '.$display_part.')';
1.147     albertel 4501: 	    }
                   4502: 	}
                   4503: 	# needed because old essay regrader has not parts info
                   4504: 	if (exists $$record{"$version:resource.regrader"}) {
                   4505: 	    $displaySub[2].=$$record{"$version:resource.regrader"};
                   4506: 	}
                   4507: 	$studentTable.='<td>'.$displaySub[0].'&nbsp;</td><td>'.$displaySub[1];
                   4508: 	if ($displaySub[2]) {
1.467     albertel 4509: 	    $studentTable.=&mt('Manually graded by [_1]',$displaySub[2]);
1.147     albertel 4510: 	}
1.467     albertel 4511: 	$studentTable.='&nbsp;</td>'.
                   4512: 	    &Apache::loncommon::end_data_table_row();
1.119     ng       4513:     }
1.467     albertel 4514:     $studentTable.=&Apache::loncommon::end_data_table();
1.119     ng       4515:     return $studentTable;
1.71      ng       4516: }
                   4517: 
                   4518: sub updateGradeByPage {
                   4519:     my ($request) = shift;
                   4520: 
1.257     albertel 4521:     my $cdom      = $env{"course.$env{'request.course.id'}.domain"};
                   4522:     my $cnum      = $env{"course.$env{'request.course.id'}.num"};
                   4523:     my $getsec    = $env{'form.section'} eq '' ? 'all' : $env{'form.section'};
                   4524:     my $pageTitle = $env{'form.page'};
1.103     albertel 4525:     my ($classlist,undef,$fullname) = &getclasslist($getsec,'1');
1.257     albertel 4526:     my ($uname,$udom) = split(/:/,$env{'form.student'});
                   4527:     my $usec=$classlist->{$env{'form.student'}}[5];
1.103     albertel 4528:     if (!&canmodify($usec)) {
1.526     raeburn  4529: 	$request->print('<span class="LC_warning">'.&mt('Unable to modify requested student ([_1])',$env{'form.student'}).'</span>');
1.324     albertel 4530: 	$request->print(&show_grading_menu_form($env{'form.symb'}));
1.103     albertel 4531: 	return;
                   4532:     }
1.398     albertel 4533:     my $result='<h3><span class="LC_info">&nbsp;'.$env{'form.title'}.'</span></h3>';
1.526     raeburn  4534:     $result.='<h3>&nbsp;'.&mt('Student: ').&nameUserString(undef,$env{'form.fullname'},$uname,$udom).
1.129     ng       4535: 	'</h3>'."\n";
1.70      ng       4536: 
1.68      ng       4537:     $request->print($result);
                   4538: 
1.132     bowersj2 4539:     my $navmap = Apache::lonnavmaps::navmap->new();
1.257     albertel 4540:     my ($mapUrl, $id, $resUrl) = &Apache::lonnet::decode_symb( $env{'form.page'});
1.71      ng       4541:     my $map = $navmap->getResourceByUrl($resUrl); # add to navmaps
1.288     albertel 4542:     if (!$map) {
1.527     raeburn  4543: 	$request->print('<span class="LC_warning">'.&mt('Unable to grade requested sequence ([_1]).',$resUrl).'</span>');
1.324     albertel 4544: 	my ($symb)=&get_symb($request);
                   4545: 	$request->print(&show_grading_menu_form($symb));
1.288     albertel 4546: 	return; 
                   4547:     }
1.71      ng       4548:     my $iterator = $navmap->getIterator($map->map_start(),
                   4549: 					$map->map_finish());
1.70      ng       4550: 
1.484     albertel 4551:     my $studentTable=
                   4552: 	&Apache::loncommon::start_data_table().
                   4553: 	&Apache::loncommon::start_data_table_header_row().
1.485     albertel 4554: 	'<th align="center">&nbsp;'.&mt('Prob.').'&nbsp;</th>'.
                   4555: 	'<th>&nbsp;'.&mt('Title').'&nbsp;</th>'.
                   4556: 	'<th>&nbsp;'.&mt('Previous Score').'&nbsp;</th>'.
                   4557: 	'<th>&nbsp;'.&mt('New Score').'&nbsp;</th>'.
1.484     albertel 4558: 	&Apache::loncommon::end_data_table_header_row();
1.71      ng       4559: 
                   4560:     $iterator->next(); # skip the first BEGIN_MAP
                   4561:     my $curRes = $iterator->next(); # for "current resource"
1.196     albertel 4562:     my ($depth,$question,$prob,$changeflag)= (1,1,1,0);
1.101     albertel 4563:     while ($depth > 0) {
1.71      ng       4564:         if($curRes == $iterator->BEGIN_MAP) { $depth++; }
1.100     bowersj2 4565:         if($curRes == $iterator->END_MAP) { $depth--; }
1.71      ng       4566: 
1.385     albertel 4567:         if (ref($curRes) && $curRes->is_problem()) {
1.91      albertel 4568: 	    my $parts = $curRes->parts();
1.71      ng       4569:             my $title = $curRes->compTitle();
                   4570: 	    my $symbx = $curRes->symb();
1.484     albertel 4571: 	    $studentTable.=
                   4572: 		&Apache::loncommon::start_data_table_row().
                   4573: 		'<td align="center" valign="top" >'.$prob.
1.485     albertel 4574: 		(scalar(@{$parts}) == 1 ? '' 
1.526     raeburn  4575:                                         : '<br />('.&mt('[quant,_1,&nbsp;part]',scalar(@{$parts}))
                   4576: 		.')').'</td>';
1.71      ng       4577: 	    $studentTable.='<td valign="top">&nbsp;<b>'.$title.'</b>&nbsp;</td>';
                   4578: 
                   4579: 	    my %newrecord=();
                   4580: 	    my @displayPts=();
1.269     raeburn  4581:             my %aggregate = ();
                   4582:             my $aggregateflag = 0;
1.71      ng       4583: 	    foreach my $partid (@{$parts}) {
1.257     albertel 4584: 		my $newpts = $env{'form.GD_BOX'.$question.'_'.$partid};
                   4585: 		my $oldpts = $env{'form.oldpts'.$question.'_'.$partid};
1.71      ng       4586: 
1.257     albertel 4587: 		my $wgt = $env{'form.WGT'.$question.'_'.$partid} != 0 ? 
                   4588: 		    $env{'form.WGT'.$question.'_'.$partid} : 1;
1.71      ng       4589: 		my $partial = $newpts/$wgt;
                   4590: 		my $score;
                   4591: 		if ($partial > 0) {
                   4592: 		    $score = 'correct_by_override';
1.125     ng       4593: 		} elsif ($newpts ne '') { #empty is taken as 0
1.71      ng       4594: 		    $score = 'incorrect_by_override';
                   4595: 		}
1.257     albertel 4596: 		my $dropMenu = $env{'form.GD_SEL'.$question.'_'.$partid};
1.125     ng       4597: 		if ($dropMenu eq 'excused') {
1.71      ng       4598: 		    $partial = '';
                   4599: 		    $score = 'excused';
1.125     ng       4600: 		} elsif ($dropMenu eq 'reset status'
1.257     albertel 4601: 			 && $env{'form.solved'.$question.'_'.$partid} ne '') { #update only if previous record exists
1.125     ng       4602: 		    $newrecord{'resource.'.$partid.'.tries'} = 0;
                   4603: 		    $newrecord{'resource.'.$partid.'.solved'} = '';
                   4604: 		    $newrecord{'resource.'.$partid.'.award'} = '';
                   4605: 		    $newrecord{'resource.'.$partid.'.awarded'} = 0;
1.257     albertel 4606: 		    $newrecord{'resource.'.$partid.'.regrader'} = "$env{'user.name'}:$env{'user.domain'}";
1.125     ng       4607: 		    $changeflag++;
                   4608: 		    $newpts = '';
1.269     raeburn  4609:                     
                   4610:                     my $aggtries =  $env{'form.aggtries'.$question.'_'.$partid};
                   4611:                     my $totaltries = $env{'form.totaltries'.$question.'_'.$partid};
                   4612:                     my $solvedstatus = $env{'form.solved'.$question.'_'.$partid};
                   4613:                     if ($aggtries > 0) {
                   4614:                         &decrement_aggs($symbx,$partid,\%aggregate,$aggtries,$totaltries,$solvedstatus);
                   4615:                         $aggregateflag = 1;
                   4616:                     }
1.71      ng       4617: 		}
1.324     albertel 4618: 		my $display_part=&get_display_part($partid,$curRes->symb());
1.257     albertel 4619: 		my $oldstatus = $env{'form.solved'.$question.'_'.$partid};
1.526     raeburn  4620: 		$displayPts[0].='&nbsp;<b>'.&mt('Part').':</b> '.$display_part.' = '.
1.71      ng       4621: 		    (($oldstatus eq 'excused') ? 'excused' : $oldpts).
1.326     albertel 4622: 		    '&nbsp;<br />';
1.526     raeburn  4623: 		$displayPts[1].='&nbsp;<b>'.&mt('Part').':</b> '.$display_part.' = '.
1.125     ng       4624: 		     (($score eq 'excused') ? 'excused' : $newpts).
1.326     albertel 4625: 		    '&nbsp;<br />';
1.71      ng       4626: 		$question++;
1.380     albertel 4627: 		next if ($dropMenu eq 'reset status' || ($newpts eq $oldpts && $score ne 'excused'));
1.125     ng       4628: 
1.71      ng       4629: 		$newrecord{'resource.'.$partid.'.awarded'}  = $partial if $partial ne '';
1.125     ng       4630: 		$newrecord{'resource.'.$partid.'.solved'}   = $score if $score ne '';
1.257     albertel 4631: 		$newrecord{'resource.'.$partid.'.regrader'} = "$env{'user.name'}:$env{'user.domain'}"
1.125     ng       4632: 		    if (scalar(keys(%newrecord)) > 0);
1.71      ng       4633: 
                   4634: 		$changeflag++;
                   4635: 	    }
                   4636: 	    if (scalar(keys(%newrecord)) > 0) {
1.382     albertel 4637: 		my %record = 
                   4638: 		    &Apache::lonnet::restore($symbx,$env{'request.course.id'},
                   4639: 					     $udom,$uname);
                   4640: 
                   4641: 		if (&Apache::lonnet::validCODE($env{'form.CODE'})) {
                   4642: 		    $newrecord{'resource.CODE'} = $env{'form.CODE'};
                   4643: 		} elsif (&Apache::lonnet::validCODE($record{'resource.CODE'})) {
                   4644: 		    $newrecord{'resource.CODE'} = '';
                   4645: 		}
1.257     albertel 4646: 		&Apache::lonnet::cstore(\%newrecord,$symbx,$env{'request.course.id'},
1.71      ng       4647: 					$udom,$uname);
1.382     albertel 4648: 		%record = &Apache::lonnet::restore($symbx,
                   4649: 						   $env{'request.course.id'},
                   4650: 						   $udom,$uname);
1.380     albertel 4651: 		&check_and_remove_from_queue($parts,\%record,undef,$symbx,
                   4652: 					     $cdom,$cnum,$udom,$uname);
1.71      ng       4653: 	    }
1.380     albertel 4654: 	    
1.269     raeburn  4655:             if ($aggregateflag) {
                   4656:                 &Apache::lonnet::cinc('nohist_resourcetracker',\%aggregate,
                   4657:                       $env{'course.'.$env{'request.course.id'}.'.domain'},
                   4658:                       $env{'course.'.$env{'request.course.id'}.'.num'});
                   4659:             }
1.125     ng       4660: 
1.71      ng       4661: 	    $studentTable.='<td valign="top">'.$displayPts[0].'</td>'.
                   4662: 		'<td valign="top">'.$displayPts[1].'</td>'.
1.484     albertel 4663: 		&Apache::loncommon::end_data_table_row();
1.68      ng       4664: 
1.196     albertel 4665: 	    $prob++;
1.68      ng       4666: 	}
1.71      ng       4667:         $curRes = $iterator->next();
1.68      ng       4668:     }
1.98      albertel 4669: 
1.484     albertel 4670:     $studentTable.=&Apache::loncommon::end_data_table();
1.324     albertel 4671:     $studentTable.=&show_grading_menu_form($env{'form.symb'});
1.526     raeburn  4672:     my $grademsg=($changeflag == 0 ? &mt('No score was changed or updated.') :
                   4673: 		  &mt('The scores were changed for [quant,_1,problem].',
                   4674: 		  $changeflag));
1.76      ng       4675:     $request->print($grademsg.$studentTable);
1.68      ng       4676: 
1.70      ng       4677:     return '';
                   4678: }
                   4679: 
1.72      ng       4680: #-------- end of section for handling grading by page/sequence ---------
                   4681: #
                   4682: #-------------------------------------------------------------------
                   4683: 
1.75      albertel 4684: #--------------------Scantron Grading-----------------------------------
                   4685: #
                   4686: #------ start of section for handling grading by page/sequence ---------
                   4687: 
1.423     albertel 4688: =pod
                   4689: 
                   4690: =head1 Bubble sheet grading routines
                   4691: 
1.424     albertel 4692:   For this documentation:
                   4693: 
                   4694:    'scanline' refers to the full line of characters
                   4695:    from the file that we are parsing that represents one entire sheet
                   4696: 
                   4697:    'bubble line' refers to the data
                   4698:    representing the line of bubbles that are on the physical bubble sheet
                   4699: 
                   4700: 
                   4701: The overall process is that a scanned in bubble sheet data is uploaded
                   4702: into a course. When a user wants to grade, they select a
                   4703: sequence/folder of resources, a file of bubble sheet info, and pick
                   4704: one of the predefined configurations for what each scanline looks
                   4705: like.
                   4706: 
                   4707: Next each scanline is checked for any errors of either 'missing
1.435     foxr     4708: bubbles' (it's an error because it may have been mis-scanned
1.424     albertel 4709: because too light bubbling), 'double bubble' (each bubble line should
                   4710: have no more that one letter picked), invalid or duplicated CODE,
1.556     weissno  4711: invalid student/employee ID
1.424     albertel 4712: 
                   4713: If the CODE option is used that determines the randomization of the
1.556     weissno  4714: homework problems, either way the student/employee ID is looked up into a
1.424     albertel 4715: username:domain.
                   4716: 
                   4717: During the validation phase the instructor can choose to skip scanlines. 
                   4718: 
1.435     foxr     4719: After the validation phase, there are now 3 bubble sheet files
1.424     albertel 4720: 
                   4721:   scantron_original_filename (unmodified original file)
                   4722:   scantron_corrected_filename (file where the corrected information has replaced the original information)
                   4723:   scantron_skipped_filename (contains the exact text of scanlines that where skipped)
                   4724: 
                   4725: Also there is a separate hash nohist_scantrondata that contains extra
                   4726: correction information that isn't representable in the bubble sheet
                   4727: file (see &scantron_getfile() for more information)
                   4728: 
                   4729: After all scanlines are either valid, marked as valid or skipped, then
                   4730: foreach line foreach problem in the picked sequence, an ssi request is
                   4731: made that simulates a user submitting their selected letter(s) against
                   4732: the homework problem.
1.423     albertel 4733: 
                   4734: =over 4
                   4735: 
                   4736: 
                   4737: 
                   4738: =item defaultFormData
                   4739: 
                   4740:   Returns html hidden inputs used to hold context/default values.
                   4741: 
                   4742:  Arguments:
                   4743:   $symb - $symb of the current resource 
                   4744: 
                   4745: =cut
1.422     foxr     4746: 
1.81      albertel 4747: sub defaultFormData {
1.324     albertel 4748:     my ($symb)=@_;
1.447     foxr     4749:     return '<input type="hidden" name="symb"    value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
1.257     albertel 4750:      '<input type="hidden" name="saveState" value="'.$env{'form.saveState'}.'" />'."\n".
                   4751:      '<input type="hidden" name="probTitle" value="'.$env{'form.probTitle'}.'" />'."\n";
1.81      albertel 4752: }
                   4753: 
1.447     foxr     4754: 
1.423     albertel 4755: =pod 
                   4756: 
                   4757: =item getSequenceDropDown
                   4758: 
                   4759:    Return html dropdown of possible sequences to grade
                   4760:  
                   4761:  Arguments:
                   4762:    $symb - $symb of the current resource 
                   4763: 
                   4764: =cut
1.422     foxr     4765: 
1.75      albertel 4766: sub getSequenceDropDown {
1.423     albertel 4767:     my ($symb)=@_;
1.75      albertel 4768:     my $result='<select name="selectpage">'."\n";
1.423     albertel 4769:     my ($titles,$symbx) = &getSymbMap();
1.137     albertel 4770:     my ($curpage)=&Apache::lonnet::decode_symb($symb); 
1.75      albertel 4771:     my $ctr=0;
                   4772:     foreach (@$titles) {
                   4773: 	my ($minder,$showtitle) = ($_ =~ /(\d+)\.(.*)/);
                   4774: 	$result.='<option value="'.$$symbx{$_}.'" '.
1.401     albertel 4775: 	    ($$symbx{$_} =~ /$curpage$/ ? 'selected="selected"' : '').
1.75      albertel 4776: 	    '>'.$showtitle.'</option>'."\n";
                   4777: 	$ctr++;
                   4778:     }
                   4779:     $result.= '</select>';
                   4780:     return $result;
                   4781: }
                   4782: 
1.495     albertel 4783: my %bubble_lines_per_response;     # no. bubble lines for each response.
1.554     raeburn  4784:                                    # key is zero-based index - 0, 1, 2 ...
1.495     albertel 4785: 
                   4786: my %first_bubble_line;             # First bubble line no. for each bubble.
                   4787: 
1.509     raeburn  4788: my %subdivided_bubble_lines;       # no. bubble lines for optionresponse, 
                   4789:                                    # matchresponse or rankresponse, where 
                   4790:                                    # an individual response can have multiple 
                   4791:                                    # lines
1.503     raeburn  4792: 
                   4793: my %responsetype_per_response;     # responsetype for each response
                   4794: 
1.495     albertel 4795: # Save and restore the bubble lines array to the form env.
                   4796: 
                   4797: 
                   4798: sub save_bubble_lines {
                   4799:     foreach my $line (keys(%bubble_lines_per_response)) {
                   4800: 	$env{"form.scantron.bubblelines.$line"}  = $bubble_lines_per_response{$line};
                   4801: 	$env{"form.scantron.first_bubble_line.$line"} =
                   4802: 	    $first_bubble_line{$line};
1.503     raeburn  4803:         $env{"form.scantron.sub_bubblelines.$line"} = 
                   4804:             $subdivided_bubble_lines{$line};
                   4805:         $env{"form.scantron.responsetype.$line"} =
                   4806:             $responsetype_per_response{$line};
1.495     albertel 4807:     }
                   4808: }
                   4809: 
                   4810: 
                   4811: sub restore_bubble_lines {
                   4812:     my $line = 0;
                   4813:     %bubble_lines_per_response = ();
                   4814:     while ($env{"form.scantron.bubblelines.$line"}) {
                   4815: 	my $value = $env{"form.scantron.bubblelines.$line"};
                   4816: 	$bubble_lines_per_response{$line} = $value;
                   4817: 	$first_bubble_line{$line}  =
                   4818: 	    $env{"form.scantron.first_bubble_line.$line"};
1.503     raeburn  4819:         $subdivided_bubble_lines{$line} =
                   4820:             $env{"form.scantron.sub_bubblelines.$line"};
                   4821:         $responsetype_per_response{$line} =
                   4822:             $env{"form.scantron.responsetype.$line"};
1.495     albertel 4823: 	$line++;
                   4824:     }
                   4825: }
                   4826: 
                   4827: #  Given the parsed scanline, get the response for 
                   4828: #  'answer' number n:
                   4829: 
                   4830: sub get_response_bubbles {
                   4831:     my ($parsed_line, $response)  = @_;
                   4832: 
                   4833:     my $bubble_line = $first_bubble_line{$response-1} +1;
                   4834:     my $bubble_lines= $bubble_lines_per_response{$response-1};
                   4835:     
                   4836:     my $selected = "";
                   4837: 
                   4838:     for (my $bline = 0; $bline < $bubble_lines; $bline++) {
                   4839: 	$selected .= $$parsed_line{"scantron.$bubble_line.answer"}.":";
                   4840: 	$bubble_line++;
                   4841:     }
                   4842:     return $selected;
                   4843: }
1.423     albertel 4844: 
                   4845: =pod 
                   4846: 
                   4847: =item scantron_filenames
                   4848: 
                   4849:    Returns a list of the scantron files in the current course 
                   4850: 
                   4851: =cut
1.422     foxr     4852: 
1.202     albertel 4853: sub scantron_filenames {
1.257     albertel 4854:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
                   4855:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
1.517     raeburn  4856:     my $getpropath = 1;
1.157     albertel 4857:     my @files=&Apache::lonnet::dirlist('userfiles',$cdom,$cname,
1.517     raeburn  4858:                                        $getpropath);
1.202     albertel 4859:     my @possiblenames;
1.201     albertel 4860:     foreach my $filename (sort(@files)) {
1.157     albertel 4861: 	($filename)=split(/&/,$filename);
                   4862: 	if ($filename!~/^scantron_orig_/) { next ; }
                   4863: 	$filename=~s/^scantron_orig_//;
1.202     albertel 4864: 	push(@possiblenames,$filename);
                   4865:     }
                   4866:     return @possiblenames;
                   4867: }
                   4868: 
1.423     albertel 4869: =pod 
                   4870: 
                   4871: =item scantron_uploads
                   4872: 
                   4873:    Returns  html drop-down list of scantron files in current course.
                   4874: 
                   4875:  Arguments:
                   4876:    $file2grade - filename to set as selected in the dropdown
                   4877: 
                   4878: =cut
1.422     foxr     4879: 
1.202     albertel 4880: sub scantron_uploads {
1.209     ng       4881:     my ($file2grade) = @_;
1.202     albertel 4882:     my $result=	'<select name="scantron_selectfile">';
                   4883:     $result.="<option></option>";
                   4884:     foreach my $filename (sort(&scantron_filenames())) {
1.401     albertel 4885: 	$result.="<option".($filename eq $file2grade ? ' selected="selected"':'').">$filename</option>\n";
1.81      albertel 4886:     }
                   4887:     $result.="</select>";
                   4888:     return $result;
                   4889: }
                   4890: 
1.423     albertel 4891: =pod 
                   4892: 
                   4893: =item scantron_scantab
                   4894: 
                   4895:   Returns html drop down of the scantron formats in the scantronformat.tab
                   4896:   file.
                   4897: 
                   4898: =cut
1.422     foxr     4899: 
1.82      albertel 4900: sub scantron_scantab {
                   4901:     my $result='<select name="scantron_format">'."\n";
1.191     albertel 4902:     $result.='<option></option>'."\n";
1.518     raeburn  4903:     my @lines = &get_scantronformat_file();
                   4904:     if (@lines > 0) {
                   4905:         foreach my $line (@lines) {
                   4906:             next if (($line =~ /^\#/) || ($line eq ''));
                   4907: 	    my ($name,$descrip)=split(/:/,$line);
                   4908: 	    $result.='<option value="'.$name.'">'.$descrip.'</option>'."\n";
                   4909:         }
1.82      albertel 4910:     }
                   4911:     $result.='</select>'."\n";
1.518     raeburn  4912:     return $result;
                   4913: }
                   4914: 
                   4915: =pod
                   4916: 
                   4917: =item get_scantronformat_file
                   4918: 
                   4919:   Returns an array containing lines from the scantron format file for
                   4920:   the domain of the course.
                   4921: 
                   4922:   If a url for a custom.tab file is listed in domain's configuration.db, 
                   4923:   lines are from this file.
                   4924: 
                   4925:   Otherwise, if a default.tab has been published in RES space by the 
                   4926:   domainconfig user, lines are from this file.
                   4927: 
                   4928:   Otherwise, fall back to getting lines from the legacy file on the
1.519     raeburn  4929:   local server:  /home/httpd/lonTabs/default_scantronformat.tab    
1.82      albertel 4930: 
1.518     raeburn  4931: =cut
                   4932: 
                   4933: sub get_scantronformat_file {
                   4934:     my $cdom= $env{'course.'.$env{'request.course.id'}.'.domain'};
                   4935:     my %domconfig = &Apache::lonnet::get_dom('configuration',['scantron'],$cdom);
                   4936:     my $gottab = 0;
                   4937:     my @lines;
                   4938:     if (ref($domconfig{'scantron'}) eq 'HASH') {
                   4939:         if ($domconfig{'scantron'}{'scantronformat'} ne '') {
                   4940:             my $formatfile = &Apache::lonnet::getfile($Apache::lonnet::perlvar{'lonDocRoot'}.$domconfig{'scantron'}{'scantronformat'});
                   4941:             if ($formatfile ne '-1') {
                   4942:                 @lines = split("\n",$formatfile,-1);
                   4943:                 $gottab = 1;
                   4944:             }
                   4945:         }
                   4946:     }
                   4947:     if (!$gottab) {
                   4948:         my $confname = $cdom.'-domainconfig';
                   4949:         my $default = $Apache::lonnet::perlvar{'lonDocRoot'}.'/res/'.$cdom.'/'.$confname.'/default.tab';
                   4950:         my $formatfile =  &Apache::lonnet::getfile($default);
                   4951:         if ($formatfile ne '-1') {
                   4952:             @lines = split("\n",$formatfile,-1);
                   4953:             $gottab = 1;
                   4954:         }
                   4955:     }
                   4956:     if (!$gottab) {
1.519     raeburn  4957:         my @domains = &Apache::lonnet::current_machine_domains();
                   4958:         if (grep(/^\Q$cdom\E$/,@domains)) {
                   4959:             my $fh=Apache::File->new($Apache::lonnet::perlvar{'lonTabDir'}.'/scantronformat.tab');
                   4960:             @lines = <$fh>;
                   4961:             close($fh);
                   4962:         } else {
                   4963:             my $fh=Apache::File->new($Apache::lonnet::perlvar{'lonTabDir'}.'/default_scantronformat.tab');
                   4964:             @lines = <$fh>;
                   4965:             close($fh);
                   4966:         }
1.518     raeburn  4967:     }
                   4968:     return @lines;
1.82      albertel 4969: }
                   4970: 
1.423     albertel 4971: =pod 
                   4972: 
                   4973: =item scantron_CODElist
                   4974: 
                   4975:   Returns html drop down of the saved CODE lists from current course,
                   4976:   generated from earlier printings.
                   4977: 
                   4978: =cut
1.422     foxr     4979: 
1.186     albertel 4980: sub scantron_CODElist {
1.257     albertel 4981:     my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   4982:     my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
1.186     albertel 4983:     my @names=&Apache::lonnet::getkeys('CODEs',$cdom,$cnum);
                   4984:     my $namechoice='<option></option>';
1.225     albertel 4985:     foreach my $name (sort {uc($a) cmp uc($b)} @names) {
1.191     albertel 4986: 	if ($name =~ /^error: 2 /) { next; }
1.278     albertel 4987: 	if ($name =~ /^type\0/) { next; }
1.186     albertel 4988: 	$namechoice.='<option value="'.$name.'">'.$name.'</option>';
                   4989:     }
                   4990:     $namechoice='<select name="scantron_CODElist">'.$namechoice.'</select>';
                   4991:     return $namechoice;
                   4992: }
                   4993: 
1.423     albertel 4994: =pod 
                   4995: 
                   4996: =item scantron_CODEunique
                   4997: 
                   4998:   Returns the html for "Each CODE to be used once" radio.
                   4999: 
                   5000: =cut
1.422     foxr     5001: 
1.186     albertel 5002: sub scantron_CODEunique {
1.532     bisitz   5003:     my $result='<span class="LC_nobreak">
1.272     albertel 5004:                  <label><input type="radio" name="scantron_CODEunique"
1.423     albertel 5005:                         value="yes" checked="checked" />'.&mt('Yes').' </label>
1.381     albertel 5006:                 </span>
1.532     bisitz   5007:                 <span class="LC_nobreak">
1.272     albertel 5008:                  <label><input type="radio" name="scantron_CODEunique"
1.423     albertel 5009:                         value="no" />'.&mt('No').' </label>
1.381     albertel 5010:                 </span>';
1.186     albertel 5011:     return $result;
                   5012: }
1.423     albertel 5013: 
                   5014: =pod 
                   5015: 
                   5016: =item scantron_selectphase
                   5017: 
                   5018:   Generates the initial screen to start the bubble sheet process.
                   5019:   Allows for - starting a grading run.
1.424     albertel 5020:              - downloading existing scan data (original, corrected
1.423     albertel 5021:                                                 or skipped info)
                   5022: 
                   5023:              - uploading new scan data
                   5024: 
                   5025:  Arguments:
                   5026:   $r          - The Apache request object
                   5027:   $file2grade - name of the file that contain the scanned data to score
                   5028: 
                   5029: =cut
1.186     albertel 5030: 
1.75      albertel 5031: sub scantron_selectphase {
1.209     ng       5032:     my ($r,$file2grade) = @_;
1.324     albertel 5033:     my ($symb)=&get_symb($r);
1.75      albertel 5034:     if (!$symb) {return '';}
1.423     albertel 5035:     my $sequence_selector=&getSequenceDropDown($symb);
1.324     albertel 5036:     my $default_form_data=&defaultFormData($symb);
                   5037:     my $grading_menu_button=&show_grading_menu_form($symb);
1.209     ng       5038:     my $file_selector=&scantron_uploads($file2grade);
1.82      albertel 5039:     my $format_selector=&scantron_scantab();
1.186     albertel 5040:     my $CODE_selector=&scantron_CODElist();
                   5041:     my $CODE_unique=&scantron_CODEunique();
1.75      albertel 5042:     my $result;
1.422     foxr     5043: 
1.513     foxr     5044:     $ssi_error = 0;
                   5045: 
1.422     foxr     5046:     # Chunk of form to prompt for a file to grade and how:
                   5047: 
1.489     albertel 5048:     $result.= '
                   5049:     <br />
                   5050:     <form method="post" enctype="multipart/form-data" action="/adm/grades" name="scantron_process">
                   5051:     <input type="hidden" name="command" value="scantron_warning" />
                   5052:     '.$default_form_data.'
                   5053:     '.&Apache::loncommon::start_data_table('LC_scantron_action').'
                   5054:        '.&Apache::loncommon::start_data_table_header_row().'
                   5055:             <th colspan="2">
1.492     albertel 5056:               &nbsp;'.&mt('Specify file and which Folder/Sequence to grade').'
1.489     albertel 5057:             </th>
                   5058:        '.&Apache::loncommon::end_data_table_header_row().'
                   5059:        '.&Apache::loncommon::start_data_table_row().'
1.492     albertel 5060:             <td> '.&mt('Sequence to grade:').' </td><td> '.$sequence_selector.' </td>
1.489     albertel 5061:        '.&Apache::loncommon::end_data_table_row().'
                   5062:        '.&Apache::loncommon::start_data_table_row().'
1.492     albertel 5063:             <td> '.&mt('Filename of scoring office file:').' </td><td> '.$file_selector.' </td>
1.489     albertel 5064:        '.&Apache::loncommon::end_data_table_row().'
                   5065:        '.&Apache::loncommon::start_data_table_row().'
1.492     albertel 5066:             <td> '.&mt('Format of data file:').' </td><td> '.$format_selector.' </td>
1.489     albertel 5067:        '.&Apache::loncommon::end_data_table_row().'
                   5068:        '.&Apache::loncommon::start_data_table_row().'
1.492     albertel 5069:             <td> '.&mt('Saved CODEs to validate against:').' </td><td> '.$CODE_selector.' </td>
1.489     albertel 5070:        '.&Apache::loncommon::end_data_table_row().'
                   5071:        '.&Apache::loncommon::start_data_table_row().'
1.492     albertel 5072:             <td> '.&mt('Each CODE is only to be used once:').'</td><td> '.$CODE_unique.' </td>
1.489     albertel 5073:        '.&Apache::loncommon::end_data_table_row().'
                   5074:        '.&Apache::loncommon::start_data_table_row().'
1.492     albertel 5075: 	    <td> '.&mt('Options:').' </td>
1.187     albertel 5076:             <td>
1.492     albertel 5077: 	       <label><input type="checkbox" name="scantron_options_redo" value="redo_skipped"/> '.&mt('Do only previously skipped records').'</label> <br />
                   5078:                <label><input type="checkbox" name="scantron_options_ignore" value="ignore_corrections"/> '.&mt('Remove all existing corrections').'</label> <br />
                   5079:                <label><input type="checkbox" name="scantron_options_hidden" value="ignore_hidden"/> '.&mt('Skip hidden resources when grading').'</label>
1.187     albertel 5080: 	    </td>
1.489     albertel 5081:        '.&Apache::loncommon::end_data_table_row().'
                   5082:        '.&Apache::loncommon::start_data_table_row().'
1.174     albertel 5083:             <td colspan="2">
1.492     albertel 5084:               <input type="submit" value="'.&mt('Grading: Validate Scantron Records').'" />
1.162     albertel 5085:             </td>
1.489     albertel 5086:        '.&Apache::loncommon::end_data_table_row().'
                   5087:     '.&Apache::loncommon::end_data_table().'
                   5088:     </form>
                   5089: ';
1.162     albertel 5090:    
                   5091:     $r->print($result);
                   5092: 
1.257     albertel 5093:     if (&Apache::lonnet::allowed('usc',$env{'request.role.domain'}) ||
                   5094:         &Apache::lonnet::allowed('usc',$env{'request.course.id'})) {
1.162     albertel 5095: 
1.422     foxr     5096: 	# Chunk of form to prompt for a scantron file upload.
                   5097: 
1.489     albertel 5098:         $r->print('
                   5099:     <br />
                   5100:     '.&Apache::loncommon::start_data_table('LC_scantron_action').'
                   5101:        '.&Apache::loncommon::start_data_table_header_row().'
                   5102:             <th>
1.492     albertel 5103:               &nbsp;'.&mt('Specify a Scantron data file to upload.').'
1.489     albertel 5104:             </th>
                   5105:        '.&Apache::loncommon::end_data_table_header_row().'
                   5106:        '.&Apache::loncommon::start_data_table_row().'
1.162     albertel 5107:             <td>
1.489     albertel 5108: ');
1.324     albertel 5109:     my $default_form_data=&defaultFormData(&get_symb($r,1));
1.257     albertel 5110:     my $cdom= $env{'course.'.$env{'request.course.id'}.'.domain'};
                   5111:     my $cnum= $env{'course.'.$env{'request.course.id'}.'.num'};
1.492     albertel 5112:     $r->print('
1.174     albertel 5113:               <script type="text/javascript" language="javascript">
                   5114:     function checkUpload(formname) {
                   5115: 	if (formname.upfile.value == "") {
1.492     albertel 5116: 	    alert("'.&mt('Please use the browse button to select a file from your local directory.').'");
1.174     albertel 5117: 	    return false;
                   5118: 	}
                   5119: 	formname.submit();
                   5120:     }
                   5121:               </script>
                   5122: 
1.492     albertel 5123:               <form enctype="multipart/form-data" action="/adm/grades" name="rules" method="post">
                   5124:                 '.$default_form_data.'
                   5125:                 <input name="courseid" type="hidden" value="'.$cnum.'" />
                   5126:                 <input name="domainid" type="hidden" value="'.$cdom.'" />
                   5127:                 <input name="command" value="scantronupload_save" type="hidden" />
                   5128:                 '.&mt('File to upload: [_1]','<input type="file" name="upfile" size="50" />').'
1.174     albertel 5129:                 <br />
1.492     albertel 5130:                 <input type="button" onClick="javascript:checkUpload(this.form);" value="'.&mt('Upload Scantron Data').'" />
1.174     albertel 5131:               </form>
1.492     albertel 5132: ');
1.162     albertel 5133: 
1.489     albertel 5134:         $r->print('
1.162     albertel 5135:             </td>
1.489     albertel 5136:        '.&Apache::loncommon::end_data_table_row().'
                   5137:        '.&Apache::loncommon::end_data_table().'
                   5138: ');
1.162     albertel 5139:     }
1.422     foxr     5140: 
                   5141:     # Chunk of the form that prompts to view a scoring office file,
                   5142:     # corrected file, skipped records in a file.
                   5143: 
1.489     albertel 5144:     $r->print('
                   5145:    <br />
                   5146:    <form action="/adm/grades" name="scantron_download">
                   5147:      '.$default_form_data.'
                   5148:      <input type="hidden" name="command" value="scantron_download" />
                   5149:      '.&Apache::loncommon::start_data_table('LC_scantron_action').'
                   5150:        '.&Apache::loncommon::start_data_table_header_row().'
                   5151:               <th>
1.492     albertel 5152:                 &nbsp;'.&mt('Download a scoring office file').'
1.489     albertel 5153:               </th>
                   5154:        '.&Apache::loncommon::end_data_table_header_row().'
                   5155:        '.&Apache::loncommon::start_data_table_row().'
1.492     albertel 5156:               <td> '.&mt('Filename of scoring office file: [_1]',$file_selector).' 
1.489     albertel 5157:                 <br />
1.492     albertel 5158:                 <input type="submit" value="'.&mt('Download: Show List of Associated Files').'" />
1.489     albertel 5159:        '.&Apache::loncommon::end_data_table_row().'
                   5160:      '.&Apache::loncommon::end_data_table().'
                   5161:    </form>
                   5162:    <br />
                   5163: ');
1.162     albertel 5164: 
1.457     banghart 5165:     &Apache::lonpickcode::code_list($r,2);
1.523     raeburn  5166: 
1.528     raeburn  5167:     $r->print('<br /><form method="post" name="checkscantron">'.
1.523     raeburn  5168:              $default_form_data."\n".
                   5169:              &Apache::loncommon::start_data_table('LC_scantron_action')."\n".
                   5170:              &Apache::loncommon::start_data_table_header_row()."\n".
                   5171:              '<th colspan="2">
                   5172:               &nbsp;'.&mt('Review scantron data and submissions for a previously graded folder/sequence')."\n".
                   5173:              '</th>'."\n".
                   5174:               &Apache::loncommon::end_data_table_header_row()."\n".
                   5175:               &Apache::loncommon::start_data_table_row()."\n".
                   5176:               '<td> '.&mt('Graded folder/sequence:').' </td>'."\n".
                   5177:               '<td> '.$sequence_selector.' </td>'.
                   5178:               &Apache::loncommon::end_data_table_row()."\n".
                   5179:               &Apache::loncommon::start_data_table_row()."\n".
                   5180:               '<td> '.&mt('Filename of scoring office file:').' </td>'."\n".
                   5181:               '<td> '.$file_selector.' </td>'."\n".
                   5182:               &Apache::loncommon::end_data_table_row()."\n".
                   5183:               &Apache::loncommon::start_data_table_row()."\n".
                   5184:               '<td> '.&mt('Format of data file:').' </td>'."\n".
                   5185:               '<td> '.$format_selector.' </td>'."\n".
                   5186:               &Apache::loncommon::end_data_table_row()."\n".
                   5187:               &Apache::loncommon::start_data_table_row()."\n".
1.557     raeburn  5188:               '<td> '.&mt('Options').' </td>'."\n".
                   5189:               '<td> <label><input type="checkbox" name="scantron_options_hidden" value="ignore_hidden"/> '.&mt('Skip hidden resources').'</label></td>'.
                   5190:               &Apache::loncommon::end_data_table_row()."\n".
                   5191:               &Apache::loncommon::start_data_table_row()."\n".
1.523     raeburn  5192:               '<td colspan="2">'."\n".
                   5193:               '<input type="hidden" name="command" value="checksubmissions" />'."\n".
                   5194:               '<input type="submit" value="'.&mt('Review Scantron Data and Submission Records').'" />'."\n".
                   5195:               '</td>'."\n".
                   5196:               &Apache::loncommon::end_data_table_row()."\n".
                   5197:               &Apache::loncommon::end_data_table()."\n".
                   5198:               '</form><br />');
1.457     banghart 5199:     $r->print($grading_menu_button);
1.523     raeburn  5200:     return;
1.75      albertel 5201: }
                   5202: 
1.423     albertel 5203: =pod
                   5204: 
                   5205: =item get_scantron_config
                   5206: 
                   5207:    Parse and return the scantron configuration line selected as a
                   5208:    hash of configuration file fields.
                   5209: 
                   5210:  Arguments:
                   5211:     which - the name of the configuration to parse from the file.
                   5212: 
                   5213: 
                   5214:  Returns:
                   5215:             If the named configuration is not in the file, an empty
                   5216:             hash is returned.
                   5217:     a hash with the fields
                   5218:       name         - internal name for the this configuration setup
                   5219:       description  - text to display to operator that describes this config
                   5220:       CODElocation - if 0 or the string 'none'
                   5221:                           - no CODE exists for this config
                   5222:                      if -1 || the string 'letter'
                   5223:                           - a CODE exists for this config and is
                   5224:                             a string of letters
                   5225:                      Unsupported value (but planned for future support)
                   5226:                           if a positive integer
                   5227:                                - The CODE exists as the first n items from
                   5228:                                  the question section of the form
                   5229:                           if the string 'number'
                   5230:                                - The CODE exists for this config and is
                   5231:                                  a string of numbers
                   5232:       CODEstart   - (only matter if a CODE exists) column in the line where
                   5233:                      the CODE starts
                   5234:       CODElength  - length of the CODE
1.556     weissno  5235:       IDstart     - column where the student/employee ID number starts
                   5236:       IDlength    - length of the student/employee ID info
1.423     albertel 5237:       Qstart      - column where the information from the bubbled
                   5238:                     'questions' start
                   5239:       Qlength     - number of columns comprising a single bubble line from
                   5240:                     the sheet. (usually either 1 or 10)
1.424     albertel 5241:       Qon         - either a single character representing the character used
1.423     albertel 5242:                     to signal a bubble was chosen in the positional setup, or
                   5243:                     the string 'letter' if the letter of the chosen bubble is
                   5244:                     in the final, or 'number' if a number representing the
                   5245:                     chosen bubble is in the file (1->A 0->J)
1.424     albertel 5246:       Qoff        - the character used to represent that a bubble was
                   5247:                     left blank
1.423     albertel 5248:       PaperID     - if the scanning process generates a unique number for each
                   5249:                     sheet scanned the column that this ID number starts in
                   5250:       PaperIDlength - number of columns that comprise the unique ID number
                   5251:                       for the sheet of paper
1.424     albertel 5252:       FirstName   - column that the first name starts in
1.423     albertel 5253:       FirstNameLength - number of columns that the first name spans
                   5254:  
                   5255:       LastName    - column that the last name starts in
                   5256:       LastNameLength - number of columns that the last name spans
                   5257: 
                   5258: =cut
1.422     foxr     5259: 
1.82      albertel 5260: sub get_scantron_config {
                   5261:     my ($which) = @_;
1.518     raeburn  5262:     my @lines = &get_scantronformat_file();
1.82      albertel 5263:     my %config;
1.157     albertel 5264:     #FIXME probably should move to XML it has already gotten a bit much now
1.518     raeburn  5265:     foreach my $line (@lines) {
1.82      albertel 5266: 	my ($name,$descrip)=split(/:/,$line);
                   5267: 	if ($name ne $which ) { next; }
                   5268: 	chomp($line);
                   5269: 	my @config=split(/:/,$line);
                   5270: 	$config{'name'}=$config[0];
                   5271: 	$config{'description'}=$config[1];
                   5272: 	$config{'CODElocation'}=$config[2];
                   5273: 	$config{'CODEstart'}=$config[3];
                   5274: 	$config{'CODElength'}=$config[4];
                   5275: 	$config{'IDstart'}=$config[5];
                   5276: 	$config{'IDlength'}=$config[6];
                   5277: 	$config{'Qstart'}=$config[7];
1.497     foxr     5278:  	$config{'Qlength'}=$config[8];
1.82      albertel 5279: 	$config{'Qoff'}=$config[9];
                   5280: 	$config{'Qon'}=$config[10];
1.157     albertel 5281: 	$config{'PaperID'}=$config[11];
                   5282: 	$config{'PaperIDlength'}=$config[12];
                   5283: 	$config{'FirstName'}=$config[13];
                   5284: 	$config{'FirstNamelength'}=$config[14];
                   5285: 	$config{'LastName'}=$config[15];
                   5286: 	$config{'LastNamelength'}=$config[16];
1.82      albertel 5287: 	last;
                   5288:     }
                   5289:     return %config;
                   5290: }
                   5291: 
1.423     albertel 5292: =pod 
                   5293: 
                   5294: =item username_to_idmap
                   5295: 
1.556     weissno  5296:     creates a hash keyed by student/employee ID with values of the corresponding
1.423     albertel 5297:     student username:domain.
                   5298: 
                   5299:   Arguments:
                   5300: 
                   5301:     $classlist - reference to the class list hash. This is a hash
                   5302:                  keyed by student name:domain  whose elements are references
1.424     albertel 5303:                  to arrays containing various chunks of information
1.423     albertel 5304:                  about the student. (See loncoursedata for more info).
                   5305: 
                   5306:   Returns
                   5307:     %idmap - the constructed hash
                   5308: 
                   5309: =cut
                   5310: 
1.82      albertel 5311: sub username_to_idmap {
                   5312:     my ($classlist)= @_;
                   5313:     my %idmap;
                   5314:     foreach my $student (keys(%$classlist)) {
                   5315: 	$idmap{$classlist->{$student}->[&Apache::loncoursedata::CL_ID]}=
                   5316: 	    $student;
                   5317:     }
                   5318:     return %idmap;
                   5319: }
1.423     albertel 5320: 
                   5321: =pod
                   5322: 
1.424     albertel 5323: =item scantron_fixup_scanline
1.423     albertel 5324: 
                   5325:    Process a requested correction to a scanline.
                   5326: 
                   5327:   Arguments:
                   5328:     $scantron_config   - hash from &get_scantron_config()
                   5329:     $scan_data         - hash of correction information 
                   5330:                           (see &scantron_getfile())
                   5331:     $line              - existing scanline
                   5332:     $whichline         - line number of the passed in scanline
                   5333:     $field             - type of change to process 
                   5334:                          (either 
1.556     weissno  5335:                           'ID'     -> correct the student/employee ID number
1.423     albertel 5336:                           'CODE'   -> correct the CODE
                   5337:                           'answer' -> fixup the submitted answers)
                   5338:     
                   5339:    $args               - hash of additional info,
                   5340:                           - 'ID' 
                   5341:                                'newid' -> studentID to use in replacement
1.424     albertel 5342:                                           of existing one
1.423     albertel 5343:                           - 'CODE' 
                   5344:                                'CODE_ignore_dup' - set to true if duplicates
                   5345:                                                    should be ignored.
                   5346: 	                       'CODE' - is new code or 'use_unfound'
1.424     albertel 5347:                                         if the existing unfound code should
1.423     albertel 5348:                                         be used as is
                   5349:                           - 'answer'
                   5350:                                'response' - new answer or 'none' if blank
                   5351:                                'question' - the bubble line to change
1.503     raeburn  5352:                                'questionnum' - the question identifier,
                   5353:                                                may include subquestion. 
1.423     albertel 5354: 
                   5355:   Returns:
                   5356:     $line - the modified scanline
                   5357: 
                   5358:   Side effects: 
                   5359:     $scan_data - may be updated
                   5360: 
                   5361: =cut
                   5362: 
1.82      albertel 5363: 
1.157     albertel 5364: sub scantron_fixup_scanline {
                   5365:     my ($scantron_config,$scan_data,$line,$whichline,$field,$args)=@_;
                   5366:     if ($field eq 'ID') {
                   5367: 	if (length($args->{'newid'}) > $$scantron_config{'IDlength'}) {
1.186     albertel 5368: 	    return ($line,1,'New value too large');
1.157     albertel 5369: 	}
                   5370: 	if (length($args->{'newid'}) < $$scantron_config{'IDlength'}) {
                   5371: 	    $args->{'newid'}=sprintf('%-'.$$scantron_config{'IDlength'}.'s',
                   5372: 				     $args->{'newid'});
                   5373: 	}
                   5374: 	substr($line,$$scantron_config{'IDstart'}-1,
                   5375: 	       $$scantron_config{'IDlength'})=$args->{'newid'};
                   5376: 	if ($args->{'newid'}=~/^\s*$/) {
                   5377: 	    &scan_data($scan_data,"$whichline.user",
                   5378: 		       $args->{'username'}.':'.$args->{'domain'});
                   5379: 	}
1.186     albertel 5380:     } elsif ($field eq 'CODE') {
1.192     albertel 5381: 	if ($args->{'CODE_ignore_dup'}) {
                   5382: 	    &scan_data($scan_data,"$whichline.CODE_ignore_dup",'1');
                   5383: 	}
                   5384: 	&scan_data($scan_data,"$whichline.useCODE",'1');
                   5385: 	if ($args->{'CODE'} ne 'use_unfound') {
1.191     albertel 5386: 	    if (length($args->{'CODE'}) > $$scantron_config{'CODElength'}) {
                   5387: 		return ($line,1,'New CODE value too large');
                   5388: 	    }
                   5389: 	    if (length($args->{'CODE'}) < $$scantron_config{'CODElength'}) {
                   5390: 		$args->{'CODE'}=sprintf('%-'.$$scantron_config{'CODElength'}.'s',$args->{'CODE'});
                   5391: 	    }
                   5392: 	    substr($line,$$scantron_config{'CODEstart'}-1,
                   5393: 		   $$scantron_config{'CODElength'})=$args->{'CODE'};
1.186     albertel 5394: 	}
1.157     albertel 5395:     } elsif ($field eq 'answer') {
1.497     foxr     5396: 	my $length=$scantron_config->{'Qlength'};
1.157     albertel 5397: 	my $off=$scantron_config->{'Qoff'};
                   5398: 	my $on=$scantron_config->{'Qon'};
1.497     foxr     5399: 	my $answer=${off}x$length;
                   5400: 	if ($args->{'response'} eq 'none') {
                   5401: 	    &scan_data($scan_data,
1.503     raeburn  5402: 		       "$whichline.no_bubble.".$args->{'questionnum'},'1');
1.497     foxr     5403: 	} else {
                   5404: 	    if ($on eq 'letter') {
                   5405: 		my @alphabet=('A'..'Z');
                   5406: 		$answer=$alphabet[$args->{'response'}];
                   5407: 	    } elsif ($on eq 'number') {
                   5408: 		$answer=$args->{'response'}+1;
                   5409: 		if ($answer == 10) { $answer = '0'; }
1.274     albertel 5410: 	    } else {
1.497     foxr     5411: 		substr($answer,$args->{'response'},1)=$on;
1.274     albertel 5412: 	    }
1.497     foxr     5413: 	    &scan_data($scan_data,
1.503     raeburn  5414: 		       "$whichline.no_bubble.".$args->{'questionnum'},undef,'1');
1.157     albertel 5415: 	}
1.497     foxr     5416: 	my $where=$length*($args->{'question'}-1)+$scantron_config->{'Qstart'};
                   5417: 	substr($line,$where-1,$length)=$answer;
1.157     albertel 5418:     }
                   5419:     return $line;
                   5420: }
1.423     albertel 5421: 
                   5422: =pod
                   5423: 
                   5424: =item scan_data
                   5425: 
                   5426:     Edit or look up  an item in the scan_data hash.
                   5427: 
                   5428:   Arguments:
                   5429:     $scan_data  - The hash (see scantron_getfile)
                   5430:     $key        - shorthand of the key to edit (actual key is
1.424     albertel 5431:                   scantronfilename_key).
1.423     albertel 5432:     $data        - New value of the hash entry.
                   5433:     $delete      - If true, the entry is removed from the hash.
                   5434: 
                   5435:   Returns:
                   5436:     The new value of the hash table field (undefined if deleted).
                   5437: 
                   5438: =cut
                   5439: 
                   5440: 
1.157     albertel 5441: sub scan_data {
                   5442:     my ($scan_data,$key,$value,$delete)=@_;
1.257     albertel 5443:     my $filename=$env{'form.scantron_selectfile'};
1.157     albertel 5444:     if (defined($value)) {
                   5445: 	$scan_data->{$filename.'_'.$key} = $value;
                   5446:     }
                   5447:     if ($delete) { delete($scan_data->{$filename.'_'.$key}); }
                   5448:     return $scan_data->{$filename.'_'.$key};
                   5449: }
1.423     albertel 5450: 
1.495     albertel 5451: # ----- These first few routines are general use routines.----
                   5452: 
                   5453: # Return the number of occurences of a pattern in a string.
                   5454: 
                   5455: sub occurence_count {
                   5456:     my ($string, $pattern) = @_;
                   5457: 
                   5458:     my @matches = ($string =~ /$pattern/g);
                   5459: 
                   5460:     return scalar(@matches);
                   5461: }
                   5462: 
                   5463: 
                   5464: # Take a string known to have digits and convert all the
                   5465: # digits into letters in the range J,A..I.
                   5466: 
                   5467: sub digits_to_letters {
                   5468:     my ($input) = @_;
                   5469: 
                   5470:     my @alphabet = ('J', 'A'..'I');
                   5471: 
                   5472:     my @input    = split(//, $input);
                   5473:     my $output ='';
                   5474:     for (my $i = 0; $i < scalar(@input); $i++) {
                   5475: 	if ($input[$i] =~ /\d/) {
                   5476: 	    $output .= $alphabet[$input[$i]];
                   5477: 	} else {
                   5478: 	    $output .= $input[$i];
                   5479: 	}
                   5480:     }
                   5481:     return $output;
                   5482: }
                   5483: 
1.423     albertel 5484: =pod 
                   5485: 
                   5486: =item scantron_parse_scanline
                   5487: 
                   5488:   Decodes a scanline from the selected scantron file
                   5489: 
                   5490:  Arguments:
                   5491:     line             - The text of the scantron file line to process
                   5492:     whichline        - Line number
                   5493:     scantron_config  - Hash describing the format of the scantron lines.
                   5494:     scan_data        - Hash of extra information about the scanline
                   5495:                        (see scantron_getfile for more information)
                   5496:     just_header      - True if should not process question answers but only
                   5497:                        the stuff to the left of the answers.
                   5498:  Returns:
                   5499:    Hash containing the result of parsing the scanline
                   5500: 
                   5501:    Keys are all proceeded by the string 'scantron.'
                   5502: 
                   5503:        CODE    - the CODE in use for this scanline
                   5504:        useCODE - 1 if the CODE is invalid but it usage has been forced
                   5505:                  by the operator
                   5506:        CODE_ignore_dup - 1 if the CODE is a duplicated use when unique
                   5507:                             CODEs were selected, but the usage has been
                   5508:                             forced by the operator
1.556     weissno  5509:        ID  - student/employee ID
1.423     albertel 5510:        PaperID - if used, the ID number printed on the sheet when the 
                   5511:                  paper was scanned
                   5512:        FirstName - first name from the sheet
                   5513:        LastName  - last name from the sheet
                   5514: 
                   5515:      if just_header was not true these key may also exist
                   5516: 
1.447     foxr     5517:        missingerror - a list of bubble ranges that are considered to be answers
                   5518:                       to a single question that don't have any bubbles filled in.
                   5519:                       Of the form questionnumber:firstbubblenumber:count.
                   5520:        doubleerror  - a list of bubble ranges that are considered to be answers
                   5521:                       to a single question that have more than one bubble filled in.
                   5522:                       Of the form questionnumber::firstbubblenumber:count
                   5523:    
                   5524:                 In the above, count is the number of bubble responses in the
                   5525:                 input line needed to represent the possible answers to the question.
                   5526:                 e.g. a radioresponse with 15 choices in an answer sheet with 10 choices
                   5527:                 per line would have count = 2.
                   5528: 
1.423     albertel 5529:        maxquest     - the number of the last bubble line that was parsed
                   5530: 
                   5531:        (<number> starts at 1)
                   5532:        <number>.answer - zero or more letters representing the selected
                   5533:                          letters from the scanline for the bubble line 
                   5534:                          <number>.
                   5535:                          if blank there was either no bubble or there where
                   5536:                          multiple bubbles, (consult the keys missingerror and
                   5537:                          doubleerror if this is an error condition)
                   5538: 
                   5539: =cut
                   5540: 
1.82      albertel 5541: sub scantron_parse_scanline {
1.423     albertel 5542:     my ($line,$whichline,$scantron_config,$scan_data,$just_header)=@_;
1.470     foxr     5543: 
1.82      albertel 5544:     my %record;
1.550     raeburn  5545:     my $lastpos = $env{'form.scantron_maxbubble'}*$$scantron_config{'Qlength'};
                   5546:     my $questions=substr($line,$$scantron_config{'Qstart'}-1,$lastpos);  # Answers
1.422     foxr     5547:     my $data=substr($line,0,$$scantron_config{'Qstart'}-1);     # earlier stuff
1.278     albertel 5548:     if (!($$scantron_config{'CODElocation'} eq 0 ||
                   5549: 	  $$scantron_config{'CODElocation'} eq 'none')) {
                   5550: 	if ($$scantron_config{'CODElocation'} < 0 ||
                   5551: 	    $$scantron_config{'CODElocation'} eq 'letter' ||
                   5552: 	    $$scantron_config{'CODElocation'} eq 'number') {
1.191     albertel 5553: 	    $record{'scantron.CODE'}=substr($data,
                   5554: 					    $$scantron_config{'CODEstart'}-1,
1.83      albertel 5555: 					    $$scantron_config{'CODElength'});
1.191     albertel 5556: 	    if (&scan_data($scan_data,"$whichline.useCODE")) {
                   5557: 		$record{'scantron.useCODE'}=1;
                   5558: 	    }
1.192     albertel 5559: 	    if (&scan_data($scan_data,"$whichline.CODE_ignore_dup")) {
                   5560: 		$record{'scantron.CODE_ignore_dup'}=1;
                   5561: 	    }
1.82      albertel 5562: 	} else {
                   5563: 	    #FIXME interpret first N questions
                   5564: 	}
                   5565:     }
1.83      albertel 5566:     $record{'scantron.ID'}=substr($data,$$scantron_config{'IDstart'}-1,
                   5567: 				  $$scantron_config{'IDlength'});
1.157     albertel 5568:     $record{'scantron.PaperID'}=
                   5569: 	substr($data,$$scantron_config{'PaperID'}-1,
                   5570: 	       $$scantron_config{'PaperIDlength'});
                   5571:     $record{'scantron.FirstName'}=
                   5572: 	substr($data,$$scantron_config{'FirstName'}-1,
                   5573: 	       $$scantron_config{'FirstNamelength'});
                   5574:     $record{'scantron.LastName'}=
                   5575: 	substr($data,$$scantron_config{'LastName'}-1,
                   5576: 	       $$scantron_config{'LastNamelength'});
1.423     albertel 5577:     if ($just_header) { return \%record; }
1.194     albertel 5578: 
1.82      albertel 5579:     my @alphabet=('A'..'Z');
                   5580:     my $questnum=0;
1.447     foxr     5581:     my $ansnum  =1;		# Multiple 'answer lines'/question.
                   5582: 
1.470     foxr     5583:     chomp($questions);		# Get rid of any trailing \n.
                   5584:     $questions =~ s/\r$//;      # Get rid of trailing \r too (MAC or Win uploads).
                   5585:     while (length($questions)) {
1.447     foxr     5586: 	my $answers_needed = $bubble_lines_per_response{$questnum};
1.503     raeburn  5587:         my $answer_length  = ($$scantron_config{'Qlength'} * $answers_needed)
                   5588:                              || 1;
                   5589:         $questnum++;
                   5590:         my $quest_id = $questnum;
                   5591:         my $currentquest = substr($questions,0,$answer_length);
                   5592:         $questions       = substr($questions,$answer_length);
                   5593:         if (length($currentquest) < $answer_length) { next; }
                   5594: 
                   5595:         if ($subdivided_bubble_lines{$questnum-1} =~ /,/) {
                   5596:             my $subquestnum = 1;
                   5597:             my $subquestions = $currentquest;
                   5598:             my @subanswers_needed = 
                   5599:                 split(/,/,$subdivided_bubble_lines{$questnum-1});  
                   5600:             foreach my $subans (@subanswers_needed) {
                   5601:                 my $subans_length =
                   5602:                     ($$scantron_config{'Qlength'} * $subans)  || 1;
                   5603:                 my $currsubquest = substr($subquestions,0,$subans_length);
                   5604:                 $subquestions   = substr($subquestions,$subans_length);
                   5605:                 $quest_id = "$questnum.$subquestnum";
                   5606:                 if (($$scantron_config{'Qon'} eq 'letter') ||
                   5607:                     ($$scantron_config{'Qon'} eq 'number')) {
                   5608:                     $ansnum = &scantron_validator_lettnum($ansnum, 
                   5609:                         $questnum,$quest_id,$subans,$currsubquest,$whichline,
                   5610:                         \@alphabet,\%record,$scantron_config,$scan_data);
                   5611:                 } else {
                   5612:                     $ansnum = &scantron_validator_positional($ansnum,
                   5613:                         $questnum,$quest_id,$subans,$currsubquest,$whichline,                        \@alphabet,\%record,$scantron_config,$scan_data);
                   5614:                 }
                   5615:                 $subquestnum ++;
                   5616:             }
                   5617:         } else {
                   5618:             if (($$scantron_config{'Qon'} eq 'letter') ||
                   5619:                 ($$scantron_config{'Qon'} eq 'number')) {
                   5620:                 $ansnum = &scantron_validator_lettnum($ansnum,$questnum,
                   5621:                     $quest_id,$answers_needed,$currentquest,$whichline,
                   5622:                     \@alphabet,\%record,$scantron_config,$scan_data);
                   5623:             } else {
                   5624:                 $ansnum = &scantron_validator_positional($ansnum,$questnum,
                   5625:                     $quest_id,$answers_needed,$currentquest,$whichline,
                   5626:                     \@alphabet,\%record,$scantron_config,$scan_data);
                   5627:             }
                   5628:         }
                   5629:     }
                   5630:     $record{'scantron.maxquest'}=$questnum;
                   5631:     return \%record;
                   5632: }
1.447     foxr     5633: 
1.503     raeburn  5634: sub scantron_validator_lettnum {
                   5635:     my ($ansnum,$questnum,$quest_id,$answers_needed,$currquest,$whichline,
                   5636:         $alphabet,$record,$scantron_config,$scan_data) = @_;
                   5637: 
                   5638:     # Qon 'letter' implies for each slot in currquest we have:
                   5639:     #    ? or * for doubles, a letter in A-Z for a bubble, and
                   5640:     #    about anything else (esp. a value of Qoff) for missing
                   5641:     #    bubbles.
                   5642:     #
                   5643:     # Qon 'number' implies each slot gives a digit that indexes the
                   5644:     #    bubbles filled, or Qoff, or a non-number for unbubbled lines,
                   5645:     #    and * or ? for double bubbles on a single line.
                   5646:     #
1.447     foxr     5647: 
1.503     raeburn  5648:     my $matchon;
                   5649:     if ($$scantron_config{'Qon'} eq 'letter') {
                   5650:         $matchon = '[A-Z]';
                   5651:     } elsif ($$scantron_config{'Qon'} eq 'number') {
                   5652:         $matchon = '\d';
                   5653:     }
                   5654:     my $occurrences = 0;
                   5655:     if (($responsetype_per_response{$questnum-1} eq 'essayresponse') ||
                   5656:         ($responsetype_per_response{$questnum-1} eq 'formularesponse') ||
1.510     raeburn  5657:         ($responsetype_per_response{$questnum-1} eq 'stringresponse') ||
                   5658:         ($responsetype_per_response{$questnum-1} eq 'imageresponse') ||
                   5659:         ($responsetype_per_response{$questnum-1} eq 'reactionresponse') ||
                   5660:         ($responsetype_per_response{$questnum-1} eq 'organicresponse')) {
1.503     raeburn  5661:         my @singlelines = split('',$currquest);
                   5662:         foreach my $entry (@singlelines) {
                   5663:             $occurrences = &occurence_count($entry,$matchon);
                   5664:             if ($occurrences > 1) {
                   5665:                 last;
                   5666:             }
                   5667:         } 
                   5668:     } else {
                   5669:         $occurrences = &occurence_count($currquest,$matchon); 
                   5670:     }
                   5671:     if (($currquest =~ /\?/ || $currquest =~ /\*/) || ($occurrences > 1)) {
                   5672:         push(@{$record->{'scantron.doubleerror'}},$quest_id);
                   5673:         for (my $ans=0; $ans<$answers_needed; $ans++) {
                   5674:             my $bubble = substr($currquest,$ans,1);
                   5675:             if ($bubble =~ /$matchon/ ) {
                   5676:                 if ($$scantron_config{'Qon'} eq 'number') {
                   5677:                     if ($bubble == 0) {
                   5678:                         $bubble = 10; 
                   5679:                     }
                   5680:                     $record->{"scantron.$ansnum.answer"} = 
                   5681:                         $alphabet->[$bubble-1];
                   5682:                 } else {
                   5683:                     $record->{"scantron.$ansnum.answer"} = $bubble;
                   5684:                 }
                   5685:             } else {
                   5686:                 $record->{"scantron.$ansnum.answer"}='';
                   5687:             }
                   5688:             $ansnum++;
                   5689:         }
                   5690:     } elsif (!defined($currquest)
                   5691:             || (&occurence_count($currquest, $$scantron_config{'Qoff'}) == length($currquest))
                   5692:             || (&occurence_count($currquest,$matchon) == 0)) {
                   5693:         for (my $ans=0; $ans<$answers_needed; $ans++ ) {
                   5694:             $record->{"scantron.$ansnum.answer"}='';
                   5695:             $ansnum++;
                   5696:         }
                   5697:         if (!&scan_data($scan_data,"$whichline.no_bubble.$quest_id")) {
                   5698:             push(@{$record->{'scantron.missingerror'}},$quest_id);
                   5699:         }
                   5700:     } else {
                   5701:         if ($$scantron_config{'Qon'} eq 'number') {
                   5702:             $currquest = &digits_to_letters($currquest);            
                   5703:         }
                   5704:         for (my $ans=0; $ans<$answers_needed; $ans++) {
                   5705:             my $bubble = substr($currquest,$ans,1);
                   5706:             $record->{"scantron.$ansnum.answer"} = $bubble;
                   5707:             $ansnum++;
                   5708:         }
                   5709:     }
                   5710:     return $ansnum;
                   5711: }
1.447     foxr     5712: 
1.503     raeburn  5713: sub scantron_validator_positional {
                   5714:     my ($ansnum,$questnum,$quest_id,$answers_needed,$currquest,
                   5715:         $whichline,$alphabet,$record,$scantron_config,$scan_data) = @_;
1.447     foxr     5716: 
1.503     raeburn  5717:     # Otherwise there's a positional notation;
                   5718:     # each bubble line requires Qlength items, and there are filled in
                   5719:     # bubbles for each case where there 'Qon' characters.
                   5720:     #
1.447     foxr     5721: 
1.503     raeburn  5722:     my @array=split($$scantron_config{'Qon'},$currquest,-1);
1.447     foxr     5723: 
1.503     raeburn  5724:     # If the split only gives us one element.. the full length of the
                   5725:     # answer string, no bubbles are filled in:
1.447     foxr     5726: 
1.507     raeburn  5727:     if ($answers_needed eq '') {
                   5728:         return;
                   5729:     }
                   5730: 
1.503     raeburn  5731:     if (length($array[0]) eq $$scantron_config{'Qlength'}*$answers_needed) {
                   5732:         for (my $ans=0; $ans<$answers_needed; $ans++ ) {
                   5733:             $record->{"scantron.$ansnum.answer"}='';
                   5734:             $ansnum++;
                   5735:         }
                   5736:         if (!&scan_data($scan_data,"$whichline.no_bubble.$quest_id")) {
                   5737:             push(@{$record->{"scantron.missingerror"}},$quest_id);
                   5738:         }
                   5739:     } elsif (scalar(@array) == 2) {
                   5740:         my $location = length($array[0]);
                   5741:         my $line_num = int($location / $$scantron_config{'Qlength'});
                   5742:         my $bubble   = $alphabet->[$location % $$scantron_config{'Qlength'}];
                   5743:         for (my $ans=0; $ans<$answers_needed; $ans++) {
                   5744:             if ($ans eq $line_num) {
                   5745:                 $record->{"scantron.$ansnum.answer"} = $bubble;
                   5746:             } else {
                   5747:                 $record->{"scantron.$ansnum.answer"} = ' ';
                   5748:             }
                   5749:             $ansnum++;
                   5750:          }
                   5751:     } else {
                   5752:         #  If there's more than one instance of a bubble character
                   5753:         #  That's a double bubble; with positional notation we can
                   5754:         #  record all the bubbles filled in as well as the
                   5755:         #  fact this response consists of multiple bubbles.
                   5756:         #
                   5757:         if (($responsetype_per_response{$questnum-1} eq 'essayresponse') ||
                   5758:             ($responsetype_per_response{$questnum-1} eq 'formularesponse') ||
1.510     raeburn  5759:             ($responsetype_per_response{$questnum-1} eq 'stringresponse') ||
                   5760:             ($responsetype_per_response{$questnum-1} eq 'imageresponse') ||
                   5761:             ($responsetype_per_response{$questnum-1} eq 'reactionresponse') ||
                   5762:             ($responsetype_per_response{$questnum-1} eq 'organicresponse')) {
1.503     raeburn  5763:             my $doubleerror = 0;
                   5764:             while (($currquest >= $$scantron_config{'Qlength'}) && 
                   5765:                    (!$doubleerror)) {
                   5766:                my $currline = substr($currquest,0,$$scantron_config{'Qlength'});
                   5767:                $currquest = substr($currquest,$$scantron_config{'Qlength'});
                   5768:                my @currarray = split($$scantron_config{'Qon'},$currline,-1);
                   5769:                if (length(@currarray) > 2) {
                   5770:                    $doubleerror = 1;
                   5771:                } 
                   5772:             }
                   5773:             if ($doubleerror) {
                   5774:                 push(@{$record->{'scantron.doubleerror'}},$quest_id);
                   5775:             }
                   5776:         } else {
                   5777:             push(@{$record->{'scantron.doubleerror'}},$quest_id);
                   5778:         }
                   5779:         my $item = $ansnum;
                   5780:         for (my $ans=0; $ans<$answers_needed; $ans++) {
                   5781:             $record->{"scantron.$item.answer"} = '';
                   5782:             $item ++;
                   5783:         }
1.447     foxr     5784: 
1.503     raeburn  5785:         my @ans=@array;
                   5786:         my $i=0;
                   5787:         my $increment = 0;
                   5788:         while ($#ans) {
                   5789:             $i+=length($ans[0]) + $increment;
                   5790:             my $line   = int($i/$$scantron_config{'Qlength'} + $ansnum);
                   5791:             my $bubble = $i%$$scantron_config{'Qlength'};
                   5792:             $record->{"scantron.$line.answer"}.=$alphabet->[$bubble];
                   5793:             shift(@ans);
                   5794:             $increment = 1;
                   5795:         }
                   5796:         $ansnum += $answers_needed;
1.82      albertel 5797:     }
1.503     raeburn  5798:     return $ansnum;
1.82      albertel 5799: }
                   5800: 
1.423     albertel 5801: =pod
                   5802: 
                   5803: =item scantron_add_delay
                   5804: 
                   5805:    Adds an error message that occurred during the grading phase to a
                   5806:    queue of messages to be shown after grading pass is complete
                   5807: 
                   5808:  Arguments:
1.424     albertel 5809:    $delayqueue  - arrary ref of hash ref of error messages
1.423     albertel 5810:    $scanline    - the scanline that caused the error
                   5811:    $errormesage - the error message
                   5812:    $errorcode   - a numeric code for the error
                   5813: 
                   5814:  Side Effects:
1.424     albertel 5815:    updates the $delayqueue to have a new hash ref of the error
1.423     albertel 5816: 
                   5817: =cut
                   5818: 
1.82      albertel 5819: sub scantron_add_delay {
1.140     albertel 5820:     my ($delayqueue,$scanline,$errormessage,$errorcode)=@_;
                   5821:     push(@$delayqueue,
                   5822: 	 {'line' => $scanline, 'emsg' => $errormessage,
                   5823: 	  'ecode' => $errorcode }
                   5824: 	 );
1.82      albertel 5825: }
                   5826: 
1.423     albertel 5827: =pod
                   5828: 
                   5829: =item scantron_find_student
                   5830: 
1.424     albertel 5831:    Finds the username for the current scanline
                   5832: 
                   5833:   Arguments:
                   5834:    $scantron_record - hash result from scantron_parse_scanline
                   5835:    $scan_data       - hash of correction information 
                   5836:                       (see &scantron_getfile() form more information)
                   5837:    $idmap           - hash from &username_to_idmap()
                   5838:    $line            - number of current scanline
                   5839:  
                   5840:   Returns:
                   5841:    Either 'username:domain' or undef if unknown
                   5842: 
1.423     albertel 5843: =cut
                   5844: 
1.82      albertel 5845: sub scantron_find_student {
1.157     albertel 5846:     my ($scantron_record,$scan_data,$idmap,$line)=@_;
1.83      albertel 5847:     my $scanID=$$scantron_record{'scantron.ID'};
1.157     albertel 5848:     if ($scanID =~ /^\s*$/) {
                   5849:  	return &scan_data($scan_data,"$line.user");
                   5850:     }
1.83      albertel 5851:     foreach my $id (keys(%$idmap)) {
1.157     albertel 5852:  	if (lc($id) eq lc($scanID)) {
                   5853:  	    return $$idmap{$id};
                   5854:  	}
1.83      albertel 5855:     }
                   5856:     return undef;
                   5857: }
                   5858: 
1.423     albertel 5859: =pod
                   5860: 
                   5861: =item scantron_filter
                   5862: 
1.424     albertel 5863:    Filter sub for lonnavmaps, filters out hidden resources if ignore
                   5864:    hidden resources was selected
                   5865: 
1.423     albertel 5866: =cut
                   5867: 
1.83      albertel 5868: sub scantron_filter {
                   5869:     my ($curres)=@_;
1.331     albertel 5870: 
                   5871:     if (ref($curres) && $curres->is_problem()) {
                   5872: 	# if the user has asked to not have either hidden
                   5873: 	# or 'randomout' controlled resources to be graded
                   5874: 	# don't include them
                   5875: 	if ($env{'form.scantron_options_hidden'} eq 'ignore_hidden'
                   5876: 	    && $curres->randomout) {
                   5877: 	    return 0;
                   5878: 	}
1.83      albertel 5879: 	return 1;
                   5880:     }
                   5881:     return 0;
1.82      albertel 5882: }
                   5883: 
1.423     albertel 5884: =pod
                   5885: 
                   5886: =item scantron_process_corrections
                   5887: 
1.424     albertel 5888:    Gets correction information out of submitted form data and corrects
                   5889:    the scanline
                   5890: 
1.423     albertel 5891: =cut
                   5892: 
1.157     albertel 5893: sub scantron_process_corrections {
                   5894:     my ($r) = @_;
1.257     albertel 5895:     my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
1.157     albertel 5896:     my ($scanlines,$scan_data)=&scantron_getfile();
                   5897:     my $classlist=&Apache::loncoursedata::get_classlist();
1.257     albertel 5898:     my $which=$env{'form.scantron_line'};
1.200     albertel 5899:     my $line=&scantron_get_line($scanlines,$scan_data,$which);
1.157     albertel 5900:     my ($skip,$err,$errmsg);
1.257     albertel 5901:     if ($env{'form.scantron_skip_record'}) {
1.157     albertel 5902: 	$skip=1;
1.257     albertel 5903:     } elsif ($env{'form.scantron_corrections'} =~ /^(duplicate|incorrect)ID$/) {
                   5904: 	my $newstudent=$env{'form.scantron_username'}.':'.
                   5905: 	    $env{'form.scantron_domain'};
1.157     albertel 5906: 	my $newid=$classlist->{$newstudent}->[&Apache::loncoursedata::CL_ID];
                   5907: 	($line,$err,$errmsg)=
                   5908: 	    &scantron_fixup_scanline(\%scantron_config,$scan_data,$line,$which,
                   5909: 				     'ID',{'newid'=>$newid,
1.257     albertel 5910: 				    'username'=>$env{'form.scantron_username'},
                   5911: 				    'domain'=>$env{'form.scantron_domain'}});
                   5912:     } elsif ($env{'form.scantron_corrections'} =~ /^(duplicate|incorrect)CODE$/) {
                   5913: 	my $resolution=$env{'form.scantron_CODE_resolution'};
1.190     albertel 5914: 	my $newCODE;
1.192     albertel 5915: 	my %args;
1.190     albertel 5916: 	if      ($resolution eq 'use_unfound') {
1.191     albertel 5917: 	    $newCODE='use_unfound';
1.190     albertel 5918: 	} elsif ($resolution eq 'use_found') {
1.257     albertel 5919: 	    $newCODE=$env{'form.scantron_CODE_selectedvalue'};
1.190     albertel 5920: 	} elsif ($resolution eq 'use_typed') {
1.257     albertel 5921: 	    $newCODE=$env{'form.scantron_CODE_newvalue'};
1.194     albertel 5922: 	} elsif ($resolution =~ /^use_closest_(\d+)/) {
1.257     albertel 5923: 	    $newCODE=$env{"form.scantron_CODE_closest_$1"};
1.190     albertel 5924: 	}
1.257     albertel 5925: 	if ($env{'form.scantron_corrections'} eq 'duplicateCODE') {
1.192     albertel 5926: 	    $args{'CODE_ignore_dup'}=1;
                   5927: 	}
                   5928: 	$args{'CODE'}=$newCODE;
1.186     albertel 5929: 	($line,$err,$errmsg)=
                   5930: 	    &scantron_fixup_scanline(\%scantron_config,$scan_data,$line,$which,
1.192     albertel 5931: 				     'CODE',\%args);
1.257     albertel 5932:     } elsif ($env{'form.scantron_corrections'} =~ /^(missing|double)bubble$/) {
                   5933: 	foreach my $question (split(',',$env{'form.scantron_questions'})) {
1.157     albertel 5934: 	    ($line,$err,$errmsg)=
                   5935: 		&scantron_fixup_scanline(\%scantron_config,$scan_data,$line,
                   5936: 					 $which,'answer',
                   5937: 					 { 'question'=>$question,
1.503     raeburn  5938: 		      		   'response'=>$env{"form.scantron_correct_Q_$question"},
                   5939:                                    'questionnum'=>$env{"form.scantron_questionnum_Q_$question"}});
1.157     albertel 5940: 	    if ($err) { last; }
                   5941: 	}
                   5942:     }
                   5943:     if ($err) {
1.398     albertel 5944: 	$r->print("<span class=\"LC_warning\">Unable to accept last correction, an error occurred :$errmsg:</span>");
1.157     albertel 5945:     } else {
1.200     albertel 5946: 	&scantron_put_line($scanlines,$scan_data,$which,$line,$skip);
1.157     albertel 5947: 	&scantron_putfile($scanlines,$scan_data);
                   5948:     }
                   5949: }
                   5950: 
1.423     albertel 5951: =pod
                   5952: 
                   5953: =item reset_skipping_status
                   5954: 
1.424     albertel 5955:    Forgets the current set of remember skipped scanlines (and thus
                   5956:    reverts back to considering all lines in the
                   5957:    scantron_skipped_<filename> file)
                   5958: 
1.423     albertel 5959: =cut
                   5960: 
1.200     albertel 5961: sub reset_skipping_status {
                   5962:     my ($scanlines,$scan_data)=&scantron_getfile();
                   5963:     &scan_data($scan_data,'remember_skipping',undef,1);
                   5964:     &scantron_putfile(undef,$scan_data);
                   5965: }
                   5966: 
1.423     albertel 5967: =pod
                   5968: 
                   5969: =item start_skipping
                   5970: 
1.424     albertel 5971:    Marks a scanline to be skipped. 
                   5972: 
1.423     albertel 5973: =cut
                   5974: 
1.376     albertel 5975: sub start_skipping {
1.200     albertel 5976:     my ($scan_data,$i)=@_;
                   5977:     my %remembered=split(':',&scan_data($scan_data,'remember_skipping'));
1.376     albertel 5978:     if ($env{'form.scantron_options_redo'} =~ /^redo_/) {
                   5979: 	$remembered{$i}=2;
                   5980:     } else {
                   5981: 	$remembered{$i}=1;
                   5982:     }
1.200     albertel 5983:     &scan_data($scan_data,'remember_skipping',join(':',%remembered));
                   5984: }
                   5985: 
1.423     albertel 5986: =pod
                   5987: 
                   5988: =item should_be_skipped
                   5989: 
1.424     albertel 5990:    Checks whether a scanline should be skipped.
                   5991: 
1.423     albertel 5992: =cut
                   5993: 
1.200     albertel 5994: sub should_be_skipped {
1.376     albertel 5995:     my ($scanlines,$scan_data,$i)=@_;
1.257     albertel 5996:     if ($env{'form.scantron_options_redo'} !~ /^redo_/) {
1.200     albertel 5997: 	# not redoing old skips
1.376     albertel 5998: 	if ($scanlines->{'skipped'}[$i]) { return 1; }
1.200     albertel 5999: 	return 0;
                   6000:     }
                   6001:     my %remembered=split(':',&scan_data($scan_data,'remember_skipping'));
1.376     albertel 6002: 
                   6003:     if (exists($remembered{$i}) && $remembered{$i} != 2 ) {
                   6004: 	return 0;
                   6005:     }
1.200     albertel 6006:     return 1;
                   6007: }
                   6008: 
1.423     albertel 6009: =pod
                   6010: 
                   6011: =item remember_current_skipped
                   6012: 
1.424     albertel 6013:    Discovers what scanlines are in the scantron_skipped_<filename>
                   6014:    file and remembers them into scan_data for later use.
                   6015: 
1.423     albertel 6016: =cut
                   6017: 
1.200     albertel 6018: sub remember_current_skipped {
                   6019:     my ($scanlines,$scan_data)=&scantron_getfile();
                   6020:     my %to_remember;
                   6021:     for (my $i=0;$i<=$scanlines->{'count'};$i++) {
                   6022: 	if ($scanlines->{'skipped'}[$i]) {
                   6023: 	    $to_remember{$i}=1;
                   6024: 	}
                   6025:     }
1.376     albertel 6026: 
1.200     albertel 6027:     &scan_data($scan_data,'remember_skipping',join(':',%to_remember));
                   6028:     &scantron_putfile(undef,$scan_data);
                   6029: }
                   6030: 
1.423     albertel 6031: =pod
                   6032: 
                   6033: =item check_for_error
                   6034: 
1.424     albertel 6035:     Checks if there was an error when attempting to remove a specific
                   6036:     scantron_.. bubble sheet data file. Prints out an error if
                   6037:     something went wrong.
                   6038: 
1.423     albertel 6039: =cut
                   6040: 
1.200     albertel 6041: sub check_for_error {
                   6042:     my ($r,$result)=@_;
                   6043:     if ($result ne 'ok' && $result ne 'not_found' ) {
1.492     albertel 6044: 	$r->print(&mt("An error occurred ([_1]) when trying to remove the existing corrections.",$result));
1.200     albertel 6045:     }
                   6046: }
1.157     albertel 6047: 
1.423     albertel 6048: =pod
                   6049: 
                   6050: =item scantron_warning_screen
                   6051: 
1.424     albertel 6052:    Interstitial screen to make sure the operator has selected the
                   6053:    correct options before we start the validation phase.
                   6054: 
1.423     albertel 6055: =cut
                   6056: 
1.203     albertel 6057: sub scantron_warning_screen {
                   6058:     my ($button_text)=@_;
1.257     albertel 6059:     my $title=&Apache::lonnet::gettitle($env{'form.selectpage'});
1.284     albertel 6060:     my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
1.373     albertel 6061:     my $CODElist;
1.284     albertel 6062:     if ($scantron_config{'CODElocation'} &&
                   6063: 	$scantron_config{'CODEstart'} &&
                   6064: 	$scantron_config{'CODElength'}) {
                   6065: 	$CODElist=$env{'form.scantron_CODElist'};
1.398     albertel 6066: 	if ($env{'form.scantron_CODElist'} eq '') { $CODElist='<span class="LC_warning">None</span>'; }
1.284     albertel 6067: 	$CODElist=
1.492     albertel 6068: 	    '<tr><td><b>'.&mt('List of CODES to validate against:').'</b></td><td><tt>'.
1.373     albertel 6069: 	    $env{'form.scantron_CODElist'}.'</tt></td></tr>';
1.284     albertel 6070:     }
1.492     albertel 6071:     return ('
1.203     albertel 6072: <p>
1.492     albertel 6073: <span class="LC_warning">
                   6074: '.&mt('Please double check the information below before clicking on \'[_1]\'',&mt($button_text)).'</span>
1.203     albertel 6075: </p>
                   6076: <table>
1.492     albertel 6077: <tr><td><b>'.&mt('Sequence to be Graded:').'</b></td><td>'.$title.'</td></tr>
                   6078: <tr><td><b>'.&mt('Data File that will be used:').'</b></td><td><tt>'.$env{'form.scantron_selectfile'}.'</tt></td></tr>
                   6079: '.$CODElist.'
1.203     albertel 6080: </table>
                   6081: <br />
1.492     albertel 6082: <p> '.&mt('If this information is correct, please click on \'[_1]\'.',&mt($button_text)).'</p>
                   6083: <p> '.&mt('If something is incorrect, please click the \'Grading Menu\' button to start over.').'</p>
1.203     albertel 6084: 
                   6085: <br />
1.492     albertel 6086: ');
1.203     albertel 6087: }
                   6088: 
1.423     albertel 6089: =pod
                   6090: 
                   6091: =item scantron_do_warning
                   6092: 
1.424     albertel 6093:    Check if the operator has picked something for all required
                   6094:    fields. Error out if something is missing.
                   6095: 
1.423     albertel 6096: =cut
                   6097: 
1.203     albertel 6098: sub scantron_do_warning {
                   6099:     my ($r)=@_;
1.324     albertel 6100:     my ($symb)=&get_symb($r);
1.203     albertel 6101:     if (!$symb) {return '';}
1.324     albertel 6102:     my $default_form_data=&defaultFormData($symb);
1.203     albertel 6103:     $r->print(&scantron_form_start().$default_form_data);
1.257     albertel 6104:     if ( $env{'form.selectpage'} eq '' ||
                   6105: 	 $env{'form.scantron_selectfile'} eq '' ||
                   6106: 	 $env{'form.scantron_format'} eq '' ) {
1.492     albertel 6107: 	$r->print("<p>".&mt('You have forgetten to specify some information. Please go Back and try again.')."</p>");
1.257     albertel 6108: 	if ( $env{'form.selectpage'} eq '') {
1.492     albertel 6109: 	    $r->print('<p><span class="LC_error">'.&mt('You have not selected a Sequence to grade').'</span></p>');
1.237     albertel 6110: 	} 
1.257     albertel 6111: 	if ( $env{'form.scantron_selectfile'} eq '') {
1.492     albertel 6112: 	    $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 6113: 	} 
1.257     albertel 6114: 	if ( $env{'form.scantron_format'} eq '') {
1.492     albertel 6115: 	    $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 6116: 	} 
                   6117:     } else {
1.265     www      6118: 	my $warning=&scantron_warning_screen('Grading: Validate Records');
1.492     albertel 6119: 	$r->print('
                   6120: '.$warning.'
                   6121: <input type="submit" name="submit" value="'.&mt('Grading: Validate Records').'" />
1.203     albertel 6122: <input type="hidden" name="command" value="scantron_validate" />
1.492     albertel 6123: ');
1.237     albertel 6124:     }
1.352     albertel 6125:     $r->print("</form><br />".&show_grading_menu_form($symb));
1.203     albertel 6126:     return '';
                   6127: }
                   6128: 
1.423     albertel 6129: =pod
                   6130: 
                   6131: =item scantron_form_start
                   6132: 
1.424     albertel 6133:     html hidden input for remembering all selected grading options
                   6134: 
1.423     albertel 6135: =cut
                   6136: 
1.203     albertel 6137: sub scantron_form_start {
                   6138:     my ($max_bubble)=@_;
                   6139:     my $result= <<SCANTRONFORM;
                   6140: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="scantronupload">
1.257     albertel 6141:   <input type="hidden" name="selectpage" value="$env{'form.selectpage'}" />
                   6142:   <input type="hidden" name="scantron_format" value="$env{'form.scantron_format'}" />
                   6143:   <input type="hidden" name="scantron_selectfile" value="$env{'form.scantron_selectfile'}" />
1.218     albertel 6144:   <input type="hidden" name="scantron_maxbubble" value="$max_bubble" />
1.257     albertel 6145:   <input type="hidden" name="scantron_CODElist" value="$env{'form.scantron_CODElist'}" />
                   6146:   <input type="hidden" name="scantron_CODEunique" value="$env{'form.scantron_CODEunique'}" />
                   6147:   <input type="hidden" name="scantron_options_redo" value="$env{'form.scantron_options_redo'}" />
                   6148:   <input type="hidden" name="scantron_options_ignore" value="$env{'form.scantron_options_ignore'}" />
1.331     albertel 6149:   <input type="hidden" name="scantron_options_hidden" value="$env{'form.scantron_options_hidden'}" />
1.203     albertel 6150: SCANTRONFORM
1.447     foxr     6151: 
                   6152:   my $line = 0;
                   6153:     while (defined($env{"form.scantron.bubblelines.$line"})) {
                   6154:        my $chunk =
                   6155: 	   '<input type="hidden" name="scantron.bubblelines.'.$line.'" value="'.$env{"form.scantron.bubblelines.$line"}.'" />'."\n";
1.448     foxr     6156:        $chunk .=
                   6157: 	   '<input type="hidden" name="scantron.first_bubble_line.'.$line.'" value="'.$env{"form.scantron.first_bubble_line.$line"}.'" />'."\n";
1.503     raeburn  6158:        $chunk .= 
                   6159:            '<input type="hidden" name="scantron.sub_bubblelines.'.$line.'" value="'.$env{"form.scantron.sub_bubblelines.$line"}.'" />'."\n";
1.504     raeburn  6160:        $chunk .=
                   6161:            '<input type="hidden" name="scantron.responsetype.'.$line.'" value="'.$env{"form.scantron.responsetype.$line"}.'" />'."\n";
1.447     foxr     6162:        $result .= $chunk;
                   6163:        $line++;
                   6164:    }
1.203     albertel 6165:     return $result;
                   6166: }
                   6167: 
1.423     albertel 6168: =pod
                   6169: 
                   6170: =item scantron_validate_file
                   6171: 
1.424     albertel 6172:     Dispatch routine for doing validation of a bubble sheet data file.
                   6173: 
                   6174:     Also processes any necessary information resets that need to
                   6175:     occur before validation begins (ignore previous corrections,
                   6176:     restarting the skipped records processing)
                   6177: 
1.423     albertel 6178: =cut
                   6179: 
1.157     albertel 6180: sub scantron_validate_file {
                   6181:     my ($r) = @_;
1.324     albertel 6182:     my ($symb)=&get_symb($r);
1.157     albertel 6183:     if (!$symb) {return '';}
1.324     albertel 6184:     my $default_form_data=&defaultFormData($symb);
1.200     albertel 6185:     
                   6186:     # do the detection of only doing skipped records first befroe we delete
1.424     albertel 6187:     # them when doing the corrections reset
1.257     albertel 6188:     if ($env{'form.scantron_options_redo'} ne 'redo_skipped_ready') {
1.200     albertel 6189: 	&reset_skipping_status();
                   6190:     }
1.257     albertel 6191:     if ($env{'form.scantron_options_redo'} eq 'redo_skipped') {
1.200     albertel 6192: 	&remember_current_skipped();
1.257     albertel 6193: 	$env{'form.scantron_options_redo'}='redo_skipped_ready';
1.200     albertel 6194:     }
                   6195: 
1.257     albertel 6196:     if ($env{'form.scantron_options_ignore'} eq 'ignore_corrections') {
1.200     albertel 6197: 	&check_for_error($r,&scantron_remove_file('corrected'));
                   6198: 	&check_for_error($r,&scantron_remove_file('skipped'));
                   6199: 	&check_for_error($r,&scantron_remove_scan_data());
1.257     albertel 6200: 	$env{'form.scantron_options_ignore'}='done';
1.192     albertel 6201:     }
1.200     albertel 6202: 
1.257     albertel 6203:     if ($env{'form.scantron_corrections'}) {
1.157     albertel 6204: 	&scantron_process_corrections($r);
                   6205:     }
1.503     raeburn  6206:     $r->print('<p>'.&mt('Gathering necessary information.').'</p>');$r->rflush();
1.157     albertel 6207:     #get the student pick code ready
                   6208:     $r->print(&Apache::loncommon::studentbrowser_javascript());
1.330     albertel 6209:     my $max_bubble=&scantron_get_maxbubble();
1.203     albertel 6210:     my $result=&scantron_form_start($max_bubble).$default_form_data;
1.157     albertel 6211:     $r->print($result);
                   6212:     
1.334     albertel 6213:     my @validate_phases=( 'sequence',
                   6214: 			  'ID',
1.157     albertel 6215: 			  'CODE',
                   6216: 			  'doublebubble',
                   6217: 			  'missingbubbles');
1.257     albertel 6218:     if (!$env{'form.validatepass'}) {
                   6219: 	$env{'form.validatepass'} = 0;
1.157     albertel 6220:     }
1.257     albertel 6221:     my $currentphase=$env{'form.validatepass'};
1.157     albertel 6222: 
1.448     foxr     6223: 
1.157     albertel 6224:     my $stop=0;
                   6225:     while (!$stop && $currentphase < scalar(@validate_phases)) {
1.503     raeburn  6226: 	$r->print(&mt('Validating '.$validate_phases[$currentphase]).'<br />');
1.157     albertel 6227: 	$r->rflush();
                   6228: 	my $which="scantron_validate_".$validate_phases[$currentphase];
                   6229: 	{
                   6230: 	    no strict 'refs';
                   6231: 	    ($stop,$currentphase)=&$which($r,$currentphase);
                   6232: 	}
                   6233:     }
                   6234:     if (!$stop) {
1.203     albertel 6235: 	my $warning=&scantron_warning_screen('Start Grading');
1.542     raeburn  6236: 	$r->print(&mt('Validation process complete.').'<br />'.
                   6237:                   $warning.
                   6238:                   &mt('Perform verification for each student after storage of submissions?').
                   6239:                   '&nbsp;<span class="LC_nobreak"><label>'.
                   6240:                   '<input type="radio" name="verifyrecord" value="1" />'.&mt('Yes').'</label>'.
                   6241:                   ('&nbsp;'x3).'<label>'.
                   6242:                   '<input type="radio" name="verifyrecord" value="0" checked="checked" />'.&mt('No').
                   6243:                   '</label></span><br />'.
                   6244:                   &mt('Grading will take longer if you use verification.').'<br />'.
                   6245:                   &mt("Alternatively, the 'Review scantron data' utility (see grading menu) can be used for all students after grading is complete.").'<br /><br />'.
                   6246:                   '<input type="submit" name="submit" value="'.&mt('Start Grading').'" />'.
                   6247:                   '<input type="hidden" name="command" value="scantron_process" />'."\n");
1.157     albertel 6248:     } else {
                   6249: 	$r->print('<input type="hidden" name="command" value="scantron_validate" />');
                   6250: 	$r->print("<input type='hidden' name='validatepass' value='".$currentphase."' />");
                   6251:     }
                   6252:     if ($stop) {
1.334     albertel 6253: 	if ($validate_phases[$currentphase] eq 'sequence') {
1.539     riegler  6254: 	    $r->print('<input type="submit" name="submit" value="'.&mt('Ignore').' &rarr; " />');
1.492     albertel 6255: 	    $r->print(' '.&mt('this error').' <br />');
1.334     albertel 6256: 
1.492     albertel 6257: 	    $r->print(" <p>".&mt("Or click the 'Grading Menu' button to start over.")."</p>");
1.334     albertel 6258: 	} else {
1.503     raeburn  6259:             if ($validate_phases[$currentphase] eq 'doublebubble' || $validate_phases[$currentphase] eq 'missingbubbles') {
1.539     riegler  6260: 	        $r->print('<input type="button" name="submitbutton" value="'.&mt('Continue').' &rarr;" onclick="javascript:verify_bubble_radio(this.form)" />');
1.503     raeburn  6261:             } else {
1.539     riegler  6262:                 $r->print('<input type="submit" name="submit" value="'.&mt('Continue').' &rarr;" />');
1.503     raeburn  6263:             }
1.492     albertel 6264: 	    $r->print(' '.&mt('using corrected info').' <br />');
                   6265: 	    $r->print("<input type='submit' value='".&mt("Skip")."' name='scantron_skip_record' />");
                   6266: 	    $r->print(" ".&mt("this scanline saving it for later."));
1.334     albertel 6267: 	}
1.157     albertel 6268:     }
1.352     albertel 6269:     $r->print(" </form><br />".&show_grading_menu_form($symb));
1.157     albertel 6270:     return '';
                   6271: }
                   6272: 
1.423     albertel 6273: 
                   6274: =pod
                   6275: 
                   6276: =item scantron_remove_file
                   6277: 
1.424     albertel 6278:    Removes the requested bubble sheet data file, makes sure that
                   6279:    scantron_original_<filename> is never removed
                   6280: 
                   6281: 
1.423     albertel 6282: =cut
                   6283: 
1.200     albertel 6284: sub scantron_remove_file {
1.192     albertel 6285:     my ($which)=@_;
1.257     albertel 6286:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   6287:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1.192     albertel 6288:     my $file='scantron_';
1.200     albertel 6289:     if ($which eq 'corrected' || $which eq 'skipped') {
                   6290: 	$file.=$which.'_';
1.192     albertel 6291:     } else {
                   6292: 	return 'refused';
                   6293:     }
1.257     albertel 6294:     $file.=$env{'form.scantron_selectfile'};
1.200     albertel 6295:     return &Apache::lonnet::removeuserfile($cname,$cdom,$file);
                   6296: }
                   6297: 
1.423     albertel 6298: 
                   6299: =pod
                   6300: 
                   6301: =item scantron_remove_scan_data
                   6302: 
1.424     albertel 6303:    Removes all scan_data correction for the requested bubble sheet
                   6304:    data file.  (In the case that both the are doing skipped records we need
                   6305:    to remember the old skipped lines for the time being so that element
                   6306:    persists for a while.)
                   6307: 
1.423     albertel 6308: =cut
                   6309: 
1.200     albertel 6310: sub scantron_remove_scan_data {
1.257     albertel 6311:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   6312:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1.192     albertel 6313:     my @keys=&Apache::lonnet::getkeys('nohist_scantrondata',$cdom,$cname);
                   6314:     my @todelete;
1.257     albertel 6315:     my $filename=$env{'form.scantron_selectfile'};
1.192     albertel 6316:     foreach my $key (@keys) {
                   6317: 	if ($key=~/^\Q$filename\E_/) {
1.257     albertel 6318: 	    if ($env{'form.scantron_options_redo'} eq 'redo_skipped_ready' &&
1.200     albertel 6319: 		$key=~/remember_skipping/) {
                   6320: 		next;
                   6321: 	    }
1.192     albertel 6322: 	    push(@todelete,$key);
                   6323: 	}
                   6324:     }
1.200     albertel 6325:     my $result;
1.192     albertel 6326:     if (@todelete) {
1.491     albertel 6327: 	$result = &Apache::lonnet::del('nohist_scantrondata',
                   6328: 				       \@todelete,$cdom,$cname);
                   6329:     } else {
                   6330: 	$result = 'ok';
1.192     albertel 6331:     }
                   6332:     return $result;
                   6333: }
                   6334: 
1.423     albertel 6335: 
                   6336: =pod
                   6337: 
                   6338: =item scantron_getfile
                   6339: 
1.424     albertel 6340:     Fetches the requested bubble sheet data file (all 3 versions), and
                   6341:     the scan_data hash
                   6342:   
                   6343:   Arguments:
                   6344:     None
                   6345: 
                   6346:   Returns:
                   6347:     2 hash references
                   6348: 
                   6349:      - first one has 
                   6350:          orig      -
                   6351:          corrected -
                   6352:          skipped   -  each of which points to an array ref of the specified
                   6353:                       file broken up into individual lines
                   6354:          count     - number of scanlines
                   6355:  
                   6356:      - second is the scan_data hash possible keys are
1.425     albertel 6357:        ($number refers to scanline numbered $number and thus the key affects
                   6358:         only that scanline
                   6359:         $bubline refers to the specific bubble line element and the aspects
                   6360:         refers to that specific bubble line element)
                   6361: 
                   6362:        $number.user - username:domain to use
                   6363:        $number.CODE_ignore_dup 
                   6364:                     - ignore the duplicate CODE error 
                   6365:        $number.useCODE
                   6366:                     - use the CODE in the scanline as is
                   6367:        $number.no_bubble.$bubline
                   6368:                     - it is valid that there is no bubbled in bubble
                   6369:                       at $number $bubline
                   6370:        remember_skipping
                   6371:                     - a frozen hash containing keys of $number and values
                   6372:                       of either 
                   6373:                         1 - we are on a 'do skipped records pass' and plan
                   6374:                             on processing this line
                   6375:                         2 - we are on a 'do skipped records pass' and this
                   6376:                             scanline has been marked to skip yet again
1.424     albertel 6377: 
1.423     albertel 6378: =cut
                   6379: 
1.157     albertel 6380: sub scantron_getfile {
1.200     albertel 6381:     #FIXME really would prefer a scantron directory
1.257     albertel 6382:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   6383:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1.157     albertel 6384:     my $lines;
                   6385:     $lines=&Apache::lonnet::getfile('/uploaded/'.$cdom.'/'.$cname.'/'.
1.257     albertel 6386: 		       'scantron_orig_'.$env{'form.scantron_selectfile'});
1.157     albertel 6387:     my %scanlines;
                   6388:     $scanlines{'orig'}=[(split("\n",$lines,-1))];
                   6389:     my $temp=$scanlines{'orig'};
                   6390:     $scanlines{'count'}=$#$temp;
                   6391: 
                   6392:     $lines=&Apache::lonnet::getfile('/uploaded/'.$cdom.'/'.$cname.'/'.
1.257     albertel 6393: 		       'scantron_corrected_'.$env{'form.scantron_selectfile'});
1.157     albertel 6394:     if ($lines eq '-1') {
                   6395: 	$scanlines{'corrected'}=[];
                   6396:     } else {
                   6397: 	$scanlines{'corrected'}=[(split("\n",$lines,-1))];
                   6398:     }
                   6399:     $lines=&Apache::lonnet::getfile('/uploaded/'.$cdom.'/'.$cname.'/'.
1.257     albertel 6400: 		       'scantron_skipped_'.$env{'form.scantron_selectfile'});
1.157     albertel 6401:     if ($lines eq '-1') {
                   6402: 	$scanlines{'skipped'}=[];
                   6403:     } else {
                   6404: 	$scanlines{'skipped'}=[(split("\n",$lines,-1))];
                   6405:     }
1.175     albertel 6406:     my @tmp=&Apache::lonnet::dump('nohist_scantrondata',$cdom,$cname);
1.157     albertel 6407:     if ($tmp[0] =~ /^(error:|no_such_host)/) { @tmp=(); }
                   6408:     my %scan_data = @tmp;
                   6409:     return (\%scanlines,\%scan_data);
                   6410: }
                   6411: 
1.423     albertel 6412: =pod
                   6413: 
                   6414: =item lonnet_putfile
                   6415: 
1.424     albertel 6416:    Wrapper routine to call &Apache::lonnet::finishuserfileupload
                   6417: 
                   6418:  Arguments:
                   6419:    $contents - data to store
                   6420:    $filename - filename to store $contents into
                   6421: 
                   6422:  Returns:
                   6423:    result value from &Apache::lonnet::finishuserfileupload
                   6424: 
1.423     albertel 6425: =cut
                   6426: 
1.157     albertel 6427: sub lonnet_putfile {
                   6428:     my ($contents,$filename)=@_;
1.257     albertel 6429:     my $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   6430:     my $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
                   6431:     $env{'form.sillywaytopassafilearound'}=$contents;
1.275     albertel 6432:     &Apache::lonnet::finishuserfileupload($docuname,$docudom,'sillywaytopassafilearound',$filename);
1.157     albertel 6433: 
                   6434: }
                   6435: 
1.423     albertel 6436: =pod
                   6437: 
                   6438: =item scantron_putfile
                   6439: 
1.424     albertel 6440:     Stores the current version of the bubble sheet data files, and the
                   6441:     scan_data hash. (Does not modify the original version only the
                   6442:     corrected and skipped versions.
                   6443: 
                   6444:  Arguments:
                   6445:     $scanlines - hash ref that looks like the first return value from
                   6446:                  &scantron_getfile()
                   6447:     $scan_data - hash ref that looks like the second return value from
                   6448:                  &scantron_getfile()
                   6449: 
1.423     albertel 6450: =cut
                   6451: 
1.157     albertel 6452: sub scantron_putfile {
                   6453:     my ($scanlines,$scan_data) = @_;
1.200     albertel 6454:     #FIXME really would prefer a scantron directory
1.257     albertel 6455:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   6456:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1.200     albertel 6457:     if ($scanlines) {
                   6458: 	my $prefix='scantron_';
1.157     albertel 6459: # no need to update orig, shouldn't change
                   6460: #   &lonnet_putfile(join("\n",@{$scanlines->{'orig'}}),$prefix.'orig_'.
1.257     albertel 6461: #		    $env{'form.scantron_selectfile'});
1.200     albertel 6462: 	&lonnet_putfile(join("\n",@{$scanlines->{'corrected'}}),
                   6463: 			$prefix.'corrected_'.
1.257     albertel 6464: 			$env{'form.scantron_selectfile'});
1.200     albertel 6465: 	&lonnet_putfile(join("\n",@{$scanlines->{'skipped'}}),
                   6466: 			$prefix.'skipped_'.
1.257     albertel 6467: 			$env{'form.scantron_selectfile'});
1.200     albertel 6468:     }
1.175     albertel 6469:     &Apache::lonnet::put('nohist_scantrondata',$scan_data,$cdom,$cname);
1.157     albertel 6470: }
                   6471: 
1.423     albertel 6472: =pod
                   6473: 
                   6474: =item scantron_get_line
                   6475: 
1.424     albertel 6476:    Returns the correct version of the scanline
                   6477: 
                   6478:  Arguments:
                   6479:     $scanlines - hash ref that looks like the first return value from
                   6480:                  &scantron_getfile()
                   6481:     $scan_data - hash ref that looks like the second return value from
                   6482:                  &scantron_getfile()
                   6483:     $i         - number of the requested line (starts at 0)
                   6484: 
                   6485:  Returns:
                   6486:    A scanline, (either the original or the corrected one if it
                   6487:    exists), or undef if the requested scanline should be
                   6488:    skipped. (Either because it's an skipped scanline, or it's an
                   6489:    unskipped scanline and we are not doing a 'do skipped scanlines'
                   6490:    pass.
                   6491: 
1.423     albertel 6492: =cut
                   6493: 
1.157     albertel 6494: sub scantron_get_line {
1.200     albertel 6495:     my ($scanlines,$scan_data,$i)=@_;
1.376     albertel 6496:     if (&should_be_skipped($scanlines,$scan_data,$i)) { return undef; }
                   6497:     #if ($scanlines->{'skipped'}[$i]) { return undef; }
1.157     albertel 6498:     if ($scanlines->{'corrected'}[$i]) {return $scanlines->{'corrected'}[$i];}
                   6499:     return $scanlines->{'orig'}[$i]; 
                   6500: }
                   6501: 
1.423     albertel 6502: =pod
                   6503: 
                   6504: =item scantron_todo_count
                   6505: 
1.424     albertel 6506:     Counts the number of scanlines that need processing.
                   6507: 
                   6508:  Arguments:
                   6509:     $scanlines - hash ref that looks like the first return value from
                   6510:                  &scantron_getfile()
                   6511:     $scan_data - hash ref that looks like the second return value from
                   6512:                  &scantron_getfile()
                   6513: 
                   6514:  Returns:
                   6515:     $count - number of scanlines to process
                   6516: 
1.423     albertel 6517: =cut
                   6518: 
1.200     albertel 6519: sub get_todo_count {
                   6520:     my ($scanlines,$scan_data)=@_;
                   6521:     my $count=0;
                   6522:     for (my $i=0;$i<=$scanlines->{'count'};$i++) {
                   6523: 	my $line=&scantron_get_line($scanlines,$scan_data,$i);
                   6524: 	if ($line=~/^[\s\cz]*$/) { next; }
                   6525: 	$count++;
                   6526:     }
                   6527:     return $count;
                   6528: }
                   6529: 
1.423     albertel 6530: =pod
                   6531: 
                   6532: =item scantron_put_line
                   6533: 
1.424     albertel 6534:     Updates the 'corrected' or 'skipped' versions of the bubble sheet
                   6535:     data file.
                   6536: 
                   6537:  Arguments:
                   6538:     $scanlines - hash ref that looks like the first return value from
                   6539:                  &scantron_getfile()
                   6540:     $scan_data - hash ref that looks like the second return value from
                   6541:                  &scantron_getfile()
                   6542:     $i         - line number to update
                   6543:     $newline   - contents of the updated scanline
                   6544:     $skip      - if true make the line for skipping and update the
                   6545:                  'skipped' file
                   6546: 
1.423     albertel 6547: =cut
                   6548: 
1.157     albertel 6549: sub scantron_put_line {
1.200     albertel 6550:     my ($scanlines,$scan_data,$i,$newline,$skip)=@_;
1.157     albertel 6551:     if ($skip) {
                   6552: 	$scanlines->{'skipped'}[$i]=$newline;
1.376     albertel 6553: 	&start_skipping($scan_data,$i);
1.157     albertel 6554: 	return;
                   6555:     }
                   6556:     $scanlines->{'corrected'}[$i]=$newline;
                   6557: }
                   6558: 
1.423     albertel 6559: =pod
                   6560: 
                   6561: =item scantron_clear_skip
                   6562: 
1.424     albertel 6563:    Remove a line from the 'skipped' file
                   6564: 
                   6565:  Arguments:
                   6566:     $scanlines - hash ref that looks like the first return value from
                   6567:                  &scantron_getfile()
                   6568:     $scan_data - hash ref that looks like the second return value from
                   6569:                  &scantron_getfile()
                   6570:     $i         - line number to update
                   6571: 
1.423     albertel 6572: =cut
                   6573: 
1.376     albertel 6574: sub scantron_clear_skip {
                   6575:     my ($scanlines,$scan_data,$i)=@_;
                   6576:     if (exists($scanlines->{'skipped'}[$i])) {
                   6577: 	undef($scanlines->{'skipped'}[$i]);
                   6578: 	return 1;
                   6579:     }
                   6580:     return 0;
                   6581: }
                   6582: 
1.423     albertel 6583: =pod
                   6584: 
                   6585: =item scantron_filter_not_exam
                   6586: 
1.424     albertel 6587:    Filter routine used by &Apache::lonnavmaps::retrieveResources(), to
                   6588:    filter out resources that are not marked as 'exam' mode
                   6589: 
1.423     albertel 6590: =cut
                   6591: 
1.334     albertel 6592: sub scantron_filter_not_exam {
                   6593:     my ($curres)=@_;
                   6594:     
                   6595:     if (ref($curres) && $curres->is_problem() && !$curres->is_exam()) {
                   6596: 	# if the user has asked to not have either hidden
                   6597: 	# or 'randomout' controlled resources to be graded
                   6598: 	# don't include them
                   6599: 	if ($env{'form.scantron_options_hidden'} eq 'ignore_hidden'
                   6600: 	    && $curres->randomout) {
                   6601: 	    return 0;
                   6602: 	}
                   6603: 	return 1;
                   6604:     }
                   6605:     return 0;
                   6606: }
                   6607: 
1.423     albertel 6608: =pod
                   6609: 
                   6610: =item scantron_validate_sequence
                   6611: 
1.424     albertel 6612:     Validates the selected sequence, checking for resource that are
                   6613:     not set to exam mode.
                   6614: 
1.423     albertel 6615: =cut
                   6616: 
1.334     albertel 6617: sub scantron_validate_sequence {
                   6618:     my ($r,$currentphase) = @_;
                   6619: 
                   6620:     my $navmap=Apache::lonnavmaps::navmap->new();
                   6621:     my (undef,undef,$sequence)=
                   6622: 	&Apache::lonnet::decode_symb($env{'form.selectpage'});
                   6623: 
                   6624:     my $map=$navmap->getResourceByUrl($sequence);
                   6625: 
                   6626:     $r->print('<input type="hidden" name="validate_sequence_exam"
                   6627:                                     value="ignore" />');
                   6628:     if ($env{'form.validate_sequence_exam'} ne 'ignore') {
                   6629: 	my @resources=
                   6630: 	    $navmap->retrieveResources($map,\&scantron_filter_not_exam,1,0);
                   6631: 	if (@resources) {
1.357     banghart 6632: 	    $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 6633: 	    return (1,$currentphase);
                   6634: 	}
                   6635:     }
                   6636: 
                   6637:     return (0,$currentphase+1);
                   6638: }
                   6639: 
1.423     albertel 6640: 
                   6641: 
1.157     albertel 6642: sub scantron_validate_ID {
                   6643:     my ($r,$currentphase) = @_;
                   6644:     
                   6645:     #get student info
                   6646:     my $classlist=&Apache::loncoursedata::get_classlist();
                   6647:     my %idmap=&username_to_idmap($classlist);
                   6648: 
                   6649:     #get scantron line setup
1.257     albertel 6650:     my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
1.157     albertel 6651:     my ($scanlines,$scan_data)=&scantron_getfile();
1.447     foxr     6652:     
                   6653:     &scantron_get_maxbubble();	# parse needs the bubble_lines.. array.
1.157     albertel 6654: 
                   6655:     my %found=('ids'=>{},'usernames'=>{});
                   6656:     for (my $i=0;$i<=$scanlines->{'count'};$i++) {
1.200     albertel 6657: 	my $line=&scantron_get_line($scanlines,$scan_data,$i);
1.157     albertel 6658: 	if ($line=~/^[\s\cz]*$/) { next; }
                   6659: 	my $scan_record=&scantron_parse_scanline($line,$i,\%scantron_config,
                   6660: 						 $scan_data);
                   6661: 	my $id=$$scan_record{'scantron.ID'};
                   6662: 	my $found;
                   6663: 	foreach my $checkid (keys(%idmap)) {
                   6664: 	    if (lc($checkid) eq lc($id)) { $found=$checkid;last; }
                   6665: 	}
                   6666: 	if ($found) {
                   6667: 	    my $username=$idmap{$found};
                   6668: 	    if ($found{'ids'}{$found}) {
                   6669: 		&scantron_get_correction($r,$i,$scan_record,\%scantron_config,
                   6670: 					 $line,'duplicateID',$found);
1.194     albertel 6671: 		return(1,$currentphase);
1.157     albertel 6672: 	    } elsif ($found{'usernames'}{$username}) {
                   6673: 		&scantron_get_correction($r,$i,$scan_record,\%scantron_config,
                   6674: 					 $line,'duplicateID',$username);
1.194     albertel 6675: 		return(1,$currentphase);
1.157     albertel 6676: 	    }
1.186     albertel 6677: 	    #FIXME store away line we previously saw the ID on to use above
1.157     albertel 6678: 	    $found{'ids'}{$found}++;
                   6679: 	    $found{'usernames'}{$username}++;
                   6680: 	} else {
                   6681: 	    if ($id =~ /^\s*$/) {
1.158     albertel 6682: 		my $username=&scan_data($scan_data,"$i.user");
1.157     albertel 6683: 		if (defined($username) && $found{'usernames'}{$username}) {
                   6684: 		    &scantron_get_correction($r,$i,$scan_record,
                   6685: 					     \%scantron_config,
                   6686: 					     $line,'duplicateID',$username);
1.194     albertel 6687: 		    return(1,$currentphase);
1.157     albertel 6688: 		} elsif (!defined($username)) {
                   6689: 		    &scantron_get_correction($r,$i,$scan_record,
                   6690: 					     \%scantron_config,
                   6691: 					     $line,'incorrectID');
1.194     albertel 6692: 		    return(1,$currentphase);
1.157     albertel 6693: 		}
                   6694: 		$found{'usernames'}{$username}++;
                   6695: 	    } else {
                   6696: 		&scantron_get_correction($r,$i,$scan_record,\%scantron_config,
                   6697: 					 $line,'incorrectID');
1.194     albertel 6698: 		return(1,$currentphase);
1.157     albertel 6699: 	    }
                   6700: 	}
                   6701:     }
                   6702: 
                   6703:     return (0,$currentphase+1);
                   6704: }
                   6705: 
1.423     albertel 6706: 
1.157     albertel 6707: sub scantron_get_correction {
                   6708:     my ($r,$i,$scan_record,$scan_config,$line,$error,$arg)=@_;
1.454     banghart 6709: #FIXME in the case of a duplicated ID the previous line, probably need
1.157     albertel 6710: #to show both the current line and the previous one and allow skipping
                   6711: #the previous one or the current one
                   6712: 
1.333     albertel 6713:     if ( $$scan_record{'scantron.PaperID'} =~ /\S/) {
1.492     albertel 6714: 	$r->print("<p>".&mt("<b>An error was detected ($error)</b>".
                   6715: 			    " for PaperID <tt>[_1]</tt>",
                   6716: 			    $$scan_record{'scantron.PaperID'})."</p> \n");
1.157     albertel 6717:     } else {
1.492     albertel 6718: 	$r->print("<p>".&mt("<b>An error was detected ($error)</b>".
                   6719: 			    " in scanline [_1] <pre>[_2]</pre>",
                   6720: 			    $i,$line)."</p> \n");
                   6721:     }
                   6722:     my $message="<p>".&mt("The ID on the form is  <tt>[_1]</tt><br />".
                   6723: 			  "The name on the paper is [_2],[_3]",
                   6724: 			  $$scan_record{'scantron.ID'},
                   6725: 			  $$scan_record{'scantron.LastName'},
                   6726: 			  $$scan_record{'scantron.FirstName'})."</p>";
1.242     albertel 6727: 
1.157     albertel 6728:     $r->print('<input type="hidden" name="scantron_corrections" value="'.$error.'" />'."\n");
                   6729:     $r->print('<input type="hidden" name="scantron_line" value="'.$i.'" />'."\n");
1.503     raeburn  6730:                            # Array populated for doublebubble or
                   6731:     my @lines_to_correct;  # missingbubble errors to build javascript
                   6732:                            # to validate radio button checking   
                   6733: 
1.157     albertel 6734:     if ($error =~ /ID$/) {
1.186     albertel 6735: 	if ($error eq 'incorrectID') {
1.492     albertel 6736: 	    $r->print("<p>".&mt("The encoded ID is not in the classlist").
                   6737: 		      "</p>\n");
1.157     albertel 6738: 	} elsif ($error eq 'duplicateID') {
1.492     albertel 6739: 	    $r->print("<p>".&mt("The encoded ID has also been used by a previous paper [_1]",$arg)."</p>\n");
1.157     albertel 6740: 	}
1.242     albertel 6741: 	$r->print($message);
1.492     albertel 6742: 	$r->print("<p>".&mt("How should I handle this?")." <br /> \n");
1.157     albertel 6743: 	$r->print("\n<ul><li> ");
                   6744: 	#FIXME it would be nice if this sent back the user ID and
                   6745: 	#could do partial userID matches
                   6746: 	$r->print(&Apache::loncommon::selectstudent_link('scantronupload',
                   6747: 				       'scantron_username','scantron_domain'));
                   6748: 	$r->print(": <input type='text' name='scantron_username' value='' />");
                   6749: 	$r->print("\n@".
1.257     albertel 6750: 		 &Apache::loncommon::select_dom_form($env{'request.role.domain'},'scantron_domain'));
1.157     albertel 6751: 
                   6752: 	$r->print('</li>');
1.186     albertel 6753:     } elsif ($error =~ /CODE$/) {
                   6754: 	if ($error eq 'incorrectCODE') {
1.492     albertel 6755: 	    $r->print("<p>".&mt("The encoded CODE is not in the list of possible CODEs.")."</p>\n");
1.186     albertel 6756: 	} elsif ($error eq 'duplicateCODE') {
1.492     albertel 6757: 	    $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 6758: 	}
1.492     albertel 6759: 	$r->print("<p>".&mt("The CODE on the form is  <tt>'[_1]'</tt>",
                   6760: 			    $$scan_record{'scantron.CODE'})."<br />\n");
1.242     albertel 6761: 	$r->print($message);
1.492     albertel 6762: 	$r->print("<p>".&mt("How should I handle this?")." <br /> \n");
1.187     albertel 6763: 	$r->print("\n<br /> ");
1.194     albertel 6764: 	my $i=0;
1.273     albertel 6765: 	if ($error eq 'incorrectCODE' 
                   6766: 	    && $$scan_record{'scantron.CODE'}=~/\S/ ) {
1.194     albertel 6767: 	    my ($max,$closest)=&scantron_get_closely_matching_CODEs($arg,$$scan_record{'scantron.CODE'});
1.278     albertel 6768: 	    if ($closest > 0) {
                   6769: 		foreach my $testcode (@{$closest}) {
                   6770: 		    my $checked='';
1.401     albertel 6771: 		    if (!$i) { $checked=' checked="checked" '; }
1.492     albertel 6772: 		    $r->print("
                   6773:    <label>
                   6774:        <input type='radio' name='scantron_CODE_resolution' value='use_closest_$i' $checked />
                   6775:        ".&mt("Use the similar CODE [_1] instead.",
                   6776: 	    "<b><tt>".$testcode."</tt></b>")."
                   6777:     </label>
                   6778:     <input type='hidden' name='scantron_CODE_closest_$i' value='$testcode' />");
1.278     albertel 6779: 		    $r->print("\n<br />");
                   6780: 		    $i++;
                   6781: 		}
1.194     albertel 6782: 	    }
                   6783: 	}
1.273     albertel 6784: 	if ($$scan_record{'scantron.CODE'}=~/\S/ ) {
1.401     albertel 6785: 	    my $checked; if (!$i) { $checked=' checked="checked" '; }
1.492     albertel 6786: 	    $r->print("
                   6787:     <label>
                   6788:         <input type='radio' name='scantron_CODE_resolution' value='use_unfound' $checked />
                   6789:        ".&mt("Use the CODE [_1] that is was on the paper, ignoring the error.",
                   6790: 	     "<b><tt>".$$scan_record{'scantron.CODE'}."</tt></b>")."
                   6791:     </label>");
1.273     albertel 6792: 	    $r->print("\n<br />");
                   6793: 	}
1.194     albertel 6794: 
1.188     albertel 6795: 	$r->print(<<ENDSCRIPT);
                   6796: <script type="text/javascript">
                   6797: function change_radio(field) {
1.190     albertel 6798:     var slct=document.scantronupload.scantron_CODE_resolution;
1.188     albertel 6799:     var i;
                   6800:     for (i=0;i<slct.length;i++) {
                   6801:         if (slct[i].value==field) { slct[i].checked=true; }
                   6802:     }
                   6803: }
                   6804: </script>
                   6805: ENDSCRIPT
1.187     albertel 6806: 	my $href="/adm/pickcode?".
1.359     www      6807: 	   "form=".&escape("scantronupload").
                   6808: 	   "&scantron_format=".&escape($env{'form.scantron_format'}).
                   6809: 	   "&scantron_CODElist=".&escape($env{'form.scantron_CODElist'}).
                   6810: 	   "&curCODE=".&escape($$scan_record{'scantron.CODE'}).
                   6811: 	   "&scantron_selectfile=".&escape($env{'form.scantron_selectfile'});
1.332     albertel 6812: 	if ($env{'form.scantron_CODElist'} =~ /\S/) { 
1.492     albertel 6813: 	    $r->print("
                   6814:     <label>
                   6815:        <input type='radio' name='scantron_CODE_resolution' value='use_found' />
                   6816:        ".&mt("[_1]Select[_2] a CODE from the list of all CODEs and use it.",
                   6817: 	     "<a target='_blank' href='$href'>","</a>")."
                   6818:     </label> 
1.558     bisitz   6819:     ".&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 6820: 	    $r->print("\n<br />");
                   6821: 	}
1.492     albertel 6822: 	$r->print("
                   6823:     <label>
                   6824:        <input type='radio' name='scantron_CODE_resolution' value='use_typed' />
                   6825:        ".&mt("Use [_1] as the CODE.",
                   6826: 	     "</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 6827: 	$r->print("\n<br /><br />");
1.157     albertel 6828:     } elsif ($error eq 'doublebubble') {
1.503     raeburn  6829: 	$r->print("<p>".&mt("There have been multiple bubbles scanned for some question(s)")."</p>\n");
1.497     foxr     6830: 
                   6831: 	# The form field scantron_questions is acutally a list of line numbers.
                   6832: 	# represented by this form so:
                   6833: 
                   6834: 	my $line_list = &questions_to_line_list($arg);
                   6835: 
1.157     albertel 6836: 	$r->print('<input type="hidden" name="scantron_questions" value="'.
1.497     foxr     6837: 		  $line_list.'" />');
1.242     albertel 6838: 	$r->print($message);
1.492     albertel 6839: 	$r->print("<p>".&mt("Please indicate which bubble should be used for grading")."</p>");
1.157     albertel 6840: 	foreach my $question (@{$arg}) {
1.503     raeburn  6841: 	    my @linenums = &prompt_for_corrections($r,$question,$scan_config,
                   6842:                                                    $scan_record, $error);
1.524     raeburn  6843:             push(@lines_to_correct,@linenums);
1.157     albertel 6844: 	}
1.503     raeburn  6845:         $r->print(&verify_bubbles_checked(@lines_to_correct));
1.157     albertel 6846:     } elsif ($error eq 'missingbubble') {
1.492     albertel 6847: 	$r->print("<p>".&mt("There have been <b>no</b> bubbles scanned for some question(s)")."</p>\n");
1.242     albertel 6848: 	$r->print($message);
1.492     albertel 6849: 	$r->print("<p>".&mt("Please indicate which bubble should be used for grading.")."</p>");
1.503     raeburn  6850: 	$r->print(&mt("Some questions have no scanned bubbles.")."\n");
1.497     foxr     6851: 
1.503     raeburn  6852: 	# The form field scantron_questions is actually a list of line numbers not
1.497     foxr     6853: 	# a list of question numbers. Therefore:
                   6854: 	#
                   6855: 	
                   6856: 	my $line_list = &questions_to_line_list($arg);
                   6857: 
1.157     albertel 6858: 	$r->print('<input type="hidden" name="scantron_questions" value="'.
1.497     foxr     6859: 		  $line_list.'" />');
1.157     albertel 6860: 	foreach my $question (@{$arg}) {
1.503     raeburn  6861: 	    my @linenums = &prompt_for_corrections($r,$question,$scan_config,
                   6862:                                                    $scan_record, $error);
1.524     raeburn  6863:             push(@lines_to_correct,@linenums);
1.157     albertel 6864: 	}
1.503     raeburn  6865:         $r->print(&verify_bubbles_checked(@lines_to_correct));
1.157     albertel 6866:     } else {
                   6867: 	$r->print("\n<ul>");
                   6868:     }
                   6869:     $r->print("\n</li></ul>");
1.497     foxr     6870: }
                   6871: 
1.503     raeburn  6872: sub verify_bubbles_checked {
                   6873:     my (@ansnums) = @_;
                   6874:     my $ansnumstr = join('","',@ansnums);
                   6875:     my $warning = &mt("A bubble or 'No bubble' selection has not been made for one or more lines.");
                   6876:     my $output = (<<ENDSCRIPT);
                   6877: <script type="text/javascript">
                   6878: function verify_bubble_radio(form) {
                   6879:     var ansnumArray = new Array ("$ansnumstr");
                   6880:     var need_bubble_count = 0;
                   6881:     for (var i=0; i<ansnumArray.length; i++) {
                   6882:         if (form.elements["scantron_correct_Q_"+ansnumArray[i]].length > 1) {
                   6883:             var bubble_picked = 0; 
                   6884:             for (var j=0; j<form.elements["scantron_correct_Q_"+ansnumArray[i]].length; j++) {
                   6885:                 if (form.elements["scantron_correct_Q_"+ansnumArray[i]][j].checked == true) {
                   6886:                     bubble_picked = 1;
                   6887:                 }
                   6888:             }
                   6889:             if (bubble_picked == 0) {
                   6890:                 need_bubble_count ++;
                   6891:             }
                   6892:         }
                   6893:     }
                   6894:     if (need_bubble_count) {
                   6895:         alert("$warning");
                   6896:         return;
                   6897:     }
                   6898:     form.submit(); 
                   6899: }
                   6900: </script>
                   6901: ENDSCRIPT
                   6902:     return $output;
                   6903: }
                   6904: 
1.497     foxr     6905: =pod
                   6906: 
                   6907: =item  questions_to_line_list
1.157     albertel 6908: 
1.497     foxr     6909: Converts a list of questions into a string of comma separated
                   6910: line numbers in the answer sheet used by the questions.  This is
                   6911: used to fill in the scantron_questions form field.
                   6912: 
                   6913:   Arguments:
                   6914:      questions    - Reference to an array of questions.
                   6915: 
                   6916: =cut
                   6917: 
                   6918: 
                   6919: sub questions_to_line_list {
                   6920:     my ($questions) = @_;
                   6921:     my @lines;
                   6922: 
1.503     raeburn  6923:     foreach my $item (@{$questions}) {
                   6924:         my $question = $item;
                   6925:         my ($first,$count,$last);
                   6926:         if ($item =~ /^(\d+)\.(\d+)$/) {
                   6927:             $question = $1;
                   6928:             my $subquestion = $2;
                   6929:             $first = $first_bubble_line{$question-1} + 1;
                   6930:             my @subans = split(/,/,$subdivided_bubble_lines{$question-1});
                   6931:             my $subcount = 1;
                   6932:             while ($subcount<$subquestion) {
                   6933:                 $first += $subans[$subcount-1];
                   6934:                 $subcount ++;
                   6935:             }
                   6936:             $count = $subans[$subquestion-1];
                   6937:         } else {
                   6938: 	    $first   = $first_bubble_line{$question-1} + 1;
                   6939: 	    $count   = $bubble_lines_per_response{$question-1};
                   6940:         }
1.506     raeburn  6941:         $last = $first+$count-1;
1.503     raeburn  6942:         push(@lines, ($first..$last));
1.497     foxr     6943:     }
                   6944:     return join(',', @lines);
                   6945: }
                   6946: 
                   6947: =pod 
                   6948: 
                   6949: =item prompt_for_corrections
                   6950: 
                   6951: Prompts for a potentially multiline correction to the
                   6952: user's bubbling (factors out common code from scantron_get_correction
                   6953: for multi and missing bubble cases).
                   6954: 
                   6955:  Arguments:
                   6956:    $r           - Apache request object.
                   6957:    $question    - The question number to prompt for.
                   6958:    $scan_config - The scantron file configuration hash.
                   6959:    $scan_record - Reference to the hash that has the the parsed scanlines.
1.503     raeburn  6960:    $error       - Type of error
1.497     foxr     6961: 
                   6962:  Implicit inputs:
                   6963:    %bubble_lines_per_response   - Starting line numbers for each question.
                   6964:                                   Numbered from 0 (but question numbers are from
                   6965:                                   1.
                   6966:    %first_bubble_line           - Starting bubble line for each question.
1.509     raeburn  6967:    %subdivided_bubble_lines     - optionresponse, matchresponse and rankresponse 
                   6968:                                   type problems render as separate sub-questions, 
1.503     raeburn  6969:                                   in exam mode. This hash contains a 
                   6970:                                   comma-separated list of the lines per 
                   6971:                                   sub-question.
1.510     raeburn  6972:    %responsetype_per_response   - essayresponse, formularesponse,
                   6973:                                   stringresponse, imageresponse, reactionresponse,
                   6974:                                   and organicresponse type problem parts can have
1.503     raeburn  6975:                                   multiple lines per response if the weight
                   6976:                                   assigned exceeds 10.  In this case, only
                   6977:                                   one bubble per line is permitted, but more 
                   6978:                                   than one line might contain bubbles, e.g.
                   6979:                                   bubbling of: line 1 - J, line 2 - J, 
                   6980:                                   line 3 - B would assign 22 points.  
1.497     foxr     6981: 
                   6982: =cut
                   6983: 
                   6984: sub prompt_for_corrections {
1.503     raeburn  6985:     my ($r, $question, $scan_config, $scan_record, $error) = @_;
                   6986:     my ($current_line,$lines);
                   6987:     my @linenums;
                   6988:     my $questionnum = $question;
                   6989:     if ($question =~ /^(\d+)\.(\d+)$/) {
                   6990:         $question = $1;
                   6991:         $current_line = $first_bubble_line{$question-1} + 1 ;
                   6992:         my $subquestion = $2;
                   6993:         my @subans = split(/,/,$subdivided_bubble_lines{$question-1});
                   6994:         my $subcount = 1;
                   6995:         while ($subcount<$subquestion) {
                   6996:             $current_line += $subans[$subcount-1];
                   6997:             $subcount ++;
                   6998:         }
                   6999:         $lines = $subans[$subquestion-1];
                   7000:     } else {
                   7001:         $current_line = $first_bubble_line{$question-1} + 1 ;
                   7002:         $lines        = $bubble_lines_per_response{$question-1};
                   7003:     }
1.497     foxr     7004:     if ($lines > 1) {
1.503     raeburn  7005:         $r->print(&mt('The group of bubble lines below responds to a single question.').'<br />');
                   7006:         if (($responsetype_per_response{$question-1} eq 'essayresponse') ||
                   7007:             ($responsetype_per_response{$question-1} eq 'formularesponse') ||
1.510     raeburn  7008:             ($responsetype_per_response{$question-1} eq 'stringresponse') ||
                   7009:             ($responsetype_per_response{$question-1} eq 'imageresponse') ||
                   7010:             ($responsetype_per_response{$question-1} eq 'reactionresponse') ||
                   7011:             ($responsetype_per_response{$question-1} eq 'organicresponse')) {
1.503     raeburn  7012:             $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 scantron sheets.",$lines).'<br /><br />'.&mt('A non-zero score can be assigned to the student during scantron 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 />');
                   7013:         } else {
                   7014:             $r->print(&mt("Select at most one bubble in a single line and select 'No Bubble' in all the other lines. ")."<br />");
                   7015:         }
1.497     foxr     7016:     }
                   7017:     for (my $i =0; $i < $lines; $i++) {
1.503     raeburn  7018:         my $selected = $$scan_record{"scantron.$current_line.answer"};
                   7019: 	&scantron_bubble_selector($r,$scan_config,$current_line, 
                   7020: 	        		  $questionnum,$error,split('', $selected));
1.524     raeburn  7021:         push(@linenums,$current_line);
1.497     foxr     7022: 	$current_line++;
                   7023:     }
                   7024:     if ($lines > 1) {
                   7025: 	$r->print("<hr /><br />");
                   7026:     }
1.503     raeburn  7027:     return @linenums;
1.157     albertel 7028: }
1.423     albertel 7029: 
                   7030: =pod
                   7031: 
                   7032: =item scantron_bubble_selector
                   7033:   
                   7034:    Generates the html radiobuttons to correct a single bubble line
1.424     albertel 7035:    possibly showing the existing the selected bubbles if known
1.423     albertel 7036: 
                   7037:  Arguments:
                   7038:     $r           - Apache request object
                   7039:     $scan_config - hash from &get_scantron_config()
1.497     foxr     7040:     $line        - Number of the line being displayed.
1.503     raeburn  7041:     $questionnum - Question number (may include subquestion)
                   7042:     $error       - Type of error.
1.497     foxr     7043:     @selected    - Array of bubbles picked on this line.
1.423     albertel 7044: 
                   7045: =cut
                   7046: 
1.157     albertel 7047: sub scantron_bubble_selector {
1.503     raeburn  7048:     my ($r,$scan_config,$line,$questionnum,$error,@selected)=@_;
1.157     albertel 7049:     my $max=$$scan_config{'Qlength'};
1.274     albertel 7050: 
                   7051:     my $scmode=$$scan_config{'Qon'};
                   7052:     if ($scmode eq 'number' || $scmode eq 'letter') { $max=10; }	     
                   7053: 
1.157     albertel 7054:     my @alphabet=('A'..'Z');
1.503     raeburn  7055:     $r->print(&Apache::loncommon::start_data_table().
                   7056:               &Apache::loncommon::start_data_table_row());
                   7057:     $r->print('<td rowspan="2" class="LC_leftcol_header">'.$line.'</td>');
1.497     foxr     7058:     for (my $i=0;$i<$max+1;$i++) {
                   7059: 	$r->print("\n".'<td align="center">');
                   7060: 	if ($selected[0] eq $alphabet[$i]) { $r->print('X'); shift(@selected) }
                   7061: 	else { $r->print('&nbsp;'); }
                   7062: 	$r->print('</td>');
                   7063:     }
1.503     raeburn  7064:     $r->print(&Apache::loncommon::end_data_table_row().
                   7065:               &Apache::loncommon::start_data_table_row());
1.497     foxr     7066:     for (my $i=0;$i<$max;$i++) {
                   7067: 	$r->print("\n".
                   7068: 		  '<td><label><input type="radio" name="scantron_correct_Q_'.
                   7069: 		  $line.'" value="'.$i.'" />'.$alphabet[$i]."</label></td>");
                   7070:     }
1.503     raeburn  7071:     my $nobub_checked = ' ';
                   7072:     if ($error eq 'missingbubble') {
                   7073:         $nobub_checked = ' checked = "checked" ';
                   7074:     }
                   7075:     $r->print("\n".'<td><label><input type="radio" name="scantron_correct_Q_'.
                   7076: 	      $line.'" value="none"'.$nobub_checked.'/>'.&mt('No bubble').
                   7077:               '</label>'."\n".'<input type="hidden" name="scantron_questionnum_Q_'.
                   7078:               $line.'" value="'.$questionnum.'" /></td>');
                   7079:     $r->print(&Apache::loncommon::end_data_table_row().
                   7080:               &Apache::loncommon::end_data_table());
1.157     albertel 7081: }
                   7082: 
1.423     albertel 7083: =pod
                   7084: 
                   7085: =item num_matches
                   7086: 
1.424     albertel 7087:    Counts the number of characters that are the same between the two arguments.
                   7088: 
                   7089:  Arguments:
                   7090:    $orig - CODE from the scanline
                   7091:    $code - CODE to match against
                   7092: 
                   7093:  Returns:
                   7094:    $count - integer count of the number of same characters between the
                   7095:             two arguments
                   7096: 
1.423     albertel 7097: =cut
                   7098: 
1.194     albertel 7099: sub num_matches {
                   7100:     my ($orig,$code) = @_;
                   7101:     my @code=split(//,$code);
                   7102:     my @orig=split(//,$orig);
                   7103:     my $same=0;
                   7104:     for (my $i=0;$i<scalar(@code);$i++) {
                   7105: 	if ($code[$i] eq $orig[$i]) { $same++; }
                   7106:     }
                   7107:     return $same;
                   7108: }
                   7109: 
1.423     albertel 7110: =pod
                   7111: 
                   7112: =item scantron_get_closely_matching_CODEs
                   7113: 
1.424     albertel 7114:    Cycles through all CODEs and finds the set that has the greatest
                   7115:    number of same characters as the provided CODE
                   7116: 
                   7117:  Arguments:
                   7118:    $allcodes - hash ref returned by &get_codes()
                   7119:    $CODE     - CODE from the current scanline
                   7120: 
                   7121:  Returns:
                   7122:    2 element list
                   7123:     - first elements is number of how closely matching the best fit is 
                   7124:       (5 means best set has 5 matching characters)
                   7125:     - second element is an arrary ref containing the set of valid CODEs
                   7126:       that best fit the passed in CODE
                   7127: 
1.423     albertel 7128: =cut
                   7129: 
1.194     albertel 7130: sub scantron_get_closely_matching_CODEs {
                   7131:     my ($allcodes,$CODE)=@_;
                   7132:     my @CODEs;
                   7133:     foreach my $testcode (sort(keys(%{$allcodes}))) {
                   7134: 	push(@{$CODEs[&num_matches($CODE,$testcode)]},$testcode);
                   7135:     }
                   7136: 
                   7137:     return ($#CODEs,$CODEs[-1]);
                   7138: }
                   7139: 
1.423     albertel 7140: =pod
                   7141: 
                   7142: =item get_codes
                   7143: 
1.424     albertel 7144:    Builds a hash which has keys of all of the valid CODEs from the selected
                   7145:    set of remembered CODEs.
                   7146: 
                   7147:  Arguments:
                   7148:   $old_name - name of the set of remembered CODEs
                   7149:   $cdom     - domain of the course
                   7150:   $cnum     - internal course name
                   7151: 
                   7152:  Returns:
                   7153:   %allcodes - keys are the valid CODEs, values are all 1
                   7154: 
1.423     albertel 7155: =cut
                   7156: 
1.194     albertel 7157: sub get_codes {
1.280     foxr     7158:     my ($old_name, $cdom, $cnum) = @_;
                   7159:     if (!$old_name) {
                   7160: 	$old_name=$env{'form.scantron_CODElist'};
                   7161:     }
                   7162:     if (!$cdom) {
                   7163: 	$cdom =$env{'course.'.$env{'request.course.id'}.'.domain'};
                   7164:     }
                   7165:     if (!$cnum) {
                   7166: 	$cnum =$env{'course.'.$env{'request.course.id'}.'.num'};
                   7167:     }
1.278     albertel 7168:     my %result=&Apache::lonnet::get('CODEs',[$old_name,"type\0$old_name"],
                   7169: 				    $cdom,$cnum);
                   7170:     my %allcodes;
                   7171:     if ($result{"type\0$old_name"} eq 'number') {
                   7172: 	%allcodes=map {($_,1)} split(',',$result{$old_name});
                   7173:     } else {
                   7174: 	%allcodes=map {(&Apache::lonprintout::num_to_letters($_),1)} split(',',$result{$old_name});
                   7175:     }
1.194     albertel 7176:     return %allcodes;
                   7177: }
                   7178: 
1.423     albertel 7179: =pod
                   7180: 
                   7181: =item scantron_validate_CODE
                   7182: 
1.424     albertel 7183:    Validates all scanlines in the selected file to not have any
                   7184:    invalid or underspecified CODEs and that none of the codes are
                   7185:    duplicated if this was requested.
                   7186: 
1.423     albertel 7187: =cut
                   7188: 
1.157     albertel 7189: sub scantron_validate_CODE {
                   7190:     my ($r,$currentphase) = @_;
1.257     albertel 7191:     my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
1.186     albertel 7192:     if ($scantron_config{'CODElocation'} &&
                   7193: 	$scantron_config{'CODEstart'} &&
                   7194: 	$scantron_config{'CODElength'}) {
1.257     albertel 7195: 	if (!defined($env{'form.scantron_CODElist'})) {
1.186     albertel 7196: 	    &FIXME_blow_up()
                   7197: 	}
                   7198:     } else {
                   7199: 	return (0,$currentphase+1);
                   7200:     }
                   7201:     
                   7202:     my %usedCODEs;
                   7203: 
1.194     albertel 7204:     my %allcodes=&get_codes();
1.186     albertel 7205: 
1.447     foxr     7206:     &scantron_get_maxbubble();	# parse needs the lines per response array.
                   7207: 
1.186     albertel 7208:     my ($scanlines,$scan_data)=&scantron_getfile();
                   7209:     for (my $i=0;$i<=$scanlines->{'count'};$i++) {
1.200     albertel 7210: 	my $line=&scantron_get_line($scanlines,$scan_data,$i);
1.186     albertel 7211: 	if ($line=~/^[\s\cz]*$/) { next; }
                   7212: 	my $scan_record=&scantron_parse_scanline($line,$i,\%scantron_config,
                   7213: 						 $scan_data);
                   7214: 	my $CODE=$$scan_record{'scantron.CODE'};
                   7215: 	my $error=0;
1.224     albertel 7216: 	if (!&Apache::lonnet::validCODE($CODE)) {
                   7217: 	    &scantron_get_correction($r,$i,$scan_record,
                   7218: 				     \%scantron_config,
                   7219: 				     $line,'incorrectCODE',\%allcodes);
                   7220: 	    return(1,$currentphase);
                   7221: 	}
1.221     albertel 7222: 	if (%allcodes && !exists($allcodes{$CODE}) 
                   7223: 	    && !$$scan_record{'scantron.useCODE'}) {
1.186     albertel 7224: 	    &scantron_get_correction($r,$i,$scan_record,
                   7225: 				     \%scantron_config,
1.194     albertel 7226: 				     $line,'incorrectCODE',\%allcodes);
                   7227: 	    return(1,$currentphase);
1.186     albertel 7228: 	}
1.214     albertel 7229: 	if (exists($usedCODEs{$CODE}) 
1.257     albertel 7230: 	    && $env{'form.scantron_CODEunique'} eq 'yes'
1.192     albertel 7231: 	    && !$$scan_record{'scantron.CODE_ignore_dup'}) {
1.186     albertel 7232: 	    &scantron_get_correction($r,$i,$scan_record,
                   7233: 				     \%scantron_config,
1.194     albertel 7234: 				     $line,'duplicateCODE',$usedCODEs{$CODE});
                   7235: 	    return(1,$currentphase);
1.186     albertel 7236: 	}
1.524     raeburn  7237: 	push(@{$usedCODEs{$CODE}},$$scan_record{'scantron.PaperID'});
1.186     albertel 7238:     }
1.157     albertel 7239:     return (0,$currentphase+1);
                   7240: }
                   7241: 
1.423     albertel 7242: =pod
                   7243: 
                   7244: =item scantron_validate_doublebubble
                   7245: 
1.424     albertel 7246:    Validates all scanlines in the selected file to not have any
                   7247:    bubble lines with multiple bubbles marked.
                   7248: 
1.423     albertel 7249: =cut
                   7250: 
1.157     albertel 7251: sub scantron_validate_doublebubble {
                   7252:     my ($r,$currentphase) = @_;
                   7253:     #get student info
                   7254:     my $classlist=&Apache::loncoursedata::get_classlist();
                   7255:     my %idmap=&username_to_idmap($classlist);
                   7256: 
                   7257:     #get scantron line setup
1.257     albertel 7258:     my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
1.157     albertel 7259:     my ($scanlines,$scan_data)=&scantron_getfile();
1.447     foxr     7260:     &scantron_get_maxbubble();	# parse needs the bubble line array.
                   7261: 
1.157     albertel 7262:     for (my $i=0;$i<=$scanlines->{'count'};$i++) {
1.200     albertel 7263: 	my $line=&scantron_get_line($scanlines,$scan_data,$i);
1.157     albertel 7264: 	if ($line=~/^[\s\cz]*$/) { next; }
                   7265: 	my $scan_record=&scantron_parse_scanline($line,$i,\%scantron_config,
                   7266: 						 $scan_data);
                   7267: 	if (!defined($$scan_record{'scantron.doubleerror'})) { next; }
                   7268: 	&scantron_get_correction($r,$i,$scan_record,\%scantron_config,$line,
                   7269: 				 'doublebubble',
                   7270: 				 $$scan_record{'scantron.doubleerror'});
                   7271:     	return (1,$currentphase);
                   7272:     }
                   7273:     return (0,$currentphase+1);
                   7274: }
                   7275: 
1.423     albertel 7276: 
1.503     raeburn  7277: sub scantron_get_maxbubble {
1.257     albertel 7278:     if (defined($env{'form.scantron_maxbubble'}) &&
                   7279: 	$env{'form.scantron_maxbubble'}) {
1.447     foxr     7280: 	&restore_bubble_lines();
1.257     albertel 7281: 	return $env{'form.scantron_maxbubble'};
1.191     albertel 7282:     }
1.330     albertel 7283: 
1.447     foxr     7284:     my (undef, undef, $sequence) =
1.257     albertel 7285: 	&Apache::lonnet::decode_symb($env{'form.selectpage'});
1.330     albertel 7286: 
1.447     foxr     7287:     my $navmap=Apache::lonnavmaps::navmap->new();
1.191     albertel 7288:     my $map=$navmap->getResourceByUrl($sequence);
                   7289:     my @resources=$navmap->retrieveResources($map,\&scantron_filter,1,0);
1.330     albertel 7290: 
                   7291:     &Apache::lonxml::clear_problem_counter();
                   7292: 
1.557     raeburn  7293:     my $uname       = $env{'user.name'};
                   7294:     my $udom        = $env{'user.domain'};
1.435     foxr     7295:     my $cid         = $env{'request.course.id'};
                   7296:     my $total_lines = 0;
                   7297:     %bubble_lines_per_response = ();
1.447     foxr     7298:     %first_bubble_line         = ();
1.503     raeburn  7299:     %subdivided_bubble_lines   = ();
                   7300:     %responsetype_per_response = ();
1.554     raeburn  7301: 
1.447     foxr     7302:     my $response_number = 0;
                   7303:     my $bubble_line     = 0;
1.191     albertel 7304:     foreach my $resource (@resources) {
1.542     raeburn  7305:         my ($analysis,$parts) = &scantron_partids_tograde($resource,$cid,$uname,$udom);
                   7306:         if ((ref($analysis) eq 'HASH') && (ref($parts) eq 'ARRAY')) {
                   7307: 	    foreach my $part_id (@{$parts}) {
                   7308:                 my $lines;
                   7309: 
                   7310: 	        # TODO - make this a persistent hash not an array.
                   7311: 
                   7312:                 # optionresponse, matchresponse and rankresponse type items 
                   7313:                 # render as separate sub-questions in exam mode.
                   7314:                 if (($analysis->{$part_id.'.type'} eq 'optionresponse') ||
                   7315:                     ($analysis->{$part_id.'.type'} eq 'matchresponse') ||
                   7316:                     ($analysis->{$part_id.'.type'} eq 'rankresponse')) {
                   7317:                     my ($numbub,$numshown);
                   7318:                     if ($analysis->{$part_id.'.type'} eq 'optionresponse') {
                   7319:                         if (ref($analysis->{$part_id.'.options'}) eq 'ARRAY') {
                   7320:                             $numbub = scalar(@{$analysis->{$part_id.'.options'}});
                   7321:                         }
                   7322:                     } elsif ($analysis->{$part_id.'.type'} eq 'matchresponse') {
                   7323:                         if (ref($analysis->{$part_id.'.items'}) eq 'ARRAY') {
                   7324:                             $numbub = scalar(@{$analysis->{$part_id.'.items'}});
                   7325:                         }
                   7326:                     } elsif ($analysis->{$part_id.'.type'} eq 'rankresponse') {
                   7327:                         if (ref($analysis->{$part_id.'.foils'}) eq 'ARRAY') {
                   7328:                             $numbub = scalar(@{$analysis->{$part_id.'.foils'}});
                   7329:                         }
                   7330:                     }
                   7331:                     if (ref($analysis->{$part_id.'.shown'}) eq 'ARRAY') {
                   7332:                         $numshown = scalar(@{$analysis->{$part_id.'.shown'}});
                   7333:                     }
                   7334:                     my $bubbles_per_line = 10;
                   7335:                     my $inner_bubble_lines = int($numbub/$bubbles_per_line);
                   7336:                     if (($numbub % $bubbles_per_line) != 0) {
                   7337:                         $inner_bubble_lines++;
                   7338:                     }
                   7339:                     for (my $i=0; $i<$numshown; $i++) {
                   7340:                         $subdivided_bubble_lines{$response_number} .= 
                   7341:                             $inner_bubble_lines.',';
                   7342:                     }
                   7343:                     $subdivided_bubble_lines{$response_number} =~ s/,$//;
                   7344:                     $lines = $numshown * $inner_bubble_lines;
                   7345:                 } else {
                   7346:                     $lines = $analysis->{"$part_id.bubble_lines"};
                   7347:                 } 
                   7348: 
                   7349:                 $first_bubble_line{$response_number} = $bubble_line;
                   7350: 	        $bubble_lines_per_response{$response_number} = $lines;
                   7351:                 $responsetype_per_response{$response_number} = 
                   7352:                     $analysis->{$part_id.'.type'};
                   7353: 	        $response_number++;
                   7354: 
                   7355: 	        $bubble_line +=  $lines;
                   7356: 	        $total_lines +=  $lines;
                   7357: 	    }
                   7358:         }
                   7359:     }
1.552     raeburn  7360:     &Apache::lonnet::delenv('scantron.');
1.542     raeburn  7361: 
                   7362:     &save_bubble_lines();
                   7363:     $env{'form.scantron_maxbubble'} =
                   7364: 	$total_lines;
                   7365:     return $env{'form.scantron_maxbubble'};
                   7366: }
1.523     raeburn  7367: 
1.157     albertel 7368: sub scantron_validate_missingbubbles {
                   7369:     my ($r,$currentphase) = @_;
                   7370:     #get student info
                   7371:     my $classlist=&Apache::loncoursedata::get_classlist();
                   7372:     my %idmap=&username_to_idmap($classlist);
                   7373: 
                   7374:     #get scantron line setup
1.257     albertel 7375:     my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
1.157     albertel 7376:     my ($scanlines,$scan_data)=&scantron_getfile();
1.191     albertel 7377:     my $max_bubble=&scantron_get_maxbubble();
1.157     albertel 7378:     if (!$max_bubble) { $max_bubble=2**31; }
                   7379:     for (my $i=0;$i<=$scanlines->{'count'};$i++) {
1.200     albertel 7380: 	my $line=&scantron_get_line($scanlines,$scan_data,$i);
1.157     albertel 7381: 	if ($line=~/^[\s\cz]*$/) { next; }
                   7382: 	my $scan_record=&scantron_parse_scanline($line,$i,\%scantron_config,
                   7383: 						 $scan_data);
                   7384: 	if (!defined($$scan_record{'scantron.missingerror'})) { next; }
                   7385: 	my @to_correct;
1.470     foxr     7386: 	
                   7387: 	# Probably here's where the error is...
                   7388: 
1.157     albertel 7389: 	foreach my $missing (@{$$scan_record{'scantron.missingerror'}}) {
1.505     raeburn  7390:             my $lastbubble;
                   7391:             if ($missing =~ /^(\d+)\.(\d+)$/) {
                   7392:                my $question = $1;
                   7393:                my $subquestion = $2;
                   7394:                if (!defined($first_bubble_line{$question -1})) { next; }
                   7395:                my $first = $first_bubble_line{$question-1};
                   7396:                my @subans = split(/,/,$subdivided_bubble_lines{$question-1});
                   7397:                my $subcount = 1;
                   7398:                while ($subcount<$subquestion) {
                   7399:                    $first += $subans[$subcount-1];
                   7400:                    $subcount ++;
                   7401:                }
                   7402:                my $count = $subans[$subquestion-1];
                   7403:                $lastbubble = $first + $count;
                   7404:             } else {
                   7405:                 if (!defined($first_bubble_line{$missing - 1})) { next; }
                   7406:                 $lastbubble = $first_bubble_line{$missing - 1} + $bubble_lines_per_response{$missing - 1};
                   7407:             }
                   7408:             if ($lastbubble > $max_bubble) { next; }
1.157     albertel 7409: 	    push(@to_correct,$missing);
                   7410: 	}
                   7411: 	if (@to_correct) {
                   7412: 	    &scantron_get_correction($r,$i,$scan_record,\%scantron_config,
                   7413: 				     $line,'missingbubble',\@to_correct);
                   7414: 	    return (1,$currentphase);
                   7415: 	}
                   7416: 
                   7417:     }
                   7418:     return (0,$currentphase+1);
                   7419: }
                   7420: 
1.423     albertel 7421: 
1.82      albertel 7422: sub scantron_process_students {
1.75      albertel 7423:     my ($r) = @_;
1.513     foxr     7424: 
1.257     albertel 7425:     my (undef,undef,$sequence)=&Apache::lonnet::decode_symb($env{'form.selectpage'});
1.324     albertel 7426:     my ($symb)=&get_symb($r);
1.513     foxr     7427:     if (!$symb) {
                   7428: 	return '';
                   7429:     }
1.324     albertel 7430:     my $default_form_data=&defaultFormData($symb);
1.82      albertel 7431: 
1.257     albertel 7432:     my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
1.157     albertel 7433:     my ($scanlines,$scan_data)=&scantron_getfile();
1.82      albertel 7434:     my $classlist=&Apache::loncoursedata::get_classlist();
                   7435:     my %idmap=&username_to_idmap($classlist);
1.132     bowersj2 7436:     my $navmap=Apache::lonnavmaps::navmap->new();
1.83      albertel 7437:     my $map=$navmap->getResourceByUrl($sequence);
                   7438:     my @resources=$navmap->retrieveResources($map,\&scantron_filter,1,0);
1.557     raeburn  7439:     my (%grader_partids_by_symb,%grader_randomlists_by_symb);
                   7440:     &graders_resources_pass(\@resources,\%grader_partids_by_symb,
                   7441:                             \%grader_randomlists_by_symb);
                   7442:     foreach my $resource (@resources) {
                   7443:         my $ressymb = $resource->symb();
                   7444:         my ($analysis,$parts) =
                   7445:             &scantron_partids_tograde($resource,$env{'request.course.id'},
                   7446:                                       $env{'user.name'},$env{'user.domain'},1);
                   7447:         $grader_partids_by_symb{$ressymb} = $parts;
                   7448:         if (ref($analysis) eq 'HASH') {
                   7449:             if (ref($analysis->{'parts_withrandomlist'}) eq 'ARRAY') {
                   7450:                 $grader_randomlists_by_symb{$ressymb} = 
                   7451:                     $analysis->{'parts_withrandomlist'};
                   7452:             }
                   7453:         }
                   7454:     }
                   7455: 
1.554     raeburn  7456:     my ($uname,$udom);
1.82      albertel 7457:     my $result= <<SCANTRONFORM;
1.81      albertel 7458: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="scantronupload">
                   7459:   <input type="hidden" name="command" value="scantron_configphase" />
                   7460:   $default_form_data
                   7461: SCANTRONFORM
1.82      albertel 7462:     $r->print($result);
                   7463: 
                   7464:     my @delayqueue;
1.542     raeburn  7465:     my (%completedstudents,%scandata);
1.140     albertel 7466:     
1.520     www      7467:     my $lock=&Apache::lonnet::set_lock(&mt('Grading bubblesheet exam'));
1.200     albertel 7468:     my $count=&get_todo_count($scanlines,$scan_data);
1.157     albertel 7469:     my %prog_state=&Apache::lonhtmlcommon::Create_PrgWin($r,'Scantron Status',
1.200     albertel 7470:  				    'Scantron Progress',$count,
1.195     albertel 7471: 				    'inline',undef,'scantronupload');
1.140     albertel 7472:     &Apache::lonhtmlcommon::Update_PrgWin($r,\%prog_state,
                   7473: 					  'Processing first student');
1.542     raeburn  7474:     $r->print('<br />');
1.140     albertel 7475:     my $start=&Time::HiRes::time();
1.158     albertel 7476:     my $i=-1;
1.542     raeburn  7477:     my $started;
1.447     foxr     7478: 
                   7479:     &scantron_get_maxbubble();	# Need the bubble lines array to parse.
1.513     foxr     7480: 
                   7481:     # If an ssi failed in scantron_get_maxbubble, put an error message out to
                   7482:     # the user and return.
                   7483: 
                   7484:     if ($ssi_error) {
                   7485: 	$r->print("</form>");
                   7486: 	&ssi_print_error($r);
                   7487: 	$r->print(&show_grading_menu_form($symb));
1.520     www      7488:         &Apache::lonnet::remove_lock($lock);
1.513     foxr     7489: 	return '';		# Dunno why the other returns return '' rather than just returning.
                   7490:     }
1.447     foxr     7491: 
1.542     raeburn  7492:     my %lettdig = &letter_to_digits();
                   7493:     my $numletts = scalar(keys(%lettdig));
                   7494: 
1.157     albertel 7495:     while ($i<$scanlines->{'count'}) {
                   7496:  	($uname,$udom)=('','');
                   7497:  	$i++;
1.200     albertel 7498:  	my $line=&scantron_get_line($scanlines,$scan_data,$i);
1.157     albertel 7499:  	if ($line=~/^[\s\cz]*$/) { next; }
1.200     albertel 7500: 	if ($started) {
                   7501: 	    &Apache::lonhtmlcommon::Increment_PrgWin($r,\%prog_state,
                   7502: 						     'last student');
                   7503: 	}
                   7504: 	$started=1;
1.157     albertel 7505:  	my $scan_record=&scantron_parse_scanline($line,$i,\%scantron_config,
                   7506:  						 $scan_data);
                   7507:  	unless ($uname=&scantron_find_student($scan_record,$scan_data,
                   7508:  					      \%idmap,$i)) {
                   7509:   	    &scantron_add_delay(\@delayqueue,$line,
                   7510:  				'Unable to find a student that matches',1);
                   7511:  	    next;
                   7512:   	}
                   7513:  	if (exists $completedstudents{$uname}) {
                   7514:  	    &scantron_add_delay(\@delayqueue,$line,
                   7515:  				'Student '.$uname.' has multiple sheets',2);
                   7516:  	    next;
                   7517:  	}
                   7518:   	($uname,$udom)=split(/:/,$uname);
1.330     albertel 7519: 
1.554     raeburn  7520:         my %partids_by_symb;
                   7521:         foreach my $resource (@resources) {
                   7522:             my $ressymb = $resource->symb();
1.557     raeburn  7523:             if ((exists($grader_randomlists_by_symb{$ressymb})) ||
                   7524:                 (ref($grader_partids_by_symb{$ressymb}) ne 'ARRAY')) {
                   7525:                 my ($analysis,$parts) =
                   7526:                     &scantron_partids_tograde($resource,$env{'request.course.id'},$uname,$udom);
                   7527:                 $partids_by_symb{$ressymb} = $parts;
                   7528:             } else {
                   7529:                 $partids_by_symb{$ressymb} = $grader_partids_by_symb{$ressymb};
                   7530:             }
1.554     raeburn  7531:         }
                   7532: 
1.330     albertel 7533: 	&Apache::lonxml::clear_problem_counter();
1.514     raeburn  7534:   	&Apache::lonnet::appenv($scan_record);
1.376     albertel 7535: 
                   7536: 	if (&scantron_clear_skip($scanlines,$scan_data,$i)) {
                   7537: 	    &scantron_putfile($scanlines,$scan_data);
                   7538: 	}
1.161     albertel 7539: 	
1.542     raeburn  7540:         my $scancode;
                   7541:         if ((exists($scan_record->{'scantron.CODE'})) &&
                   7542:             (&Apache::lonnet::validCODE($scan_record->{'scantron.CODE'}))) {
                   7543:             $scancode = $scan_record->{'scantron.CODE'};
                   7544:         } else {
                   7545:             $scancode = '';
                   7546:         }
                   7547: 
                   7548:         if (&grade_student_bubbles($r,$uname,$udom,$scan_record,$scancode,
1.554     raeburn  7549:                                    \@resources,\%partids_by_symb) eq 'ssi_error') {
1.542     raeburn  7550:             $ssi_error = 0; # So end of handler error message does not trigger.
                   7551:             $r->print("</form>");
                   7552:             &ssi_print_error($r);
                   7553:             $r->print(&show_grading_menu_form($symb));
                   7554:             &Apache::lonnet::remove_lock($lock);
                   7555:             return '';      # Why return ''?  Beats me.
                   7556:         }
1.513     foxr     7557: 
1.140     albertel 7558: 	$completedstudents{$uname}={'line'=>$line};
1.542     raeburn  7559:         if ($env{'form.verifyrecord'}) {
                   7560:             my $lastpos = $env{'form.scantron_maxbubble'}*$scantron_config{'Qlength'};
                   7561:             my $studentdata = substr($line,$scantron_config{'Qstart'}-1,$lastpos);
                   7562:             chomp($studentdata);
                   7563:             $studentdata =~ s/\r$//;
                   7564:             my $studentrecord = '';
                   7565:             my $counter = -1;
                   7566:             foreach my $resource (@resources) {
1.554     raeburn  7567:                 my $ressymb = $resource->symb();
1.542     raeburn  7568:                 ($counter,my $recording) =
                   7569:                     &verify_scantron_grading($resource,$udom,$uname,$env{'request.course.id'},
1.554     raeburn  7570:                                              $counter,$studentdata,$partids_by_symb{$ressymb},
1.542     raeburn  7571:                                              \%scantron_config,\%lettdig,$numletts);
                   7572:                 $studentrecord .= $recording;
                   7573:             }
                   7574:             if ($studentrecord ne $studentdata) {
1.554     raeburn  7575:                 &Apache::lonxml::clear_problem_counter();
                   7576:                 if (&grade_student_bubbles($r,$uname,$udom,$scan_record,$scancode,
                   7577:                                            \@resources,\%partids_by_symb) eq 'ssi_error') {
                   7578:                     $ssi_error = 0; # So end of handler error message does not trigger.
                   7579:                     $r->print("</form>");
                   7580:                     &ssi_print_error($r);
                   7581:                     $r->print(&show_grading_menu_form($symb));
                   7582:                     &Apache::lonnet::remove_lock($lock);
                   7583:                     delete($completedstudents{$uname});
                   7584:                     return '';
                   7585:                 }
1.542     raeburn  7586:                 $counter = -1;
                   7587:                 $studentrecord = '';
                   7588:                 foreach my $resource (@resources) {
1.554     raeburn  7589:                     my $ressymb = $resource->symb();
1.542     raeburn  7590:                     ($counter,my $recording) =
                   7591:                         &verify_scantron_grading($resource,$udom,$uname,$env{'request.course.id'},
1.554     raeburn  7592:                                                  $counter,$studentdata,$partids_by_symb{$ressymb},
1.542     raeburn  7593:                                                  \%scantron_config,\%lettdig,$numletts);
                   7594:                     $studentrecord .= $recording;
                   7595:                 }
                   7596:                 if ($studentrecord ne $studentdata) {
                   7597:                     $r->print('<p><span class="LC_error">');
                   7598:                     if ($scancode eq '') {
                   7599:                         $r->print(&mt('Mismatch grading bubble sheet for user: [_1] with ID: [_2].',
                   7600:                                   $uname.':'.$udom,$scan_record->{'scantron.ID'}));
                   7601:                     } else {
                   7602:                         $r->print(&mt('Mismatch grading bubble sheet for user: [_1] with ID: [_2] and CODE: [_3].',
                   7603:                                   $uname.':'.$udom,$scan_record->{'scantron.ID'},$scancode));
                   7604:                     }
                   7605:                     $r->print('</span><br />'.&Apache::loncommon::start_data_table()."\n".
                   7606:                               &Apache::loncommon::start_data_table_header_row()."\n".
                   7607:                               '<th>'.&mt('Source').'</th><th>'.&mt('Bubbled responses').'</th>'.
                   7608:                               &Apache::loncommon::end_data_table_header_row()."\n".
                   7609:                               &Apache::loncommon::start_data_table_row().
                   7610:                               '<td>'.&mt('Bubble Sheet').'</td>'.
                   7611:                               '<td><span class="LC_nobreak">'.$studentdata.'</span></td>'.
                   7612:                               &Apache::loncommon::end_data_table_row().
                   7613:                               &Apache::loncommon::start_data_table_row().
                   7614:                               '<td>Stored submissions</td>'.
                   7615:                               '<td><span class="LC_nobreak">'.$studentrecord.'</span></td>'."\n".
                   7616:                               &Apache::loncommon::end_data_table_row().
                   7617:                               &Apache::loncommon::end_data_table().'</p>');
                   7618:                 } else {
                   7619:                     $r->print('<br /><span class="LC_warning">'.
                   7620:                              &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 />'.
                   7621:                              &mt("As a consequence, this user's submission history records two tries.").
                   7622:                                  '</span><br />');
                   7623:                 }
                   7624:             }
                   7625:         }
1.543     raeburn  7626:         if (&Apache::loncommon::connection_aborted($r)) { last; }
1.140     albertel 7627:     } continue {
1.330     albertel 7628: 	&Apache::lonxml::clear_problem_counter();
1.552     raeburn  7629: 	&Apache::lonnet::delenv('scantron.');
1.82      albertel 7630:     }
1.140     albertel 7631:     &Apache::lonhtmlcommon::Close_PrgWin($r,\%prog_state);
1.520     www      7632:     &Apache::lonnet::remove_lock($lock);
1.172     albertel 7633: #    my $lasttime = &Time::HiRes::time()-$start;
                   7634: #    $r->print("<p>took $lasttime</p>");
1.140     albertel 7635: 
1.200     albertel 7636:     $r->print("</form>");
1.324     albertel 7637:     $r->print(&show_grading_menu_form($symb));
1.157     albertel 7638:     return '';
1.75      albertel 7639: }
1.157     albertel 7640: 
1.557     raeburn  7641: sub graders_resources_pass {
                   7642:     my ($resources,$grader_partids_by_symb,$grader_randomlists_by_symb) = @_;
                   7643:     if ((ref($resources) eq 'ARRAY') && (ref($grader_partids_by_symb)) && 
                   7644:         (ref($grader_randomlists_by_symb) eq 'HASH')) {
                   7645:         foreach my $resource (@{$resources}) {
                   7646:             my $ressymb = $resource->symb();
                   7647:             my ($analysis,$parts) =
                   7648:                 &scantron_partids_tograde($resource,$env{'request.course.id'},
                   7649:                                           $env{'user.name'},$env{'user.domain'},1);
                   7650:             $grader_partids_by_symb->{$ressymb} = $parts;
                   7651:             if (ref($analysis) eq 'HASH') {
                   7652:                 if (ref($analysis->{'parts_withrandomlist'}) eq 'ARRAY') {
                   7653:                     $grader_randomlists_by_symb->{$ressymb} =
                   7654:                         $analysis->{'parts_withrandomlist'};
                   7655:                 }
                   7656:             }
                   7657:         }
                   7658:     }
                   7659:     return;
                   7660: }
                   7661: 
1.542     raeburn  7662: sub grade_student_bubbles {
1.554     raeburn  7663:     my ($r,$uname,$udom,$scan_record,$scancode,$resources,$parts) = @_;
                   7664:     if (ref($resources) eq 'ARRAY') {
                   7665:         my $count = 0;
                   7666:         foreach my $resource (@{$resources}) {
                   7667:             my $ressymb = $resource->symb();
                   7668:             my %form = ('submitted'      => 'scantron',
                   7669:                         'grade_target'   => 'grade',
                   7670:                         'grade_username' => $uname,
                   7671:                         'grade_domain'   => $udom,
                   7672:                         'grade_courseid' => $env{'request.course.id'},
                   7673:                         'grade_symb'     => $ressymb,
                   7674:                         'CODE'           => $scancode
                   7675:                        );
                   7676:             if (ref($parts) eq 'HASH') {
                   7677:                 if (ref($parts->{$ressymb}) eq 'ARRAY') {
                   7678:                     foreach my $part (@{$parts->{$ressymb}}) {
                   7679:                         $form{'scantron_questnum_start.'.$part} =
                   7680:                             1+$env{'form.scantron.first_bubble_line.'.$count};
                   7681:                         $count++;
                   7682:                     }
                   7683:                 }
                   7684:             }
                   7685:             my $result=&ssi_with_retries($resource->src(),$ssi_retries,%form);
                   7686:             return 'ssi_error' if ($ssi_error);
                   7687:             last if (&Apache::loncommon::connection_aborted($r));
                   7688:         }
1.542     raeburn  7689:     }
                   7690:     return;
                   7691: }
                   7692: 
1.157     albertel 7693: sub scantron_upload_scantron_data {
                   7694:     my ($r)=@_;
1.257     albertel 7695:     $r->print(&Apache::loncommon::coursebrowser_javascript($env{'request.role.domain'}));
1.157     albertel 7696:     my $select_link=&Apache::loncommon::selectcourse_link('rules','courseid',
1.181     albertel 7697: 							  'domainid',
                   7698: 							  'coursename');
1.257     albertel 7699:     my $domsel=&Apache::loncommon::select_dom_form($env{'request.role.domain'},
1.157     albertel 7700: 						   'domainid');
1.324     albertel 7701:     my $default_form_data=&defaultFormData(&get_symb($r,1));
1.492     albertel 7702:     $r->print('
1.157     albertel 7703: <script type="text/javascript" language="javascript">
                   7704:     function checkUpload(formname) {
                   7705: 	if (formname.upfile.value == "") {
1.539     riegler  7706: 	    alert("'.&mt('Please use the browse button to select a file from your local directory.').'");
1.157     albertel 7707: 	    return false;
                   7708: 	}
                   7709: 	formname.submit();
                   7710:     }
                   7711: </script>
                   7712: 
1.492     albertel 7713: <form enctype="multipart/form-data" action="/adm/grades" name="rules" method="post">
                   7714: '.$default_form_data.'
1.181     albertel 7715: <table>
1.492     albertel 7716: <tr><td>'.$select_link.'                             </td></tr>
                   7717: <tr><td>'.&mt('Course ID:').'     </td>
                   7718:     <td><input name="courseid"   type="text" />      </td></tr>
                   7719: <tr><td>'.&mt('Course Name:').'   </td>
                   7720:     <td><input name="coursename" type="text" />      </td></tr>
                   7721: <tr><td>'.&mt('Domain:').'        </td>
                   7722:     <td>'.$domsel.'                                  </td></tr>
                   7723: <tr><td>'.&mt('File to upload:').'</td>
                   7724:     <td><input type="file" name="upfile" size="50" /></td></tr>
1.181     albertel 7725: </table>
1.492     albertel 7726: <input name="command" value="scantronupload_save" type="hidden" />
                   7727: <input type="button" onClick="javascript:checkUpload(this.form);" value="'.&mt('Upload Scantron Data').'" />
1.157     albertel 7728: </form>
1.492     albertel 7729: ');
1.157     albertel 7730:     return '';
                   7731: }
                   7732: 
1.423     albertel 7733: 
1.157     albertel 7734: sub scantron_upload_scantron_data_save {
                   7735:     my($r)=@_;
1.324     albertel 7736:     my ($symb)=&get_symb($r,1);
1.182     albertel 7737:     my $doanotherupload=
                   7738: 	'<br /><form action="/adm/grades" method="post">'."\n".
                   7739: 	'<input type="hidden" name="command" value="scantronupload" />'."\n".
1.492     albertel 7740: 	'<input type="submit" name="submit" value="'.&mt('Do Another Upload').'" />'."\n".
1.182     albertel 7741: 	'</form>'."\n";
1.257     albertel 7742:     if (!&Apache::lonnet::allowed('usc',$env{'form.domainid'}) &&
1.162     albertel 7743: 	!&Apache::lonnet::allowed('usc',
1.257     albertel 7744: 			    $env{'form.domainid'}.'_'.$env{'form.courseid'})) {
1.492     albertel 7745: 	$r->print(&mt("You are not allowed to upload Scantron data to the requested course.")."<br />");
1.182     albertel 7746: 	if ($symb) {
1.324     albertel 7747: 	    $r->print(&show_grading_menu_form($symb));
1.182     albertel 7748: 	} else {
                   7749: 	    $r->print($doanotherupload);
                   7750: 	}
1.162     albertel 7751: 	return '';
                   7752:     }
1.257     albertel 7753:     my %coursedata=&Apache::lonnet::coursedescription($env{'form.domainid'}.'_'.$env{'form.courseid'});
1.492     albertel 7754:     $r->print(&mt("Doing upload to [_1]",$coursedata{'description'})." <br />");
1.257     albertel 7755:     my $fname=$env{'form.upfile.filename'};
1.157     albertel 7756:     #FIXME
                   7757:     #copied from lonnet::userfileupload()
                   7758:     #make that function able to target a specified course
                   7759:     # Replace Windows backslashes by forward slashes
                   7760:     $fname=~s/\\/\//g;
                   7761:     # Get rid of everything but the actual filename
                   7762:     $fname=~s/^.*\/([^\/]+)$/$1/;
                   7763:     # Replace spaces by underscores
                   7764:     $fname=~s/\s+/\_/g;
                   7765:     # Replace all other weird characters by nothing
                   7766:     $fname=~s/[^\w\.\-]//g;
                   7767:     # See if there is anything left
                   7768:     unless ($fname) { return 'error: no uploaded file'; }
1.209     ng       7769:     my $uploadedfile=$fname;
1.157     albertel 7770:     $fname='scantron_orig_'.$fname;
1.257     albertel 7771:     if (length($env{'form.upfile'}) < 2) {
1.492     albertel 7772: 	$r->print(&mt("<span class=\"LC_error\">Error:</span> The file you attempted to upload, [_1]  contained no information. Please check that you entered the correct filename.",'<span class="LC_filename">'.&HTML::Entities::encode($env{'form.upfile.filename'},'<>&"')."</span>"));
1.183     albertel 7773:     } else {
1.275     albertel 7774: 	my $result=&Apache::lonnet::finishuserfileupload($env{'form.courseid'},$env{'form.domainid'},'upfile',$fname);
1.210     albertel 7775: 	if ($result =~ m|^/uploaded/|) {
1.492     albertel 7776: 	    $r->print(&mt("<span class=\"LC_success\">Success:</span> Successfully uploaded [_1] bytes of data into location [_2]",
                   7777: 			  (length($env{'form.upfile'})-1),
                   7778: 			  '<span class="LC_filename">'.$result."</span>"));
1.210     albertel 7779: 	} else {
1.492     albertel 7780: 	    $r->print(&mt("<span class=\"LC_error\">Error:</span> An error ([_1]) occurred when attempting to upload the file, [_2]",
                   7781: 			  $result,
                   7782: 			  '<span class="LC_filename">'.&HTML::Entities::encode($env{'form.upfile.filename'},'<>&"')."</span>"));
                   7783: 
1.183     albertel 7784: 	}
                   7785:     }
1.174     albertel 7786:     if ($symb) {
1.209     ng       7787: 	$r->print(&scantron_selectphase($r,$uploadedfile));
1.174     albertel 7788:     } else {
1.182     albertel 7789: 	$r->print($doanotherupload);
1.174     albertel 7790:     }
1.157     albertel 7791:     return '';
                   7792: }
                   7793: 
1.202     albertel 7794: sub valid_file {
                   7795:     my ($requested_file)=@_;
                   7796:     foreach my $filename (sort(&scantron_filenames())) {
                   7797: 	if ($requested_file eq $filename) { return 1; }
                   7798:     }
                   7799:     return 0;
                   7800: }
                   7801: 
                   7802: sub scantron_download_scantron_data {
                   7803:     my ($r)=@_;
1.324     albertel 7804:     my $default_form_data=&defaultFormData(&get_symb($r,1));
1.257     albertel 7805:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   7806:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
                   7807:     my $file=$env{'form.scantron_selectfile'};
1.202     albertel 7808:     if (! &valid_file($file)) {
1.492     albertel 7809: 	$r->print('
1.202     albertel 7810: 	<p>
1.492     albertel 7811: 	    '.&mt('The requested file name was invalid.').'
1.202     albertel 7812:         </p>
1.492     albertel 7813: ');
1.324     albertel 7814: 	$r->print(&show_grading_menu_form(&get_symb($r,1)));
1.202     albertel 7815: 	return;
                   7816:     }
                   7817:     my $orig='/uploaded/'.$cdom.'/'.$cname.'/scantron_orig_'.$file;
                   7818:     my $corrected='/uploaded/'.$cdom.'/'.$cname.'/scantron_corrected_'.$file;
                   7819:     my $skipped='/uploaded/'.$cdom.'/'.$cname.'/scantron_skipped_'.$file;
                   7820:     &Apache::lonnet::allowuploaded('/adm/grades',$orig);
                   7821:     &Apache::lonnet::allowuploaded('/adm/grades',$corrected);
                   7822:     &Apache::lonnet::allowuploaded('/adm/grades',$skipped);
1.492     albertel 7823:     $r->print('
1.202     albertel 7824:     <p>
1.492     albertel 7825: 	'.&mt('[_1]Original[_2] file as uploaded by the scantron office.',
                   7826: 	      '<a href="'.$orig.'">','</a>').'
1.202     albertel 7827:     </p>
                   7828:     <p>
1.492     albertel 7829: 	'.&mt('[_1]Corrections[_2], a file of corrected records that were used in grading.',
                   7830: 	      '<a href="'.$corrected.'">','</a>').'
1.202     albertel 7831:     </p>
                   7832:     <p>
1.492     albertel 7833: 	'.&mt('[_1]Skipped[_2], a file of records that were skipped.',
                   7834: 	      '<a href="'.$skipped.'">','</a>').'
1.202     albertel 7835:     </p>
1.492     albertel 7836: ');
1.324     albertel 7837:     $r->print(&show_grading_menu_form(&get_symb($r,1)));
1.202     albertel 7838:     return '';
                   7839: }
1.157     albertel 7840: 
1.523     raeburn  7841: sub checkscantron_results {
                   7842:     my ($r) = @_;
                   7843:     my ($symb)=&get_symb($r);
                   7844:     if (!$symb) {return '';}
                   7845:     my $grading_menu_button=&show_grading_menu_form($symb);
                   7846:     my $cid = $env{'request.course.id'};
1.542     raeburn  7847:     my %lettdig = &letter_to_digits();
1.523     raeburn  7848:     my $numletts = scalar(keys(%lettdig));
                   7849:     my $cnum = $env{'course.'.$cid.'.num'};
                   7850:     my $cdom = $env{'course.'.$cid.'.domain'};
                   7851:     my (undef, undef, $sequence) = &Apache::lonnet::decode_symb($env{'form.selectpage'});
                   7852:     my %record;
                   7853:     my %scantron_config =
                   7854:         &Apache::grades::get_scantron_config($env{'form.scantron_format'});
                   7855:     my ($scanlines,$scan_data)=&Apache::grades::scantron_getfile();
                   7856:     my $classlist=&Apache::loncoursedata::get_classlist();
                   7857:     my %idmap=&Apache::grades::username_to_idmap($classlist);
                   7858:     my $navmap=Apache::lonnavmaps::navmap->new();
                   7859:     my $map=$navmap->getResourceByUrl($sequence);
1.557     raeburn  7860:     my @resources=$navmap->retrieveResources($map,\&scantron_filter,1,0);
                   7861:     my (%grader_partids_by_symb,%grader_randomlists_by_symb);
                   7862:     &graders_resources_pass(\@resources,\%grader_partids_by_symb,                             \%grader_randomlists_by_symb);
                   7863: 
1.554     raeburn  7864:     my ($uname,$udom);
1.523     raeburn  7865:     my (%scandata,%lastname,%bylast);
                   7866:     $r->print('
                   7867: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="checkscantron">'."\n");
                   7868: 
                   7869:     my @delayqueue;
                   7870:     my %completedstudents;
                   7871: 
                   7872:     my $count=&Apache::grades::get_todo_count($scanlines,$scan_data);
                   7873:     my %prog_state=&Apache::lonhtmlcommon::Create_PrgWin($r,'Scantron/Submissions Comparison Status',
                   7874:                                     'Progress of Scantron Data/Submission Records Comparison',$count,
                   7875:                                     'inline',undef,'checkscantron');
1.546     raeburn  7876:     my ($username,$domain,$started);
1.523     raeburn  7877: 
1.557     raeburn  7878:     &scantron_get_maxbubble();  # Need the bubble lines array to parse.
1.523     raeburn  7879: 
                   7880:     &Apache::lonhtmlcommon::Update_PrgWin($r,\%prog_state,
                   7881:                                           'Processing first student');
                   7882:     my $start=&Time::HiRes::time();
                   7883:     my $i=-1;
                   7884: 
                   7885:     while ($i<$scanlines->{'count'}) {
                   7886:         ($username,$domain,$uname)=('','','');
                   7887:         $i++;
                   7888:         my $line=&Apache::grades::scantron_get_line($scanlines,$scan_data,$i);
                   7889:         if ($line=~/^[\s\cz]*$/) { next; }
                   7890:         if ($started) {
                   7891:             &Apache::lonhtmlcommon::Increment_PrgWin($r,\%prog_state,
                   7892:                                                      'last student');
                   7893:         }
                   7894:         $started=1;
                   7895:         my $scan_record=
                   7896:             &Apache::grades::scantron_parse_scanline($line,$i,\%scantron_config,
                   7897:                                                      $scan_data);
                   7898:         unless ($uname=&Apache::grades::scantron_find_student($scan_record,$scan_data,
                   7899:                                                               \%idmap,$i)) {
                   7900:             &Apache::grades::scantron_add_delay(\@delayqueue,$line,
                   7901:                                 'Unable to find a student that matches',1);
                   7902:             next;
                   7903:         }
                   7904:         if (exists $completedstudents{$uname}) {
                   7905:             &Apache::grades::scantron_add_delay(\@delayqueue,$line,
                   7906:                                 'Student '.$uname.' has multiple sheets',2);
                   7907:             next;
                   7908:         }
                   7909:         my $pid = $scan_record->{'scantron.ID'};
                   7910:         $lastname{$pid} = $scan_record->{'scantron.LastName'};
                   7911:         push(@{$bylast{$lastname{$pid}}},$pid);
                   7912:         my $lastpos = $env{'form.scantron_maxbubble'}*$scantron_config{'Qlength'};
                   7913:         $scandata{$pid} = substr($line,$scantron_config{'Qstart'}-1,$lastpos);
                   7914:         chomp($scandata{$pid});
                   7915:         $scandata{$pid} =~ s/\r$//;
                   7916:         ($username,$domain)=split(/:/,$uname);
                   7917:         my $counter = -1;
                   7918:         foreach my $resource (@resources) {
1.557     raeburn  7919:             my $parts;
1.554     raeburn  7920:             my $ressymb = $resource->symb();
1.557     raeburn  7921:             if ((exists($grader_randomlists_by_symb{$ressymb})) ||
                   7922:                 (ref($grader_partids_by_symb{$ressymb}) ne 'ARRAY')) {
                   7923:                 (my $analysis,$parts) =
                   7924:                     &scantron_partids_tograde($resource,$env{'request.course.id'},$username,$domain);
                   7925:             } else {
                   7926:                 $parts = $grader_partids_by_symb{$ressymb};
                   7927:             }
1.542     raeburn  7928:             ($counter,my $recording) =
                   7929:                 &verify_scantron_grading($resource,$domain,$username,$cid,$counter,
1.554     raeburn  7930:                                          $scandata{$pid},$parts,
1.542     raeburn  7931:                                          \%scantron_config,\%lettdig,$numletts);
                   7932:             $record{$pid} .= $recording;
1.523     raeburn  7933:         }
                   7934:     }
                   7935:     &Apache::lonhtmlcommon::Close_PrgWin($r,\%prog_state);
                   7936:     $r->print('<br />');
                   7937:     my ($okstudents,$badstudents,$numstudents,$passed,$failed);
                   7938:     $passed = 0;
                   7939:     $failed = 0;
                   7940:     $numstudents = 0;
                   7941:     foreach my $last (sort(keys(%bylast))) {
                   7942:         if (ref($bylast{$last}) eq 'ARRAY') {
                   7943:             foreach my $pid (sort(@{$bylast{$last}})) {
                   7944:                 my $showscandata = $scandata{$pid};
                   7945:                 my $showrecord = $record{$pid};
                   7946:                 $showscandata =~ s/\s/&nbsp;/g;
                   7947:                 $showrecord =~ s/\s/&nbsp;/g;
                   7948:                 if ($scandata{$pid} eq $record{$pid}) {
                   7949:                     my $css_class = ($passed % 2)?'LC_odd_row':'LC_even_row';
                   7950:                     $okstudents .= '<tr class="'.$css_class.'">'.
                   7951: '<td>'.&mt('Scantron').'</td><td>'.$showscandata.'</td><td rowspan="2">'.$last.'</td><td rowspan="2">'.$pid.'</td>'."\n".
                   7952: '</tr>'."\n".
                   7953: '<tr class="'.$css_class.'">'."\n".
                   7954: '<td>Submissions</td><td>'.$showrecord.'</td></tr>'."\n";
                   7955:                     $passed ++;
                   7956:                 } else {
                   7957:                     my $css_class = ($failed % 2)?'LC_odd_row':'LC_even_row';
                   7958:                     $badstudents .= '<tr class="'.$css_class.'"><td>'.&mt('Scantron').'</td><td><span class="LC_nobreak">'.$scandata{$pid}.'</span></td><td rowspan="2">'.$last.'</td><td rowspan="2">'.$pid.'</td>'."\n".
                   7959: '</tr>'."\n".
                   7960: '<tr class="'.$css_class.'">'."\n".
                   7961: '<td>Submissions</td><td><span class="LC_nobreak">'.$record{$pid}.'</span></td>'."\n".
                   7962: '</tr>'."\n";
                   7963:                     $failed ++;
                   7964:                 }
                   7965:                 $numstudents ++;
                   7966:             }
                   7967:         }
                   7968:     }
                   7969:     $r->print('<p>'.&mt('Comparison of scantron 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>');
                   7970:     $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>');
                   7971:     if ($passed) {
                   7972:         $r->print(&mt('Students with exact correspondence between scantron data and submissions are as follows:').'<br /><br />');
                   7973:         $r->print(&Apache::loncommon::start_data_table()."\n".
                   7974:                  &Apache::loncommon::start_data_table_header_row()."\n".
                   7975:                  '<th>'.&mt('Source').'</th><th>'.&mt('Bubble records').'</th><th>'.&mt('Name').'</th><th>'.&mt('ID').'</th>'.
                   7976:                  &Apache::loncommon::end_data_table_header_row()."\n".
                   7977:                  $okstudents."\n".
                   7978:                  &Apache::loncommon::end_data_table().'<br />');
                   7979:     }
                   7980:     if ($failed) {
                   7981:         $r->print(&mt('Students with differences between scantron data and submissions are as follows:').'<br /><br />');
                   7982:         $r->print(&Apache::loncommon::start_data_table()."\n".
                   7983:                  &Apache::loncommon::start_data_table_header_row()."\n".
                   7984:                  '<th>'.&mt('Source').'</th><th>'.&mt('Bubble records').'</th><th>'.&mt('Name').'</th><th>'.&mt('ID').'</th>'.
                   7985:                  &Apache::loncommon::end_data_table_header_row()."\n".
                   7986:                  $badstudents."\n".
                   7987:                  &Apache::loncommon::end_data_table()).'<br />'.
                   7988:                  &mt('Differences can occur if submissions were modified using manual grading after a scantron grading pass.').'<br />'.&mt('If unexpected discrepancies were detected, it is recommended that you inspect the original scantron sheets.');  
                   7989:     }
                   7990:     $r->print('</form><br />'.$grading_menu_button);
                   7991:     return;
                   7992: }
                   7993: 
1.542     raeburn  7994: sub verify_scantron_grading {
1.554     raeburn  7995:     my ($resource,$domain,$username,$cid,$counter,$scandata,$partids,
1.542     raeburn  7996:         $scantron_config,$lettdig,$numletts) = @_;
                   7997:     my ($record,%expected,%startpos);
                   7998:     return ($counter,$record) if (!ref($resource));
                   7999:     return ($counter,$record) if (!$resource->is_problem());
                   8000:     my $symb = $resource->symb();
1.554     raeburn  8001:     return ($counter,$record) if (ref($partids) ne 'ARRAY');
                   8002:     foreach my $part_id (@{$partids}) {
1.542     raeburn  8003:         $counter ++;
                   8004:         $expected{$part_id} = 0;
                   8005:         if ($env{"form.scantron.sub_bubblelines.$counter"}) {
                   8006:             my @sub_lines = split(/,/,$env{"form.scantron.sub_bubblelines.$counter"});
                   8007:             foreach my $item (@sub_lines) {
                   8008:                 $expected{$part_id} += $item;
                   8009:             }
                   8010:         } else {
                   8011:             $expected{$part_id} = $env{"form.scantron.bubblelines.$counter"};
                   8012:         }
                   8013:         $startpos{$part_id} = $env{"form.scantron.first_bubble_line.$counter"};
                   8014:     }
                   8015:     if ($symb) {
                   8016:         my %recorded;
                   8017:         my (%returnhash) = &Apache::lonnet::restore($symb,$cid,$domain,$username);
                   8018:         if ($returnhash{'version'}) {
                   8019:             my %lasthash=();
                   8020:             my $version;
                   8021:             for ($version=1;$version<=$returnhash{'version'};$version++) {
                   8022:                 foreach my $key (sort(split(/\:/,$returnhash{$version.':keys'}))) {
                   8023:                     $lasthash{$key}=$returnhash{$version.':'.$key};
                   8024:                 }
                   8025:             }
                   8026:             foreach my $key (keys(%lasthash)) {
                   8027:                 if ($key =~ /\.scantron$/) {
                   8028:                     my $value = &unescape($lasthash{$key});
                   8029:                     my ($part_id) = ($key =~ /^resource\.(.+)\.scantron$/);
                   8030:                     if ($value eq '') {
                   8031:                         for (my $i=0; $i<$expected{$part_id}; $i++) {
                   8032:                             for (my $j=0; $j<$scantron_config->{'length'}; $j++) {
                   8033:                                 $recorded{$part_id} .= $scantron_config->{'Qoff'};
                   8034:                             }
                   8035:                         }
                   8036:                     } else {
                   8037:                         my @tocheck;
                   8038:                         my @items = split(//,$value);
                   8039:                         if (($scantron_config->{'Qon'} eq 'letter') ||
                   8040:                             ($scantron_config->{'Qon'} eq 'number')) {
                   8041:                             if (@items < $expected{$part_id}) {
                   8042:                                 my $fragment = substr($scandata,$startpos{$part_id},$expected{$part_id});
                   8043:                                 my @singles = split(//,$fragment);
                   8044:                                 foreach my $pos (@singles) {
                   8045:                                     if ($pos eq ' ') {
                   8046:                                         push(@tocheck,$pos);
                   8047:                                     } else {
                   8048:                                         my $next = shift(@items);
                   8049:                                         push(@tocheck,$next);
                   8050:                                     }
                   8051:                                 }
                   8052:                             } else {
                   8053:                                 @tocheck = @items;
                   8054:                             }
                   8055:                             foreach my $letter (@tocheck) {
                   8056:                                 if ($scantron_config->{'Qon'} eq 'letter') {
                   8057:                                     if ($letter !~ /^[A-J]$/) {
                   8058:                                         $letter = $scantron_config->{'Qoff'};
                   8059:                                     }
                   8060:                                     $recorded{$part_id} .= $letter;
                   8061:                                 } elsif ($scantron_config->{'Qon'} eq 'number') {
                   8062:                                     my $digit;
                   8063:                                     if ($letter !~ /^[A-J]$/) {
                   8064:                                         $digit = $scantron_config->{'Qoff'};
                   8065:                                     } else {
                   8066:                                         $digit = $lettdig->{$letter};
                   8067:                                     }
                   8068:                                     $recorded{$part_id} .= $digit;
                   8069:                                 }
                   8070:                             }
                   8071:                         } else {
                   8072:                             @tocheck = @items;
                   8073:                             for (my $i=0; $i<$expected{$part_id}; $i++) {
                   8074:                                 my $curr_sub = shift(@tocheck);
                   8075:                                 my $digit;
                   8076:                                 if ($curr_sub =~ /^[A-J]$/) {
                   8077:                                     $digit = $lettdig->{$curr_sub}-1;
                   8078:                                 }
                   8079:                                 if ($curr_sub eq 'J') {
                   8080:                                     $digit += scalar($numletts);
                   8081:                                 }
                   8082:                                 for (my $j=0; $j<$scantron_config->{'Qlength'}; $j++) {
                   8083:                                     if ($j == $digit) {
                   8084:                                         $recorded{$part_id} .= $scantron_config->{'Qon'};
                   8085:                                     } else {
                   8086:                                         $recorded{$part_id} .= $scantron_config->{'Qoff'};
                   8087:                                     }
                   8088:                                 }
                   8089:                             }
                   8090:                         }
                   8091:                     }
                   8092:                 }
                   8093:             }
                   8094:         }
1.554     raeburn  8095:         foreach my $part_id (@{$partids}) {
1.542     raeburn  8096:             if ($recorded{$part_id} eq '') {
                   8097:                 for (my $i=0; $i<$expected{$part_id}; $i++) {
                   8098:                     for (my $j=0; $j<$scantron_config->{'Qlength'}; $j++) {
                   8099:                         $recorded{$part_id} .= $scantron_config->{'Qoff'};
                   8100:                     }
                   8101:                 }
                   8102:             }
                   8103:             $record .= $recorded{$part_id};
                   8104:         }
                   8105:     }
                   8106:     return ($counter,$record);
                   8107: }
                   8108: 
                   8109: sub letter_to_digits { 
                   8110:     my %lettdig = (
                   8111:                     A => 1,
                   8112:                     B => 2,
                   8113:                     C => 3,
                   8114:                     D => 4,
                   8115:                     E => 5,
                   8116:                     F => 6,
                   8117:                     G => 7,
                   8118:                     H => 8,
                   8119:                     I => 9,
                   8120:                     J => 0,
                   8121:                   );
                   8122:     return %lettdig;
                   8123: }
                   8124: 
1.423     albertel 8125: 
1.75      albertel 8126: #-------- end of section for handling grading scantron forms -------
                   8127: #
                   8128: #-------------------------------------------------------------------
                   8129: 
1.72      ng       8130: #-------------------------- Menu interface -------------------------
                   8131: #
                   8132: #--- Show a Grading Menu button - Calls the next routine ---
                   8133: sub show_grading_menu_form {
1.324     albertel 8134:     my ($symb)=@_;
1.125     ng       8135:     my $result.='<br /><form action="/adm/grades" method="post">'."\n".
1.418     albertel 8136: 	'<input type="hidden" name="symb" value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
1.257     albertel 8137: 	'<input type="hidden" name="saveState"  value="'.$env{'form.saveState'}.'" />'."\n".
1.72      ng       8138: 	'<input type="hidden" name="command" value="gradingmenu" />'."\n".
1.478     albertel 8139: 	'<input type="submit" name="submit" value="'.&mt('Grading Menu').'" />'."\n".
1.72      ng       8140: 	'</form>'."\n";
                   8141:     return $result;
                   8142: }
                   8143: 
1.77      ng       8144: # -- Retrieve choices for grading form
                   8145: sub savedState {
                   8146:     my %savedState = ();
1.257     albertel 8147:     if ($env{'form.saveState'}) {
                   8148: 	foreach (split(/:/,$env{'form.saveState'})) {
1.77      ng       8149: 	    my ($key,$value) = split(/=/,$_,2);
                   8150: 	    $savedState{$key} = $value;
                   8151: 	}
                   8152:     }
                   8153:     return \%savedState;
                   8154: }
1.76      ng       8155: 
1.443     banghart 8156: sub grading_menu {
                   8157:     my ($request) = @_;
                   8158:     my ($symb)=&get_symb($request);
                   8159:     if (!$symb) {return '';}
                   8160:     my $probTitle = &Apache::lonnet::gettitle($symb);
                   8161:     my ($table,undef,$hdgrade) = &showResourceInfo($symb,$probTitle);
                   8162: 
1.444     banghart 8163:     $request->print($table);
1.443     banghart 8164:     my %fields = ('symb'=>&Apache::lonenc::check_encrypt($symb),
                   8165:                   'handgrade'=>$hdgrade,
                   8166:                   'probTitle'=>$probTitle,
                   8167:                   'command'=>'submit_options',
                   8168:                   'saveState'=>"",
                   8169:                   'gradingMenu'=>1,
                   8170:                   'showgrading'=>"yes");
1.538     schulted 8171:     
                   8172:     my $url1 = &Apache::lonhtmlcommon::build_url('grades/',\%fields);
                   8173:     
1.443     banghart 8174:     $fields{'command'} = 'csvform';
1.538     schulted 8175:     my $url2 = &Apache::lonhtmlcommon::build_url('grades/',\%fields);
                   8176:     
1.443     banghart 8177:     $fields{'command'} = 'processclicker';
1.538     schulted 8178:     my $url3 = &Apache::lonhtmlcommon::build_url('grades/',\%fields);
                   8179:     
1.443     banghart 8180:     $fields{'command'} = 'scantron_selectphase';
1.538     schulted 8181:     my $url4 = &Apache::lonhtmlcommon::build_url('grades/',\%fields);
                   8182:     
                   8183:     my @menu = ({	categorytitle=>'Course Grading',
                   8184:             items =>[
                   8185:                         {	linktext => 'Manual Grading/View Submissions',
                   8186:                     		url => $url1,
                   8187:                     		permission => 'F',
                   8188:                     		icon => 'edit-find-replace.png',
                   8189:                     		linktitle => 'Start the process of hand grading submissions.'
                   8190:                         },
                   8191:                 	    {	linktext => 'Upload Scores',
                   8192:                     		url => $url2,
                   8193:                     		permission => 'F',
                   8194:                     		icon => 'uploadscores.png',
                   8195:                     		linktitle => 'Specify a file containing the class scores for current resource.'
                   8196:                 	    },
                   8197:                 	    {	linktext => 'Process Clicker',
                   8198:                     		url => $url3,
                   8199:                     		permission => 'F',
                   8200:                     		icon => 'addClickerInfoFile.png',
                   8201:                     		linktitle => 'Specify a file containing the clicker information for this resource.'
                   8202:                 	    },
                   8203:                 	    {	linktext => 'Grade/Manage/Review Scantron Forms',
                   8204:                     		url => $url4,
                   8205:                     		permission => 'F',
                   8206:                     		icon => 'stat.png',
                   8207:                     		linktitle => 'Grade scantron exams, upload/download scantron data files, and review previously graded scantron exams.'
                   8208:                 	    }
                   8209:                     ]
                   8210:             });
                   8211: 
                   8212:     #$fields{'command'} = 'verify';
                   8213:     #$url = &Apache::lonhtmlcommon::build_url('grades/',\%fields);
1.443     banghart 8214:     #
                   8215:     # Create the menu
                   8216:     my $Str;
1.444     banghart 8217:     # $Str .= '<h2>'.&mt('Please select a grading task').'</h2>';
1.445     banghart 8218:     $Str .= '<form method="post" action="" name="gradingMenu">';
                   8219:     $Str .= '<input type="hidden" name="command" value="" />'.
                   8220:     	'<input type="hidden" name="symb"        value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
                   8221: 	'<input type="hidden" name="handgrade"   value="'.$hdgrade.'" />'."\n".
1.476     albertel 8222: 	'<input type="hidden" name="probTitle"   value="'.$probTitle.'" />'."\n".
1.445     banghart 8223: 	'<input type="hidden" name="saveState"   value="" />'."\n".
                   8224: 	'<input type="hidden" name="gradingMenu" value="1" />'."\n".
                   8225: 	'<input type="hidden" name="showgrading" value="yes" />'."\n";
                   8226: 
1.538     schulted 8227:     $Str .= Apache::lonhtmlcommon::generate_menu(@menu);
                   8228:     #$menudata->{'jscript'}
                   8229:     $Str .='<hr /><input type="button" value="'.&mt('Verify Receipt').'" '.
                   8230:         ' onClick="javascript:checkChoice(document.forms.gradingMenu,\'5\',\'verify\')" '.
                   8231:         ' /> '.
                   8232:         &Apache::lonnet::recprefix($env{'request.course.id'}).
                   8233:         '-<input type="text" name="receipt" size="4" onChange="javascript:checkReceiptNo(this.form,\'OK\')" />';
                   8234: 
1.444     banghart 8235:     $Str .="</form>\n";
1.539     riegler  8236:     my $receiptalert = &mt("Please enter a receipt number given by a student in the receipt box.");
1.443     banghart 8237:     $request->print(<<GRADINGMENUJS);
                   8238: <script type="text/javascript" language="javascript">
                   8239:     function checkChoice(formname,val,cmdx) {
                   8240: 	if (val <= 2) {
                   8241: 	    var cmd = radioSelection(formname.radioChoice);
                   8242: 	    var cmdsave = cmd;
                   8243: 	} else {
                   8244: 	    cmd = cmdx;
                   8245: 	    cmdsave = 'submission';
                   8246: 	}
                   8247: 	formname.command.value = cmd;
                   8248: 	if (val < 5) formname.submit();
                   8249: 	if (val == 5) {
1.458     banghart 8250: 	    if (!checkReceiptNo(formname,'notOK')) { 
                   8251: 	        return false;
                   8252: 	    } else {
                   8253: 	        formname.submit();
                   8254: 	    }
1.445     banghart 8255: 	}
                   8256:     }
1.443     banghart 8257: 
                   8258:     function checkReceiptNo(formname,nospace) {
                   8259: 	var receiptNo = formname.receipt.value;
                   8260: 	var checkOpt = false;
                   8261: 	if (nospace == "OK" && isNaN(receiptNo)) {checkOpt = true;}
                   8262: 	if (nospace == "notOK" && (isNaN(receiptNo) || receiptNo == "")) {checkOpt = true;}
                   8263: 	if (checkOpt) {
1.539     riegler  8264: 	    alert("$receiptalert");
1.443     banghart 8265: 	    formname.receipt.value = "";
                   8266: 	    formname.receipt.focus();
                   8267: 	    return false;
                   8268: 	}
                   8269: 	return true;
                   8270:     }
                   8271: </script>
                   8272: GRADINGMENUJS
                   8273:     &commonJSfunctions($request);
                   8274:     return $Str;    
                   8275: }
                   8276: 
                   8277: 
                   8278: #--- Displays the submissions first page -------
                   8279: sub submit_options {
1.72      ng       8280:     my ($request) = @_;
1.324     albertel 8281:     my ($symb)=&get_symb($request);
1.72      ng       8282:     if (!$symb) {return '';}
1.76      ng       8283:     my $probTitle = &Apache::lonnet::gettitle($symb);
1.72      ng       8284: 
1.539     riegler  8285:     my $receiptalert = &mt("Please enter a receipt number given by a student in the receipt box."); 
1.72      ng       8286:     $request->print(<<GRADINGMENUJS);
                   8287: <script type="text/javascript" language="javascript">
1.116     ng       8288:     function checkChoice(formname,val,cmdx) {
                   8289: 	if (val <= 2) {
                   8290: 	    var cmd = radioSelection(formname.radioChoice);
1.118     ng       8291: 	    var cmdsave = cmd;
1.116     ng       8292: 	} else {
                   8293: 	    cmd = cmdx;
1.118     ng       8294: 	    cmdsave = 'submission';
1.116     ng       8295: 	}
                   8296: 	formname.command.value = cmd;
1.118     ng       8297: 	formname.saveState.value = "saveCmd="+cmdsave+":saveSec="+pullDownSelection(formname.section)+
1.145     albertel 8298: 	    ":saveSub="+pullDownSelection(formname.submitonly)+":saveStatus="+pullDownSelection(formname.Status);
1.116     ng       8299: 	if (val < 5) formname.submit();
                   8300: 	if (val == 5) {
1.72      ng       8301: 	    if (!checkReceiptNo(formname,'notOK')) { return false;}
                   8302: 	    formname.submit();
                   8303: 	}
1.238     albertel 8304: 	if (val < 7) formname.submit();
1.72      ng       8305:     }
                   8306: 
                   8307:     function checkReceiptNo(formname,nospace) {
                   8308: 	var receiptNo = formname.receipt.value;
                   8309: 	var checkOpt = false;
                   8310: 	if (nospace == "OK" && isNaN(receiptNo)) {checkOpt = true;}
                   8311: 	if (nospace == "notOK" && (isNaN(receiptNo) || receiptNo == "")) {checkOpt = true;}
                   8312: 	if (checkOpt) {
1.539     riegler  8313: 	    alert("$receiptalert");
1.72      ng       8314: 	    formname.receipt.value = "";
                   8315: 	    formname.receipt.focus();
                   8316: 	    return false;
                   8317: 	}
                   8318: 	return true;
                   8319:     }
                   8320: </script>
                   8321: GRADINGMENUJS
1.118     ng       8322:     &commonJSfunctions($request);
1.324     albertel 8323:     my ($table,undef,$hdgrade) = &showResourceInfo($symb,$probTitle);
1.473     albertel 8324:     my $result;
1.76      ng       8325:     my (undef,$sections) = &getclasslist('all','0');
1.77      ng       8326:     my $savedState = &savedState();
1.118     ng       8327:     my $saveCmd = ($$savedState{'saveCmd'} eq '' ? 'submission' : $$savedState{'saveCmd'});
1.77      ng       8328:     my $saveSec = ($$savedState{'saveSec'} eq '' ? 'all' : $$savedState{'saveSec'});
1.118     ng       8329:     my $saveSub = ($$savedState{'saveSub'} eq '' ? 'all' : $$savedState{'saveSub'});
1.77      ng       8330:     my $saveStatus = ($$savedState{'saveStatus'} eq '' ? 'Active' : $$savedState{'saveStatus'});
1.72      ng       8331: 
1.533     bisitz   8332:     # Preselect sections
                   8333:     my $selsec="";
                   8334:     if (ref($sections)) {
                   8335:         foreach my $section (sort(@$sections)) {
                   8336:             $selsec.='<option value="'.$section.'" '.
                   8337:                 ($saveSec eq $section ? 'selected="selected"':'').'>'.$section.'</option>'."\n";
                   8338:         }
                   8339:     }
                   8340: 
1.72      ng       8341:     $result.='<form action="/adm/grades" method="post" name="gradingMenu">'."\n".
1.418     albertel 8342: 	'<input type="hidden" name="symb"        value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
1.72      ng       8343: 	'<input type="hidden" name="handgrade"   value="'.$hdgrade.'" />'."\n".
                   8344: 	'<input type="hidden" name="probTitle"   value="'.$probTitle.'" />'."\n".
1.116     ng       8345: 	'<input type="hidden" name="command"     value="" />'."\n".
1.77      ng       8346: 	'<input type="hidden" name="saveState"   value="" />'."\n".
1.124     ng       8347: 	'<input type="hidden" name="gradingMenu" value="1" />'."\n".
1.72      ng       8348: 	'<input type="hidden" name="showgrading" value="yes" />'."\n";
                   8349: 
1.472     albertel 8350:     $result.='
1.533     bisitz   8351: <h2>
                   8352:   '.&mt('Grade Current Resource').'
                   8353: </h2>
                   8354: <div>
                   8355:   '.$table.'
                   8356: </div>
                   8357: 
1.537     harmsja  8358: <div class="LC_columnSection">
                   8359:   
1.533     bisitz   8360:     <fieldset>
                   8361:       <legend>
                   8362:        '.&mt('Sections').'
                   8363:       </legend>
                   8364:       <select name="section" multiple="multiple" size="5">'."\n";
                   8365:     $result.= $selsec;
1.401     albertel 8366:     $result.= '<option value="all" '.($saveSec eq 'all' ? 'selected="selected"' : ''). '>all</option></select> &nbsp; ';
1.472     albertel 8367:     $result.='
1.533     bisitz   8368:     </fieldset>
1.537     harmsja  8369:   
1.533     bisitz   8370:     <fieldset>
                   8371:       <legend>
                   8372:         '.&mt('Groups').'
                   8373:       </legend>
                   8374:       '.&Apache::lonstatistics::GroupSelect('group','multiple',5).'
                   8375:     </fieldset>
1.537     harmsja  8376:   
1.533     bisitz   8377:     <fieldset>
                   8378:       <legend>
                   8379:         '.&mt('Access Status').'
                   8380:       </legend>
                   8381:       '.&Apache::lonhtmlcommon::StatusOptions($saveStatus,undef,5,undef,'mult').'
                   8382:     </fieldset>
1.537     harmsja  8383:   
1.533     bisitz   8384:     <fieldset>
                   8385:       <legend>
                   8386:         '.&mt('Submission Status').'
                   8387:       </legend>
                   8388:       <select name="submitonly" size="5">
1.473     albertel 8389: 	         <option value="yes" '.      ($saveSub eq 'yes'       ? 'selected="selected"' : '').'>'.&mt('with submissions').'</option>
                   8390: 	         <option value="queued" '.   ($saveSub eq 'queued'    ? 'selected="selected"' : '').'>'.&mt('in grading queue').'</option>
                   8391: 	         <option value="graded" '.   ($saveSub eq 'graded'    ? 'selected="selected"' : '').'>'.&mt('with ungraded submissions').'</option>
                   8392: 	         <option value="incorrect" '.($saveSub eq 'incorrect' ? 'selected="selected"' : '').'>'.&mt('with incorrect submissions').'</option>
                   8393:                  <option value="all" '.      ($saveSub eq 'all'       ? 'selected="selected"' : '').'>'.&mt('with any status').'</option>
1.533     bisitz   8394:       </select>
                   8395:     </fieldset>
1.537     harmsja  8396:   
1.533     bisitz   8397: </div>
                   8398: 
                   8399: <br />
                   8400:           <div>
                   8401:             <div>
1.473     albertel 8402:               <label>
                   8403:                 <input type="radio" name="radioChoice" value="submission" '.
                   8404:                   ($saveCmd eq 'submission' ? 'checked="checked"' : '').' /> '.
                   8405:              &mt('Select individual students to grade and view submissions.').'
                   8406: 	      </label> 
                   8407:             </div>
1.533     bisitz   8408:             <div>
1.473     albertel 8409: 	      <label>
                   8410:                 <input type="radio" name="radioChoice" value="viewgrades" '.
                   8411:                   ($saveCmd eq 'viewgrades' ? 'checked="checked"' : '').' /> '.
                   8412:                     &mt('Grade all selected students in a grading table.').'
                   8413:               </label>
                   8414:             </div>
1.533     bisitz   8415:             <div>
1.539     riegler  8416: 	      <input type="button" onClick="javascript:checkChoice(this.form,\'2\');" value="'.&mt('Next').' &rarr;" />
1.473     albertel 8417:             </div>
1.472     albertel 8418:           </div>
1.533     bisitz   8419: 
                   8420: 
1.473     albertel 8421:         <h2>
                   8422:          '.&mt('Grade Complete Folder for One Student').'
                   8423:         </h2>
1.533     bisitz   8424:         <div>
                   8425:             <div>
1.473     albertel 8426:               <label>
                   8427:                 <input type="radio" name="radioChoice" value="pickStudentPage" '.
                   8428: 	  ($saveCmd eq 'pickStudentPage' ? 'checked="checked"' : '').' /> '.
                   8429:   &mt('The <b>complete</b> page/sequence/folder: For one student').'
                   8430:               </label>
                   8431:             </div>
1.533     bisitz   8432:             <div>
1.539     riegler  8433: 	      <input type="button" onClick="javascript:checkChoice(this.form,\'2\');" value="'.&mt('Next').' &rarr;" />
1.473     albertel 8434:             </div>
1.472     albertel 8435:         </div>
                   8436:   </form>';
1.499     albertel 8437:     $result .= &show_grading_menu_form($symb);
1.44      ng       8438:     return $result;
1.2       albertel 8439: }
                   8440: 
1.285     albertel 8441: sub reset_perm {
                   8442:     undef(%perm);
                   8443: }
                   8444: 
                   8445: sub init_perm {
                   8446:     &reset_perm();
1.300     albertel 8447:     foreach my $test_perm ('vgr','mgr','opa') {
                   8448: 
                   8449: 	my $scope = $env{'request.course.id'};
                   8450: 	if (!($perm{$test_perm}=&Apache::lonnet::allowed($test_perm,$scope))) {
                   8451: 
                   8452: 	    $scope .= '/'.$env{'request.course.sec'};
                   8453: 	    if ( $perm{$test_perm}=
                   8454: 		 &Apache::lonnet::allowed($test_perm,$scope)) {
                   8455: 		$perm{$test_perm.'_section'}=$env{'request.course.sec'};
                   8456: 	    } else {
                   8457: 		delete($perm{$test_perm});
                   8458: 	    }
1.285     albertel 8459: 	}
                   8460:     }
                   8461: }
                   8462: 
1.400     www      8463: sub gather_clicker_ids {
1.408     albertel 8464:     my %clicker_ids;
1.400     www      8465: 
                   8466:     my $classlist = &Apache::loncoursedata::get_classlist();
                   8467: 
                   8468:     # Set up a couple variables.
1.407     albertel 8469:     my $username_idx = &Apache::loncoursedata::CL_SNAME();
                   8470:     my $domain_idx   = &Apache::loncoursedata::CL_SDOM();
1.438     www      8471:     my $status_idx   = &Apache::loncoursedata::CL_STATUS();
1.400     www      8472: 
1.407     albertel 8473:     foreach my $student (keys(%$classlist)) {
1.438     www      8474:         if ($classlist->{$student}->[$status_idx] ne 'Active') { next; }
1.407     albertel 8475:         my $username = $classlist->{$student}->[$username_idx];
                   8476:         my $domain   = $classlist->{$student}->[$domain_idx];
1.400     www      8477:         my $clickers =
1.408     albertel 8478: 	    (&Apache::lonnet::userenvironment($domain,$username,'clickers'))[1];
1.400     www      8479:         foreach my $id (split(/\,/,$clickers)) {
1.414     www      8480:             $id=~s/^[\#0]+//;
1.421     www      8481:             $id=~s/[\-\:]//g;
1.407     albertel 8482:             if (exists($clicker_ids{$id})) {
1.408     albertel 8483: 		$clicker_ids{$id}.=','.$username.':'.$domain;
1.400     www      8484:             } else {
1.408     albertel 8485: 		$clicker_ids{$id}=$username.':'.$domain;
1.400     www      8486:             }
                   8487:         }
                   8488:     }
1.407     albertel 8489:     return %clicker_ids;
1.400     www      8490: }
                   8491: 
1.402     www      8492: sub gather_adv_clicker_ids {
1.408     albertel 8493:     my %clicker_ids;
1.402     www      8494:     my $cnum=$env{'course.'.$env{'request.course.id'}.'.num'};
                   8495:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
                   8496:     my %coursepersonnel=&Apache::lonnet::get_course_adv_roles($cdom.'/'.$cnum);
1.409     albertel 8497:     foreach my $element (sort(keys(%coursepersonnel))) {
1.402     www      8498:         foreach my $person (split(/\,/,$coursepersonnel{$element})) {
                   8499:             my ($puname,$pudom)=split(/\:/,$person);
                   8500:             my $clickers =
1.408     albertel 8501: 		(&Apache::lonnet::userenvironment($pudom,$puname,'clickers'))[1];
1.405     www      8502:             foreach my $id (split(/\,/,$clickers)) {
1.414     www      8503: 		$id=~s/^[\#0]+//;
1.421     www      8504:                 $id=~s/[\-\:]//g;
1.408     albertel 8505: 		if (exists($clicker_ids{$id})) {
                   8506: 		    $clicker_ids{$id}.=','.$puname.':'.$pudom;
                   8507: 		} else {
                   8508: 		    $clicker_ids{$id}=$puname.':'.$pudom;
                   8509: 		}
1.405     www      8510:             }
1.402     www      8511:         }
                   8512:     }
1.407     albertel 8513:     return %clicker_ids;
1.402     www      8514: }
                   8515: 
1.413     www      8516: sub clicker_grading_parameters {
                   8517:     return ('gradingmechanism' => 'scalar',
                   8518:             'upfiletype' => 'scalar',
                   8519:             'specificid' => 'scalar',
                   8520:             'pcorrect' => 'scalar',
                   8521:             'pincorrect' => 'scalar');
                   8522: }
                   8523: 
1.400     www      8524: sub process_clicker {
                   8525:     my ($r)=@_;
                   8526:     my ($symb)=&get_symb($r);
                   8527:     if (!$symb) {return '';}
                   8528:     my $result=&checkforfile_js();
                   8529:     $env{'form.probTitle'} = &Apache::lonnet::gettitle($symb);
                   8530:     my ($table) = &showResourceInfo($symb,$env{'form.probTitle'});
                   8531:     $result.=$table;
                   8532:     $result.='<br /><table width="100%" border="0"><tr><td bgcolor="#777777">'."\n";
                   8533:     $result.='<table width="100%" border="0"><tr bgcolor="#e6ffff"><td>'."\n";
1.538     schulted 8534:     $result.='&nbsp;<b>'.&mt('Specify a file containing the clicker information for this resource.').
                   8535:         '</b></td></tr>'."\n";
1.400     www      8536:     $result.='<tr bgcolor=#ffffe6><td>'."\n";
1.413     www      8537: # Attempt to restore parameters from last session, set defaults if not present
                   8538:     my %Saveable_Parameters=&clicker_grading_parameters();
                   8539:     &Apache::loncommon::restore_course_settings('grades_clicker',
                   8540:                                                  \%Saveable_Parameters);
                   8541:     if (!$env{'form.pcorrect'}) { $env{'form.pcorrect'}=100; }
                   8542:     if (!$env{'form.pincorrect'}) { $env{'form.pincorrect'}=100; }
                   8543:     if (!$env{'form.gradingmechanism'}) { $env{'form.gradingmechanism'}='attendance'; }
                   8544:     if (!$env{'form.upfiletype'}) { $env{'form.upfiletype'}='iclicker'; }
                   8545: 
                   8546:     my %checked;
1.521     www      8547:     foreach my $gradingmechanism ('attendance','personnel','specific','given') {
1.413     www      8548:        if ($env{'form.gradingmechanism'} eq $gradingmechanism) {
                   8549:           $checked{$gradingmechanism}="checked='checked'";
                   8550:        }
                   8551:     }
                   8552: 
1.400     www      8553:     my $upload=&mt("Upload File");
                   8554:     my $type=&mt("Type");
1.402     www      8555:     my $attendance=&mt("Award points just for participation");
                   8556:     my $personnel=&mt("Correctness determined from response by course personnel");
1.414     www      8557:     my $specific=&mt("Correctness determined from response with clicker ID(s)"); 
1.521     www      8558:     my $given=&mt("Correctness determined from given list of answers").' '.
                   8559:               '<font size="-2"><tt>('.&mt("Provide comma-separated list. Use '*' for any answer correct, '-' for skip").')</tt></font>';
1.402     www      8560:     my $pcorrect=&mt("Percentage points for correct solution");
                   8561:     my $pincorrect=&mt("Percentage points for incorrect solution");
1.413     www      8562:     my $selectform=&Apache::loncommon::select_form($env{'form.upfiletype'},'upfiletype',
1.419     www      8563: 						   ('iclicker' => 'i>clicker',
                   8564:                                                     'interwrite' => 'interwrite PRS'));
1.418     albertel 8565:     $symb = &Apache::lonenc::check_encrypt($symb);
1.400     www      8566:     $result.=<<ENDUPFORM;
1.402     www      8567: <script type="text/javascript">
                   8568: function sanitycheck() {
                   8569: // Accept only integer percentages
                   8570:    document.forms.gradesupload.pcorrect.value=Math.round(document.forms.gradesupload.pcorrect.value);
                   8571:    document.forms.gradesupload.pincorrect.value=Math.round(document.forms.gradesupload.pincorrect.value);
                   8572: // Find out grading choice
                   8573:    for (i=0; i<document.forms.gradesupload.gradingmechanism.length; i++) {
                   8574:       if (document.forms.gradesupload.gradingmechanism[i].checked) {
                   8575:          gradingchoice=document.forms.gradesupload.gradingmechanism[i].value;
                   8576:       }
                   8577:    }
                   8578: // By default, new choice equals user selection
                   8579:    newgradingchoice=gradingchoice;
                   8580: // Not good to give more points for false answers than correct ones
                   8581:    if (Math.round(document.forms.gradesupload.pcorrect.value)<Math.round(document.forms.gradesupload.pincorrect.value)) {
                   8582:       document.forms.gradesupload.pcorrect.value=document.forms.gradesupload.pincorrect.value;
                   8583:    }
                   8584: // If new choice is attendance only, and old choice was correctness-based, restore defaults
                   8585:    if ((gradingchoice=='attendance') && (document.forms.gradesupload.waschecked.value!='attendance')) {
                   8586:       document.forms.gradesupload.pcorrect.value=100;
                   8587:       document.forms.gradesupload.pincorrect.value=100;
                   8588:    }
                   8589: // If the values are different, cannot be attendance only
                   8590:    if ((Math.round(document.forms.gradesupload.pcorrect.value)!=Math.round(document.forms.gradesupload.pincorrect.value)) &&
                   8591:        (gradingchoice=='attendance')) {
                   8592:        newgradingchoice='personnel';
                   8593:    }
                   8594: // Change grading choice to new one
                   8595:    for (i=0; i<document.forms.gradesupload.gradingmechanism.length; i++) {
                   8596:       if (document.forms.gradesupload.gradingmechanism[i].value==newgradingchoice) {
                   8597:          document.forms.gradesupload.gradingmechanism[i].checked=true;
                   8598:       } else {
                   8599:          document.forms.gradesupload.gradingmechanism[i].checked=false;
                   8600:       }
                   8601:    }
                   8602: // Remember the old state
                   8603:    document.forms.gradesupload.waschecked.value=newgradingchoice;
                   8604: }
                   8605: </script>
1.400     www      8606: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="gradesupload">
                   8607: <input type="hidden" name="symb" value="$symb" />
                   8608: <input type="hidden" name="command" value="processclickerfile" />
                   8609: <input type="hidden" name="probTitle" value="$env{'form.probTitle'}" />
                   8610: <input type="hidden" name="saveState"  value="$env{'form.saveState'}" />
                   8611: <input type="file" name="upfile" size="50" />
                   8612: <br /><label>$type: $selectform</label>
1.451     albertel 8613: <br /><label><input type="radio" name="gradingmechanism" value="attendance" $checked{'attendance'} onClick="sanitycheck()" />$attendance </label>
                   8614: <br /><label><input type="radio" name="gradingmechanism" value="personnel" $checked{'personnel'} onClick="sanitycheck()" />$personnel</label>
                   8615: <br /><label><input type="radio" name="gradingmechanism" value="specific" $checked{'specific'} onClick="sanitycheck()" />$specific </label>
1.414     www      8616: <input type="text" name="specificid" value="$env{'form.specificid'}" size="20" />
1.521     www      8617: <br /><label><input type="radio" name="gradingmechanism" value="given" $checked{'given'} onClick="sanitycheck()" />$given </label>
                   8618: <br />&nbsp;&nbsp;&nbsp;
                   8619: <input type="text" name="givenanswer" size="50" />
1.413     www      8620: <input type="hidden" name="waschecked" value="$env{'form.gradingmechanism'}" />
                   8621: <br /><label>$pcorrect: <input type="text" name="pcorrect" size="4" value="$env{'form.pcorrect'}" onChange="sanitycheck()" /></label>
                   8622: <br /><label>$pincorrect: <input type="text" name="pincorrect" size="4" value="$env{'form.pincorrect'}" onChange="sanitycheck()" /></label>
1.400     www      8623: <br /><input type="button" onClick="javascript:checkUpload(this.form);" value="$upload" />
                   8624: </form>
                   8625: ENDUPFORM
                   8626:     $result.='</td></tr></table>'."\n".
                   8627:              '</td></tr></table><br /><br />'."\n";
                   8628:     $result.=&show_grading_menu_form($symb);
                   8629:     return $result;
                   8630: }
                   8631: 
                   8632: sub process_clicker_file {
                   8633:     my ($r)=@_;
                   8634:     my ($symb)=&get_symb($r);
                   8635:     if (!$symb) {return '';}
1.413     www      8636: 
                   8637:     my %Saveable_Parameters=&clicker_grading_parameters();
                   8638:     &Apache::loncommon::store_course_settings('grades_clicker',
                   8639:                                               \%Saveable_Parameters);
                   8640: 
1.400     www      8641:     my ($result) = &showResourceInfo($symb,$env{'form.probTitle'});
1.404     www      8642:     if (($env{'form.gradingmechanism'} eq 'specific') && ($env{'form.specificid'}!~/\w/)) {
1.408     albertel 8643: 	$result.='<span class="LC_error">'.&mt('You need to specify a clicker ID for the correct answer').'</span>';
                   8644: 	return $result.&show_grading_menu_form($symb);
1.404     www      8645:     }
1.522     www      8646:     if (($env{'form.gradingmechanism'} eq 'given') && ($env{'form.givenanswer'}!~/\S/)) {
1.521     www      8647:         $result.='<span class="LC_error">'.&mt('You need to specify the correct answer').'</span>';
                   8648:         return $result.&show_grading_menu_form($symb);
                   8649:     }
1.522     www      8650:     my $foundgiven=0;
1.521     www      8651:     if ($env{'form.gradingmechanism'} eq 'given') {
                   8652:         $env{'form.givenanswer'}=~s/^\s*//gs;
                   8653:         $env{'form.givenanswer'}=~s/\s*$//gs;
                   8654:         $env{'form.givenanswer'}=~s/[^a-zA-Z0-9\.\*\-]+/\,/g;
                   8655:         $env{'form.givenanswer'}=uc($env{'form.givenanswer'});
1.522     www      8656:         my @answers=split(/\,/,$env{'form.givenanswer'});
                   8657:         $foundgiven=$#answers+1;
1.521     www      8658:     }
1.407     albertel 8659:     my %clicker_ids=&gather_clicker_ids();
1.408     albertel 8660:     my %correct_ids;
1.404     www      8661:     if ($env{'form.gradingmechanism'} eq 'personnel') {
1.408     albertel 8662: 	%correct_ids=&gather_adv_clicker_ids();
1.404     www      8663:     }
                   8664:     if ($env{'form.gradingmechanism'} eq 'specific') {
1.414     www      8665: 	foreach my $correct_id (split(/[\s\,]/,$env{'form.specificid'})) {;
                   8666: 	   $correct_id=~tr/a-z/A-Z/;
                   8667: 	   $correct_id=~s/\s//gs;
                   8668: 	   $correct_id=~s/^[\#0]+//;
1.421     www      8669:            $correct_id=~s/[\-\:]//g;
1.414     www      8670:            if ($correct_id) {
                   8671: 	      $correct_ids{$correct_id}='specified';
                   8672:            }
                   8673:         }
1.400     www      8674:     }
1.404     www      8675:     if ($env{'form.gradingmechanism'} eq 'attendance') {
1.408     albertel 8676: 	$result.=&mt('Score based on attendance only');
1.521     www      8677:     } elsif ($env{'form.gradingmechanism'} eq 'given') {
1.522     www      8678:         $result.=&mt('Score based on [_1] ([_2] answers)','<tt>'.$env{'form.givenanswer'}.'</tt>',$foundgiven);
1.404     www      8679:     } else {
1.408     albertel 8680: 	my $number=0;
1.411     www      8681: 	$result.='<p><b>'.&mt('Correctness determined by the following IDs').'</b>';
1.408     albertel 8682: 	foreach my $id (sort(keys(%correct_ids))) {
1.411     www      8683: 	    $result.='<br /><tt>'.$id.'</tt> - ';
1.408     albertel 8684: 	    if ($correct_ids{$id} eq 'specified') {
                   8685: 		$result.=&mt('specified');
                   8686: 	    } else {
                   8687: 		my ($uname,$udom)=split(/\:/,$correct_ids{$id});
                   8688: 		$result.=&Apache::loncommon::plainname($uname,$udom);
                   8689: 	    }
                   8690: 	    $number++;
                   8691: 	}
1.411     www      8692:         $result.="</p>\n";
1.408     albertel 8693: 	if ($number==0) {
                   8694: 	    $result.='<span class="LC_error">'.&mt('No IDs found to determine correct answer').'</span>';
                   8695: 	    return $result.&show_grading_menu_form($symb);
                   8696: 	}
1.404     www      8697:     }
1.405     www      8698:     if (length($env{'form.upfile'}) < 2) {
1.407     albertel 8699:         $result.=&mt('[_1] Error: [_2] The file you attempted to upload, [_3] contained no information. Please check that you entered the correct filename.',
                   8700: 		     '<span class="LC_error">',
                   8701: 		     '</span>',
                   8702: 		     '<span class="LC_filename">'.&HTML::Entities::encode($env{'form.upfile.filename'},'<>&"').'</span>');
1.405     www      8703:         return $result.&show_grading_menu_form($symb);
                   8704:     }
1.410     www      8705: 
                   8706: # Were able to get all the info needed, now analyze the file
                   8707: 
1.411     www      8708:     $result.=&Apache::loncommon::studentbrowser_javascript();
1.418     albertel 8709:     $symb = &Apache::lonenc::check_encrypt($symb);
1.410     www      8710:     my $heading=&mt('Scanning clicker file');
                   8711:     $result.=(<<ENDHEADER);
                   8712: <br /><table width="100%" border="0"><tr><td bgcolor="#777777">
                   8713: <table width="100%" border="0"><tr bgcolor="#e6ffff"><td>
                   8714: <b>$heading</b></td></tr><tr bgcolor=#ffffe6><td>
                   8715: <form method="post" action="/adm/grades" name="clickeranalysis">
                   8716: <input type="hidden" name="symb" value="$symb" />
                   8717: <input type="hidden" name="command" value="assignclickergrades" />
                   8718: <input type="hidden" name="probTitle" value="$env{'form.probTitle'}" />
                   8719: <input type="hidden" name="saveState"  value="$env{'form.saveState'}" />
1.411     www      8720: <input type="hidden" name="gradingmechanism" value="$env{'form.gradingmechanism'}" />
                   8721: <input type="hidden" name="pcorrect" value="$env{'form.pcorrect'}" />
                   8722: <input type="hidden" name="pincorrect" value="$env{'form.pincorrect'}" />
1.410     www      8723: ENDHEADER
1.522     www      8724:     if ($env{'form.gradingmechanism'} eq 'given') {
                   8725:        $result.='<input type="hidden" name="correct:given" value="'.$env{'form.givenanswer'}.'" />';
                   8726:     } 
1.408     albertel 8727:     my %responses;
                   8728:     my @questiontitles;
1.405     www      8729:     my $errormsg='';
                   8730:     my $number=0;
                   8731:     if ($env{'form.upfiletype'} eq 'iclicker') {
1.408     albertel 8732: 	($errormsg,$number)=&iclicker_eval(\@questiontitles,\%responses);
1.406     www      8733:     }
1.419     www      8734:     if ($env{'form.upfiletype'} eq 'interwrite') {
                   8735:         ($errormsg,$number)=&interwrite_eval(\@questiontitles,\%responses);
                   8736:     }
1.411     www      8737:     $result.='<br />'.&mt('Found [_1] question(s)',$number).'<br />'.
                   8738:              '<input type="hidden" name="number" value="'.$number.'" />'.
                   8739:              &mt('Awarding [_1] percent for correct and [_2] percent for incorrect responses',
                   8740:                  $env{'form.pcorrect'},$env{'form.pincorrect'}).
                   8741:              '<br />';
1.522     www      8742:     if (($env{'form.gradingmechanism'} eq 'given') && ($number!=$foundgiven)) {
                   8743:        $result.='<span class="LC_error">'.&mt('Number of given answers does not agree with number of questions in file.').'</span>';
                   8744:        return $result.&show_grading_menu_form($symb);
                   8745:     } 
1.414     www      8746: # Remember Question Titles
                   8747: # FIXME: Possibly need delimiter other than ":"
                   8748:     for (my $i=0;$i<$number;$i++) {
                   8749:         $result.='<input type="hidden" name="question:'.$i.'" value="'.
                   8750:                  &HTML::Entities::encode($questiontitles[$i],'"&<>').'" />';
                   8751:     }
1.411     www      8752:     my $correct_count=0;
                   8753:     my $student_count=0;
                   8754:     my $unknown_count=0;
1.414     www      8755: # Match answers with usernames
                   8756: # FIXME: Possibly need delimiter other than ":"
1.409     albertel 8757:     foreach my $id (keys(%responses)) {
1.410     www      8758:        if ($correct_ids{$id}) {
1.414     www      8759:           $result.="\n".'<input type="hidden" name="correct:'.$correct_count.':'.$correct_ids{$id}.'" value="'.$responses{$id}.'" />';
1.411     www      8760:           $correct_count++;
1.410     www      8761:        } elsif ($clicker_ids{$id}) {
1.437     www      8762:           if ($clicker_ids{$id}=~/\,/) {
                   8763: # More than one user with the same clicker!
                   8764:              $result.="\n<hr />".&mt('Clicker registered more than once').": <tt>".$id."</tt><br />";
                   8765:              $result.="\n".'<input type="hidden" name="unknown:'.$id.'" value="'.$responses{$id}.'" />'.
                   8766:                            "<select name='multi".$id."'>";
                   8767:              foreach my $reguser (sort(split(/\,/,$clicker_ids{$id}))) {
                   8768:                  $result.="<option value='".$reguser."'>".&Apache::loncommon::plainname(split(/\:/,$reguser)).' ('.$reguser.')</option>';
                   8769:              }
                   8770:              $result.='</select>';
                   8771:              $unknown_count++;
                   8772:           } else {
                   8773: # Good: found one and only one user with the right clicker
                   8774:              $result.="\n".'<input type="hidden" name="student:'.$clicker_ids{$id}.'" value="'.$responses{$id}.'" />';
                   8775:              $student_count++;
                   8776:           }
1.410     www      8777:        } else {
1.411     www      8778:           $result.="\n<hr />".&mt('Unregistered Clicker')." <tt>".$id."</tt><br />";
                   8779:           $result.="\n".'<input type="hidden" name="unknown:'.$id.'" value="'.$responses{$id}.'" />'.
                   8780:                    "\n".&mt("Username").": <input type='text' name='uname".$id."' />&nbsp;".
                   8781:                    "\n".&mt("Domain").": ".
                   8782:                    &Apache::loncommon::select_dom_form($env{'course.'.$env{'request.course.id'}.'.domain'},'udom'.$id).'&nbsp;'.
                   8783:                    &Apache::loncommon::selectstudent_link('clickeranalysis','uname'.$id,'udom'.$id);
                   8784:           $unknown_count++;
1.410     www      8785:        }
1.405     www      8786:     }
1.412     www      8787:     $result.='<hr />'.
                   8788:              &mt('Found [_1] registered and [_2] unregistered clickers.',$student_count,$unknown_count);
1.521     www      8789:     if (($env{'form.gradingmechanism'} ne 'attendance') && ($env{'form.gradingmechanism'} ne 'given')) {
1.412     www      8790:        if ($correct_count==0) {
                   8791:           $errormsg.="Found no correct answers answers for grading!";
                   8792:        } elsif ($correct_count>1) {
1.414     www      8793:           $result.='<br /><span class="LC_warning">'.&mt("Found [_1] entries for grading!",$correct_count).'</span>';
1.412     www      8794:        }
                   8795:     }
1.428     www      8796:     if ($number<1) {
                   8797:        $errormsg.="Found no questions.";
                   8798:     }
1.412     www      8799:     if ($errormsg) {
                   8800:        $result.='<br /><span class="LC_error">'.&mt($errormsg).'</span>';
                   8801:     } else {
                   8802:        $result.='<br /><input type="submit" name="finalize" value="'.&mt('Finalize Grading').'" />';
                   8803:     }
                   8804:     $result.='</form></td></tr></table>'."\n".
1.410     www      8805:              '</td></tr></table><br /><br />'."\n";
1.404     www      8806:     return $result.&show_grading_menu_form($symb);
1.400     www      8807: }
                   8808: 
1.405     www      8809: sub iclicker_eval {
1.406     www      8810:     my ($questiontitles,$responses)=@_;
1.405     www      8811:     my $number=0;
                   8812:     my $errormsg='';
                   8813:     foreach my $line (split(/[\n\r]/,$env{'form.upfile'})) {
1.410     www      8814:         my %components=&Apache::loncommon::record_sep($line);
                   8815:         my @entries=map {$components{$_}} (sort(keys(%components)));
1.408     albertel 8816: 	if ($entries[0] eq 'Question') {
                   8817: 	    for (my $i=3;$i<$#entries;$i+=6) {
                   8818: 		$$questiontitles[$number]=$entries[$i];
                   8819: 		$number++;
                   8820: 	    }
                   8821: 	}
                   8822: 	if ($entries[0]=~/^\#/) {
                   8823: 	    my $id=$entries[0];
                   8824: 	    my @idresponses;
                   8825: 	    $id=~s/^[\#0]+//;
                   8826: 	    for (my $i=0;$i<$number;$i++) {
                   8827: 		my $idx=3+$i*6;
                   8828: 		push(@idresponses,$entries[$idx]);
                   8829: 	    }
                   8830: 	    $$responses{$id}=join(',',@idresponses);
                   8831: 	}
1.405     www      8832:     }
                   8833:     return ($errormsg,$number);
                   8834: }
                   8835: 
1.419     www      8836: sub interwrite_eval {
                   8837:     my ($questiontitles,$responses)=@_;
                   8838:     my $number=0;
                   8839:     my $errormsg='';
1.420     www      8840:     my $skipline=1;
                   8841:     my $questionnumber=0;
                   8842:     my %idresponses=();
1.419     www      8843:     foreach my $line (split(/[\n\r]/,$env{'form.upfile'})) {
                   8844:         my %components=&Apache::loncommon::record_sep($line);
                   8845:         my @entries=map {$components{$_}} (sort(keys(%components)));
1.420     www      8846:         if ($entries[1] eq 'Time') { $skipline=0; next; }
                   8847:         if ($entries[1] eq 'Response') { $skipline=1; }
                   8848:         next if $skipline;
                   8849:         if ($entries[0]!=$questionnumber) {
                   8850:            $questionnumber=$entries[0];
                   8851:            $$questiontitles[$number]=&mt('Question [_1]',$questionnumber);
                   8852:            $number++;
1.419     www      8853:         }
1.420     www      8854:         my $id=$entries[4];
                   8855:         $id=~s/^[\#0]+//;
1.421     www      8856:         $id=~s/^v\d*\://i;
                   8857:         $id=~s/[\-\:]//g;
1.420     www      8858:         $idresponses{$id}[$number]=$entries[6];
                   8859:     }
1.524     raeburn  8860:     foreach my $id (keys(%idresponses)) {
1.420     www      8861:        $$responses{$id}=join(',',@{$idresponses{$id}});
                   8862:        $$responses{$id}=~s/^\s*\,//;
1.419     www      8863:     }
                   8864:     return ($errormsg,$number);
                   8865: }
                   8866: 
1.414     www      8867: sub assign_clicker_grades {
                   8868:     my ($r)=@_;
                   8869:     my ($symb)=&get_symb($r);
                   8870:     if (!$symb) {return '';}
1.416     www      8871: # See which part we are saving to
                   8872:     my ($partlist,$handgrade,$responseType) = &response_type($symb);
                   8873: # FIXME: This should probably look for the first handgradeable part
                   8874:     my $part=$$partlist[0];
                   8875: # Start screen output
1.414     www      8876:     my ($result) = &showResourceInfo($symb,$env{'form.probTitle'});
1.416     www      8877: 
1.414     www      8878:     my $heading=&mt('Assigning grades based on clicker file');
                   8879:     $result.=(<<ENDHEADER);
                   8880: <br /><table width="100%" border="0"><tr><td bgcolor="#777777">
                   8881: <table width="100%" border="0"><tr bgcolor="#e6ffff"><td>
                   8882: <b>$heading</b></td></tr><tr bgcolor=#ffffe6><td>
                   8883: ENDHEADER
                   8884: # Get correct result
                   8885: # FIXME: Possibly need delimiter other than ":"
                   8886:     my @correct=();
1.415     www      8887:     my $gradingmechanism=$env{'form.gradingmechanism'};
                   8888:     my $number=$env{'form.number'};
                   8889:     if ($gradingmechanism ne 'attendance') {
1.414     www      8890:        foreach my $key (keys(%env)) {
                   8891:           if ($key=~/^form\.correct\:/) {
                   8892:              my @input=split(/\,/,$env{$key});
                   8893:              for (my $i=0;$i<=$#input;$i++) {
                   8894:                  if (($correct[$i]) && ($input[$i]) &&
                   8895:                      ($correct[$i] ne $input[$i])) {
                   8896:                     $result.='<br /><span class="LC_warning">'.
                   8897:                              &mt('More than one correct result given for question "[_1]": [_2] versus [_3].',
                   8898:                                  $env{'form.question:'.$i},$correct[$i],$input[$i]).'</span>';
                   8899:                  } elsif ($input[$i]) {
                   8900:                     $correct[$i]=$input[$i];
                   8901:                  }
                   8902:              }
                   8903:           }
                   8904:        }
1.415     www      8905:        for (my $i=0;$i<$number;$i++) {
1.414     www      8906:           if (!$correct[$i]) {
                   8907:              $result.='<br /><span class="LC_error">'.
                   8908:                       &mt('No correct result given for question "[_1]"!',
                   8909:                           $env{'form.question:'.$i}).'</span>';
                   8910:           }
                   8911:        }
                   8912:        $result.='<br />'.&mt("Correct answer: [_1]",join(', ',map { ($_?$_:'-') } @correct));
                   8913:     }
                   8914: # Start grading
1.415     www      8915:     my $pcorrect=$env{'form.pcorrect'};
                   8916:     my $pincorrect=$env{'form.pincorrect'};
1.416     www      8917:     my $storecount=0;
1.415     www      8918:     foreach my $key (keys(%env)) {
1.420     www      8919:        my $user='';
1.415     www      8920:        if ($key=~/^form\.student\:(.*)$/) {
1.420     www      8921:           $user=$1;
                   8922:        }
                   8923:        if ($key=~/^form\.unknown\:(.*)$/) {
                   8924:           my $id=$1;
                   8925:           if (($env{'form.uname'.$id}) && ($env{'form.udom'.$id})) {
                   8926:              $user=$env{'form.uname'.$id}.':'.$env{'form.udom'.$id};
1.437     www      8927:           } elsif ($env{'form.multi'.$id}) {
                   8928:              $user=$env{'form.multi'.$id};
1.420     www      8929:           }
                   8930:        }
                   8931:        if ($user) { 
1.415     www      8932:           my @answer=split(/\,/,$env{$key});
                   8933:           my $sum=0;
1.522     www      8934:           my $realnumber=$number;
1.415     www      8935:           for (my $i=0;$i<$number;$i++) {
                   8936:              if ($answer[$i]) {
                   8937:                 if ($gradingmechanism eq 'attendance') {
                   8938:                    $sum+=$pcorrect;
1.522     www      8939:                 } elsif ($answer[$i] eq '*') {
                   8940:                    $sum+=$pcorrect;
                   8941:                 } elsif ($answer[$i] eq '-') {
                   8942:                    $realnumber--;
1.415     www      8943:                 } else {
                   8944:                    if ($answer[$i] eq $correct[$i]) {
                   8945:                       $sum+=$pcorrect;
                   8946:                    } else {
                   8947:                       $sum+=$pincorrect;
                   8948:                    }
                   8949:                 }
                   8950:              }
                   8951:           }
1.522     www      8952:           my $ave=$sum/(100*$realnumber);
1.416     www      8953: # Store
                   8954:           my ($username,$domain)=split(/\:/,$user);
                   8955:           my %grades=();
                   8956:           $grades{"resource.$part.solved"}='correct_by_override';
                   8957:           $grades{"resource.$part.awarded"}=$ave;
                   8958:           $grades{"resource.regrader"}="$env{'user.name'}:$env{'user.domain'}";
                   8959:           my $returncode=&Apache::lonnet::cstore(\%grades,$symb,
                   8960:                                                  $env{'request.course.id'},
                   8961:                                                  $domain,$username);
                   8962:           if ($returncode ne 'ok') {
                   8963:              $result.="<br /><span class=\"LC_error\">Failed to save student $username:$domain. Message when trying to save was ($returncode)</span>";
                   8964:           } else {
                   8965:              $storecount++;
                   8966:           }
1.415     www      8967:        }
                   8968:     }
                   8969: # We are done
1.549     hauer    8970:     $result.='<br />'.&mt('Successfully stored grades for [quant,_1,student].',$storecount).
1.416     www      8971:              '</td></tr></table>'."\n".
1.414     www      8972:              '</td></tr></table><br /><br />'."\n";
                   8973:     return $result.&show_grading_menu_form($symb);
                   8974: }
                   8975: 
1.1       albertel 8976: sub handler {
1.41      ng       8977:     my $request=$_[0];
1.434     albertel 8978:     &reset_caches();
1.257     albertel 8979:     if ($env{'browser.mathml'}) {
1.141     www      8980: 	&Apache::loncommon::content_type($request,'text/xml');
1.41      ng       8981:     } else {
1.141     www      8982: 	&Apache::loncommon::content_type($request,'text/html');
1.41      ng       8983:     }
                   8984:     $request->send_http_header;
1.44      ng       8985:     return '' if $request->header_only;
1.41      ng       8986:     &Apache::loncommon::get_unprocessed_cgi($ENV{'QUERY_STRING'});
1.324     albertel 8987:     my $symb=&get_symb($request,1);
1.160     albertel 8988:     my @commands=&Apache::loncommon::get_env_multiple('form.command');
                   8989:     my $command=$commands[0];
1.447     foxr     8990: 
1.160     albertel 8991:     if ($#commands > 0) {
                   8992: 	&Apache::lonnet::logthis("grades got multiple commands ".join(':',@commands));
                   8993:     }
1.447     foxr     8994: 
1.513     foxr     8995:     $ssi_error = 0;
1.535     raeburn  8996:     my $brcrum = [{href=>"/adm/grades",text=>"Grading"}];
                   8997:     $request->print(&Apache::loncommon::start_page('Grading',undef,
                   8998:                                           {'bread_crumbs' => $brcrum}));
1.324     albertel 8999:     if ($symb eq '' && $command eq '') {
1.257     albertel 9000: 	if ($env{'user.adv'}) {
                   9001: 	    if (($env{'form.codeone'}) && ($env{'form.codetwo'}) &&
                   9002: 		($env{'form.codethree'})) {
                   9003: 		my $token=$env{'form.codeone'}.'*'.$env{'form.codetwo'}.'*'.
                   9004: 		    $env{'form.codethree'};
1.41      ng       9005: 		my ($tsymb,$tuname,$tudom,$tcrsid)=
                   9006: 		    &Apache::lonnet::checkin($token);
                   9007: 		if ($tsymb) {
1.137     albertel 9008: 		    my ($map,$id,$url)=&Apache::lonnet::decode_symb($tsymb);
1.41      ng       9009: 		    if (&Apache::lonnet::allowed('mgr',$tcrsid)) {
1.513     foxr     9010: 			$request->print(&ssi_with_retries('/res/'.$url, $ssi_retries,
1.99      albertel 9011: 					  ('grade_username' => $tuname,
                   9012: 					   'grade_domain' => $tudom,
                   9013: 					   'grade_courseid' => $tcrsid,
                   9014: 					   'grade_symb' => $tsymb)));
1.41      ng       9015: 		    } else {
1.45      ng       9016: 			$request->print('<h3>Not authorized: '.$token.'</h3>');
1.99      albertel 9017: 		    }
1.41      ng       9018: 		} else {
1.45      ng       9019: 		    $request->print('<h3>Not a valid DocID: '.$token.'</h3>');
1.41      ng       9020: 		}
1.14      www      9021: 	    } else {
1.41      ng       9022: 		$request->print(&Apache::lonxml::tokeninputfield());
                   9023: 	    }
                   9024: 	}
                   9025:     } else {
1.285     albertel 9026: 	&init_perm();
1.104     albertel 9027: 	if ($command eq 'submission' && $perm{'vgr'}) {
1.257     albertel 9028: 	    ($env{'form.student'} eq '' ? &listStudents($request) : &submission($request,0,0));
1.103     albertel 9029: 	} elsif ($command eq 'pickStudentPage' && $perm{'vgr'}) {
1.68      ng       9030: 	    &pickStudentPage($request);
1.103     albertel 9031: 	} elsif ($command eq 'displayPage' && $perm{'vgr'}) {
1.68      ng       9032: 	    &displayPage($request);
1.104     albertel 9033: 	} elsif ($command eq 'gradeByPage' && $perm{'mgr'}) {
1.71      ng       9034: 	    &updateGradeByPage($request);
1.104     albertel 9035: 	} elsif ($command eq 'processGroup' && $perm{'vgr'}) {
1.41      ng       9036: 	    &processGroup($request);
1.104     albertel 9037: 	} elsif ($command eq 'gradingmenu' && $perm{'vgr'}) {
1.443     banghart 9038: 	    $request->print(&grading_menu($request));
                   9039: 	} elsif ($command eq 'submit_options' && $perm{'vgr'}) {
                   9040: 	    $request->print(&submit_options($request));
1.104     albertel 9041: 	} elsif ($command eq 'viewgrades' && $perm{'vgr'}) {
1.41      ng       9042: 	    $request->print(&viewgrades($request));
1.104     albertel 9043: 	} elsif ($command eq 'handgrade' && $perm{'mgr'}) {
1.41      ng       9044: 	    $request->print(&processHandGrade($request));
1.106     albertel 9045: 	} elsif ($command eq 'editgrades' && $perm{'mgr'}) {
1.41      ng       9046: 	    $request->print(&editgrades($request));
1.106     albertel 9047: 	} elsif ($command eq 'verify' && $perm{'vgr'}) {
1.41      ng       9048: 	    $request->print(&verifyreceipt($request));
1.400     www      9049:         } elsif ($command eq 'processclicker' && $perm{'mgr'}) {
                   9050:             $request->print(&process_clicker($request));
                   9051:         } elsif ($command eq 'processclickerfile' && $perm{'mgr'}) {
                   9052:             $request->print(&process_clicker_file($request));
1.414     www      9053:         } elsif ($command eq 'assignclickergrades' && $perm{'mgr'}) {
                   9054:             $request->print(&assign_clicker_grades($request));
1.106     albertel 9055: 	} elsif ($command eq 'csvform' && $perm{'mgr'}) {
1.72      ng       9056: 	    $request->print(&upcsvScores_form($request));
1.106     albertel 9057: 	} elsif ($command eq 'csvupload' && $perm{'mgr'}) {
1.41      ng       9058: 	    $request->print(&csvupload($request));
1.106     albertel 9059: 	} elsif ($command eq 'csvuploadmap' && $perm{'mgr'} ) {
1.41      ng       9060: 	    $request->print(&csvuploadmap($request));
1.246     albertel 9061: 	} elsif ($command eq 'csvuploadoptions' && $perm{'mgr'}) {
1.257     albertel 9062: 	    if ($env{'form.associate'} ne 'Reverse Association') {
1.246     albertel 9063: 		$request->print(&csvuploadoptions($request));
1.41      ng       9064: 	    } else {
1.257     albertel 9065: 		if ( $env{'form.upfile_associate'} ne 'reverse' ) {
                   9066: 		    $env{'form.upfile_associate'} = 'reverse';
1.41      ng       9067: 		} else {
1.257     albertel 9068: 		    $env{'form.upfile_associate'} = 'forward';
1.41      ng       9069: 		}
                   9070: 		$request->print(&csvuploadmap($request));
                   9071: 	    }
1.246     albertel 9072: 	} elsif ($command eq 'csvuploadassign' && $perm{'mgr'} ) {
                   9073: 	    $request->print(&csvuploadassign($request));
1.106     albertel 9074: 	} elsif ($command eq 'scantron_selectphase' && $perm{'mgr'}) {
1.75      albertel 9075: 	    $request->print(&scantron_selectphase($request));
1.203     albertel 9076:  	} elsif ($command eq 'scantron_warning' && $perm{'mgr'}) {
                   9077:  	    $request->print(&scantron_do_warning($request));
1.142     albertel 9078: 	} elsif ($command eq 'scantron_validate' && $perm{'mgr'}) {
                   9079: 	    $request->print(&scantron_validate_file($request));
1.106     albertel 9080: 	} elsif ($command eq 'scantron_process' && $perm{'mgr'}) {
1.82      albertel 9081: 	    $request->print(&scantron_process_students($request));
1.157     albertel 9082:  	} elsif ($command eq 'scantronupload' && 
1.257     albertel 9083:  		 (&Apache::lonnet::allowed('usc',$env{'request.role.domain'})||
                   9084: 		  &Apache::lonnet::allowed('usc',$env{'request.course.id'}))) {
1.162     albertel 9085:  	    $request->print(&scantron_upload_scantron_data($request)); 
1.157     albertel 9086:  	} elsif ($command eq 'scantronupload_save' &&
1.257     albertel 9087:  		 (&Apache::lonnet::allowed('usc',$env{'request.role.domain'})||
                   9088: 		  &Apache::lonnet::allowed('usc',$env{'request.course.id'}))) {
1.157     albertel 9089:  	    $request->print(&scantron_upload_scantron_data_save($request));
1.202     albertel 9090:  	} elsif ($command eq 'scantron_download' &&
1.257     albertel 9091: 		 &Apache::lonnet::allowed('usc',$env{'request.course.id'})) {
1.162     albertel 9092:  	    $request->print(&scantron_download_scantron_data($request));
1.523     raeburn  9093:         } elsif ($command eq 'checksubmissions' && $perm{'vgr'}) {
                   9094:             $request->print(&checkscantron_results($request));     
1.106     albertel 9095: 	} elsif ($command) {
1.157     albertel 9096: 	    $request->print("Access Denied ($command)");
1.26      albertel 9097: 	}
1.2       albertel 9098:     }
1.513     foxr     9099:     if ($ssi_error) {
                   9100: 	&ssi_print_error($request);
                   9101:     }
1.353     albertel 9102:     $request->print(&Apache::loncommon::end_page());
1.434     albertel 9103:     &reset_caches();
1.44      ng       9104:     return '';
                   9105: }
                   9106: 
1.1       albertel 9107: 1;
                   9108: 
1.13      albertel 9109: __END__;
1.531     jms      9110: 
                   9111: 
                   9112: =head1 NAME
                   9113: 
                   9114: Apache::grades
                   9115: 
                   9116: =head1 SYNOPSIS
                   9117: 
                   9118: Handles the viewing of grades.
                   9119: 
                   9120: This is part of the LearningOnline Network with CAPA project
                   9121: described at http://www.lon-capa.org.
                   9122: 
                   9123: =head1 OVERVIEW
                   9124: 
                   9125: Do an ssi with retries:
                   9126: While I'd love to factor out this with the vesrion in lonprintout,
                   9127: 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
                   9128: I'm not quite ready to invent (e.g. an ssi_with_retry object).
                   9129: 
                   9130: At least the logic that drives this has been pulled out into loncommon.
                   9131: 
                   9132: 
                   9133: 
                   9134: ssi_with_retries - Does the server side include of a resource.
                   9135:                      if the ssi call returns an error we'll retry it up to
                   9136:                      the number of times requested by the caller.
                   9137:                      If we still have a proble, no text is appended to the
                   9138:                      output and we set some global variables.
                   9139:                      to indicate to the caller an SSI error occurred.  
                   9140:                      All of this is supposed to deal with the issues described
                   9141:                      in LonCAPA BZ 5631 see:
                   9142:                      http://bugs.lon-capa.org/show_bug.cgi?id=5631
                   9143:                      by informing the user that this happened.
                   9144: 
                   9145: Parameters:
                   9146:   resource   - The resource to include.  This is passed directly, without
                   9147:                interpretation to lonnet::ssi.
                   9148:   form       - The form hash parameters that guide the interpretation of the resource
                   9149:                
                   9150:   retries    - Number of retries allowed before giving up completely.
                   9151: Returns:
                   9152:   On success, returns the rendered resource identified by the resource parameter.
                   9153: Side Effects:
                   9154:   The following global variables can be set:
                   9155:    ssi_error                - If an unrecoverable error occurred this becomes true.
                   9156:                               It is up to the caller to initialize this to false
                   9157:                               if desired.
                   9158:    ssi_error_resource  - If an unrecoverable error occurred, this is the value
                   9159:                               of the resource that could not be rendered by the ssi
                   9160:                               call.
                   9161:    ssi_error_message   - The error string fetched from the ssi response
                   9162:                               in the event of an error.
                   9163: 
                   9164: 
                   9165: =head1 HANDLER SUBROUTINE
                   9166: 
                   9167: ssi_with_retries()
                   9168: 
                   9169: =head1 SUBROUTINES
                   9170: 
                   9171: =over
                   9172: 
                   9173: =item scantron_get_correction() : 
                   9174: 
                   9175:    Builds the interface screen to interact with the operator to fix a
                   9176:    specific error condition in a specific scanline
                   9177: 
                   9178:  Arguments:
                   9179:     $r           - Apache request object
                   9180:     $i           - number of the current scanline
                   9181:     $scan_record - hash ref as returned from &scantron_parse_scanline()
                   9182:     $scan_config - hash ref as returned from &get_scantron_config()
                   9183:     $line        - full contents of the current scanline
                   9184:     $error       - error condition, valid values are
                   9185:                    'incorrectCODE', 'duplicateCODE',
                   9186:                    'doublebubble', 'missingbubble',
                   9187:                    'duplicateID', 'incorrectID'
                   9188:     $arg         - extra information needed
                   9189:        For errors:
                   9190:          - duplicateID   - paper number that this studentID was seen before on
                   9191:          - duplicateCODE - array ref of the paper numbers this CODE was
                   9192:                            seen on before
                   9193:          - incorrectCODE - current incorrect CODE 
                   9194:          - doublebubble  - array ref of the bubble lines that have double
                   9195:                            bubble errors
                   9196:          - missingbubble - array ref of the bubble lines that have missing
                   9197:                            bubble errors
                   9198: 
                   9199: =item  scantron_get_maxbubble() : 
                   9200: 
                   9201:    Returns the maximum number of bubble lines that are expected to
                   9202:    occur. Does this by walking the selected sequence rendering the
                   9203:    resource and then checking &Apache::lonxml::get_problem_counter()
                   9204:    for what the current value of the problem counter is.
                   9205: 
                   9206:    Caches the results to $env{'form.scantron_maxbubble'},
                   9207:    $env{'form.scantron.bubble_lines.n'}, 
                   9208:    $env{'form.scantron.first_bubble_line.n'} and
                   9209:    $env{"form.scantron.sub_bubblelines.n"}
                   9210:    which are the total number of bubble, lines, the number of bubble
                   9211:    lines for response n and number of the first bubble line for response n,
                   9212:    and a comma separated list of numbers of bubble lines for sub-questions
                   9213:    (for optionresponse, matchresponse, and rankresponse items), for response n.  
                   9214: 
                   9215: 
                   9216: =item  scantron_validate_missingbubbles() : 
                   9217: 
                   9218:    Validates all scanlines in the selected file to not have any
                   9219:     answers that don't have bubbles that have not been verified
                   9220:     to be bubble free.
                   9221: 
                   9222: =item  scantron_process_students() : 
                   9223: 
                   9224:    Routine that does the actual grading of the bubble sheet information.
                   9225: 
                   9226:    The parsed scanline hash is added to %env 
                   9227: 
                   9228:    Then foreach unskipped scanline it does an &Apache::lonnet::ssi()
                   9229:    foreach resource , with the form data of
                   9230: 
                   9231: 	'submitted'     =>'scantron' 
                   9232: 	'grade_target'  =>'grade',
                   9233: 	'grade_username'=> username of student
                   9234: 	'grade_domain'  => domain of student
                   9235: 	'grade_courseid'=> of course
                   9236: 	'grade_symb'    => symb of resource to grade
                   9237: 
                   9238:     This triggers a grading pass. The problem grading code takes care
                   9239:     of converting the bubbled letter information (now in %env) into a
                   9240:     valid submission.
                   9241: 
                   9242: =item  scantron_upload_scantron_data() :
                   9243: 
                   9244:     Creates the screen for adding a new bubble sheet data file to a course.
                   9245: 
                   9246: =item  scantron_upload_scantron_data_save() : 
                   9247: 
                   9248:    Adds a provided bubble information data file to the course if user
                   9249:    has the correct privileges to do so. 
                   9250: 
                   9251: =item  valid_file() :
                   9252: 
                   9253:    Validates that the requested bubble data file exists in the course.
                   9254: 
                   9255: =item  scantron_download_scantron_data() : 
                   9256: 
                   9257:    Shows a list of the three internal files (original, corrected,
                   9258:    skipped) for a specific bubble sheet data file that exists in the
                   9259:    course.
                   9260: 
                   9261: =item  scantron_validate_ID() : 
                   9262: 
                   9263:    Validates all scanlines in the selected file to not have any
1.556     weissno  9264:    invalid or underspecified student/employee IDs
1.531     jms      9265: 
                   9266: =back
                   9267: 
                   9268: =cut

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