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

1.17      albertel    1: # The LearningOnline Network with CAPA
1.13      albertel    2: # The LON-CAPA Grading handler
1.17      albertel    3: #
1.613   ! www         4: # $Id: grades.pm,v 1.612 2010/04/12 13:11:42 www 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.598     www        99: # Returns an array of everything that the resources stores away
                    100: #
                    101: 
1.44      ng        102: sub getpartlist {
1.582     raeburn   103:     my ($symb,$errorref) = @_;
1.439     albertel  104: 
                    105:     my $navmap   = Apache::lonnavmaps::navmap->new();
1.582     raeburn   106:     unless (ref($navmap)) {
                    107:         if (ref($errorref)) { 
                    108:             $$errorref = 'navmap';
                    109:             return;
                    110:         }
                    111:     }
1.439     albertel  112:     my $res      = $navmap->getBySymb($symb);
                    113:     my $partlist = $res->parts();
                    114:     my $url      = $res->src();
                    115:     my @metakeys = split(/,/,&Apache::lonnet::metadata($url,'keys'));
                    116: 
1.146     albertel  117:     my @stores;
1.439     albertel  118:     foreach my $part (@{ $partlist }) {
1.146     albertel  119: 	foreach my $key (@metakeys) {
                    120: 	    if ($key =~ m/^stores_\Q$part\E_/) { push(@stores,$key); }
                    121: 	}
                    122:     }
                    123:     return @stores;
1.2       albertel  124: }
                    125: 
1.129     ng        126: #--- Format fullname, username:domain if different for display
                    127: #--- Use anywhere where the student names are listed
                    128: sub nameUserString {
                    129:     my ($type,$fullname,$uname,$udom) = @_;
                    130:     if ($type eq 'header') {
1.485     albertel  131: 	return '<b>&nbsp;'.&mt('Fullname').'&nbsp;</b><span class="LC_internal_info">('.&mt('Username').')</span>';
1.129     ng        132:     } else {
1.398     albertel  133: 	return '&nbsp;'.$fullname.'<span class="LC_internal_info">&nbsp;('.$uname.
                    134: 	    ($env{'user.domain'} eq $udom ? '' : ' ('.$udom.')').')</span>';
1.129     ng        135:     }
                    136: }
                    137: 
1.44      ng        138: #--- Get the partlist and the response type for a given problem. ---
                    139: #--- Indicate if a response type is coded handgraded or not. ---
1.39      ng        140: sub response_type {
1.582     raeburn   141:     my ($symb,$response_error) = @_;
1.377     albertel  142: 
                    143:     my $navmap = Apache::lonnavmaps::navmap->new();
1.582     raeburn   144:     unless (ref($navmap)) {
                    145:         if (ref($response_error)) {
                    146:             $$response_error = 1;
                    147:         }
                    148:         return;
                    149:     }
1.377     albertel  150:     my $res = $navmap->getBySymb($symb);
1.593     raeburn   151:     unless (ref($res)) {
                    152:         $$response_error = 1;
                    153:         return;
                    154:     }
1.377     albertel  155:     my $partlist = $res->parts();
1.392     albertel  156:     my %vPart = 
                    157: 	map { $_ => 1 } (&Apache::loncommon::get_env_multiple('form.vPart'));
1.377     albertel  158:     my (%response_types,%handgrade);
                    159:     foreach my $part (@{ $partlist }) {
1.392     albertel  160: 	next if (%vPart && !exists($vPart{$part}));
                    161: 
1.377     albertel  162: 	my @types = $res->responseType($part);
                    163: 	my @ids = $res->responseIds($part);
                    164: 	for (my $i=0; $i < scalar(@ids); $i++) {
                    165: 	    $response_types{$part}{$ids[$i]} = $types[$i];
                    166: 	    $handgrade{$part.'_'.$ids[$i]} = 
                    167: 		&Apache::lonnet::EXT('resource.'.$part.'_'.$ids[$i].
                    168: 				     '.handgrade',$symb);
1.41      ng        169: 	}
                    170:     }
1.377     albertel  171:     return ($partlist,\%handgrade,\%response_types);
1.39      ng        172: }
                    173: 
1.375     albertel  174: sub flatten_responseType {
                    175:     my ($responseType) = @_;
                    176:     my @part_response_id =
                    177: 	map { 
                    178: 	    my $part = $_;
                    179: 	    map {
                    180: 		[$part,$_]
                    181: 		} sort(keys(%{ $responseType->{$part} }));
                    182: 	} sort(keys(%$responseType));
                    183:     return @part_response_id;
                    184: }
                    185: 
1.207     albertel  186: sub get_display_part {
1.324     albertel  187:     my ($partID,$symb)=@_;
1.207     albertel  188:     my $display=&Apache::lonnet::EXT('resource.'.$partID.'.display',$symb);
                    189:     if (defined($display) and $display ne '') {
1.577     bisitz    190:         $display.= ' (<span class="LC_internal_info">'
                    191:                   .&mt('Part ID: [_1]',$partID).'</span>)';
1.207     albertel  192:     } else {
                    193: 	$display=$partID;
                    194:     }
                    195:     return $display;
                    196: }
1.269     raeburn   197: 
1.434     albertel  198: sub reset_caches {
                    199:     &reset_analyze_cache();
                    200:     &reset_perm();
                    201: }
                    202: 
                    203: {
                    204:     my %analyze_cache;
1.557     raeburn   205:     my %analyze_cache_formkeys;
1.148     albertel  206: 
1.434     albertel  207:     sub reset_analyze_cache {
                    208: 	undef(%analyze_cache);
1.557     raeburn   209:         undef(%analyze_cache_formkeys);
1.434     albertel  210:     }
                    211: 
                    212:     sub get_analyze {
1.557     raeburn   213: 	my ($symb,$uname,$udom,$no_increment,$add_to_hash)=@_;
1.434     albertel  214: 	my $key = "$symb\0$uname\0$udom";
1.557     raeburn   215: 	if (exists($analyze_cache{$key})) {
                    216:             my $getupdate = 0;
                    217:             if (ref($add_to_hash) eq 'HASH') {
                    218:                 foreach my $item (keys(%{$add_to_hash})) {
                    219:                     if (ref($analyze_cache_formkeys{$key}) eq 'HASH') {
                    220:                         if (!exists($analyze_cache_formkeys{$key}{$item})) {
                    221:                             $getupdate = 1;
                    222:                             last;
                    223:                         }
                    224:                     } else {
                    225:                         $getupdate = 1;
                    226:                     }
                    227:                 }
                    228:             }
                    229:             if (!$getupdate) {
                    230:                 return $analyze_cache{$key};
                    231:             }
                    232:         }
1.434     albertel  233: 
                    234: 	my (undef,undef,$url)=&Apache::lonnet::decode_symb($symb);
                    235: 	$url=&Apache::lonnet::clutter($url);
1.557     raeburn   236:         my %form = ('grade_target'      => 'analyze',
                    237:                     'grade_domain'      => $udom,
                    238:                     'grade_symb'        => $symb,
                    239:                     'grade_courseid'    =>  $env{'request.course.id'},
                    240:                     'grade_username'    => $uname,
                    241:                     'grade_noincrement' => $no_increment);
                    242:         if (ref($add_to_hash)) {
                    243:             %form = (%form,%{$add_to_hash});
                    244:         } 
                    245: 	my $subresult=&ssi_with_retries($url, $ssi_retries,%form);
1.434     albertel  246: 	(undef,$subresult)=split(/_HASH_REF__/,$subresult,2);
                    247: 	my %analyze=&Apache::lonnet::str2hash($subresult);
1.557     raeburn   248:         if (ref($add_to_hash) eq 'HASH') {
                    249:             $analyze_cache_formkeys{$key} = $add_to_hash;
                    250:         } else {
                    251:             $analyze_cache_formkeys{$key} = {};
                    252:         }
1.434     albertel  253: 	return $analyze_cache{$key} = \%analyze;
                    254:     }
                    255: 
                    256:     sub get_order {
1.525     raeburn   257: 	my ($partid,$respid,$symb,$uname,$udom,$no_increment)=@_;
                    258: 	my $analyze = &get_analyze($symb,$uname,$udom,$no_increment);
1.434     albertel  259: 	return $analyze->{"$partid.$respid.shown"};
                    260:     }
                    261: 
                    262:     sub get_radiobutton_correct_foil {
                    263: 	my ($partid,$respid,$symb,$uname,$udom)=@_;
                    264: 	my $analyze = &get_analyze($symb,$uname,$udom);
1.555     raeburn   265:         my $foils = &get_order($partid,$respid,$symb,$uname,$udom);
                    266:         if (ref($foils) eq 'ARRAY') {
                    267: 	    foreach my $foil (@{$foils}) {
                    268: 	        if ($analyze->{"$partid.$respid.foil.value.$foil"} eq 'true') {
                    269: 		    return $foil;
                    270: 	        }
1.434     albertel  271: 	    }
                    272: 	}
                    273:     }
1.554     raeburn   274: 
                    275:     sub scantron_partids_tograde {
1.557     raeburn   276:         my ($resource,$cid,$uname,$udom,$check_for_randomlist) = @_;
1.554     raeburn   277:         my (%analysis,@parts);
                    278:         if (ref($resource)) {
                    279:             my $symb = $resource->symb();
1.557     raeburn   280:             my $add_to_form;
                    281:             if ($check_for_randomlist) {
                    282:                 $add_to_form = { 'check_parts_withrandomlist' => 1,};
                    283:             }
                    284:             my $analyze = &get_analyze($symb,$uname,$udom,undef,$add_to_form);
1.554     raeburn   285:             if (ref($analyze) eq 'HASH') {
                    286:                 %analysis = %{$analyze};
                    287:             }
                    288:             if (ref($analysis{'parts'}) eq 'ARRAY') {
                    289:                 foreach my $part (@{$analysis{'parts'}}) {
                    290:                     my ($id,$respid) = split(/\./,$part);
                    291:                     if (!&Apache::loncommon::check_if_partid_hidden($id,$symb,$udom,$uname)) {
                    292:                         push(@parts,$part);
                    293:                     }
                    294:                 }
                    295:             }
                    296:         }
                    297:         return (\%analysis,\@parts);
                    298:     }
                    299: 
1.148     albertel  300: }
1.434     albertel  301: 
1.118     ng        302: #--- Clean response type for display
1.335     albertel  303: #--- Currently filters option/rank/radiobutton/match/essay/Task
                    304: #        response types only.
1.118     ng        305: sub cleanRecord {
1.336     albertel  306:     my ($answer,$response,$symb,$partid,$respid,$record,$order,$version,
                    307: 	$uname,$udom) = @_;
1.398     albertel  308:     my $grayFont = '<span class="LC_internal_info">';
1.148     albertel  309:     if ($response =~ /^(option|rank)$/) {
                    310: 	my %answer=&Apache::lonnet::str2hash($answer);
                    311: 	my %grading=&Apache::lonnet::str2hash($record->{$version."resource.$partid.$respid.submissiongrading"});
                    312: 	my ($toprow,$bottomrow);
                    313: 	foreach my $foil (@$order) {
                    314: 	    if ($grading{$foil} == 1) {
                    315: 		$toprow.='<td><b>'.$answer{$foil}.'&nbsp;</b></td>';
                    316: 	    } else {
                    317: 		$toprow.='<td><i>'.$answer{$foil}.'&nbsp;</i></td>';
                    318: 	    }
1.398     albertel  319: 	    $bottomrow.='<td>'.$grayFont.$foil.'</span>&nbsp;</td>';
1.148     albertel  320: 	}
                    321: 	return '<blockquote><table border="1">'.
1.466     albertel  322: 	    '<tr valign="top"><td>'.&mt('Answer').'</td>'.$toprow.'</tr>'.
                    323: 	    '<tr valign="top"><td>'.$grayFont.&mt('Option ID').'</span></td>'.
1.148     albertel  324: 	    $grayFont.$bottomrow.'</tr>'.'</table></blockquote>';
                    325:     } elsif ($response eq 'match') {
                    326: 	my %answer=&Apache::lonnet::str2hash($answer);
                    327: 	my %grading=&Apache::lonnet::str2hash($record->{$version."resource.$partid.$respid.submissiongrading"});
                    328: 	my @items=&Apache::lonnet::str2array($record->{$version."resource.$partid.$respid.submissionitems"});
                    329: 	my ($toprow,$middlerow,$bottomrow);
                    330: 	foreach my $foil (@$order) {
                    331: 	    my $item=shift(@items);
                    332: 	    if ($grading{$foil} == 1) {
                    333: 		$toprow.='<td><b>'.$item.'&nbsp;</b></td>';
1.398     albertel  334: 		$middlerow.='<td><b>'.$grayFont.$answer{$foil}.'&nbsp;</span></b></td>';
1.148     albertel  335: 	    } else {
                    336: 		$toprow.='<td><i>'.$item.'&nbsp;</i></td>';
1.398     albertel  337: 		$middlerow.='<td><i>'.$grayFont.$answer{$foil}.'&nbsp;</span></i></td>';
1.148     albertel  338: 	    }
1.398     albertel  339: 	    $bottomrow.='<td>'.$grayFont.$foil.'</span>&nbsp;</td>';
1.118     ng        340: 	}
1.126     ng        341: 	return '<blockquote><table border="1">'.
1.466     albertel  342: 	    '<tr valign="top"><td>'.&mt('Answer').'</td>'.$toprow.'</tr>'.
                    343: 	    '<tr valign="top"><td>'.$grayFont.&mt('Item ID').'</span></td>'.
1.148     albertel  344: 	    $middlerow.'</tr>'.
1.466     albertel  345: 	    '<tr valign="top"><td>'.$grayFont.&mt('Option ID').'</span></td>'.
1.148     albertel  346: 	    $bottomrow.'</tr>'.'</table></blockquote>';
                    347:     } elsif ($response eq 'radiobutton') {
                    348: 	my %answer=&Apache::lonnet::str2hash($answer);
                    349: 	my ($toprow,$bottomrow);
1.434     albertel  350: 	my $correct = 
                    351: 	    &get_radiobutton_correct_foil($partid,$respid,$symb,$uname,$udom);
                    352: 	foreach my $foil (@$order) {
1.148     albertel  353: 	    if (exists($answer{$foil})) {
1.434     albertel  354: 		if ($foil eq $correct) {
1.466     albertel  355: 		    $toprow.='<td><b>'.&mt('true').'</b></td>';
1.148     albertel  356: 		} else {
1.466     albertel  357: 		    $toprow.='<td><i>'.&mt('true').'</i></td>';
1.148     albertel  358: 		}
                    359: 	    } else {
1.466     albertel  360: 		$toprow.='<td>'.&mt('false').'</td>';
1.148     albertel  361: 	    }
1.398     albertel  362: 	    $bottomrow.='<td>'.$grayFont.$foil.'</span>&nbsp;</td>';
1.148     albertel  363: 	}
                    364: 	return '<blockquote><table border="1">'.
1.466     albertel  365: 	    '<tr valign="top"><td>'.&mt('Answer').'</td>'.$toprow.'</tr>'.
                    366: 	    '<tr valign="top"><td>'.$grayFont.&mt('Option ID').'</span></td>'.
1.597     wenzelju  367: 	    $bottomrow.'</tr>'.'</table></blockquote>';
1.148     albertel  368:     } elsif ($response eq 'essay') {
1.257     albertel  369: 	if (! exists ($env{'form.'.$symb})) {
1.122     ng        370: 	    my (%keyhash) = &Apache::lonnet::dump('nohist_handgrade',
1.257     albertel  371: 						  $env{'course.'.$env{'request.course.id'}.'.domain'},
                    372: 						  $env{'course.'.$env{'request.course.id'}.'.num'});
1.122     ng        373: 
1.257     albertel  374: 	    my $loginuser = $env{'user.name'}.':'.$env{'user.domain'};
                    375: 	    $env{'form.keywords'} = $keyhash{$symb.'_keywords'} ne '' ? $keyhash{$symb.'_keywords'} : '';
                    376: 	    $env{'form.kwclr'}    = $keyhash{$loginuser.'_kwclr'} ne '' ? $keyhash{$loginuser.'_kwclr'} : 'red';
                    377: 	    $env{'form.kwsize'}   = $keyhash{$loginuser.'_kwsize'} ne '' ? $keyhash{$loginuser.'_kwsize'} : '0';
                    378: 	    $env{'form.kwstyle'}  = $keyhash{$loginuser.'_kwstyle'} ne '' ? $keyhash{$loginuser.'_kwstyle'} : '';
                    379: 	    $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        380: 	}
1.166     albertel  381: 	$answer =~ s-\n-<br />-g;
                    382: 	return '<br /><br /><blockquote><tt>'.&keywords_highlight($answer).'</tt></blockquote>';
1.268     albertel  383:     } elsif ( $response eq 'organic') {
                    384: 	my $result='Smile representation: "<tt>'.$answer.'</tt>"';
                    385: 	my $jme=$record->{$version."resource.$partid.$respid.molecule"};
                    386: 	$result.=&Apache::chemresponse::jme_img($jme,$answer,400);
                    387: 	return $result;
1.335     albertel  388:     } elsif ( $response eq 'Task') {
                    389: 	if ( $answer eq 'SUBMITTED') {
                    390: 	    my $files = $record->{$version."resource.$respid.$partid.bridgetask.portfiles"};
1.336     albertel  391: 	    my $result = &Apache::bridgetask::file_list($files,$uname,$udom);
1.335     albertel  392: 	    return $result;
                    393: 	} elsif ( grep(/^\Q$version\E.*?\.instance$/, keys(%{$record})) ) {
                    394: 	    my @matches = grep(/^\Q$version\E.*?\.instance$/,
                    395: 			       keys(%{$record}));
                    396: 	    return join('<br />',($version,@matches));
                    397: 			       
                    398: 			       
                    399: 	} else {
                    400: 	    my $result =
                    401: 		'<p>'
                    402: 		.&mt('Overall result: [_1]',
                    403: 		     $record->{$version."resource.$respid.$partid.status"})
                    404: 		.'</p>';
                    405: 	    
                    406: 	    $result .= '<ul>';
                    407: 	    my @grade = grep(/^\Q${version}resource.$respid.$partid.\E[^.]*[.]status$/,
                    408: 			     keys(%{$record}));
                    409: 	    foreach my $grade (sort(@grade)) {
                    410: 		my ($dim) = ($grade =~/[.]([^.]+)[.]status$/);
                    411: 		$result.= '<li>'.&mt("Dimension: [_1], status [_2] ",
                    412: 				     $dim, $record->{$grade}).
                    413: 			  '</li>';
                    414: 	    }
                    415: 	    $result.='</ul>';
                    416: 	    return $result;
                    417: 	}
1.440     albertel  418:     } elsif ( $response =~ m/(?:numerical|formula)/) {
                    419: 	$answer = 
                    420: 	    &Apache::loncommon::format_previous_attempt_value('submission',
                    421: 							      $answer);
1.122     ng        422:     }
1.118     ng        423:     return $answer;
                    424: }
                    425: 
                    426: #-- A couple of common js functions
                    427: sub commonJSfunctions {
                    428:     my $request = shift;
1.597     wenzelju  429:     $request->print(&Apache::lonhtmlcommon::scripttag(<<COMMONJSFUNCTIONS));
1.118     ng        430:     function radioSelection(radioButton) {
                    431: 	var selection=null;
                    432: 	if (radioButton.length > 1) {
                    433: 	    for (var i=0; i<radioButton.length; i++) {
                    434: 		if (radioButton[i].checked) {
                    435: 		    return radioButton[i].value;
                    436: 		}
                    437: 	    }
                    438: 	} else {
                    439: 	    if (radioButton.checked) return radioButton.value;
                    440: 	}
                    441: 	return selection;
                    442:     }
                    443: 
                    444:     function pullDownSelection(selectOne) {
                    445: 	var selection="";
                    446: 	if (selectOne.length > 1) {
                    447: 	    for (var i=0; i<selectOne.length; i++) {
                    448: 		if (selectOne[i].selected) {
                    449: 		    return selectOne[i].value;
                    450: 		}
                    451: 	    }
                    452: 	} else {
1.138     albertel  453:             // only one value it must be the selected one
                    454: 	    return selectOne.value;
1.118     ng        455: 	}
                    456:     }
                    457: COMMONJSFUNCTIONS
                    458: }
                    459: 
1.44      ng        460: #--- Dumps the class list with usernames,list of sections,
                    461: #--- section, ids and fullnames for each user.
                    462: sub getclasslist {
1.449     banghart  463:     my ($getsec,$filterlist,$getgroup) = @_;
1.291     albertel  464:     my @getsec;
1.450     banghart  465:     my @getgroup;
1.442     banghart  466:     my $stu_status = join(':',&Apache::loncommon::get_env_multiple('form.Status'));
1.291     albertel  467:     if (!ref($getsec)) {
                    468: 	if ($getsec ne '' && $getsec ne 'all') {
                    469: 	    @getsec=($getsec);
                    470: 	}
                    471:     } else {
                    472: 	@getsec=@{$getsec};
                    473:     }
                    474:     if (grep(/^all$/,@getsec)) { undef(@getsec); }
1.450     banghart  475:     if (!ref($getgroup)) {
                    476: 	if ($getgroup ne '' && $getgroup ne 'all') {
                    477: 	    @getgroup=($getgroup);
                    478: 	}
                    479:     } else {
                    480: 	@getgroup=@{$getgroup};
                    481:     }
                    482:     if (grep(/^all$/,@getgroup)) { undef(@getgroup); }
1.291     albertel  483: 
1.449     banghart  484:     my ($classlist,$keylist)=&Apache::loncoursedata::get_classlist();
1.49      albertel  485:     # Bail out if we were unable to get the classlist
1.56      matthew   486:     return if (! defined($classlist));
1.449     banghart  487:     &Apache::loncoursedata::get_group_memberships($classlist,$keylist);
1.56      matthew   488:     #
                    489:     my %sections;
                    490:     my %fullnames;
1.205     matthew   491:     foreach my $student (keys(%$classlist)) {
                    492:         my $end      = 
                    493:             $classlist->{$student}->[&Apache::loncoursedata::CL_END()];
                    494:         my $start    = 
                    495:             $classlist->{$student}->[&Apache::loncoursedata::CL_START()];
                    496:         my $id       = 
                    497:             $classlist->{$student}->[&Apache::loncoursedata::CL_ID()];
                    498:         my $section  = 
                    499:             $classlist->{$student}->[&Apache::loncoursedata::CL_SECTION()];
                    500:         my $fullname = 
                    501:             $classlist->{$student}->[&Apache::loncoursedata::CL_FULLNAME()];
                    502:         my $status   = 
                    503:             $classlist->{$student}->[&Apache::loncoursedata::CL_STATUS()];
1.449     banghart  504:         my $group   = 
                    505:             $classlist->{$student}->[&Apache::loncoursedata::CL_GROUP()];
1.76      ng        506: 	# filter students according to status selected
1.442     banghart  507: 	if ($filterlist && (!($stu_status =~ /Any/))) {
                    508: 	    if (!($stu_status =~ $status)) {
1.450     banghart  509: 		delete($classlist->{$student});
1.76      ng        510: 		next;
                    511: 	    }
                    512: 	}
1.450     banghart  513: 	# filter students according to groups selected
1.453     banghart  514: 	my @stu_groups = split(/,/,$group);
1.450     banghart  515: 	if (@getgroup) {
                    516: 	    my $exclude = 1;
1.454     banghart  517: 	    foreach my $grp (@getgroup) {
                    518: 	        foreach my $stu_group (@stu_groups) {
1.453     banghart  519: 	            if ($stu_group eq $grp) {
                    520: 	                $exclude = 0;
                    521:     	            } 
1.450     banghart  522: 	        }
1.453     banghart  523:     	        if (($grp eq 'none') && !$group) {
                    524:         	        $exclude = 0;
                    525:         	}
1.450     banghart  526: 	    }
                    527: 	    if ($exclude) {
                    528: 	        delete($classlist->{$student});
                    529: 	    }
                    530: 	}
1.205     matthew   531: 	$section = ($section ne '' ? $section : 'none');
1.106     albertel  532: 	if (&canview($section)) {
1.291     albertel  533: 	    if (!@getsec || grep(/^\Q$section\E$/,@getsec)) {
1.103     albertel  534: 		$sections{$section}++;
1.450     banghart  535: 		if ($classlist->{$student}) {
                    536: 		    $fullnames{$student}=$fullname;
                    537: 		}
1.103     albertel  538: 	    } else {
1.205     matthew   539: 		delete($classlist->{$student});
1.103     albertel  540: 	    }
                    541: 	} else {
1.205     matthew   542: 	    delete($classlist->{$student});
1.103     albertel  543: 	}
1.44      ng        544:     }
                    545:     my %seen = ();
1.56      matthew   546:     my @sections = sort(keys(%sections));
                    547:     return ($classlist,\@sections,\%fullnames);
1.44      ng        548: }
                    549: 
1.103     albertel  550: sub canmodify {
                    551:     my ($sec)=@_;
                    552:     if ($perm{'mgr'}) {
                    553: 	if (!defined($perm{'mgr_section'})) {
                    554: 	    # can modify whole class
                    555: 	    return 1;
                    556: 	} else {
                    557: 	    if ($sec eq $perm{'mgr_section'}) {
                    558: 		#can modify the requested section
                    559: 		return 1;
                    560: 	    } else {
                    561: 		# can't modify the request section
                    562: 		return 0;
                    563: 	    }
                    564: 	}
                    565:     }
                    566:     #can't modify
                    567:     return 0;
                    568: }
                    569: 
                    570: sub canview {
                    571:     my ($sec)=@_;
                    572:     if ($perm{'vgr'}) {
                    573: 	if (!defined($perm{'vgr_section'})) {
                    574: 	    # can modify whole class
                    575: 	    return 1;
                    576: 	} else {
                    577: 	    if ($sec eq $perm{'vgr_section'}) {
                    578: 		#can modify the requested section
                    579: 		return 1;
                    580: 	    } else {
                    581: 		# can't modify the request section
                    582: 		return 0;
                    583: 	    }
                    584: 	}
                    585:     }
                    586:     #can't modify
                    587:     return 0;
                    588: }
                    589: 
1.44      ng        590: #--- Retrieve the grade status of a student for all the parts
                    591: sub student_gradeStatus {
1.324     albertel  592:     my ($symb,$udom,$uname,$partlist) = @_;
1.257     albertel  593:     my %record     = &Apache::lonnet::restore($symb,$env{'request.course.id'},$udom,$uname);
1.44      ng        594:     my %partstatus = ();
                    595:     foreach (@$partlist) {
1.128     ng        596: 	my ($status,undef)   = split(/_/,$record{"resource.$_.solved"},2);
1.44      ng        597: 	$status              = 'nothing' if ($status eq '');
                    598: 	$partstatus{$_}      = $status;
                    599: 	my $subkey           = "resource.$_.submitted_by";
                    600: 	$partstatus{$subkey} = $record{$subkey} if ($record{$subkey} ne '');
                    601:     }
                    602:     return %partstatus;
                    603: }
                    604: 
1.45      ng        605: # hidden form and javascript that calls the form
                    606: # Use by verifyscript and viewgrades
                    607: # Shows a student's view of problem and submission
                    608: sub jscriptNform {
1.324     albertel  609:     my ($symb) = @_;
1.442     banghart  610:     my $stu_status = join(':',&Apache::loncommon::get_env_multiple('form.Status'));
1.597     wenzelju  611:     my $jscript= &Apache::lonhtmlcommon::scripttag(
1.45      ng        612: 	'    function viewOneStudent(user,domain) {'."\n".
                    613: 	'	document.onestudent.student.value = user;'."\n".
                    614: 	'	document.onestudent.userdom.value = domain;'."\n".
                    615: 	'	document.onestudent.submit();'."\n".
                    616: 	'    }'."\n".
1.597     wenzelju  617: 	"\n");
1.45      ng        618:     $jscript.= '<form action="/adm/grades" method="post" name="onestudent">'."\n".
1.418     albertel  619: 	'<input type="hidden" name="symb"    value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
1.442     banghart  620: 	'<input type="hidden" name="Status"  value="'.$stu_status.'" />'."\n".
1.45      ng        621: 	'<input type="hidden" name="command" value="submission" />'."\n".
                    622: 	'<input type="hidden" name="student" value="" />'."\n".
                    623: 	'<input type="hidden" name="userdom" value="" />'."\n".
                    624: 	'</form>'."\n";
                    625:     return $jscript;
                    626: }
1.39      ng        627: 
1.447     foxr      628: 
                    629: 
1.315     bowersj2  630: # Given the score (as a number [0-1] and the weight) what is the final
                    631: # point value? This function will round to the nearest tenth, third,
                    632: # or quarter if one of those is within the tolerance of .00001.
1.316     albertel  633: sub compute_points {
1.315     bowersj2  634:     my ($score, $weight) = @_;
                    635:     
                    636:     my $tolerance = .00001;
                    637:     my $points = $score * $weight;
                    638: 
                    639:     # Check for nearness to 1/x.
                    640:     my $check_for_nearness = sub {
                    641:         my ($factor) = @_;
                    642:         my $num = ($points * $factor) + $tolerance;
                    643:         my $floored_num = floor($num);
1.316     albertel  644:         if ($num - $floored_num < 2 * $tolerance * $factor) {
1.315     bowersj2  645:             return $floored_num / $factor;
                    646:         }
                    647:         return $points;
                    648:     };
                    649: 
                    650:     $points = $check_for_nearness->(10);
                    651:     $points = $check_for_nearness->(3);
                    652:     $points = $check_for_nearness->(4);
                    653:     
                    654:     return $points;
                    655: }
                    656: 
1.44      ng        657: #------------------ End of general use routines --------------------
1.87      www       658: 
                    659: #
                    660: # Find most similar essay
                    661: #
                    662: 
                    663: sub most_similar {
1.426     albertel  664:     my ($uname,$udom,$uessay,$old_essays)=@_;
1.87      www       665: 
                    666: # ignore spaces and punctuation
                    667: 
                    668:     $uessay=~s/\W+/ /gs;
                    669: 
1.282     www       670: # ignore empty submissions (occuring when only files are sent)
                    671: 
1.598     www       672:     unless ($uessay=~/\w+/s) { return ''; }
1.282     www       673: 
1.87      www       674: # these will be returned. Do not care if not at least 50 percent similar
1.88      www       675:     my $limit=0.6;
1.87      www       676:     my $sname='';
                    677:     my $sdom='';
                    678:     my $scrsid='';
                    679:     my $sessay='';
                    680: # go through all essays ...
1.426     albertel  681:     foreach my $tkey (keys(%$old_essays)) {
                    682: 	my ($tname,$tdom,$tcrsid)=map {&unescape($_)} (split(/\./,$tkey));
1.87      www       683: # ... except the same student
1.426     albertel  684:         next if (($tname eq $uname) && ($tdom eq $udom));
                    685: 	my $tessay=$old_essays->{$tkey};
                    686: 	$tessay=~s/\W+/ /gs;
1.87      www       687: # String similarity gives up if not even limit
1.426     albertel  688: 	my $tsimilar=&String::Similarity::similarity($uessay,$tessay,$limit);
1.87      www       689: # Found one
1.426     albertel  690: 	if ($tsimilar>$limit) {
                    691: 	    $limit=$tsimilar;
                    692: 	    $sname=$tname;
                    693: 	    $sdom=$tdom;
                    694: 	    $scrsid=$tcrsid;
                    695: 	    $sessay=$old_essays->{$tkey};
                    696: 	}
1.87      www       697:     }
1.88      www       698:     if ($limit>0.6) {
1.87      www       699:        return ($sname,$sdom,$scrsid,$sessay,$limit);
                    700:     } else {
                    701:        return ('','','','',0);
                    702:     }
                    703: }
                    704: 
1.44      ng        705: #-------------------------------------------------------------------
                    706: 
                    707: #------------------------------------ Receipt Verification Routines
1.45      ng        708: #
1.602     www       709: 
                    710: sub initialverifyreceipt {
1.608     www       711:    my ($request,$symb) = @_;
1.602     www       712:    &commonJSfunctions($request);
1.605     www       713:    return '<form name="gradingMenu"><input type="submit" value="'.&mt('Verify Receipt Number.').'" />'.
1.602     www       714:         &Apache::lonnet::recprefix($env{'request.course.id'}).
                    715:         '-<input type="text" name="receipt" size="4" />'.
1.603     www       716:         '<input type="hidden" name="symb" value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
                    717:         '<input type="hidden" name="command" value="verify" />'.
                    718:         "</form>\n";
1.602     www       719: }
                    720: 
1.44      ng        721: #--- Check whether a receipt number is valid.---
                    722: sub verifyreceipt {
1.608     www       723:     my ($request,$symb)  = @_;
1.44      ng        724: 
1.257     albertel  725:     my $courseid = $env{'request.course.id'};
1.184     www       726:     my $receipt  = &Apache::lonnet::recprefix($courseid).'-'.
1.257     albertel  727: 	$env{'form.receipt'};
1.44      ng        728:     $receipt     =~ s/[^\-\d]//g;
                    729: 
1.487     albertel  730:     my $title.=
                    731: 	'<h3><span class="LC_info">'.
1.605     www       732: 	&mt('Verifying Receipt Number [_1]',$receipt).
                    733: 	'</span></h3>'."\n";
1.44      ng        734: 
                    735:     my ($string,$contents,$matches) = ('','',0);
1.56      matthew   736:     my (undef,undef,$fullname) = &getclasslist('all','0');
1.177     albertel  737:     
                    738:     my $receiptparts=0;
1.390     albertel  739:     if ($env{"course.$courseid.receiptalg"} eq 'receipt2' ||
                    740: 	$env{"course.$courseid.receiptalg"} eq 'receipt3') { $receiptparts=1; }
1.177     albertel  741:     my $parts=['0'];
1.582     raeburn   742:     if ($receiptparts) {
                    743:         my $res_error; 
                    744:         ($parts)=&response_type($symb,\$res_error);
                    745:         if ($res_error) {
                    746:             return &navmap_errormsg();
                    747:         } 
                    748:     }
1.486     albertel  749:     
                    750:     my $header = 
                    751: 	&Apache::loncommon::start_data_table().
                    752: 	&Apache::loncommon::start_data_table_header_row().
1.487     albertel  753: 	'<th>&nbsp;'.&mt('Fullname').'&nbsp;</th>'."\n".
                    754: 	'<th>&nbsp;'.&mt('Username').'&nbsp;</th>'."\n".
                    755: 	'<th>&nbsp;'.&mt('Domain').'&nbsp;</th>';
1.486     albertel  756:     if ($receiptparts) {
1.487     albertel  757: 	$header.='<th>&nbsp;'.&mt('Problem Part').'&nbsp;</th>';
1.486     albertel  758:     }
                    759:     $header.=
                    760: 	&Apache::loncommon::end_data_table_header_row();
                    761: 
1.294     albertel  762:     foreach (sort 
                    763: 	     {
                    764: 		 if (lc($$fullname{$a}) ne lc($$fullname{$b})) {
                    765: 		     return (lc($$fullname{$a}) cmp lc($$fullname{$b}));
                    766: 		 }
                    767: 		 return $a cmp $b;
                    768: 	     } (keys(%$fullname))) {
1.44      ng        769: 	my ($uname,$udom)=split(/\:/);
1.177     albertel  770: 	foreach my $part (@$parts) {
                    771: 	    if ($receipt eq &Apache::lonnet::ireceipt($uname,$udom,$courseid,$symb,$part)) {
1.486     albertel  772: 		$contents.=
                    773: 		    &Apache::loncommon::start_data_table_row().
                    774: 		    '<td>&nbsp;'."\n".
1.177     albertel  775: 		    '<a href="javascript:viewOneStudent(\''.$uname.'\',\''.$udom.
1.417     albertel  776: 		    '\');" target="_self">'.$$fullname{$_}.'</a>&nbsp;</td>'."\n".
1.177     albertel  777: 		    '<td>&nbsp;'.$uname.'&nbsp;</td>'.
                    778: 		    '<td>&nbsp;'.$udom.'&nbsp;</td>';
                    779: 		if ($receiptparts) {
                    780: 		    $contents.='<td>&nbsp;'.$part.'&nbsp;</td>';
                    781: 		}
1.486     albertel  782: 		$contents.= 
                    783: 		    &Apache::loncommon::end_data_table_row()."\n";
1.177     albertel  784: 		
                    785: 		$matches++;
                    786: 	    }
1.44      ng        787: 	}
                    788:     }
                    789:     if ($matches == 0) {
1.584     bisitz    790:         $string = $title
                    791:                  .'<p class="LC_warning">'
                    792:                  .&mt('No match found for the above receipt number.')
                    793:                  .'</p>';
1.44      ng        794:     } else {
1.324     albertel  795: 	$string = &jscriptNform($symb).$title.
1.487     albertel  796: 	    '<p>'.
1.584     bisitz    797: 	    &mt('The above receipt number matches the following [quant,_1,student].',$matches).
1.487     albertel  798: 	    '</p>'.
1.486     albertel  799: 	    $header.
                    800: 	    $contents.
                    801: 	    &Apache::loncommon::end_data_table()."\n";
1.44      ng        802:     }
1.324     albertel  803:     return $string.&show_grading_menu_form($symb);
1.44      ng        804: }
                    805: 
                    806: #--- This is called by a number of programs.
                    807: #--- Called from the Grading Menu - View/Grade an individual student
                    808: #--- Also called directly when one clicks on the subm button 
                    809: #    on the problem page.
1.30      ng        810: sub listStudents {
1.608     www       811:     my ($request,$symb) = @_;
1.49      albertel  812: 
1.257     albertel  813:     my $cdom      = $env{"course.$env{'request.course.id'}.domain"};
                    814:     my $cnum      = $env{"course.$env{'request.course.id'}.num"};
                    815:     my $getsec    = $env{'form.section'} eq '' ? 'all' : $env{'form.section'};
1.449     banghart  816:     my $getgroup  = $env{'form.group'} eq '' ? 'all' : $env{'form.group'};
1.257     albertel  817:     my $submitonly= $env{'form.submitonly'} eq '' ? 'all' : $env{'form.submitonly'};
1.548     bisitz    818:     my $viewgrade = $env{'form.showgrading'} eq 'yes' ? 'View/Grade/Regrade' : 'View';
1.49      albertel  819: 
1.548     bisitz    820:     my $result='<h3><span class="LC_info">&nbsp;'
                    821: 	.&mt("$viewgrade Submissions for a Student or a Group of Students")
1.485     albertel  822: 	.'</span></h3>';
1.118     ng        823: 
1.598     www       824:     my ($partlist,$handgrade,$responseType) = &response_type($symb
                    825: #,$res_error
                    826:     );
1.49      albertel  827: 
1.559     raeburn   828:     my %lt = &Apache::lonlocal::texthash (
                    829: 		'multiple' => 'Please select a student or group of students before clicking on the Next button.',
                    830: 		'single'   => 'Please select the student before clicking on the Next button.',
                    831: 	     );
1.597     wenzelju  832:     $request->print(&Apache::lonhtmlcommon::scripttag(<<LISTJAVASCRIPT));
1.110     ng        833:     function checkSelect(checkBox) {
                    834: 	var ctr=0;
                    835: 	var sense="";
                    836: 	if (checkBox.length > 1) {
                    837: 	    for (var i=0; i<checkBox.length; i++) {
                    838: 		if (checkBox[i].checked) {
                    839: 		    ctr++;
                    840: 		}
                    841: 	    }
1.485     albertel  842: 	    sense = '$lt{'multiple'}';
1.110     ng        843: 	} else {
                    844: 	    if (checkBox.checked) {
                    845: 		ctr = 1;
                    846: 	    }
1.485     albertel  847: 	    sense = '$lt{'single'}';
1.110     ng        848: 	}
                    849: 	if (ctr == 0) {
1.485     albertel  850: 	    alert(sense);
1.110     ng        851: 	    return false;
                    852: 	}
                    853: 	document.gradesub.submit();
                    854:     }
                    855: 
                    856:     function reLoadList(formname) {
1.112     ng        857: 	if (formname.saveStatusOld.value == pullDownSelection(formname.Status)) {return;}
1.110     ng        858: 	formname.command.value = 'submission';
                    859: 	formname.submit();
                    860:     }
1.45      ng        861: LISTJAVASCRIPT
                    862: 
1.118     ng        863:     &commonJSfunctions($request);
1.41      ng        864:     $request->print($result);
1.39      ng        865: 
1.401     albertel  866:     my $checkhdgrade = ($env{'form.handgrade'} eq 'yes' && scalar(@$partlist) > 1 ) ? 'checked="checked"' : '';
                    867:     my $checklastsub = $checkhdgrade eq '' ? 'checked="checked"' : '';
1.154     albertel  868:     my $gradeTable='<form action="/adm/grades" method="post" name="gradesub">'.
1.598     www       869: 	"\n";
1.485     albertel  870: 	
1.561     bisitz    871:     $gradeTable .= &Apache::lonhtmlcommon::start_pick_box();
                    872:     $gradeTable .= &Apache::lonhtmlcommon::row_title(&mt('View Problem Text'))
                    873:                   .'<label><input type="radio" name="vProb" value="no" checked="checked" /> '.&mt('no').' </label>'."\n"
                    874:                   .'<label><input type="radio" name="vProb" value="yes" /> '.&mt('one student').' </label>'."\n"
                    875:                   .'<label><input type="radio" name="vProb" value="all" /> '.&mt('all students').' </label><br />'."\n"
                    876:                   .&Apache::lonhtmlcommon::row_closure();
                    877:     $gradeTable .= &Apache::lonhtmlcommon::row_title(&mt('View Answer'))
                    878:                   .'<label><input type="radio" name="vAns" value="no"  /> '.&mt('no').' </label>'."\n"
                    879:                   .'<label><input type="radio" name="vAns" value="yes" /> '.&mt('one student').' </label>'."\n"
                    880:                   .'<label><input type="radio" name="vAns" value="all" checked="checked" /> '.&mt('all students').' </label><br />'."\n"
                    881:                   .&Apache::lonhtmlcommon::row_closure();
1.485     albertel  882: 
                    883:     my $submission_options;
1.257     albertel  884:     if ($env{'form.handgrade'} eq 'yes' && scalar(@$partlist) > 1) {
1.485     albertel  885: 	$submission_options.=
                    886: 	    '<label><input type="radio" name="lastSub" value="hdgrade" '.$checkhdgrade.' /> '.&mt('essay part only').' </label>'."\n";
1.49      albertel  887:     }
1.442     banghart  888:     my $stu_status = join(':',&Apache::loncommon::get_env_multiple('form.Status'));
                    889:     my $saveStatus = $stu_status eq '' ? 'Active' : $stu_status;
1.257     albertel  890:     $env{'form.Status'} = $saveStatus;
1.485     albertel  891:     $submission_options.=
1.592     bisitz    892:         '<span class="LC_nobreak">'.
                    893:         '<label><input type="radio" name="lastSub" value="lastonly" '.$checklastsub.' /> '.
                    894:         &mt('last submission only').' </label></span>'."\n".
                    895:         '<span class="LC_nobreak">'.
                    896:         '<label><input type="radio" name="lastSub" value="last" /> '.
                    897:         &mt('last submission &amp; parts info').' </label></span>'."\n".
                    898:         '<span class="LC_nobreak">'.
                    899:         '<label><input type="radio" name="lastSub" value="datesub" /> '.
                    900:         &mt('by dates and submissions').'</label></span>'."\n".
                    901:         '<span class="LC_nobreak">'.
                    902:         '<label><input type="radio" name="lastSub" value="all" /> '.
                    903:         &mt('all details').'</label></span>';
1.561     bisitz    904:     $gradeTable .= &Apache::lonhtmlcommon::row_title(&mt('Submissions'))
                    905:                   .$submission_options
                    906:                   .&Apache::lonhtmlcommon::row_closure();
                    907: 
                    908:     $gradeTable .= &Apache::lonhtmlcommon::row_title(&mt('Grading Increments'))
                    909:                   .'<select name="increment">'
                    910:                   .'<option value="1">'.&mt('Whole Points').'</option>'
                    911:                   .'<option value=".5">'.&mt('Half Points').'</option>'
                    912:                   .'<option value=".25">'.&mt('Quarter Points').'</option>'
                    913:                   .'<option value=".1">'.&mt('Tenths of a Point').'</option>'
                    914:                   .'</select>'
                    915:                   .&Apache::lonhtmlcommon::row_closure();
1.485     albertel  916: 
                    917:     $gradeTable .= 
1.432     banghart  918:         &build_section_inputs().
1.45      ng        919: 	'<input type="hidden" name="submitonly"  value="'.$submitonly.'" />'."\n".
1.257     albertel  920: 	'<input type="hidden" name="handgrade"   value="'.$env{'form.handgrade'}.'" /><br />'."\n".
                    921: 	'<input type="hidden" name="showgrading" value="'.$env{'form.showgrading'}.'" /><br />'."\n".
1.418     albertel  922: 	'<input type="hidden" name="symb" value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
1.110     ng        923: 	'<input type="hidden" name="saveStatusOld" value="'.$saveStatus.'" />'."\n";
                    924: 
1.257     albertel  925:     if (exists($env{'form.gradingMenu'}) && exists($env{'form.Status'})) {
1.561     bisitz    926: 	$gradeTable .= '<input type="hidden" name="Status" value="'.$stu_status.'" />'."\n";
1.124     ng        927:     } else {
1.561     bisitz    928:         $gradeTable .= &Apache::lonhtmlcommon::row_title(&mt('Student Status'))
                    929:                       .&Apache::lonhtmlcommon::StatusOptions(
                    930:                            $saveStatus,undef,1,'javascript:reLoadList(this.form);')
                    931:                       .&Apache::lonhtmlcommon::row_closure();
1.124     ng        932:     }
1.112     ng        933: 
1.561     bisitz    934:     $gradeTable .= &Apache::lonhtmlcommon::row_title(&mt('Check For Plagiarism'))
                    935:                   .'<input type="checkbox" name="checkPlag" checked="checked" />'
                    936:                   .&Apache::lonhtmlcommon::row_closure(1)
                    937:                   .&Apache::lonhtmlcommon::end_pick_box();
                    938: 
                    939:     $gradeTable .= '<p>'
                    940:                   .&mt('To '.lc($viewgrade)." a submission or a group of submissions, click on the check box(es) next to the student's name(s). Then click on the Next button.")."\n"
                    941:                   .'<input type="hidden" name="command" value="processGroup" />'
                    942:                   .'</p>';
1.249     albertel  943: 
                    944: # checkall buttons
                    945:     $gradeTable.=&check_script('gradesub', 'stuinfo');
1.110     ng        946:     $gradeTable.='<input type="button" '."\n".
1.589     bisitz    947:         'onclick="javascript:checkSelect(this.form.stuinfo);" '."\n".
                    948:         'value="'.&mt('Next').' &rarr;" /> <br />'."\n";
1.249     albertel  949:     $gradeTable.=&check_buttons();
1.450     banghart  950:     my ($classlist, undef, $fullname) = &getclasslist($getsec,'1',$getgroup);
1.474     albertel  951:     $gradeTable.= &Apache::loncommon::start_data_table().
                    952: 	&Apache::loncommon::start_data_table_header_row();
1.110     ng        953:     my $loop = 0;
                    954:     while ($loop < 2) {
1.485     albertel  955: 	$gradeTable.='<th>'.&mt('No.').'</th><th>'.&mt('Select').'</th>'.
                    956: 	    '<th>'.&nameUserString('header').'&nbsp;'.&mt('Section/Group').'</th>';
1.301     albertel  957: 	if ($env{'form.showgrading'} eq 'yes' 
                    958: 	    && $submitonly ne 'queued'
                    959: 	    && $submitonly ne 'all') {
1.485     albertel  960: 	    foreach my $part (sort(@$partlist)) {
                    961: 		my $display_part=
                    962: 		    &get_display_part((split(/_/,$part))[0],$symb);
                    963: 		$gradeTable.=
                    964: 		    '<th>'.&mt('Part: [_1] Status',$display_part).'</th>';
1.110     ng        965: 	    }
1.301     albertel  966: 	} elsif ($submitonly eq 'queued') {
1.474     albertel  967: 	    $gradeTable.='<th>'.&mt('Queue Status').'&nbsp;</th>';
1.110     ng        968: 	}
                    969: 	$loop++;
1.126     ng        970: #	$gradeTable.='<td></td>' if ($loop%2 ==1);
1.41      ng        971:     }
1.474     albertel  972:     $gradeTable.=&Apache::loncommon::end_data_table_header_row()."\n";
1.41      ng        973: 
1.45      ng        974:     my $ctr = 0;
1.294     albertel  975:     foreach my $student (sort 
                    976: 			 {
                    977: 			     if (lc($$fullname{$a}) ne lc($$fullname{$b})) {
                    978: 				 return (lc($$fullname{$a}) cmp lc($$fullname{$b}));
                    979: 			     }
                    980: 			     return $a cmp $b;
                    981: 			 }
                    982: 			 (keys(%$fullname))) {
1.41      ng        983: 	my ($uname,$udom) = split(/:/,$student);
1.301     albertel  984: 
1.110     ng        985: 	my %status = ();
1.301     albertel  986: 
                    987: 	if ($submitonly eq 'queued') {
                    988: 	    my %queue_status = 
                    989: 		&Apache::bridgetask::get_student_status($symb,$cdom,$cnum,
                    990: 							$udom,$uname);
                    991: 	    next if (!defined($queue_status{'gradingqueue'}));
                    992: 	    $status{'gradingqueue'} = $queue_status{'gradingqueue'};
                    993: 	}
                    994: 
                    995: 	if ($env{'form.showgrading'} eq 'yes' 
                    996: 	    && $submitonly ne 'queued'
                    997: 	    && $submitonly ne 'all') {
1.324     albertel  998: 	    (%status) =&student_gradeStatus($symb,$udom,$uname,$partlist);
1.145     albertel  999: 	    my $submitted = 0;
1.164     albertel 1000: 	    my $graded = 0;
1.248     albertel 1001: 	    my $incorrect = 0;
1.110     ng       1002: 	    foreach (keys(%status)) {
1.145     albertel 1003: 		$submitted = 1 if ($status{$_} ne 'nothing');
1.248     albertel 1004: 		$graded = 1 if ($status{$_} =~ /^ungraded/);
                   1005: 		$incorrect = 1 if ($status{$_} =~ /^incorrect/);
                   1006: 		
1.110     ng       1007: 		my ($foo,$partid,$foo1) = split(/\./,$_);
                   1008: 		if ($status{'resource.'.$partid.'.submitted_by'} ne '') {
1.145     albertel 1009: 		    $submitted = 0;
1.150     albertel 1010: 		    my ($part)=split(/\./,$partid);
1.110     ng       1011: 		    $gradeTable.='<input type="hidden" name="'.
1.150     albertel 1012: 			$student.':'.$part.':submitted_by" value="'.
1.110     ng       1013: 			$status{'resource.'.$partid.'.submitted_by'}.'" />';
                   1014: 		}
1.41      ng       1015: 	    }
1.248     albertel 1016: 	    
1.156     albertel 1017: 	    next if (!$submitted && ($submitonly eq 'yes' ||
                   1018: 				     $submitonly eq 'incorrect' ||
                   1019: 				     $submitonly eq 'graded'));
1.248     albertel 1020: 	    next if (!$graded && ($submitonly eq 'graded'));
                   1021: 	    next if (!$incorrect && $submitonly eq 'incorrect');
1.41      ng       1022: 	}
1.34      ng       1023: 
1.45      ng       1024: 	$ctr++;
1.249     albertel 1025: 	my $section = $classlist->{$student}->[&Apache::loncoursedata::CL_SECTION()];
1.452     banghart 1026:         my $group = $classlist->{$student}->[&Apache::loncoursedata::CL_GROUP()];
1.104     albertel 1027: 	if ( $perm{'vgr'} eq 'F' ) {
1.474     albertel 1028: 	    if ($ctr%2 ==1) {
                   1029: 		$gradeTable.= &Apache::loncommon::start_data_table_row();
                   1030: 	    }
1.126     ng       1031: 	    $gradeTable.='<td align="right">'.$ctr.'&nbsp;</td>'.
1.563     bisitz   1032:                '<td align="center"><label><input type="checkbox" name="stuinfo" value="'.
1.249     albertel 1033:                $student.':'.$$fullname{$student}.':::SECTION'.$section.
                   1034: 	       ')&nbsp;" />&nbsp;&nbsp;</label></td>'."\n".'<td>'.
                   1035: 	       &nameUserString(undef,$$fullname{$student},$uname,$udom).
1.474     albertel 1036: 	       '&nbsp;'.$section.($group ne '' ?'/'.$group:'').'</td>'."\n";
1.110     ng       1037: 
1.257     albertel 1038: 	    if ($env{'form.showgrading'} eq 'yes' && $submitonly ne 'all') {
1.524     raeburn  1039: 		foreach (sort(keys(%status))) {
1.485     albertel 1040: 		    next if ($_ =~ /^resource.*?submitted_by$/);
                   1041: 		    $gradeTable.='<td align="center">&nbsp;'.&mt($status{$_}).'&nbsp;</td>'."\n";
1.110     ng       1042: 		}
1.41      ng       1043: 	    }
1.126     ng       1044: #	    $gradeTable.='<td></td>' if ($ctr%2 ==1);
1.474     albertel 1045: 	    if ($ctr%2 ==0) {
                   1046: 		$gradeTable.=&Apache::loncommon::end_data_table_row()."\n";
                   1047: 	    }
1.41      ng       1048: 	}
                   1049:     }
1.110     ng       1050:     if ($ctr%2 ==1) {
1.126     ng       1051: 	$gradeTable.='<td>&nbsp;</td><td>&nbsp;</td><td>&nbsp;</td>';
1.301     albertel 1052: 	    if ($env{'form.showgrading'} eq 'yes' 
                   1053: 		&& $submitonly ne 'queued'
                   1054: 		&& $submitonly ne 'all') {
1.110     ng       1055: 		foreach (@$partlist) {
                   1056: 		    $gradeTable.='<td>&nbsp;</td>';
                   1057: 		}
1.301     albertel 1058: 	    } elsif ($submitonly eq 'queued') {
                   1059: 		$gradeTable.='<td>&nbsp;</td>';
1.110     ng       1060: 	    }
1.474     albertel 1061: 	$gradeTable.=&Apache::loncommon::end_data_table_row();
1.110     ng       1062:     }
                   1063: 
1.474     albertel 1064:     $gradeTable.=&Apache::loncommon::end_data_table()."\n".
1.589     bisitz   1065:         '<input type="button" '.
                   1066:         'onclick="javascript:checkSelect(this.form.stuinfo);" '.
                   1067:         'value="'.&mt('Next').' &rarr;" /></form>'."\n";
1.45      ng       1068:     if ($ctr == 0) {
1.96      albertel 1069: 	my $num_students=(scalar(keys(%$fullname)));
                   1070: 	if ($num_students eq 0) {
1.485     albertel 1071: 	    $gradeTable='<br />&nbsp;<span class="LC_warning">'.&mt('There are no students currently enrolled.').'</span>';
1.96      albertel 1072: 	} else {
1.171     albertel 1073: 	    my $submissions='submissions';
                   1074: 	    if ($submitonly eq 'incorrect') { $submissions = 'incorrect submissions'; }
                   1075: 	    if ($submitonly eq 'graded'   ) { $submissions = 'ungraded submissions'; }
1.301     albertel 1076: 	    if ($submitonly eq 'queued'   ) { $submissions = 'queued submissions'; }
1.398     albertel 1077: 	    $gradeTable='<br />&nbsp;<span class="LC_warning">'.
1.485     albertel 1078: 		&mt('No '.$submissions.' found for this resource for any students. ([_1] students checked for '.$submissions.')',
                   1079: 		    $num_students).
                   1080: 		'</span><br />';
1.96      albertel 1081: 	}
1.46      ng       1082:     } elsif ($ctr == 1) {
1.474     albertel 1083: 	$gradeTable =~ s/type="checkbox"/type="checkbox" checked="checked"/;
1.45      ng       1084:     }
1.324     albertel 1085:     $gradeTable.=&show_grading_menu_form($symb);
1.45      ng       1086:     $request->print($gradeTable);
1.44      ng       1087:     return '';
1.10      ng       1088: }
                   1089: 
1.44      ng       1090: #---- Called from the listStudents routine
1.249     albertel 1091: 
                   1092: sub check_script {
                   1093:     my ($form, $type)=@_;
1.597     wenzelju 1094:     my $chkallscript= &Apache::lonhtmlcommon::scripttag('
1.249     albertel 1095:     function checkall() {
                   1096:         for (i=0; i<document.forms.'.$form.'.elements.length; i++) {
                   1097:             ele = document.forms.'.$form.'.elements[i];
                   1098:             if (ele.name == "'.$type.'") {
                   1099:             document.forms.'.$form.'.elements[i].checked=true;
                   1100:                                        }
                   1101:         }
                   1102:     }
                   1103: 
                   1104:     function checksec() {
                   1105:         for (i=0; i<document.forms.'.$form.'.elements.length; i++) {
                   1106:             ele = document.forms.'.$form.'.elements[i];
                   1107:            string = document.forms.'.$form.'.chksec.value;
                   1108:            if
                   1109:           (ele.value.indexOf(":::SECTION"+string)>0) {
                   1110:               document.forms.'.$form.'.elements[i].checked=true;
                   1111:             }
                   1112:         }
                   1113:     }
                   1114: 
                   1115: 
                   1116:     function uncheckall() {
                   1117:         for (i=0; i<document.forms.'.$form.'.elements.length; i++) {
                   1118:             ele = document.forms.'.$form.'.elements[i];
                   1119:             if (ele.name == "'.$type.'") {
                   1120:             document.forms.'.$form.'.elements[i].checked=false;
                   1121:                                        }
                   1122:         }
                   1123:     }
                   1124: 
1.597     wenzelju 1125: '."\n");
1.249     albertel 1126:     return $chkallscript;
                   1127: }
                   1128: 
                   1129: sub check_buttons {
1.485     albertel 1130:     my $buttons.='<input type="button" onclick="checkall()" value="'.&mt('Check All').'" />';
                   1131:     $buttons.='<input type="button" onclick="uncheckall()" value="'.&mt('Uncheck All').'" />&nbsp;';
                   1132:     $buttons.='<input type="button" onclick="checksec()" value="'.&mt('Check Section/Group').'" />';
1.249     albertel 1133:     $buttons.='<input type="text" size="5" name="chksec" />&nbsp;';
                   1134:     return $buttons;
                   1135: }
                   1136: 
1.44      ng       1137: #     Displays the submissions for one student or a group of students
1.34      ng       1138: sub processGroup {
1.41      ng       1139:     my ($request)  = shift;
                   1140:     my $ctr        = 0;
1.155     albertel 1141:     my @stuchecked = &Apache::loncommon::get_env_multiple('form.stuinfo');
1.41      ng       1142:     my $total      = scalar(@stuchecked)-1;
1.45      ng       1143: 
1.396     banghart 1144:     foreach my $student (@stuchecked) {
                   1145: 	my ($uname,$udom,$fullname) = split(/:/,$student);
1.257     albertel 1146: 	$env{'form.student'}        = $uname;
                   1147: 	$env{'form.userdom'}        = $udom;
                   1148: 	$env{'form.fullname'}       = $fullname;
1.41      ng       1149: 	&submission($request,$ctr,$total);
                   1150: 	$ctr++;
                   1151:     }
                   1152:     return '';
1.35      ng       1153: }
1.34      ng       1154: 
1.44      ng       1155: #------------------------------------------------------------------------------------
                   1156: #
                   1157: #-------------------------- Next few routines handles grading by student, essentially
                   1158: #                           handles essay response type problem/part
                   1159: #
                   1160: #--- Javascript to handle the submission page functionality ---
                   1161: sub sub_page_js {
                   1162:     my $request = shift;
1.539     riegler  1163: 	    my $alertmsg = &mt('A number equal or greater than 0 is expected. Entered value = ');
1.597     wenzelju 1164:     $request->print(&Apache::lonhtmlcommon::scripttag(<<SUBJAVASCRIPT));
1.71      ng       1165:     function updateRadio(formname,id,weight) {
1.125     ng       1166: 	var gradeBox = formname["GD_BOX"+id];
                   1167: 	var radioButton = formname["RADVAL"+id];
                   1168: 	var oldpts = formname["oldpts"+id].value;
1.72      ng       1169: 	var pts = checkSolved(formname,id) == 'update' ? gradeBox.value : oldpts;
1.71      ng       1170: 	gradeBox.value = pts;
                   1171: 	var resetbox = false;
                   1172: 	if (isNaN(pts) || pts < 0) {
1.539     riegler  1173: 	    alert("$alertmsg"+pts);
1.71      ng       1174: 	    for (var i=0; i<radioButton.length; i++) {
                   1175: 		if (radioButton[i].checked) {
                   1176: 		    gradeBox.value = i;
                   1177: 		    resetbox = true;
                   1178: 		}
                   1179: 	    }
                   1180: 	    if (!resetbox) {
                   1181: 		formtextbox.value = "";
                   1182: 	    }
                   1183: 	    return;
1.44      ng       1184: 	}
1.71      ng       1185: 
                   1186: 	if (pts > weight) {
                   1187: 	    var resp = confirm("You entered a value ("+pts+
                   1188: 			       ") greater than the weight for the part. Accept?");
                   1189: 	    if (resp == false) {
1.125     ng       1190: 		gradeBox.value = oldpts;
1.71      ng       1191: 		return;
                   1192: 	    }
1.44      ng       1193: 	}
1.13      albertel 1194: 
1.71      ng       1195: 	for (var i=0; i<radioButton.length; i++) {
                   1196: 	    radioButton[i].checked=false;
                   1197: 	    if (pts == i && pts != "") {
                   1198: 		radioButton[i].checked=true;
                   1199: 	    }
                   1200: 	}
                   1201: 	updateSelect(formname,id);
1.125     ng       1202: 	formname["stores"+id].value = "0";
1.41      ng       1203:     }
1.5       albertel 1204: 
1.72      ng       1205:     function writeBox(formname,id,pts) {
1.125     ng       1206: 	var gradeBox = formname["GD_BOX"+id];
1.71      ng       1207: 	if (checkSolved(formname,id) == 'update') {
                   1208: 	    gradeBox.value = pts;
                   1209: 	} else {
1.125     ng       1210: 	    var oldpts = formname["oldpts"+id].value;
1.72      ng       1211: 	    gradeBox.value = oldpts;
1.125     ng       1212: 	    var radioButton = formname["RADVAL"+id];
1.71      ng       1213: 	    for (var i=0; i<radioButton.length; i++) {
                   1214: 		radioButton[i].checked=false;
1.72      ng       1215: 		if (i == oldpts) {
1.71      ng       1216: 		    radioButton[i].checked=true;
                   1217: 		}
                   1218: 	    }
1.41      ng       1219: 	}
1.125     ng       1220: 	formname["stores"+id].value = "0";
1.71      ng       1221: 	updateSelect(formname,id);
                   1222: 	return;
1.41      ng       1223:     }
1.44      ng       1224: 
1.71      ng       1225:     function clearRadBox(formname,id) {
                   1226: 	if (checkSolved(formname,id) == 'noupdate') {
                   1227: 	    updateSelect(formname,id);
                   1228: 	    return;
                   1229: 	}
1.125     ng       1230: 	gradeSelect = formname["GD_SEL"+id];
1.71      ng       1231: 	for (var i=0; i<gradeSelect.length; i++) {
                   1232: 	    if (gradeSelect[i].selected) {
                   1233: 		var selectx=i;
                   1234: 	    }
                   1235: 	}
1.125     ng       1236: 	var stores = formname["stores"+id];
1.71      ng       1237: 	if (selectx == stores.value) { return };
1.125     ng       1238: 	var gradeBox = formname["GD_BOX"+id];
1.71      ng       1239: 	gradeBox.value = "";
1.125     ng       1240: 	var radioButton = formname["RADVAL"+id];
1.71      ng       1241: 	for (var i=0; i<radioButton.length; i++) {
                   1242: 	    radioButton[i].checked=false;
                   1243: 	}
                   1244: 	stores.value = selectx;
                   1245:     }
1.5       albertel 1246: 
1.71      ng       1247:     function checkSolved(formname,id) {
1.125     ng       1248: 	if (formname["solved"+id].value == "correct_by_student" && formname.overRideScore.value == 'no') {
1.118     ng       1249: 	    var reply = confirm("This problem has been graded correct by the computer. Do you want to change the score?");
                   1250: 	    if (!reply) {return "noupdate";}
1.120     ng       1251: 	    formname.overRideScore.value = 'yes';
1.41      ng       1252: 	}
1.71      ng       1253: 	return "update";
1.13      albertel 1254:     }
1.71      ng       1255: 
                   1256:     function updateSelect(formname,id) {
1.125     ng       1257: 	formname["GD_SEL"+id][0].selected = true;
1.71      ng       1258: 	return;
1.41      ng       1259:     }
1.33      ng       1260: 
1.121     ng       1261: //=========== Check that a point is assigned for all the parts  ============
1.71      ng       1262:     function checksubmit(formname,val,total,parttot) {
1.121     ng       1263: 	formname.gradeOpt.value = val;
1.71      ng       1264: 	if (val == "Save & Next") {
                   1265: 	    for (i=0;i<=total;i++) {
                   1266: 		for (j=0;j<parttot;j++) {
1.125     ng       1267: 		    var partid = formname["partid"+i+"_"+j].value;
1.127     ng       1268: 		    if (formname["GD_SEL"+i+"_"+partid][0].selected) {
1.125     ng       1269: 			var points = formname["GD_BOX"+i+"_"+partid].value;
1.71      ng       1270: 			if (points == "") {
1.125     ng       1271: 			    var name = formname["name"+i].value;
1.129     ng       1272: 			    var studentID = (name != '' ? name : formname["unamedom"+i].value);
                   1273: 			    var resp = confirm("You did not assign a score for "+studentID+
                   1274: 					       ", part "+partid+". Continue?");
1.71      ng       1275: 			    if (resp == false) {
1.125     ng       1276: 				formname["GD_BOX"+i+"_"+partid].focus();
1.71      ng       1277: 				return false;
                   1278: 			    }
                   1279: 			}
                   1280: 		    }
                   1281: 		    
                   1282: 		}
                   1283: 	    }
                   1284: 	    
                   1285: 	}
1.121     ng       1286: 	if (val == "Grade Student") {
                   1287: 	    formname.showgrading.value = "yes";
                   1288: 	    if (formname.Status.value == "") {
                   1289: 		formname.Status.value = "Active";
                   1290: 	    }
                   1291: 	    formname.studentNo.value = total;
                   1292: 	}
1.120     ng       1293: 	formname.submit();
                   1294:     }
                   1295: 
1.71      ng       1296: //======= Check that a score is assigned for all the problems (page/sequence grading only) =========
                   1297:     function checkSubmitPage(formname,total) {
                   1298: 	noscore = new Array(100);
                   1299: 	var ptr = 0;
                   1300: 	for (i=1;i<total;i++) {
1.125     ng       1301: 	    var partid = formname["q_"+i].value;
1.127     ng       1302: 	    if (formname["GD_SEL"+i+"_"+partid][0].selected) {
1.125     ng       1303: 		var points = formname["GD_BOX"+i+"_"+partid].value;
                   1304: 		var status = formname["solved"+i+"_"+partid].value;
1.71      ng       1305: 		if (points == "" && status != "correct_by_student") {
                   1306: 		    noscore[ptr] = i;
                   1307: 		    ptr++;
                   1308: 		}
                   1309: 	    }
                   1310: 	}
                   1311: 	if (ptr != 0) {
                   1312: 	    var sense = ptr == 1 ? ": " : "s: ";
                   1313: 	    var prolist = "";
                   1314: 	    if (ptr == 1) {
                   1315: 		prolist = noscore[0];
                   1316: 	    } else {
                   1317: 		var i = 0;
                   1318: 		while (i < ptr-1) {
                   1319: 		    prolist += noscore[i]+", ";
                   1320: 		    i++;
                   1321: 		}
                   1322: 		prolist += "and "+noscore[i];
                   1323: 	    }
                   1324: 	    var resp = confirm("You did not assign any score for the following problem"+sense+prolist+". Continue?");
                   1325: 	    if (resp == false) {
                   1326: 		return false;
                   1327: 	    }
                   1328: 	}
1.45      ng       1329: 
1.71      ng       1330: 	formname.submit();
                   1331:     }
                   1332: SUBJAVASCRIPT
                   1333: }
1.45      ng       1334: 
1.71      ng       1335: #--- javascript for essay type problem --
                   1336: sub sub_page_kw_js {
                   1337:     my $request = shift;
1.80      ng       1338:     my $iconpath = $request->dir_config('lonIconsURL');
1.118     ng       1339:     &commonJSfunctions($request);
1.350     albertel 1340: 
1.597     wenzelju 1341:     my $inner_js_msg_central= &Apache::lonhtmlcommon::scripttag(<<INNERJS);
1.350     albertel 1342:     function checkInput() {
                   1343:       opener.document.SCORE.msgsub.value = opener.checkEntities(document.msgcenter.msgsub.value);
                   1344:       var nmsg   = opener.document.SCORE.savemsgN.value;
                   1345:       var usrctr = document.msgcenter.usrctr.value;
                   1346:       var newval = opener.document.SCORE["newmsg"+usrctr];
                   1347:       newval.value = opener.checkEntities(document.msgcenter.newmsg.value);
                   1348: 
                   1349:       var msgchk = "";
                   1350:       if (document.msgcenter.subchk.checked) {
                   1351:          msgchk = "msgsub,";
                   1352:       }
                   1353:       var includemsg = 0;
                   1354:       for (var i=1; i<=nmsg; i++) {
                   1355:           var opnmsg = opener.document.SCORE["savemsg"+i];
                   1356:           var frmmsg = document.msgcenter["msg"+i];
                   1357:           opnmsg.value = opener.checkEntities(frmmsg.value);
                   1358:           var showflg = opener.document.SCORE["shownOnce"+i];
                   1359:           showflg.value = "1";
                   1360:           var chkbox = document.msgcenter["msgn"+i];
                   1361:           if (chkbox.checked) {
                   1362:              msgchk += "savemsg"+i+",";
                   1363:              includemsg = 1;
                   1364:           }
                   1365:       }
                   1366:       if (document.msgcenter.newmsgchk.checked) {
                   1367:          msgchk += "newmsg"+usrctr;
                   1368:          includemsg = 1;
                   1369:       }
                   1370:       imgformname = opener.document.SCORE["mailicon"+usrctr];
                   1371:       imgformname.src = "$iconpath/"+((includemsg) ? "mailto.gif" : "mailbkgrd.gif");
                   1372:       var includemsg = opener.document.SCORE["includemsg"+usrctr];
                   1373:       includemsg.value = msgchk;
                   1374: 
                   1375:       self.close()
                   1376: 
                   1377:     }
                   1378: INNERJS
                   1379: 
1.597     wenzelju 1380:     my $inner_js_highlight_central= &Apache::lonhtmlcommon::scripttag(<<INNERJS);
1.351     albertel 1381:     function updateChoice(flag) {
                   1382:       opener.document.SCORE.kwclr.value = opener.radioSelection(document.hlCenter.kwdclr);
                   1383:       opener.document.SCORE.kwsize.value = opener.radioSelection(document.hlCenter.kwdsize);
                   1384:       opener.document.SCORE.kwstyle.value = opener.radioSelection(document.hlCenter.kwdstyle);
                   1385:       opener.document.SCORE.refresh.value = "on";
                   1386:       if (opener.document.SCORE.keywords.value!=""){
                   1387:          opener.document.SCORE.submit();
                   1388:       }
                   1389:       self.close()
                   1390:     }
                   1391: INNERJS
                   1392: 
                   1393:     my $start_page_msg_central = 
                   1394:         &Apache::loncommon::start_page('Message Central',$inner_js_msg_central,
                   1395: 				       {'js_ready'  => 1,
                   1396: 					'only_body' => 1,
                   1397: 					'bgcolor'   =>'#FFFFFF',});
                   1398:     my $end_page_msg_central = 
                   1399: 	&Apache::loncommon::end_page({'js_ready' => 1});
                   1400: 
                   1401: 
                   1402:     my $start_page_highlight_central = 
                   1403:         &Apache::loncommon::start_page('Highlight Central',
                   1404: 				       $inner_js_highlight_central,
1.350     albertel 1405: 				       {'js_ready'  => 1,
                   1406: 					'only_body' => 1,
                   1407: 					'bgcolor'   =>'#FFFFFF',});
1.351     albertel 1408:     my $end_page_highlight_central = 
1.350     albertel 1409: 	&Apache::loncommon::end_page({'js_ready' => 1});
                   1410: 
1.219     www      1411:     my $docopen=&Apache::lonhtmlcommon::javascript_docopen();
1.236     albertel 1412:     $docopen=~s/^document\.//;
1.539     riegler  1413:     my $alertmsg = &mt('Please select a word or group of words from document and then click this link.');
1.597     wenzelju 1414:     $request->print(&Apache::lonhtmlcommon::scripttag(<<SUBJAVASCRIPT));
1.45      ng       1415: 
1.44      ng       1416: //===================== Show list of keywords ====================
1.122     ng       1417:   function keywords(formname) {
                   1418:     var nret = prompt("Keywords list, separated by a space. Add/delete to list if desired.",formname.keywords.value);
1.44      ng       1419:     if (nret==null) return;
1.122     ng       1420:     formname.keywords.value = nret;
1.44      ng       1421: 
1.122     ng       1422:     if (formname.keywords.value != "") {
1.128     ng       1423: 	formname.refresh.value = "on";
1.122     ng       1424: 	formname.submit();
1.44      ng       1425:     }
                   1426:     return;
                   1427:   }
                   1428: 
                   1429: //===================== Script to view submitted by ==================
                   1430:   function viewSubmitter(submitter) {
                   1431:     document.SCORE.refresh.value = "on";
                   1432:     document.SCORE.NCT.value = "1";
                   1433:     document.SCORE.unamedom0.value = submitter;
                   1434:     document.SCORE.submit();
                   1435:     return;
                   1436:   }
                   1437: 
                   1438: //===================== Script to add keyword(s) ==================
                   1439:   function getSel() {
                   1440:     if (document.getSelection) txt = document.getSelection();
                   1441:     else if (document.selection) txt = document.selection.createRange().text;
                   1442:     else return;
                   1443:     var cleantxt = txt.replace(new RegExp('([\\f\\n\\r\\t\\v ])+', 'g')," ");
                   1444:     if (cleantxt=="") {
1.539     riegler  1445: 	alert("$alertmsg");
1.44      ng       1446: 	return;
                   1447:     }
                   1448:     var nret = prompt("Add selection to keyword list? Edit if desired.",cleantxt);
                   1449:     if (nret==null) return;
1.127     ng       1450:     document.SCORE.keywords.value = document.SCORE.keywords.value+" "+nret;
1.44      ng       1451:     if (document.SCORE.keywords.value != "") {
1.127     ng       1452: 	document.SCORE.refresh.value = "on";
1.44      ng       1453: 	document.SCORE.submit();
                   1454:     }
                   1455:     return;
                   1456:   }
                   1457: 
                   1458: //====================== Script for composing message ==============
1.80      ng       1459:    // preload images
                   1460:    img1 = new Image();
                   1461:    img1.src = "$iconpath/mailbkgrd.gif";
                   1462:    img2 = new Image();
                   1463:    img2.src = "$iconpath/mailto.gif";
                   1464: 
1.44      ng       1465:   function msgCenter(msgform,usrctr,fullname) {
                   1466:     var Nmsg  = msgform.savemsgN.value;
                   1467:     savedMsgHeader(Nmsg,usrctr,fullname);
                   1468:     var subject = msgform.msgsub.value;
1.127     ng       1469:     var msgchk = document.SCORE["includemsg"+usrctr].value;
1.44      ng       1470:     re = /msgsub/;
                   1471:     var shwsel = "";
                   1472:     if (re.test(msgchk)) { shwsel = "checked" }
1.123     ng       1473:     subject = (document.SCORE.shownSub.value == 0 ? checkEntities(subject) : subject);
                   1474:     displaySubject(checkEntities(subject),shwsel);
1.44      ng       1475:     for (var i=1; i<=Nmsg; i++) {
1.123     ng       1476: 	var testmsg = "savemsg"+i+",";
                   1477: 	re = new RegExp(testmsg,"g");
1.44      ng       1478: 	shwsel = "";
                   1479: 	if (re.test(msgchk)) { shwsel = "checked" }
1.125     ng       1480: 	var message = document.SCORE["savemsg"+i].value;
1.126     ng       1481: 	message = (document.SCORE["shownOnce"+i].value == 0 ? checkEntities(message) : message);
1.123     ng       1482: 	displaySavedMsg(i,message,shwsel); //I do not get it. w/o checkEntities on saved messages,
                   1483: 	                                   //any &lt; is already converted to <, etc. However, only once!!
1.44      ng       1484:     }
1.125     ng       1485:     newmsg = document.SCORE["newmsg"+usrctr].value;
1.44      ng       1486:     shwsel = "";
                   1487:     re = /newmsg/;
                   1488:     if (re.test(msgchk)) { shwsel = "checked" }
                   1489:     newMsg(newmsg,shwsel);
                   1490:     msgTail(); 
                   1491:     return;
                   1492:   }
                   1493: 
1.123     ng       1494:   function checkEntities(strx) {
                   1495:     if (strx.length == 0) return strx;
                   1496:     var orgStr = ["&", "<", ">", '"']; 
                   1497:     var newStr = ["&amp;", "&lt;", "&gt;", "&quot;"];
                   1498:     var counter = 0;
                   1499:     while (counter < 4) {
                   1500: 	strx = strReplace(strx,orgStr[counter],newStr[counter]);
                   1501: 	counter++;
                   1502:     }
                   1503:     return strx;
                   1504:   }
                   1505: 
                   1506:   function strReplace(strx, orgStr, newStr) {
                   1507:     return strx.split(orgStr).join(newStr);
                   1508:   }
                   1509: 
1.44      ng       1510:   function savedMsgHeader(Nmsg,usrctr,fullname) {
1.76      ng       1511:     var height = 70*Nmsg+250;
1.44      ng       1512:     var scrollbar = "no";
                   1513:     if (height > 600) {
                   1514: 	height = 600;
                   1515: 	scrollbar = "yes";
                   1516:     }
1.118     ng       1517:     var xpos = (screen.width-600)/2;
                   1518:     xpos = (xpos < 0) ? '0' : xpos;
                   1519:     var ypos = (screen.height-height)/2-30;
                   1520:     ypos = (ypos < 0) ? '0' : ypos;
                   1521: 
1.206     albertel 1522:     pWin = window.open('', 'MessageCenter', 'resizable=yes,toolbar=no,location=no,scrollbars='+scrollbar+',screenx='+xpos+',screeny='+ypos+',width=600,height='+height);
1.76      ng       1523:     pWin.focus();
                   1524:     pDoc = pWin.document;
1.219     www      1525:     pDoc.$docopen;
1.351     albertel 1526:     pDoc.write('$start_page_msg_central');
1.76      ng       1527: 
                   1528:     pDoc.write("<form action=\\"inactive\\" name=\\"msgcenter\\">");
                   1529:     pDoc.write("<input value=\\""+usrctr+"\\" name=\\"usrctr\\" type=\\"hidden\\">");
1.465     albertel 1530:     pDoc.write("<h3><span class=\\"LC_info\\">&nbsp;Compose Message for \"+fullname+\"<\\/span><\\/h3><br /><br />");
1.76      ng       1531: 
1.564     bisitz   1532:     pDoc.write('<table border="0" width="100%"><tr><td bgcolor="#777777">');
                   1533:     pDoc.write('<table border="0" width="100%"><tr bgcolor="#DDFFFF">');
1.465     albertel 1534:     pDoc.write("<td><b>Type<\\/b><\\/td><td><b>Include<\\/b><\\/td><td><b>Message<\\/td><\\/tr>");
1.44      ng       1535: }
                   1536:     function displaySubject(msg,shwsel) {
1.76      ng       1537:     pDoc = pWin.document;
                   1538:     pDoc.write("<tr bgcolor=\\"#ffffdd\\">");
1.465     albertel 1539:     pDoc.write("<td>Subject<\\/td>");
                   1540:     pDoc.write("<td align=\\"center\\"><input name=\\"subchk\\" type=\\"checkbox\\"" +shwsel+"><\\/td>");
                   1541:     pDoc.write("<td><input name=\\"msgsub\\" type=\\"text\\" value=\\""+msg+"\\"size=\\"60\\" maxlength=\\"80\\"><\\/td><\\/tr>");
1.44      ng       1542: }
                   1543: 
1.72      ng       1544:   function displaySavedMsg(ctr,msg,shwsel) {
1.76      ng       1545:     pDoc = pWin.document;
                   1546:     pDoc.write("<tr bgcolor=\\"#ffffdd\\">");
1.465     albertel 1547:     pDoc.write("<td align=\\"center\\">"+ctr+"<\\/td>");
                   1548:     pDoc.write("<td align=\\"center\\"><input name=\\"msgn"+ctr+"\\" type=\\"checkbox\\"" +shwsel+"><\\/td>");
                   1549:     pDoc.write("<td><textarea name=\\"msg"+ctr+"\\" cols=\\"60\\" rows=\\"3\\">"+msg+"<\\/textarea><\\/td><\\/tr>");
1.44      ng       1550: }
                   1551: 
                   1552:   function newMsg(newmsg,shwsel) {
1.76      ng       1553:     pDoc = pWin.document;
                   1554:     pDoc.write("<tr bgcolor=\\"#ffffdd\\">");
1.465     albertel 1555:     pDoc.write("<td align=\\"center\\">New<\\/td>");
                   1556:     pDoc.write("<td align=\\"center\\"><input name=\\"newmsgchk\\" type=\\"checkbox\\"" +shwsel+"><\\/td>");
                   1557:     pDoc.write("<td><textarea name=\\"newmsg\\" cols=\\"60\\" rows=\\"3\\" onchange=\\"javascript:this.form.newmsgchk.checked=true\\" >"+newmsg+"<\\/textarea><\\/td><\\/tr>");
1.44      ng       1558: }
                   1559: 
                   1560:   function msgTail() {
1.76      ng       1561:     pDoc = pWin.document;
1.465     albertel 1562:     pDoc.write("<\\/table>");
                   1563:     pDoc.write("<\\/td><\\/tr><\\/table>&nbsp;");
1.589     bisitz   1564:     pDoc.write("<input type=\\"button\\" value=\\"Save\\" onclick=\\"javascript:checkInput()\\">&nbsp;&nbsp;");
                   1565:     pDoc.write("<input type=\\"button\\" value=\\"Cancel\\" onclick=\\"self.close()\\"><br /><br />");
1.465     albertel 1566:     pDoc.write("<\\/form>");
1.351     albertel 1567:     pDoc.write('$end_page_msg_central');
1.128     ng       1568:     pDoc.close();
1.44      ng       1569: }
                   1570: 
                   1571: //====================== Script for keyword highlight options ==============
                   1572:   function kwhighlight() {
                   1573:     var kwclr    = document.SCORE.kwclr.value;
                   1574:     var kwsize   = document.SCORE.kwsize.value;
                   1575:     var kwstyle  = document.SCORE.kwstyle.value;
                   1576:     var redsel = "";
                   1577:     var grnsel = "";
                   1578:     var blusel = "";
                   1579:     if (kwclr=="red")   {var redsel="checked"};
                   1580:     if (kwclr=="green") {var grnsel="checked"};
                   1581:     if (kwclr=="blue")  {var blusel="checked"};
                   1582:     var sznsel = "";
                   1583:     var sz1sel = "";
                   1584:     var sz2sel = "";
                   1585:     if (kwsize=="0")  {var sznsel="checked"};
                   1586:     if (kwsize=="+1") {var sz1sel="checked"};
                   1587:     if (kwsize=="+2") {var sz2sel="checked"};
                   1588:     var synsel = "";
                   1589:     var syisel = "";
                   1590:     var sybsel = "";
                   1591:     if (kwstyle=="")    {var synsel="checked"};
                   1592:     if (kwstyle=="<i>") {var syisel="checked"};
                   1593:     if (kwstyle=="<b>") {var sybsel="checked"};
                   1594:     highlightCentral();
                   1595:     highlightbody('red','red',redsel,'0','normal',sznsel,'','normal',synsel);
                   1596:     highlightbody('green','green',grnsel,'+1','+1',sz1sel,'<i>','italic',syisel);
                   1597:     highlightbody('blue','blue',blusel,'+2','+2',sz2sel,'<b>','bold',sybsel);
                   1598:     highlightend();
                   1599:     return;
                   1600:   }
                   1601: 
                   1602:   function highlightCentral() {
1.76      ng       1603: //    if (window.hwdWin) window.hwdWin.close();
1.118     ng       1604:     var xpos = (screen.width-400)/2;
                   1605:     xpos = (xpos < 0) ? '0' : xpos;
                   1606:     var ypos = (screen.height-330)/2-30;
                   1607:     ypos = (ypos < 0) ? '0' : ypos;
                   1608: 
1.206     albertel 1609:     hwdWin = window.open('', 'KeywordHighlightCentral', 'resizeable=yes,toolbar=no,location=no,scrollbars=no,width=400,height=300,screenx='+xpos+',screeny='+ypos);
1.76      ng       1610:     hwdWin.focus();
                   1611:     var hDoc = hwdWin.document;
1.219     www      1612:     hDoc.$docopen;
1.351     albertel 1613:     hDoc.write('$start_page_highlight_central');
1.76      ng       1614:     hDoc.write("<form action=\\"inactive\\" name=\\"hlCenter\\">");
1.465     albertel 1615:     hDoc.write("<h3><span class=\\"LC_info\\">&nbsp;Keyword Highlight Options<\\/span><\\/h3><br /><br />");
1.76      ng       1616: 
1.564     bisitz   1617:     hDoc.write('<table border="0" width="100%"><tr><td bgcolor="#777777">');
                   1618:     hDoc.write('<table border="0" width="100%"><tr bgcolor="#DDFFFF">');
1.465     albertel 1619:     hDoc.write("<td><b>Text Color<\\/b><\\/td><td><b>Font Size<\\/b><\\/td><td><b>Font Style<\\/td><\\/tr>");
1.44      ng       1620:   }
                   1621: 
                   1622:   function highlightbody(clrval,clrtxt,clrsel,szval,sztxt,szsel,syval,sytxt,sysel) { 
1.76      ng       1623:     var hDoc = hwdWin.document;
                   1624:     hDoc.write("<tr bgcolor=\\"#ffffdd\\">");
                   1625:     hDoc.write("<td align=\\"left\\">");
1.465     albertel 1626:     hDoc.write("<input name=\\"kwdclr\\" type=\\"radio\\" value=\\""+clrval+"\\" "+clrsel+">&nbsp;"+clrtxt+"<\\/td>");
1.76      ng       1627:     hDoc.write("<td align=\\"left\\">");
1.465     albertel 1628:     hDoc.write("<input name=\\"kwdsize\\" type=\\"radio\\" value=\\""+szval+"\\" "+szsel+">&nbsp;"+sztxt+"<\\/td>");
1.76      ng       1629:     hDoc.write("<td align=\\"left\\">");
1.465     albertel 1630:     hDoc.write("<input name=\\"kwdstyle\\" type=\\"radio\\" value=\\""+syval+"\\" "+sysel+">&nbsp;"+sytxt+"<\\/td>");
                   1631:     hDoc.write("<\\/tr>");
1.44      ng       1632:   }
                   1633: 
                   1634:   function highlightend() { 
1.76      ng       1635:     var hDoc = hwdWin.document;
1.465     albertel 1636:     hDoc.write("<\\/table>");
                   1637:     hDoc.write("<\\/td><\\/tr><\\/table>&nbsp;");
1.589     bisitz   1638:     hDoc.write("<input type=\\"button\\" value=\\"Save\\" onclick=\\"javascript:updateChoice(1)\\">&nbsp;&nbsp;");
                   1639:     hDoc.write("<input type=\\"button\\" value=\\"Cancel\\" onclick=\\"self.close()\\"><br /><br />");
1.465     albertel 1640:     hDoc.write("<\\/form>");
1.351     albertel 1641:     hDoc.write('$end_page_highlight_central');
1.128     ng       1642:     hDoc.close();
1.44      ng       1643:   }
                   1644: 
                   1645: SUBJAVASCRIPT
                   1646: }
                   1647: 
1.349     albertel 1648: sub get_increment {
1.348     bowersj2 1649:     my $increment = $env{'form.increment'};
                   1650:     if ($increment != 1 && $increment != .5 && $increment != .25 &&
                   1651:         $increment != .1) {
                   1652:         $increment = 1;
                   1653:     }
                   1654:     return $increment;
                   1655: }
                   1656: 
1.585     bisitz   1657: sub gradeBox_start {
                   1658:     return (
                   1659:         &Apache::loncommon::start_data_table()
                   1660:        .&Apache::loncommon::start_data_table_header_row()
                   1661:        .'<th>'.&mt('Part').'</th>'
                   1662:        .'<th>'.&mt('Points').'</th>'
                   1663:        .'<th>&nbsp;</th>'
                   1664:        .'<th>'.&mt('Assign Grade').'</th>'
                   1665:        .'<th>'.&mt('Weight').'</th>'
                   1666:        .'<th>'.&mt('Grade Status').'</th>'
                   1667:        .&Apache::loncommon::end_data_table_header_row()
                   1668:     );
                   1669: }
                   1670: 
                   1671: sub gradeBox_end {
                   1672:     return (
                   1673:         &Apache::loncommon::end_data_table()
                   1674:     );
                   1675: }
1.71      ng       1676: #--- displays the grading box, used in essay type problem and grading by page/sequence
                   1677: sub gradeBox {
1.322     albertel 1678:     my ($request,$symb,$uname,$udom,$counter,$partid,$record) = @_;
1.381     albertel 1679:     my $checkIcon = '<img alt="'.&mt('Check Mark').
1.485     albertel 1680: 	'" src="'.&Apache::loncommon::lonhttpdurl($request->dir_config('lonIconsURL').'/check.gif').'" height="16" border="0" />';
1.71      ng       1681:     my $wgt    = &Apache::lonnet::EXT('resource.'.$partid.'.weight',$symb,$udom,$uname);
1.466     albertel 1682:     my $wgtmsg = ($wgt > 0) ? &mt('(problem weight)') 
                   1683:                            : '<span class="LC_info">'.&mt('problem weight assigned by computer').'</span>';
1.71      ng       1684:     $wgt       = ($wgt > 0 ? $wgt : '1');
                   1685:     my $score  = ($$record{'resource.'.$partid.'.awarded'} eq '' ?
1.320     albertel 1686: 		  '' : &compute_points($$record{'resource.'.$partid.'.awarded'},$wgt));
1.71      ng       1687:     my $result='<input type="hidden" name="WGT'.$counter.'_'.$partid.'" value="'.$wgt.'" />'."\n";
1.466     albertel 1688:     my $display_part= &get_display_part($partid,$symb);
1.270     albertel 1689:     my %last_resets = &get_last_resets($symb,$env{'request.course.id'},
                   1690: 				       [$partid]);
                   1691:     my $aggtries = $$record{'resource.'.$partid.'.tries'};
1.269     raeburn  1692:     if ($last_resets{$partid}) {
                   1693:         $aggtries = &get_num_tries($record,$last_resets{$partid},$partid);
                   1694:     }
1.585     bisitz   1695:     $result.=&Apache::loncommon::start_data_table_row();
1.71      ng       1696:     my $ctr = 0;
1.348     bowersj2 1697:     my $thisweight = 0;
1.349     albertel 1698:     my $increment = &get_increment();
1.485     albertel 1699: 
                   1700:     my $radio.='<table border="0"><tr>'."\n";  # display radio buttons in a nice table 10 across
1.348     bowersj2 1701:     while ($thisweight<=$wgt) {
1.532     bisitz   1702: 	$radio.= '<td><span class="LC_nobreak"><label><input type="radio" name="RADVAL'.$counter.'_'.$partid.'" '.
1.589     bisitz   1703:         'onclick="javascript:writeBox(this.form,\''.$counter.'_'.$partid.'\','.
1.348     bowersj2 1704: 	    $thisweight.')" value="'.$thisweight.'" '.
1.401     albertel 1705: 	    ($score eq $thisweight ? 'checked="checked"':'').' /> '.$thisweight."</label></span></td>\n";
1.485     albertel 1706: 	$radio.=(($ctr+1)%10 == 0 ? '</tr><tr>' : '');
1.348     bowersj2 1707:         $thisweight += $increment;
1.71      ng       1708: 	$ctr++;
                   1709:     }
1.485     albertel 1710:     $radio.='</tr></table>';
                   1711: 
                   1712:     my $line.='<input type="text" name="GD_BOX'.$counter.'_'.$partid.'"'.
1.71      ng       1713: 	($score ne ''? ' value = "'.$score.'"':'').' size="4" '.
1.589     bisitz   1714: 	'onchange="javascript:updateRadio(this.form,\''.$counter.'_'.$partid.'\','.
1.71      ng       1715: 	$wgt.')" /></td>'."\n";
1.485     albertel 1716:     $line.='<td>/'.$wgt.' '.$wgtmsg.
1.71      ng       1717: 	($$record{'resource.'.$partid.'.solved'} eq 'correct_by_student' ? '&nbsp;'.$checkIcon : '').
1.585     bisitz   1718: 	' </td>'."\n";
                   1719:     $line.='<td><select name="GD_SEL'.$counter.'_'.$partid.'" '.
1.589     bisitz   1720: 	'onchange="javascript:clearRadBox(this.form,\''.$counter.'_'.$partid.'\')" >'."\n";
1.71      ng       1721:     if ($$record{'resource.'.$partid.'.solved'} eq 'excused') {
1.485     albertel 1722: 	$line.='<option></option>'.
                   1723: 	    '<option value="excused" selected="selected">'.&mt('excused').'</option>';
1.71      ng       1724:     } else {
1.485     albertel 1725: 	$line.='<option selected="selected"></option>'.
                   1726: 	    '<option value="excused" >'.&mt('excused').'</option>';
1.71      ng       1727:     }
1.485     albertel 1728:     $line.='<option value="reset status">'.&mt('reset status').'</option></select>'."\n";
                   1729: 
                   1730: 
                   1731:     $result .= 
1.585     bisitz   1732: 	    '<td>'.$display_part.'</td><td>'.$radio.'</td><td>'.&mt('or').'</td><td>'.$line.'</td>';
                   1733:     $result.=&Apache::loncommon::end_data_table_row();
1.71      ng       1734:     $result.='<input type="hidden" name="stores'.$counter.'_'.$partid.'" value="" />'."\n".
                   1735: 	'<input type="hidden" name="oldpts'.$counter.'_'.$partid.'" value="'.$score.'" />'."\n".
                   1736: 	'<input type="hidden" name="solved'.$counter.'_'.$partid.'" value="'.
1.269     raeburn  1737: 	$$record{'resource.'.$partid.'.solved'}.'" />'."\n".
                   1738:         '<input type="hidden" name="totaltries'.$counter.'_'.$partid.'" value="'.
                   1739:         $$record{'resource.'.$partid.'.tries'}.'" />'."\n".
                   1740:         '<input type="hidden" name="aggtries'.$counter.'_'.$partid.'" value="'.
                   1741:         $aggtries.'" />'."\n";
1.582     raeburn  1742:     my $res_error;
                   1743:     $result.=&handback_box($symb,$uname,$udom,$counter,$partid,$record,\$res_error);
                   1744:     if ($res_error) {
                   1745:         return &navmap_errormsg();
                   1746:     }
1.318     banghart 1747:     return $result;
                   1748: }
1.322     albertel 1749: 
                   1750: sub handback_box {
1.582     raeburn  1751:     my ($symb,$uname,$udom,$counter,$partid,$record,$res_error) = @_;
                   1752:     my ($partlist,$handgrade,$responseType) = &response_type($symb,$res_error);
1.323     banghart 1753:     my (@respids);
1.375     albertel 1754:      my @part_response_id = &flatten_responseType($responseType);
                   1755:     foreach my $part_response_id (@part_response_id) {
                   1756:     	my ($part,$resp) = @{ $part_response_id };
1.323     banghart 1757:         if ($part eq $partid) {
1.375     albertel 1758:             push(@respids,$resp);
1.323     banghart 1759:         }
                   1760:     }
1.318     banghart 1761:     my $result;
1.323     banghart 1762:     foreach my $respid (@respids) {
1.322     albertel 1763: 	my $prefix = $counter.'_'.$partid.'_'.$respid.'_';
                   1764: 	my $files=&get_submitted_files($udom,$uname,$partid,$respid,$record);
                   1765: 	next if (!@$files);
                   1766: 	my $file_counter = 1;
1.313     banghart 1767: 	foreach my $file (@$files) {
1.368     banghart 1768: 	    if ($file =~ /\/portfolio\//) {
                   1769:     	        my ($file_path, $file_disp) = ($file =~ m|(.+/)(.+)$|);
                   1770:     	        my ($name,$version,$ext) = &file_name_version_ext($file_disp);
                   1771:     	        $file_disp = "$name.$ext";
                   1772:     	        $file = $file_path.$file_disp;
                   1773:     	        $result.=&mt('Return commented version of [_1] to student.',
                   1774:     			 '<span class="LC_filename">'.$file_disp.'</span>');
                   1775:     	        $result.='<input type="file"   name="'.$prefix.'returndoc'.$file_counter.'" />'."\n";
                   1776:     	        $result.='<input type="hidden" name="'.$prefix.'origdoc'.$file_counter.'" value="'.$file.'" /><br />';
1.485     albertel 1777:     	        $result.='('.&mt('File will be uploaded when you click on Save &amp; Next below.').')<br />';
1.368     banghart 1778:     	        $file_counter++;
                   1779: 	    }
1.322     albertel 1780: 	}
1.313     banghart 1781:     }
1.318     banghart 1782:     return $result;    
1.71      ng       1783: }
1.44      ng       1784: 
1.58      albertel 1785: sub show_problem {
1.382     albertel 1786:     my ($request,$symb,$uname,$udom,$removeform,$viewon,$mode,$form) = @_;
1.144     albertel 1787:     my $rendered;
1.382     albertel 1788:     my %form = ((ref($form) eq 'HASH')? %{$form} : ());
1.329     albertel 1789:     &Apache::lonxml::remember_problem_counter();
1.144     albertel 1790:     if ($mode eq 'both' or $mode eq 'text') {
                   1791: 	$rendered=&Apache::loncommon::get_student_view($symb,$uname,$udom,
1.382     albertel 1792: 						       $env{'request.course.id'},
                   1793: 						       undef,\%form);
1.144     albertel 1794:     }
1.58      albertel 1795:     if ($removeform) {
                   1796: 	$rendered=~s|<form(.*?)>||g;
                   1797: 	$rendered=~s|</form>||g;
1.374     albertel 1798: 	$rendered=~s|(<input[^>]*name\s*=\s*"?)(\w+)("?)|$1would_have_been_$2$3|g;
1.58      albertel 1799:     }
1.144     albertel 1800:     my $companswer;
                   1801:     if ($mode eq 'both' or $mode eq 'answer') {
1.329     albertel 1802: 	&Apache::lonxml::restore_problem_counter();
1.382     albertel 1803: 	$companswer=
                   1804: 	    &Apache::loncommon::get_student_answers($symb,$uname,$udom,
                   1805: 						    $env{'request.course.id'},
                   1806: 						    %form);
1.144     albertel 1807:     }
1.58      albertel 1808:     if ($removeform) {
                   1809: 	$companswer=~s|<form(.*?)>||g;
                   1810: 	$companswer=~s|</form>||g;
1.144     albertel 1811: 	$companswer=~s|name="submit"|name="would_have_been_submit"|g;
1.58      albertel 1812:     }
1.468     albertel 1813:     $rendered=
1.588     bisitz   1814:         '<div class="LC_Box">'
                   1815:        .'<h3 class="LC_hcell">'.&mt('View of the problem').'</h3>'
                   1816:        .$rendered
                   1817:        .'</div>';
1.468     albertel 1818:     $companswer=
1.588     bisitz   1819:         '<div class="LC_Box">'
                   1820:        .'<h3 class="LC_hcell">'.&mt('Correct answer').'</h3>'
                   1821:        .$companswer
                   1822:        .'</div>';
1.468     albertel 1823:     my $result;
1.144     albertel 1824:     if ($mode eq 'both') {
1.588     bisitz   1825:         $result=$rendered.$companswer;
1.144     albertel 1826:     } elsif ($mode eq 'text') {
1.588     bisitz   1827:         $result=$rendered;
1.144     albertel 1828:     } elsif ($mode eq 'answer') {
1.588     bisitz   1829:         $result=$companswer;
1.144     albertel 1830:     }
1.71      ng       1831:     return $result;
1.58      albertel 1832: }
1.397     albertel 1833: 
1.396     banghart 1834: sub files_exist {
                   1835:     my ($r, $symb) = @_;
                   1836:     my @students = &Apache::loncommon::get_env_multiple('form.stuinfo');
1.397     albertel 1837: 
1.396     banghart 1838:     foreach my $student (@students) {
                   1839:         my ($uname,$udom,$fullname) = split(/:/,$student);
1.397     albertel 1840:         my %record = &Apache::lonnet::restore($symb,$env{'request.course.id'},
                   1841: 					      $udom,$uname);
1.396     banghart 1842:         my ($string,$timestamp)= &get_last_submission(\%record);
1.397     albertel 1843:         foreach my $submission (@$string) {
                   1844:             my ($partid,$respid) =
                   1845: 		($submission =~ /^resource\.([^\.]*)\.([^\.]*)\.submission/);
                   1846:             my $files=&get_submitted_files($udom,$uname,$partid,$respid,
                   1847: 					   \%record);
                   1848:             return 1 if (@$files);
1.396     banghart 1849:         }
                   1850:     }
1.397     albertel 1851:     return 0;
1.396     banghart 1852: }
1.397     albertel 1853: 
1.394     banghart 1854: sub download_all_link {
                   1855:     my ($r,$symb) = @_;
1.395     albertel 1856:     my $all_students = 
                   1857: 	join("\n", &Apache::loncommon::get_env_multiple('form.stuinfo'));
                   1858: 
                   1859:     my $parts =
                   1860: 	join("\n",&Apache::loncommon::get_env_multiple('form.vPart'));
                   1861: 
1.394     banghart 1862:     my $identifier = &Apache::loncommon::get_cgi_id();
1.514     raeburn  1863:     &Apache::lonnet::appenv({'cgi.'.$identifier.'.students' => $all_students,
                   1864:                              'cgi.'.$identifier.'.symb' => $symb,
                   1865:                              'cgi.'.$identifier.'.parts' => $parts,});
1.395     albertel 1866:     $r->print('<a href="/cgi-bin/multidownload.pl?'.$identifier.'">'.
                   1867: 	      &mt('Download All Submitted Documents').'</a>');
1.394     banghart 1868:     return
                   1869: }
1.395     albertel 1870: 
1.432     banghart 1871: sub build_section_inputs {
                   1872:     my $section_inputs;
                   1873:     if ($env{'form.section'} eq '') {
                   1874:         $section_inputs .= '<input type="hidden" name="section" value="all" />'."\n";
                   1875:     } else {
                   1876:         my @sections = &Apache::loncommon::get_env_multiple('form.section');
1.434     albertel 1877:         foreach my $section (@sections) {
1.432     banghart 1878:             $section_inputs .= '<input type="hidden" name="section" value="'.$section.'" />'."\n";
                   1879:         }
                   1880:     }
                   1881:     return $section_inputs;
                   1882: }
                   1883: 
1.44      ng       1884: # --------------------------- show submissions of a student, option to grade 
                   1885: sub submission {
1.608     www      1886:     my ($request,$counter,$total,$symb) = @_;
1.257     albertel 1887:     my ($uname,$udom)     = ($env{'form.student'},$env{'form.userdom'});
                   1888:     $udom = ($udom eq '' ? $env{'user.domain'} : $udom); #has form.userdom changed for a student?
                   1889:     my $usec = &Apache::lonnet::getsection($udom,$uname,$env{'request.course.id'});
                   1890:     $env{'form.fullname'} = &Apache::loncommon::plainname($uname,$udom,'lastname') if $env{'form.fullname'} eq '';
1.608     www      1891: 
1.605     www      1892:     my $probtitle=&Apache::lonnet::gettitle($symb); 
1.324     albertel 1893:     if ($symb eq '') { $request->print("Unable to handle ambiguous references:."); return ''; }
1.104     albertel 1894: 
                   1895:     if (!&canview($usec)) {
1.398     albertel 1896: 	$request->print('<span class="LC_warning">Unable to view requested student.('.
                   1897: 			$uname.':'.$udom.' in section '.$usec.' in course id '.
                   1898: 			$env{'request.course.id'}.')</span>');
1.324     albertel 1899: 	$request->print(&show_grading_menu_form($symb));
1.104     albertel 1900: 	return;
                   1901:     }
                   1902: 
1.257     albertel 1903:     if (!$env{'form.lastSub'}) { $env{'form.lastSub'} = 'datesub'; }
                   1904:     if (!$env{'form.vProb'}) { $env{'form.vProb'} = 'yes'; }
                   1905:     if (!$env{'form.vAns'}) { $env{'form.vAns'} = 'yes'; }
                   1906:     my $last = ($env{'form.lastSub'} eq 'last' ? 'last' : '');
1.381     albertel 1907:     my $checkIcon = '<img alt="'.&mt('Check Mark').
                   1908: 	'" src="'.$request->dir_config('lonIconsURL').
1.122     ng       1909: 	'/check.gif" height="16" border="0" />';
1.41      ng       1910: 
1.426     albertel 1911:     my %old_essays;
1.41      ng       1912:     # header info
                   1913:     if ($counter == 0) {
                   1914: 	&sub_page_js($request);
1.257     albertel 1915: 	&sub_page_kw_js($request) if ($env{'form.handgrade'} eq 'yes');
1.397     albertel 1916: 	if ($env{'form.handgrade'} eq 'yes' && &files_exist($request, $symb)) {
1.396     banghart 1917: 	    &download_all_link($request, $symb);
                   1918: 	}
1.605     www      1919: 	$request->print('<h3>&nbsp;<span class="LC_info">'.&mt('Submission Record').'</span></h3>');
1.118     ng       1920: 
1.44      ng       1921: 	# option to display problem, only once else it cause problems 
                   1922:         # with the form later since the problem has a form.
1.257     albertel 1923: 	if ($env{'form.vProb'} eq 'yes' or $env{'form.vAns'} eq 'yes') {
1.144     albertel 1924: 	    my $mode;
1.257     albertel 1925: 	    if ($env{'form.vProb'} eq 'yes' && $env{'form.vAns'} eq 'yes') {
1.144     albertel 1926: 		$mode='both';
1.257     albertel 1927: 	    } elsif ($env{'form.vProb'} eq 'yes') {
1.144     albertel 1928: 		$mode='text';
1.257     albertel 1929: 	    } elsif ($env{'form.vAns'} eq 'yes') {
1.144     albertel 1930: 		$mode='answer';
                   1931: 	    }
1.329     albertel 1932: 	    &Apache::lonxml::clear_problem_counter();
1.144     albertel 1933: 	    $request->print(&show_problem($request,$symb,$uname,$udom,0,1,$mode));
1.41      ng       1934: 	}
1.441     www      1935: 
1.44      ng       1936: 	# kwclr is the only variable that is guaranteed to be non blank 
                   1937:         # if this subroutine has been called once.
1.41      ng       1938: 	my %keyhash = ();
1.257     albertel 1939: 	if ($env{'form.kwclr'} eq '' && $env{'form.handgrade'} eq 'yes') {
1.41      ng       1940: 	    %keyhash = &Apache::lonnet::dump('nohist_handgrade',
1.257     albertel 1941: 					     $env{'course.'.$env{'request.course.id'}.'.domain'},
                   1942: 					     $env{'course.'.$env{'request.course.id'}.'.num'});
1.41      ng       1943: 
1.257     albertel 1944: 	    my $loginuser = $env{'user.name'}.':'.$env{'user.domain'};
                   1945: 	    $env{'form.keywords'} = $keyhash{$symb.'_keywords'} ne '' ? $keyhash{$symb.'_keywords'} : '';
                   1946: 	    $env{'form.kwclr'}    = $keyhash{$loginuser.'_kwclr'} ne '' ? $keyhash{$loginuser.'_kwclr'} : 'red';
                   1947: 	    $env{'form.kwsize'}   = $keyhash{$loginuser.'_kwsize'} ne '' ? $keyhash{$loginuser.'_kwsize'} : '0';
                   1948: 	    $env{'form.kwstyle'}  = $keyhash{$loginuser.'_kwstyle'} ne '' ? $keyhash{$loginuser.'_kwstyle'} : '';
                   1949: 	    $env{'form.msgsub'}   = $keyhash{$symb.'_subject'} ne '' ? 
1.605     www      1950: 		$keyhash{$symb.'_subject'} : $probtitle;
1.257     albertel 1951: 	    $env{'form.savemsgN'} = $keyhash{$symb.'_savemsgN'} ne '' ? $keyhash{$symb.'_savemsgN'} : '0';
1.41      ng       1952: 	}
1.257     albertel 1953: 	my $overRideScore = $env{'form.overRideScore'} eq '' ? 'no' : $env{'form.overRideScore'};
1.442     banghart 1954: 	my $stu_status = join(':',&Apache::loncommon::get_env_multiple('form.Status'));
1.303     banghart 1955: 	$request->print('<form action="/adm/grades" method="post" name="SCORE" enctype="multipart/form-data">'."\n".
1.41      ng       1956: 			'<input type="hidden" name="command"    value="handgrade" />'."\n".
1.442     banghart 1957: 			'<input type="hidden" name="Status"     value="'.$stu_status.'" />'."\n".
1.120     ng       1958: 			'<input type="hidden" name="overRideScore" value="'.$overRideScore.'" />'."\n".
1.41      ng       1959: 			'<input type="hidden" name="refresh"    value="off" />'."\n".
1.120     ng       1960: 			'<input type="hidden" name="studentNo"  value="" />'."\n".
                   1961: 			'<input type="hidden" name="gradeOpt"   value="" />'."\n".
1.418     albertel 1962: 			'<input type="hidden" name="symb"       value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
1.257     albertel 1963: 			'<input type="hidden" name="showgrading" value="'.$env{'form.showgrading'}.'" />'."\n".
                   1964: 			'<input type="hidden" name="vProb"      value="'.$env{'form.vProb'}.'" />'."\n".
                   1965: 			'<input type="hidden" name="vAns"       value="'.$env{'form.vAns'}.'" />'."\n".
                   1966: 			'<input type="hidden" name="lastSub"    value="'.$env{'form.lastSub'}.'" />'."\n".
1.432     banghart 1967: 			&build_section_inputs().
1.326     albertel 1968: 			'<input type="hidden" name="submitonly" value="'.$env{'form.submitonly'}.'" />'."\n".
                   1969: 			'<input type="hidden" name="handgrade"  value="'.$env{'form.handgrade'}.'" />'."\n".
1.41      ng       1970: 			'<input type="hidden" name="NCT"'.
1.257     albertel 1971: 			' value="'.($env{'form.NTSTU'} ne '' ? $env{'form.NTSTU'} : $total+1).'" />'."\n");
                   1972: 	if ($env{'form.handgrade'} eq 'yes') {
                   1973: 	    $request->print('<input type="hidden" name="keywords" value="'.$env{'form.keywords'}.'" />'."\n".
                   1974: 			    '<input type="hidden" name="kwclr"    value="'.$env{'form.kwclr'}.'" />'."\n".
                   1975: 			    '<input type="hidden" name="kwsize"   value="'.$env{'form.kwsize'}.'" />'."\n".
                   1976: 			    '<input type="hidden" name="kwstyle"  value="'.$env{'form.kwstyle'}.'" />'."\n".
                   1977: 			    '<input type="hidden" name="msgsub"   value="'.$env{'form.msgsub'}.'" />'."\n".
1.123     ng       1978: 			    '<input type="hidden" name="shownSub" value="0" />'."\n".
1.257     albertel 1979: 			    '<input type="hidden" name="savemsgN" value="'.$env{'form.savemsgN'}.'" />'."\n");
1.154     albertel 1980: 	    foreach my $partid (&Apache::loncommon::get_env_multiple('form.vPart')) {
                   1981: 		$request->print('<input type="hidden" name="vPart" value="'.$partid.'" />'."\n");
                   1982: 	    }
1.123     ng       1983: 	}
1.41      ng       1984: 	
                   1985: 	my ($cts,$prnmsg) = (1,'');
1.257     albertel 1986: 	while ($cts <= $env{'form.savemsgN'}) {
1.41      ng       1987: 	    $prnmsg.='<input type="hidden" name="savemsg'.$cts.'" value="'.
1.123     ng       1988: 		(!exists($keyhash{$symb.'_savemsg'.$cts}) ? 
1.257     albertel 1989: 		 &Apache::lonfeedback::clear_out_html($env{'form.savemsg'.$cts}) :
1.80      ng       1990: 		 &Apache::lonfeedback::clear_out_html($keyhash{$symb.'_savemsg'.$cts})).
1.123     ng       1991: 		'" />'."\n".
                   1992: 		'<input type="hidden" name="shownOnce'.$cts.'" value="0" />'."\n";
1.41      ng       1993: 	    $cts++;
                   1994: 	}
                   1995: 	$request->print($prnmsg);
1.32      ng       1996: 
1.257     albertel 1997: 	if ($env{'form.handgrade'} eq 'yes' && $env{'form.showgrading'} eq 'yes') {
1.88      www      1998: #
                   1999: # Print out the keyword options line
                   2000: #
1.41      ng       2001: 	    $request->print(<<KEYWORDS);
1.38      ng       2002: &nbsp;<b>Keyword Options:</b>&nbsp;
1.417     albertel 2003: <a href="javascript:keywords(document.SCORE);" target="_self">List</a>&nbsp; &nbsp;
1.589     bisitz   2004: <a href="#" onmousedown="javascript:getSel(); return false"
1.38      ng       2005:  CLASS="page">Paste Selection to List</a>&nbsp; &nbsp;
1.417     albertel 2006: <a href="javascript:kwhighlight();" target="_self">Highlight Attribute</a><br /><br />
1.38      ng       2007: KEYWORDS
1.88      www      2008: #
                   2009: # Load the other essays for similarity check
                   2010: #
1.324     albertel 2011:             my (undef,undef,$essayurl) = &Apache::lonnet::decode_symb($symb);
1.384     albertel 2012: 	    my ($adom,$aname,$apath)=($essayurl=~/^($LONCAPA::domain_re)\/($LONCAPA::username_re)\/(.*)$/);
1.359     www      2013: 	    $apath=&escape($apath);
1.88      www      2014: 	    $apath=~s/\W/\_/gs;
1.426     albertel 2015: 	    %old_essays=&Apache::lonnet::dump('nohist_essay_'.$apath,$adom,$aname);
1.41      ng       2016:         }
                   2017:     }
1.44      ng       2018: 
1.441     www      2019: # This is where output for one specific student would start
1.592     bisitz   2020:     my $add_class = ($counter%2) ? ' LC_grade_show_user_odd_row' : '';
                   2021:     $request->print(
                   2022:         "\n\n"
                   2023:        .'<div class="LC_grade_show_user'.$add_class.'">'
                   2024:        .'<h2>'.&nameUserString(undef,$env{'form.fullname'},$uname,$udom).'</h2>'
                   2025:        ."\n"
                   2026:     );
1.441     www      2027: 
1.592     bisitz   2028:     # Show additional functions if allowed
                   2029:     if ($perm{'vgr'}) {
                   2030:         $request->print(
                   2031:             &Apache::loncommon::track_student_link(
                   2032:                 &mt('View recent activity'),
                   2033:                 $uname,$udom,'check')
                   2034:            .' '
                   2035:         );
                   2036:     }
                   2037:     if ($perm{'opa'}) {
                   2038:         $request->print(
                   2039:             &Apache::loncommon::pprmlink(
                   2040:                 &mt('Set/Change parameters'),
                   2041:                 $uname,$udom,$symb,'check'));
                   2042:     }
                   2043: 
                   2044:     # Show Problem
1.257     albertel 2045:     if ($env{'form.vProb'} eq 'all' or $env{'form.vAns'} eq 'all') {
1.144     albertel 2046: 	my $mode;
1.257     albertel 2047: 	if ($env{'form.vProb'} eq 'all' && $env{'form.vAns'} eq 'all') {
1.144     albertel 2048: 	    $mode='both';
1.257     albertel 2049: 	} elsif ($env{'form.vProb'} eq 'all' ) {
1.144     albertel 2050: 	    $mode='text';
1.257     albertel 2051: 	} elsif ($env{'form.vAns'} eq 'all') {
1.144     albertel 2052: 	    $mode='answer';
                   2053: 	}
1.329     albertel 2054: 	&Apache::lonxml::clear_problem_counter();
1.475     albertel 2055: 	$request->print(&show_problem($request,$symb,$uname,$udom,1,1,$mode,{'request.prefix' => 'ctr'.$counter}));
1.58      albertel 2056:     }
1.144     albertel 2057: 
1.257     albertel 2058:     my %record = &Apache::lonnet::restore($symb,$env{'request.course.id'},$udom,$uname);
1.582     raeburn  2059:     my $res_error;
                   2060:     my ($partlist,$handgrade,$responseType) = &response_type($symb,\$res_error);
                   2061:     if ($res_error) {
                   2062:         $request->print(&navmap_errormsg());
                   2063:         return;
                   2064:     }
1.41      ng       2065: 
1.44      ng       2066:     # Display student info
1.41      ng       2067:     $request->print(($counter == 0 ? '' : '<br />'));
1.590     bisitz   2068: 
                   2069:     my $result='<div class="LC_Box">'
                   2070:               .'<h3 class="LC_hcell">'.&mt('Submissions').'</h3>';
1.45      ng       2071:     $result.='<input type="hidden" name="name'.$counter.
1.588     bisitz   2072:              '" value="'.$env{'form.fullname'}.'" />'."\n";
1.469     albertel 2073:     if ($env{'form.handgrade'} eq 'no') {
1.588     bisitz   2074:         $result.='<p class="LC_info">'
                   2075:                 .&mt('Part(s) graded correct by the computer is marked with a [_1] symbol.',$checkIcon)
                   2076:                 ."</p>\n";
1.469     albertel 2077:     }
                   2078: 
1.118     ng       2079:     # If any part of the problem is an essay-response (handgraded), then check for collaborators
1.464     albertel 2080:     my $fullname;
                   2081:     my $col_fullnames = [];
1.257     albertel 2082:     if ($env{'form.handgrade'} eq 'yes') {
1.464     albertel 2083: 	(my $sub_result,$fullname,$col_fullnames)=
                   2084: 	    &check_collaborators($symb,$uname,$udom,\%record,$handgrade,
                   2085: 				 $counter);
                   2086: 	$result.=$sub_result;
1.41      ng       2087:     }
1.44      ng       2088:     $request->print($result."\n");
1.588     bisitz   2089: 
1.44      ng       2090:     # print student answer/submission
1.588     bisitz   2091:     # Options are (1) Handgraded submission only
1.44      ng       2092:     #             (2) Last submission, includes submission that is not handgraded 
                   2093:     #                  (for multi-response type part)
                   2094:     #             (3) Last submission plus the parts info
                   2095:     #             (4) The whole record for this student
1.257     albertel 2096:     if ($env{'form.lastSub'} =~ /^(lastonly|hdgrade)$/) {
1.151     albertel 2097: 	my ($string,$timestamp)= &get_last_submission(\%record);
1.468     albertel 2098: 	
                   2099: 	my $lastsubonly;
                   2100: 
1.588     bisitz   2101:         if ($$timestamp eq '') {
                   2102:             $lastsubonly.='<div class="LC_grade_submissions_body">'.$$string[0].'</div>'; 
                   2103:         } else {
1.592     bisitz   2104:             $lastsubonly =
                   2105:                 '<div class="LC_grade_submissions_body">'
                   2106:                .'<b>'.&mt('Date Submitted:').'</b> '.$$timestamp."\n";
1.468     albertel 2107: 
1.151     albertel 2108: 	    my %seenparts;
1.375     albertel 2109: 	    my @part_response_id = &flatten_responseType($responseType);
                   2110: 	    foreach my $part (@part_response_id) {
1.393     albertel 2111: 		next if ($env{'form.lastSub'} eq 'hdgrade' 
                   2112: 			 && $$handgrade{$$part[0].'_'.$$part[1]} ne 'yes');
                   2113: 
1.375     albertel 2114: 		my ($partid,$respid) = @{ $part };
1.324     albertel 2115: 		my $display_part=&get_display_part($partid,$symb);
1.257     albertel 2116: 		if ($env{"form.$uname:$udom:$partid:submitted_by"}) {
1.151     albertel 2117: 		    if (exists($seenparts{$partid})) { next; }
                   2118: 		    $seenparts{$partid}=1;
1.207     albertel 2119: 		    my $submitby='<b>Part:</b> '.$display_part.
                   2120: 			' <b>Collaborative submission by:</b> '.
1.151     albertel 2121: 			'<a href="javascript:viewSubmitter(\''.
1.257     albertel 2122: 			$env{"form.$uname:$udom:$partid:submitted_by"}.
1.417     albertel 2123: 			'\');" target="_self">'.
1.257     albertel 2124: 			$$fullname{$env{"form.$uname:$udom:$partid:submitted_by"}}.'</a><br />';
1.151     albertel 2125: 		    $request->print($submitby);
                   2126: 		    next;
                   2127: 		}
                   2128: 		my $responsetype = $responseType->{$partid}->{$respid};
                   2129: 		if (!exists($record{"resource.$partid.$respid.submission"})) {
1.577     bisitz   2130:                     $lastsubonly.="\n".'<div class="LC_grade_submission_part">'.
                   2131:                         '<b>'.&mt('Part: [_1]',$display_part).'</b>'.
                   2132:                         ' <span class="LC_internal_info">'.
1.597     wenzelju 2133:                         '('.&mt('Part ID: [_1]',$respid).')'.
1.577     bisitz   2134:                         '</span>&nbsp; &nbsp;'.
1.539     riegler  2135: 			'<span class="LC_warning">'.&mt('Nothing submitted - no attempts.').'</span><br /><br /></div>';
1.151     albertel 2136: 		    next;
                   2137: 		}
1.468     albertel 2138: 		foreach my $submission (@$string) {
                   2139: 		    my ($partid,$respid) = ($submission =~ /^resource\.([^\.]*)\.([^\.]*)\.submission/);
1.375     albertel 2140: 		    if (join('_',@{$part}) ne ($partid.'_'.$respid)) { next; }
1.596     raeburn  2141: 		    my ($ressub,$hide,$subval) = split(/:/,$submission,3);
1.151     albertel 2142: 		    # Similarity check
                   2143: 		    my $similar='';
1.257     albertel 2144: 		    if($env{'form.checkPlag'}){
1.151     albertel 2145: 			my ($oname,$odom,$ocrsid,$oessay,$osim)=
1.426     albertel 2146: 			    &most_similar($uname,$udom,$subval,\%old_essays);
1.151     albertel 2147: 			if ($osim) {
                   2148: 			    $osim=int($osim*100.0);
1.426     albertel 2149: 			    my %old_course_desc = 
                   2150: 				&Apache::lonnet::coursedescription($ocrsid,
                   2151: 								   {'one_time' => 1});
                   2152: 
1.596     raeburn  2153:                             if ($hide) {
                   2154:                                 $similar='<hr /><span class="LC_warning">'.&mt("Essay was found to be similar to another essay submitted for this assignment.").'<br />'.
                   2155:                                          &mt('As the current submission is for an anonymous survey, no other details are available.').'</span><hr />';
                   2156:                             } else {
                   2157: 			        $similar="<hr /><h3><span class=\"LC_warning\">".
                   2158: 				    &mt('Essay is [_1]% similar to an essay by [_2] in course [_3] (course id [_4]:[_5])',
                   2159: 				        $osim,
                   2160: 				        &Apache::loncommon::plainname($oname,$odom).' ('.$oname.':'.$odom.')',
                   2161: 				        $old_course_desc{'description'},
                   2162: 				        $old_course_desc{'num'},
                   2163: 				        $old_course_desc{'domain'}).
                   2164: 				    '</span></h3><blockquote><i>'.
                   2165: 				    &keywords_highlight($oessay).
                   2166: 				    '</i></blockquote><hr />';
                   2167:                             }
1.151     albertel 2168: 			}
1.150     albertel 2169: 		    }
1.151     albertel 2170: 		    my $order=&get_order($partid,$respid,$symb,$uname,$udom);
1.257     albertel 2171: 		    if ($env{'form.lastSub'} eq 'lastonly' || 
                   2172: 			($env{'form.lastSub'} eq 'hdgrade' && 
1.377     albertel 2173: 			 $$handgrade{$$part[0].'_'.$$part[1]} eq 'yes')) {
1.324     albertel 2174: 			my $display_part=&get_display_part($partid,$symb);
1.577     bisitz   2175:                         $lastsubonly.='<div class="LC_grade_submission_part">'.
                   2176:                             '<b>'.&mt('Part: [_1]',$display_part).'</b>'.
                   2177:                             ' <span class="LC_internal_info">'.
                   2178:                             '('.&mt('Part ID: [_1]',$respid).')'.
1.597     wenzelju 2179:                             '</span>&nbsp; &nbsp;';
1.313     banghart 2180: 			my $files=&get_submitted_files($udom,$uname,$partid,$respid,\%record);
                   2181: 			if (@$files) {
1.596     raeburn  2182:                             if ($hide) {
                   2183:                                 $lastsubonly.='<br />'.&mt('[quant,_1,file] uploaded to this anonymous survey',scalar(@{$files}));
                   2184:                             } else {
                   2185:                                 $lastsubonly.='<br /><span class="LC_warning">'.&mt('Like all files provided by users, this file may contain viruses').'</span><br />';
                   2186:                                 foreach my $file (@$files) {
                   2187:                                     &Apache::lonnet::allowuploaded('/adm/grades',$file);
                   2188:                                     $lastsubonly.='<br /><a href="'.$file.'?rawmode=1" target="lonGRDs"><img src="'.&Apache::loncommon::icon($file).'" border="0" /> '.$file.'</a>';
                   2189:                                 }
                   2190:                             }
1.236     albertel 2191: 			    $lastsubonly.='<br />';
1.41      ng       2192: 			}
1.596     raeburn  2193:                         if ($hide) {
                   2194:                             $lastsubonly.='<b>'.&mt('Anonymous Survey').'</b>'; 
                   2195:                         } else {
                   2196: 			    $lastsubonly.='<b>'.&mt('Submitted Answer:').' </b>'.
                   2197: 			        &cleanRecord($subval,$responsetype,$symb,$partid,
                   2198: 					     $respid,\%record,$order,undef,$uname,$udom);
                   2199:                         }
1.151     albertel 2200: 			if ($similar) {$lastsubonly.="<br /><br />$similar\n";}
1.468     albertel 2201: 			$lastsubonly.='</div>';
1.41      ng       2202: 		    }
                   2203: 		}
                   2204: 	    }
1.588     bisitz   2205: 	    $lastsubonly.='</div>'."\n"; # End: LC_grade_submissions_body
1.151     albertel 2206: 	}
                   2207: 	$request->print($lastsubonly);
1.468     albertel 2208:    } elsif ($env{'form.lastSub'} eq 'datesub') {
1.598     www      2209: #	my (undef,$responseType,undef,$parts) = &showResourceInfo($symb);
                   2210:     my ($parts,$handgrade,$responseType) = &response_type($symb);
                   2211: 
1.148     albertel 2212: 	$request->print(&displaySubByDates($symb,\%record,$parts,$responseType,$checkIcon,$uname,$udom));
1.257     albertel 2213:     } elsif ($env{'form.lastSub'} =~ /^(last|all)$/) {
1.41      ng       2214: 	$request->print(&Apache::loncommon::get_previous_attempt($symb,$uname,$udom,
1.257     albertel 2215: 								 $env{'request.course.id'},
1.44      ng       2216: 								 $last,'.submission',
                   2217: 								 'Apache::grades::keywords_highlight'));
1.41      ng       2218:     }
1.120     ng       2219: 
1.121     ng       2220:     $request->print('<input type="hidden" name="unamedom'.$counter.'" value="'.$uname.':'
                   2221: 	.$udom.'" />'."\n");
1.44      ng       2222:     # return if view submission with no grading option
1.257     albertel 2223:     if ($env{'form.showgrading'} eq '' || (!&canmodify($usec))) {
1.120     ng       2224: 	my $toGrade.='<input type="button" value="Grade Student" '.
1.589     bisitz   2225: 	    'onclick="javascript:checksubmit(this.form,\'Grade Student\',\''
1.417     albertel 2226: 	    .$counter.'\');" target="_self" /> &nbsp;'."\n" if (&canmodify($usec));
1.468     albertel 2227: 	$toGrade.='</div>'."\n";
1.257     albertel 2228: 	if (($env{'form.command'} eq 'submission') || 
                   2229: 	    ($env{'form.command'} eq 'processGroup' && $counter == $total)) {
1.324     albertel 2230: 	    $toGrade.='</form>'.&show_grading_menu_form($symb); 
1.169     albertel 2231: 	}
1.180     albertel 2232: 	$request->print($toGrade);
1.41      ng       2233: 	return;
1.180     albertel 2234:     } else {
1.468     albertel 2235: 	$request->print('</div>'."\n");
1.41      ng       2236:     }
1.33      ng       2237: 
1.121     ng       2238:     # essay grading message center
1.257     albertel 2239:     if ($env{'form.handgrade'} eq 'yes') {
1.468     albertel 2240: 	my $result='<div class="LC_grade_message_center">';
                   2241:     
                   2242: 	$result.='<div class="LC_grade_message_center_header">'.
                   2243: 	    &mt('Send Message').'</div><div class="LC_grade_message_center_body">';
1.257     albertel 2244: 	my ($lastname,$givenn) = split(/,/,$env{'form.fullname'});
1.118     ng       2245: 	my $msgfor = $givenn.' '.$lastname;
1.464     albertel 2246: 	if (scalar(@$col_fullnames) > 0) {
                   2247: 	    my $lastone = pop(@$col_fullnames);
                   2248: 	    $msgfor .= ', '.(join ', ',@$col_fullnames).' and '.$lastone.'.';
1.118     ng       2249: 	}
                   2250: 	$msgfor =~ s/\'/\\'/g; #' stupid emacs - no! javascript
1.468     albertel 2251: 	$result.='<input type="hidden" name="includemsg'.$counter.'" value="" />'."\n".
1.121     ng       2252: 	    '<input type="hidden" name="newmsg'.$counter.'" value="" />'."\n";
                   2253: 	$result.='&nbsp;<a href="javascript:msgCenter(document.SCORE,'.$counter.
1.417     albertel 2254: 	    ',\''.$msgfor.'\');" target="_self">'.
1.464     albertel 2255: 	    &mt('Compose message to student').(scalar(@$col_fullnames) >= 1 ? 's' : '').'</a><label> ('.
1.350     albertel 2256: 	    &mt('incl. grades').' <input type="checkbox" name="withgrades'.$counter.'" /></label>)'.
1.118     ng       2257: 	    '<img src="'.$request->dir_config('lonIconsURL').
                   2258: 	    '/mailbkgrd.gif" width="14" height="10" name="mailicon'.$counter.'" />'."\n".
1.298     www      2259: 	    '<br />&nbsp;('.
1.468     albertel 2260: 	    &mt('Message will be sent when you click on Save &amp; Next below.').")\n";
                   2261: 	$result.='</div></div>';
1.121     ng       2262: 	$request->print($result);
1.118     ng       2263:     }
1.41      ng       2264: 
                   2265:     my %seen = ();
                   2266:     my @partlist;
1.129     ng       2267:     my @gradePartRespid;
1.375     albertel 2268:     my @part_response_id = &flatten_responseType($responseType);
1.585     bisitz   2269:     $request->print(
1.588     bisitz   2270:         '<div class="LC_Box">'
                   2271:        .'<h3 class="LC_hcell">'.&mt('Assign Grades').'</h3>'
1.585     bisitz   2272:     );
1.592     bisitz   2273:     $request->print(&gradeBox_start());
1.375     albertel 2274:     foreach my $part_response_id (@part_response_id) {
                   2275:     	my ($partid,$respid) = @{ $part_response_id };
                   2276: 	my $part_resp = join('_',@{ $part_response_id });
1.322     albertel 2277: 	next if ($seen{$partid} > 0);
1.41      ng       2278: 	$seen{$partid}++;
1.393     albertel 2279: 	next if ($$handgrade{$part_resp} ne 'yes' 
                   2280: 		 && $env{'form.lastSub'} eq 'hdgrade');
1.524     raeburn  2281: 	push(@partlist,$partid);
                   2282: 	push(@gradePartRespid,$partid.'.'.$respid);
1.322     albertel 2283: 	$request->print(&gradeBox($request,$symb,$uname,$udom,$counter,$partid,\%record));
1.41      ng       2284:     }
1.585     bisitz   2285:     $request->print(&gradeBox_end()); # </div>
                   2286:     $request->print('</div>');
1.468     albertel 2287: 
                   2288:     $request->print('<div class="LC_grade_info_links">');
                   2289:     $request->print('</div>');
                   2290: 
1.45      ng       2291:     $result='<input type="hidden" name="partlist'.$counter.
                   2292: 	'" value="'.(join ":",@partlist).'" />'."\n";
1.129     ng       2293:     $result.='<input type="hidden" name="gradePartRespid'.
                   2294: 	'" value="'.(join ":",@gradePartRespid).'" />'."\n" if ($counter == 0);
1.45      ng       2295:     my $ctr = 0;
                   2296:     while ($ctr < scalar(@partlist)) {
                   2297: 	$result.='<input type="hidden" name="partid'.$counter.'_'.$ctr.'" value="'.
                   2298: 	    $partlist[$ctr].'" />'."\n";
                   2299: 	$ctr++;
                   2300:     }
1.468     albertel 2301:     $request->print($result.''."\n");
1.41      ng       2302: 
1.441     www      2303: # Done with printing info for one student
                   2304: 
1.468     albertel 2305:     $request->print('</div>');#LC_grade_show_user
1.441     www      2306: 
                   2307: 
1.41      ng       2308:     # print end of form
                   2309:     if ($counter == $total) {
1.592     bisitz   2310:         my $endform='<br /><hr /><table border="0"><tr><td>'."\n";
1.485     albertel 2311: 	$endform.='<input type="button" value="'.&mt('Save &amp; Next').'" '.
1.589     bisitz   2312: 	    'onclick="javascript:checksubmit(this.form,\'Save & Next\','.
1.417     albertel 2313: 	    $total.','.scalar(@partlist).');" target="_self" /> &nbsp;'."\n";
1.119     ng       2314: 	my $ntstu ='<select name="NTSTU">'.
                   2315: 	    '<option>1</option><option>2</option>'.
                   2316: 	    '<option>3</option><option>5</option>'.
                   2317: 	    '<option>7</option><option>10</option></select>'."\n";
1.257     albertel 2318: 	my $nsel = ($env{'form.NTSTU'} ne '' ? $env{'form.NTSTU'} : '1');
1.401     albertel 2319: 	$ntstu =~ s/<option>$nsel</<option selected="selected">$nsel</;
1.578     raeburn  2320:         $endform.=&mt('[_1]student(s)',$ntstu);
1.485     albertel 2321: 	$endform.='&nbsp;&nbsp;<input type="button" value="'.&mt('Previous').'" '.
1.589     bisitz   2322: 	    'onclick="javascript:checksubmit(this.form,\'Previous\');" target="_self" /> &nbsp;'."\n".
1.485     albertel 2323: 	    '<input type="button" value="'.&mt('Next').'" '.
1.589     bisitz   2324: 	    'onclick="javascript:checksubmit(this.form,\'Next\');" target="_self" /> &nbsp;';
1.592     bisitz   2325:         $endform.='<span class="LC_warning">'.
                   2326:                   &mt('(Next and Previous (student) do not save the scores.)').
                   2327:                   '</span>'."\n" ;
1.349     albertel 2328:         $endform.="<input type='hidden' value='".&get_increment().
1.348     bowersj2 2329:             "' name='increment' />";
1.485     albertel 2330: 	$endform.='</td></tr></table></form>';
1.324     albertel 2331: 	$endform.=&show_grading_menu_form($symb);
1.41      ng       2332: 	$request->print($endform);
                   2333:     }
                   2334:     return '';
1.38      ng       2335: }
                   2336: 
1.464     albertel 2337: sub check_collaborators {
                   2338:     my ($symb,$uname,$udom,$record,$handgrade,$counter) = @_;
                   2339:     my ($result,@col_fullnames);
                   2340:     my ($classlist,undef,$fullname) = &getclasslist('all','0');
                   2341:     foreach my $part (keys(%$handgrade)) {
                   2342: 	my $ncol = &Apache::lonnet::EXT('resource.'.$part.
                   2343: 					'.maxcollaborators',
                   2344: 					$symb,$udom,$uname);
                   2345: 	next if ($ncol <= 0);
                   2346: 	$part =~ s/\_/\./g;
                   2347: 	next if ($record->{'resource.'.$part.'.collaborators'} eq '');
                   2348: 	my (@good_collaborators, @bad_collaborators);
                   2349: 	foreach my $possible_collaborator
                   2350: 	    (split(/,?\s+/,$record->{'resource.'.$part.'.collaborators'})) { 
                   2351: 	    $possible_collaborator =~ s/[\$\^\(\)]//g;
                   2352: 	    next if ($possible_collaborator eq '');
                   2353: 	    my ($co_name,$co_dom) = split(/\@|:/,$possible_collaborator);
                   2354: 	    $co_dom = $udom if (! defined($co_dom) || $co_dom =~ /^domain$/i);
                   2355: 	    next if ($co_name eq $uname && $co_dom eq $udom);
                   2356: 	    # Doing this grep allows 'fuzzy' specification
                   2357: 	    my @matches = grep(/^\Q$co_name\E:\Q$co_dom\E$/i, 
                   2358: 			       keys(%$classlist));
                   2359: 	    if (! scalar(@matches)) {
                   2360: 		push(@bad_collaborators, $possible_collaborator);
                   2361: 	    } else {
                   2362: 		push(@good_collaborators, @matches);
                   2363: 	    }
                   2364: 	}
                   2365: 	if (scalar(@good_collaborators) != 0) {
1.466     albertel 2366: 	    $result.='<br />'.&mt('Collaborators: ');
1.464     albertel 2367: 	    foreach my $name (@good_collaborators) {
                   2368: 		my ($lastname,$givenn) = split(/,/,$$fullname{$name});
                   2369: 		push(@col_fullnames, $givenn.' '.$lastname);
                   2370: 		$result.=$fullname->{$name}.'&nbsp; &nbsp; &nbsp;';
                   2371: 	    }
                   2372: 	    $result.='<br />'."\n";
1.466     albertel 2373: 	    my ($part)=split(/\./,$part);
1.464     albertel 2374: 	    $result.='<input type="hidden" name="collaborator'.$counter.
                   2375: 		'" value="'.$part.':'.(join ':',@good_collaborators).'" />'.
                   2376: 		"\n";
                   2377: 	}
                   2378: 	if (scalar(@bad_collaborators) > 0) {
1.466     albertel 2379: 	    $result.='<div class="LC_warning">';
1.464     albertel 2380: 	    $result.=&mt('This student has submitted [quant,_1,invalid collaborator]: [_2]',scalar(@bad_collaborators),join(', ',@bad_collaborators));
                   2381: 	    $result .= '</div>';
                   2382: 	}         
                   2383: 	if (scalar(@bad_collaborators > $ncol)) {
1.466     albertel 2384: 	    $result .= '<div class="LC_warning">';
1.464     albertel 2385: 	    $result .= &mt('This student has submitted too many '.
                   2386: 		'collaborators.  Maximum is [_1].',$ncol);
                   2387: 	    $result .= '</div>';
                   2388: 	}
                   2389:     }
                   2390:     return ($result,$fullname,\@col_fullnames);
                   2391: }
                   2392: 
1.44      ng       2393: #--- Retrieve the last submission for all the parts
1.38      ng       2394: sub get_last_submission {
1.119     ng       2395:     my ($returnhash)=@_;
1.596     raeburn  2396:     my (@string,$timestamp,%lasthidden);
1.119     ng       2397:     if ($$returnhash{'version'}) {
1.46      ng       2398: 	my %lasthash=();
                   2399: 	my ($version);
1.119     ng       2400: 	for ($version=1;$version<=$$returnhash{'version'};$version++) {
1.397     albertel 2401: 	    foreach my $key (sort(split(/\:/,
                   2402: 					$$returnhash{$version.':keys'}))) {
                   2403: 		$lasthash{$key}=$$returnhash{$version.':'.$key};
                   2404: 		$timestamp = 
1.545     raeburn  2405: 		    &Apache::lonlocal::locallocaltime($$returnhash{$version.':timestamp'});
1.46      ng       2406: 	    }
                   2407: 	}
1.596     raeburn  2408:         my %typeparts;
                   2409:         my $showsurv = 
                   2410:             &Apache::lonnet::allowed('vas',$env{'request.course.id'});
                   2411:         foreach my $key (sort(keys(%lasthash))) {
                   2412:             if ($key =~ /\.type$/) {
                   2413:                 if (($lasthash{$key} eq 'anonsurvey') || 
                   2414:                     ($lasthash{$key} eq 'anonsurveycred')) {
                   2415:                     my ($ign,@parts) = split(/\./,$key);
                   2416:                     pop(@parts);
                   2417:                     unless ($showsurv) {
                   2418:                         my $id = join(',',@parts);
                   2419:                         $typeparts{$ign.'.'.$id} = $lasthash{$key};
                   2420:                     }
                   2421:                     delete($lasthash{$key});
                   2422:                 }
                   2423:             }
                   2424:         }
                   2425:         my @hidden = keys(%typeparts);
1.397     albertel 2426: 	foreach my $key (keys(%lasthash)) {
                   2427: 	    next if ($key !~ /\.submission$/);
1.596     raeburn  2428:             my $hide;
                   2429:             if (@hidden) {
                   2430:                 foreach my $id (@hidden) {
                   2431:                     if ($key =~ /^\Q$id\E/) {
                   2432:                         $hide = 1;
                   2433:                         last;
                   2434:                     }
                   2435:                 }
                   2436:             }
1.397     albertel 2437: 	    my ($partid,$foo) = split(/submission$/,$key);
                   2438: 	    my $draft  = $lasthash{$partid.'awarddetail'} eq 'DRAFT' ?
1.398     albertel 2439: 		'<span class="LC_warning">Draft Copy</span> ' : '';
1.596     raeburn  2440: 	    push(@string, join(':', $key, $hide, $draft.$lasthash{$key}));
1.41      ng       2441: 	}
                   2442:     }
1.397     albertel 2443:     if (!@string) {
                   2444: 	$string[0] =
1.539     riegler  2445: 	    '<span class="LC_warning">'.&mt('Nothing submitted - no attempts.').'</span>';
1.397     albertel 2446:     }
                   2447:     return (\@string,\$timestamp);
1.38      ng       2448: }
1.35      ng       2449: 
1.44      ng       2450: #--- High light keywords, with style choosen by user.
1.38      ng       2451: sub keywords_highlight {
1.44      ng       2452:     my $string    = shift;
1.257     albertel 2453:     my $size      = $env{'form.kwsize'} eq '0' ? '' : 'size='.$env{'form.kwsize'};
                   2454:     my $styleon   = $env{'form.kwstyle'} eq ''  ? '' : $env{'form.kwstyle'};
1.41      ng       2455:     (my $styleoff = $styleon) =~ s/\</\<\//;
1.257     albertel 2456:     my @keylist   = split(/[,\s+]/,$env{'form.keywords'});
1.398     albertel 2457:     foreach my $keyword (@keylist) {
                   2458: 	$string =~ s/\b\Q$keyword\E(\b|\.)/<font color\=$env{'form.kwclr'} $size\>$styleon$keyword$styleoff<\/font>/gi;
1.41      ng       2459:     }
                   2460:     return $string;
1.38      ng       2461: }
1.36      ng       2462: 
1.44      ng       2463: #--- Called from submission routine
1.38      ng       2464: sub processHandGrade {
1.608     www      2465:     my ($request,$symb) = @_;
1.324     albertel 2466:     my (undef,undef,$url) = &Apache::lonnet::decode_symb($symb);
1.257     albertel 2467:     my $button = $env{'form.gradeOpt'};
                   2468:     my $ngrade = $env{'form.NCT'};
                   2469:     my $ntstu  = $env{'form.NTSTU'};
1.301     albertel 2470:     my $cdom   = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   2471:     my $cnum   = $env{'course.'.$env{'request.course.id'}.'.num'};
                   2472: 
1.44      ng       2473:     if ($button eq 'Save & Next') {
                   2474: 	my $ctr = 0;
                   2475: 	while ($ctr < $ngrade) {
1.257     albertel 2476: 	    my ($uname,$udom) = split(/:/,$env{'form.unamedom'.$ctr});
1.324     albertel 2477: 	    my ($errorflag,$pts,$wgt) = &saveHandGrade($request,$symb,$uname,$udom,$ctr);
1.71      ng       2478: 	    if ($errorflag eq 'no_score') {
                   2479: 		$ctr++;
                   2480: 		next;
                   2481: 	    }
1.104     albertel 2482: 	    if ($errorflag eq 'not_allowed') {
1.398     albertel 2483: 		$request->print("<span class=\"LC_warning\">Not allowed to modify grades for $uname:$udom</span>");
1.104     albertel 2484: 		$ctr++;
                   2485: 		next;
                   2486: 	    }
1.257     albertel 2487: 	    my $includemsg = $env{'form.includemsg'.$ctr};
1.44      ng       2488: 	    my ($subject,$message,$msgstatus) = ('','','');
1.418     albertel 2489: 	    my $restitle = &Apache::lonnet::gettitle($symb);
                   2490:             my ($feedurl,$showsymb) =
                   2491: 		&get_feedurl_and_symb($symb,$uname,$udom);
                   2492: 	    my $messagetail;
1.62      albertel 2493: 	    if ($includemsg =~ /savemsg|newmsg\Q$ctr\E/) {
1.298     www      2494: 		$subject = $env{'form.msgsub'} if ($includemsg =~ /msgsub/);
1.295     www      2495: 		unless ($subject=~/\w/) { $subject=&mt('Grading Feedback'); }
1.386     raeburn  2496: 		$subject.=' ['.$restitle.']';
1.44      ng       2497: 		my (@msgnum) = split(/,/,$includemsg);
                   2498: 		foreach (@msgnum) {
1.257     albertel 2499: 		    $message.=$env{'form.'.$_} if ($_ =~ /savemsg|newmsg/ && $_ ne '');
1.44      ng       2500: 		}
1.80      ng       2501: 		$message =&Apache::lonfeedback::clear_out_html($message);
1.298     www      2502: 		if ($env{'form.withgrades'.$ctr}) {
                   2503: 		    $message.="\n\nPoint".($pts > 1 ? 's':'').' awarded = '.$pts.' out of '.$wgt;
1.386     raeburn  2504: 		    $messagetail = " for <a href=\"".
1.605     www      2505: 		                   $feedurl."?symb=$showsymb\">$restitle</a>";
1.386     raeburn  2506: 		}
                   2507: 		$msgstatus = 
                   2508:                     &Apache::lonmsg::user_normal_msg($uname,$udom,$subject,
                   2509: 						     $message.$messagetail,
1.418     albertel 2510:                                                      undef,$feedurl,undef,
1.386     raeburn  2511:                                                      undef,undef,$showsymb,
                   2512:                                                      $restitle);
1.574     bisitz   2513: 		$request->print('<br />'.&mt('Sending message to [_1]',$uname.':'.$udom).': '.
1.296     www      2514: 				$msgstatus);
1.44      ng       2515: 	    }
1.257     albertel 2516: 	    if ($env{'form.collaborator'.$ctr}) {
1.155     albertel 2517: 		my @collabstrs=&Apache::loncommon::get_env_multiple("form.collaborator$ctr");
1.150     albertel 2518: 		foreach my $collabstr (@collabstrs) {
                   2519: 		    my ($part,@collaborators) = split(/:/,$collabstr);
1.310     banghart 2520: 		    foreach my $collaborator (@collaborators) {
1.150     albertel 2521: 			my ($errorflag,$pts,$wgt) = 
1.324     albertel 2522: 			    &saveHandGrade($request,$symb,$collaborator,$udom,$ctr,
1.257     albertel 2523: 					   $env{'form.unamedom'.$ctr},$part);
1.150     albertel 2524: 			if ($errorflag eq 'not_allowed') {
1.362     albertel 2525: 			    $request->print("<span class=\"LC_error\">".&mt('Not allowed to modify grades for [_1]',"$collaborator:$udom")."</span>");
1.150     albertel 2526: 			    next;
1.418     albertel 2527: 			} elsif ($message ne '') {
                   2528: 			    my ($baseurl,$showsymb) = 
                   2529: 				&get_feedurl_and_symb($symb,$collaborator,
                   2530: 						      $udom);
                   2531: 			    if ($env{'form.withgrades'.$ctr}) {
                   2532: 				$messagetail = " for <a href=\"".
1.605     www      2533:                                     $baseurl."?symb=$showsymb\">$restitle</a>";
1.150     albertel 2534: 			    }
1.418     albertel 2535: 			    $msgstatus = 
                   2536: 				&Apache::lonmsg::user_normal_msg($collaborator,$udom,$subject,$message.$messagetail,undef,$baseurl,undef,undef,undef,$showsymb,$restitle);
1.104     albertel 2537: 			}
1.44      ng       2538: 		    }
                   2539: 		}
                   2540: 	    }
                   2541: 	    $ctr++;
                   2542: 	}
                   2543:     }
                   2544: 
1.257     albertel 2545:     if ($env{'form.handgrade'} eq 'yes') {
1.119     ng       2546: 	# Keywords sorted in alphabatical order
1.257     albertel 2547: 	my $loginuser = $env{'user.name'}.':'.$env{'user.domain'};
1.119     ng       2548: 	my %keyhash = ();
1.257     albertel 2549: 	$env{'form.keywords'}           =~ s/,\s{0,}|\s+/ /g;
                   2550: 	$env{'form.keywords'}           =~ s/^\s+|\s+$//;
                   2551: 	my (@keywords) = sort(split(/\s+/,$env{'form.keywords'}));
                   2552: 	$env{'form.keywords'} = join(' ',@keywords);
                   2553: 	$keyhash{$symb.'_keywords'}     = $env{'form.keywords'};
                   2554: 	$keyhash{$symb.'_subject'}      = $env{'form.msgsub'};
                   2555: 	$keyhash{$loginuser.'_kwclr'}   = $env{'form.kwclr'};
                   2556: 	$keyhash{$loginuser.'_kwsize'}  = $env{'form.kwsize'};
                   2557: 	$keyhash{$loginuser.'_kwstyle'} = $env{'form.kwstyle'};
1.119     ng       2558: 
                   2559: 	# message center - Order of message gets changed. Blank line is eliminated.
1.257     albertel 2560: 	# New messages are saved in env for the next student.
1.119     ng       2561: 	# All messages are saved in nohist_handgrade.db
                   2562: 	my ($ctr,$idx) = (1,1);
1.257     albertel 2563: 	while ($ctr <= $env{'form.savemsgN'}) {
                   2564: 	    if ($env{'form.savemsg'.$ctr} ne '') {
                   2565: 		$keyhash{$symb.'_savemsg'.$idx} = $env{'form.savemsg'.$ctr};
1.119     ng       2566: 		$idx++;
                   2567: 	    }
                   2568: 	    $ctr++;
1.41      ng       2569: 	}
1.119     ng       2570: 	$ctr = 0;
                   2571: 	while ($ctr < $ngrade) {
1.257     albertel 2572: 	    if ($env{'form.newmsg'.$ctr} ne '') {
                   2573: 		$keyhash{$symb.'_savemsg'.$idx} = $env{'form.newmsg'.$ctr};
                   2574: 		$env{'form.savemsg'.$idx} = $env{'form.newmsg'.$ctr};
1.119     ng       2575: 		$idx++;
                   2576: 	    }
                   2577: 	    $ctr++;
1.41      ng       2578: 	}
1.257     albertel 2579: 	$env{'form.savemsgN'} = --$idx;
                   2580: 	$keyhash{$symb.'_savemsgN'} = $env{'form.savemsgN'};
1.119     ng       2581: 	my $putresult = &Apache::lonnet::put
1.301     albertel 2582: 	    ('nohist_handgrade',\%keyhash,$cdom,$cnum);
1.41      ng       2583:     }
1.44      ng       2584:     # Called by Save & Refresh from Highlight Attribute Window
1.257     albertel 2585:     my (undef,undef,$fullname) = &getclasslist($env{'form.section'},'1');
                   2586:     if ($env{'form.refresh'} eq 'on') {
1.86      ng       2587: 	my ($ctr,$total) = (0,0);
                   2588: 	while ($ctr < $ngrade) {
1.257     albertel 2589: 	    $total++ if  $env{'form.unamedom'.$ctr} ne '';
1.86      ng       2590: 	    $ctr++;
                   2591: 	}
1.257     albertel 2592: 	$env{'form.NTSTU'}=$ngrade;
1.86      ng       2593: 	$ctr = 0;
                   2594: 	while ($ctr < $total) {
1.257     albertel 2595: 	    my $processUser = $env{'form.unamedom'.$ctr};
                   2596: 	    ($env{'form.student'},$env{'form.userdom'}) = split(/:/,$processUser);
                   2597: 	    $env{'form.fullname'} = $$fullname{$processUser};
1.86      ng       2598: 	    &submission($request,$ctr,$total-1);
1.41      ng       2599: 	    $ctr++;
                   2600: 	}
                   2601: 	return '';
                   2602:     }
1.36      ng       2603: 
1.121     ng       2604: # Go directly to grade student - from submission or link from chart page
1.120     ng       2605:     if ($button eq 'Grade Student') {
1.598     www      2606: #	(undef,undef,$env{'form.handgrade'},undef,undef) = &showResourceInfo($symb);
1.257     albertel 2607: 	my $processUser = $env{'form.unamedom'.$env{'form.studentNo'}};
                   2608: 	($env{'form.student'},$env{'form.userdom'}) = split(/:/,$processUser);
                   2609: 	$env{'form.fullname'} = $$fullname{$processUser};
1.120     ng       2610: 	&submission($request,0,0);
                   2611: 	return '';
                   2612:     }
                   2613: 
1.44      ng       2614:     # Get the next/previous one or group of students
1.257     albertel 2615:     my $firststu = $env{'form.unamedom0'};
                   2616:     my $laststu = $env{'form.unamedom'.($ngrade-1)};
1.119     ng       2617:     my $ctr = 2;
1.41      ng       2618:     while ($laststu eq '') {
1.257     albertel 2619: 	$laststu  = $env{'form.unamedom'.($ngrade-$ctr)};
1.41      ng       2620: 	$ctr++;
                   2621: 	$laststu = $firststu if ($ctr > $ngrade);
                   2622:     }
1.44      ng       2623: 
1.41      ng       2624:     my (@parsedlist,@nextlist);
                   2625:     my ($nextflg) = 0;
1.524     raeburn  2626:     foreach my $item (sort 
1.294     albertel 2627: 	     {
                   2628: 		 if (lc($$fullname{$a}) ne lc($$fullname{$b})) {
                   2629: 		     return (lc($$fullname{$a}) cmp lc($$fullname{$b}));
                   2630: 		 }
                   2631: 		 return $a cmp $b;
                   2632: 	     } (keys(%$fullname))) {
1.605     www      2633: # FIXME: this is fishy, looks like the button label
1.41      ng       2634: 	if ($nextflg == 1 && $button =~ /Next$/) {
1.524     raeburn  2635: 	    push(@parsedlist,$item);
1.41      ng       2636: 	}
1.524     raeburn  2637: 	$nextflg = 1 if ($item eq $laststu);
1.41      ng       2638: 	if ($button eq 'Previous') {
1.524     raeburn  2639: 	    last if ($item eq $firststu);
                   2640: 	    push(@parsedlist,$item);
1.41      ng       2641: 	}
                   2642:     }
                   2643:     $ctr = 0;
1.605     www      2644: # FIXME: this is fishy, looks like the button label
1.41      ng       2645:     @parsedlist = reverse @parsedlist if ($button eq 'Previous');
1.582     raeburn  2646:     my $res_error;
                   2647:     my ($partlist) = &response_type($symb,\$res_error);
                   2648:     if ($res_error) {
                   2649:         $request->print(&navmap_errormsg());
                   2650:         return;
                   2651:     }
1.41      ng       2652:     foreach my $student (@parsedlist) {
1.257     albertel 2653: 	my $submitonly=$env{'form.submitonly'};
1.41      ng       2654: 	my ($uname,$udom) = split(/:/,$student);
1.301     albertel 2655: 	
                   2656: 	if ($submitonly eq 'queued') {
                   2657: 	    my %queue_status = 
                   2658: 		&Apache::bridgetask::get_student_status($symb,$cdom,$cnum,
                   2659: 							$udom,$uname);
                   2660: 	    next if (!defined($queue_status{'gradingqueue'}));
                   2661: 	}
                   2662: 
1.156     albertel 2663: 	if ($submitonly =~ /^(yes|graded|incorrect)$/) {
1.257     albertel 2664: #	    my %record = &Apache::lonnet::restore($symb,$env{'request.course.id'},$udom,$uname);
1.324     albertel 2665: 	    my %status=&student_gradeStatus($symb,$udom,$uname,$partlist);
1.145     albertel 2666: 	    my $submitted = 0;
1.248     albertel 2667: 	    my $ungraded = 0;
                   2668: 	    my $incorrect = 0;
1.524     raeburn  2669: 	    foreach my $item (keys(%status)) {
                   2670: 		$submitted = 1 if ($status{$item} ne 'nothing');
                   2671: 		$ungraded = 1 if ($status{$item} =~ /^ungraded/);
                   2672: 		$incorrect = 1 if ($status{$item} =~ /^incorrect/);
                   2673: 		my ($foo,$partid,$foo1) = split(/\./,$item);
1.145     albertel 2674: 		if ($status{'resource.'.$partid.'.submitted_by'} ne '') {
                   2675: 		    $submitted = 0;
                   2676: 		}
1.41      ng       2677: 	    }
1.156     albertel 2678: 	    next if (!$submitted && ($submitonly eq 'yes' ||
                   2679: 				     $submitonly eq 'incorrect' ||
                   2680: 				     $submitonly eq 'graded'));
1.248     albertel 2681: 	    next if (!$ungraded && ($submitonly eq 'graded'));
                   2682: 	    next if (!$incorrect && $submitonly eq 'incorrect');
1.41      ng       2683: 	}
1.524     raeburn  2684: 	push(@nextlist,$student) if ($ctr < $ntstu);
1.129     ng       2685: 	last if ($ctr == $ntstu);
1.41      ng       2686: 	$ctr++;
                   2687:     }
1.36      ng       2688: 
1.41      ng       2689:     $ctr = 0;
                   2690:     my $total = scalar(@nextlist)-1;
1.39      ng       2691: 
1.524     raeburn  2692:     foreach (sort(@nextlist)) {
1.41      ng       2693: 	my ($uname,$udom,$submitter) = split(/:/);
1.257     albertel 2694: 	$env{'form.student'}  = $uname;
                   2695: 	$env{'form.userdom'}  = $udom;
                   2696: 	$env{'form.fullname'} = $$fullname{$_};
1.41      ng       2697: 	&submission($request,$ctr,$total);
                   2698: 	$ctr++;
                   2699:     }
                   2700:     if ($total < 0) {
1.485     albertel 2701: 	my $the_end = '<h3><span class="LC_info">'.&mt('LON-CAPA User Message').'</span></h3><br />'."\n";
                   2702: 	$the_end.=&mt('<b>Message: </b> No more students for this section or class.').'<br /><br />'."\n";
                   2703: 	$the_end.=&mt('Click on the button below to return to the grading menu.').'<br /><br />'."\n";
1.324     albertel 2704: 	$the_end.=&show_grading_menu_form($symb);
1.41      ng       2705: 	$request->print($the_end);
                   2706:     }
                   2707:     return '';
1.38      ng       2708: }
1.36      ng       2709: 
1.44      ng       2710: #---- Save the score and award for each student, if changed
1.38      ng       2711: sub saveHandGrade {
1.324     albertel 2712:     my ($request,$symb,$stuname,$domain,$newflg,$submitter,$part) = @_;
1.342     banghart 2713:     my @version_parts;
1.104     albertel 2714:     my $usec = &Apache::lonnet::getsection($domain,$stuname,
1.257     albertel 2715: 					   $env{'request.course.id'});
1.104     albertel 2716:     if (!&canmodify($usec)) { return('not_allowed'); }
1.337     banghart 2717:     my %record = &Apache::lonnet::restore($symb,$env{'request.course.id'},$domain,$stuname);
1.251     banghart 2718:     my @parts_graded;
1.77      ng       2719:     my %newrecord  = ();
                   2720:     my ($pts,$wgt) = ('','');
1.269     raeburn  2721:     my %aggregate = ();
                   2722:     my $aggregateflag = 0;
1.301     albertel 2723:     my @parts = split(/:/,$env{'form.partlist'.$newflg});
                   2724:     foreach my $new_part (@parts) {
1.337     banghart 2725: 	#collaborator ($submi may vary for different parts
1.259     banghart 2726: 	if ($submitter && $new_part ne $part) { next; }
                   2727: 	my $dropMenu = $env{'form.GD_SEL'.$newflg.'_'.$new_part};
1.125     ng       2728: 	if ($dropMenu eq 'excused') {
1.259     banghart 2729: 	    if ($record{'resource.'.$new_part.'.solved'} ne 'excused') {
                   2730: 		$newrecord{'resource.'.$new_part.'.solved'} = 'excused';
                   2731: 		if (exists($record{'resource.'.$new_part.'.awarded'})) {
                   2732: 		    $newrecord{'resource.'.$new_part.'.awarded'} = '';
1.58      albertel 2733: 		}
1.364     banghart 2734: 	        $newrecord{'resource.'.$new_part.'.regrader'}="$env{'user.name'}:$env{'user.domain'}";
1.58      albertel 2735: 	    }
1.125     ng       2736: 	} elsif ($dropMenu eq 'reset status'
1.259     banghart 2737: 		 && exists($record{'resource.'.$new_part.'.solved'})) { #don't bother if no old records -> no attempts
1.524     raeburn  2738: 	    foreach my $key (keys(%record)) {
1.259     banghart 2739: 		if ($key=~/^resource\.\Q$new_part\E\./) { $newrecord{$key} = ''; }
1.197     albertel 2740: 	    }
1.259     banghart 2741: 	    $newrecord{'resource.'.$new_part.'.regrader'}=
1.257     albertel 2742: 		"$env{'user.name'}:$env{'user.domain'}";
1.270     albertel 2743:             my $totaltries = $record{'resource.'.$part.'.tries'};
                   2744: 
                   2745:             my %last_resets = &get_last_resets($symb,$env{'request.course.id'},
                   2746: 					       [$new_part]);
                   2747:             my $aggtries =$totaltries;
1.269     raeburn  2748:             if ($last_resets{$new_part}) {
1.270     albertel 2749:                 $aggtries = &get_num_tries(\%record,$last_resets{$new_part},
                   2750: 					   $new_part);
1.269     raeburn  2751:             }
1.270     albertel 2752: 
                   2753:             my $solvedstatus = $record{'resource.'.$new_part.'.solved'};
1.269     raeburn  2754:             if ($aggtries > 0) {
1.327     albertel 2755:                 &decrement_aggs($symb,$new_part,\%aggregate,$aggtries,$totaltries,$solvedstatus);
1.269     raeburn  2756:                 $aggregateflag = 1;
                   2757:             }
1.125     ng       2758: 	} elsif ($dropMenu eq '') {
1.259     banghart 2759: 	    $pts = ($env{'form.GD_BOX'.$newflg.'_'.$new_part} ne '' ? 
                   2760: 		    $env{'form.GD_BOX'.$newflg.'_'.$new_part} : 
                   2761: 		    $env{'form.RADVAL'.$newflg.'_'.$new_part});
                   2762: 	    if ($pts eq '' && $env{'form.GD_SEL'.$newflg.'_'.$new_part} eq '') {
1.153     albertel 2763: 		next;
                   2764: 	    }
1.259     banghart 2765: 	    $wgt = $env{'form.WGT'.$newflg.'_'.$new_part} eq '' ? 1 : 
                   2766: 		$env{'form.WGT'.$newflg.'_'.$new_part};
1.41      ng       2767: 	    my $partial= $pts/$wgt;
1.259     banghart 2768: 	    if ($partial eq $record{'resource.'.$new_part.'.awarded'}) {
1.153     albertel 2769: 		#do not update score for part if not changed.
1.346     banghart 2770:                 &handback_files($request,$symb,$stuname,$domain,$newflg,$new_part,\%newrecord);
1.153     albertel 2771: 		next;
1.251     banghart 2772: 	    } else {
1.524     raeburn  2773: 	        push(@parts_graded,$new_part);
1.153     albertel 2774: 	    }
1.259     banghart 2775: 	    if ($record{'resource.'.$new_part.'.awarded'} ne $partial) {
                   2776: 		$newrecord{'resource.'.$new_part.'.awarded'}  = $partial;
1.153     albertel 2777: 	    }
1.259     banghart 2778: 	    my $reckey = 'resource.'.$new_part.'.solved';
1.41      ng       2779: 	    if ($partial == 0) {
1.153     albertel 2780: 		if ($record{$reckey} ne 'incorrect_by_override') {
                   2781: 		    $newrecord{$reckey} = 'incorrect_by_override';
                   2782: 		}
1.41      ng       2783: 	    } else {
1.153     albertel 2784: 		if ($record{$reckey} ne 'correct_by_override') {
                   2785: 		    $newrecord{$reckey} = 'correct_by_override';
                   2786: 		}
                   2787: 	    }	    
                   2788: 	    if ($submitter && 
1.259     banghart 2789: 		($record{'resource.'.$new_part.'.submitted_by'} ne $submitter)) {
                   2790: 		$newrecord{'resource.'.$new_part.'.submitted_by'} = $submitter;
1.41      ng       2791: 	    }
1.259     banghart 2792: 	    $newrecord{'resource.'.$new_part.'.regrader'}=
1.257     albertel 2793: 		"$env{'user.name'}:$env{'user.domain'}";
1.41      ng       2794: 	}
1.259     banghart 2795: 	# unless problem has been graded, set flag to version the submitted files
1.305     banghart 2796: 	unless ($record{'resource.'.$new_part.'.solved'} =~ /^correct_/  || 
                   2797: 	        $record{'resource.'.$new_part.'.solved'} eq 'incorrect_by_override' ||
                   2798: 	        $dropMenu eq 'reset status')
                   2799: 	   {
1.524     raeburn  2800: 	    push(@version_parts,$new_part);
1.259     banghart 2801: 	}
1.41      ng       2802:     }
1.301     albertel 2803:     my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   2804:     my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   2805: 
1.344     albertel 2806:     if (%newrecord) {
                   2807:         if (@version_parts) {
1.364     banghart 2808:             my @changed_keys = &version_portfiles(\%record, \@parts_graded, 
                   2809:                                 $env{'request.course.id'}, $symb, $domain, $stuname, \@version_parts);
1.344     albertel 2810: 	    @newrecord{@changed_keys} = @record{@changed_keys};
1.367     albertel 2811: 	    foreach my $new_part (@version_parts) {
                   2812: 		&handback_files($request,$symb,$stuname,$domain,$newflg,
                   2813: 				$new_part,\%newrecord);
                   2814: 	    }
1.259     banghart 2815:         }
1.44      ng       2816: 	&Apache::lonnet::cstore(\%newrecord,$symb,
1.257     albertel 2817: 				$env{'request.course.id'},$domain,$stuname);
1.380     albertel 2818: 	&check_and_remove_from_queue(\@parts,\%record,\%newrecord,$symb,
                   2819: 				     $cdom,$cnum,$domain,$stuname);
1.41      ng       2820:     }
1.269     raeburn  2821:     if ($aggregateflag) {
                   2822:         &Apache::lonnet::cinc('nohist_resourcetracker',\%aggregate,
1.301     albertel 2823: 			      $cdom,$cnum);
1.269     raeburn  2824:     }
1.301     albertel 2825:     return ('',$pts,$wgt);
1.36      ng       2826: }
1.322     albertel 2827: 
1.380     albertel 2828: sub check_and_remove_from_queue {
                   2829:     my ($parts,$record,$newrecord,$symb,$cdom,$cnum,$domain,$stuname) = @_;
                   2830:     my @ungraded_parts;
                   2831:     foreach my $part (@{$parts}) {
                   2832: 	if (    $record->{   'resource.'.$part.'.awarded'} eq ''
                   2833: 	     && $record->{   'resource.'.$part.'.solved' } ne 'excused'
                   2834: 	     && $newrecord->{'resource.'.$part.'.awarded'} eq ''
                   2835: 	     && $newrecord->{'resource.'.$part.'.solved' } ne 'excused'
                   2836: 		) {
                   2837: 	    push(@ungraded_parts, $part);
                   2838: 	}
                   2839:     }
                   2840:     if ( !@ungraded_parts ) {
                   2841: 	&Apache::bridgetask::remove_from_queue('gradingqueue',$symb,$cdom,
                   2842: 					       $cnum,$domain,$stuname);
                   2843:     }
                   2844: }
                   2845: 
1.337     banghart 2846: sub handback_files {
                   2847:     my ($request,$symb,$stuname,$domain,$newflg,$new_part,$newrecord) = @_;
1.517     raeburn  2848:     my $portfolio_root = '/userfiles/portfolio';
1.582     raeburn  2849:     my $res_error;
                   2850:     my ($partlist,$handgrade,$responseType) = &response_type($symb,\$res_error);
                   2851:     if ($res_error) {
                   2852:         $request->print('<br />'.&navmap_errormsg().'<br />');
                   2853:         return;
                   2854:     }
1.375     albertel 2855:     my @part_response_id = &flatten_responseType($responseType);
                   2856:     foreach my $part_response_id (@part_response_id) {
                   2857:     	my ($part_id,$resp_id) = @{ $part_response_id };
                   2858: 	my $part_resp = join('_',@{ $part_response_id });
1.337     banghart 2859:             if (($env{'form.'.$newflg.'_'.$part_resp.'_returndoc1'}) && ($new_part == $part_id)) {
                   2860:                 # if multiple files are uploaded names will be 'returndoc2','returndoc3'
                   2861:                 my $file_counter = 1;
1.367     albertel 2862: 		my $file_msg;
1.337     banghart 2863:                 while ($env{'form.'.$newflg.'_'.$part_resp.'_returndoc'.$file_counter}) {
                   2864:                     my $fname=$env{'form.'.$newflg.'_'.$part_resp.'_returndoc'.$file_counter.'.filename'};
1.338     banghart 2865:                     my ($directory,$answer_file) = 
                   2866:                         ($env{'form.'.$newflg.'_'.$part_resp.'_origdoc'.$file_counter} =~ /^(.*?)([^\/]*)$/);
                   2867:                     my ($answer_name,$answer_ver,$answer_ext) =
                   2868: 		        &file_name_version_ext($answer_file);
1.355     banghart 2869: 		    my ($portfolio_path) = ($directory =~ /^.+$stuname\/portfolio(.*)/);
1.517     raeburn  2870:                     my $getpropath = 1;
                   2871: 		    my @dir_list = &Apache::lonnet::dirlist($portfolio_root.$portfolio_path,$domain,$stuname,$getpropath);
1.338     banghart 2872: 		    my $version = &get_next_version($answer_name, $answer_ext, \@dir_list);
1.355     banghart 2873:                     # fix file name
                   2874:                     my ($save_file_name) = (($directory.$answer_name.".$version.".$answer_ext) =~ /^.+\/${stuname}\/(.*)/);
                   2875:                     my $result=&Apache::lonnet::finishuserfileupload($stuname,$domain,
                   2876:             	                                $newflg.'_'.$part_resp.'_returndoc'.$file_counter,
                   2877:             	                                $save_file_name);
1.337     banghart 2878:                     if ($result !~ m|^/uploaded/|) {
1.536     raeburn  2879:                         $request->print('<br /><span class="LC_error">'.
                   2880:                             &mt('An error occurred ([_1]) while trying to upload [_2].',
                   2881:                                 $result,$newflg.'_'.$part_resp.'_returndoc'.$file_counter).
                   2882:                                         '</span>');
1.356     banghart 2883:                     } else {
1.360     banghart 2884:                         # mark the file as read only
                   2885:                         my @files = ($save_file_name);
1.372     albertel 2886:                         my @what = ($symb,$env{'request.course.id'},'handback');
1.360     banghart 2887:                         &Apache::lonnet::mark_as_readonly($domain,$stuname,\@files,\@what);
1.367     albertel 2888: 			if (exists($$newrecord{"resource.$new_part.$resp_id.handback"})) {
                   2889: 			    $$newrecord{"resource.$new_part.$resp_id.handback"}.=',';
                   2890: 			}
                   2891:                         $$newrecord{"resource.$new_part.$resp_id.handback"} .= $save_file_name;
                   2892: 			$file_msg.= "\n".'<br /><span class="LC_filename"><a href="/uploaded/'."$domain/$stuname/".$save_file_name.'">'.$save_file_name."</a></span><br />";
                   2893: 
1.337     banghart 2894:                     }
                   2895:                     $request->print("<br />".$fname." will be the uploaded file name");
1.354     albertel 2896:                     $request->print(" ".$env{'form.'.$newflg.'_'.$part_resp.'_origdoc'.$file_counter});
1.337     banghart 2897:                     $file_counter++;
                   2898:                 }
1.367     albertel 2899: 		my $subject = "File Handed Back by Instructor ";
                   2900: 		my $message = "A file has been returned that was originally submitted in reponse to: <br />";
                   2901: 		$message .= "<strong>".&Apache::lonnet::gettitle($symb)."</strong><br />";
                   2902: 		$message .= ' The returned file(s) are named: '. $file_msg;
                   2903: 		$message .= " and can be found in your portfolio space.";
1.418     albertel 2904: 		my ($feedurl,$showsymb) = 
                   2905: 		    &get_feedurl_and_symb($symb,$domain,$stuname);
1.386     raeburn  2906:                 my $restitle = &Apache::lonnet::gettitle($symb);
                   2907: 		my $msgstatus = 
                   2908:                    &Apache::lonmsg::user_normal_msg($stuname,$domain,$subject.
                   2909: 			 ' (File Returned) ['.$restitle.']',$message,undef,
1.418     albertel 2910:                          $feedurl,undef,undef,undef,$showsymb,$restitle);
1.337     banghart 2911:             }
                   2912:         }
1.338     banghart 2913:     return;
1.337     banghart 2914: }
                   2915: 
1.418     albertel 2916: sub get_feedurl_and_symb {
                   2917:     my ($symb,$uname,$udom) = @_;
                   2918:     my (undef,undef,$url) = &Apache::lonnet::decode_symb($symb);
                   2919:     $url = &Apache::lonnet::clutter($url);
                   2920:     my $encrypturl=&Apache::lonnet::EXT('resource.0.encrypturl',
                   2921: 					$symb,$udom,$uname);
                   2922:     if ($encrypturl =~ /^yes$/i) {
                   2923: 	&Apache::lonenc::encrypted(\$url,1);
                   2924: 	&Apache::lonenc::encrypted(\$symb,1);
                   2925:     }
                   2926:     return ($url,$symb);
                   2927: }
                   2928: 
1.313     banghart 2929: sub get_submitted_files {
                   2930:     my ($udom,$uname,$partid,$respid,$record) = @_;
                   2931:     my @files;
                   2932:     if ($$record{"resource.$partid.$respid.portfiles"}) {
                   2933:         my $file_url = '/uploaded/'.$udom.'/'.$uname.'/portfolio';
                   2934:         foreach my $file (split(',',$$record{"resource.$partid.$respid.portfiles"})) {
                   2935:     	    push(@files,$file_url.$file);
                   2936:         }
                   2937:     }
                   2938:     if ($$record{"resource.$partid.$respid.uploadedurl"}) {
                   2939:         push(@files,$$record{"resource.$partid.$respid.uploadedurl"});
                   2940:     }
                   2941:     return (\@files);
                   2942: }
1.322     albertel 2943: 
1.269     raeburn  2944: # ----------- Provides number of tries since last reset.
                   2945: sub get_num_tries {
                   2946:     my ($record,$last_reset,$part) = @_;
                   2947:     my $timestamp = '';
                   2948:     my $num_tries = 0;
                   2949:     if ($$record{'version'}) {
                   2950:         for (my $version=$$record{'version'};$version>=1;$version--) {
                   2951:             if (exists($$record{$version.':resource.'.$part.'.solved'})) {
                   2952:                 $timestamp = $$record{$version.':timestamp'};
                   2953:                 if ($timestamp > $last_reset) {
                   2954:                     $num_tries ++;
                   2955:                 } else {
                   2956:                     last;
                   2957:                 }
                   2958:             }
                   2959:         }
                   2960:     }
                   2961:     return $num_tries;
                   2962: }
                   2963: 
                   2964: # ----------- Determine decrements required in aggregate totals 
                   2965: sub decrement_aggs {
                   2966:     my ($symb,$part,$aggregate,$aggtries,$totaltries,$solvedstatus) = @_;
                   2967:     my %decrement = (
                   2968:                         attempts => 0,
                   2969:                         users => 0,
                   2970:                         correct => 0
                   2971:                     );
                   2972:     $decrement{'attempts'} = $aggtries;
                   2973:     if ($solvedstatus =~ /^correct/) {
                   2974:         $decrement{'correct'} = 1;
                   2975:     }
                   2976:     if ($aggtries == $totaltries) {
                   2977:         $decrement{'users'} = 1;
                   2978:     }
1.524     raeburn  2979:     foreach my $type (keys(%decrement)) {
1.269     raeburn  2980:         $$aggregate{$symb."\0".$part."\0".$type} = -$decrement{$type};
                   2981:     }
                   2982:     return;
                   2983: }
                   2984: 
                   2985: # ----------- Determine timestamps for last reset of aggregate totals for parts  
                   2986: sub get_last_resets {
1.270     albertel 2987:     my ($symb,$courseid,$partids) =@_;
                   2988:     my %last_resets;
1.269     raeburn  2989:     my $cdom = $env{'course.'.$courseid.'.domain'};
                   2990:     my $cname = $env{'course.'.$courseid.'.num'};
1.271     albertel 2991:     my @keys;
                   2992:     foreach my $part (@{$partids}) {
                   2993: 	push(@keys,"$symb\0$part\0resettime");
                   2994:     }
                   2995:     my %results=&Apache::lonnet::get('nohist_resourcetracker',\@keys,
                   2996: 				     $cdom,$cname);
                   2997:     foreach my $part (@{$partids}) {
                   2998: 	$last_resets{$part}=$results{"$symb\0$part\0resettime"};
1.269     raeburn  2999:     }
1.270     albertel 3000:     return %last_resets;
1.269     raeburn  3001: }
                   3002: 
1.251     banghart 3003: # ----------- Handles creating versions for portfolio files as answers
                   3004: sub version_portfiles {
1.343     banghart 3005:     my ($record, $parts_graded, $courseid, $symb, $domain, $stu_name, $v_flag) = @_;
1.263     banghart 3006:     my $version_parts = join('|',@$v_flag);
1.343     banghart 3007:     my @returned_keys;
1.255     banghart 3008:     my $parts = join('|', @$parts_graded);
1.517     raeburn  3009:     my $portfolio_root = '/userfiles/portfolio';
1.277     albertel 3010:     foreach my $key (keys(%$record)) {
1.259     banghart 3011:         my $new_portfiles;
1.263     banghart 3012:         if ($key =~ /^resource\.($version_parts)\./ && $key =~ /\.portfiles$/ ) {
1.342     banghart 3013:             my @versioned_portfiles;
1.367     albertel 3014:             my @portfiles = split(/\s*,\s*/,$$record{$key});
1.252     banghart 3015:             foreach my $file (@portfiles) {
1.306     banghart 3016:                 &Apache::lonnet::unmark_as_readonly($domain,$stu_name,[$symb,$env{'request.course.id'}],$file);
1.304     albertel 3017:                 my ($directory,$answer_file) =($file =~ /^(.*?)([^\/]*)$/);
                   3018: 		my ($answer_name,$answer_ver,$answer_ext) =
                   3019: 		    &file_name_version_ext($answer_file);
1.517     raeburn  3020:                 my $getpropath = 1;    
                   3021:                 my @dir_list = &Apache::lonnet::dirlist($portfolio_root.$directory,$domain,$stu_name,$getpropath);
1.342     banghart 3022:                 my $version = &get_next_version($answer_name, $answer_ext, \@dir_list);
1.306     banghart 3023:                 my $new_answer = &version_selected_portfile($domain, $stu_name, $directory, $answer_file, $version);
                   3024:                 if ($new_answer ne 'problem getting file') {
1.342     banghart 3025:                     push(@versioned_portfiles, $directory.$new_answer);
1.306     banghart 3026:                     &Apache::lonnet::mark_as_readonly($domain,$stu_name,
1.367     albertel 3027:                         [$directory.$new_answer],
1.306     banghart 3028:                         [$symb,$env{'request.course.id'},'graded']);
1.259     banghart 3029:                 }
1.252     banghart 3030:             }
1.343     banghart 3031:             $$record{$key} = join(',',@versioned_portfiles);
                   3032:             push(@returned_keys,$key);
1.251     banghart 3033:         }
                   3034:     } 
1.343     banghart 3035:     return (@returned_keys);   
1.305     banghart 3036: }
                   3037: 
1.307     banghart 3038: sub get_next_version {
1.341     banghart 3039:     my ($answer_name, $answer_ext, $dir_list) = @_;
1.307     banghart 3040:     my $version;
                   3041:     foreach my $row (@$dir_list) {
                   3042:         my ($file) = split(/\&/,$row,2);
                   3043:         my ($file_name,$file_version,$file_ext) =
                   3044: 	    &file_name_version_ext($file);
                   3045:         if (($file_name eq $answer_name) && 
                   3046: 	    ($file_ext eq $answer_ext)) {
                   3047:                 # gets here if filename and extension match, regardless of version
                   3048:                 if ($file_version ne '') {
                   3049:                 # a versioned file is found  so save it for later
                   3050:                 if ($file_version > $version) {
                   3051: 		    $version = $file_version;
                   3052: 	        }
                   3053:             }
                   3054:         }
                   3055:     } 
                   3056:     $version ++;
                   3057:     return($version);
                   3058: }
                   3059: 
1.305     banghart 3060: sub version_selected_portfile {
1.306     banghart 3061:     my ($domain,$stu_name,$directory,$file_name,$version) = @_;
                   3062:     my ($answer_name,$answer_ver,$answer_ext) =
                   3063:         &file_name_version_ext($file_name);
                   3064:     my $new_answer;
                   3065:     $env{'form.copy'} = &Apache::lonnet::getfile("/uploaded/$domain/$stu_name/portfolio$directory$file_name");
                   3066:     if($env{'form.copy'} eq '-1') {
                   3067:         $new_answer = 'problem getting file';
                   3068:     } else {
                   3069:         $new_answer = $answer_name.'.'.$version.'.'.$answer_ext;
                   3070:         my $copy_result = &Apache::lonnet::finishuserfileupload(
                   3071:                             $stu_name,$domain,'copy',
                   3072: 		        '/portfolio'.$directory.$new_answer);
                   3073:     }    
                   3074:     return ($new_answer);
1.251     banghart 3075: }
                   3076: 
1.304     albertel 3077: sub file_name_version_ext {
                   3078:     my ($file)=@_;
                   3079:     my @file_parts = split(/\./, $file);
                   3080:     my ($name,$version,$ext);
                   3081:     if (@file_parts > 1) {
                   3082: 	$ext=pop(@file_parts);
                   3083: 	if (@file_parts > 1 && $file_parts[-1] =~ /^\d+$/) {
                   3084: 	    $version=pop(@file_parts);
                   3085: 	}
                   3086: 	$name=join('.',@file_parts);
                   3087:     } else {
                   3088: 	$name=join('.',@file_parts);
                   3089:     }
                   3090:     return($name,$version,$ext);
                   3091: }
                   3092: 
1.44      ng       3093: #--------------------------------------------------------------------------------------
                   3094: #
                   3095: #-------------------------- Next few routines handles grading by section or whole class
                   3096: #
                   3097: #--- Javascript to handle grading by section or whole class
1.42      ng       3098: sub viewgrades_js {
                   3099:     my ($request) = shift;
                   3100: 
1.539     riegler  3101:     my $alertmsg = &mt('A number equal or greater than 0 is expected. Entered value = ');
1.597     wenzelju 3102:     $request->print(&Apache::lonhtmlcommon::scripttag(<<VIEWJAVASCRIPT));
1.45      ng       3103:    function writePoint(partid,weight,point) {
1.125     ng       3104: 	var radioButton = document.classgrade["RADVAL_"+partid];
                   3105: 	var textbox = document.classgrade["TEXTVAL_"+partid];
1.42      ng       3106: 	if (point == "textval") {
1.125     ng       3107: 	    point = document.classgrade["TEXTVAL_"+partid].value;
1.109     matthew  3108: 	    if (isNaN(point) || parseFloat(point) < 0) {
1.539     riegler  3109: 		alert("$alertmsg"+parseFloat(point));
1.42      ng       3110: 		var resetbox = false;
                   3111: 		for (var i=0; i<radioButton.length; i++) {
                   3112: 		    if (radioButton[i].checked) {
                   3113: 			textbox.value = i;
                   3114: 			resetbox = true;
                   3115: 		    }
                   3116: 		}
                   3117: 		if (!resetbox) {
                   3118: 		    textbox.value = "";
                   3119: 		}
                   3120: 		return;
                   3121: 	    }
1.109     matthew  3122: 	    if (parseFloat(point) > parseFloat(weight)) {
                   3123: 		var resp = confirm("You entered a value ("+parseFloat(point)+
1.44      ng       3124: 				   ") greater than the weight for the part. Accept?");
                   3125: 		if (resp == false) {
                   3126: 		    textbox.value = "";
                   3127: 		    return;
                   3128: 		}
                   3129: 	    }
1.42      ng       3130: 	    for (var i=0; i<radioButton.length; i++) {
                   3131: 		radioButton[i].checked=false;
1.109     matthew  3132: 		if (parseFloat(point) == i) {
1.42      ng       3133: 		    radioButton[i].checked=true;
                   3134: 		}
                   3135: 	    }
1.41      ng       3136: 
1.42      ng       3137: 	} else {
1.125     ng       3138: 	    textbox.value = parseFloat(point);
1.42      ng       3139: 	}
1.41      ng       3140: 	for (i=0;i<document.classgrade.total.value;i++) {
1.125     ng       3141: 	    var user = document.classgrade["ctr"+i].value;
1.289     albertel 3142: 	    user = user.replace(new RegExp(':', 'g'),"_");
1.125     ng       3143: 	    var scorename = document.classgrade["GD_"+user+"_"+partid+"_awarded"];
                   3144: 	    var saveval   = document.classgrade["GD_"+user+"_"+partid+"_solved_s"].value;
                   3145: 	    var selname   = document.classgrade["GD_"+user+"_"+partid+"_solved"];
1.42      ng       3146: 	    if (saveval != "correct") {
                   3147: 		scorename.value = point;
1.43      ng       3148: 		if (selname[0].selected != true) {
                   3149: 		    selname[0].selected = true;
                   3150: 		}
1.42      ng       3151: 	    }
                   3152: 	}
1.125     ng       3153: 	document.classgrade["SELVAL_"+partid][0].selected = true;
1.42      ng       3154:     }
                   3155: 
                   3156:     function writeRadText(partid,weight) {
1.125     ng       3157: 	var selval   = document.classgrade["SELVAL_"+partid];
                   3158: 	var radioButton = document.classgrade["RADVAL_"+partid];
1.265     www      3159:         var override = document.classgrade["FORCE_"+partid].checked;
1.125     ng       3160: 	var textbox = document.classgrade["TEXTVAL_"+partid];
                   3161: 	if (selval[1].selected || selval[2].selected) {
1.42      ng       3162: 	    for (var i=0; i<radioButton.length; i++) {
                   3163: 		radioButton[i].checked=false;
                   3164: 
                   3165: 	    }
                   3166: 	    textbox.value = "";
                   3167: 
                   3168: 	    for (i=0;i<document.classgrade.total.value;i++) {
1.125     ng       3169: 		var user = document.classgrade["ctr"+i].value;
1.289     albertel 3170: 		user = user.replace(new RegExp(':', 'g'),"_");
1.125     ng       3171: 		var scorename = document.classgrade["GD_"+user+"_"+partid+"_awarded"];
                   3172: 		var saveval   = document.classgrade["GD_"+user+"_"+partid+"_solved_s"].value;
                   3173: 		var selname   = document.classgrade["GD_"+user+"_"+partid+"_solved"];
1.265     www      3174: 		if ((saveval != "correct") || override) {
1.42      ng       3175: 		    scorename.value = "";
1.125     ng       3176: 		    if (selval[1].selected) {
                   3177: 			selname[1].selected = true;
                   3178: 		    } else {
                   3179: 			selname[2].selected = true;
                   3180: 			if (Number(document.classgrade["GD_"+user+"_"+partid+"_tries"].value)) 
                   3181: 			{document.classgrade["GD_"+user+"_"+partid+"_tries"].value = '0';}
                   3182: 		    }
1.42      ng       3183: 		}
                   3184: 	    }
1.43      ng       3185: 	} else {
                   3186: 	    for (i=0;i<document.classgrade.total.value;i++) {
1.125     ng       3187: 		var user = document.classgrade["ctr"+i].value;
1.289     albertel 3188: 		user = user.replace(new RegExp(':', 'g'),"_");
1.125     ng       3189: 		var scorename = document.classgrade["GD_"+user+"_"+partid+"_awarded"];
                   3190: 		var saveval   = document.classgrade["GD_"+user+"_"+partid+"_solved_s"].value;
                   3191: 		var selname   = document.classgrade["GD_"+user+"_"+partid+"_solved"];
1.265     www      3192: 		if ((saveval != "correct") || override) {
1.125     ng       3193: 		    scorename.value = document.classgrade["GD_"+user+"_"+partid+"_awarded_s"].value;
1.43      ng       3194: 		    selname[0].selected = true;
                   3195: 		}
                   3196: 	    }
                   3197: 	}	    
1.42      ng       3198:     }
                   3199: 
                   3200:     function changeSelect(partid,user) {
1.125     ng       3201: 	var selval = document.classgrade["GD_"+user+'_'+partid+"_solved"];
                   3202: 	var textbox = document.classgrade["GD_"+user+'_'+partid+"_awarded"];
1.44      ng       3203: 	var point  = textbox.value;
1.125     ng       3204: 	var weight = document.classgrade["weight_"+partid].value;
1.44      ng       3205: 
1.109     matthew  3206: 	if (isNaN(point) || parseFloat(point) < 0) {
1.539     riegler  3207: 	    alert("$alertmsg"+parseFloat(point));
1.44      ng       3208: 	    textbox.value = "";
                   3209: 	    return;
                   3210: 	}
1.109     matthew  3211: 	if (parseFloat(point) > parseFloat(weight)) {
                   3212: 	    var resp = confirm("You entered a value ("+parseFloat(point)+
1.44      ng       3213: 			       ") greater than the weight of the part. Accept?");
                   3214: 	    if (resp == false) {
                   3215: 		textbox.value = "";
                   3216: 		return;
                   3217: 	    }
                   3218: 	}
1.42      ng       3219: 	selval[0].selected = true;
                   3220:     }
                   3221: 
                   3222:     function changeOneScore(partid,user) {
1.125     ng       3223: 	var selval = document.classgrade["GD_"+user+'_'+partid+"_solved"];
                   3224: 	if (selval[1].selected || selval[2].selected) {
                   3225: 	    document.classgrade["GD_"+user+'_'+partid+"_awarded"].value = "";
                   3226: 	    if (selval[2].selected) {
                   3227: 		document.classgrade["GD_"+user+'_'+partid+"_tries"].value = "0";
                   3228: 	    }
1.269     raeburn  3229:         }
1.42      ng       3230:     }
                   3231: 
                   3232:     function resetEntry(numpart) {
                   3233: 	for (ctpart=0;ctpart<numpart;ctpart++) {
1.125     ng       3234: 	    var partid = document.classgrade["partid_"+ctpart].value;
                   3235: 	    var radioButton = document.classgrade["RADVAL_"+partid];
                   3236: 	    var textbox = document.classgrade["TEXTVAL_"+partid];
                   3237: 	    var selval  = document.classgrade["SELVAL_"+partid];
1.42      ng       3238: 	    for (var i=0; i<radioButton.length; i++) {
                   3239: 		radioButton[i].checked=false;
                   3240: 
                   3241: 	    }
                   3242: 	    textbox.value = "";
                   3243: 	    selval[0].selected = true;
                   3244: 
                   3245: 	    for (i=0;i<document.classgrade.total.value;i++) {
1.125     ng       3246: 		var user = document.classgrade["ctr"+i].value;
1.289     albertel 3247: 		user = user.replace(new RegExp(':', 'g'),"_");
1.125     ng       3248: 		var resetscore = document.classgrade["GD_"+user+"_"+partid+"_awarded"];
                   3249: 		resetscore.value = document.classgrade["GD_"+user+"_"+partid+"_awarded_s"].value;
                   3250: 		var resettries = document.classgrade["GD_"+user+"_"+partid+"_tries"];
                   3251: 		resettries.value = document.classgrade["GD_"+user+"_"+partid+"_tries_s"].value;
                   3252: 		var saveselval   = document.classgrade["GD_"+user+"_"+partid+"_solved_s"].value;
                   3253: 		var selname   = document.classgrade["GD_"+user+"_"+partid+"_solved"];
1.42      ng       3254: 		if (saveselval == "excused") {
1.43      ng       3255: 		    if (selname[1].selected == false) { selname[1].selected = true;}
1.42      ng       3256: 		} else {
1.43      ng       3257: 		    if (selname[0].selected == false) {selname[0].selected = true};
1.42      ng       3258: 		}
                   3259: 	    }
1.41      ng       3260: 	}
1.42      ng       3261:     }
                   3262: 
1.41      ng       3263: VIEWJAVASCRIPT
1.42      ng       3264: }
                   3265: 
1.44      ng       3266: #--- show scores for a section or whole class w/ option to change/update a score
1.42      ng       3267: sub viewgrades {
1.608     www      3268:     my ($request,$symb) = @_;
1.42      ng       3269:     &viewgrades_js($request);
1.41      ng       3270: 
1.168     albertel 3271:     #need to make sure we have the correct data for later EXT calls, 
                   3272:     #thus invalidate the cache
                   3273:     &Apache::lonnet::devalidatecourseresdata(
1.257     albertel 3274:                  $env{'course.'.$env{'request.course.id'}.'.num'},
                   3275:                  $env{'course.'.$env{'request.course.id'}.'.domain'});
1.168     albertel 3276:     &Apache::lonnet::clear_EXT_cache_status();
                   3277: 
1.398     albertel 3278:     my $result='<h3><span class="LC_info">'.&mt('Manual Grading').'</span></h3>';
1.41      ng       3279: 
                   3280:     #view individual student submission form - called using Javascript viewOneStudent
1.324     albertel 3281:     $result.=&jscriptNform($symb);
1.41      ng       3282: 
1.44      ng       3283:     #beginning of class grading form
1.442     banghart 3284:     my $stu_status = join(':',&Apache::loncommon::get_env_multiple('form.Status'));
1.41      ng       3285:     $result.= '<form action="/adm/grades" method="post" name="classgrade">'."\n".
1.418     albertel 3286: 	'<input type="hidden" name="symb"    value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
1.38      ng       3287: 	'<input type="hidden" name="command" value="editgrades" />'."\n".
1.432     banghart 3288: 	&build_section_inputs().
1.442     banghart 3289: 	'<input type="hidden" name="Status" value="'.$env{'stu_status'}.'" />'."\n".
1.72      ng       3290: 
1.560     raeburn  3291:     my ($common_header,$specific_header);
1.257     albertel 3292:     if ($env{'form.section'} eq 'all') {
1.560     raeburn  3293: 	$common_header = &mt('Assign Common Grade to Class');
                   3294:         $specific_header = &mt('Assign Grade to Specific Students in Class');
1.257     albertel 3295:     } elsif ($env{'form.section'} eq 'none') {
1.560     raeburn  3296:         $common_header = &mt('Assign Common Grade to Students in no Section');
                   3297: 	$specific_header = &mt('Assign Grade to Specific Students in no Section');
1.52      albertel 3298:     } else {
1.560     raeburn  3299:         my $section_display = join (", ",&Apache::loncommon::get_env_multiple('form.section'));
                   3300:         $common_header = &mt('Assign Common Grade to Students in Section(s) [_1]',$section_display);
                   3301: 	$specific_header = &mt('Assign Grade to Specific Students in Section(s) [_1]',$section_display);
1.52      albertel 3302:     }
1.560     raeburn  3303:     $result.= '<h3>'.$common_header.'</h3>'.&Apache::loncommon::start_data_table();
1.44      ng       3304:     #radio buttons/text box for assigning points for a section or class.
                   3305:     #handles different parts of a problem
1.582     raeburn  3306:     my $res_error;
                   3307:     my ($partlist,$handgrade,$responseType) = &response_type($symb,\$res_error);
                   3308:     if ($res_error) {
                   3309:         return &navmap_errormsg();
                   3310:     }
1.42      ng       3311:     my %weight = ();
                   3312:     my $ctsparts = 0;
1.45      ng       3313:     my %seen = ();
1.375     albertel 3314:     my @part_response_id = &flatten_responseType($responseType);
                   3315:     foreach my $part_response_id (@part_response_id) {
                   3316:     	my ($partid,$respid) = @{ $part_response_id };
                   3317: 	my $part_resp = join('_',@{ $part_response_id });
1.45      ng       3318: 	next if $seen{$partid};
                   3319: 	$seen{$partid}++;
1.375     albertel 3320: 	my $handgrade=$$handgrade{$part_resp};
1.42      ng       3321: 	my $wgt = &Apache::lonnet::EXT('resource.'.$partid.'.weight',$symb);
                   3322: 	$weight{$partid} = $wgt eq '' ? '1' : $wgt;
                   3323: 
1.324     albertel 3324: 	my $display_part=&get_display_part($partid,$symb);
1.485     albertel 3325: 	my $radio.='<table border="0"><tr>';  
1.41      ng       3326: 	my $ctr = 0;
1.42      ng       3327: 	while ($ctr<=$weight{$partid}) { # display radio buttons in a nice table 10 across
1.485     albertel 3328: 	    $radio.= '<td><label><input type="radio" name="RADVAL_'.$partid.'" '.
1.54      albertel 3329: 		'onclick="javascript:writePoint(\''.$partid.'\','.$weight{$partid}.
1.288     albertel 3330: 		','.$ctr.')" />'.$ctr."</label></td>\n";
1.41      ng       3331: 	    $result.=(($ctr+1)%10 == 0 ? '</tr><tr>' : '');
                   3332: 	    $ctr++;
                   3333: 	}
1.485     albertel 3334: 	$radio.='</tr></table>';
                   3335: 	my $line = '<input type="text" name="TEXTVAL_'.
1.589     bisitz   3336: 	    $partid.'" size="4" '.'onchange="javascript:writePoint(\''.
1.54      albertel 3337: 		$partid.'\','.$weight{$partid}.',\'textval\')" /> /'.
1.539     riegler  3338: 	    $weight{$partid}.' '.&mt('(problem weight)').'</td>'."\n";
                   3339: 	$line.= '<td><b>'.&mt('Grade Status').':</b><select name="SELVAL_'.$partid.'"'.
1.589     bisitz   3340: 	    'onchange="javascript:writeRadText(\''.$partid.'\','.
1.59      albertel 3341: 		$weight{$partid}.')"> '.
1.401     albertel 3342: 	    '<option selected="selected"> </option>'.
1.485     albertel 3343: 	    '<option value="excused">'.&mt('excused').'</option>'.
                   3344: 	    '<option value="reset status">'.&mt('reset status').'</option>'.
                   3345: 	    '</select></td>'.
                   3346:             '<td><label><input type="checkbox" name="FORCE_'.$partid.'" />'.&mt('Override "Correct"').'</label>';
                   3347: 	$line.='<input type="hidden" name="partid_'.
                   3348: 	    $ctsparts.'" value="'.$partid.'" />'."\n";
                   3349: 	$line.='<input type="hidden" name="weight_'.
                   3350: 	    $partid.'" value="'.$weight{$partid}.'" />'."\n";
                   3351: 
                   3352: 	$result.=
                   3353: 	    &Apache::loncommon::start_data_table_row()."\n".
1.577     bisitz   3354: 	    '<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 3355: 	    &Apache::loncommon::end_data_table_row()."\n";
1.42      ng       3356: 	$ctsparts++;
1.41      ng       3357:     }
1.474     albertel 3358:     $result.=&Apache::loncommon::end_data_table()."\n".
1.52      albertel 3359: 	'<input type="hidden" name="totalparts" value="'.$ctsparts.'" />';
1.485     albertel 3360:     $result.='<input type="button" value="'.&mt('Revert to Default').'" '.
1.589     bisitz   3361: 	'onclick="javascript:resetEntry('.$ctsparts.');" />';
1.41      ng       3362: 
1.44      ng       3363:     #table listing all the students in a section/class
                   3364:     #header of table
1.560     raeburn  3365:     $result.= '<h3>'.$specific_header.'</h3>'.
                   3366:               &Apache::loncommon::start_data_table().
                   3367: 	      &Apache::loncommon::start_data_table_header_row().
                   3368: 	      '<th>'.&mt('No.').'</th>'.
                   3369: 	      '<th>'.&nameUserString('header')."</th>\n";
1.582     raeburn  3370:     my $partserror;
                   3371:     my (@parts) = sort(&getpartlist($symb,\$partserror));
                   3372:     if ($partserror) {
                   3373:         return &navmap_errormsg();
                   3374:     }
1.324     albertel 3375:     my (undef,undef,$url)=&Apache::lonnet::decode_symb($symb);
1.269     raeburn  3376:     my @partids = ();
1.41      ng       3377:     foreach my $part (@parts) {
                   3378: 	my $display=&Apache::lonnet::metadata($url,$part.'.display');
1.539     riegler  3379:         my $narrowtext = &mt('Tries');
                   3380: 	$display =~ s|^Number of Attempts|$narrowtext <br />|; # makes the column narrower
1.41      ng       3381: 	if  (!$display) { $display = &Apache::lonnet::metadata($url,$part.'.name'); }
1.207     albertel 3382: 	my ($partid) = &split_part_type($part);
1.524     raeburn  3383:         push(@partids,$partid);
1.324     albertel 3384: 	my $display_part=&get_display_part($partid,$symb);
1.41      ng       3385: 	if ($display =~ /^Partial Credit Factor/) {
1.485     albertel 3386: 	    $result.='<th>'.
                   3387: 		&mt('Score Part: [_1]<br /> (weight = [_2])',
                   3388: 		    $display_part,$weight{$partid}).'</th>'."\n";
1.41      ng       3389: 	    next;
1.485     albertel 3390: 	    
1.207     albertel 3391: 	} else {
1.485     albertel 3392: 	    if ($display =~ /Problem Status/) {
                   3393: 		my $grade_status_mt = &mt('Grade Status');
                   3394: 		$display =~ s{Problem Status}{$grade_status_mt<br />};
                   3395: 	    }
                   3396: 	    my $part_mt = &mt('Part:');
                   3397: 	    $display =~s{\[Part: \Q$partid\E\]}{$part_mt $display_part};
1.41      ng       3398: 	}
1.485     albertel 3399: 
1.474     albertel 3400: 	$result.='<th>'.$display.'</th>'."\n";
1.41      ng       3401:     }
1.474     albertel 3402:     $result.=&Apache::loncommon::end_data_table_header_row();
1.44      ng       3403: 
1.270     albertel 3404:     my %last_resets = 
                   3405: 	&get_last_resets($symb,$env{'request.course.id'},\@partids);
1.269     raeburn  3406: 
1.41      ng       3407:     #get info for each student
1.44      ng       3408:     #list all the students - with points and grade status
1.257     albertel 3409:     my (undef,undef,$fullname) = &getclasslist($env{'form.section'},'1');
1.41      ng       3410:     my $ctr = 0;
1.294     albertel 3411:     foreach (sort 
                   3412: 	     {
                   3413: 		 if (lc($$fullname{$a}) ne lc($$fullname{$b})) {
                   3414: 		     return (lc($$fullname{$a}) cmp lc($$fullname{$b}));
                   3415: 		 }
                   3416: 		 return $a cmp $b;
                   3417: 	     } (keys(%$fullname))) {
1.126     ng       3418: 	$ctr++;
1.324     albertel 3419: 	$result.=&viewstudentgrade($symb,$env{'request.course.id'},
1.269     raeburn  3420: 				   $_,$$fullname{$_},\@parts,\%weight,$ctr,\%last_resets);
1.41      ng       3421:     }
1.474     albertel 3422:     $result.=&Apache::loncommon::end_data_table();
1.41      ng       3423:     $result.='<input type="hidden" name="total" value="'.$ctr.'" />'."\n";
1.485     albertel 3424:     $result.='<input type="button" value="'.&mt('Save').'" '.
1.589     bisitz   3425: 	'onclick="javascript:submit();" target="_self" /></form>'."\n";
1.96      albertel 3426:     if (scalar(%$fullname) eq 0) {
                   3427: 	my $colspan=3+scalar(@parts);
1.433     banghart 3428: 	my $section_display = join (", ",&Apache::loncommon::get_env_multiple('form.section'));
1.442     banghart 3429:         my $stu_status = join(' or ',&Apache::loncommon::get_env_multiple('form.Status'));
1.433     banghart 3430: 	$result='<span class="LC_warning">'.
1.485     albertel 3431: 	    &mt('There are no students in section(s) [_1] with enrollment status [_2] to modify or grade.',
1.442     banghart 3432: 	        $section_display, $stu_status).
1.433     banghart 3433: 	    '</span>';
1.96      albertel 3434:     }
1.324     albertel 3435:     $result.=&show_grading_menu_form($symb);
1.41      ng       3436:     return $result;
                   3437: }
                   3438: 
1.44      ng       3439: #--- call by previous routine to display each student
1.41      ng       3440: sub viewstudentgrade {
1.324     albertel 3441:     my ($symb,$courseid,$student,$fullname,$parts,$weight,$ctr,$last_resets) = @_;
1.44      ng       3442:     my ($uname,$udom) = split(/:/,$student);
                   3443:     my %record=&Apache::lonnet::restore($symb,$courseid,$udom,$uname);
1.269     raeburn  3444:     my %aggregates = (); 
1.474     albertel 3445:     my $result=&Apache::loncommon::start_data_table_row().'<td align="right">'.
1.233     albertel 3446: 	'<input type="hidden" name="ctr'.($ctr-1).'" value="'.$student.'" />'.
                   3447: 	"\n".$ctr.'&nbsp;</td><td>&nbsp;'.
1.44      ng       3448: 	'<a href="javascript:viewOneStudent(\''.$uname.'\',\''.$udom.
1.417     albertel 3449: 	'\');" target="_self">'.$fullname.'</a> '.
1.398     albertel 3450: 	'<span class="LC_internal_info">('.$uname.($env{'user.domain'} eq $udom ? '' : ':'.$udom).')</span></td>'."\n";
1.281     albertel 3451:     $student=~s/:/_/; # colon doen't work in javascript for names
1.63      albertel 3452:     foreach my $apart (@$parts) {
                   3453: 	my ($part,$type) = &split_part_type($apart);
1.41      ng       3454: 	my $score=$record{"resource.$part.$type"};
1.276     albertel 3455:         $result.='<td align="center">';
1.269     raeburn  3456:         my ($aggtries,$totaltries);
                   3457:         unless (exists($aggregates{$part})) {
1.270     albertel 3458: 	    $totaltries = $record{'resource.'.$part.'.tries'};
                   3459: 
                   3460: 	    $aggtries = $totaltries;
1.269     raeburn  3461:             if ($$last_resets{$part}) {  
1.270     albertel 3462:                 $aggtries = &get_num_tries(\%record,$$last_resets{$part},
                   3463: 					   $part);
                   3464:             }
1.269     raeburn  3465:             $result.='<input type="hidden" name="'.
                   3466:                 'GD_'.$student.'_'.$part.'_aggtries" value="'.$aggtries.'" />'."\n";
                   3467:             $result.='<input type="hidden" name="'.
                   3468:                 'GD_'.$student.'_'.$part.'_totaltries" value="'.$totaltries.'" />'."\n";
                   3469:             $aggregates{$part} = 1;
                   3470:         }
1.41      ng       3471: 	if ($type eq 'awarded') {
1.320     albertel 3472: 	    my $pts = $score eq '' ? '' : &compute_points($score,$$weight{$part});
1.42      ng       3473: 	    $result.='<input type="hidden" name="'.
1.89      albertel 3474: 		'GD_'.$student.'_'.$part.'_awarded_s" value="'.$pts.'" />'."\n";
1.233     albertel 3475: 	    $result.='<input type="text" name="'.
1.89      albertel 3476: 		'GD_'.$student.'_'.$part.'_awarded" '.
1.589     bisitz   3477:                 'onchange="javascript:changeSelect(\''.$part.'\',\''.$student.
1.44      ng       3478: 		'\')" value="'.$pts.'" size="4" /></td>'."\n";
1.41      ng       3479: 	} elsif ($type eq 'solved') {
                   3480: 	    my ($status,$foo)=split(/_/,$score,2);
                   3481: 	    $status = 'nothing' if ($status eq '');
1.89      albertel 3482: 	    $result.='<input type="hidden" name="'.'GD_'.$student.'_'.
1.54      albertel 3483: 		$part.'_solved_s" value="'.$status.'" />'."\n";
1.233     albertel 3484: 	    $result.='&nbsp;<select name="'.
1.89      albertel 3485: 		'GD_'.$student.'_'.$part.'_solved" '.
1.589     bisitz   3486:                 'onchange="javascript:changeOneScore(\''.$part.'\',\''.$student.'\')" >'."\n";
1.485     albertel 3487: 	    $result.= (($status eq 'excused') ? '<option> </option><option selected="selected" value="excused">'.&mt('excused').'</option>' 
                   3488: 		: '<option selected="selected"> </option><option value="excused">'.&mt('excused').'</option>')."\n";
                   3489: 	    $result.='<option value="reset status">'.&mt('reset status').'</option>';
1.126     ng       3490: 	    $result.="</select>&nbsp;</td>\n";
1.122     ng       3491: 	} else {
                   3492: 	    $result.='<input type="hidden" name="'.
                   3493: 		'GD_'.$student.'_'.$part.'_'.$type.'_s" value="'.$score.'" />'.
                   3494: 		    "\n";
1.233     albertel 3495: 	    $result.='<input type="text" name="'.
1.122     ng       3496: 		'GD_'.$student.'_'.$part.'_'.$type.'" '.
                   3497: 		'value="'.$score.'" size="4" /></td>'."\n";
1.41      ng       3498: 	}
                   3499:     }
1.474     albertel 3500:     $result.=&Apache::loncommon::end_data_table_row();
1.41      ng       3501:     return $result;
1.38      ng       3502: }
                   3503: 
1.44      ng       3504: #--- change scores for all the students in a section/class
                   3505: #    record does not get update if unchanged
1.38      ng       3506: sub editgrades {
1.608     www      3507:     my ($request,$symb) = @_;
1.41      ng       3508: 
1.433     banghart 3509:     my $section_display = join (", ",&Apache::loncommon::get_env_multiple('form.section'));
1.477     albertel 3510:     my $title='<h2>'.&mt('Current Grade Status').'</h2>';
1.433     banghart 3511:     $title.='<h4>'.&mt('<b>Section: </b>[_1]',$section_display).'</h4>'."\n";
1.126     ng       3512: 
1.477     albertel 3513:     my $result= &Apache::loncommon::start_data_table().
                   3514: 	&Apache::loncommon::start_data_table_header_row().
                   3515: 	'<th rowspan="2" valign="middle">'.&mt('No.').'</th>'.
                   3516: 	'<th rowspan="2" valign="middle">'.&nameUserString('header')."</th>\n";
1.43      ng       3517:     my %scoreptr = (
                   3518: 		    'correct'  =>'correct_by_override',
                   3519: 		    'incorrect'=>'incorrect_by_override',
                   3520: 		    'excused'  =>'excused',
                   3521: 		    'ungraded' =>'ungraded_attempted',
1.596     raeburn  3522:                     'credited' =>'credit_attempted',
1.43      ng       3523: 		    'nothing'  => '',
                   3524: 		    );
1.257     albertel 3525:     my ($classlist,undef,$fullname) = &getclasslist($env{'form.section'},'0');
1.34      ng       3526: 
1.44      ng       3527:     my (@partid);
                   3528:     my %weight = ();
1.54      albertel 3529:     my %columns = ();
1.44      ng       3530:     my ($i,$ctr,$count,$rec_update) = (0,0,0,0);
1.54      albertel 3531: 
1.582     raeburn  3532:     my $partserror;
                   3533:     my (@parts) = sort(&getpartlist($symb,\$partserror));
                   3534:     if ($partserror) {
                   3535:         return &navmap_errormsg();
                   3536:     }
1.54      albertel 3537:     my $header;
1.257     albertel 3538:     while ($ctr < $env{'form.totalparts'}) {
                   3539: 	my $partid = $env{'form.partid_'.$ctr};
1.524     raeburn  3540: 	push(@partid,$partid);
1.257     albertel 3541: 	$weight{$partid} = $env{'form.weight_'.$partid};
1.44      ng       3542: 	$ctr++;
1.54      albertel 3543:     }
1.324     albertel 3544:     my (undef,undef,$url) = &Apache::lonnet::decode_symb($symb);
1.54      albertel 3545:     foreach my $partid (@partid) {
1.478     albertel 3546: 	$header .= '<th align="center">'.&mt('Old Score').'</th>'.
                   3547: 	    '<th align="center">'.&mt('New Score').'</th>';
1.54      albertel 3548: 	$columns{$partid}=2;
                   3549: 	foreach my $stores (@parts) {
                   3550: 	    my ($part,$type) = &split_part_type($stores);
                   3551: 	    if ($part !~ m/^\Q$partid\E/) { next;}
                   3552: 	    if ($type eq 'awarded' || $type eq 'solved') { next; }
                   3553: 	    my $display=&Apache::lonnet::metadata($url,$stores.'.display');
1.551     raeburn  3554: 	    $display =~ s/\[Part: \Q$part\E\]//;
1.539     riegler  3555:             my $narrowtext = &mt('Tries');
                   3556: 	    $display =~ s/Number of Attempts/$narrowtext/;
                   3557: 	    $header .= '<th align="center">'.&mt('Old').' '.$display.'</th>'.
                   3558: 		'<th align="center">'.&mt('New').' '.$display.'</th>';
1.54      albertel 3559: 	    $columns{$partid}+=2;
                   3560: 	}
                   3561:     }
                   3562:     foreach my $partid (@partid) {
1.324     albertel 3563: 	my $display_part=&get_display_part($partid,$symb);
1.478     albertel 3564: 	$result .= '<th colspan="'.$columns{$partid}.'" align="center">'.
                   3565: 	    &mt('Part: [_1] (Weight = [_2])',$display_part,$weight{$partid}).
                   3566: 	    '</th>';
1.54      albertel 3567: 
1.44      ng       3568:     }
1.477     albertel 3569:     $result .= &Apache::loncommon::end_data_table_header_row().
                   3570: 	&Apache::loncommon::start_data_table_header_row().
                   3571: 	$header.
                   3572: 	&Apache::loncommon::end_data_table_header_row();
                   3573:     my @noupdate;
1.126     ng       3574:     my ($updateCtr,$noupdateCtr) = (1,1);
1.257     albertel 3575:     for ($i=0; $i<$env{'form.total'}; $i++) {
1.93      albertel 3576: 	my $line;
1.257     albertel 3577: 	my $user = $env{'form.ctr'.$i};
1.281     albertel 3578: 	my ($uname,$udom)=split(/:/,$user);
1.44      ng       3579: 	my %newrecord;
                   3580: 	my $updateflag = 0;
1.281     albertel 3581: 	$line .= '<td>'.&nameUserString(undef,$$fullname{$user},$uname,$udom).'</td>';
1.108     albertel 3582: 	my $usec=$classlist->{"$uname:$udom"}[5];
1.105     albertel 3583: 	if (!&canmodify($usec)) {
1.126     ng       3584: 	    my $numcols=scalar(@partid)*4+2;
1.477     albertel 3585: 	    push(@noupdate,
1.478     albertel 3586: 		 $line."<td colspan=\"$numcols\"><span class=\"LC_warning\">".
                   3587: 		 &mt('Not allowed to modify student')."</span></td></tr>");
1.105     albertel 3588: 	    next;
                   3589: 	}
1.269     raeburn  3590:         my %aggregate = ();
                   3591:         my $aggregateflag = 0;
1.281     albertel 3592: 	$user=~s/:/_/; # colon doen't work in javascript for names
1.44      ng       3593: 	foreach (@partid) {
1.257     albertel 3594: 	    my $old_aw    = $env{'form.GD_'.$user.'_'.$_.'_awarded_s'};
1.54      albertel 3595: 	    my $old_part_pcr = $old_aw/($weight{$_} ne '0' ? $weight{$_}:1);
                   3596: 	    my $old_part  = $old_aw eq '' ? '' : $old_part_pcr;
1.257     albertel 3597: 	    my $old_score = $scoreptr{$env{'form.GD_'.$user.'_'.$_.'_solved_s'}};
                   3598: 	    my $awarded   = $env{'form.GD_'.$user.'_'.$_.'_awarded'};
1.54      albertel 3599: 	    my $pcr       = $awarded/($weight{$_} ne '0' ? $weight{$_} : 1);
                   3600: 	    my $partial   = $awarded eq '' ? '' : $pcr;
1.44      ng       3601: 	    my $score;
                   3602: 	    if ($partial eq '') {
1.257     albertel 3603: 		$score = $scoreptr{$env{'form.GD_'.$user.'_'.$_.'_solved_s'}};
1.44      ng       3604: 	    } elsif ($partial > 0) {
                   3605: 		$score = 'correct_by_override';
                   3606: 	    } elsif ($partial == 0) {
                   3607: 		$score = 'incorrect_by_override';
                   3608: 	    }
1.257     albertel 3609: 	    my $dropMenu = $env{'form.GD_'.$user.'_'.$_.'_solved'};
1.125     ng       3610: 	    $score = 'excused' if (($dropMenu eq 'excused') && ($score ne 'excused'));
                   3611: 
1.292     albertel 3612: 	    $newrecord{'resource.'.$_.'.regrader'}=
                   3613: 		"$env{'user.name'}:$env{'user.domain'}";
1.125     ng       3614: 	    if ($dropMenu eq 'reset status' &&
                   3615: 		$old_score ne '') { # ignore if no previous attempts => nothing to reset
1.299     albertel 3616: 		$newrecord{'resource.'.$_.'.tries'} = '';
1.125     ng       3617: 		$newrecord{'resource.'.$_.'.solved'} = '';
                   3618: 		$newrecord{'resource.'.$_.'.award'} = '';
1.299     albertel 3619: 		$newrecord{'resource.'.$_.'.awarded'} = '';
1.125     ng       3620: 		$updateflag = 1;
1.269     raeburn  3621:                 if ($env{'form.GD_'.$user.'_'.$_.'_aggtries'} > 0) {
                   3622:                     my $aggtries = $env{'form.GD_'.$user.'_'.$_.'_aggtries'};
                   3623:                     my $totaltries = $env{'form.GD_'.$user.'_'.$_.'_totaltries'};
                   3624:                     my $solvedstatus = $env{'form.GD_'.$user.'_'.$_.'_solved_s'};
                   3625:                     &decrement_aggs($symb,$_,\%aggregate,$aggtries,$totaltries,$solvedstatus);
                   3626:                     $aggregateflag = 1;
                   3627:                 }
1.139     albertel 3628: 	    } elsif (!($old_part eq $partial && $old_score eq $score)) {
                   3629: 		$updateflag = 1;
                   3630: 		$newrecord{'resource.'.$_.'.awarded'}  = $partial if $partial ne '';
                   3631: 		$newrecord{'resource.'.$_.'.solved'}   = $score;
                   3632: 		$rec_update++;
1.125     ng       3633: 	    }
                   3634: 
1.93      albertel 3635: 	    $line .= '<td align="center">'.$old_aw.'&nbsp;</td>'.
1.44      ng       3636: 		'<td align="center">'.$awarded.
                   3637: 		($score eq 'excused' ? $score : '').'&nbsp;</td>';
1.5       albertel 3638: 
1.54      albertel 3639: 
                   3640: 	    my $partid=$_;
                   3641: 	    foreach my $stores (@parts) {
                   3642: 		my ($part,$type) = &split_part_type($stores);
                   3643: 		if ($part !~ m/^\Q$partid\E/) { next;}
                   3644: 		if ($type eq 'awarded' || $type eq 'solved') { next; }
1.257     albertel 3645: 		my $old_aw    = $env{'form.GD_'.$user.'_'.$part.'_'.$type.'_s'};
                   3646: 		my $awarded   = $env{'form.GD_'.$user.'_'.$part.'_'.$type};
1.54      albertel 3647: 		if ($awarded ne '' && $awarded ne $old_aw) {
                   3648: 		    $newrecord{'resource.'.$part.'.'.$type}= $awarded;
1.257     albertel 3649: 		    $newrecord{'resource.'.$part.'.regrader'}="$env{'user.name'}:$env{'user.domain'}";
1.54      albertel 3650: 		    $updateflag=1;
                   3651: 		}
1.93      albertel 3652: 		$line .= '<td align="center">'.$old_aw.'&nbsp;</td>'.
1.54      albertel 3653: 		    '<td align="center">'.$awarded.'&nbsp;</td>';
                   3654: 	    }
1.44      ng       3655: 	}
1.477     albertel 3656: 	$line.="\n";
1.301     albertel 3657: 
                   3658: 	my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   3659: 	my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   3660: 
1.44      ng       3661: 	if ($updateflag) {
                   3662: 	    $count++;
1.257     albertel 3663: 	    &Apache::lonnet::cstore(\%newrecord,$symb,$env{'request.course.id'},
1.89      albertel 3664: 				    $udom,$uname);
1.301     albertel 3665: 
                   3666: 	    if (&Apache::bridgetask::in_queue('gradingqueue',$symb,$cdom,
                   3667: 					      $cnum,$udom,$uname)) {
                   3668: 		# need to figure out if should be in queue.
                   3669: 		my %record =  
                   3670: 		    &Apache::lonnet::restore($symb,$env{'request.course.id'},
                   3671: 					     $udom,$uname);
                   3672: 		my $all_graded = 1;
                   3673: 		my $none_graded = 1;
                   3674: 		foreach my $part (@parts) {
                   3675: 		    if ( $record{'resource.'.$part.'.awarded'} eq '' ) {
                   3676: 			$all_graded = 0;
                   3677: 		    } else {
                   3678: 			$none_graded = 0;
                   3679: 		    }
                   3680: 		}
                   3681: 
                   3682: 		if ($all_graded || $none_graded) {
                   3683: 		    &Apache::bridgetask::remove_from_queue('gradingqueue',
                   3684: 							   $symb,$cdom,$cnum,
                   3685: 							   $udom,$uname);
                   3686: 		}
                   3687: 	    }
                   3688: 
1.477     albertel 3689: 	    $result.=&Apache::loncommon::start_data_table_row().
                   3690: 		'<td align="right">&nbsp;'.$updateCtr.'&nbsp;</td>'.$line.
                   3691: 		&Apache::loncommon::end_data_table_row();
1.126     ng       3692: 	    $updateCtr++;
1.93      albertel 3693: 	} else {
1.477     albertel 3694: 	    push(@noupdate,
                   3695: 		 '<td align="right">&nbsp;'.$noupdateCtr.'&nbsp;</td>'.$line);
1.126     ng       3696: 	    $noupdateCtr++;
1.44      ng       3697: 	}
1.269     raeburn  3698:         if ($aggregateflag) {
                   3699:             &Apache::lonnet::cinc('nohist_resourcetracker',\%aggregate,
1.301     albertel 3700: 				  $cdom,$cnum);
1.269     raeburn  3701:         }
1.93      albertel 3702:     }
1.477     albertel 3703:     if (@noupdate) {
1.126     ng       3704: #	my $numcols=(scalar(@partid)*(scalar(@parts)-1)*2)+3;
                   3705: 	my $numcols=scalar(@partid)*4+2;
1.477     albertel 3706: 	$result .= &Apache::loncommon::start_data_table_row('LC_empty_row').
1.478     albertel 3707: 	    '<td align="center" colspan="'.$numcols.'">'.
                   3708: 	    &mt('No Changes Occurred For the Students Below').
                   3709: 	    '</td>'.
1.477     albertel 3710: 	    &Apache::loncommon::end_data_table_row();
                   3711: 	foreach my $line (@noupdate) {
                   3712: 	    $result.=
                   3713: 		&Apache::loncommon::start_data_table_row().
                   3714: 		$line.
                   3715: 		&Apache::loncommon::end_data_table_row();
                   3716: 	}
1.44      ng       3717:     }
1.477     albertel 3718:     $result .= &Apache::loncommon::end_data_table().
                   3719: 	&show_grading_menu_form($symb);
1.478     albertel 3720:     my $msg = '<p><b>'.
                   3721: 	&mt('Number of records updated = [_1] for [quant,_2,student].',
                   3722: 	    $rec_update,$count).'</b><br />'.
                   3723: 	'<b>'.&mt('Total number of students = [_1]',$env{'form.total'}).
                   3724: 	'</b></p>';
1.44      ng       3725:     return $title.$msg.$result;
1.5       albertel 3726: }
1.54      albertel 3727: 
                   3728: sub split_part_type {
                   3729:     my ($partstr) = @_;
                   3730:     my ($temp,@allparts)=split(/_/,$partstr);
                   3731:     my $type=pop(@allparts);
1.439     albertel 3732:     my $part=join('_',@allparts);
1.54      albertel 3733:     return ($part,$type);
                   3734: }
                   3735: 
1.44      ng       3736: #------------- end of section for handling grading by section/class ---------
                   3737: #
                   3738: #----------------------------------------------------------------------------
                   3739: 
1.5       albertel 3740: 
1.44      ng       3741: #----------------------------------------------------------------------------
                   3742: #
                   3743: #-------------------------- Next few routines handles grading by csv upload
                   3744: #
                   3745: #--- Javascript to handle csv upload
1.27      albertel 3746: sub csvupload_javascript_reverse_associate {
1.573     bisitz   3747:     my $error1=&mt('You need to specify the username or the student/employee ID');
1.246     albertel 3748:     my $error2=&mt('You need to specify at least one grading field');
1.27      albertel 3749:   return(<<ENDPICK);
                   3750:   function verify(vf) {
                   3751:     var foundsomething=0;
                   3752:     var founduname=0;
1.243     albertel 3753:     var foundID=0;
1.27      albertel 3754:     for (i=0;i<=vf.nfields.value;i++) {
                   3755:       tw=eval('vf.f'+i+'.selectedIndex');
1.243     albertel 3756:       if (i==0 && tw!=0) { foundID=1; }
                   3757:       if (i==1 && tw!=0) { founduname=1; }
                   3758:       if (i!=0 && i!=1 && i!=2 && tw!=0) { foundsomething=1; }
1.27      albertel 3759:     }
1.246     albertel 3760:     if (founduname==0 && foundID==0) {
                   3761: 	alert('$error1');
                   3762: 	return;
1.27      albertel 3763:     }
                   3764:     if (foundsomething==0) {
1.246     albertel 3765: 	alert('$error2');
                   3766: 	return;
1.27      albertel 3767:     }
                   3768:     vf.submit();
                   3769:   }
                   3770:   function flip(vf,tf) {
                   3771:     var nw=eval('vf.f'+tf+'.selectedIndex');
                   3772:     var i;
                   3773:     for (i=0;i<=vf.nfields.value;i++) {
                   3774:       //can not pick the same destination field for both name and domain
                   3775:       if (((i ==0)||(i ==1)) && 
                   3776:           ((tf==0)||(tf==1)) && 
                   3777:           (i!=tf) &&
                   3778:           (eval('vf.f'+i+'.selectedIndex')==nw)) {
                   3779:         eval('vf.f'+i+'.selectedIndex=0;')
                   3780:       }
                   3781:     }
                   3782:   }
                   3783: ENDPICK
                   3784: }
                   3785: 
                   3786: sub csvupload_javascript_forward_associate {
1.573     bisitz   3787:     my $error1=&mt('You need to specify the username or the student/employee ID');
1.246     albertel 3788:     my $error2=&mt('You need to specify at least one grading field');
1.27      albertel 3789:   return(<<ENDPICK);
                   3790:   function verify(vf) {
                   3791:     var foundsomething=0;
                   3792:     var founduname=0;
1.243     albertel 3793:     var foundID=0;
1.27      albertel 3794:     for (i=0;i<=vf.nfields.value;i++) {
                   3795:       tw=eval('vf.f'+i+'.selectedIndex');
1.243     albertel 3796:       if (tw==1) { foundID=1; }
                   3797:       if (tw==2) { founduname=1; }
                   3798:       if (tw>3) { foundsomething=1; }
1.27      albertel 3799:     }
1.246     albertel 3800:     if (founduname==0 && foundID==0) {
                   3801: 	alert('$error1');
                   3802: 	return;
1.27      albertel 3803:     }
                   3804:     if (foundsomething==0) {
1.246     albertel 3805: 	alert('$error2');
                   3806: 	return;
1.27      albertel 3807:     }
                   3808:     vf.submit();
                   3809:   }
                   3810:   function flip(vf,tf) {
                   3811:     var nw=eval('vf.f'+tf+'.selectedIndex');
                   3812:     var i;
                   3813:     //can not pick the same destination field twice
                   3814:     for (i=0;i<=vf.nfields.value;i++) {
                   3815:       if ((i!=tf) && (eval('vf.f'+i+'.selectedIndex')==nw)) {
                   3816:         eval('vf.f'+i+'.selectedIndex=0;')
                   3817:       }
                   3818:     }
                   3819:   }
                   3820: ENDPICK
                   3821: }
                   3822: 
1.26      albertel 3823: sub csvuploadmap_header {
1.324     albertel 3824:     my ($request,$symb,$datatoken,$distotal)= @_;
1.41      ng       3825:     my $javascript;
1.257     albertel 3826:     if ($env{'form.upfile_associate'} eq 'reverse') {
1.41      ng       3827: 	$javascript=&csvupload_javascript_reverse_associate();
                   3828:     } else {
                   3829: 	$javascript=&csvupload_javascript_forward_associate();
                   3830:     }
1.45      ng       3831: 
1.598     www      3832:     my $result='';
1.257     albertel 3833:     my $checked=(($env{'form.noFirstLine'})?' checked="checked"':'');
1.245     albertel 3834:     my $ignore=&mt('Ignore First Line');
1.418     albertel 3835:     $symb = &Apache::lonenc::check_encrypt($symb);
1.41      ng       3836:     $request->print(<<ENDPICK);
1.26      albertel 3837: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="gradesupload">
1.398     albertel 3838: <h3><span class="LC_info">Uploading Class Grades</span></h3>
1.45      ng       3839: $result
1.326     albertel 3840: <hr />
1.26      albertel 3841: <h3>Identify fields</h3>
                   3842: Total number of records found in file: $distotal <hr />
                   3843: Enter as many fields as you can. The system will inform you and bring you back
                   3844: to this page if the data selected is insufficient to run your class.<hr />
1.589     bisitz   3845: <input type="button" value="Reverse Association" onclick="javascript:this.form.associate.value='Reverse Association';submit(this.form);" />
1.245     albertel 3846: <label><input type="checkbox" name="noFirstLine" $checked />$ignore</label>
1.26      albertel 3847: <input type="hidden" name="associate"  value="" />
                   3848: <input type="hidden" name="phase"      value="three" />
                   3849: <input type="hidden" name="datatoken"  value="$datatoken" />
1.257     albertel 3850: <input type="hidden" name="fileupload" value="$env{'form.fileupload'}" />
                   3851: <input type="hidden" name="upfiletype" value="$env{'form.upfiletype'}" />
1.26      albertel 3852: <input type="hidden" name="upfile_associate" 
1.257     albertel 3853:                                        value="$env{'form.upfile_associate'}" />
1.26      albertel 3854: <input type="hidden" name="symb"       value="$symb" />
1.246     albertel 3855: <input type="hidden" name="command"    value="csvuploadoptions" />
1.26      albertel 3856: <hr />
                   3857: ENDPICK
1.597     wenzelju 3858:     $request->print(&Apache::lonhtmlcommon::scripttag($javascript));
1.118     ng       3859:     return '';
1.26      albertel 3860: 
                   3861: }
                   3862: 
                   3863: sub csvupload_fields {
1.582     raeburn  3864:     my ($symb,$errorref) = @_;
                   3865:     my (@parts) = &getpartlist($symb,$errorref);
                   3866:     if (ref($errorref)) {
                   3867:         if ($$errorref) {
                   3868:             return;
                   3869:         }
                   3870:     }
                   3871: 
1.556     weissno  3872:     my @fields=(['ID','Student/Employee ID'],
1.243     albertel 3873: 		['username','Student Username'],
                   3874: 		['domain','Student Domain']);
1.324     albertel 3875:     my (undef,undef,$url) = &Apache::lonnet::decode_symb($symb);
1.41      ng       3876:     foreach my $part (sort(@parts)) {
                   3877: 	my @datum;
                   3878: 	my $display=&Apache::lonnet::metadata($url,$part.'.display');
                   3879: 	my $name=$part;
                   3880: 	if  (!$display) { $display = $name; }
                   3881: 	@datum=($name,$display);
1.244     albertel 3882: 	if ($name=~/^stores_(.*)_awarded/) {
                   3883: 	    push(@fields,['stores_'.$1.'_points',"Points [Part: $1]"]);
                   3884: 	}
1.41      ng       3885: 	push(@fields,\@datum);
                   3886:     }
                   3887:     return (@fields);
1.26      albertel 3888: }
                   3889: 
                   3890: sub csvuploadmap_footer {
1.41      ng       3891:     my ($request,$i,$keyfields) =@_;
                   3892:     $request->print(<<ENDPICK);
1.26      albertel 3893: </table>
                   3894: <input type="hidden" name="nfields" value="$i" />
                   3895: <input type="hidden" name="keyfields" value="$keyfields" />
1.589     bisitz   3896: <input type="button" onclick="javascript:verify(this.form)" value="Assign Grades" /><br />
1.26      albertel 3897: </form>
                   3898: ENDPICK
                   3899: }
                   3900: 
1.283     albertel 3901: sub checkforfile_js {
1.539     riegler  3902:     my $alertmsg = &mt('Please use the browse button to select a file from your local directory.');
1.597     wenzelju 3903:     my $result = &Apache::lonhtmlcommon::scripttag(<<CSVFORMJS);
1.86      ng       3904:     function checkUpload(formname) {
                   3905: 	if (formname.upfile.value == "") {
1.539     riegler  3906: 	    alert("$alertmsg");
1.86      ng       3907: 	    return false;
                   3908: 	}
                   3909: 	formname.submit();
                   3910:     }
                   3911: CSVFORMJS
1.283     albertel 3912:     return $result;
                   3913: }
                   3914: 
                   3915: sub upcsvScores_form {
1.608     www      3916:     my ($request,$symb) = @_;
1.283     albertel 3917:     if (!$symb) {return '';}
                   3918:     my $result=&checkforfile_js();
1.326     albertel 3919:     $result.='<br /><table width="100%" border="0"><tr><td bgcolor="#777777">'."\n";
                   3920:     $result.='<table width="100%" border="0"><tr bgcolor="#e6ffff"><td>'."\n";
1.538     schulted 3921:     $result.='&nbsp;<b>'.&mt('Specify a file containing the class scores for current resource.').
                   3922: 	'</b></td></tr>'."\n";
1.86      ng       3923:     $result.='<tr bgcolor=#ffffe6><td>'."\n";
1.370     www      3924:     my $upload=&mt("Upload Scores");
1.86      ng       3925:     my $upfile_select=&Apache::loncommon::upfile_select_html();
1.245     albertel 3926:     my $ignore=&mt('Ignore First Line');
1.418     albertel 3927:     $symb = &Apache::lonenc::check_encrypt($symb);
1.86      ng       3928:     $result.=<<ENDUPFORM;
1.106     albertel 3929: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="gradesupload">
1.86      ng       3930: <input type="hidden" name="symb" value="$symb" />
                   3931: <input type="hidden" name="command" value="csvuploadmap" />
                   3932: $upfile_select
1.589     bisitz   3933: <br /><input type="button" onclick="javascript:checkUpload(this.form);" value="$upload" />
1.283     albertel 3934: <label><input type="checkbox" name="noFirstLine" />$ignore</label>
1.86      ng       3935: </form>
                   3936: ENDUPFORM
1.370     www      3937:     $result.=&Apache::loncommon::help_open_topic("Course_Convert_To_CSV",
                   3938:                            &mt("How do I create a CSV file from a spreadsheet"))
                   3939:     .'</td></tr></table>'."\n";
1.86      ng       3940:     $result.='</td></tr></table><br /><br />'."\n";
1.324     albertel 3941:     $result.=&show_grading_menu_form($symb);
1.86      ng       3942:     return $result;
                   3943: }
                   3944: 
                   3945: 
1.26      albertel 3946: sub csvuploadmap {
1.608     www      3947:     my ($request,$symb)= @_;
1.41      ng       3948:     if (!$symb) {return '';}
1.72      ng       3949: 
1.41      ng       3950:     my $datatoken;
1.257     albertel 3951:     if (!$env{'form.datatoken'}) {
1.41      ng       3952: 	$datatoken=&Apache::loncommon::upfile_store($request);
1.26      albertel 3953:     } else {
1.257     albertel 3954: 	$datatoken=$env{'form.datatoken'};
1.41      ng       3955: 	&Apache::loncommon::load_tmp_file($request);
1.26      albertel 3956:     }
1.41      ng       3957:     my @records=&Apache::loncommon::upfile_record_sep();
1.257     albertel 3958:     if ($env{'form.noFirstLine'}) { shift(@records); }
1.324     albertel 3959:     &csvuploadmap_header($request,$symb,$datatoken,$#records+1);
1.41      ng       3960:     my ($i,$keyfields);
                   3961:     if (@records) {
1.582     raeburn  3962:         my $fieldserror;
                   3963: 	my @fields=&csvupload_fields($symb,\$fieldserror);
                   3964:         if ($fieldserror) {
                   3965:             $request->print(&navmap_errormsg());
                   3966:             return;
                   3967:         }
1.257     albertel 3968: 	if ($env{'form.upfile_associate'} eq 'reverse') {	
1.41      ng       3969: 	    &Apache::loncommon::csv_print_samples($request,\@records);
                   3970: 	    $i=&Apache::loncommon::csv_print_select_table($request,\@records,
                   3971: 							  \@fields);
                   3972: 	    foreach (@fields) { $keyfields.=$_->[0].','; }
                   3973: 	    chop($keyfields);
                   3974: 	} else {
                   3975: 	    unshift(@fields,['none','']);
                   3976: 	    $i=&Apache::loncommon::csv_samples_select_table($request,\@records,
                   3977: 							    \@fields);
1.311     banghart 3978:             foreach my $rec (@records) {
                   3979:                 my %temp = &Apache::loncommon::record_sep($rec);
                   3980:                 if (%temp) {
                   3981:                     $keyfields=join(',',sort(keys(%temp)));
                   3982:                     last;
                   3983:                 }
                   3984:             }
1.41      ng       3985: 	}
                   3986:     }
                   3987:     &csvuploadmap_footer($request,$i,$keyfields);
1.324     albertel 3988:     $request->print(&show_grading_menu_form($symb));
1.72      ng       3989: 
1.41      ng       3990:     return '';
1.27      albertel 3991: }
                   3992: 
1.246     albertel 3993: sub csvuploadoptions {
1.608     www      3994:     my ($request,$symb)= @_;
1.257     albertel 3995:     my $checked=(($env{'form.noFirstLine'})?'1':'0');
1.246     albertel 3996:     my $ignore=&mt('Ignore First Line');
                   3997:     $request->print(<<ENDPICK);
                   3998: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="gradesupload">
1.398     albertel 3999: <h3><span class="LC_info">Uploading Class Grade Options</span></h3>
1.246     albertel 4000: <input type="hidden" name="command"    value="csvuploadassign" />
1.302     albertel 4001: <!--
1.246     albertel 4002: <p>
                   4003: <label>
                   4004:    <input type="checkbox" name="show_full_results" />
                   4005:    Show a table of all changes
                   4006: </label>
                   4007: </p>
1.302     albertel 4008: -->
1.246     albertel 4009: <p>
                   4010: <label>
                   4011:    <input type="checkbox" name="overwite_scores" checked="checked" />
                   4012:    Overwrite any existing score
                   4013: </label>
                   4014: </p>
                   4015: ENDPICK
                   4016:     my %fields=&get_fields();
                   4017:     if (!defined($fields{'domain'})) {
1.257     albertel 4018: 	my $domform = &Apache::loncommon::select_dom_form($env{'request.role.domain'},'default_domain');
1.246     albertel 4019: 	$request->print("\n<p> Users are in domain: ".$domform."</p>\n");
                   4020:     }
1.257     albertel 4021:     foreach my $key (sort(keys(%env))) {
1.246     albertel 4022: 	if ($key !~ /^form\.(.*)$/) { next; }
                   4023: 	my $cleankey=$1;
                   4024: 	if ($cleankey eq 'command') { next; }
                   4025: 	$request->print('<input type="hidden" name="'.$cleankey.
1.257     albertel 4026: 			'"  value="'.$env{$key}.'" />'."\n");
1.246     albertel 4027:     }
                   4028:     # FIXME do a check for any duplicated user ids...
                   4029:     # FIXME do a check for any invalid user ids?...
1.290     albertel 4030:     $request->print('<input type="submit" value="Assign Grades" /><br />
                   4031: <hr /></form>'."\n");
1.324     albertel 4032:     $request->print(&show_grading_menu_form($symb));
1.246     albertel 4033:     return '';
                   4034: }
                   4035: 
                   4036: sub get_fields {
                   4037:     my %fields;
1.257     albertel 4038:     my @keyfields = split(/\,/,$env{'form.keyfields'});
                   4039:     for (my $i=0; $i<=$env{'form.nfields'}; $i++) {
                   4040: 	if ($env{'form.upfile_associate'} eq 'reverse') {
                   4041: 	    if ($env{'form.f'.$i} ne 'none') {
                   4042: 		$fields{$keyfields[$i]}=$env{'form.f'.$i};
1.41      ng       4043: 	    }
                   4044: 	} else {
1.257     albertel 4045: 	    if ($env{'form.f'.$i} ne 'none') {
                   4046: 		$fields{$env{'form.f'.$i}}=$keyfields[$i];
1.41      ng       4047: 	    }
                   4048: 	}
1.27      albertel 4049:     }
1.246     albertel 4050:     return %fields;
                   4051: }
                   4052: 
                   4053: sub csvuploadassign {
1.608     www      4054:     my ($request,$symb)= @_;
1.246     albertel 4055:     if (!$symb) {return '';}
1.345     bowersj2 4056:     my $error_msg = '';
1.246     albertel 4057:     &Apache::loncommon::load_tmp_file($request);
                   4058:     my @gradedata = &Apache::loncommon::upfile_record_sep();
1.257     albertel 4059:     if ($env{'form.noFirstLine'}) { shift(@gradedata); }
1.246     albertel 4060:     my %fields=&get_fields();
1.41      ng       4061:     $request->print('<h3>Assigning Grades</h3>');
1.257     albertel 4062:     my $courseid=$env{'request.course.id'};
1.97      albertel 4063:     my ($classlist) = &getclasslist('all',0);
1.106     albertel 4064:     my @notallowed;
1.41      ng       4065:     my @skipped;
                   4066:     my $countdone=0;
                   4067:     foreach my $grade (@gradedata) {
                   4068: 	my %entries=&Apache::loncommon::record_sep($grade);
1.246     albertel 4069: 	my $domain;
                   4070: 	if ($entries{$fields{'domain'}}) {
                   4071: 	    $domain=$entries{$fields{'domain'}};
                   4072: 	} else {
1.257     albertel 4073: 	    $domain=$env{'form.default_domain'};
1.246     albertel 4074: 	}
1.243     albertel 4075: 	$domain=~s/\s//g;
1.41      ng       4076: 	my $username=$entries{$fields{'username'}};
1.160     albertel 4077: 	$username=~s/\s//g;
1.243     albertel 4078: 	if (!$username) {
                   4079: 	    my $id=$entries{$fields{'ID'}};
1.247     albertel 4080: 	    $id=~s/\s//g;
1.243     albertel 4081: 	    my %ids=&Apache::lonnet::idget($domain,$id);
                   4082: 	    $username=$ids{$id};
                   4083: 	}
1.41      ng       4084: 	if (!exists($$classlist{"$username:$domain"})) {
1.247     albertel 4085: 	    my $id=$entries{$fields{'ID'}};
                   4086: 	    $id=~s/\s//g;
                   4087: 	    if ($id) {
                   4088: 		push(@skipped,"$id:$domain");
                   4089: 	    } else {
                   4090: 		push(@skipped,"$username:$domain");
                   4091: 	    }
1.41      ng       4092: 	    next;
                   4093: 	}
1.108     albertel 4094: 	my $usec=$classlist->{"$username:$domain"}[5];
1.106     albertel 4095: 	if (!&canmodify($usec)) {
                   4096: 	    push(@notallowed,"$username:$domain");
                   4097: 	    next;
                   4098: 	}
1.244     albertel 4099: 	my %points;
1.41      ng       4100: 	my %grades;
                   4101: 	foreach my $dest (keys(%fields)) {
1.244     albertel 4102: 	    if ($dest eq 'ID' || $dest eq 'username' ||
                   4103: 		$dest eq 'domain') { next; }
                   4104: 	    if ($entries{$fields{$dest}} =~ /^\s*$/) { next; }
                   4105: 	    if ($dest=~/stores_(.*)_points/) {
                   4106: 		my $part=$1;
                   4107: 		my $wgt =&Apache::lonnet::EXT('resource.'.$part.'.weight',
                   4108: 					      $symb,$domain,$username);
1.345     bowersj2 4109:                 if ($wgt) {
                   4110:                     $entries{$fields{$dest}}=~s/\s//g;
                   4111:                     my $pcr=$entries{$fields{$dest}} / $wgt;
1.463     albertel 4112:                     my $award=($pcr == 0) ? 'incorrect_by_override'
                   4113:                                           : 'correct_by_override';
1.345     bowersj2 4114:                     $grades{"resource.$part.awarded"}=$pcr;
                   4115:                     $grades{"resource.$part.solved"}=$award;
                   4116:                     $points{$part}=1;
                   4117:                 } else {
                   4118:                     $error_msg = "<br />" .
                   4119:                         &mt("Some point values were assigned"
                   4120:                             ." for problems with a weight "
                   4121:                             ."of zero. These values were "
                   4122:                             ."ignored.");
                   4123:                 }
1.244     albertel 4124: 	    } else {
                   4125: 		if ($dest=~/stores_(.*)_awarded/) { if ($points{$1}) {next;} }
                   4126: 		if ($dest=~/stores_(.*)_solved/)  { if ($points{$1}) {next;} }
                   4127: 		my $store_key=$dest;
                   4128: 		$store_key=~s/^stores/resource/;
                   4129: 		$store_key=~s/_/\./g;
                   4130: 		$grades{$store_key}=$entries{$fields{$dest}};
                   4131: 	    }
1.41      ng       4132: 	}
1.508     www      4133: 	if (! %grades) { 
                   4134:            push(@skipped,&mt("[_1]: no data to save","$username:$domain")); 
                   4135:         } else {
                   4136: 	   $grades{"resource.regrader"}="$env{'user.name'}:$env{'user.domain'}";
                   4137: 	   my $result=&Apache::lonnet::cstore(\%grades,$symb,
1.302     albertel 4138: 					   $env{'request.course.id'},
                   4139: 					   $domain,$username);
1.508     www      4140: 	   if ($result eq 'ok') {
                   4141: 	      $request->print('.');
                   4142: 	   } else {
                   4143: 	      $request->print("<p><span class=\"LC_error\">".
                   4144:                               &mt("Failed to save data for student [_1]. Message when trying to save was: [_2]",
                   4145:                                   "$username:$domain",$result)."</span></p>");
                   4146: 	   }
                   4147: 	   $request->rflush();
                   4148: 	   $countdone++;
                   4149:         }
1.41      ng       4150:     }
1.570     www      4151:     $request->print('<br />'.&Apache::lonhtmlcommon::confirm_success(&mt("Saved scores for [quant,_1,student]",$countdone),$countdone==0));
1.41      ng       4152:     if (@skipped) {
1.571     www      4153: 	$request->print('<br />'.&Apache::lonhtmlcommon::confirm_success(&mt('No scores stored for the following username(s):'),1).'<br />');
                   4154:         $request->print(join(', ',@skipped));
1.106     albertel 4155:     }
                   4156:     if (@notallowed) {
1.571     www      4157: 	$request->print('<br />'.&Apache::lonhtmlcommon::confirm_success(&mt('Modification of scores not allowed for the following username(s):'),1).'<br />');
                   4158: 	$request->print(join(', ',@notallowed));
1.41      ng       4159:     }
1.106     albertel 4160:     $request->print("<br />\n");
1.324     albertel 4161:     $request->print(&show_grading_menu_form($symb));
1.345     bowersj2 4162:     return $error_msg;
1.26      albertel 4163: }
1.44      ng       4164: #------------- end of section for handling csv file upload ---------
                   4165: #
                   4166: #-------------------------------------------------------------------
                   4167: #
1.122     ng       4168: #-------------- Next few routines handle grading by page/sequence
1.72      ng       4169: #
                   4170: #--- Select a page/sequence and a student to grade
1.68      ng       4171: sub pickStudentPage {
1.608     www      4172:     my ($request,$symb) = @_;
1.68      ng       4173: 
1.539     riegler  4174:     my $alertmsg = &mt('Please select the student you wish to grade.');
1.597     wenzelju 4175:     $request->print(&Apache::lonhtmlcommon::scripttag(<<LISTJAVASCRIPT));
1.68      ng       4176: 
                   4177: function checkPickOne(formname) {
1.76      ng       4178:     if (radioSelection(formname.student) == null) {
1.539     riegler  4179: 	alert("$alertmsg");
1.68      ng       4180: 	return;
                   4181:     }
1.125     ng       4182:     ptr = pullDownSelection(formname.selectpage);
                   4183:     formname.page.value = formname["page"+ptr].value;
                   4184:     formname.title.value = formname["title"+ptr].value;
1.68      ng       4185:     formname.submit();
                   4186: }
                   4187: 
                   4188: LISTJAVASCRIPT
1.118     ng       4189:     &commonJSfunctions($request);
1.608     www      4190: 
1.257     albertel 4191:     my $cdom      = $env{"course.$env{'request.course.id'}.domain"};
                   4192:     my $cnum      = $env{"course.$env{'request.course.id'}.num"};
                   4193:     my $getsec    = $env{'form.section'} eq '' ? 'all' : $env{'form.section'};
1.68      ng       4194: 
1.398     albertel 4195:     my $result='<h3><span class="LC_info">&nbsp;'.
1.485     albertel 4196: 	&mt('Manual Grading by Page or Sequence').'</span></h3>';
1.68      ng       4197: 
1.80      ng       4198:     $result.='<form action="/adm/grades" method="post" name="displayPage">'."\n";
1.582     raeburn  4199:     my $map_error;
                   4200:     my ($titles,$symbx) = &getSymbMap($map_error);
                   4201:     if ($map_error) {
                   4202:         $request->print(&navmap_errormsg());
                   4203:         return; 
                   4204:     }
1.137     albertel 4205:     my ($curpage) =&Apache::lonnet::decode_symb($symb); 
                   4206: #    my ($curpage,$mapId) =&Apache::lonnet::decode_symb($symb); 
                   4207: #    my $type=($curpage =~ /\.(page|sequence)/);
1.485     albertel 4208:     my $select = '<select name="selectpage">'."\n";
1.70      ng       4209:     my $ctr=0;
1.68      ng       4210:     foreach (@$titles) {
                   4211: 	my ($minder,$showtitle) = ($_ =~ /(\d+)\.(.*)/);
1.485     albertel 4212: 	$select.='<option value="'.$ctr.'" '.
1.401     albertel 4213: 	    ($$symbx{$_} =~ /$curpage$/ ? 'selected="selected"' : '').
1.71      ng       4214: 	    '>'.$showtitle.'</option>'."\n";
1.70      ng       4215: 	$ctr++;
1.68      ng       4216:     }
1.485     albertel 4217:     $select.= '</select>';
1.539     riegler  4218:     $result.='&nbsp;<b>'.&mt('Problems from').':</b> '.$select."<br />\n";
1.485     albertel 4219: 
1.70      ng       4220:     $ctr=0;
                   4221:     foreach (@$titles) {
                   4222: 	my ($minder,$showtitle) = ($_ =~ /(\d+)\.(.*)/);
                   4223: 	$result.='<input type="hidden" name="page'.$ctr.'" value="'.$$symbx{$_}.'" />'."\n";
                   4224: 	$result.='<input type="hidden" name="title'.$ctr.'" value="'.$showtitle.'" />'."\n";
                   4225: 	$ctr++;
                   4226:     }
1.72      ng       4227:     $result.='<input type="hidden" name="page" />'."\n".
                   4228: 	'<input type="hidden" name="title" />'."\n";
1.68      ng       4229: 
1.485     albertel 4230:     my $options =
                   4231: 	'<label><input type="radio" name="vProb" value="no" checked="checked" /> '.&mt('no').' </label>'."\n".
                   4232: 	'<label><input type="radio" name="vProb" value="yes" /> '.&mt('yes').' </label>'."<br />\n";
1.539     riegler  4233:     $result.='&nbsp;<b>'.&mt('View Problem Text').': </b>'.$options;
1.485     albertel 4234: 
                   4235:     $options =
                   4236: 	'<label><input type="radio" name="lastSub" value="none" /> '.&mt('none').' </label>'."\n".
                   4237: 	'<label><input type="radio" name="lastSub" value="datesub" checked="checked" /> '.&mt('by dates and submissions').'</label>'."\n".
                   4238: 	'<label><input type="radio" name="lastSub" value="all" /> '.&mt('all details').' </label>'."\n";
1.539     riegler  4239:     $result.='&nbsp;<b>'.&mt('Submissions').': </b>'.$options;
1.432     banghart 4240:     
                   4241:     $result.=&build_section_inputs();
1.442     banghart 4242:     my $stu_status = join(':',&Apache::loncommon::get_env_multiple('form.Status'));
                   4243:     $result.='<input type="hidden" name="Status"  value="'.$stu_status.'" />'."\n".
1.72      ng       4244: 	'<input type="hidden" name="command" value="displayPage" />'."\n".
1.613   ! www      4245: 	'<input type="hidden" name="symb"    value="'.&Apache::lonenc::check_encrypt($symb).'" />'."<br />\n";
1.72      ng       4246: 
1.539     riegler  4247:     $result.='&nbsp;<b>'.&mt('Use CODE').': </b> <input type="text" name="CODE" value="" /> <br />'."\n";
1.382     albertel 4248: 
1.80      ng       4249:     $result.='&nbsp;<input type="button" '.
1.589     bisitz   4250:              'onclick="javascript:checkPickOne(this.form);" value="'.&mt('Next').' &rarr;" /><br />'."\n";
1.72      ng       4251: 
1.68      ng       4252:     $request->print($result);
                   4253: 
1.485     albertel 4254:     my $studentTable.='&nbsp;<b>'.&mt('Select a student you wish to grade and then click on the Next button.').'</b><br />'.
1.484     albertel 4255: 	&Apache::loncommon::start_data_table().
                   4256: 	&Apache::loncommon::start_data_table_header_row().
1.485     albertel 4257: 	'<th align="right">&nbsp;'.&mt('No.').'</th>'.
1.484     albertel 4258: 	'<th>'.&nameUserString('header').'</th>'.
1.485     albertel 4259: 	'<th align="right">&nbsp;'.&mt('No.').'</th>'.
1.484     albertel 4260: 	'<th>'.&nameUserString('header').'</th>'.
                   4261: 	&Apache::loncommon::end_data_table_header_row();
1.68      ng       4262:  
1.76      ng       4263:     my (undef,undef,$fullname) = &getclasslist($getsec,'1');
1.68      ng       4264:     my $ptr = 1;
1.294     albertel 4265:     foreach my $student (sort 
                   4266: 			 {
                   4267: 			     if (lc($$fullname{$a}) ne lc($$fullname{$b})) {
                   4268: 				 return (lc($$fullname{$a}) cmp lc($$fullname{$b}));
                   4269: 			     }
                   4270: 			     return $a cmp $b;
                   4271: 			 } (keys(%$fullname))) {
1.68      ng       4272: 	my ($uname,$udom) = split(/:/,$student);
1.484     albertel 4273: 	$studentTable.=($ptr%2==1 ? &Apache::loncommon::start_data_table_row()
                   4274:                                   : '</td>');
1.126     ng       4275: 	$studentTable.='<td align="right">'.$ptr.'&nbsp;</td>';
1.288     albertel 4276: 	$studentTable.='<td>&nbsp;<label><input type="radio" name="student" value="'.$student.'" /> '
                   4277: 	    .&nameUserString(undef,$$fullname{$student},$uname,$udom)."</label>\n";
1.484     albertel 4278: 	$studentTable.=
                   4279: 	    ($ptr%2 == 0 ? '</td>'.&Apache::loncommon::end_data_table_row() 
                   4280:                          : '');
1.68      ng       4281: 	$ptr++;
                   4282:     }
1.484     albertel 4283:     if ($ptr%2 == 0) {
                   4284: 	$studentTable.='</td><td>&nbsp;</td><td>&nbsp;</td>'.
                   4285: 	    &Apache::loncommon::end_data_table_row();
                   4286:     }
                   4287:     $studentTable.=&Apache::loncommon::end_data_table()."\n";
1.126     ng       4288:     $studentTable.='<input type="button" '.
1.589     bisitz   4289:                    'onclick="javascript:checkPickOne(this.form);" value="'.&mt('Next').' &rarr;" /></form>'."\n";
1.68      ng       4290: 
1.324     albertel 4291:     $studentTable.=&show_grading_menu_form($symb);
1.68      ng       4292:     $request->print($studentTable);
                   4293: 
                   4294:     return '';
                   4295: }
                   4296: 
                   4297: sub getSymbMap {
1.582     raeburn  4298:     my ($map_error) = @_;
1.132     bowersj2 4299:     my $navmap = Apache::lonnavmaps::navmap->new();
1.582     raeburn  4300:     unless (ref($navmap)) {
                   4301:         if (ref($map_error)) {
                   4302:             $$map_error = 'navmap';
                   4303:         }
                   4304:         return;
                   4305:     }
1.68      ng       4306:     my %symbx = ();
                   4307:     my @titles = ();
1.117     bowersj2 4308:     my $minder = 0;
                   4309: 
                   4310:     # Gather every sequence that has problems.
1.240     albertel 4311:     my @sequences = $navmap->retrieveResources(undef, sub { shift->is_map(); },
                   4312: 					       1,0,1);
1.117     bowersj2 4313:     for my $sequence ($navmap->getById('0.0'), @sequences) {
1.241     albertel 4314: 	if ($navmap->hasResource($sequence, sub { shift->is_problem(); }, 0) ) {
1.381     albertel 4315: 	    my $title = $minder.'.'.
                   4316: 		&HTML::Entities::encode($sequence->compTitle(),'"\'&');
                   4317: 	    push(@titles, $title); # minder in case two titles are identical
                   4318: 	    $symbx{$title} = &HTML::Entities::encode($sequence->symb(),'"\'&');
1.117     bowersj2 4319: 	    $minder++;
1.241     albertel 4320: 	}
1.68      ng       4321:     }
                   4322:     return \@titles,\%symbx;
                   4323: }
                   4324: 
1.72      ng       4325: #
                   4326: #--- Displays a page/sequence w/wo problems, w/wo submissions
1.68      ng       4327: sub displayPage {
1.608     www      4328:     my ($request,$symb) = @_;
1.257     albertel 4329:     my $cdom      = $env{"course.$env{'request.course.id'}.domain"};
                   4330:     my $cnum      = $env{"course.$env{'request.course.id'}.num"};
                   4331:     my $getsec    = $env{'form.section'} eq '' ? 'all' : $env{'form.section'};
                   4332:     my $pageTitle = $env{'form.page'};
1.103     albertel 4333:     my ($classlist,undef,$fullname) = &getclasslist($getsec,'1');
1.257     albertel 4334:     my ($uname,$udom) = split(/:/,$env{'form.student'});
                   4335:     my $usec=$classlist->{$env{'form.student'}}[5];
1.168     albertel 4336: 
                   4337:     #need to make sure we have the correct data for later EXT calls, 
                   4338:     #thus invalidate the cache
                   4339:     &Apache::lonnet::devalidatecourseresdata(
1.257     albertel 4340:                  $env{'course.'.$env{'request.course.id'}.'.num'},
                   4341:                  $env{'course.'.$env{'request.course.id'}.'.domain'});
1.168     albertel 4342:     &Apache::lonnet::clear_EXT_cache_status();
                   4343: 
1.103     albertel 4344:     if (!&canview($usec)) {
1.485     albertel 4345: 	$request->print('<span class="LC_warning">'.&mt('Unable to view requested student. ([_1])',$env{'form.student'}).'</span>');
1.324     albertel 4346: 	$request->print(&show_grading_menu_form($symb));
1.103     albertel 4347: 	return;
                   4348:     }
1.398     albertel 4349:     my $result='<h3><span class="LC_info">&nbsp;'.$env{'form.title'}.'</span></h3>';
1.485     albertel 4350:     $result.='<h3>&nbsp;'.&mt('Student: [_1]',&nameUserString(undef,$$fullname{$env{'form.student'}},$uname,$udom)).
1.129     ng       4351: 	'</h3>'."\n";
1.500     albertel 4352:     $env{'form.CODE'} = uc($env{'form.CODE'});
1.501     foxr     4353:     if (&Apache::lonnet::validCODE(uc($env{'form.CODE'}))) {
1.485     albertel 4354: 	$result.='<h3>&nbsp;'.&mt('CODE: [_1]',$env{'form.CODE'}).'</h3>'."\n";
1.382     albertel 4355:     } else {
                   4356: 	delete($env{'form.CODE'});
                   4357:     }
1.71      ng       4358:     &sub_page_js($request);
                   4359:     $request->print($result);
                   4360: 
1.132     bowersj2 4361:     my $navmap = Apache::lonnavmaps::navmap->new();
1.582     raeburn  4362:     unless (ref($navmap)) {
                   4363:         $request->print(&navmap_errormsg());
                   4364:         $request->print(&show_grading_menu_form($symb));
                   4365:         return;
                   4366:     }
1.257     albertel 4367:     my ($mapUrl, $id, $resUrl)=&Apache::lonnet::decode_symb($env{'form.page'});
1.68      ng       4368:     my $map = $navmap->getResourceByUrl($resUrl); # add to navmaps
1.288     albertel 4369:     if (!$map) {
1.485     albertel 4370: 	$request->print('<span class="LC_warning">'.&mt('Unable to view requested sequence. ([_1])',$resUrl).'</span>');
1.324     albertel 4371: 	$request->print(&show_grading_menu_form($symb));
1.288     albertel 4372: 	return; 
                   4373:     }
1.68      ng       4374:     my $iterator = $navmap->getIterator($map->map_start(),
                   4375: 					$map->map_finish());
                   4376: 
1.71      ng       4377:     my $studentTable='<form action="/adm/grades" method="post" name="gradePage">'."\n".
1.72      ng       4378: 	'<input type="hidden" name="command" value="gradeByPage" />'."\n".
1.257     albertel 4379: 	'<input type="hidden" name="fullname" value="'.$$fullname{$env{'form.student'}}.'" />'."\n".
                   4380: 	'<input type="hidden" name="student" value="'.$env{'form.student'}.'" />'."\n".
1.72      ng       4381: 	'<input type="hidden" name="page"    value="'.$pageTitle.'" />'."\n".
1.257     albertel 4382: 	'<input type="hidden" name="title"   value="'.$env{'form.title'}.'" />'."\n".
1.418     albertel 4383: 	'<input type="hidden" name="symb"    value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
1.613   ! www      4384: 	'<input type="hidden" name="overRideScore" value="no" />'."\n";
1.71      ng       4385: 
1.382     albertel 4386:     if (defined($env{'form.CODE'})) {
                   4387: 	$studentTable.=
                   4388: 	    '<input type="hidden" name="CODE" value="'.$env{'form.CODE'}.'" />'."\n";
                   4389:     }
1.381     albertel 4390:     my $checkIcon = '<img alt="'.&mt('Check Mark').
1.485     albertel 4391: 	'" src="'.&Apache::loncommon::lonhttpdurl($request->dir_config('lonIconsURL').'/check.gif').'" height="16" border="0" />';
1.71      ng       4392: 
1.594     bisitz   4393:     $studentTable.='&nbsp;<span class="LC_info">'.
                   4394:         &mt('Problems graded correct by the computer are marked with a [_1] symbol.',$checkIcon).
                   4395:         '</span>'."\n".
1.484     albertel 4396: 	&Apache::loncommon::start_data_table().
                   4397: 	&Apache::loncommon::start_data_table_header_row().
                   4398: 	'<th align="center">&nbsp;Prob.&nbsp;</th>'.
1.485     albertel 4399: 	'<th>&nbsp;'.($env{'form.vProb'} eq 'no' ? &mt('Title') : &mt('Problem Text')).'/'.&mt('Grade').'</th>'.
1.484     albertel 4400: 	&Apache::loncommon::end_data_table_header_row();
1.71      ng       4401: 
1.329     albertel 4402:     &Apache::lonxml::clear_problem_counter();
1.196     albertel 4403:     my ($depth,$question,$prob) = (1,1,1);
1.68      ng       4404:     $iterator->next(); # skip the first BEGIN_MAP
                   4405:     my $curRes = $iterator->next(); # for "current resource"
1.101     albertel 4406:     while ($depth > 0) {
1.68      ng       4407:         if($curRes == $iterator->BEGIN_MAP) { $depth++; }
1.100     bowersj2 4408:         if($curRes == $iterator->END_MAP) { $depth--; }
1.68      ng       4409: 
1.385     albertel 4410:         if (ref($curRes) && $curRes->is_problem()) {
1.91      albertel 4411: 	    my $parts = $curRes->parts();
1.68      ng       4412:             my $title = $curRes->compTitle();
1.71      ng       4413: 	    my $symbx = $curRes->symb();
1.484     albertel 4414: 	    $studentTable.=
                   4415: 		&Apache::loncommon::start_data_table_row().
                   4416: 		'<td align="center" valign="top" >'.$prob.
1.485     albertel 4417: 		(scalar(@{$parts}) == 1 ? '' 
                   4418: 		                        : '<br />('.&mt('[_1]&nbsp;parts)',
                   4419: 							scalar(@{$parts}))
                   4420: 		 ).
                   4421: 		 '</td>';
1.71      ng       4422: 	    $studentTable.='<td valign="top">';
1.382     albertel 4423: 	    my %form = ('CODE' => $env{'form.CODE'},);
1.257     albertel 4424: 	    if ($env{'form.vProb'} eq 'yes' ) {
1.144     albertel 4425: 		$studentTable.=&show_problem($request,$symbx,$uname,$udom,1,
1.383     albertel 4426: 					     undef,'both',\%form);
1.71      ng       4427: 	    } else {
1.382     albertel 4428: 		my $companswer = &Apache::loncommon::get_student_answers($symbx,$uname,$udom,$env{'request.course.id'},%form);
1.80      ng       4429: 		$companswer =~ s|<form(.*?)>||g;
                   4430: 		$companswer =~ s|</form>||g;
1.71      ng       4431: #		while ($companswer =~ /(<a href\=\"javascript:newWindow.*?Script Vars<\/a>)/s) { #<a href="javascript:newWindow</a>
1.116     ng       4432: #		    $companswer =~ s/$1/ /ms;
1.326     albertel 4433: #		    $request->print('match='.$1."<br />\n");
1.71      ng       4434: #		}
1.116     ng       4435: #		$companswer =~ s|<table border=\"1\">|<table border=\"0\">|g;
1.539     riegler  4436: 		$studentTable.='&nbsp;<b>'.$title.'</b>&nbsp;<br />&nbsp;<b>'.&mt('Correct answer').':</b><br />'.$companswer;
1.71      ng       4437: 	    }
                   4438: 
1.257     albertel 4439: 	    my %record = &Apache::lonnet::restore($symbx,$env{'request.course.id'},$udom,$uname);
1.125     ng       4440: 
1.257     albertel 4441: 	    if ($env{'form.lastSub'} eq 'datesub') {
1.71      ng       4442: 		if ($record{'version'} eq '') {
1.485     albertel 4443: 		    $studentTable.='<br />&nbsp;<span class="LC_warning">'.&mt('No recorded submission for this problem.').'</span><br />';
1.71      ng       4444: 		} else {
1.116     ng       4445: 		    my %responseType = ();
                   4446: 		    foreach my $partid (@{$parts}) {
1.147     albertel 4447: 			my @responseIds =$curRes->responseIds($partid);
                   4448: 			my @responseType =$curRes->responseType($partid);
                   4449: 			my %responseIds;
                   4450: 			for (my $i=0;$i<=$#responseIds;$i++) {
                   4451: 			    $responseIds{$responseIds[$i]}=$responseType[$i];
                   4452: 			}
                   4453: 			$responseType{$partid} = \%responseIds;
1.116     ng       4454: 		    }
1.148     albertel 4455: 		    $studentTable.= &displaySubByDates($symbx,\%record,$parts,\%responseType,$checkIcon,$uname,$udom);
1.147     albertel 4456: 
1.71      ng       4457: 		}
1.257     albertel 4458: 	    } elsif ($env{'form.lastSub'} eq 'all') {
                   4459: 		my $last = ($env{'form.lastSub'} eq 'last' ? 'last' : '');
1.71      ng       4460: 		$studentTable.=&Apache::loncommon::get_previous_attempt($symbx,$uname,$udom,
1.257     albertel 4461: 									$env{'request.course.id'},
1.71      ng       4462: 									'','.submission');
                   4463:  
                   4464: 	    }
1.103     albertel 4465: 	    if (&canmodify($usec)) {
1.585     bisitz   4466:             $studentTable.=&gradeBox_start();
1.103     albertel 4467: 		foreach my $partid (@{$parts}) {
                   4468: 		    $studentTable.=&gradeBox($request,$symbx,$uname,$udom,$question,$partid,\%record);
                   4469: 		    $studentTable.='<input type="hidden" name="q_'.$question.'" value="'.$partid.'" />'."\n";
                   4470: 		    $question++;
                   4471: 		}
1.585     bisitz   4472:             $studentTable.=&gradeBox_end();
1.196     albertel 4473: 		$prob++;
1.71      ng       4474: 	    }
                   4475: 	    $studentTable.='</td></tr>';
1.68      ng       4476: 
1.103     albertel 4477: 	}
1.68      ng       4478:         $curRes = $iterator->next();
                   4479:     }
                   4480: 
1.589     bisitz   4481:     $studentTable.=
                   4482:         '</table>'."\n".
                   4483:         '<input type="button" value="'.&mt('Save').'" '.
                   4484:         'onclick="javascript:checkSubmitPage(this.form,'.$question.');" />'.
                   4485:         '</form>'."\n";
1.324     albertel 4486:     $studentTable.=&show_grading_menu_form($symb);
1.71      ng       4487:     $request->print($studentTable);
                   4488: 
                   4489:     return '';
1.119     ng       4490: }
                   4491: 
                   4492: sub displaySubByDates {
1.148     albertel 4493:     my ($symb,$record,$parts,$responseType,$checkIcon,$uname,$udom) = @_;
1.224     albertel 4494:     my $isCODE=0;
1.335     albertel 4495:     my $isTask = ($symb =~/\.task$/);
1.224     albertel 4496:     if (exists($record->{'resource.CODE'})) { $isCODE=1; }
1.467     albertel 4497:     my $studentTable=&Apache::loncommon::start_data_table().
                   4498: 	&Apache::loncommon::start_data_table_header_row().
                   4499: 	'<th>'.&mt('Date/Time').'</th>'.
                   4500: 	($isCODE?'<th>'.&mt('CODE').'</th>':'').
                   4501: 	'<th>'.&mt('Submission').'</th>'.
                   4502: 	'<th>'.&mt('Status').'</th>'.
                   4503: 	&Apache::loncommon::end_data_table_header_row();
1.119     ng       4504:     my ($version);
                   4505:     my %mark;
1.148     albertel 4506:     my %orders;
1.119     ng       4507:     $mark{'correct_by_student'} = $checkIcon;
1.147     albertel 4508:     if (!exists($$record{'1:timestamp'})) {
1.539     riegler  4509: 	return '<br />&nbsp;<span class="LC_warning">'.&mt('Nothing submitted - no attempts.').'</span><br />';
1.147     albertel 4510:     }
1.335     albertel 4511: 
                   4512:     my $interaction;
1.525     raeburn  4513:     my $no_increment = 1;
1.119     ng       4514:     for ($version=1;$version<=$$record{'version'};$version++) {
1.467     albertel 4515: 	my $timestamp = 
                   4516: 	    &Apache::lonlocal::locallocaltime($$record{$version.':timestamp'});
1.335     albertel 4517: 	if (exists($$record{$version.':resource.0.version'})) {
                   4518: 	    $interaction = $$record{$version.':resource.0.version'};
                   4519: 	}
                   4520: 
                   4521: 	my $where = ($isTask ? "$version:resource.$interaction"
                   4522: 		             : "$version:resource");
1.467     albertel 4523: 	$studentTable.=&Apache::loncommon::start_data_table_row().
                   4524: 	    '<td>'.$timestamp.'</td>';
1.224     albertel 4525: 	if ($isCODE) {
                   4526: 	    $studentTable.='<td>'.$record->{$version.':resource.CODE'}.'</td>';
                   4527: 	}
1.119     ng       4528: 	my @versionKeys = split(/\:/,$$record{$version.':keys'});
                   4529: 	my @displaySub = ();
                   4530: 	foreach my $partid (@{$parts}) {
1.596     raeburn  4531:             my $hidden;
                   4532:             if (($$record{$version.':resource.'.$partid.'.type'} eq 'anonsurvey') ||
                   4533:                 ($$record{$version.':resource.'.$partid.'.type'} eq 'anonsurveycred')) {
                   4534:                 $hidden = 1;
                   4535:             }
1.335     albertel 4536: 	    my @matchKey = ($isTask ? sort(grep /^resource\.\d+\.\Q$partid\E\.award$/,@versionKeys)
                   4537: 			            : sort(grep /^resource\.\Q$partid\E\..*?\.submission$/,@versionKeys));
                   4538: 	    
1.122     ng       4539: #	    next if ($$record{"$version:resource.$partid.solved"} eq '');
1.324     albertel 4540: 	    my $display_part=&get_display_part($partid,$symb);
1.147     albertel 4541: 	    foreach my $matchKey (@matchKey) {
1.198     albertel 4542: 		if (exists($$record{$version.':'.$matchKey}) &&
                   4543: 		    $$record{$version.':'.$matchKey} ne '') {
1.596     raeburn  4544:                     
1.335     albertel 4545: 		    my ($responseId)= ($isTask ? ($matchKey=~ /^resource\.(.*?)\.\Q$partid\E\.award$/)
                   4546: 				               : ($matchKey=~ /^resource\.\Q$partid\E\.(.*?)\.submission$/));
1.577     bisitz   4547:                     $displaySub[0].='<span class="LC_nobreak"';
                   4548:                     $displaySub[0].='<b>'.&mt('Part: [_1]',$display_part).'</b>'
                   4549:                                    .' <span class="LC_internal_info">'
                   4550:                                    .'('.&mt('Part ID: [_1]',$responseId).')'
                   4551:                                    .'</span>'
                   4552:                                    .' <b>';
1.596     raeburn  4553:                     if ($hidden) {
                   4554:                         $displaySub[0].= &mt('Anonymous Survey').'</b>';
                   4555:                     } else {
                   4556: 		        if ($$record{"$where.$partid.tries"} eq '') {
                   4557: 			    $displaySub[0].=&mt('Trial not counted');
                   4558: 		        } else {
                   4559: 			    $displaySub[0].=&mt('Trial: [_1]',
1.467     albertel 4560: 					    $$record{"$where.$partid.tries"});
1.596     raeburn  4561: 		        }
                   4562: 		        my $responseType=($isTask ? 'Task'
1.335     albertel 4563:                                               : $responseType->{$partid}->{$responseId});
1.596     raeburn  4564: 		        if (!exists($orders{$partid})) { $orders{$partid}={}; }
                   4565: 		        if (!exists($orders{$partid}->{$responseId})) {
                   4566: 			    $orders{$partid}->{$responseId}=
                   4567: 			        &get_order($partid,$responseId,$symb,$uname,$udom,
                   4568:                                            $no_increment);
                   4569: 		        }
                   4570: 		        $displaySub[0].='</b></span>'; # /nobreak
                   4571: 		        $displaySub[0].='&nbsp; '.
                   4572: 			    &cleanRecord($$record{$version.':'.$matchKey},$responseType,$symb,$partid,$responseId,$record,$orders{$partid}->{$responseId},"$version:",$uname,$udom).'<br />';
                   4573:                     }
1.147     albertel 4574: 		}
                   4575: 	    }
1.335     albertel 4576: 	    if (exists($$record{"$where.$partid.checkedin"})) {
1.485     albertel 4577: 		$displaySub[1].=&mt('Checked in by [_1] into slot [_2]',
                   4578: 				    $$record{"$where.$partid.checkedin"},
                   4579: 				    $$record{"$where.$partid.checkedin.slot"}).
                   4580: 					'<br />';
1.335     albertel 4581: 	    }
                   4582: 	    if (exists $$record{"$where.$partid.award"}) {
1.485     albertel 4583: 		$displaySub[1].='<b>'.&mt('Part:').'</b>&nbsp;'.$display_part.' &nbsp;'.
1.335     albertel 4584: 		    lc($$record{"$where.$partid.award"}).' '.
                   4585: 		    $mark{$$record{"$where.$partid.solved"}}.
1.147     albertel 4586: 		    '<br />';
                   4587: 	    }
1.335     albertel 4588: 	    if (exists $$record{"$where.$partid.regrader"}) {
                   4589: 		$displaySub[2].=$$record{"$where.$partid.regrader"}.
                   4590: 		    ' (<b>'.&mt('Part').':</b> '.$display_part.')';
                   4591: 	    } elsif ($$record{"$version:resource.$partid.regrader"} =~ /\S/) {
                   4592: 		$displaySub[2].=
                   4593: 		    $$record{"$version:resource.$partid.regrader"}.
1.207     albertel 4594: 		    ' (<b>'.&mt('Part').':</b> '.$display_part.')';
1.147     albertel 4595: 	    }
                   4596: 	}
                   4597: 	# needed because old essay regrader has not parts info
                   4598: 	if (exists $$record{"$version:resource.regrader"}) {
                   4599: 	    $displaySub[2].=$$record{"$version:resource.regrader"};
                   4600: 	}
                   4601: 	$studentTable.='<td>'.$displaySub[0].'&nbsp;</td><td>'.$displaySub[1];
                   4602: 	if ($displaySub[2]) {
1.467     albertel 4603: 	    $studentTable.=&mt('Manually graded by [_1]',$displaySub[2]);
1.147     albertel 4604: 	}
1.467     albertel 4605: 	$studentTable.='&nbsp;</td>'.
                   4606: 	    &Apache::loncommon::end_data_table_row();
1.119     ng       4607:     }
1.467     albertel 4608:     $studentTable.=&Apache::loncommon::end_data_table();
1.119     ng       4609:     return $studentTable;
1.71      ng       4610: }
                   4611: 
                   4612: sub updateGradeByPage {
1.608     www      4613:     my ($request,$symb) = @_;
1.71      ng       4614: 
1.257     albertel 4615:     my $cdom      = $env{"course.$env{'request.course.id'}.domain"};
                   4616:     my $cnum      = $env{"course.$env{'request.course.id'}.num"};
                   4617:     my $getsec    = $env{'form.section'} eq '' ? 'all' : $env{'form.section'};
                   4618:     my $pageTitle = $env{'form.page'};
1.103     albertel 4619:     my ($classlist,undef,$fullname) = &getclasslist($getsec,'1');
1.257     albertel 4620:     my ($uname,$udom) = split(/:/,$env{'form.student'});
                   4621:     my $usec=$classlist->{$env{'form.student'}}[5];
1.103     albertel 4622:     if (!&canmodify($usec)) {
1.526     raeburn  4623: 	$request->print('<span class="LC_warning">'.&mt('Unable to modify requested student ([_1])',$env{'form.student'}).'</span>');
1.324     albertel 4624: 	$request->print(&show_grading_menu_form($env{'form.symb'}));
1.103     albertel 4625: 	return;
                   4626:     }
1.398     albertel 4627:     my $result='<h3><span class="LC_info">&nbsp;'.$env{'form.title'}.'</span></h3>';
1.526     raeburn  4628:     $result.='<h3>&nbsp;'.&mt('Student: ').&nameUserString(undef,$env{'form.fullname'},$uname,$udom).
1.129     ng       4629: 	'</h3>'."\n";
1.70      ng       4630: 
1.68      ng       4631:     $request->print($result);
                   4632: 
1.582     raeburn  4633: 
1.132     bowersj2 4634:     my $navmap = Apache::lonnavmaps::navmap->new();
1.582     raeburn  4635:     unless (ref($navmap)) {
                   4636:         $request->print(&navmap_errormsg());
                   4637:         return;
                   4638:     }
1.257     albertel 4639:     my ($mapUrl, $id, $resUrl) = &Apache::lonnet::decode_symb( $env{'form.page'});
1.71      ng       4640:     my $map = $navmap->getResourceByUrl($resUrl); # add to navmaps
1.288     albertel 4641:     if (!$map) {
1.527     raeburn  4642: 	$request->print('<span class="LC_warning">'.&mt('Unable to grade requested sequence ([_1]).',$resUrl).'</span>');
1.324     albertel 4643: 	$request->print(&show_grading_menu_form($symb));
1.288     albertel 4644: 	return; 
                   4645:     }
1.71      ng       4646:     my $iterator = $navmap->getIterator($map->map_start(),
                   4647: 					$map->map_finish());
1.70      ng       4648: 
1.484     albertel 4649:     my $studentTable=
                   4650: 	&Apache::loncommon::start_data_table().
                   4651: 	&Apache::loncommon::start_data_table_header_row().
1.485     albertel 4652: 	'<th align="center">&nbsp;'.&mt('Prob.').'&nbsp;</th>'.
                   4653: 	'<th>&nbsp;'.&mt('Title').'&nbsp;</th>'.
                   4654: 	'<th>&nbsp;'.&mt('Previous Score').'&nbsp;</th>'.
                   4655: 	'<th>&nbsp;'.&mt('New Score').'&nbsp;</th>'.
1.484     albertel 4656: 	&Apache::loncommon::end_data_table_header_row();
1.71      ng       4657: 
                   4658:     $iterator->next(); # skip the first BEGIN_MAP
                   4659:     my $curRes = $iterator->next(); # for "current resource"
1.196     albertel 4660:     my ($depth,$question,$prob,$changeflag)= (1,1,1,0);
1.101     albertel 4661:     while ($depth > 0) {
1.71      ng       4662:         if($curRes == $iterator->BEGIN_MAP) { $depth++; }
1.100     bowersj2 4663:         if($curRes == $iterator->END_MAP) { $depth--; }
1.71      ng       4664: 
1.385     albertel 4665:         if (ref($curRes) && $curRes->is_problem()) {
1.91      albertel 4666: 	    my $parts = $curRes->parts();
1.71      ng       4667:             my $title = $curRes->compTitle();
                   4668: 	    my $symbx = $curRes->symb();
1.484     albertel 4669: 	    $studentTable.=
                   4670: 		&Apache::loncommon::start_data_table_row().
                   4671: 		'<td align="center" valign="top" >'.$prob.
1.485     albertel 4672: 		(scalar(@{$parts}) == 1 ? '' 
1.526     raeburn  4673:                                         : '<br />('.&mt('[quant,_1,&nbsp;part]',scalar(@{$parts}))
                   4674: 		.')').'</td>';
1.71      ng       4675: 	    $studentTable.='<td valign="top">&nbsp;<b>'.$title.'</b>&nbsp;</td>';
                   4676: 
                   4677: 	    my %newrecord=();
                   4678: 	    my @displayPts=();
1.269     raeburn  4679:             my %aggregate = ();
                   4680:             my $aggregateflag = 0;
1.71      ng       4681: 	    foreach my $partid (@{$parts}) {
1.257     albertel 4682: 		my $newpts = $env{'form.GD_BOX'.$question.'_'.$partid};
                   4683: 		my $oldpts = $env{'form.oldpts'.$question.'_'.$partid};
1.71      ng       4684: 
1.257     albertel 4685: 		my $wgt = $env{'form.WGT'.$question.'_'.$partid} != 0 ? 
                   4686: 		    $env{'form.WGT'.$question.'_'.$partid} : 1;
1.71      ng       4687: 		my $partial = $newpts/$wgt;
                   4688: 		my $score;
                   4689: 		if ($partial > 0) {
                   4690: 		    $score = 'correct_by_override';
1.125     ng       4691: 		} elsif ($newpts ne '') { #empty is taken as 0
1.71      ng       4692: 		    $score = 'incorrect_by_override';
                   4693: 		}
1.257     albertel 4694: 		my $dropMenu = $env{'form.GD_SEL'.$question.'_'.$partid};
1.125     ng       4695: 		if ($dropMenu eq 'excused') {
1.71      ng       4696: 		    $partial = '';
                   4697: 		    $score = 'excused';
1.125     ng       4698: 		} elsif ($dropMenu eq 'reset status'
1.257     albertel 4699: 			 && $env{'form.solved'.$question.'_'.$partid} ne '') { #update only if previous record exists
1.125     ng       4700: 		    $newrecord{'resource.'.$partid.'.tries'} = 0;
                   4701: 		    $newrecord{'resource.'.$partid.'.solved'} = '';
                   4702: 		    $newrecord{'resource.'.$partid.'.award'} = '';
                   4703: 		    $newrecord{'resource.'.$partid.'.awarded'} = 0;
1.257     albertel 4704: 		    $newrecord{'resource.'.$partid.'.regrader'} = "$env{'user.name'}:$env{'user.domain'}";
1.125     ng       4705: 		    $changeflag++;
                   4706: 		    $newpts = '';
1.269     raeburn  4707:                     
                   4708:                     my $aggtries =  $env{'form.aggtries'.$question.'_'.$partid};
                   4709:                     my $totaltries = $env{'form.totaltries'.$question.'_'.$partid};
                   4710:                     my $solvedstatus = $env{'form.solved'.$question.'_'.$partid};
                   4711:                     if ($aggtries > 0) {
                   4712:                         &decrement_aggs($symbx,$partid,\%aggregate,$aggtries,$totaltries,$solvedstatus);
                   4713:                         $aggregateflag = 1;
                   4714:                     }
1.71      ng       4715: 		}
1.324     albertel 4716: 		my $display_part=&get_display_part($partid,$curRes->symb());
1.257     albertel 4717: 		my $oldstatus = $env{'form.solved'.$question.'_'.$partid};
1.526     raeburn  4718: 		$displayPts[0].='&nbsp;<b>'.&mt('Part').':</b> '.$display_part.' = '.
1.71      ng       4719: 		    (($oldstatus eq 'excused') ? 'excused' : $oldpts).
1.326     albertel 4720: 		    '&nbsp;<br />';
1.526     raeburn  4721: 		$displayPts[1].='&nbsp;<b>'.&mt('Part').':</b> '.$display_part.' = '.
1.125     ng       4722: 		     (($score eq 'excused') ? 'excused' : $newpts).
1.326     albertel 4723: 		    '&nbsp;<br />';
1.71      ng       4724: 		$question++;
1.380     albertel 4725: 		next if ($dropMenu eq 'reset status' || ($newpts eq $oldpts && $score ne 'excused'));
1.125     ng       4726: 
1.71      ng       4727: 		$newrecord{'resource.'.$partid.'.awarded'}  = $partial if $partial ne '';
1.125     ng       4728: 		$newrecord{'resource.'.$partid.'.solved'}   = $score if $score ne '';
1.257     albertel 4729: 		$newrecord{'resource.'.$partid.'.regrader'} = "$env{'user.name'}:$env{'user.domain'}"
1.125     ng       4730: 		    if (scalar(keys(%newrecord)) > 0);
1.71      ng       4731: 
                   4732: 		$changeflag++;
                   4733: 	    }
                   4734: 	    if (scalar(keys(%newrecord)) > 0) {
1.382     albertel 4735: 		my %record = 
                   4736: 		    &Apache::lonnet::restore($symbx,$env{'request.course.id'},
                   4737: 					     $udom,$uname);
                   4738: 
                   4739: 		if (&Apache::lonnet::validCODE($env{'form.CODE'})) {
                   4740: 		    $newrecord{'resource.CODE'} = $env{'form.CODE'};
                   4741: 		} elsif (&Apache::lonnet::validCODE($record{'resource.CODE'})) {
                   4742: 		    $newrecord{'resource.CODE'} = '';
                   4743: 		}
1.257     albertel 4744: 		&Apache::lonnet::cstore(\%newrecord,$symbx,$env{'request.course.id'},
1.71      ng       4745: 					$udom,$uname);
1.382     albertel 4746: 		%record = &Apache::lonnet::restore($symbx,
                   4747: 						   $env{'request.course.id'},
                   4748: 						   $udom,$uname);
1.380     albertel 4749: 		&check_and_remove_from_queue($parts,\%record,undef,$symbx,
                   4750: 					     $cdom,$cnum,$udom,$uname);
1.71      ng       4751: 	    }
1.380     albertel 4752: 	    
1.269     raeburn  4753:             if ($aggregateflag) {
                   4754:                 &Apache::lonnet::cinc('nohist_resourcetracker',\%aggregate,
                   4755:                       $env{'course.'.$env{'request.course.id'}.'.domain'},
                   4756:                       $env{'course.'.$env{'request.course.id'}.'.num'});
                   4757:             }
1.125     ng       4758: 
1.71      ng       4759: 	    $studentTable.='<td valign="top">'.$displayPts[0].'</td>'.
                   4760: 		'<td valign="top">'.$displayPts[1].'</td>'.
1.484     albertel 4761: 		&Apache::loncommon::end_data_table_row();
1.68      ng       4762: 
1.196     albertel 4763: 	    $prob++;
1.68      ng       4764: 	}
1.71      ng       4765:         $curRes = $iterator->next();
1.68      ng       4766:     }
1.98      albertel 4767: 
1.484     albertel 4768:     $studentTable.=&Apache::loncommon::end_data_table();
1.324     albertel 4769:     $studentTable.=&show_grading_menu_form($env{'form.symb'});
1.526     raeburn  4770:     my $grademsg=($changeflag == 0 ? &mt('No score was changed or updated.') :
                   4771: 		  &mt('The scores were changed for [quant,_1,problem].',
                   4772: 		  $changeflag));
1.76      ng       4773:     $request->print($grademsg.$studentTable);
1.68      ng       4774: 
1.70      ng       4775:     return '';
                   4776: }
                   4777: 
1.72      ng       4778: #-------- end of section for handling grading by page/sequence ---------
                   4779: #
                   4780: #-------------------------------------------------------------------
                   4781: 
1.581     www      4782: #-------------------- Bubblesheet (Scantron) Grading -------------------
1.75      albertel 4783: #
                   4784: #------ start of section for handling grading by page/sequence ---------
                   4785: 
1.423     albertel 4786: =pod
                   4787: 
                   4788: =head1 Bubble sheet grading routines
                   4789: 
1.424     albertel 4790:   For this documentation:
                   4791: 
                   4792:    'scanline' refers to the full line of characters
                   4793:    from the file that we are parsing that represents one entire sheet
                   4794: 
                   4795:    'bubble line' refers to the data
                   4796:    representing the line of bubbles that are on the physical bubble sheet
                   4797: 
                   4798: 
                   4799: The overall process is that a scanned in bubble sheet data is uploaded
                   4800: into a course. When a user wants to grade, they select a
                   4801: sequence/folder of resources, a file of bubble sheet info, and pick
                   4802: one of the predefined configurations for what each scanline looks
                   4803: like.
                   4804: 
                   4805: Next each scanline is checked for any errors of either 'missing
1.435     foxr     4806: bubbles' (it's an error because it may have been mis-scanned
1.424     albertel 4807: because too light bubbling), 'double bubble' (each bubble line should
                   4808: have no more that one letter picked), invalid or duplicated CODE,
1.556     weissno  4809: invalid student/employee ID
1.424     albertel 4810: 
                   4811: If the CODE option is used that determines the randomization of the
1.556     weissno  4812: homework problems, either way the student/employee ID is looked up into a
1.424     albertel 4813: username:domain.
                   4814: 
                   4815: During the validation phase the instructor can choose to skip scanlines. 
                   4816: 
1.435     foxr     4817: After the validation phase, there are now 3 bubble sheet files
1.424     albertel 4818: 
                   4819:   scantron_original_filename (unmodified original file)
                   4820:   scantron_corrected_filename (file where the corrected information has replaced the original information)
                   4821:   scantron_skipped_filename (contains the exact text of scanlines that where skipped)
                   4822: 
                   4823: Also there is a separate hash nohist_scantrondata that contains extra
                   4824: correction information that isn't representable in the bubble sheet
                   4825: file (see &scantron_getfile() for more information)
                   4826: 
                   4827: After all scanlines are either valid, marked as valid or skipped, then
                   4828: foreach line foreach problem in the picked sequence, an ssi request is
                   4829: made that simulates a user submitting their selected letter(s) against
                   4830: the homework problem.
1.423     albertel 4831: 
                   4832: =over 4
                   4833: 
                   4834: 
                   4835: 
                   4836: =item defaultFormData
                   4837: 
                   4838:   Returns html hidden inputs used to hold context/default values.
                   4839: 
                   4840:  Arguments:
                   4841:   $symb - $symb of the current resource 
                   4842: 
                   4843: =cut
1.422     foxr     4844: 
1.81      albertel 4845: sub defaultFormData {
1.324     albertel 4846:     my ($symb)=@_;
1.613   ! www      4847:     return '<input type="hidden" name="symb"    value="'.&Apache::lonenc::check_encrypt($symb).'" />';
1.81      albertel 4848: }
                   4849: 
1.447     foxr     4850: 
1.423     albertel 4851: =pod 
                   4852: 
                   4853: =item getSequenceDropDown
                   4854: 
                   4855:    Return html dropdown of possible sequences to grade
                   4856:  
                   4857:  Arguments:
1.582     raeburn  4858:    $symb - $symb of the current resource
                   4859:    $map_error - ref to scalar which will container error if
                   4860:                 $navmap object is unavailable in &getSymbMap().
1.423     albertel 4861: 
                   4862: =cut
1.422     foxr     4863: 
1.75      albertel 4864: sub getSequenceDropDown {
1.582     raeburn  4865:     my ($symb,$map_error)=@_;
1.75      albertel 4866:     my $result='<select name="selectpage">'."\n";
1.582     raeburn  4867:     my ($titles,$symbx) = &getSymbMap($map_error);
                   4868:     if (ref($map_error)) {
                   4869:         return if ($$map_error);
                   4870:     }
1.137     albertel 4871:     my ($curpage)=&Apache::lonnet::decode_symb($symb); 
1.75      albertel 4872:     my $ctr=0;
                   4873:     foreach (@$titles) {
                   4874: 	my ($minder,$showtitle) = ($_ =~ /(\d+)\.(.*)/);
                   4875: 	$result.='<option value="'.$$symbx{$_}.'" '.
1.401     albertel 4876: 	    ($$symbx{$_} =~ /$curpage$/ ? 'selected="selected"' : '').
1.75      albertel 4877: 	    '>'.$showtitle.'</option>'."\n";
                   4878: 	$ctr++;
                   4879:     }
                   4880:     $result.= '</select>';
                   4881:     return $result;
                   4882: }
                   4883: 
1.495     albertel 4884: my %bubble_lines_per_response;     # no. bubble lines for each response.
1.554     raeburn  4885:                                    # key is zero-based index - 0, 1, 2 ...
1.495     albertel 4886: 
                   4887: my %first_bubble_line;             # First bubble line no. for each bubble.
                   4888: 
1.509     raeburn  4889: my %subdivided_bubble_lines;       # no. bubble lines for optionresponse, 
                   4890:                                    # matchresponse or rankresponse, where 
                   4891:                                    # an individual response can have multiple 
                   4892:                                    # lines
1.503     raeburn  4893: 
                   4894: my %responsetype_per_response;     # responsetype for each response
                   4895: 
1.495     albertel 4896: # Save and restore the bubble lines array to the form env.
                   4897: 
                   4898: 
                   4899: sub save_bubble_lines {
                   4900:     foreach my $line (keys(%bubble_lines_per_response)) {
                   4901: 	$env{"form.scantron.bubblelines.$line"}  = $bubble_lines_per_response{$line};
                   4902: 	$env{"form.scantron.first_bubble_line.$line"} =
                   4903: 	    $first_bubble_line{$line};
1.503     raeburn  4904:         $env{"form.scantron.sub_bubblelines.$line"} = 
                   4905:             $subdivided_bubble_lines{$line};
                   4906:         $env{"form.scantron.responsetype.$line"} =
                   4907:             $responsetype_per_response{$line};
1.495     albertel 4908:     }
                   4909: }
                   4910: 
                   4911: 
                   4912: sub restore_bubble_lines {
                   4913:     my $line = 0;
                   4914:     %bubble_lines_per_response = ();
                   4915:     while ($env{"form.scantron.bubblelines.$line"}) {
                   4916: 	my $value = $env{"form.scantron.bubblelines.$line"};
                   4917: 	$bubble_lines_per_response{$line} = $value;
                   4918: 	$first_bubble_line{$line}  =
                   4919: 	    $env{"form.scantron.first_bubble_line.$line"};
1.503     raeburn  4920:         $subdivided_bubble_lines{$line} =
                   4921:             $env{"form.scantron.sub_bubblelines.$line"};
                   4922:         $responsetype_per_response{$line} =
                   4923:             $env{"form.scantron.responsetype.$line"};
1.495     albertel 4924: 	$line++;
                   4925:     }
                   4926: }
                   4927: 
                   4928: #  Given the parsed scanline, get the response for 
                   4929: #  'answer' number n:
                   4930: 
                   4931: sub get_response_bubbles {
                   4932:     my ($parsed_line, $response)  = @_;
                   4933: 
                   4934:     my $bubble_line = $first_bubble_line{$response-1} +1;
                   4935:     my $bubble_lines= $bubble_lines_per_response{$response-1};
                   4936:     
                   4937:     my $selected = "";
                   4938: 
                   4939:     for (my $bline = 0; $bline < $bubble_lines; $bline++) {
                   4940: 	$selected .= $$parsed_line{"scantron.$bubble_line.answer"}.":";
                   4941: 	$bubble_line++;
                   4942:     }
                   4943:     return $selected;
                   4944: }
1.423     albertel 4945: 
                   4946: =pod 
                   4947: 
                   4948: =item scantron_filenames
                   4949: 
                   4950:    Returns a list of the scantron files in the current course 
                   4951: 
                   4952: =cut
1.422     foxr     4953: 
1.202     albertel 4954: sub scantron_filenames {
1.257     albertel 4955:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
                   4956:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
1.517     raeburn  4957:     my $getpropath = 1;
1.157     albertel 4958:     my @files=&Apache::lonnet::dirlist('userfiles',$cdom,$cname,
1.517     raeburn  4959:                                        $getpropath);
1.202     albertel 4960:     my @possiblenames;
1.201     albertel 4961:     foreach my $filename (sort(@files)) {
1.157     albertel 4962: 	($filename)=split(/&/,$filename);
                   4963: 	if ($filename!~/^scantron_orig_/) { next ; }
                   4964: 	$filename=~s/^scantron_orig_//;
1.202     albertel 4965: 	push(@possiblenames,$filename);
                   4966:     }
                   4967:     return @possiblenames;
                   4968: }
                   4969: 
1.423     albertel 4970: =pod 
                   4971: 
                   4972: =item scantron_uploads
                   4973: 
                   4974:    Returns  html drop-down list of scantron files in current course.
                   4975: 
                   4976:  Arguments:
                   4977:    $file2grade - filename to set as selected in the dropdown
                   4978: 
                   4979: =cut
1.422     foxr     4980: 
1.202     albertel 4981: sub scantron_uploads {
1.209     ng       4982:     my ($file2grade) = @_;
1.202     albertel 4983:     my $result=	'<select name="scantron_selectfile">';
                   4984:     $result.="<option></option>";
                   4985:     foreach my $filename (sort(&scantron_filenames())) {
1.401     albertel 4986: 	$result.="<option".($filename eq $file2grade ? ' selected="selected"':'').">$filename</option>\n";
1.81      albertel 4987:     }
                   4988:     $result.="</select>";
                   4989:     return $result;
                   4990: }
                   4991: 
1.423     albertel 4992: =pod 
                   4993: 
                   4994: =item scantron_scantab
                   4995: 
                   4996:   Returns html drop down of the scantron formats in the scantronformat.tab
                   4997:   file.
                   4998: 
                   4999: =cut
1.422     foxr     5000: 
1.82      albertel 5001: sub scantron_scantab {
                   5002:     my $result='<select name="scantron_format">'."\n";
1.191     albertel 5003:     $result.='<option></option>'."\n";
1.518     raeburn  5004:     my @lines = &get_scantronformat_file();
                   5005:     if (@lines > 0) {
                   5006:         foreach my $line (@lines) {
                   5007:             next if (($line =~ /^\#/) || ($line eq ''));
                   5008: 	    my ($name,$descrip)=split(/:/,$line);
                   5009: 	    $result.='<option value="'.$name.'">'.$descrip.'</option>'."\n";
                   5010:         }
1.82      albertel 5011:     }
                   5012:     $result.='</select>'."\n";
1.518     raeburn  5013:     return $result;
                   5014: }
                   5015: 
                   5016: =pod
                   5017: 
                   5018: =item get_scantronformat_file
                   5019: 
                   5020:   Returns an array containing lines from the scantron format file for
                   5021:   the domain of the course.
                   5022: 
                   5023:   If a url for a custom.tab file is listed in domain's configuration.db, 
                   5024:   lines are from this file.
                   5025: 
                   5026:   Otherwise, if a default.tab has been published in RES space by the 
                   5027:   domainconfig user, lines are from this file.
                   5028: 
                   5029:   Otherwise, fall back to getting lines from the legacy file on the
1.519     raeburn  5030:   local server:  /home/httpd/lonTabs/default_scantronformat.tab    
1.82      albertel 5031: 
1.518     raeburn  5032: =cut
                   5033: 
                   5034: sub get_scantronformat_file {
                   5035:     my $cdom= $env{'course.'.$env{'request.course.id'}.'.domain'};
                   5036:     my %domconfig = &Apache::lonnet::get_dom('configuration',['scantron'],$cdom);
                   5037:     my $gottab = 0;
                   5038:     my @lines;
                   5039:     if (ref($domconfig{'scantron'}) eq 'HASH') {
                   5040:         if ($domconfig{'scantron'}{'scantronformat'} ne '') {
                   5041:             my $formatfile = &Apache::lonnet::getfile($Apache::lonnet::perlvar{'lonDocRoot'}.$domconfig{'scantron'}{'scantronformat'});
                   5042:             if ($formatfile ne '-1') {
                   5043:                 @lines = split("\n",$formatfile,-1);
                   5044:                 $gottab = 1;
                   5045:             }
                   5046:         }
                   5047:     }
                   5048:     if (!$gottab) {
                   5049:         my $confname = $cdom.'-domainconfig';
                   5050:         my $default = $Apache::lonnet::perlvar{'lonDocRoot'}.'/res/'.$cdom.'/'.$confname.'/default.tab';
                   5051:         my $formatfile =  &Apache::lonnet::getfile($default);
                   5052:         if ($formatfile ne '-1') {
                   5053:             @lines = split("\n",$formatfile,-1);
                   5054:             $gottab = 1;
                   5055:         }
                   5056:     }
                   5057:     if (!$gottab) {
1.519     raeburn  5058:         my @domains = &Apache::lonnet::current_machine_domains();
                   5059:         if (grep(/^\Q$cdom\E$/,@domains)) {
                   5060:             my $fh=Apache::File->new($Apache::lonnet::perlvar{'lonTabDir'}.'/scantronformat.tab');
                   5061:             @lines = <$fh>;
                   5062:             close($fh);
                   5063:         } else {
                   5064:             my $fh=Apache::File->new($Apache::lonnet::perlvar{'lonTabDir'}.'/default_scantronformat.tab');
                   5065:             @lines = <$fh>;
                   5066:             close($fh);
                   5067:         }
1.518     raeburn  5068:     }
                   5069:     return @lines;
1.82      albertel 5070: }
                   5071: 
1.423     albertel 5072: =pod 
                   5073: 
                   5074: =item scantron_CODElist
                   5075: 
                   5076:   Returns html drop down of the saved CODE lists from current course,
                   5077:   generated from earlier printings.
                   5078: 
                   5079: =cut
1.422     foxr     5080: 
1.186     albertel 5081: sub scantron_CODElist {
1.257     albertel 5082:     my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   5083:     my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
1.186     albertel 5084:     my @names=&Apache::lonnet::getkeys('CODEs',$cdom,$cnum);
                   5085:     my $namechoice='<option></option>';
1.225     albertel 5086:     foreach my $name (sort {uc($a) cmp uc($b)} @names) {
1.191     albertel 5087: 	if ($name =~ /^error: 2 /) { next; }
1.278     albertel 5088: 	if ($name =~ /^type\0/) { next; }
1.186     albertel 5089: 	$namechoice.='<option value="'.$name.'">'.$name.'</option>';
                   5090:     }
                   5091:     $namechoice='<select name="scantron_CODElist">'.$namechoice.'</select>';
                   5092:     return $namechoice;
                   5093: }
                   5094: 
1.423     albertel 5095: =pod 
                   5096: 
                   5097: =item scantron_CODEunique
                   5098: 
                   5099:   Returns the html for "Each CODE to be used once" radio.
                   5100: 
                   5101: =cut
1.422     foxr     5102: 
1.186     albertel 5103: sub scantron_CODEunique {
1.532     bisitz   5104:     my $result='<span class="LC_nobreak">
1.272     albertel 5105:                  <label><input type="radio" name="scantron_CODEunique"
1.423     albertel 5106:                         value="yes" checked="checked" />'.&mt('Yes').' </label>
1.381     albertel 5107:                 </span>
1.532     bisitz   5108:                 <span class="LC_nobreak">
1.272     albertel 5109:                  <label><input type="radio" name="scantron_CODEunique"
1.423     albertel 5110:                         value="no" />'.&mt('No').' </label>
1.381     albertel 5111:                 </span>';
1.186     albertel 5112:     return $result;
                   5113: }
1.423     albertel 5114: 
                   5115: =pod 
                   5116: 
                   5117: =item scantron_selectphase
                   5118: 
                   5119:   Generates the initial screen to start the bubble sheet process.
                   5120:   Allows for - starting a grading run.
1.424     albertel 5121:              - downloading existing scan data (original, corrected
1.423     albertel 5122:                                                 or skipped info)
                   5123: 
                   5124:              - uploading new scan data
                   5125: 
                   5126:  Arguments:
                   5127:   $r          - The Apache request object
                   5128:   $file2grade - name of the file that contain the scanned data to score
                   5129: 
                   5130: =cut
1.186     albertel 5131: 
1.75      albertel 5132: sub scantron_selectphase {
1.608     www      5133:     my ($r,$file2grade,$symb) = @_;
1.75      albertel 5134:     if (!$symb) {return '';}
1.582     raeburn  5135:     my $map_error;
                   5136:     my $sequence_selector=&getSequenceDropDown($symb,\$map_error);
                   5137:     if ($map_error) {
                   5138:         $r->print('<br />'.&navmap_errormsg().'<br />');
                   5139:         return;
                   5140:     }
1.324     albertel 5141:     my $default_form_data=&defaultFormData($symb);
                   5142:     my $grading_menu_button=&show_grading_menu_form($symb);
1.209     ng       5143:     my $file_selector=&scantron_uploads($file2grade);
1.82      albertel 5144:     my $format_selector=&scantron_scantab();
1.186     albertel 5145:     my $CODE_selector=&scantron_CODElist();
                   5146:     my $CODE_unique=&scantron_CODEunique();
1.75      albertel 5147:     my $result;
1.422     foxr     5148: 
1.513     foxr     5149:     $ssi_error = 0;
                   5150: 
1.606     wenzelju 5151:     if (&Apache::lonnet::allowed('usc',$env{'request.role.domain'}) ||
                   5152:         &Apache::lonnet::allowed('usc',$env{'request.course.id'})) {
                   5153: 
                   5154: 	# Chunk of form to prompt for a scantron file upload.
                   5155: 
                   5156:         $r->print('
                   5157:     <br />
                   5158:     '.&Apache::loncommon::start_data_table('LC_scantron_action').'
                   5159:        '.&Apache::loncommon::start_data_table_header_row().'
                   5160:             <th>
                   5161:               &nbsp;'.&mt('Specify a bubblesheet data file to upload.').'
                   5162:             </th>
                   5163:        '.&Apache::loncommon::end_data_table_header_row().'
                   5164:        '.&Apache::loncommon::start_data_table_row().'
                   5165:             <td>
                   5166: ');
1.608     www      5167:     my $default_form_data=&defaultFormData($symb);
1.606     wenzelju 5168:     my $cdom= $env{'course.'.$env{'request.course.id'}.'.domain'};
                   5169:     my $cnum= $env{'course.'.$env{'request.course.id'}.'.num'};
                   5170:     $r->print(&Apache::lonhtmlcommon::scripttag('
                   5171:     function checkUpload(formname) {
                   5172: 	if (formname.upfile.value == "") {
                   5173: 	    alert("'.&mt('Please use the browse button to select a file from your local directory.').'");
                   5174: 	    return false;
                   5175: 	}
                   5176: 	formname.submit();
                   5177:     }'));
                   5178:     $r->print('
                   5179:               <form enctype="multipart/form-data" action="/adm/grades" name="rules" method="post">
                   5180:                 '.$default_form_data.'
                   5181:                 <input name="courseid" type="hidden" value="'.$cnum.'" />
                   5182:                 <input name="domainid" type="hidden" value="'.$cdom.'" />
                   5183:                 <input name="command" value="scantronupload_save" type="hidden" />
                   5184:                 '.&mt('File to upload: [_1]','<input type="file" name="upfile" size="50" />').'
                   5185:                 <br />
                   5186:                 <input type="button" onclick="javascript:checkUpload(this.form);" value="'.&mt('Upload Bubblesheet Data').'" />
                   5187:               </form>
                   5188: ');
                   5189: 
                   5190:         $r->print('
                   5191:             </td>
                   5192:        '.&Apache::loncommon::end_data_table_row().'
                   5193:        '.&Apache::loncommon::end_data_table().'
                   5194: ');
                   5195:     }
                   5196: 
1.422     foxr     5197:     # Chunk of form to prompt for a file to grade and how:
                   5198: 
1.489     albertel 5199:     $result.= '
                   5200:     <br />
                   5201:     <form method="post" enctype="multipart/form-data" action="/adm/grades" name="scantron_process">
                   5202:     <input type="hidden" name="command" value="scantron_warning" />
                   5203:     '.$default_form_data.'
                   5204:     '.&Apache::loncommon::start_data_table('LC_scantron_action').'
                   5205:        '.&Apache::loncommon::start_data_table_header_row().'
                   5206:             <th colspan="2">
1.492     albertel 5207:               &nbsp;'.&mt('Specify file and which Folder/Sequence to grade').'
1.489     albertel 5208:             </th>
                   5209:        '.&Apache::loncommon::end_data_table_header_row().'
                   5210:        '.&Apache::loncommon::start_data_table_row().'
1.492     albertel 5211:             <td> '.&mt('Sequence to grade:').' </td><td> '.$sequence_selector.' </td>
1.489     albertel 5212:        '.&Apache::loncommon::end_data_table_row().'
                   5213:        '.&Apache::loncommon::start_data_table_row().'
1.572     www      5214:             <td> '.&mt('Filename of bubblesheet data file:').' </td><td> '.$file_selector.' </td>
1.489     albertel 5215:        '.&Apache::loncommon::end_data_table_row().'
                   5216:        '.&Apache::loncommon::start_data_table_row().'
1.572     www      5217:             <td> '.&mt('Format of bubblesheet data file:').' </td><td> '.$format_selector.' </td>
1.489     albertel 5218:        '.&Apache::loncommon::end_data_table_row().'
                   5219:        '.&Apache::loncommon::start_data_table_row().'
1.492     albertel 5220:             <td> '.&mt('Saved CODEs to validate against:').' </td><td> '.$CODE_selector.' </td>
1.489     albertel 5221:        '.&Apache::loncommon::end_data_table_row().'
                   5222:        '.&Apache::loncommon::start_data_table_row().'
1.492     albertel 5223:             <td> '.&mt('Each CODE is only to be used once:').'</td><td> '.$CODE_unique.' </td>
1.489     albertel 5224:        '.&Apache::loncommon::end_data_table_row().'
                   5225:        '.&Apache::loncommon::start_data_table_row().'
1.492     albertel 5226: 	    <td> '.&mt('Options:').' </td>
1.187     albertel 5227:             <td>
1.492     albertel 5228: 	       <label><input type="checkbox" name="scantron_options_redo" value="redo_skipped"/> '.&mt('Do only previously skipped records').'</label> <br />
                   5229:                <label><input type="checkbox" name="scantron_options_ignore" value="ignore_corrections"/> '.&mt('Remove all existing corrections').'</label> <br />
                   5230:                <label><input type="checkbox" name="scantron_options_hidden" value="ignore_hidden"/> '.&mt('Skip hidden resources when grading').'</label>
1.187     albertel 5231: 	    </td>
1.489     albertel 5232:        '.&Apache::loncommon::end_data_table_row().'
                   5233:        '.&Apache::loncommon::start_data_table_row().'
1.174     albertel 5234:             <td colspan="2">
1.572     www      5235:               <input type="submit" value="'.&mt('Grading: Validate Bubblesheet Records').'" />
1.162     albertel 5236:             </td>
1.489     albertel 5237:        '.&Apache::loncommon::end_data_table_row().'
                   5238:     '.&Apache::loncommon::end_data_table().'
                   5239:     </form>
                   5240: ';
1.162     albertel 5241:    
                   5242:     $r->print($result);
                   5243: 
1.422     foxr     5244: 
                   5245: 
                   5246:     # Chunk of the form that prompts to view a scoring office file,
                   5247:     # corrected file, skipped records in a file.
                   5248: 
1.489     albertel 5249:     $r->print('
                   5250:    <br />
                   5251:    <form action="/adm/grades" name="scantron_download">
                   5252:      '.$default_form_data.'
                   5253:      <input type="hidden" name="command" value="scantron_download" />
                   5254:      '.&Apache::loncommon::start_data_table('LC_scantron_action').'
                   5255:        '.&Apache::loncommon::start_data_table_header_row().'
                   5256:               <th>
1.492     albertel 5257:                 &nbsp;'.&mt('Download a scoring office file').'
1.489     albertel 5258:               </th>
                   5259:        '.&Apache::loncommon::end_data_table_header_row().'
                   5260:        '.&Apache::loncommon::start_data_table_row().'
1.492     albertel 5261:               <td> '.&mt('Filename of scoring office file: [_1]',$file_selector).' 
1.489     albertel 5262:                 <br />
1.492     albertel 5263:                 <input type="submit" value="'.&mt('Download: Show List of Associated Files').'" />
1.489     albertel 5264:        '.&Apache::loncommon::end_data_table_row().'
                   5265:      '.&Apache::loncommon::end_data_table().'
                   5266:    </form>
                   5267:    <br />
                   5268: ');
1.162     albertel 5269: 
1.457     banghart 5270:     &Apache::lonpickcode::code_list($r,2);
1.523     raeburn  5271: 
1.528     raeburn  5272:     $r->print('<br /><form method="post" name="checkscantron">'.
1.523     raeburn  5273:              $default_form_data."\n".
                   5274:              &Apache::loncommon::start_data_table('LC_scantron_action')."\n".
                   5275:              &Apache::loncommon::start_data_table_header_row()."\n".
                   5276:              '<th colspan="2">
1.572     www      5277:               &nbsp;'.&mt('Review bubblesheet data and submissions for a previously graded folder/sequence')."\n".
1.523     raeburn  5278:              '</th>'."\n".
                   5279:               &Apache::loncommon::end_data_table_header_row()."\n".
                   5280:               &Apache::loncommon::start_data_table_row()."\n".
                   5281:               '<td> '.&mt('Graded folder/sequence:').' </td>'."\n".
                   5282:               '<td> '.$sequence_selector.' </td>'.
                   5283:               &Apache::loncommon::end_data_table_row()."\n".
                   5284:               &Apache::loncommon::start_data_table_row()."\n".
                   5285:               '<td> '.&mt('Filename of scoring office file:').' </td>'."\n".
                   5286:               '<td> '.$file_selector.' </td>'."\n".
                   5287:               &Apache::loncommon::end_data_table_row()."\n".
                   5288:               &Apache::loncommon::start_data_table_row()."\n".
                   5289:               '<td> '.&mt('Format of data file:').' </td>'."\n".
                   5290:               '<td> '.$format_selector.' </td>'."\n".
                   5291:               &Apache::loncommon::end_data_table_row()."\n".
                   5292:               &Apache::loncommon::start_data_table_row()."\n".
1.557     raeburn  5293:               '<td> '.&mt('Options').' </td>'."\n".
                   5294:               '<td> <label><input type="checkbox" name="scantron_options_hidden" value="ignore_hidden"/> '.&mt('Skip hidden resources').'</label></td>'.
                   5295:               &Apache::loncommon::end_data_table_row()."\n".
                   5296:               &Apache::loncommon::start_data_table_row()."\n".
1.523     raeburn  5297:               '<td colspan="2">'."\n".
                   5298:               '<input type="hidden" name="command" value="checksubmissions" />'."\n".
1.575     www      5299:               '<input type="submit" value="'.&mt('Review Bubblesheet Data and Submission Records').'" />'."\n".
1.523     raeburn  5300:               '</td>'."\n".
                   5301:               &Apache::loncommon::end_data_table_row()."\n".
                   5302:               &Apache::loncommon::end_data_table()."\n".
                   5303:               '</form><br />');
1.457     banghart 5304:     $r->print($grading_menu_button);
1.523     raeburn  5305:     return;
1.75      albertel 5306: }
                   5307: 
1.423     albertel 5308: =pod
                   5309: 
                   5310: =item get_scantron_config
                   5311: 
                   5312:    Parse and return the scantron configuration line selected as a
                   5313:    hash of configuration file fields.
                   5314: 
                   5315:  Arguments:
                   5316:     which - the name of the configuration to parse from the file.
                   5317: 
                   5318: 
                   5319:  Returns:
                   5320:             If the named configuration is not in the file, an empty
                   5321:             hash is returned.
                   5322:     a hash with the fields
                   5323:       name         - internal name for the this configuration setup
                   5324:       description  - text to display to operator that describes this config
                   5325:       CODElocation - if 0 or the string 'none'
                   5326:                           - no CODE exists for this config
                   5327:                      if -1 || the string 'letter'
                   5328:                           - a CODE exists for this config and is
                   5329:                             a string of letters
                   5330:                      Unsupported value (but planned for future support)
                   5331:                           if a positive integer
                   5332:                                - The CODE exists as the first n items from
                   5333:                                  the question section of the form
                   5334:                           if the string 'number'
                   5335:                                - The CODE exists for this config and is
                   5336:                                  a string of numbers
                   5337:       CODEstart   - (only matter if a CODE exists) column in the line where
                   5338:                      the CODE starts
                   5339:       CODElength  - length of the CODE
1.573     bisitz   5340:       IDstart     - column where the student/employee ID starts
1.556     weissno  5341:       IDlength    - length of the student/employee ID info
1.423     albertel 5342:       Qstart      - column where the information from the bubbled
                   5343:                     'questions' start
                   5344:       Qlength     - number of columns comprising a single bubble line from
                   5345:                     the sheet. (usually either 1 or 10)
1.424     albertel 5346:       Qon         - either a single character representing the character used
1.423     albertel 5347:                     to signal a bubble was chosen in the positional setup, or
                   5348:                     the string 'letter' if the letter of the chosen bubble is
                   5349:                     in the final, or 'number' if a number representing the
                   5350:                     chosen bubble is in the file (1->A 0->J)
1.424     albertel 5351:       Qoff        - the character used to represent that a bubble was
                   5352:                     left blank
1.423     albertel 5353:       PaperID     - if the scanning process generates a unique number for each
                   5354:                     sheet scanned the column that this ID number starts in
                   5355:       PaperIDlength - number of columns that comprise the unique ID number
                   5356:                       for the sheet of paper
1.424     albertel 5357:       FirstName   - column that the first name starts in
1.423     albertel 5358:       FirstNameLength - number of columns that the first name spans
                   5359:  
                   5360:       LastName    - column that the last name starts in
                   5361:       LastNameLength - number of columns that the last name spans
                   5362: 
                   5363: =cut
1.422     foxr     5364: 
1.82      albertel 5365: sub get_scantron_config {
                   5366:     my ($which) = @_;
1.518     raeburn  5367:     my @lines = &get_scantronformat_file();
1.82      albertel 5368:     my %config;
1.157     albertel 5369:     #FIXME probably should move to XML it has already gotten a bit much now
1.518     raeburn  5370:     foreach my $line (@lines) {
1.82      albertel 5371: 	my ($name,$descrip)=split(/:/,$line);
                   5372: 	if ($name ne $which ) { next; }
                   5373: 	chomp($line);
                   5374: 	my @config=split(/:/,$line);
                   5375: 	$config{'name'}=$config[0];
                   5376: 	$config{'description'}=$config[1];
                   5377: 	$config{'CODElocation'}=$config[2];
                   5378: 	$config{'CODEstart'}=$config[3];
                   5379: 	$config{'CODElength'}=$config[4];
                   5380: 	$config{'IDstart'}=$config[5];
                   5381: 	$config{'IDlength'}=$config[6];
                   5382: 	$config{'Qstart'}=$config[7];
1.497     foxr     5383:  	$config{'Qlength'}=$config[8];
1.82      albertel 5384: 	$config{'Qoff'}=$config[9];
                   5385: 	$config{'Qon'}=$config[10];
1.157     albertel 5386: 	$config{'PaperID'}=$config[11];
                   5387: 	$config{'PaperIDlength'}=$config[12];
                   5388: 	$config{'FirstName'}=$config[13];
                   5389: 	$config{'FirstNamelength'}=$config[14];
                   5390: 	$config{'LastName'}=$config[15];
                   5391: 	$config{'LastNamelength'}=$config[16];
1.82      albertel 5392: 	last;
                   5393:     }
                   5394:     return %config;
                   5395: }
                   5396: 
1.423     albertel 5397: =pod 
                   5398: 
                   5399: =item username_to_idmap
                   5400: 
1.556     weissno  5401:     creates a hash keyed by student/employee ID with values of the corresponding
1.423     albertel 5402:     student username:domain.
                   5403: 
                   5404:   Arguments:
                   5405: 
                   5406:     $classlist - reference to the class list hash. This is a hash
                   5407:                  keyed by student name:domain  whose elements are references
1.424     albertel 5408:                  to arrays containing various chunks of information
1.423     albertel 5409:                  about the student. (See loncoursedata for more info).
                   5410: 
                   5411:   Returns
                   5412:     %idmap - the constructed hash
                   5413: 
                   5414: =cut
                   5415: 
1.82      albertel 5416: sub username_to_idmap {
                   5417:     my ($classlist)= @_;
                   5418:     my %idmap;
                   5419:     foreach my $student (keys(%$classlist)) {
                   5420: 	$idmap{$classlist->{$student}->[&Apache::loncoursedata::CL_ID]}=
                   5421: 	    $student;
                   5422:     }
                   5423:     return %idmap;
                   5424: }
1.423     albertel 5425: 
                   5426: =pod
                   5427: 
1.424     albertel 5428: =item scantron_fixup_scanline
1.423     albertel 5429: 
                   5430:    Process a requested correction to a scanline.
                   5431: 
                   5432:   Arguments:
                   5433:     $scantron_config   - hash from &get_scantron_config()
                   5434:     $scan_data         - hash of correction information 
                   5435:                           (see &scantron_getfile())
                   5436:     $line              - existing scanline
                   5437:     $whichline         - line number of the passed in scanline
                   5438:     $field             - type of change to process 
                   5439:                          (either 
1.573     bisitz   5440:                           'ID'     -> correct the student/employee ID
1.423     albertel 5441:                           'CODE'   -> correct the CODE
                   5442:                           'answer' -> fixup the submitted answers)
                   5443:     
                   5444:    $args               - hash of additional info,
                   5445:                           - 'ID' 
                   5446:                                'newid' -> studentID to use in replacement
1.424     albertel 5447:                                           of existing one
1.423     albertel 5448:                           - 'CODE' 
                   5449:                                'CODE_ignore_dup' - set to true if duplicates
                   5450:                                                    should be ignored.
                   5451: 	                       'CODE' - is new code or 'use_unfound'
1.424     albertel 5452:                                         if the existing unfound code should
1.423     albertel 5453:                                         be used as is
                   5454:                           - 'answer'
                   5455:                                'response' - new answer or 'none' if blank
                   5456:                                'question' - the bubble line to change
1.503     raeburn  5457:                                'questionnum' - the question identifier,
                   5458:                                                may include subquestion. 
1.423     albertel 5459: 
                   5460:   Returns:
                   5461:     $line - the modified scanline
                   5462: 
                   5463:   Side effects: 
                   5464:     $scan_data - may be updated
                   5465: 
                   5466: =cut
                   5467: 
1.82      albertel 5468: 
1.157     albertel 5469: sub scantron_fixup_scanline {
                   5470:     my ($scantron_config,$scan_data,$line,$whichline,$field,$args)=@_;
                   5471:     if ($field eq 'ID') {
                   5472: 	if (length($args->{'newid'}) > $$scantron_config{'IDlength'}) {
1.186     albertel 5473: 	    return ($line,1,'New value too large');
1.157     albertel 5474: 	}
                   5475: 	if (length($args->{'newid'}) < $$scantron_config{'IDlength'}) {
                   5476: 	    $args->{'newid'}=sprintf('%-'.$$scantron_config{'IDlength'}.'s',
                   5477: 				     $args->{'newid'});
                   5478: 	}
                   5479: 	substr($line,$$scantron_config{'IDstart'}-1,
                   5480: 	       $$scantron_config{'IDlength'})=$args->{'newid'};
                   5481: 	if ($args->{'newid'}=~/^\s*$/) {
                   5482: 	    &scan_data($scan_data,"$whichline.user",
                   5483: 		       $args->{'username'}.':'.$args->{'domain'});
                   5484: 	}
1.186     albertel 5485:     } elsif ($field eq 'CODE') {
1.192     albertel 5486: 	if ($args->{'CODE_ignore_dup'}) {
                   5487: 	    &scan_data($scan_data,"$whichline.CODE_ignore_dup",'1');
                   5488: 	}
                   5489: 	&scan_data($scan_data,"$whichline.useCODE",'1');
                   5490: 	if ($args->{'CODE'} ne 'use_unfound') {
1.191     albertel 5491: 	    if (length($args->{'CODE'}) > $$scantron_config{'CODElength'}) {
                   5492: 		return ($line,1,'New CODE value too large');
                   5493: 	    }
                   5494: 	    if (length($args->{'CODE'}) < $$scantron_config{'CODElength'}) {
                   5495: 		$args->{'CODE'}=sprintf('%-'.$$scantron_config{'CODElength'}.'s',$args->{'CODE'});
                   5496: 	    }
                   5497: 	    substr($line,$$scantron_config{'CODEstart'}-1,
                   5498: 		   $$scantron_config{'CODElength'})=$args->{'CODE'};
1.186     albertel 5499: 	}
1.157     albertel 5500:     } elsif ($field eq 'answer') {
1.497     foxr     5501: 	my $length=$scantron_config->{'Qlength'};
1.157     albertel 5502: 	my $off=$scantron_config->{'Qoff'};
                   5503: 	my $on=$scantron_config->{'Qon'};
1.497     foxr     5504: 	my $answer=${off}x$length;
                   5505: 	if ($args->{'response'} eq 'none') {
                   5506: 	    &scan_data($scan_data,
1.503     raeburn  5507: 		       "$whichline.no_bubble.".$args->{'questionnum'},'1');
1.497     foxr     5508: 	} else {
                   5509: 	    if ($on eq 'letter') {
                   5510: 		my @alphabet=('A'..'Z');
                   5511: 		$answer=$alphabet[$args->{'response'}];
                   5512: 	    } elsif ($on eq 'number') {
                   5513: 		$answer=$args->{'response'}+1;
                   5514: 		if ($answer == 10) { $answer = '0'; }
1.274     albertel 5515: 	    } else {
1.497     foxr     5516: 		substr($answer,$args->{'response'},1)=$on;
1.274     albertel 5517: 	    }
1.497     foxr     5518: 	    &scan_data($scan_data,
1.503     raeburn  5519: 		       "$whichline.no_bubble.".$args->{'questionnum'},undef,'1');
1.157     albertel 5520: 	}
1.497     foxr     5521: 	my $where=$length*($args->{'question'}-1)+$scantron_config->{'Qstart'};
                   5522: 	substr($line,$where-1,$length)=$answer;
1.157     albertel 5523:     }
                   5524:     return $line;
                   5525: }
1.423     albertel 5526: 
                   5527: =pod
                   5528: 
                   5529: =item scan_data
                   5530: 
                   5531:     Edit or look up  an item in the scan_data hash.
                   5532: 
                   5533:   Arguments:
                   5534:     $scan_data  - The hash (see scantron_getfile)
                   5535:     $key        - shorthand of the key to edit (actual key is
1.424     albertel 5536:                   scantronfilename_key).
1.423     albertel 5537:     $data        - New value of the hash entry.
                   5538:     $delete      - If true, the entry is removed from the hash.
                   5539: 
                   5540:   Returns:
                   5541:     The new value of the hash table field (undefined if deleted).
                   5542: 
                   5543: =cut
                   5544: 
                   5545: 
1.157     albertel 5546: sub scan_data {
                   5547:     my ($scan_data,$key,$value,$delete)=@_;
1.257     albertel 5548:     my $filename=$env{'form.scantron_selectfile'};
1.157     albertel 5549:     if (defined($value)) {
                   5550: 	$scan_data->{$filename.'_'.$key} = $value;
                   5551:     }
                   5552:     if ($delete) { delete($scan_data->{$filename.'_'.$key}); }
                   5553:     return $scan_data->{$filename.'_'.$key};
                   5554: }
1.423     albertel 5555: 
1.495     albertel 5556: # ----- These first few routines are general use routines.----
                   5557: 
                   5558: # Return the number of occurences of a pattern in a string.
                   5559: 
                   5560: sub occurence_count {
                   5561:     my ($string, $pattern) = @_;
                   5562: 
                   5563:     my @matches = ($string =~ /$pattern/g);
                   5564: 
                   5565:     return scalar(@matches);
                   5566: }
                   5567: 
                   5568: 
                   5569: # Take a string known to have digits and convert all the
                   5570: # digits into letters in the range J,A..I.
                   5571: 
                   5572: sub digits_to_letters {
                   5573:     my ($input) = @_;
                   5574: 
                   5575:     my @alphabet = ('J', 'A'..'I');
                   5576: 
                   5577:     my @input    = split(//, $input);
                   5578:     my $output ='';
                   5579:     for (my $i = 0; $i < scalar(@input); $i++) {
                   5580: 	if ($input[$i] =~ /\d/) {
                   5581: 	    $output .= $alphabet[$input[$i]];
                   5582: 	} else {
                   5583: 	    $output .= $input[$i];
                   5584: 	}
                   5585:     }
                   5586:     return $output;
                   5587: }
                   5588: 
1.423     albertel 5589: =pod 
                   5590: 
                   5591: =item scantron_parse_scanline
                   5592: 
                   5593:   Decodes a scanline from the selected scantron file
                   5594: 
                   5595:  Arguments:
                   5596:     line             - The text of the scantron file line to process
                   5597:     whichline        - Line number
                   5598:     scantron_config  - Hash describing the format of the scantron lines.
                   5599:     scan_data        - Hash of extra information about the scanline
                   5600:                        (see scantron_getfile for more information)
                   5601:     just_header      - True if should not process question answers but only
                   5602:                        the stuff to the left of the answers.
                   5603:  Returns:
                   5604:    Hash containing the result of parsing the scanline
                   5605: 
                   5606:    Keys are all proceeded by the string 'scantron.'
                   5607: 
                   5608:        CODE    - the CODE in use for this scanline
                   5609:        useCODE - 1 if the CODE is invalid but it usage has been forced
                   5610:                  by the operator
                   5611:        CODE_ignore_dup - 1 if the CODE is a duplicated use when unique
                   5612:                             CODEs were selected, but the usage has been
                   5613:                             forced by the operator
1.556     weissno  5614:        ID  - student/employee ID
1.423     albertel 5615:        PaperID - if used, the ID number printed on the sheet when the 
                   5616:                  paper was scanned
                   5617:        FirstName - first name from the sheet
                   5618:        LastName  - last name from the sheet
                   5619: 
                   5620:      if just_header was not true these key may also exist
                   5621: 
1.447     foxr     5622:        missingerror - a list of bubble ranges that are considered to be answers
                   5623:                       to a single question that don't have any bubbles filled in.
                   5624:                       Of the form questionnumber:firstbubblenumber:count.
                   5625:        doubleerror  - a list of bubble ranges that are considered to be answers
                   5626:                       to a single question that have more than one bubble filled in.
                   5627:                       Of the form questionnumber::firstbubblenumber:count
                   5628:    
                   5629:                 In the above, count is the number of bubble responses in the
                   5630:                 input line needed to represent the possible answers to the question.
                   5631:                 e.g. a radioresponse with 15 choices in an answer sheet with 10 choices
                   5632:                 per line would have count = 2.
                   5633: 
1.423     albertel 5634:        maxquest     - the number of the last bubble line that was parsed
                   5635: 
                   5636:        (<number> starts at 1)
                   5637:        <number>.answer - zero or more letters representing the selected
                   5638:                          letters from the scanline for the bubble line 
                   5639:                          <number>.
                   5640:                          if blank there was either no bubble or there where
                   5641:                          multiple bubbles, (consult the keys missingerror and
                   5642:                          doubleerror if this is an error condition)
                   5643: 
                   5644: =cut
                   5645: 
1.82      albertel 5646: sub scantron_parse_scanline {
1.423     albertel 5647:     my ($line,$whichline,$scantron_config,$scan_data,$just_header)=@_;
1.470     foxr     5648: 
1.82      albertel 5649:     my %record;
1.550     raeburn  5650:     my $lastpos = $env{'form.scantron_maxbubble'}*$$scantron_config{'Qlength'};
                   5651:     my $questions=substr($line,$$scantron_config{'Qstart'}-1,$lastpos);  # Answers
1.422     foxr     5652:     my $data=substr($line,0,$$scantron_config{'Qstart'}-1);     # earlier stuff
1.278     albertel 5653:     if (!($$scantron_config{'CODElocation'} eq 0 ||
                   5654: 	  $$scantron_config{'CODElocation'} eq 'none')) {
                   5655: 	if ($$scantron_config{'CODElocation'} < 0 ||
                   5656: 	    $$scantron_config{'CODElocation'} eq 'letter' ||
                   5657: 	    $$scantron_config{'CODElocation'} eq 'number') {
1.191     albertel 5658: 	    $record{'scantron.CODE'}=substr($data,
                   5659: 					    $$scantron_config{'CODEstart'}-1,
1.83      albertel 5660: 					    $$scantron_config{'CODElength'});
1.191     albertel 5661: 	    if (&scan_data($scan_data,"$whichline.useCODE")) {
                   5662: 		$record{'scantron.useCODE'}=1;
                   5663: 	    }
1.192     albertel 5664: 	    if (&scan_data($scan_data,"$whichline.CODE_ignore_dup")) {
                   5665: 		$record{'scantron.CODE_ignore_dup'}=1;
                   5666: 	    }
1.82      albertel 5667: 	} else {
                   5668: 	    #FIXME interpret first N questions
                   5669: 	}
                   5670:     }
1.83      albertel 5671:     $record{'scantron.ID'}=substr($data,$$scantron_config{'IDstart'}-1,
                   5672: 				  $$scantron_config{'IDlength'});
1.157     albertel 5673:     $record{'scantron.PaperID'}=
                   5674: 	substr($data,$$scantron_config{'PaperID'}-1,
                   5675: 	       $$scantron_config{'PaperIDlength'});
                   5676:     $record{'scantron.FirstName'}=
                   5677: 	substr($data,$$scantron_config{'FirstName'}-1,
                   5678: 	       $$scantron_config{'FirstNamelength'});
                   5679:     $record{'scantron.LastName'}=
                   5680: 	substr($data,$$scantron_config{'LastName'}-1,
                   5681: 	       $$scantron_config{'LastNamelength'});
1.423     albertel 5682:     if ($just_header) { return \%record; }
1.194     albertel 5683: 
1.82      albertel 5684:     my @alphabet=('A'..'Z');
                   5685:     my $questnum=0;
1.447     foxr     5686:     my $ansnum  =1;		# Multiple 'answer lines'/question.
                   5687: 
1.470     foxr     5688:     chomp($questions);		# Get rid of any trailing \n.
                   5689:     $questions =~ s/\r$//;      # Get rid of trailing \r too (MAC or Win uploads).
                   5690:     while (length($questions)) {
1.447     foxr     5691: 	my $answers_needed = $bubble_lines_per_response{$questnum};
1.503     raeburn  5692:         my $answer_length  = ($$scantron_config{'Qlength'} * $answers_needed)
                   5693:                              || 1;
                   5694:         $questnum++;
                   5695:         my $quest_id = $questnum;
                   5696:         my $currentquest = substr($questions,0,$answer_length);
                   5697:         $questions       = substr($questions,$answer_length);
                   5698:         if (length($currentquest) < $answer_length) { next; }
                   5699: 
                   5700:         if ($subdivided_bubble_lines{$questnum-1} =~ /,/) {
                   5701:             my $subquestnum = 1;
                   5702:             my $subquestions = $currentquest;
                   5703:             my @subanswers_needed = 
                   5704:                 split(/,/,$subdivided_bubble_lines{$questnum-1});  
                   5705:             foreach my $subans (@subanswers_needed) {
                   5706:                 my $subans_length =
                   5707:                     ($$scantron_config{'Qlength'} * $subans)  || 1;
                   5708:                 my $currsubquest = substr($subquestions,0,$subans_length);
                   5709:                 $subquestions   = substr($subquestions,$subans_length);
                   5710:                 $quest_id = "$questnum.$subquestnum";
                   5711:                 if (($$scantron_config{'Qon'} eq 'letter') ||
                   5712:                     ($$scantron_config{'Qon'} eq 'number')) {
                   5713:                     $ansnum = &scantron_validator_lettnum($ansnum, 
                   5714:                         $questnum,$quest_id,$subans,$currsubquest,$whichline,
                   5715:                         \@alphabet,\%record,$scantron_config,$scan_data);
                   5716:                 } else {
                   5717:                     $ansnum = &scantron_validator_positional($ansnum,
                   5718:                         $questnum,$quest_id,$subans,$currsubquest,$whichline,                        \@alphabet,\%record,$scantron_config,$scan_data);
                   5719:                 }
                   5720:                 $subquestnum ++;
                   5721:             }
                   5722:         } else {
                   5723:             if (($$scantron_config{'Qon'} eq 'letter') ||
                   5724:                 ($$scantron_config{'Qon'} eq 'number')) {
                   5725:                 $ansnum = &scantron_validator_lettnum($ansnum,$questnum,
                   5726:                     $quest_id,$answers_needed,$currentquest,$whichline,
                   5727:                     \@alphabet,\%record,$scantron_config,$scan_data);
                   5728:             } else {
                   5729:                 $ansnum = &scantron_validator_positional($ansnum,$questnum,
                   5730:                     $quest_id,$answers_needed,$currentquest,$whichline,
                   5731:                     \@alphabet,\%record,$scantron_config,$scan_data);
                   5732:             }
                   5733:         }
                   5734:     }
                   5735:     $record{'scantron.maxquest'}=$questnum;
                   5736:     return \%record;
                   5737: }
1.447     foxr     5738: 
1.503     raeburn  5739: sub scantron_validator_lettnum {
                   5740:     my ($ansnum,$questnum,$quest_id,$answers_needed,$currquest,$whichline,
                   5741:         $alphabet,$record,$scantron_config,$scan_data) = @_;
                   5742: 
                   5743:     # Qon 'letter' implies for each slot in currquest we have:
                   5744:     #    ? or * for doubles, a letter in A-Z for a bubble, and
                   5745:     #    about anything else (esp. a value of Qoff) for missing
                   5746:     #    bubbles.
                   5747:     #
                   5748:     # Qon 'number' implies each slot gives a digit that indexes the
                   5749:     #    bubbles filled, or Qoff, or a non-number for unbubbled lines,
                   5750:     #    and * or ? for double bubbles on a single line.
                   5751:     #
1.447     foxr     5752: 
1.503     raeburn  5753:     my $matchon;
                   5754:     if ($$scantron_config{'Qon'} eq 'letter') {
                   5755:         $matchon = '[A-Z]';
                   5756:     } elsif ($$scantron_config{'Qon'} eq 'number') {
                   5757:         $matchon = '\d';
                   5758:     }
                   5759:     my $occurrences = 0;
                   5760:     if (($responsetype_per_response{$questnum-1} eq 'essayresponse') ||
                   5761:         ($responsetype_per_response{$questnum-1} eq 'formularesponse') ||
1.510     raeburn  5762:         ($responsetype_per_response{$questnum-1} eq 'stringresponse') ||
                   5763:         ($responsetype_per_response{$questnum-1} eq 'imageresponse') ||
                   5764:         ($responsetype_per_response{$questnum-1} eq 'reactionresponse') ||
                   5765:         ($responsetype_per_response{$questnum-1} eq 'organicresponse')) {
1.503     raeburn  5766:         my @singlelines = split('',$currquest);
                   5767:         foreach my $entry (@singlelines) {
                   5768:             $occurrences = &occurence_count($entry,$matchon);
                   5769:             if ($occurrences > 1) {
                   5770:                 last;
                   5771:             }
                   5772:         } 
                   5773:     } else {
                   5774:         $occurrences = &occurence_count($currquest,$matchon); 
                   5775:     }
                   5776:     if (($currquest =~ /\?/ || $currquest =~ /\*/) || ($occurrences > 1)) {
                   5777:         push(@{$record->{'scantron.doubleerror'}},$quest_id);
                   5778:         for (my $ans=0; $ans<$answers_needed; $ans++) {
                   5779:             my $bubble = substr($currquest,$ans,1);
                   5780:             if ($bubble =~ /$matchon/ ) {
                   5781:                 if ($$scantron_config{'Qon'} eq 'number') {
                   5782:                     if ($bubble == 0) {
                   5783:                         $bubble = 10; 
                   5784:                     }
                   5785:                     $record->{"scantron.$ansnum.answer"} = 
                   5786:                         $alphabet->[$bubble-1];
                   5787:                 } else {
                   5788:                     $record->{"scantron.$ansnum.answer"} = $bubble;
                   5789:                 }
                   5790:             } else {
                   5791:                 $record->{"scantron.$ansnum.answer"}='';
                   5792:             }
                   5793:             $ansnum++;
                   5794:         }
                   5795:     } elsif (!defined($currquest)
                   5796:             || (&occurence_count($currquest, $$scantron_config{'Qoff'}) == length($currquest))
                   5797:             || (&occurence_count($currquest,$matchon) == 0)) {
                   5798:         for (my $ans=0; $ans<$answers_needed; $ans++ ) {
                   5799:             $record->{"scantron.$ansnum.answer"}='';
                   5800:             $ansnum++;
                   5801:         }
                   5802:         if (!&scan_data($scan_data,"$whichline.no_bubble.$quest_id")) {
                   5803:             push(@{$record->{'scantron.missingerror'}},$quest_id);
                   5804:         }
                   5805:     } else {
                   5806:         if ($$scantron_config{'Qon'} eq 'number') {
                   5807:             $currquest = &digits_to_letters($currquest);            
                   5808:         }
                   5809:         for (my $ans=0; $ans<$answers_needed; $ans++) {
                   5810:             my $bubble = substr($currquest,$ans,1);
                   5811:             $record->{"scantron.$ansnum.answer"} = $bubble;
                   5812:             $ansnum++;
                   5813:         }
                   5814:     }
                   5815:     return $ansnum;
                   5816: }
1.447     foxr     5817: 
1.503     raeburn  5818: sub scantron_validator_positional {
                   5819:     my ($ansnum,$questnum,$quest_id,$answers_needed,$currquest,
                   5820:         $whichline,$alphabet,$record,$scantron_config,$scan_data) = @_;
1.447     foxr     5821: 
1.503     raeburn  5822:     # Otherwise there's a positional notation;
                   5823:     # each bubble line requires Qlength items, and there are filled in
                   5824:     # bubbles for each case where there 'Qon' characters.
                   5825:     #
1.447     foxr     5826: 
1.503     raeburn  5827:     my @array=split($$scantron_config{'Qon'},$currquest,-1);
1.447     foxr     5828: 
1.503     raeburn  5829:     # If the split only gives us one element.. the full length of the
                   5830:     # answer string, no bubbles are filled in:
1.447     foxr     5831: 
1.507     raeburn  5832:     if ($answers_needed eq '') {
                   5833:         return;
                   5834:     }
                   5835: 
1.503     raeburn  5836:     if (length($array[0]) eq $$scantron_config{'Qlength'}*$answers_needed) {
                   5837:         for (my $ans=0; $ans<$answers_needed; $ans++ ) {
                   5838:             $record->{"scantron.$ansnum.answer"}='';
                   5839:             $ansnum++;
                   5840:         }
                   5841:         if (!&scan_data($scan_data,"$whichline.no_bubble.$quest_id")) {
                   5842:             push(@{$record->{"scantron.missingerror"}},$quest_id);
                   5843:         }
                   5844:     } elsif (scalar(@array) == 2) {
                   5845:         my $location = length($array[0]);
                   5846:         my $line_num = int($location / $$scantron_config{'Qlength'});
                   5847:         my $bubble   = $alphabet->[$location % $$scantron_config{'Qlength'}];
                   5848:         for (my $ans=0; $ans<$answers_needed; $ans++) {
                   5849:             if ($ans eq $line_num) {
                   5850:                 $record->{"scantron.$ansnum.answer"} = $bubble;
                   5851:             } else {
                   5852:                 $record->{"scantron.$ansnum.answer"} = ' ';
                   5853:             }
                   5854:             $ansnum++;
                   5855:          }
                   5856:     } else {
                   5857:         #  If there's more than one instance of a bubble character
                   5858:         #  That's a double bubble; with positional notation we can
                   5859:         #  record all the bubbles filled in as well as the
                   5860:         #  fact this response consists of multiple bubbles.
                   5861:         #
                   5862:         if (($responsetype_per_response{$questnum-1} eq 'essayresponse') ||
                   5863:             ($responsetype_per_response{$questnum-1} eq 'formularesponse') ||
1.510     raeburn  5864:             ($responsetype_per_response{$questnum-1} eq 'stringresponse') ||
                   5865:             ($responsetype_per_response{$questnum-1} eq 'imageresponse') ||
                   5866:             ($responsetype_per_response{$questnum-1} eq 'reactionresponse') ||
                   5867:             ($responsetype_per_response{$questnum-1} eq 'organicresponse')) {
1.503     raeburn  5868:             my $doubleerror = 0;
                   5869:             while (($currquest >= $$scantron_config{'Qlength'}) && 
                   5870:                    (!$doubleerror)) {
                   5871:                my $currline = substr($currquest,0,$$scantron_config{'Qlength'});
                   5872:                $currquest = substr($currquest,$$scantron_config{'Qlength'});
                   5873:                my @currarray = split($$scantron_config{'Qon'},$currline,-1);
                   5874:                if (length(@currarray) > 2) {
                   5875:                    $doubleerror = 1;
                   5876:                } 
                   5877:             }
                   5878:             if ($doubleerror) {
                   5879:                 push(@{$record->{'scantron.doubleerror'}},$quest_id);
                   5880:             }
                   5881:         } else {
                   5882:             push(@{$record->{'scantron.doubleerror'}},$quest_id);
                   5883:         }
                   5884:         my $item = $ansnum;
                   5885:         for (my $ans=0; $ans<$answers_needed; $ans++) {
                   5886:             $record->{"scantron.$item.answer"} = '';
                   5887:             $item ++;
                   5888:         }
1.447     foxr     5889: 
1.503     raeburn  5890:         my @ans=@array;
                   5891:         my $i=0;
                   5892:         my $increment = 0;
                   5893:         while ($#ans) {
                   5894:             $i+=length($ans[0]) + $increment;
                   5895:             my $line   = int($i/$$scantron_config{'Qlength'} + $ansnum);
                   5896:             my $bubble = $i%$$scantron_config{'Qlength'};
                   5897:             $record->{"scantron.$line.answer"}.=$alphabet->[$bubble];
                   5898:             shift(@ans);
                   5899:             $increment = 1;
                   5900:         }
                   5901:         $ansnum += $answers_needed;
1.82      albertel 5902:     }
1.503     raeburn  5903:     return $ansnum;
1.82      albertel 5904: }
                   5905: 
1.423     albertel 5906: =pod
                   5907: 
                   5908: =item scantron_add_delay
                   5909: 
                   5910:    Adds an error message that occurred during the grading phase to a
                   5911:    queue of messages to be shown after grading pass is complete
                   5912: 
                   5913:  Arguments:
1.424     albertel 5914:    $delayqueue  - arrary ref of hash ref of error messages
1.423     albertel 5915:    $scanline    - the scanline that caused the error
                   5916:    $errormesage - the error message
                   5917:    $errorcode   - a numeric code for the error
                   5918: 
                   5919:  Side Effects:
1.424     albertel 5920:    updates the $delayqueue to have a new hash ref of the error
1.423     albertel 5921: 
                   5922: =cut
                   5923: 
1.82      albertel 5924: sub scantron_add_delay {
1.140     albertel 5925:     my ($delayqueue,$scanline,$errormessage,$errorcode)=@_;
                   5926:     push(@$delayqueue,
                   5927: 	 {'line' => $scanline, 'emsg' => $errormessage,
                   5928: 	  'ecode' => $errorcode }
                   5929: 	 );
1.82      albertel 5930: }
                   5931: 
1.423     albertel 5932: =pod
                   5933: 
                   5934: =item scantron_find_student
                   5935: 
1.424     albertel 5936:    Finds the username for the current scanline
                   5937: 
                   5938:   Arguments:
                   5939:    $scantron_record - hash result from scantron_parse_scanline
                   5940:    $scan_data       - hash of correction information 
                   5941:                       (see &scantron_getfile() form more information)
                   5942:    $idmap           - hash from &username_to_idmap()
                   5943:    $line            - number of current scanline
                   5944:  
                   5945:   Returns:
                   5946:    Either 'username:domain' or undef if unknown
                   5947: 
1.423     albertel 5948: =cut
                   5949: 
1.82      albertel 5950: sub scantron_find_student {
1.157     albertel 5951:     my ($scantron_record,$scan_data,$idmap,$line)=@_;
1.83      albertel 5952:     my $scanID=$$scantron_record{'scantron.ID'};
1.157     albertel 5953:     if ($scanID =~ /^\s*$/) {
                   5954:  	return &scan_data($scan_data,"$line.user");
                   5955:     }
1.83      albertel 5956:     foreach my $id (keys(%$idmap)) {
1.157     albertel 5957:  	if (lc($id) eq lc($scanID)) {
                   5958:  	    return $$idmap{$id};
                   5959:  	}
1.83      albertel 5960:     }
                   5961:     return undef;
                   5962: }
                   5963: 
1.423     albertel 5964: =pod
                   5965: 
                   5966: =item scantron_filter
                   5967: 
1.424     albertel 5968:    Filter sub for lonnavmaps, filters out hidden resources if ignore
                   5969:    hidden resources was selected
                   5970: 
1.423     albertel 5971: =cut
                   5972: 
1.83      albertel 5973: sub scantron_filter {
                   5974:     my ($curres)=@_;
1.331     albertel 5975: 
                   5976:     if (ref($curres) && $curres->is_problem()) {
                   5977: 	# if the user has asked to not have either hidden
                   5978: 	# or 'randomout' controlled resources to be graded
                   5979: 	# don't include them
                   5980: 	if ($env{'form.scantron_options_hidden'} eq 'ignore_hidden'
                   5981: 	    && $curres->randomout) {
                   5982: 	    return 0;
                   5983: 	}
1.83      albertel 5984: 	return 1;
                   5985:     }
                   5986:     return 0;
1.82      albertel 5987: }
                   5988: 
1.423     albertel 5989: =pod
                   5990: 
                   5991: =item scantron_process_corrections
                   5992: 
1.424     albertel 5993:    Gets correction information out of submitted form data and corrects
                   5994:    the scanline
                   5995: 
1.423     albertel 5996: =cut
                   5997: 
1.157     albertel 5998: sub scantron_process_corrections {
                   5999:     my ($r) = @_;
1.257     albertel 6000:     my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
1.157     albertel 6001:     my ($scanlines,$scan_data)=&scantron_getfile();
                   6002:     my $classlist=&Apache::loncoursedata::get_classlist();
1.257     albertel 6003:     my $which=$env{'form.scantron_line'};
1.200     albertel 6004:     my $line=&scantron_get_line($scanlines,$scan_data,$which);
1.157     albertel 6005:     my ($skip,$err,$errmsg);
1.257     albertel 6006:     if ($env{'form.scantron_skip_record'}) {
1.157     albertel 6007: 	$skip=1;
1.257     albertel 6008:     } elsif ($env{'form.scantron_corrections'} =~ /^(duplicate|incorrect)ID$/) {
                   6009: 	my $newstudent=$env{'form.scantron_username'}.':'.
                   6010: 	    $env{'form.scantron_domain'};
1.157     albertel 6011: 	my $newid=$classlist->{$newstudent}->[&Apache::loncoursedata::CL_ID];
                   6012: 	($line,$err,$errmsg)=
                   6013: 	    &scantron_fixup_scanline(\%scantron_config,$scan_data,$line,$which,
                   6014: 				     'ID',{'newid'=>$newid,
1.257     albertel 6015: 				    'username'=>$env{'form.scantron_username'},
                   6016: 				    'domain'=>$env{'form.scantron_domain'}});
                   6017:     } elsif ($env{'form.scantron_corrections'} =~ /^(duplicate|incorrect)CODE$/) {
                   6018: 	my $resolution=$env{'form.scantron_CODE_resolution'};
1.190     albertel 6019: 	my $newCODE;
1.192     albertel 6020: 	my %args;
1.190     albertel 6021: 	if      ($resolution eq 'use_unfound') {
1.191     albertel 6022: 	    $newCODE='use_unfound';
1.190     albertel 6023: 	} elsif ($resolution eq 'use_found') {
1.257     albertel 6024: 	    $newCODE=$env{'form.scantron_CODE_selectedvalue'};
1.190     albertel 6025: 	} elsif ($resolution eq 'use_typed') {
1.257     albertel 6026: 	    $newCODE=$env{'form.scantron_CODE_newvalue'};
1.194     albertel 6027: 	} elsif ($resolution =~ /^use_closest_(\d+)/) {
1.257     albertel 6028: 	    $newCODE=$env{"form.scantron_CODE_closest_$1"};
1.190     albertel 6029: 	}
1.257     albertel 6030: 	if ($env{'form.scantron_corrections'} eq 'duplicateCODE') {
1.192     albertel 6031: 	    $args{'CODE_ignore_dup'}=1;
                   6032: 	}
                   6033: 	$args{'CODE'}=$newCODE;
1.186     albertel 6034: 	($line,$err,$errmsg)=
                   6035: 	    &scantron_fixup_scanline(\%scantron_config,$scan_data,$line,$which,
1.192     albertel 6036: 				     'CODE',\%args);
1.257     albertel 6037:     } elsif ($env{'form.scantron_corrections'} =~ /^(missing|double)bubble$/) {
                   6038: 	foreach my $question (split(',',$env{'form.scantron_questions'})) {
1.157     albertel 6039: 	    ($line,$err,$errmsg)=
                   6040: 		&scantron_fixup_scanline(\%scantron_config,$scan_data,$line,
                   6041: 					 $which,'answer',
                   6042: 					 { 'question'=>$question,
1.503     raeburn  6043: 		      		   'response'=>$env{"form.scantron_correct_Q_$question"},
                   6044:                                    'questionnum'=>$env{"form.scantron_questionnum_Q_$question"}});
1.157     albertel 6045: 	    if ($err) { last; }
                   6046: 	}
                   6047:     }
                   6048:     if ($err) {
1.398     albertel 6049: 	$r->print("<span class=\"LC_warning\">Unable to accept last correction, an error occurred :$errmsg:</span>");
1.157     albertel 6050:     } else {
1.200     albertel 6051: 	&scantron_put_line($scanlines,$scan_data,$which,$line,$skip);
1.157     albertel 6052: 	&scantron_putfile($scanlines,$scan_data);
                   6053:     }
                   6054: }
                   6055: 
1.423     albertel 6056: =pod
                   6057: 
                   6058: =item reset_skipping_status
                   6059: 
1.424     albertel 6060:    Forgets the current set of remember skipped scanlines (and thus
                   6061:    reverts back to considering all lines in the
                   6062:    scantron_skipped_<filename> file)
                   6063: 
1.423     albertel 6064: =cut
                   6065: 
1.200     albertel 6066: sub reset_skipping_status {
                   6067:     my ($scanlines,$scan_data)=&scantron_getfile();
                   6068:     &scan_data($scan_data,'remember_skipping',undef,1);
                   6069:     &scantron_putfile(undef,$scan_data);
                   6070: }
                   6071: 
1.423     albertel 6072: =pod
                   6073: 
                   6074: =item start_skipping
                   6075: 
1.424     albertel 6076:    Marks a scanline to be skipped. 
                   6077: 
1.423     albertel 6078: =cut
                   6079: 
1.376     albertel 6080: sub start_skipping {
1.200     albertel 6081:     my ($scan_data,$i)=@_;
                   6082:     my %remembered=split(':',&scan_data($scan_data,'remember_skipping'));
1.376     albertel 6083:     if ($env{'form.scantron_options_redo'} =~ /^redo_/) {
                   6084: 	$remembered{$i}=2;
                   6085:     } else {
                   6086: 	$remembered{$i}=1;
                   6087:     }
1.200     albertel 6088:     &scan_data($scan_data,'remember_skipping',join(':',%remembered));
                   6089: }
                   6090: 
1.423     albertel 6091: =pod
                   6092: 
                   6093: =item should_be_skipped
                   6094: 
1.424     albertel 6095:    Checks whether a scanline should be skipped.
                   6096: 
1.423     albertel 6097: =cut
                   6098: 
1.200     albertel 6099: sub should_be_skipped {
1.376     albertel 6100:     my ($scanlines,$scan_data,$i)=@_;
1.257     albertel 6101:     if ($env{'form.scantron_options_redo'} !~ /^redo_/) {
1.200     albertel 6102: 	# not redoing old skips
1.376     albertel 6103: 	if ($scanlines->{'skipped'}[$i]) { return 1; }
1.200     albertel 6104: 	return 0;
                   6105:     }
                   6106:     my %remembered=split(':',&scan_data($scan_data,'remember_skipping'));
1.376     albertel 6107: 
                   6108:     if (exists($remembered{$i}) && $remembered{$i} != 2 ) {
                   6109: 	return 0;
                   6110:     }
1.200     albertel 6111:     return 1;
                   6112: }
                   6113: 
1.423     albertel 6114: =pod
                   6115: 
                   6116: =item remember_current_skipped
                   6117: 
1.424     albertel 6118:    Discovers what scanlines are in the scantron_skipped_<filename>
                   6119:    file and remembers them into scan_data for later use.
                   6120: 
1.423     albertel 6121: =cut
                   6122: 
1.200     albertel 6123: sub remember_current_skipped {
                   6124:     my ($scanlines,$scan_data)=&scantron_getfile();
                   6125:     my %to_remember;
                   6126:     for (my $i=0;$i<=$scanlines->{'count'};$i++) {
                   6127: 	if ($scanlines->{'skipped'}[$i]) {
                   6128: 	    $to_remember{$i}=1;
                   6129: 	}
                   6130:     }
1.376     albertel 6131: 
1.200     albertel 6132:     &scan_data($scan_data,'remember_skipping',join(':',%to_remember));
                   6133:     &scantron_putfile(undef,$scan_data);
                   6134: }
                   6135: 
1.423     albertel 6136: =pod
                   6137: 
                   6138: =item check_for_error
                   6139: 
1.424     albertel 6140:     Checks if there was an error when attempting to remove a specific
                   6141:     scantron_.. bubble sheet data file. Prints out an error if
                   6142:     something went wrong.
                   6143: 
1.423     albertel 6144: =cut
                   6145: 
1.200     albertel 6146: sub check_for_error {
                   6147:     my ($r,$result)=@_;
                   6148:     if ($result ne 'ok' && $result ne 'not_found' ) {
1.492     albertel 6149: 	$r->print(&mt("An error occurred ([_1]) when trying to remove the existing corrections.",$result));
1.200     albertel 6150:     }
                   6151: }
1.157     albertel 6152: 
1.423     albertel 6153: =pod
                   6154: 
                   6155: =item scantron_warning_screen
                   6156: 
1.424     albertel 6157:    Interstitial screen to make sure the operator has selected the
                   6158:    correct options before we start the validation phase.
                   6159: 
1.423     albertel 6160: =cut
                   6161: 
1.203     albertel 6162: sub scantron_warning_screen {
                   6163:     my ($button_text)=@_;
1.257     albertel 6164:     my $title=&Apache::lonnet::gettitle($env{'form.selectpage'});
1.284     albertel 6165:     my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
1.373     albertel 6166:     my $CODElist;
1.284     albertel 6167:     if ($scantron_config{'CODElocation'} &&
                   6168: 	$scantron_config{'CODEstart'} &&
                   6169: 	$scantron_config{'CODElength'}) {
                   6170: 	$CODElist=$env{'form.scantron_CODElist'};
1.398     albertel 6171: 	if ($env{'form.scantron_CODElist'} eq '') { $CODElist='<span class="LC_warning">None</span>'; }
1.284     albertel 6172: 	$CODElist=
1.492     albertel 6173: 	    '<tr><td><b>'.&mt('List of CODES to validate against:').'</b></td><td><tt>'.
1.373     albertel 6174: 	    $env{'form.scantron_CODElist'}.'</tt></td></tr>';
1.284     albertel 6175:     }
1.492     albertel 6176:     return ('
1.203     albertel 6177: <p>
1.492     albertel 6178: <span class="LC_warning">
                   6179: '.&mt('Please double check the information below before clicking on \'[_1]\'',&mt($button_text)).'</span>
1.203     albertel 6180: </p>
                   6181: <table>
1.492     albertel 6182: <tr><td><b>'.&mt('Sequence to be Graded:').'</b></td><td>'.$title.'</td></tr>
                   6183: <tr><td><b>'.&mt('Data File that will be used:').'</b></td><td><tt>'.$env{'form.scantron_selectfile'}.'</tt></td></tr>
                   6184: '.$CODElist.'
1.203     albertel 6185: </table>
                   6186: <br />
1.492     albertel 6187: <p> '.&mt('If this information is correct, please click on \'[_1]\'.',&mt($button_text)).'</p>
                   6188: <p> '.&mt('If something is incorrect, please click the \'Grading Menu\' button to start over.').'</p>
1.203     albertel 6189: 
                   6190: <br />
1.492     albertel 6191: ');
1.203     albertel 6192: }
                   6193: 
1.423     albertel 6194: =pod
                   6195: 
                   6196: =item scantron_do_warning
                   6197: 
1.424     albertel 6198:    Check if the operator has picked something for all required
                   6199:    fields. Error out if something is missing.
                   6200: 
1.423     albertel 6201: =cut
                   6202: 
1.203     albertel 6203: sub scantron_do_warning {
1.608     www      6204:     my ($r,$symb)=@_;
1.203     albertel 6205:     if (!$symb) {return '';}
1.324     albertel 6206:     my $default_form_data=&defaultFormData($symb);
1.203     albertel 6207:     $r->print(&scantron_form_start().$default_form_data);
1.257     albertel 6208:     if ( $env{'form.selectpage'} eq '' ||
                   6209: 	 $env{'form.scantron_selectfile'} eq '' ||
                   6210: 	 $env{'form.scantron_format'} eq '' ) {
1.492     albertel 6211: 	$r->print("<p>".&mt('You have forgetten to specify some information. Please go Back and try again.')."</p>");
1.257     albertel 6212: 	if ( $env{'form.selectpage'} eq '') {
1.492     albertel 6213: 	    $r->print('<p><span class="LC_error">'.&mt('You have not selected a Sequence to grade').'</span></p>');
1.237     albertel 6214: 	} 
1.257     albertel 6215: 	if ( $env{'form.scantron_selectfile'} eq '') {
1.492     albertel 6216: 	    $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 6217: 	} 
1.257     albertel 6218: 	if ( $env{'form.scantron_format'} eq '') {
1.492     albertel 6219: 	    $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 6220: 	} 
                   6221:     } else {
1.265     www      6222: 	my $warning=&scantron_warning_screen('Grading: Validate Records');
1.492     albertel 6223: 	$r->print('
                   6224: '.$warning.'
                   6225: <input type="submit" name="submit" value="'.&mt('Grading: Validate Records').'" />
1.203     albertel 6226: <input type="hidden" name="command" value="scantron_validate" />
1.492     albertel 6227: ');
1.237     albertel 6228:     }
1.352     albertel 6229:     $r->print("</form><br />".&show_grading_menu_form($symb));
1.203     albertel 6230:     return '';
                   6231: }
                   6232: 
1.423     albertel 6233: =pod
                   6234: 
                   6235: =item scantron_form_start
                   6236: 
1.424     albertel 6237:     html hidden input for remembering all selected grading options
                   6238: 
1.423     albertel 6239: =cut
                   6240: 
1.203     albertel 6241: sub scantron_form_start {
                   6242:     my ($max_bubble)=@_;
                   6243:     my $result= <<SCANTRONFORM;
                   6244: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="scantronupload">
1.257     albertel 6245:   <input type="hidden" name="selectpage" value="$env{'form.selectpage'}" />
                   6246:   <input type="hidden" name="scantron_format" value="$env{'form.scantron_format'}" />
                   6247:   <input type="hidden" name="scantron_selectfile" value="$env{'form.scantron_selectfile'}" />
1.218     albertel 6248:   <input type="hidden" name="scantron_maxbubble" value="$max_bubble" />
1.257     albertel 6249:   <input type="hidden" name="scantron_CODElist" value="$env{'form.scantron_CODElist'}" />
                   6250:   <input type="hidden" name="scantron_CODEunique" value="$env{'form.scantron_CODEunique'}" />
                   6251:   <input type="hidden" name="scantron_options_redo" value="$env{'form.scantron_options_redo'}" />
                   6252:   <input type="hidden" name="scantron_options_ignore" value="$env{'form.scantron_options_ignore'}" />
1.331     albertel 6253:   <input type="hidden" name="scantron_options_hidden" value="$env{'form.scantron_options_hidden'}" />
1.203     albertel 6254: SCANTRONFORM
1.447     foxr     6255: 
                   6256:   my $line = 0;
                   6257:     while (defined($env{"form.scantron.bubblelines.$line"})) {
                   6258:        my $chunk =
                   6259: 	   '<input type="hidden" name="scantron.bubblelines.'.$line.'" value="'.$env{"form.scantron.bubblelines.$line"}.'" />'."\n";
1.448     foxr     6260:        $chunk .=
                   6261: 	   '<input type="hidden" name="scantron.first_bubble_line.'.$line.'" value="'.$env{"form.scantron.first_bubble_line.$line"}.'" />'."\n";
1.503     raeburn  6262:        $chunk .= 
                   6263:            '<input type="hidden" name="scantron.sub_bubblelines.'.$line.'" value="'.$env{"form.scantron.sub_bubblelines.$line"}.'" />'."\n";
1.504     raeburn  6264:        $chunk .=
                   6265:            '<input type="hidden" name="scantron.responsetype.'.$line.'" value="'.$env{"form.scantron.responsetype.$line"}.'" />'."\n";
1.447     foxr     6266:        $result .= $chunk;
                   6267:        $line++;
                   6268:    }
1.203     albertel 6269:     return $result;
                   6270: }
                   6271: 
1.423     albertel 6272: =pod
                   6273: 
                   6274: =item scantron_validate_file
                   6275: 
1.424     albertel 6276:     Dispatch routine for doing validation of a bubble sheet data file.
                   6277: 
                   6278:     Also processes any necessary information resets that need to
                   6279:     occur before validation begins (ignore previous corrections,
                   6280:     restarting the skipped records processing)
                   6281: 
1.423     albertel 6282: =cut
                   6283: 
1.157     albertel 6284: sub scantron_validate_file {
1.608     www      6285:     my ($r,$symb) = @_;
1.157     albertel 6286:     if (!$symb) {return '';}
1.324     albertel 6287:     my $default_form_data=&defaultFormData($symb);
1.200     albertel 6288:     
                   6289:     # do the detection of only doing skipped records first befroe we delete
1.424     albertel 6290:     # them when doing the corrections reset
1.257     albertel 6291:     if ($env{'form.scantron_options_redo'} ne 'redo_skipped_ready') {
1.200     albertel 6292: 	&reset_skipping_status();
                   6293:     }
1.257     albertel 6294:     if ($env{'form.scantron_options_redo'} eq 'redo_skipped') {
1.200     albertel 6295: 	&remember_current_skipped();
1.257     albertel 6296: 	$env{'form.scantron_options_redo'}='redo_skipped_ready';
1.200     albertel 6297:     }
                   6298: 
1.257     albertel 6299:     if ($env{'form.scantron_options_ignore'} eq 'ignore_corrections') {
1.200     albertel 6300: 	&check_for_error($r,&scantron_remove_file('corrected'));
                   6301: 	&check_for_error($r,&scantron_remove_file('skipped'));
                   6302: 	&check_for_error($r,&scantron_remove_scan_data());
1.257     albertel 6303: 	$env{'form.scantron_options_ignore'}='done';
1.192     albertel 6304:     }
1.200     albertel 6305: 
1.257     albertel 6306:     if ($env{'form.scantron_corrections'}) {
1.157     albertel 6307: 	&scantron_process_corrections($r);
                   6308:     }
1.503     raeburn  6309:     $r->print('<p>'.&mt('Gathering necessary information.').'</p>');$r->rflush();
1.157     albertel 6310:     #get the student pick code ready
                   6311:     $r->print(&Apache::loncommon::studentbrowser_javascript());
1.582     raeburn  6312:     my $nav_error;
                   6313:     my $max_bubble=&scantron_get_maxbubble(\$nav_error);
                   6314:     if ($nav_error) {
                   6315:         $r->print(&navmap_errormsg());
                   6316:         return '';
                   6317:     }
1.203     albertel 6318:     my $result=&scantron_form_start($max_bubble).$default_form_data;
1.157     albertel 6319:     $r->print($result);
                   6320:     
1.334     albertel 6321:     my @validate_phases=( 'sequence',
                   6322: 			  'ID',
1.157     albertel 6323: 			  'CODE',
                   6324: 			  'doublebubble',
                   6325: 			  'missingbubbles');
1.257     albertel 6326:     if (!$env{'form.validatepass'}) {
                   6327: 	$env{'form.validatepass'} = 0;
1.157     albertel 6328:     }
1.257     albertel 6329:     my $currentphase=$env{'form.validatepass'};
1.157     albertel 6330: 
1.448     foxr     6331: 
1.157     albertel 6332:     my $stop=0;
                   6333:     while (!$stop && $currentphase < scalar(@validate_phases)) {
1.503     raeburn  6334: 	$r->print(&mt('Validating '.$validate_phases[$currentphase]).'<br />');
1.157     albertel 6335: 	$r->rflush();
                   6336: 	my $which="scantron_validate_".$validate_phases[$currentphase];
                   6337: 	{
                   6338: 	    no strict 'refs';
                   6339: 	    ($stop,$currentphase)=&$which($r,$currentphase);
                   6340: 	}
                   6341:     }
                   6342:     if (!$stop) {
1.203     albertel 6343: 	my $warning=&scantron_warning_screen('Start Grading');
1.542     raeburn  6344: 	$r->print(&mt('Validation process complete.').'<br />'.
                   6345:                   $warning.
                   6346:                   &mt('Perform verification for each student after storage of submissions?').
                   6347:                   '&nbsp;<span class="LC_nobreak"><label>'.
                   6348:                   '<input type="radio" name="verifyrecord" value="1" />'.&mt('Yes').'</label>'.
                   6349:                   ('&nbsp;'x3).'<label>'.
                   6350:                   '<input type="radio" name="verifyrecord" value="0" checked="checked" />'.&mt('No').
                   6351:                   '</label></span><br />'.
                   6352:                   &mt('Grading will take longer if you use verification.').'<br />'.
1.572     www      6353:                   &mt("Alternatively, the 'Review bubblesheet data' utility (see grading menu) can be used for all students after grading is complete.").'<br /><br />'.
1.542     raeburn  6354:                   '<input type="submit" name="submit" value="'.&mt('Start Grading').'" />'.
                   6355:                   '<input type="hidden" name="command" value="scantron_process" />'."\n");
1.157     albertel 6356:     } else {
                   6357: 	$r->print('<input type="hidden" name="command" value="scantron_validate" />');
                   6358: 	$r->print("<input type='hidden' name='validatepass' value='".$currentphase."' />");
                   6359:     }
                   6360:     if ($stop) {
1.334     albertel 6361: 	if ($validate_phases[$currentphase] eq 'sequence') {
1.539     riegler  6362: 	    $r->print('<input type="submit" name="submit" value="'.&mt('Ignore').' &rarr; " />');
1.492     albertel 6363: 	    $r->print(' '.&mt('this error').' <br />');
1.334     albertel 6364: 
1.492     albertel 6365: 	    $r->print(" <p>".&mt("Or click the 'Grading Menu' button to start over.")."</p>");
1.334     albertel 6366: 	} else {
1.503     raeburn  6367:             if ($validate_phases[$currentphase] eq 'doublebubble' || $validate_phases[$currentphase] eq 'missingbubbles') {
1.539     riegler  6368: 	        $r->print('<input type="button" name="submitbutton" value="'.&mt('Continue').' &rarr;" onclick="javascript:verify_bubble_radio(this.form)" />');
1.503     raeburn  6369:             } else {
1.539     riegler  6370:                 $r->print('<input type="submit" name="submit" value="'.&mt('Continue').' &rarr;" />');
1.503     raeburn  6371:             }
1.492     albertel 6372: 	    $r->print(' '.&mt('using corrected info').' <br />');
                   6373: 	    $r->print("<input type='submit' value='".&mt("Skip")."' name='scantron_skip_record' />");
                   6374: 	    $r->print(" ".&mt("this scanline saving it for later."));
1.334     albertel 6375: 	}
1.157     albertel 6376:     }
1.352     albertel 6377:     $r->print(" </form><br />".&show_grading_menu_form($symb));
1.157     albertel 6378:     return '';
                   6379: }
                   6380: 
1.423     albertel 6381: 
                   6382: =pod
                   6383: 
                   6384: =item scantron_remove_file
                   6385: 
1.424     albertel 6386:    Removes the requested bubble sheet data file, makes sure that
                   6387:    scantron_original_<filename> is never removed
                   6388: 
                   6389: 
1.423     albertel 6390: =cut
                   6391: 
1.200     albertel 6392: sub scantron_remove_file {
1.192     albertel 6393:     my ($which)=@_;
1.257     albertel 6394:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   6395:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1.192     albertel 6396:     my $file='scantron_';
1.200     albertel 6397:     if ($which eq 'corrected' || $which eq 'skipped') {
                   6398: 	$file.=$which.'_';
1.192     albertel 6399:     } else {
                   6400: 	return 'refused';
                   6401:     }
1.257     albertel 6402:     $file.=$env{'form.scantron_selectfile'};
1.200     albertel 6403:     return &Apache::lonnet::removeuserfile($cname,$cdom,$file);
                   6404: }
                   6405: 
1.423     albertel 6406: 
                   6407: =pod
                   6408: 
                   6409: =item scantron_remove_scan_data
                   6410: 
1.424     albertel 6411:    Removes all scan_data correction for the requested bubble sheet
                   6412:    data file.  (In the case that both the are doing skipped records we need
                   6413:    to remember the old skipped lines for the time being so that element
                   6414:    persists for a while.)
                   6415: 
1.423     albertel 6416: =cut
                   6417: 
1.200     albertel 6418: sub scantron_remove_scan_data {
1.257     albertel 6419:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   6420:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1.192     albertel 6421:     my @keys=&Apache::lonnet::getkeys('nohist_scantrondata',$cdom,$cname);
                   6422:     my @todelete;
1.257     albertel 6423:     my $filename=$env{'form.scantron_selectfile'};
1.192     albertel 6424:     foreach my $key (@keys) {
                   6425: 	if ($key=~/^\Q$filename\E_/) {
1.257     albertel 6426: 	    if ($env{'form.scantron_options_redo'} eq 'redo_skipped_ready' &&
1.200     albertel 6427: 		$key=~/remember_skipping/) {
                   6428: 		next;
                   6429: 	    }
1.192     albertel 6430: 	    push(@todelete,$key);
                   6431: 	}
                   6432:     }
1.200     albertel 6433:     my $result;
1.192     albertel 6434:     if (@todelete) {
1.491     albertel 6435: 	$result = &Apache::lonnet::del('nohist_scantrondata',
                   6436: 				       \@todelete,$cdom,$cname);
                   6437:     } else {
                   6438: 	$result = 'ok';
1.192     albertel 6439:     }
                   6440:     return $result;
                   6441: }
                   6442: 
1.423     albertel 6443: 
                   6444: =pod
                   6445: 
                   6446: =item scantron_getfile
                   6447: 
1.424     albertel 6448:     Fetches the requested bubble sheet data file (all 3 versions), and
                   6449:     the scan_data hash
                   6450:   
                   6451:   Arguments:
                   6452:     None
                   6453: 
                   6454:   Returns:
                   6455:     2 hash references
                   6456: 
                   6457:      - first one has 
                   6458:          orig      -
                   6459:          corrected -
                   6460:          skipped   -  each of which points to an array ref of the specified
                   6461:                       file broken up into individual lines
                   6462:          count     - number of scanlines
                   6463:  
                   6464:      - second is the scan_data hash possible keys are
1.425     albertel 6465:        ($number refers to scanline numbered $number and thus the key affects
                   6466:         only that scanline
                   6467:         $bubline refers to the specific bubble line element and the aspects
                   6468:         refers to that specific bubble line element)
                   6469: 
                   6470:        $number.user - username:domain to use
                   6471:        $number.CODE_ignore_dup 
                   6472:                     - ignore the duplicate CODE error 
                   6473:        $number.useCODE
                   6474:                     - use the CODE in the scanline as is
                   6475:        $number.no_bubble.$bubline
                   6476:                     - it is valid that there is no bubbled in bubble
                   6477:                       at $number $bubline
                   6478:        remember_skipping
                   6479:                     - a frozen hash containing keys of $number and values
                   6480:                       of either 
                   6481:                         1 - we are on a 'do skipped records pass' and plan
                   6482:                             on processing this line
                   6483:                         2 - we are on a 'do skipped records pass' and this
                   6484:                             scanline has been marked to skip yet again
1.424     albertel 6485: 
1.423     albertel 6486: =cut
                   6487: 
1.157     albertel 6488: sub scantron_getfile {
1.200     albertel 6489:     #FIXME really would prefer a scantron directory
1.257     albertel 6490:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   6491:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1.157     albertel 6492:     my $lines;
                   6493:     $lines=&Apache::lonnet::getfile('/uploaded/'.$cdom.'/'.$cname.'/'.
1.257     albertel 6494: 		       'scantron_orig_'.$env{'form.scantron_selectfile'});
1.157     albertel 6495:     my %scanlines;
                   6496:     $scanlines{'orig'}=[(split("\n",$lines,-1))];
                   6497:     my $temp=$scanlines{'orig'};
                   6498:     $scanlines{'count'}=$#$temp;
                   6499: 
                   6500:     $lines=&Apache::lonnet::getfile('/uploaded/'.$cdom.'/'.$cname.'/'.
1.257     albertel 6501: 		       'scantron_corrected_'.$env{'form.scantron_selectfile'});
1.157     albertel 6502:     if ($lines eq '-1') {
                   6503: 	$scanlines{'corrected'}=[];
                   6504:     } else {
                   6505: 	$scanlines{'corrected'}=[(split("\n",$lines,-1))];
                   6506:     }
                   6507:     $lines=&Apache::lonnet::getfile('/uploaded/'.$cdom.'/'.$cname.'/'.
1.257     albertel 6508: 		       'scantron_skipped_'.$env{'form.scantron_selectfile'});
1.157     albertel 6509:     if ($lines eq '-1') {
                   6510: 	$scanlines{'skipped'}=[];
                   6511:     } else {
                   6512: 	$scanlines{'skipped'}=[(split("\n",$lines,-1))];
                   6513:     }
1.175     albertel 6514:     my @tmp=&Apache::lonnet::dump('nohist_scantrondata',$cdom,$cname);
1.157     albertel 6515:     if ($tmp[0] =~ /^(error:|no_such_host)/) { @tmp=(); }
                   6516:     my %scan_data = @tmp;
                   6517:     return (\%scanlines,\%scan_data);
                   6518: }
                   6519: 
1.423     albertel 6520: =pod
                   6521: 
                   6522: =item lonnet_putfile
                   6523: 
1.424     albertel 6524:    Wrapper routine to call &Apache::lonnet::finishuserfileupload
                   6525: 
                   6526:  Arguments:
                   6527:    $contents - data to store
                   6528:    $filename - filename to store $contents into
                   6529: 
                   6530:  Returns:
                   6531:    result value from &Apache::lonnet::finishuserfileupload
                   6532: 
1.423     albertel 6533: =cut
                   6534: 
1.157     albertel 6535: sub lonnet_putfile {
                   6536:     my ($contents,$filename)=@_;
1.257     albertel 6537:     my $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   6538:     my $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
                   6539:     $env{'form.sillywaytopassafilearound'}=$contents;
1.275     albertel 6540:     &Apache::lonnet::finishuserfileupload($docuname,$docudom,'sillywaytopassafilearound',$filename);
1.157     albertel 6541: 
                   6542: }
                   6543: 
1.423     albertel 6544: =pod
                   6545: 
                   6546: =item scantron_putfile
                   6547: 
1.424     albertel 6548:     Stores the current version of the bubble sheet data files, and the
                   6549:     scan_data hash. (Does not modify the original version only the
                   6550:     corrected and skipped versions.
                   6551: 
                   6552:  Arguments:
                   6553:     $scanlines - hash ref that looks like the first return value from
                   6554:                  &scantron_getfile()
                   6555:     $scan_data - hash ref that looks like the second return value from
                   6556:                  &scantron_getfile()
                   6557: 
1.423     albertel 6558: =cut
                   6559: 
1.157     albertel 6560: sub scantron_putfile {
                   6561:     my ($scanlines,$scan_data) = @_;
1.200     albertel 6562:     #FIXME really would prefer a scantron directory
1.257     albertel 6563:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   6564:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1.200     albertel 6565:     if ($scanlines) {
                   6566: 	my $prefix='scantron_';
1.157     albertel 6567: # no need to update orig, shouldn't change
                   6568: #   &lonnet_putfile(join("\n",@{$scanlines->{'orig'}}),$prefix.'orig_'.
1.257     albertel 6569: #		    $env{'form.scantron_selectfile'});
1.200     albertel 6570: 	&lonnet_putfile(join("\n",@{$scanlines->{'corrected'}}),
                   6571: 			$prefix.'corrected_'.
1.257     albertel 6572: 			$env{'form.scantron_selectfile'});
1.200     albertel 6573: 	&lonnet_putfile(join("\n",@{$scanlines->{'skipped'}}),
                   6574: 			$prefix.'skipped_'.
1.257     albertel 6575: 			$env{'form.scantron_selectfile'});
1.200     albertel 6576:     }
1.175     albertel 6577:     &Apache::lonnet::put('nohist_scantrondata',$scan_data,$cdom,$cname);
1.157     albertel 6578: }
                   6579: 
1.423     albertel 6580: =pod
                   6581: 
                   6582: =item scantron_get_line
                   6583: 
1.424     albertel 6584:    Returns the correct version of the scanline
                   6585: 
                   6586:  Arguments:
                   6587:     $scanlines - hash ref that looks like the first return value from
                   6588:                  &scantron_getfile()
                   6589:     $scan_data - hash ref that looks like the second return value from
                   6590:                  &scantron_getfile()
                   6591:     $i         - number of the requested line (starts at 0)
                   6592: 
                   6593:  Returns:
                   6594:    A scanline, (either the original or the corrected one if it
                   6595:    exists), or undef if the requested scanline should be
                   6596:    skipped. (Either because it's an skipped scanline, or it's an
                   6597:    unskipped scanline and we are not doing a 'do skipped scanlines'
                   6598:    pass.
                   6599: 
1.423     albertel 6600: =cut
                   6601: 
1.157     albertel 6602: sub scantron_get_line {
1.200     albertel 6603:     my ($scanlines,$scan_data,$i)=@_;
1.376     albertel 6604:     if (&should_be_skipped($scanlines,$scan_data,$i)) { return undef; }
                   6605:     #if ($scanlines->{'skipped'}[$i]) { return undef; }
1.157     albertel 6606:     if ($scanlines->{'corrected'}[$i]) {return $scanlines->{'corrected'}[$i];}
                   6607:     return $scanlines->{'orig'}[$i]; 
                   6608: }
                   6609: 
1.423     albertel 6610: =pod
                   6611: 
                   6612: =item scantron_todo_count
                   6613: 
1.424     albertel 6614:     Counts the number of scanlines that need processing.
                   6615: 
                   6616:  Arguments:
                   6617:     $scanlines - hash ref that looks like the first return value from
                   6618:                  &scantron_getfile()
                   6619:     $scan_data - hash ref that looks like the second return value from
                   6620:                  &scantron_getfile()
                   6621: 
                   6622:  Returns:
                   6623:     $count - number of scanlines to process
                   6624: 
1.423     albertel 6625: =cut
                   6626: 
1.200     albertel 6627: sub get_todo_count {
                   6628:     my ($scanlines,$scan_data)=@_;
                   6629:     my $count=0;
                   6630:     for (my $i=0;$i<=$scanlines->{'count'};$i++) {
                   6631: 	my $line=&scantron_get_line($scanlines,$scan_data,$i);
                   6632: 	if ($line=~/^[\s\cz]*$/) { next; }
                   6633: 	$count++;
                   6634:     }
                   6635:     return $count;
                   6636: }
                   6637: 
1.423     albertel 6638: =pod
                   6639: 
                   6640: =item scantron_put_line
                   6641: 
1.424     albertel 6642:     Updates the 'corrected' or 'skipped' versions of the bubble sheet
                   6643:     data file.
                   6644: 
                   6645:  Arguments:
                   6646:     $scanlines - hash ref that looks like the first return value from
                   6647:                  &scantron_getfile()
                   6648:     $scan_data - hash ref that looks like the second return value from
                   6649:                  &scantron_getfile()
                   6650:     $i         - line number to update
                   6651:     $newline   - contents of the updated scanline
                   6652:     $skip      - if true make the line for skipping and update the
                   6653:                  'skipped' file
                   6654: 
1.423     albertel 6655: =cut
                   6656: 
1.157     albertel 6657: sub scantron_put_line {
1.200     albertel 6658:     my ($scanlines,$scan_data,$i,$newline,$skip)=@_;
1.157     albertel 6659:     if ($skip) {
                   6660: 	$scanlines->{'skipped'}[$i]=$newline;
1.376     albertel 6661: 	&start_skipping($scan_data,$i);
1.157     albertel 6662: 	return;
                   6663:     }
                   6664:     $scanlines->{'corrected'}[$i]=$newline;
                   6665: }
                   6666: 
1.423     albertel 6667: =pod
                   6668: 
                   6669: =item scantron_clear_skip
                   6670: 
1.424     albertel 6671:    Remove a line from the 'skipped' file
                   6672: 
                   6673:  Arguments:
                   6674:     $scanlines - hash ref that looks like the first return value from
                   6675:                  &scantron_getfile()
                   6676:     $scan_data - hash ref that looks like the second return value from
                   6677:                  &scantron_getfile()
                   6678:     $i         - line number to update
                   6679: 
1.423     albertel 6680: =cut
                   6681: 
1.376     albertel 6682: sub scantron_clear_skip {
                   6683:     my ($scanlines,$scan_data,$i)=@_;
                   6684:     if (exists($scanlines->{'skipped'}[$i])) {
                   6685: 	undef($scanlines->{'skipped'}[$i]);
                   6686: 	return 1;
                   6687:     }
                   6688:     return 0;
                   6689: }
                   6690: 
1.423     albertel 6691: =pod
                   6692: 
                   6693: =item scantron_filter_not_exam
                   6694: 
1.424     albertel 6695:    Filter routine used by &Apache::lonnavmaps::retrieveResources(), to
                   6696:    filter out resources that are not marked as 'exam' mode
                   6697: 
1.423     albertel 6698: =cut
                   6699: 
1.334     albertel 6700: sub scantron_filter_not_exam {
                   6701:     my ($curres)=@_;
                   6702:     
                   6703:     if (ref($curres) && $curres->is_problem() && !$curres->is_exam()) {
                   6704: 	# if the user has asked to not have either hidden
                   6705: 	# or 'randomout' controlled resources to be graded
                   6706: 	# don't include them
                   6707: 	if ($env{'form.scantron_options_hidden'} eq 'ignore_hidden'
                   6708: 	    && $curres->randomout) {
                   6709: 	    return 0;
                   6710: 	}
                   6711: 	return 1;
                   6712:     }
                   6713:     return 0;
                   6714: }
                   6715: 
1.423     albertel 6716: =pod
                   6717: 
                   6718: =item scantron_validate_sequence
                   6719: 
1.424     albertel 6720:     Validates the selected sequence, checking for resource that are
                   6721:     not set to exam mode.
                   6722: 
1.423     albertel 6723: =cut
                   6724: 
1.334     albertel 6725: sub scantron_validate_sequence {
                   6726:     my ($r,$currentphase) = @_;
                   6727: 
                   6728:     my $navmap=Apache::lonnavmaps::navmap->new();
1.582     raeburn  6729:     unless (ref($navmap)) {
                   6730:         $r->print(&navmap_errormsg());
                   6731:         return (1,$currentphase);
                   6732:     }
1.334     albertel 6733:     my (undef,undef,$sequence)=
                   6734: 	&Apache::lonnet::decode_symb($env{'form.selectpage'});
                   6735: 
                   6736:     my $map=$navmap->getResourceByUrl($sequence);
                   6737: 
                   6738:     $r->print('<input type="hidden" name="validate_sequence_exam"
                   6739:                                     value="ignore" />');
                   6740:     if ($env{'form.validate_sequence_exam'} ne 'ignore') {
                   6741: 	my @resources=
                   6742: 	    $navmap->retrieveResources($map,\&scantron_filter_not_exam,1,0);
                   6743: 	if (@resources) {
1.357     banghart 6744: 	    $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 6745: 	    return (1,$currentphase);
                   6746: 	}
                   6747:     }
                   6748: 
                   6749:     return (0,$currentphase+1);
                   6750: }
                   6751: 
1.423     albertel 6752: 
                   6753: 
1.157     albertel 6754: sub scantron_validate_ID {
                   6755:     my ($r,$currentphase) = @_;
                   6756:     
                   6757:     #get student info
                   6758:     my $classlist=&Apache::loncoursedata::get_classlist();
                   6759:     my %idmap=&username_to_idmap($classlist);
                   6760: 
                   6761:     #get scantron line setup
1.257     albertel 6762:     my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
1.157     albertel 6763:     my ($scanlines,$scan_data)=&scantron_getfile();
1.582     raeburn  6764: 
                   6765:     my $nav_error;
                   6766:     &scantron_get_maxbubble(\$nav_error); # parse needs the bubble_lines.. array.
                   6767:     if ($nav_error) {
                   6768:         $r->print(&navmap_errormsg());
                   6769:         return(1,$currentphase);
                   6770:     }
1.157     albertel 6771: 
                   6772:     my %found=('ids'=>{},'usernames'=>{});
                   6773:     for (my $i=0;$i<=$scanlines->{'count'};$i++) {
1.200     albertel 6774: 	my $line=&scantron_get_line($scanlines,$scan_data,$i);
1.157     albertel 6775: 	if ($line=~/^[\s\cz]*$/) { next; }
                   6776: 	my $scan_record=&scantron_parse_scanline($line,$i,\%scantron_config,
                   6777: 						 $scan_data);
                   6778: 	my $id=$$scan_record{'scantron.ID'};
                   6779: 	my $found;
                   6780: 	foreach my $checkid (keys(%idmap)) {
                   6781: 	    if (lc($checkid) eq lc($id)) { $found=$checkid;last; }
                   6782: 	}
                   6783: 	if ($found) {
                   6784: 	    my $username=$idmap{$found};
                   6785: 	    if ($found{'ids'}{$found}) {
                   6786: 		&scantron_get_correction($r,$i,$scan_record,\%scantron_config,
                   6787: 					 $line,'duplicateID',$found);
1.194     albertel 6788: 		return(1,$currentphase);
1.157     albertel 6789: 	    } elsif ($found{'usernames'}{$username}) {
                   6790: 		&scantron_get_correction($r,$i,$scan_record,\%scantron_config,
                   6791: 					 $line,'duplicateID',$username);
1.194     albertel 6792: 		return(1,$currentphase);
1.157     albertel 6793: 	    }
1.186     albertel 6794: 	    #FIXME store away line we previously saw the ID on to use above
1.157     albertel 6795: 	    $found{'ids'}{$found}++;
                   6796: 	    $found{'usernames'}{$username}++;
                   6797: 	} else {
                   6798: 	    if ($id =~ /^\s*$/) {
1.158     albertel 6799: 		my $username=&scan_data($scan_data,"$i.user");
1.157     albertel 6800: 		if (defined($username) && $found{'usernames'}{$username}) {
                   6801: 		    &scantron_get_correction($r,$i,$scan_record,
                   6802: 					     \%scantron_config,
                   6803: 					     $line,'duplicateID',$username);
1.194     albertel 6804: 		    return(1,$currentphase);
1.157     albertel 6805: 		} elsif (!defined($username)) {
                   6806: 		    &scantron_get_correction($r,$i,$scan_record,
                   6807: 					     \%scantron_config,
                   6808: 					     $line,'incorrectID');
1.194     albertel 6809: 		    return(1,$currentphase);
1.157     albertel 6810: 		}
                   6811: 		$found{'usernames'}{$username}++;
                   6812: 	    } else {
                   6813: 		&scantron_get_correction($r,$i,$scan_record,\%scantron_config,
                   6814: 					 $line,'incorrectID');
1.194     albertel 6815: 		return(1,$currentphase);
1.157     albertel 6816: 	    }
                   6817: 	}
                   6818:     }
                   6819: 
                   6820:     return (0,$currentphase+1);
                   6821: }
                   6822: 
1.423     albertel 6823: 
1.157     albertel 6824: sub scantron_get_correction {
                   6825:     my ($r,$i,$scan_record,$scan_config,$line,$error,$arg)=@_;
1.454     banghart 6826: #FIXME in the case of a duplicated ID the previous line, probably need
1.157     albertel 6827: #to show both the current line and the previous one and allow skipping
                   6828: #the previous one or the current one
                   6829: 
1.333     albertel 6830:     if ( $$scan_record{'scantron.PaperID'} =~ /\S/) {
1.492     albertel 6831: 	$r->print("<p>".&mt("<b>An error was detected ($error)</b>".
                   6832: 			    " for PaperID <tt>[_1]</tt>",
                   6833: 			    $$scan_record{'scantron.PaperID'})."</p> \n");
1.157     albertel 6834:     } else {
1.492     albertel 6835: 	$r->print("<p>".&mt("<b>An error was detected ($error)</b>".
                   6836: 			    " in scanline [_1] <pre>[_2]</pre>",
                   6837: 			    $i,$line)."</p> \n");
                   6838:     }
                   6839:     my $message="<p>".&mt("The ID on the form is  <tt>[_1]</tt><br />".
                   6840: 			  "The name on the paper is [_2],[_3]",
                   6841: 			  $$scan_record{'scantron.ID'},
                   6842: 			  $$scan_record{'scantron.LastName'},
                   6843: 			  $$scan_record{'scantron.FirstName'})."</p>";
1.242     albertel 6844: 
1.157     albertel 6845:     $r->print('<input type="hidden" name="scantron_corrections" value="'.$error.'" />'."\n");
                   6846:     $r->print('<input type="hidden" name="scantron_line" value="'.$i.'" />'."\n");
1.503     raeburn  6847:                            # Array populated for doublebubble or
                   6848:     my @lines_to_correct;  # missingbubble errors to build javascript
                   6849:                            # to validate radio button checking   
                   6850: 
1.157     albertel 6851:     if ($error =~ /ID$/) {
1.186     albertel 6852: 	if ($error eq 'incorrectID') {
1.492     albertel 6853: 	    $r->print("<p>".&mt("The encoded ID is not in the classlist").
                   6854: 		      "</p>\n");
1.157     albertel 6855: 	} elsif ($error eq 'duplicateID') {
1.492     albertel 6856: 	    $r->print("<p>".&mt("The encoded ID has also been used by a previous paper [_1]",$arg)."</p>\n");
1.157     albertel 6857: 	}
1.242     albertel 6858: 	$r->print($message);
1.492     albertel 6859: 	$r->print("<p>".&mt("How should I handle this?")." <br /> \n");
1.157     albertel 6860: 	$r->print("\n<ul><li> ");
                   6861: 	#FIXME it would be nice if this sent back the user ID and
                   6862: 	#could do partial userID matches
                   6863: 	$r->print(&Apache::loncommon::selectstudent_link('scantronupload',
                   6864: 				       'scantron_username','scantron_domain'));
                   6865: 	$r->print(": <input type='text' name='scantron_username' value='' />");
                   6866: 	$r->print("\n@".
1.257     albertel 6867: 		 &Apache::loncommon::select_dom_form($env{'request.role.domain'},'scantron_domain'));
1.157     albertel 6868: 
                   6869: 	$r->print('</li>');
1.186     albertel 6870:     } elsif ($error =~ /CODE$/) {
                   6871: 	if ($error eq 'incorrectCODE') {
1.492     albertel 6872: 	    $r->print("<p>".&mt("The encoded CODE is not in the list of possible CODEs.")."</p>\n");
1.186     albertel 6873: 	} elsif ($error eq 'duplicateCODE') {
1.492     albertel 6874: 	    $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 6875: 	}
1.492     albertel 6876: 	$r->print("<p>".&mt("The CODE on the form is  <tt>'[_1]'</tt>",
                   6877: 			    $$scan_record{'scantron.CODE'})."<br />\n");
1.242     albertel 6878: 	$r->print($message);
1.492     albertel 6879: 	$r->print("<p>".&mt("How should I handle this?")." <br /> \n");
1.187     albertel 6880: 	$r->print("\n<br /> ");
1.194     albertel 6881: 	my $i=0;
1.273     albertel 6882: 	if ($error eq 'incorrectCODE' 
                   6883: 	    && $$scan_record{'scantron.CODE'}=~/\S/ ) {
1.194     albertel 6884: 	    my ($max,$closest)=&scantron_get_closely_matching_CODEs($arg,$$scan_record{'scantron.CODE'});
1.278     albertel 6885: 	    if ($closest > 0) {
                   6886: 		foreach my $testcode (@{$closest}) {
                   6887: 		    my $checked='';
1.569     bisitz   6888: 		    if (!$i) { $checked=' checked="checked"'; }
1.492     albertel 6889: 		    $r->print("
                   6890:    <label>
1.569     bisitz   6891:        <input type='radio' name='scantron_CODE_resolution' value='use_closest_$i'$checked />
1.492     albertel 6892:        ".&mt("Use the similar CODE [_1] instead.",
                   6893: 	    "<b><tt>".$testcode."</tt></b>")."
                   6894:     </label>
                   6895:     <input type='hidden' name='scantron_CODE_closest_$i' value='$testcode' />");
1.278     albertel 6896: 		    $r->print("\n<br />");
                   6897: 		    $i++;
                   6898: 		}
1.194     albertel 6899: 	    }
                   6900: 	}
1.273     albertel 6901: 	if ($$scan_record{'scantron.CODE'}=~/\S/ ) {
1.569     bisitz   6902: 	    my $checked; if (!$i) { $checked=' checked="checked"'; }
1.492     albertel 6903: 	    $r->print("
                   6904:     <label>
1.569     bisitz   6905:         <input type='radio' name='scantron_CODE_resolution' value='use_unfound'$checked />
1.492     albertel 6906:        ".&mt("Use the CODE [_1] that is was on the paper, ignoring the error.",
                   6907: 	     "<b><tt>".$$scan_record{'scantron.CODE'}."</tt></b>")."
                   6908:     </label>");
1.273     albertel 6909: 	    $r->print("\n<br />");
                   6910: 	}
1.194     albertel 6911: 
1.597     wenzelju 6912: 	$r->print(&Apache::lonhtmlcommon::scripttag(<<ENDSCRIPT));
1.188     albertel 6913: function change_radio(field) {
1.190     albertel 6914:     var slct=document.scantronupload.scantron_CODE_resolution;
1.188     albertel 6915:     var i;
                   6916:     for (i=0;i<slct.length;i++) {
                   6917:         if (slct[i].value==field) { slct[i].checked=true; }
                   6918:     }
                   6919: }
                   6920: ENDSCRIPT
1.187     albertel 6921: 	my $href="/adm/pickcode?".
1.359     www      6922: 	   "form=".&escape("scantronupload").
                   6923: 	   "&scantron_format=".&escape($env{'form.scantron_format'}).
                   6924: 	   "&scantron_CODElist=".&escape($env{'form.scantron_CODElist'}).
                   6925: 	   "&curCODE=".&escape($$scan_record{'scantron.CODE'}).
                   6926: 	   "&scantron_selectfile=".&escape($env{'form.scantron_selectfile'});
1.332     albertel 6927: 	if ($env{'form.scantron_CODElist'} =~ /\S/) { 
1.492     albertel 6928: 	    $r->print("
                   6929:     <label>
                   6930:        <input type='radio' name='scantron_CODE_resolution' value='use_found' />
                   6931:        ".&mt("[_1]Select[_2] a CODE from the list of all CODEs and use it.",
                   6932: 	     "<a target='_blank' href='$href'>","</a>")."
                   6933:     </label> 
1.558     bisitz   6934:     ".&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 6935: 	    $r->print("\n<br />");
                   6936: 	}
1.492     albertel 6937: 	$r->print("
                   6938:     <label>
                   6939:        <input type='radio' name='scantron_CODE_resolution' value='use_typed' />
                   6940:        ".&mt("Use [_1] as the CODE.",
                   6941: 	     "</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 6942: 	$r->print("\n<br /><br />");
1.157     albertel 6943:     } elsif ($error eq 'doublebubble') {
1.503     raeburn  6944: 	$r->print("<p>".&mt("There have been multiple bubbles scanned for some question(s)")."</p>\n");
1.497     foxr     6945: 
                   6946: 	# The form field scantron_questions is acutally a list of line numbers.
                   6947: 	# represented by this form so:
                   6948: 
                   6949: 	my $line_list = &questions_to_line_list($arg);
                   6950: 
1.157     albertel 6951: 	$r->print('<input type="hidden" name="scantron_questions" value="'.
1.497     foxr     6952: 		  $line_list.'" />');
1.242     albertel 6953: 	$r->print($message);
1.492     albertel 6954: 	$r->print("<p>".&mt("Please indicate which bubble should be used for grading")."</p>");
1.157     albertel 6955: 	foreach my $question (@{$arg}) {
1.503     raeburn  6956: 	    my @linenums = &prompt_for_corrections($r,$question,$scan_config,
                   6957:                                                    $scan_record, $error);
1.524     raeburn  6958:             push(@lines_to_correct,@linenums);
1.157     albertel 6959: 	}
1.503     raeburn  6960:         $r->print(&verify_bubbles_checked(@lines_to_correct));
1.157     albertel 6961:     } elsif ($error eq 'missingbubble') {
1.492     albertel 6962: 	$r->print("<p>".&mt("There have been <b>no</b> bubbles scanned for some question(s)")."</p>\n");
1.242     albertel 6963: 	$r->print($message);
1.492     albertel 6964: 	$r->print("<p>".&mt("Please indicate which bubble should be used for grading.")."</p>");
1.503     raeburn  6965: 	$r->print(&mt("Some questions have no scanned bubbles.")."\n");
1.497     foxr     6966: 
1.503     raeburn  6967: 	# The form field scantron_questions is actually a list of line numbers not
1.497     foxr     6968: 	# a list of question numbers. Therefore:
                   6969: 	#
                   6970: 	
                   6971: 	my $line_list = &questions_to_line_list($arg);
                   6972: 
1.157     albertel 6973: 	$r->print('<input type="hidden" name="scantron_questions" value="'.
1.497     foxr     6974: 		  $line_list.'" />');
1.157     albertel 6975: 	foreach my $question (@{$arg}) {
1.503     raeburn  6976: 	    my @linenums = &prompt_for_corrections($r,$question,$scan_config,
                   6977:                                                    $scan_record, $error);
1.524     raeburn  6978:             push(@lines_to_correct,@linenums);
1.157     albertel 6979: 	}
1.503     raeburn  6980:         $r->print(&verify_bubbles_checked(@lines_to_correct));
1.157     albertel 6981:     } else {
                   6982: 	$r->print("\n<ul>");
                   6983:     }
                   6984:     $r->print("\n</li></ul>");
1.497     foxr     6985: }
                   6986: 
1.503     raeburn  6987: sub verify_bubbles_checked {
                   6988:     my (@ansnums) = @_;
                   6989:     my $ansnumstr = join('","',@ansnums);
                   6990:     my $warning = &mt("A bubble or 'No bubble' selection has not been made for one or more lines.");
1.597     wenzelju 6991:     my $output = &Apache::lonhtmlcommon::scripttag((<<ENDSCRIPT));
1.503     raeburn  6992: function verify_bubble_radio(form) {
                   6993:     var ansnumArray = new Array ("$ansnumstr");
                   6994:     var need_bubble_count = 0;
                   6995:     for (var i=0; i<ansnumArray.length; i++) {
                   6996:         if (form.elements["scantron_correct_Q_"+ansnumArray[i]].length > 1) {
                   6997:             var bubble_picked = 0; 
                   6998:             for (var j=0; j<form.elements["scantron_correct_Q_"+ansnumArray[i]].length; j++) {
                   6999:                 if (form.elements["scantron_correct_Q_"+ansnumArray[i]][j].checked == true) {
                   7000:                     bubble_picked = 1;
                   7001:                 }
                   7002:             }
                   7003:             if (bubble_picked == 0) {
                   7004:                 need_bubble_count ++;
                   7005:             }
                   7006:         }
                   7007:     }
                   7008:     if (need_bubble_count) {
                   7009:         alert("$warning");
                   7010:         return;
                   7011:     }
                   7012:     form.submit(); 
                   7013: }
                   7014: ENDSCRIPT
                   7015:     return $output;
                   7016: }
                   7017: 
1.497     foxr     7018: =pod
                   7019: 
                   7020: =item  questions_to_line_list
1.157     albertel 7021: 
1.497     foxr     7022: Converts a list of questions into a string of comma separated
                   7023: line numbers in the answer sheet used by the questions.  This is
                   7024: used to fill in the scantron_questions form field.
                   7025: 
                   7026:   Arguments:
                   7027:      questions    - Reference to an array of questions.
                   7028: 
                   7029: =cut
                   7030: 
                   7031: 
                   7032: sub questions_to_line_list {
                   7033:     my ($questions) = @_;
                   7034:     my @lines;
                   7035: 
1.503     raeburn  7036:     foreach my $item (@{$questions}) {
                   7037:         my $question = $item;
                   7038:         my ($first,$count,$last);
                   7039:         if ($item =~ /^(\d+)\.(\d+)$/) {
                   7040:             $question = $1;
                   7041:             my $subquestion = $2;
                   7042:             $first = $first_bubble_line{$question-1} + 1;
                   7043:             my @subans = split(/,/,$subdivided_bubble_lines{$question-1});
                   7044:             my $subcount = 1;
                   7045:             while ($subcount<$subquestion) {
                   7046:                 $first += $subans[$subcount-1];
                   7047:                 $subcount ++;
                   7048:             }
                   7049:             $count = $subans[$subquestion-1];
                   7050:         } else {
                   7051: 	    $first   = $first_bubble_line{$question-1} + 1;
                   7052: 	    $count   = $bubble_lines_per_response{$question-1};
                   7053:         }
1.506     raeburn  7054:         $last = $first+$count-1;
1.503     raeburn  7055:         push(@lines, ($first..$last));
1.497     foxr     7056:     }
                   7057:     return join(',', @lines);
                   7058: }
                   7059: 
                   7060: =pod 
                   7061: 
                   7062: =item prompt_for_corrections
                   7063: 
                   7064: Prompts for a potentially multiline correction to the
                   7065: user's bubbling (factors out common code from scantron_get_correction
                   7066: for multi and missing bubble cases).
                   7067: 
                   7068:  Arguments:
                   7069:    $r           - Apache request object.
                   7070:    $question    - The question number to prompt for.
                   7071:    $scan_config - The scantron file configuration hash.
                   7072:    $scan_record - Reference to the hash that has the the parsed scanlines.
1.503     raeburn  7073:    $error       - Type of error
1.497     foxr     7074: 
                   7075:  Implicit inputs:
                   7076:    %bubble_lines_per_response   - Starting line numbers for each question.
                   7077:                                   Numbered from 0 (but question numbers are from
                   7078:                                   1.
                   7079:    %first_bubble_line           - Starting bubble line for each question.
1.509     raeburn  7080:    %subdivided_bubble_lines     - optionresponse, matchresponse and rankresponse 
                   7081:                                   type problems render as separate sub-questions, 
1.503     raeburn  7082:                                   in exam mode. This hash contains a 
                   7083:                                   comma-separated list of the lines per 
                   7084:                                   sub-question.
1.510     raeburn  7085:    %responsetype_per_response   - essayresponse, formularesponse,
                   7086:                                   stringresponse, imageresponse, reactionresponse,
                   7087:                                   and organicresponse type problem parts can have
1.503     raeburn  7088:                                   multiple lines per response if the weight
                   7089:                                   assigned exceeds 10.  In this case, only
                   7090:                                   one bubble per line is permitted, but more 
                   7091:                                   than one line might contain bubbles, e.g.
                   7092:                                   bubbling of: line 1 - J, line 2 - J, 
                   7093:                                   line 3 - B would assign 22 points.  
1.497     foxr     7094: 
                   7095: =cut
                   7096: 
                   7097: sub prompt_for_corrections {
1.503     raeburn  7098:     my ($r, $question, $scan_config, $scan_record, $error) = @_;
                   7099:     my ($current_line,$lines);
                   7100:     my @linenums;
                   7101:     my $questionnum = $question;
                   7102:     if ($question =~ /^(\d+)\.(\d+)$/) {
                   7103:         $question = $1;
                   7104:         $current_line = $first_bubble_line{$question-1} + 1 ;
                   7105:         my $subquestion = $2;
                   7106:         my @subans = split(/,/,$subdivided_bubble_lines{$question-1});
                   7107:         my $subcount = 1;
                   7108:         while ($subcount<$subquestion) {
                   7109:             $current_line += $subans[$subcount-1];
                   7110:             $subcount ++;
                   7111:         }
                   7112:         $lines = $subans[$subquestion-1];
                   7113:     } else {
                   7114:         $current_line = $first_bubble_line{$question-1} + 1 ;
                   7115:         $lines        = $bubble_lines_per_response{$question-1};
                   7116:     }
1.497     foxr     7117:     if ($lines > 1) {
1.503     raeburn  7118:         $r->print(&mt('The group of bubble lines below responds to a single question.').'<br />');
                   7119:         if (($responsetype_per_response{$question-1} eq 'essayresponse') ||
                   7120:             ($responsetype_per_response{$question-1} eq 'formularesponse') ||
1.510     raeburn  7121:             ($responsetype_per_response{$question-1} eq 'stringresponse') ||
                   7122:             ($responsetype_per_response{$question-1} eq 'imageresponse') ||
                   7123:             ($responsetype_per_response{$question-1} eq 'reactionresponse') ||
                   7124:             ($responsetype_per_response{$question-1} eq 'organicresponse')) {
1.572     www      7125:             $r->print(&mt("Although this particular question type requires handgrading, the instructions for this question in the exam directed students to leave [quant,_1,line] blank on their bubblesheets.",$lines).'<br /><br />'.&mt('A non-zero score can be assigned to the student during bubblesheet grading by selecting a bubble in at least one line.').'<br />'.&mt('The score for this question will be a sum of the numeric values for the selected bubbles from each line, where A=1 point, B=2 points etc.').'<br />'.&mt("To assign a score of zero for this question, mark all lines as 'No bubble'.").'<br /><br />');
1.503     raeburn  7126:         } else {
                   7127:             $r->print(&mt("Select at most one bubble in a single line and select 'No Bubble' in all the other lines. ")."<br />");
                   7128:         }
1.497     foxr     7129:     }
                   7130:     for (my $i =0; $i < $lines; $i++) {
1.503     raeburn  7131:         my $selected = $$scan_record{"scantron.$current_line.answer"};
                   7132: 	&scantron_bubble_selector($r,$scan_config,$current_line, 
                   7133: 	        		  $questionnum,$error,split('', $selected));
1.524     raeburn  7134:         push(@linenums,$current_line);
1.497     foxr     7135: 	$current_line++;
                   7136:     }
                   7137:     if ($lines > 1) {
                   7138: 	$r->print("<hr /><br />");
                   7139:     }
1.503     raeburn  7140:     return @linenums;
1.157     albertel 7141: }
1.423     albertel 7142: 
                   7143: =pod
                   7144: 
                   7145: =item scantron_bubble_selector
                   7146:   
                   7147:    Generates the html radiobuttons to correct a single bubble line
1.424     albertel 7148:    possibly showing the existing the selected bubbles if known
1.423     albertel 7149: 
                   7150:  Arguments:
                   7151:     $r           - Apache request object
                   7152:     $scan_config - hash from &get_scantron_config()
1.497     foxr     7153:     $line        - Number of the line being displayed.
1.503     raeburn  7154:     $questionnum - Question number (may include subquestion)
                   7155:     $error       - Type of error.
1.497     foxr     7156:     @selected    - Array of bubbles picked on this line.
1.423     albertel 7157: 
                   7158: =cut
                   7159: 
1.157     albertel 7160: sub scantron_bubble_selector {
1.503     raeburn  7161:     my ($r,$scan_config,$line,$questionnum,$error,@selected)=@_;
1.157     albertel 7162:     my $max=$$scan_config{'Qlength'};
1.274     albertel 7163: 
                   7164:     my $scmode=$$scan_config{'Qon'};
                   7165:     if ($scmode eq 'number' || $scmode eq 'letter') { $max=10; }	     
                   7166: 
1.157     albertel 7167:     my @alphabet=('A'..'Z');
1.503     raeburn  7168:     $r->print(&Apache::loncommon::start_data_table().
                   7169:               &Apache::loncommon::start_data_table_row());
                   7170:     $r->print('<td rowspan="2" class="LC_leftcol_header">'.$line.'</td>');
1.497     foxr     7171:     for (my $i=0;$i<$max+1;$i++) {
                   7172: 	$r->print("\n".'<td align="center">');
                   7173: 	if ($selected[0] eq $alphabet[$i]) { $r->print('X'); shift(@selected) }
                   7174: 	else { $r->print('&nbsp;'); }
                   7175: 	$r->print('</td>');
                   7176:     }
1.503     raeburn  7177:     $r->print(&Apache::loncommon::end_data_table_row().
                   7178:               &Apache::loncommon::start_data_table_row());
1.497     foxr     7179:     for (my $i=0;$i<$max;$i++) {
                   7180: 	$r->print("\n".
                   7181: 		  '<td><label><input type="radio" name="scantron_correct_Q_'.
                   7182: 		  $line.'" value="'.$i.'" />'.$alphabet[$i]."</label></td>");
                   7183:     }
1.503     raeburn  7184:     my $nobub_checked = ' ';
                   7185:     if ($error eq 'missingbubble') {
                   7186:         $nobub_checked = ' checked = "checked" ';
                   7187:     }
                   7188:     $r->print("\n".'<td><label><input type="radio" name="scantron_correct_Q_'.
                   7189: 	      $line.'" value="none"'.$nobub_checked.'/>'.&mt('No bubble').
                   7190:               '</label>'."\n".'<input type="hidden" name="scantron_questionnum_Q_'.
                   7191:               $line.'" value="'.$questionnum.'" /></td>');
                   7192:     $r->print(&Apache::loncommon::end_data_table_row().
                   7193:               &Apache::loncommon::end_data_table());
1.157     albertel 7194: }
                   7195: 
1.423     albertel 7196: =pod
                   7197: 
                   7198: =item num_matches
                   7199: 
1.424     albertel 7200:    Counts the number of characters that are the same between the two arguments.
                   7201: 
                   7202:  Arguments:
                   7203:    $orig - CODE from the scanline
                   7204:    $code - CODE to match against
                   7205: 
                   7206:  Returns:
                   7207:    $count - integer count of the number of same characters between the
                   7208:             two arguments
                   7209: 
1.423     albertel 7210: =cut
                   7211: 
1.194     albertel 7212: sub num_matches {
                   7213:     my ($orig,$code) = @_;
                   7214:     my @code=split(//,$code);
                   7215:     my @orig=split(//,$orig);
                   7216:     my $same=0;
                   7217:     for (my $i=0;$i<scalar(@code);$i++) {
                   7218: 	if ($code[$i] eq $orig[$i]) { $same++; }
                   7219:     }
                   7220:     return $same;
                   7221: }
                   7222: 
1.423     albertel 7223: =pod
                   7224: 
                   7225: =item scantron_get_closely_matching_CODEs
                   7226: 
1.424     albertel 7227:    Cycles through all CODEs and finds the set that has the greatest
                   7228:    number of same characters as the provided CODE
                   7229: 
                   7230:  Arguments:
                   7231:    $allcodes - hash ref returned by &get_codes()
                   7232:    $CODE     - CODE from the current scanline
                   7233: 
                   7234:  Returns:
                   7235:    2 element list
                   7236:     - first elements is number of how closely matching the best fit is 
                   7237:       (5 means best set has 5 matching characters)
                   7238:     - second element is an arrary ref containing the set of valid CODEs
                   7239:       that best fit the passed in CODE
                   7240: 
1.423     albertel 7241: =cut
                   7242: 
1.194     albertel 7243: sub scantron_get_closely_matching_CODEs {
                   7244:     my ($allcodes,$CODE)=@_;
                   7245:     my @CODEs;
                   7246:     foreach my $testcode (sort(keys(%{$allcodes}))) {
                   7247: 	push(@{$CODEs[&num_matches($CODE,$testcode)]},$testcode);
                   7248:     }
                   7249: 
                   7250:     return ($#CODEs,$CODEs[-1]);
                   7251: }
                   7252: 
1.423     albertel 7253: =pod
                   7254: 
                   7255: =item get_codes
                   7256: 
1.424     albertel 7257:    Builds a hash which has keys of all of the valid CODEs from the selected
                   7258:    set of remembered CODEs.
                   7259: 
                   7260:  Arguments:
                   7261:   $old_name - name of the set of remembered CODEs
                   7262:   $cdom     - domain of the course
                   7263:   $cnum     - internal course name
                   7264: 
                   7265:  Returns:
                   7266:   %allcodes - keys are the valid CODEs, values are all 1
                   7267: 
1.423     albertel 7268: =cut
                   7269: 
1.194     albertel 7270: sub get_codes {
1.280     foxr     7271:     my ($old_name, $cdom, $cnum) = @_;
                   7272:     if (!$old_name) {
                   7273: 	$old_name=$env{'form.scantron_CODElist'};
                   7274:     }
                   7275:     if (!$cdom) {
                   7276: 	$cdom =$env{'course.'.$env{'request.course.id'}.'.domain'};
                   7277:     }
                   7278:     if (!$cnum) {
                   7279: 	$cnum =$env{'course.'.$env{'request.course.id'}.'.num'};
                   7280:     }
1.278     albertel 7281:     my %result=&Apache::lonnet::get('CODEs',[$old_name,"type\0$old_name"],
                   7282: 				    $cdom,$cnum);
                   7283:     my %allcodes;
                   7284:     if ($result{"type\0$old_name"} eq 'number') {
                   7285: 	%allcodes=map {($_,1)} split(',',$result{$old_name});
                   7286:     } else {
                   7287: 	%allcodes=map {(&Apache::lonprintout::num_to_letters($_),1)} split(',',$result{$old_name});
                   7288:     }
1.194     albertel 7289:     return %allcodes;
                   7290: }
                   7291: 
1.423     albertel 7292: =pod
                   7293: 
                   7294: =item scantron_validate_CODE
                   7295: 
1.424     albertel 7296:    Validates all scanlines in the selected file to not have any
                   7297:    invalid or underspecified CODEs and that none of the codes are
                   7298:    duplicated if this was requested.
                   7299: 
1.423     albertel 7300: =cut
                   7301: 
1.157     albertel 7302: sub scantron_validate_CODE {
                   7303:     my ($r,$currentphase) = @_;
1.257     albertel 7304:     my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
1.186     albertel 7305:     if ($scantron_config{'CODElocation'} &&
                   7306: 	$scantron_config{'CODEstart'} &&
                   7307: 	$scantron_config{'CODElength'}) {
1.257     albertel 7308: 	if (!defined($env{'form.scantron_CODElist'})) {
1.186     albertel 7309: 	    &FIXME_blow_up()
                   7310: 	}
                   7311:     } else {
                   7312: 	return (0,$currentphase+1);
                   7313:     }
                   7314:     
                   7315:     my %usedCODEs;
                   7316: 
1.194     albertel 7317:     my %allcodes=&get_codes();
1.186     albertel 7318: 
1.582     raeburn  7319:     my $nav_error;
                   7320:     &scantron_get_maxbubble(\$nav_error); # parse needs the lines per response array.
                   7321:     if ($nav_error) {
                   7322:         $r->print(&navmap_errormsg());
                   7323:         return(1,$currentphase);
                   7324:     }
1.447     foxr     7325: 
1.186     albertel 7326:     my ($scanlines,$scan_data)=&scantron_getfile();
                   7327:     for (my $i=0;$i<=$scanlines->{'count'};$i++) {
1.200     albertel 7328: 	my $line=&scantron_get_line($scanlines,$scan_data,$i);
1.186     albertel 7329: 	if ($line=~/^[\s\cz]*$/) { next; }
                   7330: 	my $scan_record=&scantron_parse_scanline($line,$i,\%scantron_config,
                   7331: 						 $scan_data);
                   7332: 	my $CODE=$$scan_record{'scantron.CODE'};
                   7333: 	my $error=0;
1.224     albertel 7334: 	if (!&Apache::lonnet::validCODE($CODE)) {
                   7335: 	    &scantron_get_correction($r,$i,$scan_record,
                   7336: 				     \%scantron_config,
                   7337: 				     $line,'incorrectCODE',\%allcodes);
                   7338: 	    return(1,$currentphase);
                   7339: 	}
1.221     albertel 7340: 	if (%allcodes && !exists($allcodes{$CODE}) 
                   7341: 	    && !$$scan_record{'scantron.useCODE'}) {
1.186     albertel 7342: 	    &scantron_get_correction($r,$i,$scan_record,
                   7343: 				     \%scantron_config,
1.194     albertel 7344: 				     $line,'incorrectCODE',\%allcodes);
                   7345: 	    return(1,$currentphase);
1.186     albertel 7346: 	}
1.214     albertel 7347: 	if (exists($usedCODEs{$CODE}) 
1.257     albertel 7348: 	    && $env{'form.scantron_CODEunique'} eq 'yes'
1.192     albertel 7349: 	    && !$$scan_record{'scantron.CODE_ignore_dup'}) {
1.186     albertel 7350: 	    &scantron_get_correction($r,$i,$scan_record,
                   7351: 				     \%scantron_config,
1.194     albertel 7352: 				     $line,'duplicateCODE',$usedCODEs{$CODE});
                   7353: 	    return(1,$currentphase);
1.186     albertel 7354: 	}
1.524     raeburn  7355: 	push(@{$usedCODEs{$CODE}},$$scan_record{'scantron.PaperID'});
1.186     albertel 7356:     }
1.157     albertel 7357:     return (0,$currentphase+1);
                   7358: }
                   7359: 
1.423     albertel 7360: =pod
                   7361: 
                   7362: =item scantron_validate_doublebubble
                   7363: 
1.424     albertel 7364:    Validates all scanlines in the selected file to not have any
                   7365:    bubble lines with multiple bubbles marked.
                   7366: 
1.423     albertel 7367: =cut
                   7368: 
1.157     albertel 7369: sub scantron_validate_doublebubble {
                   7370:     my ($r,$currentphase) = @_;
                   7371:     #get student info
                   7372:     my $classlist=&Apache::loncoursedata::get_classlist();
                   7373:     my %idmap=&username_to_idmap($classlist);
                   7374: 
                   7375:     #get scantron line setup
1.257     albertel 7376:     my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
1.157     albertel 7377:     my ($scanlines,$scan_data)=&scantron_getfile();
1.583     raeburn  7378:     my $nav_error;
                   7379:     &scantron_get_maxbubble(\$nav_error); # parse needs the bubble line array.
                   7380:     if ($nav_error) {
                   7381:         $r->print(&navmap_errormsg());
                   7382:         return(1,$currentphase);
                   7383:     }
1.447     foxr     7384: 
1.157     albertel 7385:     for (my $i=0;$i<=$scanlines->{'count'};$i++) {
1.200     albertel 7386: 	my $line=&scantron_get_line($scanlines,$scan_data,$i);
1.157     albertel 7387: 	if ($line=~/^[\s\cz]*$/) { next; }
                   7388: 	my $scan_record=&scantron_parse_scanline($line,$i,\%scantron_config,
                   7389: 						 $scan_data);
                   7390: 	if (!defined($$scan_record{'scantron.doubleerror'})) { next; }
                   7391: 	&scantron_get_correction($r,$i,$scan_record,\%scantron_config,$line,
                   7392: 				 'doublebubble',
                   7393: 				 $$scan_record{'scantron.doubleerror'});
                   7394:     	return (1,$currentphase);
                   7395:     }
                   7396:     return (0,$currentphase+1);
                   7397: }
                   7398: 
1.423     albertel 7399: 
1.503     raeburn  7400: sub scantron_get_maxbubble {
1.582     raeburn  7401:     my ($nav_error) = @_;
1.257     albertel 7402:     if (defined($env{'form.scantron_maxbubble'}) &&
                   7403: 	$env{'form.scantron_maxbubble'}) {
1.447     foxr     7404: 	&restore_bubble_lines();
1.257     albertel 7405: 	return $env{'form.scantron_maxbubble'};
1.191     albertel 7406:     }
1.330     albertel 7407: 
1.447     foxr     7408:     my (undef, undef, $sequence) =
1.257     albertel 7409: 	&Apache::lonnet::decode_symb($env{'form.selectpage'});
1.330     albertel 7410: 
1.447     foxr     7411:     my $navmap=Apache::lonnavmaps::navmap->new();
1.582     raeburn  7412:     unless (ref($navmap)) {
                   7413:         if (ref($nav_error)) {
                   7414:             $$nav_error = 1;
                   7415:         }
1.591     raeburn  7416:         return;
1.582     raeburn  7417:     }
1.191     albertel 7418:     my $map=$navmap->getResourceByUrl($sequence);
                   7419:     my @resources=$navmap->retrieveResources($map,\&scantron_filter,1,0);
1.330     albertel 7420: 
                   7421:     &Apache::lonxml::clear_problem_counter();
                   7422: 
1.557     raeburn  7423:     my $uname       = $env{'user.name'};
                   7424:     my $udom        = $env{'user.domain'};
1.435     foxr     7425:     my $cid         = $env{'request.course.id'};
                   7426:     my $total_lines = 0;
                   7427:     %bubble_lines_per_response = ();
1.447     foxr     7428:     %first_bubble_line         = ();
1.503     raeburn  7429:     %subdivided_bubble_lines   = ();
                   7430:     %responsetype_per_response = ();
1.554     raeburn  7431: 
1.447     foxr     7432:     my $response_number = 0;
                   7433:     my $bubble_line     = 0;
1.191     albertel 7434:     foreach my $resource (@resources) {
1.542     raeburn  7435:         my ($analysis,$parts) = &scantron_partids_tograde($resource,$cid,$uname,$udom);
                   7436:         if ((ref($analysis) eq 'HASH') && (ref($parts) eq 'ARRAY')) {
                   7437: 	    foreach my $part_id (@{$parts}) {
                   7438:                 my $lines;
                   7439: 
                   7440: 	        # TODO - make this a persistent hash not an array.
                   7441: 
                   7442:                 # optionresponse, matchresponse and rankresponse type items 
                   7443:                 # render as separate sub-questions in exam mode.
                   7444:                 if (($analysis->{$part_id.'.type'} eq 'optionresponse') ||
                   7445:                     ($analysis->{$part_id.'.type'} eq 'matchresponse') ||
                   7446:                     ($analysis->{$part_id.'.type'} eq 'rankresponse')) {
                   7447:                     my ($numbub,$numshown);
                   7448:                     if ($analysis->{$part_id.'.type'} eq 'optionresponse') {
                   7449:                         if (ref($analysis->{$part_id.'.options'}) eq 'ARRAY') {
                   7450:                             $numbub = scalar(@{$analysis->{$part_id.'.options'}});
                   7451:                         }
                   7452:                     } elsif ($analysis->{$part_id.'.type'} eq 'matchresponse') {
                   7453:                         if (ref($analysis->{$part_id.'.items'}) eq 'ARRAY') {
                   7454:                             $numbub = scalar(@{$analysis->{$part_id.'.items'}});
                   7455:                         }
                   7456:                     } elsif ($analysis->{$part_id.'.type'} eq 'rankresponse') {
                   7457:                         if (ref($analysis->{$part_id.'.foils'}) eq 'ARRAY') {
                   7458:                             $numbub = scalar(@{$analysis->{$part_id.'.foils'}});
                   7459:                         }
                   7460:                     }
                   7461:                     if (ref($analysis->{$part_id.'.shown'}) eq 'ARRAY') {
                   7462:                         $numshown = scalar(@{$analysis->{$part_id.'.shown'}});
                   7463:                     }
                   7464:                     my $bubbles_per_line = 10;
                   7465:                     my $inner_bubble_lines = int($numbub/$bubbles_per_line);
                   7466:                     if (($numbub % $bubbles_per_line) != 0) {
                   7467:                         $inner_bubble_lines++;
                   7468:                     }
                   7469:                     for (my $i=0; $i<$numshown; $i++) {
                   7470:                         $subdivided_bubble_lines{$response_number} .= 
                   7471:                             $inner_bubble_lines.',';
                   7472:                     }
                   7473:                     $subdivided_bubble_lines{$response_number} =~ s/,$//;
                   7474:                     $lines = $numshown * $inner_bubble_lines;
                   7475:                 } else {
                   7476:                     $lines = $analysis->{"$part_id.bubble_lines"};
                   7477:                 } 
                   7478: 
                   7479:                 $first_bubble_line{$response_number} = $bubble_line;
                   7480: 	        $bubble_lines_per_response{$response_number} = $lines;
                   7481:                 $responsetype_per_response{$response_number} = 
                   7482:                     $analysis->{$part_id.'.type'};
                   7483: 	        $response_number++;
                   7484: 
                   7485: 	        $bubble_line +=  $lines;
                   7486: 	        $total_lines +=  $lines;
                   7487: 	    }
                   7488:         }
                   7489:     }
1.552     raeburn  7490:     &Apache::lonnet::delenv('scantron.');
1.542     raeburn  7491: 
                   7492:     &save_bubble_lines();
                   7493:     $env{'form.scantron_maxbubble'} =
                   7494: 	$total_lines;
                   7495:     return $env{'form.scantron_maxbubble'};
                   7496: }
1.523     raeburn  7497: 
1.157     albertel 7498: sub scantron_validate_missingbubbles {
                   7499:     my ($r,$currentphase) = @_;
                   7500:     #get student info
                   7501:     my $classlist=&Apache::loncoursedata::get_classlist();
                   7502:     my %idmap=&username_to_idmap($classlist);
                   7503: 
                   7504:     #get scantron line setup
1.257     albertel 7505:     my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
1.157     albertel 7506:     my ($scanlines,$scan_data)=&scantron_getfile();
1.582     raeburn  7507:     my $nav_error;
                   7508:     my $max_bubble=&scantron_get_maxbubble(\$nav_error);
                   7509:     if ($nav_error) {
                   7510:         return(1,$currentphase);
                   7511:     }
1.157     albertel 7512:     if (!$max_bubble) { $max_bubble=2**31; }
                   7513:     for (my $i=0;$i<=$scanlines->{'count'};$i++) {
1.200     albertel 7514: 	my $line=&scantron_get_line($scanlines,$scan_data,$i);
1.157     albertel 7515: 	if ($line=~/^[\s\cz]*$/) { next; }
                   7516: 	my $scan_record=&scantron_parse_scanline($line,$i,\%scantron_config,
                   7517: 						 $scan_data);
                   7518: 	if (!defined($$scan_record{'scantron.missingerror'})) { next; }
                   7519: 	my @to_correct;
1.470     foxr     7520: 	
                   7521: 	# Probably here's where the error is...
                   7522: 
1.157     albertel 7523: 	foreach my $missing (@{$$scan_record{'scantron.missingerror'}}) {
1.505     raeburn  7524:             my $lastbubble;
                   7525:             if ($missing =~ /^(\d+)\.(\d+)$/) {
                   7526:                my $question = $1;
                   7527:                my $subquestion = $2;
                   7528:                if (!defined($first_bubble_line{$question -1})) { next; }
                   7529:                my $first = $first_bubble_line{$question-1};
                   7530:                my @subans = split(/,/,$subdivided_bubble_lines{$question-1});
                   7531:                my $subcount = 1;
                   7532:                while ($subcount<$subquestion) {
                   7533:                    $first += $subans[$subcount-1];
                   7534:                    $subcount ++;
                   7535:                }
                   7536:                my $count = $subans[$subquestion-1];
                   7537:                $lastbubble = $first + $count;
                   7538:             } else {
                   7539:                 if (!defined($first_bubble_line{$missing - 1})) { next; }
                   7540:                 $lastbubble = $first_bubble_line{$missing - 1} + $bubble_lines_per_response{$missing - 1};
                   7541:             }
                   7542:             if ($lastbubble > $max_bubble) { next; }
1.157     albertel 7543: 	    push(@to_correct,$missing);
                   7544: 	}
                   7545: 	if (@to_correct) {
                   7546: 	    &scantron_get_correction($r,$i,$scan_record,\%scantron_config,
                   7547: 				     $line,'missingbubble',\@to_correct);
                   7548: 	    return (1,$currentphase);
                   7549: 	}
                   7550: 
                   7551:     }
                   7552:     return (0,$currentphase+1);
                   7553: }
                   7554: 
1.423     albertel 7555: 
1.82      albertel 7556: sub scantron_process_students {
1.608     www      7557:     my ($r,$symb) = @_;
1.513     foxr     7558: 
1.257     albertel 7559:     my (undef,undef,$sequence)=&Apache::lonnet::decode_symb($env{'form.selectpage'});
1.513     foxr     7560:     if (!$symb) {
                   7561: 	return '';
                   7562:     }
1.324     albertel 7563:     my $default_form_data=&defaultFormData($symb);
1.82      albertel 7564: 
1.257     albertel 7565:     my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
1.157     albertel 7566:     my ($scanlines,$scan_data)=&scantron_getfile();
1.82      albertel 7567:     my $classlist=&Apache::loncoursedata::get_classlist();
                   7568:     my %idmap=&username_to_idmap($classlist);
1.132     bowersj2 7569:     my $navmap=Apache::lonnavmaps::navmap->new();
1.582     raeburn  7570:     unless (ref($navmap)) {
                   7571:         $r->print(&navmap_errormsg());
                   7572:         return '';
                   7573:     }  
1.83      albertel 7574:     my $map=$navmap->getResourceByUrl($sequence);
                   7575:     my @resources=$navmap->retrieveResources($map,\&scantron_filter,1,0);
1.557     raeburn  7576:     my (%grader_partids_by_symb,%grader_randomlists_by_symb);
                   7577:     &graders_resources_pass(\@resources,\%grader_partids_by_symb,
                   7578:                             \%grader_randomlists_by_symb);
1.586     raeburn  7579:     my $resource_error;
1.557     raeburn  7580:     foreach my $resource (@resources) {
1.586     raeburn  7581:         my $ressymb;
                   7582:         if (ref($resource)) {
                   7583:             $ressymb = $resource->symb();
                   7584:         } else {
                   7585:             $resource_error = 1;
                   7586:             last;
                   7587:         }
1.557     raeburn  7588:         my ($analysis,$parts) =
                   7589:             &scantron_partids_tograde($resource,$env{'request.course.id'},
                   7590:                                       $env{'user.name'},$env{'user.domain'},1);
                   7591:         $grader_partids_by_symb{$ressymb} = $parts;
                   7592:         if (ref($analysis) eq 'HASH') {
                   7593:             if (ref($analysis->{'parts_withrandomlist'}) eq 'ARRAY') {
                   7594:                 $grader_randomlists_by_symb{$ressymb} = 
                   7595:                     $analysis->{'parts_withrandomlist'};
                   7596:             }
                   7597:         }
                   7598:     }
1.586     raeburn  7599:     if ($resource_error) {
                   7600:         $r->print(&navmap_errormsg());
                   7601:         return '';
                   7602:     }
1.557     raeburn  7603: 
1.554     raeburn  7604:     my ($uname,$udom);
1.82      albertel 7605:     my $result= <<SCANTRONFORM;
1.81      albertel 7606: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="scantronupload">
                   7607:   <input type="hidden" name="command" value="scantron_configphase" />
                   7608:   $default_form_data
                   7609: SCANTRONFORM
1.82      albertel 7610:     $r->print($result);
                   7611: 
                   7612:     my @delayqueue;
1.542     raeburn  7613:     my (%completedstudents,%scandata);
1.140     albertel 7614:     
1.520     www      7615:     my $lock=&Apache::lonnet::set_lock(&mt('Grading bubblesheet exam'));
1.200     albertel 7616:     my $count=&get_todo_count($scanlines,$scan_data);
1.575     www      7617:     my %prog_state=&Apache::lonhtmlcommon::Create_PrgWin($r,'Bubblesheet Status',
                   7618:  				    'Bubblesheet Progress',$count,
1.195     albertel 7619: 				    'inline',undef,'scantronupload');
1.140     albertel 7620:     &Apache::lonhtmlcommon::Update_PrgWin($r,\%prog_state,
                   7621: 					  'Processing first student');
1.542     raeburn  7622:     $r->print('<br />');
1.140     albertel 7623:     my $start=&Time::HiRes::time();
1.158     albertel 7624:     my $i=-1;
1.542     raeburn  7625:     my $started;
1.447     foxr     7626: 
1.582     raeburn  7627:     my $nav_error;
                   7628:     &scantron_get_maxbubble(\$nav_error); # Need the bubble lines array to parse.
                   7629:     if ($nav_error) {
                   7630:         $r->print(&navmap_errormsg());
                   7631:         return '';
                   7632:     }
                   7633: 
1.513     foxr     7634:     # If an ssi failed in scantron_get_maxbubble, put an error message out to
                   7635:     # the user and return.
                   7636: 
                   7637:     if ($ssi_error) {
                   7638: 	$r->print("</form>");
                   7639: 	&ssi_print_error($r);
                   7640: 	$r->print(&show_grading_menu_form($symb));
1.520     www      7641:         &Apache::lonnet::remove_lock($lock);
1.513     foxr     7642: 	return '';		# Dunno why the other returns return '' rather than just returning.
                   7643:     }
1.447     foxr     7644: 
1.542     raeburn  7645:     my %lettdig = &letter_to_digits();
                   7646:     my $numletts = scalar(keys(%lettdig));
                   7647: 
1.157     albertel 7648:     while ($i<$scanlines->{'count'}) {
                   7649:  	($uname,$udom)=('','');
                   7650:  	$i++;
1.200     albertel 7651:  	my $line=&scantron_get_line($scanlines,$scan_data,$i);
1.157     albertel 7652:  	if ($line=~/^[\s\cz]*$/) { next; }
1.200     albertel 7653: 	if ($started) {
                   7654: 	    &Apache::lonhtmlcommon::Increment_PrgWin($r,\%prog_state,
                   7655: 						     'last student');
                   7656: 	}
                   7657: 	$started=1;
1.157     albertel 7658:  	my $scan_record=&scantron_parse_scanline($line,$i,\%scantron_config,
                   7659:  						 $scan_data);
                   7660:  	unless ($uname=&scantron_find_student($scan_record,$scan_data,
                   7661:  					      \%idmap,$i)) {
                   7662:   	    &scantron_add_delay(\@delayqueue,$line,
                   7663:  				'Unable to find a student that matches',1);
                   7664:  	    next;
                   7665:   	}
                   7666:  	if (exists $completedstudents{$uname}) {
                   7667:  	    &scantron_add_delay(\@delayqueue,$line,
                   7668:  				'Student '.$uname.' has multiple sheets',2);
                   7669:  	    next;
                   7670:  	}
                   7671:   	($uname,$udom)=split(/:/,$uname);
1.330     albertel 7672: 
1.586     raeburn  7673:         my (%partids_by_symb,$res_error);
1.554     raeburn  7674:         foreach my $resource (@resources) {
1.586     raeburn  7675:             my $ressymb;
                   7676:             if (ref($resource)) {
                   7677:                 $ressymb = $resource->symb();
                   7678:             } else {
                   7679:                 $res_error = 1;
                   7680:                 last;
                   7681:             }
1.557     raeburn  7682:             if ((exists($grader_randomlists_by_symb{$ressymb})) ||
                   7683:                 (ref($grader_partids_by_symb{$ressymb}) ne 'ARRAY')) {
                   7684:                 my ($analysis,$parts) =
                   7685:                     &scantron_partids_tograde($resource,$env{'request.course.id'},$uname,$udom);
                   7686:                 $partids_by_symb{$ressymb} = $parts;
                   7687:             } else {
                   7688:                 $partids_by_symb{$ressymb} = $grader_partids_by_symb{$ressymb};
                   7689:             }
1.554     raeburn  7690:         }
                   7691: 
1.586     raeburn  7692:         if ($res_error) {
                   7693:             &scantron_add_delay(\@delayqueue,$line,
                   7694:                                 'An error occurred while grading student '.$uname,2);
                   7695:             next;
                   7696:         }
                   7697: 
1.330     albertel 7698: 	&Apache::lonxml::clear_problem_counter();
1.514     raeburn  7699:   	&Apache::lonnet::appenv($scan_record);
1.376     albertel 7700: 
                   7701: 	if (&scantron_clear_skip($scanlines,$scan_data,$i)) {
                   7702: 	    &scantron_putfile($scanlines,$scan_data);
                   7703: 	}
1.161     albertel 7704: 	
1.542     raeburn  7705:         my $scancode;
                   7706:         if ((exists($scan_record->{'scantron.CODE'})) &&
                   7707:             (&Apache::lonnet::validCODE($scan_record->{'scantron.CODE'}))) {
                   7708:             $scancode = $scan_record->{'scantron.CODE'};
                   7709:         } else {
                   7710:             $scancode = '';
                   7711:         }
                   7712: 
                   7713:         if (&grade_student_bubbles($r,$uname,$udom,$scan_record,$scancode,
1.554     raeburn  7714:                                    \@resources,\%partids_by_symb) eq 'ssi_error') {
1.542     raeburn  7715:             $ssi_error = 0; # So end of handler error message does not trigger.
                   7716:             $r->print("</form>");
                   7717:             &ssi_print_error($r);
                   7718:             $r->print(&show_grading_menu_form($symb));
                   7719:             &Apache::lonnet::remove_lock($lock);
                   7720:             return '';      # Why return ''?  Beats me.
                   7721:         }
1.513     foxr     7722: 
1.140     albertel 7723: 	$completedstudents{$uname}={'line'=>$line};
1.542     raeburn  7724:         if ($env{'form.verifyrecord'}) {
                   7725:             my $lastpos = $env{'form.scantron_maxbubble'}*$scantron_config{'Qlength'};
                   7726:             my $studentdata = substr($line,$scantron_config{'Qstart'}-1,$lastpos);
                   7727:             chomp($studentdata);
                   7728:             $studentdata =~ s/\r$//;
                   7729:             my $studentrecord = '';
                   7730:             my $counter = -1;
                   7731:             foreach my $resource (@resources) {
1.554     raeburn  7732:                 my $ressymb = $resource->symb();
1.542     raeburn  7733:                 ($counter,my $recording) =
                   7734:                     &verify_scantron_grading($resource,$udom,$uname,$env{'request.course.id'},
1.554     raeburn  7735:                                              $counter,$studentdata,$partids_by_symb{$ressymb},
1.542     raeburn  7736:                                              \%scantron_config,\%lettdig,$numletts);
                   7737:                 $studentrecord .= $recording;
                   7738:             }
                   7739:             if ($studentrecord ne $studentdata) {
1.554     raeburn  7740:                 &Apache::lonxml::clear_problem_counter();
                   7741:                 if (&grade_student_bubbles($r,$uname,$udom,$scan_record,$scancode,
                   7742:                                            \@resources,\%partids_by_symb) eq 'ssi_error') {
                   7743:                     $ssi_error = 0; # So end of handler error message does not trigger.
                   7744:                     $r->print("</form>");
                   7745:                     &ssi_print_error($r);
                   7746:                     $r->print(&show_grading_menu_form($symb));
                   7747:                     &Apache::lonnet::remove_lock($lock);
                   7748:                     delete($completedstudents{$uname});
                   7749:                     return '';
                   7750:                 }
1.542     raeburn  7751:                 $counter = -1;
                   7752:                 $studentrecord = '';
                   7753:                 foreach my $resource (@resources) {
1.554     raeburn  7754:                     my $ressymb = $resource->symb();
1.542     raeburn  7755:                     ($counter,my $recording) =
                   7756:                         &verify_scantron_grading($resource,$udom,$uname,$env{'request.course.id'},
1.554     raeburn  7757:                                                  $counter,$studentdata,$partids_by_symb{$ressymb},
1.542     raeburn  7758:                                                  \%scantron_config,\%lettdig,$numletts);
                   7759:                     $studentrecord .= $recording;
                   7760:                 }
                   7761:                 if ($studentrecord ne $studentdata) {
                   7762:                     $r->print('<p><span class="LC_error">');
                   7763:                     if ($scancode eq '') {
                   7764:                         $r->print(&mt('Mismatch grading bubble sheet for user: [_1] with ID: [_2].',
                   7765:                                   $uname.':'.$udom,$scan_record->{'scantron.ID'}));
                   7766:                     } else {
                   7767:                         $r->print(&mt('Mismatch grading bubble sheet for user: [_1] with ID: [_2] and CODE: [_3].',
                   7768:                                   $uname.':'.$udom,$scan_record->{'scantron.ID'},$scancode));
                   7769:                     }
                   7770:                     $r->print('</span><br />'.&Apache::loncommon::start_data_table()."\n".
                   7771:                               &Apache::loncommon::start_data_table_header_row()."\n".
                   7772:                               '<th>'.&mt('Source').'</th><th>'.&mt('Bubbled responses').'</th>'.
                   7773:                               &Apache::loncommon::end_data_table_header_row()."\n".
                   7774:                               &Apache::loncommon::start_data_table_row().
                   7775:                               '<td>'.&mt('Bubble Sheet').'</td>'.
                   7776:                               '<td><span class="LC_nobreak">'.$studentdata.'</span></td>'.
                   7777:                               &Apache::loncommon::end_data_table_row().
                   7778:                               &Apache::loncommon::start_data_table_row().
                   7779:                               '<td>Stored submissions</td>'.
                   7780:                               '<td><span class="LC_nobreak">'.$studentrecord.'</span></td>'."\n".
                   7781:                               &Apache::loncommon::end_data_table_row().
                   7782:                               &Apache::loncommon::end_data_table().'</p>');
                   7783:                 } else {
                   7784:                     $r->print('<br /><span class="LC_warning">'.
                   7785:                              &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 />'.
                   7786:                              &mt("As a consequence, this user's submission history records two tries.").
                   7787:                                  '</span><br />');
                   7788:                 }
                   7789:             }
                   7790:         }
1.543     raeburn  7791:         if (&Apache::loncommon::connection_aborted($r)) { last; }
1.140     albertel 7792:     } continue {
1.330     albertel 7793: 	&Apache::lonxml::clear_problem_counter();
1.552     raeburn  7794: 	&Apache::lonnet::delenv('scantron.');
1.82      albertel 7795:     }
1.140     albertel 7796:     &Apache::lonhtmlcommon::Close_PrgWin($r,\%prog_state);
1.520     www      7797:     &Apache::lonnet::remove_lock($lock);
1.172     albertel 7798: #    my $lasttime = &Time::HiRes::time()-$start;
                   7799: #    $r->print("<p>took $lasttime</p>");
1.140     albertel 7800: 
1.200     albertel 7801:     $r->print("</form>");
1.324     albertel 7802:     $r->print(&show_grading_menu_form($symb));
1.157     albertel 7803:     return '';
1.75      albertel 7804: }
1.157     albertel 7805: 
1.557     raeburn  7806: sub graders_resources_pass {
                   7807:     my ($resources,$grader_partids_by_symb,$grader_randomlists_by_symb) = @_;
                   7808:     if ((ref($resources) eq 'ARRAY') && (ref($grader_partids_by_symb)) && 
                   7809:         (ref($grader_randomlists_by_symb) eq 'HASH')) {
                   7810:         foreach my $resource (@{$resources}) {
                   7811:             my $ressymb = $resource->symb();
                   7812:             my ($analysis,$parts) =
                   7813:                 &scantron_partids_tograde($resource,$env{'request.course.id'},
                   7814:                                           $env{'user.name'},$env{'user.domain'},1);
                   7815:             $grader_partids_by_symb->{$ressymb} = $parts;
                   7816:             if (ref($analysis) eq 'HASH') {
                   7817:                 if (ref($analysis->{'parts_withrandomlist'}) eq 'ARRAY') {
                   7818:                     $grader_randomlists_by_symb->{$ressymb} =
                   7819:                         $analysis->{'parts_withrandomlist'};
                   7820:                 }
                   7821:             }
                   7822:         }
                   7823:     }
                   7824:     return;
                   7825: }
                   7826: 
1.542     raeburn  7827: sub grade_student_bubbles {
1.554     raeburn  7828:     my ($r,$uname,$udom,$scan_record,$scancode,$resources,$parts) = @_;
                   7829:     if (ref($resources) eq 'ARRAY') {
                   7830:         my $count = 0;
                   7831:         foreach my $resource (@{$resources}) {
                   7832:             my $ressymb = $resource->symb();
                   7833:             my %form = ('submitted'      => 'scantron',
                   7834:                         'grade_target'   => 'grade',
                   7835:                         'grade_username' => $uname,
                   7836:                         'grade_domain'   => $udom,
                   7837:                         'grade_courseid' => $env{'request.course.id'},
                   7838:                         'grade_symb'     => $ressymb,
                   7839:                         'CODE'           => $scancode
                   7840:                        );
                   7841:             if (ref($parts) eq 'HASH') {
                   7842:                 if (ref($parts->{$ressymb}) eq 'ARRAY') {
                   7843:                     foreach my $part (@{$parts->{$ressymb}}) {
                   7844:                         $form{'scantron_questnum_start.'.$part} =
                   7845:                             1+$env{'form.scantron.first_bubble_line.'.$count};
                   7846:                         $count++;
                   7847:                     }
                   7848:                 }
                   7849:             }
                   7850:             my $result=&ssi_with_retries($resource->src(),$ssi_retries,%form);
                   7851:             return 'ssi_error' if ($ssi_error);
                   7852:             last if (&Apache::loncommon::connection_aborted($r));
                   7853:         }
1.542     raeburn  7854:     }
                   7855:     return;
                   7856: }
                   7857: 
1.157     albertel 7858: sub scantron_upload_scantron_data {
1.608     www      7859:     my ($r,$symb)=@_;
1.565     raeburn  7860:     my $dom = $env{'request.role.domain'};
                   7861:     my $domdesc = &Apache::lonnet::domain($dom,'description');
                   7862:     $r->print(&Apache::loncommon::coursebrowser_javascript($dom));
1.157     albertel 7863:     my $select_link=&Apache::loncommon::selectcourse_link('rules','courseid',
1.181     albertel 7864: 							  'domainid',
1.565     raeburn  7865: 							  'coursename',$dom);
                   7866:     my $syllabuslink = '<a href="javascript:ToSyllabus();">'.&mt('Syllabus').'</a>'.
                   7867:                        ('&nbsp'x2).&mt('(shows course personnel)'); 
1.608     www      7868:     my $default_form_data=&defaultFormData($symb);
1.579     raeburn  7869:     my $nofile_alert = &mt('Please use the browse button to select a file from your local directory.');
                   7870:     my $nocourseid_alert = &mt("Please use the 'Select Course' link to open a separate window where you can search for a course to which a file can be uploaded.");
1.597     wenzelju 7871:     $r->print(&Apache::lonhtmlcommon::scripttag('
1.157     albertel 7872:     function checkUpload(formname) {
                   7873: 	if (formname.upfile.value == "") {
1.579     raeburn  7874: 	    alert("'.$nofile_alert.'");
1.157     albertel 7875: 	    return false;
                   7876: 	}
1.565     raeburn  7877:         if (formname.courseid.value == "") {
1.579     raeburn  7878:             alert("'.$nocourseid_alert.'");
1.565     raeburn  7879:             return false;
                   7880:         }
1.157     albertel 7881: 	formname.submit();
                   7882:     }
1.565     raeburn  7883: 
                   7884:     function ToSyllabus() {
                   7885:         var cdom = '."'$dom'".';
                   7886:         var cnum = document.rules.courseid.value;
                   7887:         if (cdom == "" || cdom == null) {
                   7888:             return;
                   7889:         }
                   7890:         if (cnum == "" || cnum == null) {
                   7891:            return;
                   7892:         }
                   7893:         syllwin=window.open("/public/"+cdom+"/"+cnum+"/syllabus","LONCAPASyllabus",
                   7894:                             "height=350,width=350,scrollbars=yes,menubar=no");
                   7895:         return;
                   7896:     }
                   7897: 
1.597     wenzelju 7898: '));
                   7899:     $r->print('
1.566     raeburn  7900: <h3>'.&mt('Send scanned bubblesheet data to a course').'</h3>
                   7901: 
1.492     albertel 7902: <form enctype="multipart/form-data" action="/adm/grades" name="rules" method="post">
1.565     raeburn  7903: '.$default_form_data.
                   7904:   &Apache::lonhtmlcommon::start_pick_box().
                   7905:   &Apache::lonhtmlcommon::row_title(&mt('Course ID')).
                   7906:   '<input name="courseid" type="text" size="30" />'.$select_link.
                   7907:   &Apache::lonhtmlcommon::row_closure().
                   7908:   &Apache::lonhtmlcommon::row_title(&mt('Course Name')).
                   7909:   '<input name="coursename" type="text" size="30" />'.$syllabuslink.
                   7910:   &Apache::lonhtmlcommon::row_closure().
                   7911:   &Apache::lonhtmlcommon::row_title(&mt('Domain')).
                   7912:   '<input name="domainid" type="hidden" />'.$domdesc.
                   7913:   &Apache::lonhtmlcommon::row_closure().
                   7914:   &Apache::lonhtmlcommon::row_title(&mt('File to upload')).
                   7915:   '<input type="file" name="upfile" size="50" />'.
                   7916:   &Apache::lonhtmlcommon::row_closure(1).
                   7917:   &Apache::lonhtmlcommon::end_pick_box().'<br />
                   7918: 
1.492     albertel 7919: <input name="command" value="scantronupload_save" type="hidden" />
1.589     bisitz   7920: <input type="button" onclick="javascript:checkUpload(this.form);" value="'.&mt('Upload Bubblesheet Data').'" />
1.157     albertel 7921: </form>
1.492     albertel 7922: ');
1.157     albertel 7923:     return '';
                   7924: }
                   7925: 
1.423     albertel 7926: 
1.157     albertel 7927: sub scantron_upload_scantron_data_save {
1.608     www      7928:     my($r,$symb)=@_;
1.182     albertel 7929:     my $doanotherupload=
                   7930: 	'<br /><form action="/adm/grades" method="post">'."\n".
                   7931: 	'<input type="hidden" name="command" value="scantronupload" />'."\n".
1.492     albertel 7932: 	'<input type="submit" name="submit" value="'.&mt('Do Another Upload').'" />'."\n".
1.182     albertel 7933: 	'</form>'."\n";
1.257     albertel 7934:     if (!&Apache::lonnet::allowed('usc',$env{'form.domainid'}) &&
1.162     albertel 7935: 	!&Apache::lonnet::allowed('usc',
1.257     albertel 7936: 			    $env{'form.domainid'}.'_'.$env{'form.courseid'})) {
1.575     www      7937: 	$r->print(&mt("You are not allowed to upload bubblesheet data to the requested course.")."<br />");
1.182     albertel 7938: 	if ($symb) {
1.324     albertel 7939: 	    $r->print(&show_grading_menu_form($symb));
1.182     albertel 7940: 	} else {
                   7941: 	    $r->print($doanotherupload);
                   7942: 	}
1.162     albertel 7943: 	return '';
                   7944:     }
1.257     albertel 7945:     my %coursedata=&Apache::lonnet::coursedescription($env{'form.domainid'}.'_'.$env{'form.courseid'});
1.568     raeburn  7946:     my $uploadedfile;
1.567     raeburn  7947:     $r->print('<h3>'.&mt("Uploading file to [_1]",$coursedata{'description'}).'</h3>');
1.257     albertel 7948:     if (length($env{'form.upfile'}) < 2) {
1.568     raeburn  7949:         $r->print(&mt('[_1]Error:[_2] The file you attempted to upload, [_3] contained no information. Please check that you entered the correct filename.','<span class="LC_error">','</span>','<span class="LC_filename">'.&HTML::Entities::encode($env{'form.upfile.filename'},'<>&"').'</span>'));
1.183     albertel 7950:     } else {
1.568     raeburn  7951:         my $result = 
                   7952:             &Apache::lonnet::userfileupload('upfile','','scantron','','','',
                   7953:                                             $env{'form.courseid'},$env{'form.domainid'});
                   7954: 	if ($result =~ m{^/uploaded/}) {
1.567     raeburn  7955: 	    $r->print(&mt('[_1]Success:[_2] Successfully uploaded [_3] bytes of data into location: [_4]',
                   7956:                           '<span class="LC_success">','</span>',(length($env{'form.upfile'})-1),
                   7957: 			  '<span class="LC_filename">'.$result.'</span>'));
1.568     raeburn  7958:             ($uploadedfile) = ($result =~ m{/([^/]+)$});
1.567     raeburn  7959:             $r->print(&validate_uploaded_scantron_file($env{'form.domainid'},
1.568     raeburn  7960:                                                        $env{'form.courseid'},$uploadedfile));
1.210     albertel 7961: 	} else {
1.567     raeburn  7962: 	    $r->print(&mt('[_1]Error:[_2] An error ([_3]) occurred when attempting to upload the file, [_4]',
                   7963:                           '<span class="LC_error">','</span>',$result,
1.568     raeburn  7964: 			  '<span class="LC_filename">'.&HTML::Entities::encode($env{'form.upfile.filename'},'<>&"').'</span>'));
1.183     albertel 7965: 	}
                   7966:     }
1.174     albertel 7967:     if ($symb) {
1.612     www      7968: 	$r->print(&scantron_selectphase($r,$uploadedfile,$symb));
1.174     albertel 7969:     } else {
1.182     albertel 7970: 	$r->print($doanotherupload);
1.174     albertel 7971:     }
1.157     albertel 7972:     return '';
                   7973: }
                   7974: 
1.567     raeburn  7975: sub validate_uploaded_scantron_file {
                   7976:     my ($cdom,$cname,$fname) = @_;
                   7977:     my $scanlines=&Apache::lonnet::getfile('/uploaded/'.$cdom.'/'.$cname.'/'.$fname);
                   7978:     my @lines;
                   7979:     if ($scanlines ne '-1') {
                   7980:         @lines=split("\n",$scanlines,-1);
                   7981:     }
                   7982:     my $output;
                   7983:     if (@lines) {
                   7984:         my (%counts,$max_match_format);
                   7985:         my ($max_match_count,$max_match_pct) = (0,0);
                   7986:         my $classlist = &Apache::loncoursedata::get_classlist($cdom,$cname);
                   7987:         my %idmap = &username_to_idmap($classlist);
                   7988:         foreach my $key (keys(%idmap)) {
                   7989:             my $lckey = lc($key);
                   7990:             $idmap{$lckey} = $idmap{$key};
                   7991:         }
                   7992:         my %unique_formats;
                   7993:         my @formatlines = &get_scantronformat_file();
                   7994:         foreach my $line (@formatlines) {
                   7995:             chomp($line);
                   7996:             my @config = split(/:/,$line);
                   7997:             my $idstart = $config[5];
                   7998:             my $idlength = $config[6];
                   7999:             if (($idstart ne '') && ($idlength > 0)) {
                   8000:                 if (ref($unique_formats{$idstart.':'.$idlength}) eq 'ARRAY') {
                   8001:                     push(@{$unique_formats{$idstart.':'.$idlength}},$config[0].':'.$config[1]); 
                   8002:                 } else {
                   8003:                     $unique_formats{$idstart.':'.$idlength} = [$config[0].':'.$config[1]];
                   8004:                 }
                   8005:             }
                   8006:         }
                   8007:         foreach my $key (keys(%unique_formats)) {
                   8008:             my ($idstart,$idlength) = split(':',$key);
                   8009:             %{$counts{$key}} = (
                   8010:                                'found'   => 0,
                   8011:                                'total'   => 0,
                   8012:                               );
                   8013:             foreach my $line (@lines) {
                   8014:                 next if ($line =~ /^#/);
                   8015:                 next if ($line =~ /^[\s\cz]*$/);
                   8016:                 my $id = substr($line,$idstart-1,$idlength);
                   8017:                 $id = lc($id);
                   8018:                 if (exists($idmap{$id})) {
                   8019:                     $counts{$key}{'found'} ++;
                   8020:                 }
                   8021:                 $counts{$key}{'total'} ++;
                   8022:             }
                   8023:             if ($counts{$key}{'total'}) {
                   8024:                 my $percent_match = (100*$counts{$key}{'found'})/($counts{$key}{'total'});
                   8025:                 if (($max_match_format eq '') || ($percent_match > $max_match_pct)) {
                   8026:                     $max_match_pct = $percent_match;
                   8027:                     $max_match_format = $key;
                   8028:                     $max_match_count = $counts{$key}{'total'};
                   8029:                 }
                   8030:             }
                   8031:         }
                   8032:         if (ref($unique_formats{$max_match_format}) eq 'ARRAY') {
                   8033:             my $format_descs;
                   8034:             my $numwithformat = @{$unique_formats{$max_match_format}};
                   8035:             for (my $i=0; $i<$numwithformat; $i++) {
                   8036:                 my ($name,$desc) = split(':',$unique_formats{$max_match_format}[$i]);
                   8037:                 if ($i<$numwithformat-2) {
                   8038:                     $format_descs .= '"<i>'.$desc.'</i>", ';
                   8039:                 } elsif ($i==$numwithformat-2) {
                   8040:                     $format_descs .= '"<i>'.$desc.'</i>" '.&mt('and').' ';
                   8041:                 } elsif ($i==$numwithformat-1) {
                   8042:                     $format_descs .= '"<i>'.$desc.'</i>"';
                   8043:                 }
                   8044:             }
                   8045:             my $showpct = sprintf("%.0f",$max_match_pct).'%';
                   8046:             $output .= '<br />'.&mt('Comparison of student IDs in the uploaded file with the course roster found matches for [_1] of the [_2] entries in the file (for the format defined for [_3]).','<b>'.$showpct.'</b>','<b>'.$max_match_count.'</b>',$format_descs).
                   8047:                        '<br />'.&mt('A low percentage of matches results from one of the following:').'<ul>'.
                   8048:                        '<li>'.&mt('The file was uploaded to the wrong course').'</li>'.
                   8049:                        '<li>'.&mt('The data are not in the format expected for the domain: [_1]',
                   8050:                                   '<i>'.$cdom.'</i>').'</li>'.
                   8051:                        '<li>'.&mt('Students did not bubble their IDs, or mis-bubbled them').'</li>'.
                   8052:                        '<li>'.&mt('The course roster is not up to date').'</li>'.
                   8053:                        '</ul>';
                   8054:         }
                   8055:     } else {
                   8056:         $output = '<span class="LC_warning">'.&mt('Uploaded file contained no data').'</span>';
                   8057:     }
                   8058:     return $output;
                   8059: }
                   8060: 
1.202     albertel 8061: sub valid_file {
                   8062:     my ($requested_file)=@_;
                   8063:     foreach my $filename (sort(&scantron_filenames())) {
                   8064: 	if ($requested_file eq $filename) { return 1; }
                   8065:     }
                   8066:     return 0;
                   8067: }
                   8068: 
                   8069: sub scantron_download_scantron_data {
1.608     www      8070:     my ($r,$symb)=@_;
                   8071:     my $default_form_data=&defaultFormData($symb);
1.257     albertel 8072:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   8073:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
                   8074:     my $file=$env{'form.scantron_selectfile'};
1.202     albertel 8075:     if (! &valid_file($file)) {
1.492     albertel 8076: 	$r->print('
1.202     albertel 8077: 	<p>
1.492     albertel 8078: 	    '.&mt('The requested file name was invalid.').'
1.202     albertel 8079:         </p>
1.492     albertel 8080: ');
1.608     www      8081: 	$r->print(&show_grading_menu_form($symb));
1.202     albertel 8082: 	return;
                   8083:     }
                   8084:     my $orig='/uploaded/'.$cdom.'/'.$cname.'/scantron_orig_'.$file;
                   8085:     my $corrected='/uploaded/'.$cdom.'/'.$cname.'/scantron_corrected_'.$file;
                   8086:     my $skipped='/uploaded/'.$cdom.'/'.$cname.'/scantron_skipped_'.$file;
                   8087:     &Apache::lonnet::allowuploaded('/adm/grades',$orig);
                   8088:     &Apache::lonnet::allowuploaded('/adm/grades',$corrected);
                   8089:     &Apache::lonnet::allowuploaded('/adm/grades',$skipped);
1.492     albertel 8090:     $r->print('
1.202     albertel 8091:     <p>
1.492     albertel 8092: 	'.&mt('[_1]Original[_2] file as uploaded by the scantron office.',
                   8093: 	      '<a href="'.$orig.'">','</a>').'
1.202     albertel 8094:     </p>
                   8095:     <p>
1.492     albertel 8096: 	'.&mt('[_1]Corrections[_2], a file of corrected records that were used in grading.',
                   8097: 	      '<a href="'.$corrected.'">','</a>').'
1.202     albertel 8098:     </p>
                   8099:     <p>
1.492     albertel 8100: 	'.&mt('[_1]Skipped[_2], a file of records that were skipped.',
                   8101: 	      '<a href="'.$skipped.'">','</a>').'
1.202     albertel 8102:     </p>
1.492     albertel 8103: ');
1.608     www      8104:     $r->print(&show_grading_menu_form($symb));
1.202     albertel 8105:     return '';
                   8106: }
1.157     albertel 8107: 
1.523     raeburn  8108: sub checkscantron_results {
1.608     www      8109:     my ($r,$symb) = @_;
1.523     raeburn  8110:     if (!$symb) {return '';}
                   8111:     my $grading_menu_button=&show_grading_menu_form($symb);
                   8112:     my $cid = $env{'request.course.id'};
1.542     raeburn  8113:     my %lettdig = &letter_to_digits();
1.523     raeburn  8114:     my $numletts = scalar(keys(%lettdig));
                   8115:     my $cnum = $env{'course.'.$cid.'.num'};
                   8116:     my $cdom = $env{'course.'.$cid.'.domain'};
                   8117:     my (undef, undef, $sequence) = &Apache::lonnet::decode_symb($env{'form.selectpage'});
                   8118:     my %record;
                   8119:     my %scantron_config =
                   8120:         &Apache::grades::get_scantron_config($env{'form.scantron_format'});
                   8121:     my ($scanlines,$scan_data)=&Apache::grades::scantron_getfile();
                   8122:     my $classlist=&Apache::loncoursedata::get_classlist();
                   8123:     my %idmap=&Apache::grades::username_to_idmap($classlist);
                   8124:     my $navmap=Apache::lonnavmaps::navmap->new();
1.582     raeburn  8125:     unless (ref($navmap)) {
                   8126:         $r->print(&navmap_errormsg());
                   8127:         return '';
                   8128:     }
1.523     raeburn  8129:     my $map=$navmap->getResourceByUrl($sequence);
1.557     raeburn  8130:     my @resources=$navmap->retrieveResources($map,\&scantron_filter,1,0);
                   8131:     my (%grader_partids_by_symb,%grader_randomlists_by_symb);
                   8132:     &graders_resources_pass(\@resources,\%grader_partids_by_symb,                             \%grader_randomlists_by_symb);
                   8133: 
1.554     raeburn  8134:     my ($uname,$udom);
1.523     raeburn  8135:     my (%scandata,%lastname,%bylast);
                   8136:     $r->print('
                   8137: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="checkscantron">'."\n");
                   8138: 
                   8139:     my @delayqueue;
                   8140:     my %completedstudents;
                   8141: 
                   8142:     my $count=&Apache::grades::get_todo_count($scanlines,$scan_data);
1.581     www      8143:     my %prog_state=&Apache::lonhtmlcommon::Create_PrgWin($r,'Bubblesheet/Submissions Comparison Status',
                   8144:                                     'Progress of Bubblesheet Data/Submission Records Comparison',$count,
1.523     raeburn  8145:                                     'inline',undef,'checkscantron');
1.546     raeburn  8146:     my ($username,$domain,$started);
1.582     raeburn  8147:     my $nav_error;
                   8148:     &scantron_get_maxbubble(\$nav_error); # Need the bubble lines array to parse.
                   8149:     if ($nav_error) {
                   8150:         $r->print(&navmap_errormsg());
                   8151:         return '';
                   8152:     }
1.523     raeburn  8153: 
                   8154:     &Apache::lonhtmlcommon::Update_PrgWin($r,\%prog_state,
                   8155:                                           'Processing first student');
                   8156:     my $start=&Time::HiRes::time();
                   8157:     my $i=-1;
                   8158: 
                   8159:     while ($i<$scanlines->{'count'}) {
                   8160:         ($username,$domain,$uname)=('','','');
                   8161:         $i++;
                   8162:         my $line=&Apache::grades::scantron_get_line($scanlines,$scan_data,$i);
                   8163:         if ($line=~/^[\s\cz]*$/) { next; }
                   8164:         if ($started) {
                   8165:             &Apache::lonhtmlcommon::Increment_PrgWin($r,\%prog_state,
                   8166:                                                      'last student');
                   8167:         }
                   8168:         $started=1;
                   8169:         my $scan_record=
                   8170:             &Apache::grades::scantron_parse_scanline($line,$i,\%scantron_config,
                   8171:                                                      $scan_data);
                   8172:         unless ($uname=&Apache::grades::scantron_find_student($scan_record,$scan_data,
                   8173:                                                               \%idmap,$i)) {
                   8174:             &Apache::grades::scantron_add_delay(\@delayqueue,$line,
                   8175:                                 'Unable to find a student that matches',1);
                   8176:             next;
                   8177:         }
                   8178:         if (exists $completedstudents{$uname}) {
                   8179:             &Apache::grades::scantron_add_delay(\@delayqueue,$line,
                   8180:                                 'Student '.$uname.' has multiple sheets',2);
                   8181:             next;
                   8182:         }
                   8183:         my $pid = $scan_record->{'scantron.ID'};
                   8184:         $lastname{$pid} = $scan_record->{'scantron.LastName'};
                   8185:         push(@{$bylast{$lastname{$pid}}},$pid);
                   8186:         my $lastpos = $env{'form.scantron_maxbubble'}*$scantron_config{'Qlength'};
                   8187:         $scandata{$pid} = substr($line,$scantron_config{'Qstart'}-1,$lastpos);
                   8188:         chomp($scandata{$pid});
                   8189:         $scandata{$pid} =~ s/\r$//;
                   8190:         ($username,$domain)=split(/:/,$uname);
                   8191:         my $counter = -1;
                   8192:         foreach my $resource (@resources) {
1.557     raeburn  8193:             my $parts;
1.554     raeburn  8194:             my $ressymb = $resource->symb();
1.557     raeburn  8195:             if ((exists($grader_randomlists_by_symb{$ressymb})) ||
                   8196:                 (ref($grader_partids_by_symb{$ressymb}) ne 'ARRAY')) {
                   8197:                 (my $analysis,$parts) =
                   8198:                     &scantron_partids_tograde($resource,$env{'request.course.id'},$username,$domain);
                   8199:             } else {
                   8200:                 $parts = $grader_partids_by_symb{$ressymb};
                   8201:             }
1.542     raeburn  8202:             ($counter,my $recording) =
                   8203:                 &verify_scantron_grading($resource,$domain,$username,$cid,$counter,
1.554     raeburn  8204:                                          $scandata{$pid},$parts,
1.542     raeburn  8205:                                          \%scantron_config,\%lettdig,$numletts);
                   8206:             $record{$pid} .= $recording;
1.523     raeburn  8207:         }
                   8208:     }
                   8209:     &Apache::lonhtmlcommon::Close_PrgWin($r,\%prog_state);
                   8210:     $r->print('<br />');
                   8211:     my ($okstudents,$badstudents,$numstudents,$passed,$failed);
                   8212:     $passed = 0;
                   8213:     $failed = 0;
                   8214:     $numstudents = 0;
                   8215:     foreach my $last (sort(keys(%bylast))) {
                   8216:         if (ref($bylast{$last}) eq 'ARRAY') {
                   8217:             foreach my $pid (sort(@{$bylast{$last}})) {
                   8218:                 my $showscandata = $scandata{$pid};
                   8219:                 my $showrecord = $record{$pid};
                   8220:                 $showscandata =~ s/\s/&nbsp;/g;
                   8221:                 $showrecord =~ s/\s/&nbsp;/g;
                   8222:                 if ($scandata{$pid} eq $record{$pid}) {
                   8223:                     my $css_class = ($passed % 2)?'LC_odd_row':'LC_even_row';
                   8224:                     $okstudents .= '<tr class="'.$css_class.'">'.
1.581     www      8225: '<td>'.&mt('Bubblesheet').'</td><td>'.$showscandata.'</td><td rowspan="2">'.$last.'</td><td rowspan="2">'.$pid.'</td>'."\n".
1.523     raeburn  8226: '</tr>'."\n".
                   8227: '<tr class="'.$css_class.'">'."\n".
                   8228: '<td>Submissions</td><td>'.$showrecord.'</td></tr>'."\n";
                   8229:                     $passed ++;
                   8230:                 } else {
                   8231:                     my $css_class = ($failed % 2)?'LC_odd_row':'LC_even_row';
1.581     www      8232:                     $badstudents .= '<tr class="'.$css_class.'"><td>'.&mt('Bubblesheet').'</td><td><span class="LC_nobreak">'.$scandata{$pid}.'</span></td><td rowspan="2">'.$last.'</td><td rowspan="2">'.$pid.'</td>'."\n".
1.523     raeburn  8233: '</tr>'."\n".
                   8234: '<tr class="'.$css_class.'">'."\n".
                   8235: '<td>Submissions</td><td><span class="LC_nobreak">'.$record{$pid}.'</span></td>'."\n".
                   8236: '</tr>'."\n";
                   8237:                     $failed ++;
                   8238:                 }
                   8239:                 $numstudents ++;
                   8240:             }
                   8241:         }
                   8242:     }
1.572     www      8243:     $r->print('<p>'.&mt('Comparison of bubblesheet data (including corrections) with corresponding submission records (most recent submission) for <b>[quant,_1,student]</b>  ([_2] scantron lines/student).',$numstudents,$env{'form.scantron_maxbubble'}).'</p>');
1.523     raeburn  8244:     $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>');
                   8245:     if ($passed) {
1.572     www      8246:         $r->print(&mt('Students with exact correspondence between bubblesheet data and submissions are as follows:').'<br /><br />');
1.523     raeburn  8247:         $r->print(&Apache::loncommon::start_data_table()."\n".
                   8248:                  &Apache::loncommon::start_data_table_header_row()."\n".
                   8249:                  '<th>'.&mt('Source').'</th><th>'.&mt('Bubble records').'</th><th>'.&mt('Name').'</th><th>'.&mt('ID').'</th>'.
                   8250:                  &Apache::loncommon::end_data_table_header_row()."\n".
                   8251:                  $okstudents."\n".
                   8252:                  &Apache::loncommon::end_data_table().'<br />');
                   8253:     }
                   8254:     if ($failed) {
1.572     www      8255:         $r->print(&mt('Students with differences between bubblesheet data and submissions are as follows:').'<br /><br />');
1.523     raeburn  8256:         $r->print(&Apache::loncommon::start_data_table()."\n".
                   8257:                  &Apache::loncommon::start_data_table_header_row()."\n".
                   8258:                  '<th>'.&mt('Source').'</th><th>'.&mt('Bubble records').'</th><th>'.&mt('Name').'</th><th>'.&mt('ID').'</th>'.
                   8259:                  &Apache::loncommon::end_data_table_header_row()."\n".
                   8260:                  $badstudents."\n".
                   8261:                  &Apache::loncommon::end_data_table()).'<br />'.
1.572     www      8262:                  &mt('Differences can occur if submissions were modified using manual grading after a bubblesheet grading pass.').'<br />'.&mt('If unexpected discrepancies were detected, it is recommended that you inspect the original bubblesheets.');  
1.523     raeburn  8263:     }
                   8264:     $r->print('</form><br />'.$grading_menu_button);
                   8265:     return;
                   8266: }
                   8267: 
1.542     raeburn  8268: sub verify_scantron_grading {
1.554     raeburn  8269:     my ($resource,$domain,$username,$cid,$counter,$scandata,$partids,
1.542     raeburn  8270:         $scantron_config,$lettdig,$numletts) = @_;
                   8271:     my ($record,%expected,%startpos);
                   8272:     return ($counter,$record) if (!ref($resource));
                   8273:     return ($counter,$record) if (!$resource->is_problem());
                   8274:     my $symb = $resource->symb();
1.554     raeburn  8275:     return ($counter,$record) if (ref($partids) ne 'ARRAY');
                   8276:     foreach my $part_id (@{$partids}) {
1.542     raeburn  8277:         $counter ++;
                   8278:         $expected{$part_id} = 0;
                   8279:         if ($env{"form.scantron.sub_bubblelines.$counter"}) {
                   8280:             my @sub_lines = split(/,/,$env{"form.scantron.sub_bubblelines.$counter"});
                   8281:             foreach my $item (@sub_lines) {
                   8282:                 $expected{$part_id} += $item;
                   8283:             }
                   8284:         } else {
                   8285:             $expected{$part_id} = $env{"form.scantron.bubblelines.$counter"};
                   8286:         }
                   8287:         $startpos{$part_id} = $env{"form.scantron.first_bubble_line.$counter"};
                   8288:     }
                   8289:     if ($symb) {
                   8290:         my %recorded;
                   8291:         my (%returnhash) = &Apache::lonnet::restore($symb,$cid,$domain,$username);
                   8292:         if ($returnhash{'version'}) {
                   8293:             my %lasthash=();
                   8294:             my $version;
                   8295:             for ($version=1;$version<=$returnhash{'version'};$version++) {
                   8296:                 foreach my $key (sort(split(/\:/,$returnhash{$version.':keys'}))) {
                   8297:                     $lasthash{$key}=$returnhash{$version.':'.$key};
                   8298:                 }
                   8299:             }
                   8300:             foreach my $key (keys(%lasthash)) {
                   8301:                 if ($key =~ /\.scantron$/) {
                   8302:                     my $value = &unescape($lasthash{$key});
                   8303:                     my ($part_id) = ($key =~ /^resource\.(.+)\.scantron$/);
                   8304:                     if ($value eq '') {
                   8305:                         for (my $i=0; $i<$expected{$part_id}; $i++) {
                   8306:                             for (my $j=0; $j<$scantron_config->{'length'}; $j++) {
                   8307:                                 $recorded{$part_id} .= $scantron_config->{'Qoff'};
                   8308:                             }
                   8309:                         }
                   8310:                     } else {
                   8311:                         my @tocheck;
                   8312:                         my @items = split(//,$value);
                   8313:                         if (($scantron_config->{'Qon'} eq 'letter') ||
                   8314:                             ($scantron_config->{'Qon'} eq 'number')) {
                   8315:                             if (@items < $expected{$part_id}) {
                   8316:                                 my $fragment = substr($scandata,$startpos{$part_id},$expected{$part_id});
                   8317:                                 my @singles = split(//,$fragment);
                   8318:                                 foreach my $pos (@singles) {
                   8319:                                     if ($pos eq ' ') {
                   8320:                                         push(@tocheck,$pos);
                   8321:                                     } else {
                   8322:                                         my $next = shift(@items);
                   8323:                                         push(@tocheck,$next);
                   8324:                                     }
                   8325:                                 }
                   8326:                             } else {
                   8327:                                 @tocheck = @items;
                   8328:                             }
                   8329:                             foreach my $letter (@tocheck) {
                   8330:                                 if ($scantron_config->{'Qon'} eq 'letter') {
                   8331:                                     if ($letter !~ /^[A-J]$/) {
                   8332:                                         $letter = $scantron_config->{'Qoff'};
                   8333:                                     }
                   8334:                                     $recorded{$part_id} .= $letter;
                   8335:                                 } elsif ($scantron_config->{'Qon'} eq 'number') {
                   8336:                                     my $digit;
                   8337:                                     if ($letter !~ /^[A-J]$/) {
                   8338:                                         $digit = $scantron_config->{'Qoff'};
                   8339:                                     } else {
                   8340:                                         $digit = $lettdig->{$letter};
                   8341:                                     }
                   8342:                                     $recorded{$part_id} .= $digit;
                   8343:                                 }
                   8344:                             }
                   8345:                         } else {
                   8346:                             @tocheck = @items;
                   8347:                             for (my $i=0; $i<$expected{$part_id}; $i++) {
                   8348:                                 my $curr_sub = shift(@tocheck);
                   8349:                                 my $digit;
                   8350:                                 if ($curr_sub =~ /^[A-J]$/) {
                   8351:                                     $digit = $lettdig->{$curr_sub}-1;
                   8352:                                 }
                   8353:                                 if ($curr_sub eq 'J') {
                   8354:                                     $digit += scalar($numletts);
                   8355:                                 }
                   8356:                                 for (my $j=0; $j<$scantron_config->{'Qlength'}; $j++) {
                   8357:                                     if ($j == $digit) {
                   8358:                                         $recorded{$part_id} .= $scantron_config->{'Qon'};
                   8359:                                     } else {
                   8360:                                         $recorded{$part_id} .= $scantron_config->{'Qoff'};
                   8361:                                     }
                   8362:                                 }
                   8363:                             }
                   8364:                         }
                   8365:                     }
                   8366:                 }
                   8367:             }
                   8368:         }
1.554     raeburn  8369:         foreach my $part_id (@{$partids}) {
1.542     raeburn  8370:             if ($recorded{$part_id} eq '') {
                   8371:                 for (my $i=0; $i<$expected{$part_id}; $i++) {
                   8372:                     for (my $j=0; $j<$scantron_config->{'Qlength'}; $j++) {
                   8373:                         $recorded{$part_id} .= $scantron_config->{'Qoff'};
                   8374:                     }
                   8375:                 }
                   8376:             }
                   8377:             $record .= $recorded{$part_id};
                   8378:         }
                   8379:     }
                   8380:     return ($counter,$record);
                   8381: }
                   8382: 
                   8383: sub letter_to_digits { 
                   8384:     my %lettdig = (
                   8385:                     A => 1,
                   8386:                     B => 2,
                   8387:                     C => 3,
                   8388:                     D => 4,
                   8389:                     E => 5,
                   8390:                     F => 6,
                   8391:                     G => 7,
                   8392:                     H => 8,
                   8393:                     I => 9,
                   8394:                     J => 0,
                   8395:                   );
                   8396:     return %lettdig;
                   8397: }
                   8398: 
1.423     albertel 8399: 
1.75      albertel 8400: #-------- end of section for handling grading scantron forms -------
                   8401: #
                   8402: #-------------------------------------------------------------------
                   8403: 
1.72      ng       8404: #-------------------------- Menu interface -------------------------
                   8405: #
                   8406: #--- Show a Grading Menu button - Calls the next routine ---
                   8407: sub show_grading_menu_form {
1.324     albertel 8408:     my ($symb)=@_;
1.125     ng       8409:     my $result.='<br /><form action="/adm/grades" method="post">'."\n".
1.418     albertel 8410: 	'<input type="hidden" name="symb" value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
1.72      ng       8411: 	'<input type="hidden" name="command" value="gradingmenu" />'."\n".
1.478     albertel 8412: 	'<input type="submit" name="submit" value="'.&mt('Grading Menu').'" />'."\n".
1.72      ng       8413: 	'</form>'."\n";
                   8414:     return $result;
                   8415: }
                   8416: 
1.443     banghart 8417: sub grading_menu {
1.608     www      8418:     my ($request,$symb) = @_;
1.443     banghart 8419:     if (!$symb) {return '';}
                   8420: 
                   8421:     my %fields = ('symb'=>&Apache::lonenc::check_encrypt($symb),
1.598     www      8422:                   'command'=>'individual',
1.443     banghart 8423:                   'gradingMenu'=>1,
                   8424:                   'showgrading'=>"yes");
1.538     schulted 8425:     
1.598     www      8426:     my $url1a = &Apache::lonhtmlcommon::build_url('grades/',\%fields);
                   8427: 
                   8428:     $fields{'command'}='ungraded';
                   8429:     my $url1b=&Apache::lonhtmlcommon::build_url('grades/',\%fields);
                   8430: 
                   8431:     $fields{'command'}='table';
                   8432:     my $url1c=&Apache::lonhtmlcommon::build_url('grades/',\%fields);
                   8433: 
                   8434:     $fields{'command'}='all_for_one';
                   8435:     my $url1d=&Apache::lonhtmlcommon::build_url('grades/',\%fields);
                   8436: 
1.443     banghart 8437:     $fields{'command'} = 'csvform';
1.538     schulted 8438:     my $url2 = &Apache::lonhtmlcommon::build_url('grades/',\%fields);
                   8439:     
1.443     banghart 8440:     $fields{'command'} = 'processclicker';
1.538     schulted 8441:     my $url3 = &Apache::lonhtmlcommon::build_url('grades/',\%fields);
                   8442:     
1.443     banghart 8443:     $fields{'command'} = 'scantron_selectphase';
1.538     schulted 8444:     my $url4 = &Apache::lonhtmlcommon::build_url('grades/',\%fields);
1.602     www      8445: 
                   8446:     $fields{'command'} = 'initialverifyreceipt';
                   8447:     my $url5 = &Apache::lonhtmlcommon::build_url('grades/',\%fields);
1.538     schulted 8448:     
1.598     www      8449:     my @menu = ({	categorytitle=>'Hand Grading',
1.538     schulted 8450:             items =>[
1.598     www      8451:                         {	linktext => 'Select individual students to grade',
                   8452:                     		url => $url1a,
1.538     schulted 8453:                     		permission => 'F',
                   8454:                     		icon => 'edit-find-replace.png',
1.598     www      8455:                     		linktitle => 'Grade current resource for a selection of students.'
                   8456:                         }, 
                   8457:                         {       linktext => 'Grade ungraded submissions.',
                   8458:                                 url => $url1b,
                   8459:                                 permission => 'F',
                   8460:                                 icon => 'edit-find-replace.png',
                   8461:                                 linktitle => 'Grade all submissions that have not been graded yet.'
1.538     schulted 8462:                         },
1.598     www      8463: 
                   8464:                         {       linktext => 'Grading table',
                   8465:                                 url => $url1c,
                   8466:                                 permission => 'F',
                   8467:                                 icon => 'edit-find-replace.png',
                   8468:                                 linktitle => 'Grade current resource for all students.'
                   8469:                         },
1.600     www      8470:                         {       linktext => 'Grade complete page/sequence/folder for one student',
1.598     www      8471:                                 url => $url1d,
                   8472:                                 permission => 'F',
                   8473:                                 icon => 'edit-find-replace.png',
                   8474:                                 linktitle => 'Grade all resources in current page/sequence/folder for one student.'
                   8475:                         }]},
                   8476:                          { categorytitle=>'Automated Grading',
                   8477:                items =>[
                   8478: 
1.538     schulted 8479:                 	    {	linktext => 'Upload Scores',
                   8480:                     		url => $url2,
                   8481:                     		permission => 'F',
                   8482:                     		icon => 'uploadscores.png',
                   8483:                     		linktitle => 'Specify a file containing the class scores for current resource.'
                   8484:                 	    },
                   8485:                 	    {	linktext => 'Process Clicker',
                   8486:                     		url => $url3,
                   8487:                     		permission => 'F',
                   8488:                     		icon => 'addClickerInfoFile.png',
                   8489:                     		linktitle => 'Specify a file containing the clicker information for this resource.'
                   8490:                 	    },
1.587     raeburn  8491:                 	    {	linktext => 'Grade/Manage/Review Bubblesheets',
1.538     schulted 8492:                     		url => $url4,
                   8493:                     		permission => 'F',
                   8494:                     		icon => 'stat.png',
                   8495:                     		linktitle => 'Grade scantron exams, upload/download scantron data files, and review previously graded scantron exams.'
1.602     www      8496:                 	    },
                   8497:                             {   linktext => 'Verify Receipt No.',
                   8498:                                 url => $url5,
                   8499:                                 permission => 'F',
                   8500:                                 icon => 'edit-find-replace.png',
                   8501:                                 linktitle => 'Verify a system-generated receipt number for correct problem solution.'
                   8502:                             }
                   8503: 
1.538     schulted 8504:                     ]
                   8505:             });
                   8506: 
1.443     banghart 8507:     # Create the menu
                   8508:     my $Str;
1.445     banghart 8509:     $Str .= '<form method="post" action="" name="gradingMenu">';
                   8510:     $Str .= '<input type="hidden" name="command" value="" />'.
                   8511:     	'<input type="hidden" name="symb"        value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
                   8512: 	'<input type="hidden" name="gradingMenu" value="1" />'."\n".
                   8513: 	'<input type="hidden" name="showgrading" value="yes" />'."\n";
                   8514: 
1.602     www      8515:     $Str .= &Apache::lonhtmlcommon::generate_menu(@menu);
1.443     banghart 8516:     return $Str;    
                   8517: }
                   8518: 
1.598     www      8519: 
                   8520: sub ungraded {
                   8521:     my ($request)=@_;
                   8522:     &submit_options($request);
                   8523: }
                   8524: 
1.599     www      8525: sub submit_options_sequence {
1.608     www      8526:     my ($request,$symb) = @_;
1.599     www      8527:     if (!$symb) {return '';}
1.600     www      8528:     &commonJSfunctions($request);
                   8529:     my $result;
1.599     www      8530: 
1.600     www      8531:     $result.='<form action="/adm/grades" method="post" name="gradingMenu">'."\n".
                   8532:         '<input type="hidden" name="symb"        value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
                   8533:         '<input type="hidden" name="gradingMenu" value="1" />'."\n".
                   8534:         '<input type="hidden" name="showgrading" value="yes" />'."\n";
                   8535: 
                   8536:     $result.='
                   8537: <h2>
                   8538:   '.&mt('Grade complete page/sequence/folder for one student').'
1.601     www      8539: </h2>'.
                   8540:             &selectfield(0).
                   8541:             '<input type="hidden" name="command" value="pickStudentPage" />
1.600     www      8542:             <div>
                   8543:               <input type="submit" value="'.&mt('Next').' &rarr;" />
                   8544:             </div>
                   8545:         </div>
                   8546:   </form>';
                   8547:     $result .= &show_grading_menu_form($symb);
                   8548:     return $result;
                   8549: }
                   8550: 
                   8551: sub submit_options_table {
1.608     www      8552:     my ($request,$symb) = @_;
1.600     www      8553:     if (!$symb) {return '';}
1.599     www      8554:     &commonJSfunctions($request);
                   8555:     my $result;
                   8556: 
                   8557:     $result.='<form action="/adm/grades" method="post" name="gradingMenu">'."\n".
                   8558:         '<input type="hidden" name="symb"        value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
                   8559:         '<input type="hidden" name="gradingMenu" value="1" />'."\n".
                   8560:         '<input type="hidden" name="showgrading" value="yes" />'."\n";
                   8561: 
                   8562:     $result.='
                   8563: <h2>
1.600     www      8564:   '.&mt('Grading table').'
1.601     www      8565: </h2>'.
                   8566:             &selectfield(0).
                   8567:             '<input type="hidden" name="command" value="viewgrades" />
1.599     www      8568:             <div>
                   8569:               <input type="submit" value="'.&mt('Next').' &rarr;" />
                   8570:             </div>
                   8571:         </div>
                   8572:   </form>';
                   8573:     $result .= &show_grading_menu_form($symb);
                   8574:     return $result;
                   8575: }
1.443     banghart 8576: 
1.600     www      8577: 
                   8578: 
1.443     banghart 8579: #--- Displays the submissions first page -------
                   8580: sub submit_options {
1.608     www      8581:     my ($request,$symb) = @_;
1.72      ng       8582:     if (!$symb) {return '';}
                   8583: 
1.118     ng       8584:     &commonJSfunctions($request);
1.473     albertel 8585:     my $result;
1.533     bisitz   8586: 
1.72      ng       8587:     $result.='<form action="/adm/grades" method="post" name="gradingMenu">'."\n".
1.418     albertel 8588: 	'<input type="hidden" name="symb"        value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
1.124     ng       8589: 	'<input type="hidden" name="gradingMenu" value="1" />'."\n".
1.72      ng       8590: 	'<input type="hidden" name="showgrading" value="yes" />'."\n";
                   8591: 
1.472     albertel 8592:     $result.='
1.533     bisitz   8593: <h2>
1.600     www      8594:   '.&mt('Select individual students to grade').'
1.601     www      8595: </h2>'.&selectfield(1).'
                   8596:                 <input type="hidden" name="command" value="submission" /> 
                   8597: 	      <input type="submit" value="'.&mt('Next').' &rarr;" />
                   8598:             </div>
                   8599:           </div>
                   8600: 
                   8601: 
                   8602:   </form>';
                   8603:     $result .= &show_grading_menu_form($symb);
                   8604:     return $result;
                   8605: }
1.533     bisitz   8606: 
1.601     www      8607: sub selectfield {
                   8608:    my ($full)=@_;
                   8609:    my $result='<div class="LC_columnSection">
1.537     harmsja  8610:   
1.533     bisitz   8611:     <fieldset>
                   8612:       <legend>
                   8613:        '.&mt('Sections').'
                   8614:       </legend>
1.601     www      8615:       '.&Apache::lonstatistics::SectionSelect('section','multiple',5).'
1.533     bisitz   8616:     </fieldset>
1.537     harmsja  8617:   
1.533     bisitz   8618:     <fieldset>
                   8619:       <legend>
                   8620:         '.&mt('Groups').'
                   8621:       </legend>
                   8622:       '.&Apache::lonstatistics::GroupSelect('group','multiple',5).'
                   8623:     </fieldset>
1.537     harmsja  8624:   
1.533     bisitz   8625:     <fieldset>
                   8626:       <legend>
                   8627:         '.&mt('Access Status').'
                   8628:       </legend>
1.601     www      8629:       '.&Apache::lonhtmlcommon::StatusOptions(undef,undef,5,undef,'mult').'
                   8630:     </fieldset>';
                   8631:     if ($full) {
                   8632:        $result.='
1.533     bisitz   8633:     <fieldset>
                   8634:       <legend>
                   8635:         '.&mt('Submission Status').'
1.601     www      8636:       </legend>'.
                   8637:        &Apache::loncommon::select_form('all','submitonly',
                   8638:           (&Apache::lonlocal::texthash(
                   8639:              'yes'       => 'with submissions',
                   8640:              'queued'    => 'in grading queue',
                   8641:              'graded'    => 'with ungraded submissions',
                   8642:              'incorrect' => 'with incorrect submissions',
                   8643:              'all'       => 'with any status'),
                   8644:              'select_form_order' => ['yes','queued','graded','incorrect','all'])).
                   8645:    '</fieldset>';
                   8646:     }
                   8647:     $result.='</div><br />';
1.44      ng       8648:     return $result;
1.2       albertel 8649: }
                   8650: 
1.285     albertel 8651: sub reset_perm {
                   8652:     undef(%perm);
                   8653: }
                   8654: 
                   8655: sub init_perm {
                   8656:     &reset_perm();
1.300     albertel 8657:     foreach my $test_perm ('vgr','mgr','opa') {
                   8658: 
                   8659: 	my $scope = $env{'request.course.id'};
                   8660: 	if (!($perm{$test_perm}=&Apache::lonnet::allowed($test_perm,$scope))) {
                   8661: 
                   8662: 	    $scope .= '/'.$env{'request.course.sec'};
                   8663: 	    if ( $perm{$test_perm}=
                   8664: 		 &Apache::lonnet::allowed($test_perm,$scope)) {
                   8665: 		$perm{$test_perm.'_section'}=$env{'request.course.sec'};
                   8666: 	    } else {
                   8667: 		delete($perm{$test_perm});
                   8668: 	    }
1.285     albertel 8669: 	}
                   8670:     }
                   8671: }
                   8672: 
1.400     www      8673: sub gather_clicker_ids {
1.408     albertel 8674:     my %clicker_ids;
1.400     www      8675: 
                   8676:     my $classlist = &Apache::loncoursedata::get_classlist();
                   8677: 
                   8678:     # Set up a couple variables.
1.407     albertel 8679:     my $username_idx = &Apache::loncoursedata::CL_SNAME();
                   8680:     my $domain_idx   = &Apache::loncoursedata::CL_SDOM();
1.438     www      8681:     my $status_idx   = &Apache::loncoursedata::CL_STATUS();
1.400     www      8682: 
1.407     albertel 8683:     foreach my $student (keys(%$classlist)) {
1.438     www      8684:         if ($classlist->{$student}->[$status_idx] ne 'Active') { next; }
1.407     albertel 8685:         my $username = $classlist->{$student}->[$username_idx];
                   8686:         my $domain   = $classlist->{$student}->[$domain_idx];
1.400     www      8687:         my $clickers =
1.408     albertel 8688: 	    (&Apache::lonnet::userenvironment($domain,$username,'clickers'))[1];
1.400     www      8689:         foreach my $id (split(/\,/,$clickers)) {
1.414     www      8690:             $id=~s/^[\#0]+//;
1.421     www      8691:             $id=~s/[\-\:]//g;
1.407     albertel 8692:             if (exists($clicker_ids{$id})) {
1.408     albertel 8693: 		$clicker_ids{$id}.=','.$username.':'.$domain;
1.400     www      8694:             } else {
1.408     albertel 8695: 		$clicker_ids{$id}=$username.':'.$domain;
1.400     www      8696:             }
                   8697:         }
                   8698:     }
1.407     albertel 8699:     return %clicker_ids;
1.400     www      8700: }
                   8701: 
1.402     www      8702: sub gather_adv_clicker_ids {
1.408     albertel 8703:     my %clicker_ids;
1.402     www      8704:     my $cnum=$env{'course.'.$env{'request.course.id'}.'.num'};
                   8705:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
                   8706:     my %coursepersonnel=&Apache::lonnet::get_course_adv_roles($cdom.'/'.$cnum);
1.409     albertel 8707:     foreach my $element (sort(keys(%coursepersonnel))) {
1.402     www      8708:         foreach my $person (split(/\,/,$coursepersonnel{$element})) {
                   8709:             my ($puname,$pudom)=split(/\:/,$person);
                   8710:             my $clickers =
1.408     albertel 8711: 		(&Apache::lonnet::userenvironment($pudom,$puname,'clickers'))[1];
1.405     www      8712:             foreach my $id (split(/\,/,$clickers)) {
1.414     www      8713: 		$id=~s/^[\#0]+//;
1.421     www      8714:                 $id=~s/[\-\:]//g;
1.408     albertel 8715: 		if (exists($clicker_ids{$id})) {
                   8716: 		    $clicker_ids{$id}.=','.$puname.':'.$pudom;
                   8717: 		} else {
                   8718: 		    $clicker_ids{$id}=$puname.':'.$pudom;
                   8719: 		}
1.405     www      8720:             }
1.402     www      8721:         }
                   8722:     }
1.407     albertel 8723:     return %clicker_ids;
1.402     www      8724: }
                   8725: 
1.413     www      8726: sub clicker_grading_parameters {
                   8727:     return ('gradingmechanism' => 'scalar',
                   8728:             'upfiletype' => 'scalar',
                   8729:             'specificid' => 'scalar',
                   8730:             'pcorrect' => 'scalar',
                   8731:             'pincorrect' => 'scalar');
                   8732: }
                   8733: 
1.400     www      8734: sub process_clicker {
1.608     www      8735:     my ($r,$symb)=@_;
1.400     www      8736:     if (!$symb) {return '';}
                   8737:     my $result=&checkforfile_js();
                   8738:     $result.='<br /><table width="100%" border="0"><tr><td bgcolor="#777777">'."\n";
                   8739:     $result.='<table width="100%" border="0"><tr bgcolor="#e6ffff"><td>'."\n";
1.538     schulted 8740:     $result.='&nbsp;<b>'.&mt('Specify a file containing the clicker information for this resource.').
                   8741:         '</b></td></tr>'."\n";
1.601     www      8742:     $result.='<tr bgcolor="#ffffe6"><td>'."\n";
1.413     www      8743: # Attempt to restore parameters from last session, set defaults if not present
                   8744:     my %Saveable_Parameters=&clicker_grading_parameters();
                   8745:     &Apache::loncommon::restore_course_settings('grades_clicker',
                   8746:                                                  \%Saveable_Parameters);
                   8747:     if (!$env{'form.pcorrect'}) { $env{'form.pcorrect'}=100; }
                   8748:     if (!$env{'form.pincorrect'}) { $env{'form.pincorrect'}=100; }
                   8749:     if (!$env{'form.gradingmechanism'}) { $env{'form.gradingmechanism'}='attendance'; }
                   8750:     if (!$env{'form.upfiletype'}) { $env{'form.upfiletype'}='iclicker'; }
                   8751: 
                   8752:     my %checked;
1.521     www      8753:     foreach my $gradingmechanism ('attendance','personnel','specific','given') {
1.413     www      8754:        if ($env{'form.gradingmechanism'} eq $gradingmechanism) {
1.569     bisitz   8755:           $checked{$gradingmechanism}=' checked="checked"';
1.413     www      8756:        }
                   8757:     }
                   8758: 
1.400     www      8759:     my $upload=&mt("Upload File");
                   8760:     my $type=&mt("Type");
1.402     www      8761:     my $attendance=&mt("Award points just for participation");
                   8762:     my $personnel=&mt("Correctness determined from response by course personnel");
1.414     www      8763:     my $specific=&mt("Correctness determined from response with clicker ID(s)"); 
1.521     www      8764:     my $given=&mt("Correctness determined from given list of answers").' '.
                   8765:               '<font size="-2"><tt>('.&mt("Provide comma-separated list. Use '*' for any answer correct, '-' for skip").')</tt></font>';
1.402     www      8766:     my $pcorrect=&mt("Percentage points for correct solution");
                   8767:     my $pincorrect=&mt("Percentage points for incorrect solution");
1.413     www      8768:     my $selectform=&Apache::loncommon::select_form($env{'form.upfiletype'},'upfiletype',
1.419     www      8769: 						   ('iclicker' => 'i>clicker',
                   8770:                                                     'interwrite' => 'interwrite PRS'));
1.418     albertel 8771:     $symb = &Apache::lonenc::check_encrypt($symb);
1.597     wenzelju 8772:     $result.= &Apache::lonhtmlcommon::scripttag(<<ENDUPFORM);
1.402     www      8773: function sanitycheck() {
                   8774: // Accept only integer percentages
                   8775:    document.forms.gradesupload.pcorrect.value=Math.round(document.forms.gradesupload.pcorrect.value);
                   8776:    document.forms.gradesupload.pincorrect.value=Math.round(document.forms.gradesupload.pincorrect.value);
                   8777: // Find out grading choice
                   8778:    for (i=0; i<document.forms.gradesupload.gradingmechanism.length; i++) {
                   8779:       if (document.forms.gradesupload.gradingmechanism[i].checked) {
                   8780:          gradingchoice=document.forms.gradesupload.gradingmechanism[i].value;
                   8781:       }
                   8782:    }
                   8783: // By default, new choice equals user selection
                   8784:    newgradingchoice=gradingchoice;
                   8785: // Not good to give more points for false answers than correct ones
                   8786:    if (Math.round(document.forms.gradesupload.pcorrect.value)<Math.round(document.forms.gradesupload.pincorrect.value)) {
                   8787:       document.forms.gradesupload.pcorrect.value=document.forms.gradesupload.pincorrect.value;
                   8788:    }
                   8789: // If new choice is attendance only, and old choice was correctness-based, restore defaults
                   8790:    if ((gradingchoice=='attendance') && (document.forms.gradesupload.waschecked.value!='attendance')) {
                   8791:       document.forms.gradesupload.pcorrect.value=100;
                   8792:       document.forms.gradesupload.pincorrect.value=100;
                   8793:    }
                   8794: // If the values are different, cannot be attendance only
                   8795:    if ((Math.round(document.forms.gradesupload.pcorrect.value)!=Math.round(document.forms.gradesupload.pincorrect.value)) &&
                   8796:        (gradingchoice=='attendance')) {
                   8797:        newgradingchoice='personnel';
                   8798:    }
                   8799: // Change grading choice to new one
                   8800:    for (i=0; i<document.forms.gradesupload.gradingmechanism.length; i++) {
                   8801:       if (document.forms.gradesupload.gradingmechanism[i].value==newgradingchoice) {
                   8802:          document.forms.gradesupload.gradingmechanism[i].checked=true;
                   8803:       } else {
                   8804:          document.forms.gradesupload.gradingmechanism[i].checked=false;
                   8805:       }
                   8806:    }
                   8807: // Remember the old state
                   8808:    document.forms.gradesupload.waschecked.value=newgradingchoice;
                   8809: }
1.597     wenzelju 8810: ENDUPFORM
                   8811:     $result.= <<ENDUPFORM;
1.400     www      8812: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="gradesupload">
                   8813: <input type="hidden" name="symb" value="$symb" />
                   8814: <input type="hidden" name="command" value="processclickerfile" />
                   8815: <input type="file" name="upfile" size="50" />
                   8816: <br /><label>$type: $selectform</label>
1.589     bisitz   8817: <br /><label><input type="radio" name="gradingmechanism" value="attendance"$checked{'attendance'} onclick="sanitycheck()" />$attendance </label>
                   8818: <br /><label><input type="radio" name="gradingmechanism" value="personnel"$checked{'personnel'} onclick="sanitycheck()" />$personnel</label>
                   8819: <br /><label><input type="radio" name="gradingmechanism" value="specific"$checked{'specific'} onclick="sanitycheck()" />$specific </label>
1.414     www      8820: <input type="text" name="specificid" value="$env{'form.specificid'}" size="20" />
1.589     bisitz   8821: <br /><label><input type="radio" name="gradingmechanism" value="given"$checked{'given'} onclick="sanitycheck()" />$given </label>
1.521     www      8822: <br />&nbsp;&nbsp;&nbsp;
                   8823: <input type="text" name="givenanswer" size="50" />
1.413     www      8824: <input type="hidden" name="waschecked" value="$env{'form.gradingmechanism'}" />
1.589     bisitz   8825: <br /><label>$pcorrect: <input type="text" name="pcorrect" size="4" value="$env{'form.pcorrect'}" onchange="sanitycheck()" /></label>
                   8826: <br /><label>$pincorrect: <input type="text" name="pincorrect" size="4" value="$env{'form.pincorrect'}" onchange="sanitycheck()" /></label>
                   8827: <br /><input type="button" onclick="javascript:checkUpload(this.form);" value="$upload" />
1.597     wenzelju 8828: </form>'
1.400     www      8829: ENDUPFORM
                   8830:     $result.='</td></tr></table>'."\n".
                   8831:              '</td></tr></table><br /><br />'."\n";
                   8832:     $result.=&show_grading_menu_form($symb);
                   8833:     return $result;
                   8834: }
                   8835: 
                   8836: sub process_clicker_file {
1.608     www      8837:     my ($r,$symb)=@_;
1.400     www      8838:     if (!$symb) {return '';}
1.413     www      8839: 
                   8840:     my %Saveable_Parameters=&clicker_grading_parameters();
                   8841:     &Apache::loncommon::store_course_settings('grades_clicker',
                   8842:                                               \%Saveable_Parameters);
1.598     www      8843:     my $result='';
1.404     www      8844:     if (($env{'form.gradingmechanism'} eq 'specific') && ($env{'form.specificid'}!~/\w/)) {
1.408     albertel 8845: 	$result.='<span class="LC_error">'.&mt('You need to specify a clicker ID for the correct answer').'</span>';
                   8846: 	return $result.&show_grading_menu_form($symb);
1.404     www      8847:     }
1.522     www      8848:     if (($env{'form.gradingmechanism'} eq 'given') && ($env{'form.givenanswer'}!~/\S/)) {
1.521     www      8849:         $result.='<span class="LC_error">'.&mt('You need to specify the correct answer').'</span>';
                   8850:         return $result.&show_grading_menu_form($symb);
                   8851:     }
1.522     www      8852:     my $foundgiven=0;
1.521     www      8853:     if ($env{'form.gradingmechanism'} eq 'given') {
                   8854:         $env{'form.givenanswer'}=~s/^\s*//gs;
                   8855:         $env{'form.givenanswer'}=~s/\s*$//gs;
                   8856:         $env{'form.givenanswer'}=~s/[^a-zA-Z0-9\.\*\-]+/\,/g;
                   8857:         $env{'form.givenanswer'}=uc($env{'form.givenanswer'});
1.522     www      8858:         my @answers=split(/\,/,$env{'form.givenanswer'});
                   8859:         $foundgiven=$#answers+1;
1.521     www      8860:     }
1.407     albertel 8861:     my %clicker_ids=&gather_clicker_ids();
1.408     albertel 8862:     my %correct_ids;
1.404     www      8863:     if ($env{'form.gradingmechanism'} eq 'personnel') {
1.408     albertel 8864: 	%correct_ids=&gather_adv_clicker_ids();
1.404     www      8865:     }
                   8866:     if ($env{'form.gradingmechanism'} eq 'specific') {
1.414     www      8867: 	foreach my $correct_id (split(/[\s\,]/,$env{'form.specificid'})) {;
                   8868: 	   $correct_id=~tr/a-z/A-Z/;
                   8869: 	   $correct_id=~s/\s//gs;
                   8870: 	   $correct_id=~s/^[\#0]+//;
1.421     www      8871:            $correct_id=~s/[\-\:]//g;
1.414     www      8872:            if ($correct_id) {
                   8873: 	      $correct_ids{$correct_id}='specified';
                   8874:            }
                   8875:         }
1.400     www      8876:     }
1.404     www      8877:     if ($env{'form.gradingmechanism'} eq 'attendance') {
1.408     albertel 8878: 	$result.=&mt('Score based on attendance only');
1.521     www      8879:     } elsif ($env{'form.gradingmechanism'} eq 'given') {
1.522     www      8880:         $result.=&mt('Score based on [_1] ([_2] answers)','<tt>'.$env{'form.givenanswer'}.'</tt>',$foundgiven);
1.404     www      8881:     } else {
1.408     albertel 8882: 	my $number=0;
1.411     www      8883: 	$result.='<p><b>'.&mt('Correctness determined by the following IDs').'</b>';
1.408     albertel 8884: 	foreach my $id (sort(keys(%correct_ids))) {
1.411     www      8885: 	    $result.='<br /><tt>'.$id.'</tt> - ';
1.408     albertel 8886: 	    if ($correct_ids{$id} eq 'specified') {
                   8887: 		$result.=&mt('specified');
                   8888: 	    } else {
                   8889: 		my ($uname,$udom)=split(/\:/,$correct_ids{$id});
                   8890: 		$result.=&Apache::loncommon::plainname($uname,$udom);
                   8891: 	    }
                   8892: 	    $number++;
                   8893: 	}
1.411     www      8894:         $result.="</p>\n";
1.408     albertel 8895: 	if ($number==0) {
                   8896: 	    $result.='<span class="LC_error">'.&mt('No IDs found to determine correct answer').'</span>';
                   8897: 	    return $result.&show_grading_menu_form($symb);
                   8898: 	}
1.404     www      8899:     }
1.405     www      8900:     if (length($env{'form.upfile'}) < 2) {
1.407     albertel 8901:         $result.=&mt('[_1] Error: [_2] The file you attempted to upload, [_3] contained no information. Please check that you entered the correct filename.',
                   8902: 		     '<span class="LC_error">',
                   8903: 		     '</span>',
                   8904: 		     '<span class="LC_filename">'.&HTML::Entities::encode($env{'form.upfile.filename'},'<>&"').'</span>');
1.405     www      8905:         return $result.&show_grading_menu_form($symb);
                   8906:     }
1.410     www      8907: 
                   8908: # Were able to get all the info needed, now analyze the file
                   8909: 
1.411     www      8910:     $result.=&Apache::loncommon::studentbrowser_javascript();
1.418     albertel 8911:     $symb = &Apache::lonenc::check_encrypt($symb);
1.410     www      8912:     my $heading=&mt('Scanning clicker file');
                   8913:     $result.=(<<ENDHEADER);
                   8914: <br /><table width="100%" border="0"><tr><td bgcolor="#777777">
                   8915: <table width="100%" border="0"><tr bgcolor="#e6ffff"><td>
                   8916: <b>$heading</b></td></tr><tr bgcolor=#ffffe6><td>
                   8917: <form method="post" action="/adm/grades" name="clickeranalysis">
                   8918: <input type="hidden" name="symb" value="$symb" />
                   8919: <input type="hidden" name="command" value="assignclickergrades" />
1.411     www      8920: <input type="hidden" name="gradingmechanism" value="$env{'form.gradingmechanism'}" />
                   8921: <input type="hidden" name="pcorrect" value="$env{'form.pcorrect'}" />
                   8922: <input type="hidden" name="pincorrect" value="$env{'form.pincorrect'}" />
1.410     www      8923: ENDHEADER
1.522     www      8924:     if ($env{'form.gradingmechanism'} eq 'given') {
                   8925:        $result.='<input type="hidden" name="correct:given" value="'.$env{'form.givenanswer'}.'" />';
                   8926:     } 
1.408     albertel 8927:     my %responses;
                   8928:     my @questiontitles;
1.405     www      8929:     my $errormsg='';
                   8930:     my $number=0;
                   8931:     if ($env{'form.upfiletype'} eq 'iclicker') {
1.408     albertel 8932: 	($errormsg,$number)=&iclicker_eval(\@questiontitles,\%responses);
1.406     www      8933:     }
1.419     www      8934:     if ($env{'form.upfiletype'} eq 'interwrite') {
                   8935:         ($errormsg,$number)=&interwrite_eval(\@questiontitles,\%responses);
                   8936:     }
1.411     www      8937:     $result.='<br />'.&mt('Found [_1] question(s)',$number).'<br />'.
                   8938:              '<input type="hidden" name="number" value="'.$number.'" />'.
                   8939:              &mt('Awarding [_1] percent for correct and [_2] percent for incorrect responses',
                   8940:                  $env{'form.pcorrect'},$env{'form.pincorrect'}).
                   8941:              '<br />';
1.522     www      8942:     if (($env{'form.gradingmechanism'} eq 'given') && ($number!=$foundgiven)) {
                   8943:        $result.='<span class="LC_error">'.&mt('Number of given answers does not agree with number of questions in file.').'</span>';
                   8944:        return $result.&show_grading_menu_form($symb);
                   8945:     } 
1.414     www      8946: # Remember Question Titles
                   8947: # FIXME: Possibly need delimiter other than ":"
                   8948:     for (my $i=0;$i<$number;$i++) {
                   8949:         $result.='<input type="hidden" name="question:'.$i.'" value="'.
                   8950:                  &HTML::Entities::encode($questiontitles[$i],'"&<>').'" />';
                   8951:     }
1.411     www      8952:     my $correct_count=0;
                   8953:     my $student_count=0;
                   8954:     my $unknown_count=0;
1.414     www      8955: # Match answers with usernames
                   8956: # FIXME: Possibly need delimiter other than ":"
1.409     albertel 8957:     foreach my $id (keys(%responses)) {
1.410     www      8958:        if ($correct_ids{$id}) {
1.414     www      8959:           $result.="\n".'<input type="hidden" name="correct:'.$correct_count.':'.$correct_ids{$id}.'" value="'.$responses{$id}.'" />';
1.411     www      8960:           $correct_count++;
1.410     www      8961:        } elsif ($clicker_ids{$id}) {
1.437     www      8962:           if ($clicker_ids{$id}=~/\,/) {
                   8963: # More than one user with the same clicker!
                   8964:              $result.="\n<hr />".&mt('Clicker registered more than once').": <tt>".$id."</tt><br />";
                   8965:              $result.="\n".'<input type="hidden" name="unknown:'.$id.'" value="'.$responses{$id}.'" />'.
                   8966:                            "<select name='multi".$id."'>";
                   8967:              foreach my $reguser (sort(split(/\,/,$clicker_ids{$id}))) {
                   8968:                  $result.="<option value='".$reguser."'>".&Apache::loncommon::plainname(split(/\:/,$reguser)).' ('.$reguser.')</option>';
                   8969:              }
                   8970:              $result.='</select>';
                   8971:              $unknown_count++;
                   8972:           } else {
                   8973: # Good: found one and only one user with the right clicker
                   8974:              $result.="\n".'<input type="hidden" name="student:'.$clicker_ids{$id}.'" value="'.$responses{$id}.'" />';
                   8975:              $student_count++;
                   8976:           }
1.410     www      8977:        } else {
1.411     www      8978:           $result.="\n<hr />".&mt('Unregistered Clicker')." <tt>".$id."</tt><br />";
                   8979:           $result.="\n".'<input type="hidden" name="unknown:'.$id.'" value="'.$responses{$id}.'" />'.
                   8980:                    "\n".&mt("Username").": <input type='text' name='uname".$id."' />&nbsp;".
                   8981:                    "\n".&mt("Domain").": ".
                   8982:                    &Apache::loncommon::select_dom_form($env{'course.'.$env{'request.course.id'}.'.domain'},'udom'.$id).'&nbsp;'.
                   8983:                    &Apache::loncommon::selectstudent_link('clickeranalysis','uname'.$id,'udom'.$id);
                   8984:           $unknown_count++;
1.410     www      8985:        }
1.405     www      8986:     }
1.412     www      8987:     $result.='<hr />'.
                   8988:              &mt('Found [_1] registered and [_2] unregistered clickers.',$student_count,$unknown_count);
1.521     www      8989:     if (($env{'form.gradingmechanism'} ne 'attendance') && ($env{'form.gradingmechanism'} ne 'given')) {
1.412     www      8990:        if ($correct_count==0) {
                   8991:           $errormsg.="Found no correct answers answers for grading!";
                   8992:        } elsif ($correct_count>1) {
1.414     www      8993:           $result.='<br /><span class="LC_warning">'.&mt("Found [_1] entries for grading!",$correct_count).'</span>';
1.412     www      8994:        }
                   8995:     }
1.428     www      8996:     if ($number<1) {
                   8997:        $errormsg.="Found no questions.";
                   8998:     }
1.412     www      8999:     if ($errormsg) {
                   9000:        $result.='<br /><span class="LC_error">'.&mt($errormsg).'</span>';
                   9001:     } else {
                   9002:        $result.='<br /><input type="submit" name="finalize" value="'.&mt('Finalize Grading').'" />';
                   9003:     }
                   9004:     $result.='</form></td></tr></table>'."\n".
1.410     www      9005:              '</td></tr></table><br /><br />'."\n";
1.404     www      9006:     return $result.&show_grading_menu_form($symb);
1.400     www      9007: }
                   9008: 
1.405     www      9009: sub iclicker_eval {
1.406     www      9010:     my ($questiontitles,$responses)=@_;
1.405     www      9011:     my $number=0;
                   9012:     my $errormsg='';
                   9013:     foreach my $line (split(/[\n\r]/,$env{'form.upfile'})) {
1.410     www      9014:         my %components=&Apache::loncommon::record_sep($line);
                   9015:         my @entries=map {$components{$_}} (sort(keys(%components)));
1.408     albertel 9016: 	if ($entries[0] eq 'Question') {
                   9017: 	    for (my $i=3;$i<$#entries;$i+=6) {
                   9018: 		$$questiontitles[$number]=$entries[$i];
                   9019: 		$number++;
                   9020: 	    }
                   9021: 	}
                   9022: 	if ($entries[0]=~/^\#/) {
                   9023: 	    my $id=$entries[0];
                   9024: 	    my @idresponses;
                   9025: 	    $id=~s/^[\#0]+//;
                   9026: 	    for (my $i=0;$i<$number;$i++) {
                   9027: 		my $idx=3+$i*6;
                   9028: 		push(@idresponses,$entries[$idx]);
                   9029: 	    }
                   9030: 	    $$responses{$id}=join(',',@idresponses);
                   9031: 	}
1.405     www      9032:     }
                   9033:     return ($errormsg,$number);
                   9034: }
                   9035: 
1.419     www      9036: sub interwrite_eval {
                   9037:     my ($questiontitles,$responses)=@_;
                   9038:     my $number=0;
                   9039:     my $errormsg='';
1.420     www      9040:     my $skipline=1;
                   9041:     my $questionnumber=0;
                   9042:     my %idresponses=();
1.419     www      9043:     foreach my $line (split(/[\n\r]/,$env{'form.upfile'})) {
                   9044:         my %components=&Apache::loncommon::record_sep($line);
                   9045:         my @entries=map {$components{$_}} (sort(keys(%components)));
1.420     www      9046:         if ($entries[1] eq 'Time') { $skipline=0; next; }
                   9047:         if ($entries[1] eq 'Response') { $skipline=1; }
                   9048:         next if $skipline;
                   9049:         if ($entries[0]!=$questionnumber) {
                   9050:            $questionnumber=$entries[0];
                   9051:            $$questiontitles[$number]=&mt('Question [_1]',$questionnumber);
                   9052:            $number++;
1.419     www      9053:         }
1.420     www      9054:         my $id=$entries[4];
                   9055:         $id=~s/^[\#0]+//;
1.421     www      9056:         $id=~s/^v\d*\://i;
                   9057:         $id=~s/[\-\:]//g;
1.420     www      9058:         $idresponses{$id}[$number]=$entries[6];
                   9059:     }
1.524     raeburn  9060:     foreach my $id (keys(%idresponses)) {
1.420     www      9061:        $$responses{$id}=join(',',@{$idresponses{$id}});
                   9062:        $$responses{$id}=~s/^\s*\,//;
1.419     www      9063:     }
                   9064:     return ($errormsg,$number);
                   9065: }
                   9066: 
1.414     www      9067: sub assign_clicker_grades {
1.608     www      9068:     my ($r,$symb)=@_;
1.414     www      9069:     if (!$symb) {return '';}
1.416     www      9070: # See which part we are saving to
1.582     raeburn  9071:     my $res_error;
                   9072:     my ($partlist,$handgrade,$responseType) = &response_type($symb,\$res_error);
                   9073:     if ($res_error) {
                   9074:         return &navmap_errormsg();
                   9075:     }
1.416     www      9076: # FIXME: This should probably look for the first handgradeable part
                   9077:     my $part=$$partlist[0];
                   9078: # Start screen output
1.598     www      9079:     my $result='';
1.416     www      9080: 
1.414     www      9081:     my $heading=&mt('Assigning grades based on clicker file');
                   9082:     $result.=(<<ENDHEADER);
                   9083: <br /><table width="100%" border="0"><tr><td bgcolor="#777777">
                   9084: <table width="100%" border="0"><tr bgcolor="#e6ffff"><td>
                   9085: <b>$heading</b></td></tr><tr bgcolor=#ffffe6><td>
                   9086: ENDHEADER
                   9087: # Get correct result
                   9088: # FIXME: Possibly need delimiter other than ":"
                   9089:     my @correct=();
1.415     www      9090:     my $gradingmechanism=$env{'form.gradingmechanism'};
                   9091:     my $number=$env{'form.number'};
                   9092:     if ($gradingmechanism ne 'attendance') {
1.414     www      9093:        foreach my $key (keys(%env)) {
                   9094:           if ($key=~/^form\.correct\:/) {
                   9095:              my @input=split(/\,/,$env{$key});
                   9096:              for (my $i=0;$i<=$#input;$i++) {
                   9097:                  if (($correct[$i]) && ($input[$i]) &&
                   9098:                      ($correct[$i] ne $input[$i])) {
                   9099:                     $result.='<br /><span class="LC_warning">'.
                   9100:                              &mt('More than one correct result given for question "[_1]": [_2] versus [_3].',
                   9101:                                  $env{'form.question:'.$i},$correct[$i],$input[$i]).'</span>';
                   9102:                  } elsif ($input[$i]) {
                   9103:                     $correct[$i]=$input[$i];
                   9104:                  }
                   9105:              }
                   9106:           }
                   9107:        }
1.415     www      9108:        for (my $i=0;$i<$number;$i++) {
1.414     www      9109:           if (!$correct[$i]) {
                   9110:              $result.='<br /><span class="LC_error">'.
                   9111:                       &mt('No correct result given for question "[_1]"!',
                   9112:                           $env{'form.question:'.$i}).'</span>';
                   9113:           }
                   9114:        }
                   9115:        $result.='<br />'.&mt("Correct answer: [_1]",join(', ',map { ($_?$_:'-') } @correct));
                   9116:     }
                   9117: # Start grading
1.415     www      9118:     my $pcorrect=$env{'form.pcorrect'};
                   9119:     my $pincorrect=$env{'form.pincorrect'};
1.416     www      9120:     my $storecount=0;
1.415     www      9121:     foreach my $key (keys(%env)) {
1.420     www      9122:        my $user='';
1.415     www      9123:        if ($key=~/^form\.student\:(.*)$/) {
1.420     www      9124:           $user=$1;
                   9125:        }
                   9126:        if ($key=~/^form\.unknown\:(.*)$/) {
                   9127:           my $id=$1;
                   9128:           if (($env{'form.uname'.$id}) && ($env{'form.udom'.$id})) {
                   9129:              $user=$env{'form.uname'.$id}.':'.$env{'form.udom'.$id};
1.437     www      9130:           } elsif ($env{'form.multi'.$id}) {
                   9131:              $user=$env{'form.multi'.$id};
1.420     www      9132:           }
                   9133:        }
                   9134:        if ($user) { 
1.415     www      9135:           my @answer=split(/\,/,$env{$key});
                   9136:           my $sum=0;
1.522     www      9137:           my $realnumber=$number;
1.415     www      9138:           for (my $i=0;$i<$number;$i++) {
1.576     www      9139:              if  ($correct[$i] eq '-') {
                   9140:                 $realnumber--;
                   9141:              } elsif ($answer[$i]) {
1.415     www      9142:                 if ($gradingmechanism eq 'attendance') {
                   9143:                    $sum+=$pcorrect;
1.576     www      9144:                 } elsif ($correct[$i] eq '*') {
1.522     www      9145:                    $sum+=$pcorrect;
1.415     www      9146:                 } else {
                   9147:                    if ($answer[$i] eq $correct[$i]) {
                   9148:                       $sum+=$pcorrect;
                   9149:                    } else {
                   9150:                       $sum+=$pincorrect;
                   9151:                    }
                   9152:                 }
                   9153:              }
                   9154:           }
1.522     www      9155:           my $ave=$sum/(100*$realnumber);
1.416     www      9156: # Store
                   9157:           my ($username,$domain)=split(/\:/,$user);
                   9158:           my %grades=();
                   9159:           $grades{"resource.$part.solved"}='correct_by_override';
                   9160:           $grades{"resource.$part.awarded"}=$ave;
                   9161:           $grades{"resource.regrader"}="$env{'user.name'}:$env{'user.domain'}";
                   9162:           my $returncode=&Apache::lonnet::cstore(\%grades,$symb,
                   9163:                                                  $env{'request.course.id'},
                   9164:                                                  $domain,$username);
                   9165:           if ($returncode ne 'ok') {
                   9166:              $result.="<br /><span class=\"LC_error\">Failed to save student $username:$domain. Message when trying to save was ($returncode)</span>";
                   9167:           } else {
                   9168:              $storecount++;
                   9169:           }
1.415     www      9170:        }
                   9171:     }
                   9172: # We are done
1.549     hauer    9173:     $result.='<br />'.&mt('Successfully stored grades for [quant,_1,student].',$storecount).
1.416     www      9174:              '</td></tr></table>'."\n".
1.414     www      9175:              '</td></tr></table><br /><br />'."\n";
                   9176:     return $result.&show_grading_menu_form($symb);
                   9177: }
                   9178: 
1.582     raeburn  9179: sub navmap_errormsg {
                   9180:     return '<div class="LC_error">'.
                   9181:            &mt('An error occurred retrieving information about resources in the course.').'<br />'.
1.595     raeburn  9182:            &mt('It is recommended that you [_1]re-initialize the course[_2] and then return to this grading page.','<a href="/adm/roles?selectrole=1&newrole='.$env{'request.role'}.'">','</a>').
1.582     raeburn  9183:            '</div>';
                   9184: }
1.607     droeschl 9185: 
1.609     www      9186: sub startpage {
1.613   ! www      9187:     my ($r,$symb,$crumbs,$onlyfolderflag,$nodisplayflag) = @_;
1.610     www      9188:     unshift(@$crumbs,{href=>"/adm/grades?command=gradingmenu&symb=".&HTML::Entities::encode($symb,'<>&"'),text=>"Grading"});
1.607     droeschl 9189:     $r->print(&Apache::loncommon::start_page('Grading',undef,
1.610     www      9190:                                           {'bread_crumbs' => $crumbs}));
1.613   ! www      9191:     unless ($nodisplayflag) {
        !          9192:        $r->print(&Apache::lonhtmlcommon::resource_info_box($symb,$onlyfolderflag));
        !          9193:     }
1.607     droeschl 9194: }
1.582     raeburn  9195: 
1.1       albertel 9196: sub handler {
1.41      ng       9197:     my $request=$_[0];
1.434     albertel 9198:     &reset_caches();
1.257     albertel 9199:     if ($env{'browser.mathml'}) {
1.141     www      9200: 	&Apache::loncommon::content_type($request,'text/xml');
1.41      ng       9201:     } else {
1.141     www      9202: 	&Apache::loncommon::content_type($request,'text/html');
1.41      ng       9203:     }
                   9204:     $request->send_http_header;
1.44      ng       9205:     return '' if $request->header_only;
1.41      ng       9206:     &Apache::loncommon::get_unprocessed_cgi($ENV{'QUERY_STRING'});
1.608     www      9207: 
                   9208: # see what command we need to execute
                   9209: 
1.160     albertel 9210:     my @commands=&Apache::loncommon::get_env_multiple('form.command');
                   9211:     my $command=$commands[0];
1.447     foxr     9212: 
1.160     albertel 9213:     if ($#commands > 0) {
                   9214: 	&Apache::lonnet::logthis("grades got multiple commands ".join(':',@commands));
                   9215:     }
1.608     www      9216: 
                   9217: # see what the symb is
                   9218: 
                   9219:     my $symb=$env{'form.symb'};
                   9220:     unless ($symb) {
                   9221:        (my $url=$env{'form.url'}) =~ s-^https*://($ENV{'SERVER_NAME'}|$ENV{'HTTP_HOST'})--;
                   9222:        $symb=&Apache::lonnet::symbread($url);
                   9223:     }
                   9224:     &Apache::lonenc::check_decrypt(\$symb);                             
                   9225: 
1.513     foxr     9226:     $ssi_error = 0;
1.324     albertel 9227:     if ($symb eq '' && $command eq '') {
1.601     www      9228: #
                   9229: # Not called from a resource
                   9230: #    
                   9231: 
1.41      ng       9232:     } else {
1.285     albertel 9233: 	&init_perm();
1.104     albertel 9234: 	if ($command eq 'submission' && $perm{'vgr'}) {
1.608     www      9235:             &startpage($request,$symb,[{href=>"", text=>"Student Submissions"}]);
1.611     www      9236: 	    ($env{'form.student'} eq '' ? &listStudents($request,$symb) : &submission($request,0,0,$symb));
1.103     albertel 9237: 	} elsif ($command eq 'pickStudentPage' && $perm{'vgr'}) {
1.611     www      9238:             &startpage($request,$symb);
1.608     www      9239: 	    &pickStudentPage($request,$symb);
1.103     albertel 9240: 	} elsif ($command eq 'displayPage' && $perm{'vgr'}) {
1.611     www      9241:             &startpage($request,$symb);
1.608     www      9242: 	    &displayPage($request,$symb);
1.104     albertel 9243: 	} elsif ($command eq 'gradeByPage' && $perm{'mgr'}) {
1.611     www      9244:             &startpage($request,$symb);
1.608     www      9245: 	    &updateGradeByPage($request,$symb);
1.104     albertel 9246: 	} elsif ($command eq 'processGroup' && $perm{'vgr'}) {
1.611     www      9247:             &startpage($request,$symb);
1.608     www      9248: 	    &processGroup($request,$symb);
1.104     albertel 9249: 	} elsif ($command eq 'gradingmenu' && $perm{'vgr'}) {
1.608     www      9250:             &startpage($request,$symb);
                   9251: 	    $request->print(&grading_menu($request,$symb));
1.598     www      9252: 	} elsif ($command eq 'individual' && $perm{'vgr'}) {
1.611     www      9253:             &startpage($request,$symb);
1.608     www      9254: 	    $request->print(&submit_options($request,$symb));
1.598     www      9255:         } elsif ($command eq 'ungraded' && $perm{'vgr'}) {
1.611     www      9256:             &startpage($request,$symb);
1.608     www      9257:             $request->print(&submit_options($request,$symb));
1.598     www      9258:         } elsif ($command eq 'table' && $perm{'vgr'}) {
1.613   ! www      9259:             &startpage($request,$symb,[{href=>"", text=>"Grading table"}],1);
1.611     www      9260:             $request->print(&submit_options_table($request,$symb));
1.598     www      9261:         } elsif ($command eq 'all_for_one' && $perm{'vgr'}) {
1.611     www      9262:             &startpage($request,$symb);
1.608     www      9263:             $request->print(&submit_options_sequence($request,$symb));
1.104     albertel 9264: 	} elsif ($command eq 'viewgrades' && $perm{'vgr'}) {
1.613   ! www      9265:             &startpage($request,$symb,[{href=>"/adm/grades?symb=".&HTML::Entities::encode($symb,'<>&"')."&command=table", text=>"Grading table"},{href=>'', text=>"Modify grades"}],1);
1.608     www      9266: 	    $request->print(&viewgrades($request,$symb));
1.104     albertel 9267: 	} elsif ($command eq 'handgrade' && $perm{'mgr'}) {
1.611     www      9268:             &startpage($request,$symb);
1.608     www      9269: 	    $request->print(&processHandGrade($request,$symb));
1.106     albertel 9270: 	} elsif ($command eq 'editgrades' && $perm{'mgr'}) {
1.611     www      9271:             &startpage($request,$symb);
1.608     www      9272: 	    $request->print(&editgrades($request,$symb));
1.602     www      9273:         } elsif ($command eq 'initialverifyreceipt' && $perm{'vgr'}) {
1.611     www      9274:             &startpage($request,$symb);
                   9275:             $request->print(&initialverifyreceipt($request,$symb));
1.106     albertel 9276: 	} elsif ($command eq 'verify' && $perm{'vgr'}) {
1.611     www      9277:             &startpage($request,$symb);
1.608     www      9278: 	    $request->print(&verifyreceipt($request,$symb));
1.400     www      9279:         } elsif ($command eq 'processclicker' && $perm{'mgr'}) {
1.611     www      9280:             &startpage($request,$symb);
1.608     www      9281:             $request->print(&process_clicker($request,$symb));
1.400     www      9282:         } elsif ($command eq 'processclickerfile' && $perm{'mgr'}) {
1.611     www      9283:             &startpage($request,$symb);
1.608     www      9284:             $request->print(&process_clicker_file($request,$symb));
1.414     www      9285:         } elsif ($command eq 'assignclickergrades' && $perm{'mgr'}) {
1.611     www      9286:             &startpage($request,$symb);
1.608     www      9287:             $request->print(&assign_clicker_grades($request,$symb));
1.106     albertel 9288: 	} elsif ($command eq 'csvform' && $perm{'mgr'}) {
1.611     www      9289:             &startpage($request,$symb);
1.608     www      9290: 	    $request->print(&upcsvScores_form($request,$symb));
1.106     albertel 9291: 	} elsif ($command eq 'csvupload' && $perm{'mgr'}) {
1.611     www      9292:             &startpage($request,$symb);
1.608     www      9293: 	    $request->print(&csvupload($request,$symb));
1.106     albertel 9294: 	} elsif ($command eq 'csvuploadmap' && $perm{'mgr'} ) {
1.611     www      9295:             &startpage($request,$symb);
1.608     www      9296: 	    $request->print(&csvuploadmap($request,$symb));
1.246     albertel 9297: 	} elsif ($command eq 'csvuploadoptions' && $perm{'mgr'}) {
1.257     albertel 9298: 	    if ($env{'form.associate'} ne 'Reverse Association') {
1.611     www      9299:                 &startpage($request,$symb);
1.608     www      9300: 		$request->print(&csvuploadoptions($request,$symb));
1.41      ng       9301: 	    } else {
1.257     albertel 9302: 		if ( $env{'form.upfile_associate'} ne 'reverse' ) {
                   9303: 		    $env{'form.upfile_associate'} = 'reverse';
1.41      ng       9304: 		} else {
1.257     albertel 9305: 		    $env{'form.upfile_associate'} = 'forward';
1.41      ng       9306: 		}
1.611     www      9307:                 &startpage($request,$symb);
1.608     www      9308: 		$request->print(&csvuploadmap($request,$symb));
1.41      ng       9309: 	    }
1.246     albertel 9310: 	} elsif ($command eq 'csvuploadassign' && $perm{'mgr'} ) {
1.611     www      9311:             &startpage($request,$symb);
1.608     www      9312: 	    $request->print(&csvuploadassign($request,$symb));
1.106     albertel 9313: 	} elsif ($command eq 'scantron_selectphase' && $perm{'mgr'}) {
1.611     www      9314:             &startpage($request,$symb);
1.612     www      9315: 	    $request->print(&scantron_selectphase($request,undef,$symb));
1.203     albertel 9316:  	} elsif ($command eq 'scantron_warning' && $perm{'mgr'}) {
1.611     www      9317:             &startpage($request,$symb);
1.608     www      9318:  	    $request->print(&scantron_do_warning($request,$symb));
1.142     albertel 9319: 	} elsif ($command eq 'scantron_validate' && $perm{'mgr'}) {
1.611     www      9320:             &startpage($request,$symb);
1.608     www      9321: 	    $request->print(&scantron_validate_file($request,$symb));
1.106     albertel 9322: 	} elsif ($command eq 'scantron_process' && $perm{'mgr'}) {
1.611     www      9323:             &startpage($request,$symb);
1.608     www      9324: 	    $request->print(&scantron_process_students($request,$symb));
1.157     albertel 9325:  	} elsif ($command eq 'scantronupload' && 
1.257     albertel 9326:  		 (&Apache::lonnet::allowed('usc',$env{'request.role.domain'})||
                   9327: 		  &Apache::lonnet::allowed('usc',$env{'request.course.id'}))) {
1.611     www      9328:             &startpage($request,$symb);
1.608     www      9329:  	    $request->print(&scantron_upload_scantron_data($request,$symb)); 
1.157     albertel 9330:  	} elsif ($command eq 'scantronupload_save' &&
1.257     albertel 9331:  		 (&Apache::lonnet::allowed('usc',$env{'request.role.domain'})||
                   9332: 		  &Apache::lonnet::allowed('usc',$env{'request.course.id'}))) {
1.611     www      9333:             &startpage($request,$symb);
1.608     www      9334:  	    $request->print(&scantron_upload_scantron_data_save($request,$symb));
1.202     albertel 9335:  	} elsif ($command eq 'scantron_download' &&
1.257     albertel 9336: 		 &Apache::lonnet::allowed('usc',$env{'request.course.id'})) {
1.611     www      9337:             &startpage($request,$symb);
1.608     www      9338:  	    $request->print(&scantron_download_scantron_data($request,$symb));
1.523     raeburn  9339:         } elsif ($command eq 'checksubmissions' && $perm{'vgr'}) {
1.611     www      9340:             &startpage($request,$symb);
1.608     www      9341:             $request->print(&checkscantron_results($request,$symb));     
1.106     albertel 9342: 	} elsif ($command) {
1.611     www      9343:             &startpage($request,$symb);
1.562     bisitz   9344: 	    $request->print('<p class="LC_error">'.&mt('Access Denied ([_1])',$command).'</p>');
1.26      albertel 9345: 	}
1.2       albertel 9346:     }
1.513     foxr     9347:     if ($ssi_error) {
                   9348: 	&ssi_print_error($request);
                   9349:     }
1.353     albertel 9350:     $request->print(&Apache::loncommon::end_page());
1.434     albertel 9351:     &reset_caches();
1.44      ng       9352:     return '';
                   9353: }
                   9354: 
1.1       albertel 9355: 1;
                   9356: 
1.13      albertel 9357: __END__;
1.531     jms      9358: 
                   9359: 
                   9360: =head1 NAME
                   9361: 
                   9362: Apache::grades
                   9363: 
                   9364: =head1 SYNOPSIS
                   9365: 
                   9366: Handles the viewing of grades.
                   9367: 
                   9368: This is part of the LearningOnline Network with CAPA project
                   9369: described at http://www.lon-capa.org.
                   9370: 
                   9371: =head1 OVERVIEW
                   9372: 
                   9373: Do an ssi with retries:
                   9374: While I'd love to factor out this with the vesrion in lonprintout,
                   9375: 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
                   9376: I'm not quite ready to invent (e.g. an ssi_with_retry object).
                   9377: 
                   9378: At least the logic that drives this has been pulled out into loncommon.
                   9379: 
                   9380: 
                   9381: 
                   9382: ssi_with_retries - Does the server side include of a resource.
                   9383:                      if the ssi call returns an error we'll retry it up to
                   9384:                      the number of times requested by the caller.
                   9385:                      If we still have a proble, no text is appended to the
                   9386:                      output and we set some global variables.
                   9387:                      to indicate to the caller an SSI error occurred.  
                   9388:                      All of this is supposed to deal with the issues described
                   9389:                      in LonCAPA BZ 5631 see:
                   9390:                      http://bugs.lon-capa.org/show_bug.cgi?id=5631
                   9391:                      by informing the user that this happened.
                   9392: 
                   9393: Parameters:
                   9394:   resource   - The resource to include.  This is passed directly, without
                   9395:                interpretation to lonnet::ssi.
                   9396:   form       - The form hash parameters that guide the interpretation of the resource
                   9397:                
                   9398:   retries    - Number of retries allowed before giving up completely.
                   9399: Returns:
                   9400:   On success, returns the rendered resource identified by the resource parameter.
                   9401: Side Effects:
                   9402:   The following global variables can be set:
                   9403:    ssi_error                - If an unrecoverable error occurred this becomes true.
                   9404:                               It is up to the caller to initialize this to false
                   9405:                               if desired.
                   9406:    ssi_error_resource  - If an unrecoverable error occurred, this is the value
                   9407:                               of the resource that could not be rendered by the ssi
                   9408:                               call.
                   9409:    ssi_error_message   - The error string fetched from the ssi response
                   9410:                               in the event of an error.
                   9411: 
                   9412: 
                   9413: =head1 HANDLER SUBROUTINE
                   9414: 
                   9415: ssi_with_retries()
                   9416: 
                   9417: =head1 SUBROUTINES
                   9418: 
                   9419: =over
                   9420: 
                   9421: =item scantron_get_correction() : 
                   9422: 
                   9423:    Builds the interface screen to interact with the operator to fix a
                   9424:    specific error condition in a specific scanline
                   9425: 
                   9426:  Arguments:
                   9427:     $r           - Apache request object
                   9428:     $i           - number of the current scanline
                   9429:     $scan_record - hash ref as returned from &scantron_parse_scanline()
                   9430:     $scan_config - hash ref as returned from &get_scantron_config()
                   9431:     $line        - full contents of the current scanline
                   9432:     $error       - error condition, valid values are
                   9433:                    'incorrectCODE', 'duplicateCODE',
                   9434:                    'doublebubble', 'missingbubble',
                   9435:                    'duplicateID', 'incorrectID'
                   9436:     $arg         - extra information needed
                   9437:        For errors:
                   9438:          - duplicateID   - paper number that this studentID was seen before on
                   9439:          - duplicateCODE - array ref of the paper numbers this CODE was
                   9440:                            seen on before
                   9441:          - incorrectCODE - current incorrect CODE 
                   9442:          - doublebubble  - array ref of the bubble lines that have double
                   9443:                            bubble errors
                   9444:          - missingbubble - array ref of the bubble lines that have missing
                   9445:                            bubble errors
                   9446: 
                   9447: =item  scantron_get_maxbubble() : 
                   9448: 
1.582     raeburn  9449:    Arguments:
                   9450:        $nav_error  - Reference to scalar which is a flag to indicate a
                   9451:                       failure to retrieve a navmap object.
                   9452:        if $nav_error is set to 1 by scantron_get_maxbubble(), the 
                   9453:        calling routine should trap the error condition and display the warning
                   9454:        found in &navmap_errormsg().
                   9455: 
1.531     jms      9456:    Returns the maximum number of bubble lines that are expected to
                   9457:    occur. Does this by walking the selected sequence rendering the
                   9458:    resource and then checking &Apache::lonxml::get_problem_counter()
                   9459:    for what the current value of the problem counter is.
                   9460: 
                   9461:    Caches the results to $env{'form.scantron_maxbubble'},
                   9462:    $env{'form.scantron.bubble_lines.n'}, 
                   9463:    $env{'form.scantron.first_bubble_line.n'} and
                   9464:    $env{"form.scantron.sub_bubblelines.n"}
                   9465:    which are the total number of bubble, lines, the number of bubble
                   9466:    lines for response n and number of the first bubble line for response n,
                   9467:    and a comma separated list of numbers of bubble lines for sub-questions
                   9468:    (for optionresponse, matchresponse, and rankresponse items), for response n.  
                   9469: 
                   9470: 
                   9471: =item  scantron_validate_missingbubbles() : 
                   9472: 
                   9473:    Validates all scanlines in the selected file to not have any
                   9474:     answers that don't have bubbles that have not been verified
                   9475:     to be bubble free.
                   9476: 
                   9477: =item  scantron_process_students() : 
                   9478: 
                   9479:    Routine that does the actual grading of the bubble sheet information.
                   9480: 
                   9481:    The parsed scanline hash is added to %env 
                   9482: 
                   9483:    Then foreach unskipped scanline it does an &Apache::lonnet::ssi()
                   9484:    foreach resource , with the form data of
                   9485: 
                   9486: 	'submitted'     =>'scantron' 
                   9487: 	'grade_target'  =>'grade',
                   9488: 	'grade_username'=> username of student
                   9489: 	'grade_domain'  => domain of student
                   9490: 	'grade_courseid'=> of course
                   9491: 	'grade_symb'    => symb of resource to grade
                   9492: 
                   9493:     This triggers a grading pass. The problem grading code takes care
                   9494:     of converting the bubbled letter information (now in %env) into a
                   9495:     valid submission.
                   9496: 
                   9497: =item  scantron_upload_scantron_data() :
                   9498: 
                   9499:     Creates the screen for adding a new bubble sheet data file to a course.
                   9500: 
                   9501: =item  scantron_upload_scantron_data_save() : 
                   9502: 
                   9503:    Adds a provided bubble information data file to the course if user
                   9504:    has the correct privileges to do so. 
                   9505: 
                   9506: =item  valid_file() :
                   9507: 
                   9508:    Validates that the requested bubble data file exists in the course.
                   9509: 
                   9510: =item  scantron_download_scantron_data() : 
                   9511: 
                   9512:    Shows a list of the three internal files (original, corrected,
                   9513:    skipped) for a specific bubble sheet data file that exists in the
                   9514:    course.
                   9515: 
                   9516: =item  scantron_validate_ID() : 
                   9517: 
                   9518:    Validates all scanlines in the selected file to not have any
1.556     weissno  9519:    invalid or underspecified student/employee IDs
1.531     jms      9520: 
1.582     raeburn  9521: =item navmap_errormsg() :
                   9522: 
                   9523:    Returns HTML mark-up inside a <div></div> with a link to re-initialize the course.
                   9524:    Should be called whenever the request to instantiate a navmap object fails.  
                   9525: 
1.531     jms      9526: =back
                   9527: 
                   9528: =cut

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