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

1.17      albertel    1: # The LearningOnline Network with CAPA
1.13      albertel    2: # The LON-CAPA Grading handler
1.17      albertel    3: #
1.616   ! www         4: # $Id: grades.pm,v 1.615 2010/04/13 11:38:30 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.614     www       803:     return $string;
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:     }
                   1085:     $request->print($gradeTable);
1.44      ng       1086:     return '';
1.10      ng       1087: }
                   1088: 
1.44      ng       1089: #---- Called from the listStudents routine
1.249     albertel 1090: 
                   1091: sub check_script {
                   1092:     my ($form, $type)=@_;
1.597     wenzelju 1093:     my $chkallscript= &Apache::lonhtmlcommon::scripttag('
1.249     albertel 1094:     function checkall() {
                   1095:         for (i=0; i<document.forms.'.$form.'.elements.length; i++) {
                   1096:             ele = document.forms.'.$form.'.elements[i];
                   1097:             if (ele.name == "'.$type.'") {
                   1098:             document.forms.'.$form.'.elements[i].checked=true;
                   1099:                                        }
                   1100:         }
                   1101:     }
                   1102: 
                   1103:     function checksec() {
                   1104:         for (i=0; i<document.forms.'.$form.'.elements.length; i++) {
                   1105:             ele = document.forms.'.$form.'.elements[i];
                   1106:            string = document.forms.'.$form.'.chksec.value;
                   1107:            if
                   1108:           (ele.value.indexOf(":::SECTION"+string)>0) {
                   1109:               document.forms.'.$form.'.elements[i].checked=true;
                   1110:             }
                   1111:         }
                   1112:     }
                   1113: 
                   1114: 
                   1115:     function uncheckall() {
                   1116:         for (i=0; i<document.forms.'.$form.'.elements.length; i++) {
                   1117:             ele = document.forms.'.$form.'.elements[i];
                   1118:             if (ele.name == "'.$type.'") {
                   1119:             document.forms.'.$form.'.elements[i].checked=false;
                   1120:                                        }
                   1121:         }
                   1122:     }
                   1123: 
1.597     wenzelju 1124: '."\n");
1.249     albertel 1125:     return $chkallscript;
                   1126: }
                   1127: 
                   1128: sub check_buttons {
1.485     albertel 1129:     my $buttons.='<input type="button" onclick="checkall()" value="'.&mt('Check All').'" />';
                   1130:     $buttons.='<input type="button" onclick="uncheckall()" value="'.&mt('Uncheck All').'" />&nbsp;';
                   1131:     $buttons.='<input type="button" onclick="checksec()" value="'.&mt('Check Section/Group').'" />';
1.249     albertel 1132:     $buttons.='<input type="text" size="5" name="chksec" />&nbsp;';
                   1133:     return $buttons;
                   1134: }
                   1135: 
1.44      ng       1136: #     Displays the submissions for one student or a group of students
1.34      ng       1137: sub processGroup {
1.41      ng       1138:     my ($request)  = shift;
                   1139:     my $ctr        = 0;
1.155     albertel 1140:     my @stuchecked = &Apache::loncommon::get_env_multiple('form.stuinfo');
1.41      ng       1141:     my $total      = scalar(@stuchecked)-1;
1.45      ng       1142: 
1.396     banghart 1143:     foreach my $student (@stuchecked) {
                   1144: 	my ($uname,$udom,$fullname) = split(/:/,$student);
1.257     albertel 1145: 	$env{'form.student'}        = $uname;
                   1146: 	$env{'form.userdom'}        = $udom;
                   1147: 	$env{'form.fullname'}       = $fullname;
1.41      ng       1148: 	&submission($request,$ctr,$total);
                   1149: 	$ctr++;
                   1150:     }
                   1151:     return '';
1.35      ng       1152: }
1.34      ng       1153: 
1.44      ng       1154: #------------------------------------------------------------------------------------
                   1155: #
                   1156: #-------------------------- Next few routines handles grading by student, essentially
                   1157: #                           handles essay response type problem/part
                   1158: #
                   1159: #--- Javascript to handle the submission page functionality ---
                   1160: sub sub_page_js {
                   1161:     my $request = shift;
1.539     riegler  1162: 	    my $alertmsg = &mt('A number equal or greater than 0 is expected. Entered value = ');
1.597     wenzelju 1163:     $request->print(&Apache::lonhtmlcommon::scripttag(<<SUBJAVASCRIPT));
1.71      ng       1164:     function updateRadio(formname,id,weight) {
1.125     ng       1165: 	var gradeBox = formname["GD_BOX"+id];
                   1166: 	var radioButton = formname["RADVAL"+id];
                   1167: 	var oldpts = formname["oldpts"+id].value;
1.72      ng       1168: 	var pts = checkSolved(formname,id) == 'update' ? gradeBox.value : oldpts;
1.71      ng       1169: 	gradeBox.value = pts;
                   1170: 	var resetbox = false;
                   1171: 	if (isNaN(pts) || pts < 0) {
1.539     riegler  1172: 	    alert("$alertmsg"+pts);
1.71      ng       1173: 	    for (var i=0; i<radioButton.length; i++) {
                   1174: 		if (radioButton[i].checked) {
                   1175: 		    gradeBox.value = i;
                   1176: 		    resetbox = true;
                   1177: 		}
                   1178: 	    }
                   1179: 	    if (!resetbox) {
                   1180: 		formtextbox.value = "";
                   1181: 	    }
                   1182: 	    return;
1.44      ng       1183: 	}
1.71      ng       1184: 
                   1185: 	if (pts > weight) {
                   1186: 	    var resp = confirm("You entered a value ("+pts+
                   1187: 			       ") greater than the weight for the part. Accept?");
                   1188: 	    if (resp == false) {
1.125     ng       1189: 		gradeBox.value = oldpts;
1.71      ng       1190: 		return;
                   1191: 	    }
1.44      ng       1192: 	}
1.13      albertel 1193: 
1.71      ng       1194: 	for (var i=0; i<radioButton.length; i++) {
                   1195: 	    radioButton[i].checked=false;
                   1196: 	    if (pts == i && pts != "") {
                   1197: 		radioButton[i].checked=true;
                   1198: 	    }
                   1199: 	}
                   1200: 	updateSelect(formname,id);
1.125     ng       1201: 	formname["stores"+id].value = "0";
1.41      ng       1202:     }
1.5       albertel 1203: 
1.72      ng       1204:     function writeBox(formname,id,pts) {
1.125     ng       1205: 	var gradeBox = formname["GD_BOX"+id];
1.71      ng       1206: 	if (checkSolved(formname,id) == 'update') {
                   1207: 	    gradeBox.value = pts;
                   1208: 	} else {
1.125     ng       1209: 	    var oldpts = formname["oldpts"+id].value;
1.72      ng       1210: 	    gradeBox.value = oldpts;
1.125     ng       1211: 	    var radioButton = formname["RADVAL"+id];
1.71      ng       1212: 	    for (var i=0; i<radioButton.length; i++) {
                   1213: 		radioButton[i].checked=false;
1.72      ng       1214: 		if (i == oldpts) {
1.71      ng       1215: 		    radioButton[i].checked=true;
                   1216: 		}
                   1217: 	    }
1.41      ng       1218: 	}
1.125     ng       1219: 	formname["stores"+id].value = "0";
1.71      ng       1220: 	updateSelect(formname,id);
                   1221: 	return;
1.41      ng       1222:     }
1.44      ng       1223: 
1.71      ng       1224:     function clearRadBox(formname,id) {
                   1225: 	if (checkSolved(formname,id) == 'noupdate') {
                   1226: 	    updateSelect(formname,id);
                   1227: 	    return;
                   1228: 	}
1.125     ng       1229: 	gradeSelect = formname["GD_SEL"+id];
1.71      ng       1230: 	for (var i=0; i<gradeSelect.length; i++) {
                   1231: 	    if (gradeSelect[i].selected) {
                   1232: 		var selectx=i;
                   1233: 	    }
                   1234: 	}
1.125     ng       1235: 	var stores = formname["stores"+id];
1.71      ng       1236: 	if (selectx == stores.value) { return };
1.125     ng       1237: 	var gradeBox = formname["GD_BOX"+id];
1.71      ng       1238: 	gradeBox.value = "";
1.125     ng       1239: 	var radioButton = formname["RADVAL"+id];
1.71      ng       1240: 	for (var i=0; i<radioButton.length; i++) {
                   1241: 	    radioButton[i].checked=false;
                   1242: 	}
                   1243: 	stores.value = selectx;
                   1244:     }
1.5       albertel 1245: 
1.71      ng       1246:     function checkSolved(formname,id) {
1.125     ng       1247: 	if (formname["solved"+id].value == "correct_by_student" && formname.overRideScore.value == 'no') {
1.118     ng       1248: 	    var reply = confirm("This problem has been graded correct by the computer. Do you want to change the score?");
                   1249: 	    if (!reply) {return "noupdate";}
1.120     ng       1250: 	    formname.overRideScore.value = 'yes';
1.41      ng       1251: 	}
1.71      ng       1252: 	return "update";
1.13      albertel 1253:     }
1.71      ng       1254: 
                   1255:     function updateSelect(formname,id) {
1.125     ng       1256: 	formname["GD_SEL"+id][0].selected = true;
1.71      ng       1257: 	return;
1.41      ng       1258:     }
1.33      ng       1259: 
1.121     ng       1260: //=========== Check that a point is assigned for all the parts  ============
1.71      ng       1261:     function checksubmit(formname,val,total,parttot) {
1.121     ng       1262: 	formname.gradeOpt.value = val;
1.71      ng       1263: 	if (val == "Save & Next") {
                   1264: 	    for (i=0;i<=total;i++) {
                   1265: 		for (j=0;j<parttot;j++) {
1.125     ng       1266: 		    var partid = formname["partid"+i+"_"+j].value;
1.127     ng       1267: 		    if (formname["GD_SEL"+i+"_"+partid][0].selected) {
1.125     ng       1268: 			var points = formname["GD_BOX"+i+"_"+partid].value;
1.71      ng       1269: 			if (points == "") {
1.125     ng       1270: 			    var name = formname["name"+i].value;
1.129     ng       1271: 			    var studentID = (name != '' ? name : formname["unamedom"+i].value);
                   1272: 			    var resp = confirm("You did not assign a score for "+studentID+
                   1273: 					       ", part "+partid+". Continue?");
1.71      ng       1274: 			    if (resp == false) {
1.125     ng       1275: 				formname["GD_BOX"+i+"_"+partid].focus();
1.71      ng       1276: 				return false;
                   1277: 			    }
                   1278: 			}
                   1279: 		    }
                   1280: 		    
                   1281: 		}
                   1282: 	    }
                   1283: 	    
                   1284: 	}
1.121     ng       1285: 	if (val == "Grade Student") {
                   1286: 	    formname.showgrading.value = "yes";
                   1287: 	    if (formname.Status.value == "") {
                   1288: 		formname.Status.value = "Active";
                   1289: 	    }
                   1290: 	    formname.studentNo.value = total;
                   1291: 	}
1.120     ng       1292: 	formname.submit();
                   1293:     }
                   1294: 
1.71      ng       1295: //======= Check that a score is assigned for all the problems (page/sequence grading only) =========
                   1296:     function checkSubmitPage(formname,total) {
                   1297: 	noscore = new Array(100);
                   1298: 	var ptr = 0;
                   1299: 	for (i=1;i<total;i++) {
1.125     ng       1300: 	    var partid = formname["q_"+i].value;
1.127     ng       1301: 	    if (formname["GD_SEL"+i+"_"+partid][0].selected) {
1.125     ng       1302: 		var points = formname["GD_BOX"+i+"_"+partid].value;
                   1303: 		var status = formname["solved"+i+"_"+partid].value;
1.71      ng       1304: 		if (points == "" && status != "correct_by_student") {
                   1305: 		    noscore[ptr] = i;
                   1306: 		    ptr++;
                   1307: 		}
                   1308: 	    }
                   1309: 	}
                   1310: 	if (ptr != 0) {
                   1311: 	    var sense = ptr == 1 ? ": " : "s: ";
                   1312: 	    var prolist = "";
                   1313: 	    if (ptr == 1) {
                   1314: 		prolist = noscore[0];
                   1315: 	    } else {
                   1316: 		var i = 0;
                   1317: 		while (i < ptr-1) {
                   1318: 		    prolist += noscore[i]+", ";
                   1319: 		    i++;
                   1320: 		}
                   1321: 		prolist += "and "+noscore[i];
                   1322: 	    }
                   1323: 	    var resp = confirm("You did not assign any score for the following problem"+sense+prolist+". Continue?");
                   1324: 	    if (resp == false) {
                   1325: 		return false;
                   1326: 	    }
                   1327: 	}
1.45      ng       1328: 
1.71      ng       1329: 	formname.submit();
                   1330:     }
                   1331: SUBJAVASCRIPT
                   1332: }
1.45      ng       1333: 
1.71      ng       1334: #--- javascript for essay type problem --
                   1335: sub sub_page_kw_js {
                   1336:     my $request = shift;
1.80      ng       1337:     my $iconpath = $request->dir_config('lonIconsURL');
1.118     ng       1338:     &commonJSfunctions($request);
1.350     albertel 1339: 
1.597     wenzelju 1340:     my $inner_js_msg_central= &Apache::lonhtmlcommon::scripttag(<<INNERJS);
1.350     albertel 1341:     function checkInput() {
                   1342:       opener.document.SCORE.msgsub.value = opener.checkEntities(document.msgcenter.msgsub.value);
                   1343:       var nmsg   = opener.document.SCORE.savemsgN.value;
                   1344:       var usrctr = document.msgcenter.usrctr.value;
                   1345:       var newval = opener.document.SCORE["newmsg"+usrctr];
                   1346:       newval.value = opener.checkEntities(document.msgcenter.newmsg.value);
                   1347: 
                   1348:       var msgchk = "";
                   1349:       if (document.msgcenter.subchk.checked) {
                   1350:          msgchk = "msgsub,";
                   1351:       }
                   1352:       var includemsg = 0;
                   1353:       for (var i=1; i<=nmsg; i++) {
                   1354:           var opnmsg = opener.document.SCORE["savemsg"+i];
                   1355:           var frmmsg = document.msgcenter["msg"+i];
                   1356:           opnmsg.value = opener.checkEntities(frmmsg.value);
                   1357:           var showflg = opener.document.SCORE["shownOnce"+i];
                   1358:           showflg.value = "1";
                   1359:           var chkbox = document.msgcenter["msgn"+i];
                   1360:           if (chkbox.checked) {
                   1361:              msgchk += "savemsg"+i+",";
                   1362:              includemsg = 1;
                   1363:           }
                   1364:       }
                   1365:       if (document.msgcenter.newmsgchk.checked) {
                   1366:          msgchk += "newmsg"+usrctr;
                   1367:          includemsg = 1;
                   1368:       }
                   1369:       imgformname = opener.document.SCORE["mailicon"+usrctr];
                   1370:       imgformname.src = "$iconpath/"+((includemsg) ? "mailto.gif" : "mailbkgrd.gif");
                   1371:       var includemsg = opener.document.SCORE["includemsg"+usrctr];
                   1372:       includemsg.value = msgchk;
                   1373: 
                   1374:       self.close()
                   1375: 
                   1376:     }
                   1377: INNERJS
                   1378: 
1.597     wenzelju 1379:     my $inner_js_highlight_central= &Apache::lonhtmlcommon::scripttag(<<INNERJS);
1.351     albertel 1380:     function updateChoice(flag) {
                   1381:       opener.document.SCORE.kwclr.value = opener.radioSelection(document.hlCenter.kwdclr);
                   1382:       opener.document.SCORE.kwsize.value = opener.radioSelection(document.hlCenter.kwdsize);
                   1383:       opener.document.SCORE.kwstyle.value = opener.radioSelection(document.hlCenter.kwdstyle);
                   1384:       opener.document.SCORE.refresh.value = "on";
                   1385:       if (opener.document.SCORE.keywords.value!=""){
                   1386:          opener.document.SCORE.submit();
                   1387:       }
                   1388:       self.close()
                   1389:     }
                   1390: INNERJS
                   1391: 
                   1392:     my $start_page_msg_central = 
                   1393:         &Apache::loncommon::start_page('Message Central',$inner_js_msg_central,
                   1394: 				       {'js_ready'  => 1,
                   1395: 					'only_body' => 1,
                   1396: 					'bgcolor'   =>'#FFFFFF',});
                   1397:     my $end_page_msg_central = 
                   1398: 	&Apache::loncommon::end_page({'js_ready' => 1});
                   1399: 
                   1400: 
                   1401:     my $start_page_highlight_central = 
                   1402:         &Apache::loncommon::start_page('Highlight Central',
                   1403: 				       $inner_js_highlight_central,
1.350     albertel 1404: 				       {'js_ready'  => 1,
                   1405: 					'only_body' => 1,
                   1406: 					'bgcolor'   =>'#FFFFFF',});
1.351     albertel 1407:     my $end_page_highlight_central = 
1.350     albertel 1408: 	&Apache::loncommon::end_page({'js_ready' => 1});
                   1409: 
1.219     www      1410:     my $docopen=&Apache::lonhtmlcommon::javascript_docopen();
1.236     albertel 1411:     $docopen=~s/^document\.//;
1.539     riegler  1412:     my $alertmsg = &mt('Please select a word or group of words from document and then click this link.');
1.597     wenzelju 1413:     $request->print(&Apache::lonhtmlcommon::scripttag(<<SUBJAVASCRIPT));
1.45      ng       1414: 
1.44      ng       1415: //===================== Show list of keywords ====================
1.122     ng       1416:   function keywords(formname) {
                   1417:     var nret = prompt("Keywords list, separated by a space. Add/delete to list if desired.",formname.keywords.value);
1.44      ng       1418:     if (nret==null) return;
1.122     ng       1419:     formname.keywords.value = nret;
1.44      ng       1420: 
1.122     ng       1421:     if (formname.keywords.value != "") {
1.128     ng       1422: 	formname.refresh.value = "on";
1.122     ng       1423: 	formname.submit();
1.44      ng       1424:     }
                   1425:     return;
                   1426:   }
                   1427: 
                   1428: //===================== Script to view submitted by ==================
                   1429:   function viewSubmitter(submitter) {
                   1430:     document.SCORE.refresh.value = "on";
                   1431:     document.SCORE.NCT.value = "1";
                   1432:     document.SCORE.unamedom0.value = submitter;
                   1433:     document.SCORE.submit();
                   1434:     return;
                   1435:   }
                   1436: 
                   1437: //===================== Script to add keyword(s) ==================
                   1438:   function getSel() {
                   1439:     if (document.getSelection) txt = document.getSelection();
                   1440:     else if (document.selection) txt = document.selection.createRange().text;
                   1441:     else return;
                   1442:     var cleantxt = txt.replace(new RegExp('([\\f\\n\\r\\t\\v ])+', 'g')," ");
                   1443:     if (cleantxt=="") {
1.539     riegler  1444: 	alert("$alertmsg");
1.44      ng       1445: 	return;
                   1446:     }
                   1447:     var nret = prompt("Add selection to keyword list? Edit if desired.",cleantxt);
                   1448:     if (nret==null) return;
1.127     ng       1449:     document.SCORE.keywords.value = document.SCORE.keywords.value+" "+nret;
1.44      ng       1450:     if (document.SCORE.keywords.value != "") {
1.127     ng       1451: 	document.SCORE.refresh.value = "on";
1.44      ng       1452: 	document.SCORE.submit();
                   1453:     }
                   1454:     return;
                   1455:   }
                   1456: 
                   1457: //====================== Script for composing message ==============
1.80      ng       1458:    // preload images
                   1459:    img1 = new Image();
                   1460:    img1.src = "$iconpath/mailbkgrd.gif";
                   1461:    img2 = new Image();
                   1462:    img2.src = "$iconpath/mailto.gif";
                   1463: 
1.44      ng       1464:   function msgCenter(msgform,usrctr,fullname) {
                   1465:     var Nmsg  = msgform.savemsgN.value;
                   1466:     savedMsgHeader(Nmsg,usrctr,fullname);
                   1467:     var subject = msgform.msgsub.value;
1.127     ng       1468:     var msgchk = document.SCORE["includemsg"+usrctr].value;
1.44      ng       1469:     re = /msgsub/;
                   1470:     var shwsel = "";
                   1471:     if (re.test(msgchk)) { shwsel = "checked" }
1.123     ng       1472:     subject = (document.SCORE.shownSub.value == 0 ? checkEntities(subject) : subject);
                   1473:     displaySubject(checkEntities(subject),shwsel);
1.44      ng       1474:     for (var i=1; i<=Nmsg; i++) {
1.123     ng       1475: 	var testmsg = "savemsg"+i+",";
                   1476: 	re = new RegExp(testmsg,"g");
1.44      ng       1477: 	shwsel = "";
                   1478: 	if (re.test(msgchk)) { shwsel = "checked" }
1.125     ng       1479: 	var message = document.SCORE["savemsg"+i].value;
1.126     ng       1480: 	message = (document.SCORE["shownOnce"+i].value == 0 ? checkEntities(message) : message);
1.123     ng       1481: 	displaySavedMsg(i,message,shwsel); //I do not get it. w/o checkEntities on saved messages,
                   1482: 	                                   //any &lt; is already converted to <, etc. However, only once!!
1.44      ng       1483:     }
1.125     ng       1484:     newmsg = document.SCORE["newmsg"+usrctr].value;
1.44      ng       1485:     shwsel = "";
                   1486:     re = /newmsg/;
                   1487:     if (re.test(msgchk)) { shwsel = "checked" }
                   1488:     newMsg(newmsg,shwsel);
                   1489:     msgTail(); 
                   1490:     return;
                   1491:   }
                   1492: 
1.123     ng       1493:   function checkEntities(strx) {
                   1494:     if (strx.length == 0) return strx;
                   1495:     var orgStr = ["&", "<", ">", '"']; 
                   1496:     var newStr = ["&amp;", "&lt;", "&gt;", "&quot;"];
                   1497:     var counter = 0;
                   1498:     while (counter < 4) {
                   1499: 	strx = strReplace(strx,orgStr[counter],newStr[counter]);
                   1500: 	counter++;
                   1501:     }
                   1502:     return strx;
                   1503:   }
                   1504: 
                   1505:   function strReplace(strx, orgStr, newStr) {
                   1506:     return strx.split(orgStr).join(newStr);
                   1507:   }
                   1508: 
1.44      ng       1509:   function savedMsgHeader(Nmsg,usrctr,fullname) {
1.76      ng       1510:     var height = 70*Nmsg+250;
1.44      ng       1511:     var scrollbar = "no";
                   1512:     if (height > 600) {
                   1513: 	height = 600;
                   1514: 	scrollbar = "yes";
                   1515:     }
1.118     ng       1516:     var xpos = (screen.width-600)/2;
                   1517:     xpos = (xpos < 0) ? '0' : xpos;
                   1518:     var ypos = (screen.height-height)/2-30;
                   1519:     ypos = (ypos < 0) ? '0' : ypos;
                   1520: 
1.206     albertel 1521:     pWin = window.open('', 'MessageCenter', 'resizable=yes,toolbar=no,location=no,scrollbars='+scrollbar+',screenx='+xpos+',screeny='+ypos+',width=600,height='+height);
1.76      ng       1522:     pWin.focus();
                   1523:     pDoc = pWin.document;
1.219     www      1524:     pDoc.$docopen;
1.351     albertel 1525:     pDoc.write('$start_page_msg_central');
1.76      ng       1526: 
                   1527:     pDoc.write("<form action=\\"inactive\\" name=\\"msgcenter\\">");
                   1528:     pDoc.write("<input value=\\""+usrctr+"\\" name=\\"usrctr\\" type=\\"hidden\\">");
1.465     albertel 1529:     pDoc.write("<h3><span class=\\"LC_info\\">&nbsp;Compose Message for \"+fullname+\"<\\/span><\\/h3><br /><br />");
1.76      ng       1530: 
1.564     bisitz   1531:     pDoc.write('<table border="0" width="100%"><tr><td bgcolor="#777777">');
                   1532:     pDoc.write('<table border="0" width="100%"><tr bgcolor="#DDFFFF">');
1.465     albertel 1533:     pDoc.write("<td><b>Type<\\/b><\\/td><td><b>Include<\\/b><\\/td><td><b>Message<\\/td><\\/tr>");
1.44      ng       1534: }
                   1535:     function displaySubject(msg,shwsel) {
1.76      ng       1536:     pDoc = pWin.document;
                   1537:     pDoc.write("<tr bgcolor=\\"#ffffdd\\">");
1.465     albertel 1538:     pDoc.write("<td>Subject<\\/td>");
                   1539:     pDoc.write("<td align=\\"center\\"><input name=\\"subchk\\" type=\\"checkbox\\"" +shwsel+"><\\/td>");
                   1540:     pDoc.write("<td><input name=\\"msgsub\\" type=\\"text\\" value=\\""+msg+"\\"size=\\"60\\" maxlength=\\"80\\"><\\/td><\\/tr>");
1.44      ng       1541: }
                   1542: 
1.72      ng       1543:   function displaySavedMsg(ctr,msg,shwsel) {
1.76      ng       1544:     pDoc = pWin.document;
                   1545:     pDoc.write("<tr bgcolor=\\"#ffffdd\\">");
1.465     albertel 1546:     pDoc.write("<td align=\\"center\\">"+ctr+"<\\/td>");
                   1547:     pDoc.write("<td align=\\"center\\"><input name=\\"msgn"+ctr+"\\" type=\\"checkbox\\"" +shwsel+"><\\/td>");
                   1548:     pDoc.write("<td><textarea name=\\"msg"+ctr+"\\" cols=\\"60\\" rows=\\"3\\">"+msg+"<\\/textarea><\\/td><\\/tr>");
1.44      ng       1549: }
                   1550: 
                   1551:   function newMsg(newmsg,shwsel) {
1.76      ng       1552:     pDoc = pWin.document;
                   1553:     pDoc.write("<tr bgcolor=\\"#ffffdd\\">");
1.465     albertel 1554:     pDoc.write("<td align=\\"center\\">New<\\/td>");
                   1555:     pDoc.write("<td align=\\"center\\"><input name=\\"newmsgchk\\" type=\\"checkbox\\"" +shwsel+"><\\/td>");
                   1556:     pDoc.write("<td><textarea name=\\"newmsg\\" cols=\\"60\\" rows=\\"3\\" onchange=\\"javascript:this.form.newmsgchk.checked=true\\" >"+newmsg+"<\\/textarea><\\/td><\\/tr>");
1.44      ng       1557: }
                   1558: 
                   1559:   function msgTail() {
1.76      ng       1560:     pDoc = pWin.document;
1.465     albertel 1561:     pDoc.write("<\\/table>");
                   1562:     pDoc.write("<\\/td><\\/tr><\\/table>&nbsp;");
1.589     bisitz   1563:     pDoc.write("<input type=\\"button\\" value=\\"Save\\" onclick=\\"javascript:checkInput()\\">&nbsp;&nbsp;");
                   1564:     pDoc.write("<input type=\\"button\\" value=\\"Cancel\\" onclick=\\"self.close()\\"><br /><br />");
1.465     albertel 1565:     pDoc.write("<\\/form>");
1.351     albertel 1566:     pDoc.write('$end_page_msg_central');
1.128     ng       1567:     pDoc.close();
1.44      ng       1568: }
                   1569: 
                   1570: //====================== Script for keyword highlight options ==============
                   1571:   function kwhighlight() {
                   1572:     var kwclr    = document.SCORE.kwclr.value;
                   1573:     var kwsize   = document.SCORE.kwsize.value;
                   1574:     var kwstyle  = document.SCORE.kwstyle.value;
                   1575:     var redsel = "";
                   1576:     var grnsel = "";
                   1577:     var blusel = "";
                   1578:     if (kwclr=="red")   {var redsel="checked"};
                   1579:     if (kwclr=="green") {var grnsel="checked"};
                   1580:     if (kwclr=="blue")  {var blusel="checked"};
                   1581:     var sznsel = "";
                   1582:     var sz1sel = "";
                   1583:     var sz2sel = "";
                   1584:     if (kwsize=="0")  {var sznsel="checked"};
                   1585:     if (kwsize=="+1") {var sz1sel="checked"};
                   1586:     if (kwsize=="+2") {var sz2sel="checked"};
                   1587:     var synsel = "";
                   1588:     var syisel = "";
                   1589:     var sybsel = "";
                   1590:     if (kwstyle=="")    {var synsel="checked"};
                   1591:     if (kwstyle=="<i>") {var syisel="checked"};
                   1592:     if (kwstyle=="<b>") {var sybsel="checked"};
                   1593:     highlightCentral();
                   1594:     highlightbody('red','red',redsel,'0','normal',sznsel,'','normal',synsel);
                   1595:     highlightbody('green','green',grnsel,'+1','+1',sz1sel,'<i>','italic',syisel);
                   1596:     highlightbody('blue','blue',blusel,'+2','+2',sz2sel,'<b>','bold',sybsel);
                   1597:     highlightend();
                   1598:     return;
                   1599:   }
                   1600: 
                   1601:   function highlightCentral() {
1.76      ng       1602: //    if (window.hwdWin) window.hwdWin.close();
1.118     ng       1603:     var xpos = (screen.width-400)/2;
                   1604:     xpos = (xpos < 0) ? '0' : xpos;
                   1605:     var ypos = (screen.height-330)/2-30;
                   1606:     ypos = (ypos < 0) ? '0' : ypos;
                   1607: 
1.206     albertel 1608:     hwdWin = window.open('', 'KeywordHighlightCentral', 'resizeable=yes,toolbar=no,location=no,scrollbars=no,width=400,height=300,screenx='+xpos+',screeny='+ypos);
1.76      ng       1609:     hwdWin.focus();
                   1610:     var hDoc = hwdWin.document;
1.219     www      1611:     hDoc.$docopen;
1.351     albertel 1612:     hDoc.write('$start_page_highlight_central');
1.76      ng       1613:     hDoc.write("<form action=\\"inactive\\" name=\\"hlCenter\\">");
1.465     albertel 1614:     hDoc.write("<h3><span class=\\"LC_info\\">&nbsp;Keyword Highlight Options<\\/span><\\/h3><br /><br />");
1.76      ng       1615: 
1.564     bisitz   1616:     hDoc.write('<table border="0" width="100%"><tr><td bgcolor="#777777">');
                   1617:     hDoc.write('<table border="0" width="100%"><tr bgcolor="#DDFFFF">');
1.465     albertel 1618:     hDoc.write("<td><b>Text Color<\\/b><\\/td><td><b>Font Size<\\/b><\\/td><td><b>Font Style<\\/td><\\/tr>");
1.44      ng       1619:   }
                   1620: 
                   1621:   function highlightbody(clrval,clrtxt,clrsel,szval,sztxt,szsel,syval,sytxt,sysel) { 
1.76      ng       1622:     var hDoc = hwdWin.document;
                   1623:     hDoc.write("<tr bgcolor=\\"#ffffdd\\">");
                   1624:     hDoc.write("<td align=\\"left\\">");
1.465     albertel 1625:     hDoc.write("<input name=\\"kwdclr\\" type=\\"radio\\" value=\\""+clrval+"\\" "+clrsel+">&nbsp;"+clrtxt+"<\\/td>");
1.76      ng       1626:     hDoc.write("<td align=\\"left\\">");
1.465     albertel 1627:     hDoc.write("<input name=\\"kwdsize\\" type=\\"radio\\" value=\\""+szval+"\\" "+szsel+">&nbsp;"+sztxt+"<\\/td>");
1.76      ng       1628:     hDoc.write("<td align=\\"left\\">");
1.465     albertel 1629:     hDoc.write("<input name=\\"kwdstyle\\" type=\\"radio\\" value=\\""+syval+"\\" "+sysel+">&nbsp;"+sytxt+"<\\/td>");
                   1630:     hDoc.write("<\\/tr>");
1.44      ng       1631:   }
                   1632: 
                   1633:   function highlightend() { 
1.76      ng       1634:     var hDoc = hwdWin.document;
1.465     albertel 1635:     hDoc.write("<\\/table>");
                   1636:     hDoc.write("<\\/td><\\/tr><\\/table>&nbsp;");
1.589     bisitz   1637:     hDoc.write("<input type=\\"button\\" value=\\"Save\\" onclick=\\"javascript:updateChoice(1)\\">&nbsp;&nbsp;");
                   1638:     hDoc.write("<input type=\\"button\\" value=\\"Cancel\\" onclick=\\"self.close()\\"><br /><br />");
1.465     albertel 1639:     hDoc.write("<\\/form>");
1.351     albertel 1640:     hDoc.write('$end_page_highlight_central');
1.128     ng       1641:     hDoc.close();
1.44      ng       1642:   }
                   1643: 
                   1644: SUBJAVASCRIPT
                   1645: }
                   1646: 
1.349     albertel 1647: sub get_increment {
1.348     bowersj2 1648:     my $increment = $env{'form.increment'};
                   1649:     if ($increment != 1 && $increment != .5 && $increment != .25 &&
                   1650:         $increment != .1) {
                   1651:         $increment = 1;
                   1652:     }
                   1653:     return $increment;
                   1654: }
                   1655: 
1.585     bisitz   1656: sub gradeBox_start {
                   1657:     return (
                   1658:         &Apache::loncommon::start_data_table()
                   1659:        .&Apache::loncommon::start_data_table_header_row()
                   1660:        .'<th>'.&mt('Part').'</th>'
                   1661:        .'<th>'.&mt('Points').'</th>'
                   1662:        .'<th>&nbsp;</th>'
                   1663:        .'<th>'.&mt('Assign Grade').'</th>'
                   1664:        .'<th>'.&mt('Weight').'</th>'
                   1665:        .'<th>'.&mt('Grade Status').'</th>'
                   1666:        .&Apache::loncommon::end_data_table_header_row()
                   1667:     );
                   1668: }
                   1669: 
                   1670: sub gradeBox_end {
                   1671:     return (
                   1672:         &Apache::loncommon::end_data_table()
                   1673:     );
                   1674: }
1.71      ng       1675: #--- displays the grading box, used in essay type problem and grading by page/sequence
                   1676: sub gradeBox {
1.322     albertel 1677:     my ($request,$symb,$uname,$udom,$counter,$partid,$record) = @_;
1.381     albertel 1678:     my $checkIcon = '<img alt="'.&mt('Check Mark').
1.485     albertel 1679: 	'" src="'.&Apache::loncommon::lonhttpdurl($request->dir_config('lonIconsURL').'/check.gif').'" height="16" border="0" />';
1.71      ng       1680:     my $wgt    = &Apache::lonnet::EXT('resource.'.$partid.'.weight',$symb,$udom,$uname);
1.466     albertel 1681:     my $wgtmsg = ($wgt > 0) ? &mt('(problem weight)') 
                   1682:                            : '<span class="LC_info">'.&mt('problem weight assigned by computer').'</span>';
1.71      ng       1683:     $wgt       = ($wgt > 0 ? $wgt : '1');
                   1684:     my $score  = ($$record{'resource.'.$partid.'.awarded'} eq '' ?
1.320     albertel 1685: 		  '' : &compute_points($$record{'resource.'.$partid.'.awarded'},$wgt));
1.71      ng       1686:     my $result='<input type="hidden" name="WGT'.$counter.'_'.$partid.'" value="'.$wgt.'" />'."\n";
1.466     albertel 1687:     my $display_part= &get_display_part($partid,$symb);
1.270     albertel 1688:     my %last_resets = &get_last_resets($symb,$env{'request.course.id'},
                   1689: 				       [$partid]);
                   1690:     my $aggtries = $$record{'resource.'.$partid.'.tries'};
1.269     raeburn  1691:     if ($last_resets{$partid}) {
                   1692:         $aggtries = &get_num_tries($record,$last_resets{$partid},$partid);
                   1693:     }
1.585     bisitz   1694:     $result.=&Apache::loncommon::start_data_table_row();
1.71      ng       1695:     my $ctr = 0;
1.348     bowersj2 1696:     my $thisweight = 0;
1.349     albertel 1697:     my $increment = &get_increment();
1.485     albertel 1698: 
                   1699:     my $radio.='<table border="0"><tr>'."\n";  # display radio buttons in a nice table 10 across
1.348     bowersj2 1700:     while ($thisweight<=$wgt) {
1.532     bisitz   1701: 	$radio.= '<td><span class="LC_nobreak"><label><input type="radio" name="RADVAL'.$counter.'_'.$partid.'" '.
1.589     bisitz   1702:         'onclick="javascript:writeBox(this.form,\''.$counter.'_'.$partid.'\','.
1.348     bowersj2 1703: 	    $thisweight.')" value="'.$thisweight.'" '.
1.401     albertel 1704: 	    ($score eq $thisweight ? 'checked="checked"':'').' /> '.$thisweight."</label></span></td>\n";
1.485     albertel 1705: 	$radio.=(($ctr+1)%10 == 0 ? '</tr><tr>' : '');
1.348     bowersj2 1706:         $thisweight += $increment;
1.71      ng       1707: 	$ctr++;
                   1708:     }
1.485     albertel 1709:     $radio.='</tr></table>';
                   1710: 
                   1711:     my $line.='<input type="text" name="GD_BOX'.$counter.'_'.$partid.'"'.
1.71      ng       1712: 	($score ne ''? ' value = "'.$score.'"':'').' size="4" '.
1.589     bisitz   1713: 	'onchange="javascript:updateRadio(this.form,\''.$counter.'_'.$partid.'\','.
1.71      ng       1714: 	$wgt.')" /></td>'."\n";
1.485     albertel 1715:     $line.='<td>/'.$wgt.' '.$wgtmsg.
1.71      ng       1716: 	($$record{'resource.'.$partid.'.solved'} eq 'correct_by_student' ? '&nbsp;'.$checkIcon : '').
1.585     bisitz   1717: 	' </td>'."\n";
                   1718:     $line.='<td><select name="GD_SEL'.$counter.'_'.$partid.'" '.
1.589     bisitz   1719: 	'onchange="javascript:clearRadBox(this.form,\''.$counter.'_'.$partid.'\')" >'."\n";
1.71      ng       1720:     if ($$record{'resource.'.$partid.'.solved'} eq 'excused') {
1.485     albertel 1721: 	$line.='<option></option>'.
                   1722: 	    '<option value="excused" selected="selected">'.&mt('excused').'</option>';
1.71      ng       1723:     } else {
1.485     albertel 1724: 	$line.='<option selected="selected"></option>'.
                   1725: 	    '<option value="excused" >'.&mt('excused').'</option>';
1.71      ng       1726:     }
1.485     albertel 1727:     $line.='<option value="reset status">'.&mt('reset status').'</option></select>'."\n";
                   1728: 
                   1729: 
                   1730:     $result .= 
1.585     bisitz   1731: 	    '<td>'.$display_part.'</td><td>'.$radio.'</td><td>'.&mt('or').'</td><td>'.$line.'</td>';
                   1732:     $result.=&Apache::loncommon::end_data_table_row();
1.71      ng       1733:     $result.='<input type="hidden" name="stores'.$counter.'_'.$partid.'" value="" />'."\n".
                   1734: 	'<input type="hidden" name="oldpts'.$counter.'_'.$partid.'" value="'.$score.'" />'."\n".
                   1735: 	'<input type="hidden" name="solved'.$counter.'_'.$partid.'" value="'.
1.269     raeburn  1736: 	$$record{'resource.'.$partid.'.solved'}.'" />'."\n".
                   1737:         '<input type="hidden" name="totaltries'.$counter.'_'.$partid.'" value="'.
                   1738:         $$record{'resource.'.$partid.'.tries'}.'" />'."\n".
                   1739:         '<input type="hidden" name="aggtries'.$counter.'_'.$partid.'" value="'.
                   1740:         $aggtries.'" />'."\n";
1.582     raeburn  1741:     my $res_error;
                   1742:     $result.=&handback_box($symb,$uname,$udom,$counter,$partid,$record,\$res_error);
                   1743:     if ($res_error) {
                   1744:         return &navmap_errormsg();
                   1745:     }
1.318     banghart 1746:     return $result;
                   1747: }
1.322     albertel 1748: 
                   1749: sub handback_box {
1.582     raeburn  1750:     my ($symb,$uname,$udom,$counter,$partid,$record,$res_error) = @_;
                   1751:     my ($partlist,$handgrade,$responseType) = &response_type($symb,$res_error);
1.323     banghart 1752:     my (@respids);
1.375     albertel 1753:      my @part_response_id = &flatten_responseType($responseType);
                   1754:     foreach my $part_response_id (@part_response_id) {
                   1755:     	my ($part,$resp) = @{ $part_response_id };
1.323     banghart 1756:         if ($part eq $partid) {
1.375     albertel 1757:             push(@respids,$resp);
1.323     banghart 1758:         }
                   1759:     }
1.318     banghart 1760:     my $result;
1.323     banghart 1761:     foreach my $respid (@respids) {
1.322     albertel 1762: 	my $prefix = $counter.'_'.$partid.'_'.$respid.'_';
                   1763: 	my $files=&get_submitted_files($udom,$uname,$partid,$respid,$record);
                   1764: 	next if (!@$files);
                   1765: 	my $file_counter = 1;
1.313     banghart 1766: 	foreach my $file (@$files) {
1.368     banghart 1767: 	    if ($file =~ /\/portfolio\//) {
                   1768:     	        my ($file_path, $file_disp) = ($file =~ m|(.+/)(.+)$|);
                   1769:     	        my ($name,$version,$ext) = &file_name_version_ext($file_disp);
                   1770:     	        $file_disp = "$name.$ext";
                   1771:     	        $file = $file_path.$file_disp;
                   1772:     	        $result.=&mt('Return commented version of [_1] to student.',
                   1773:     			 '<span class="LC_filename">'.$file_disp.'</span>');
                   1774:     	        $result.='<input type="file"   name="'.$prefix.'returndoc'.$file_counter.'" />'."\n";
                   1775:     	        $result.='<input type="hidden" name="'.$prefix.'origdoc'.$file_counter.'" value="'.$file.'" /><br />';
1.485     albertel 1776:     	        $result.='('.&mt('File will be uploaded when you click on Save &amp; Next below.').')<br />';
1.368     banghart 1777:     	        $file_counter++;
                   1778: 	    }
1.322     albertel 1779: 	}
1.313     banghart 1780:     }
1.318     banghart 1781:     return $result;    
1.71      ng       1782: }
1.44      ng       1783: 
1.58      albertel 1784: sub show_problem {
1.382     albertel 1785:     my ($request,$symb,$uname,$udom,$removeform,$viewon,$mode,$form) = @_;
1.144     albertel 1786:     my $rendered;
1.382     albertel 1787:     my %form = ((ref($form) eq 'HASH')? %{$form} : ());
1.329     albertel 1788:     &Apache::lonxml::remember_problem_counter();
1.144     albertel 1789:     if ($mode eq 'both' or $mode eq 'text') {
                   1790: 	$rendered=&Apache::loncommon::get_student_view($symb,$uname,$udom,
1.382     albertel 1791: 						       $env{'request.course.id'},
                   1792: 						       undef,\%form);
1.144     albertel 1793:     }
1.58      albertel 1794:     if ($removeform) {
                   1795: 	$rendered=~s|<form(.*?)>||g;
                   1796: 	$rendered=~s|</form>||g;
1.374     albertel 1797: 	$rendered=~s|(<input[^>]*name\s*=\s*"?)(\w+)("?)|$1would_have_been_$2$3|g;
1.58      albertel 1798:     }
1.144     albertel 1799:     my $companswer;
                   1800:     if ($mode eq 'both' or $mode eq 'answer') {
1.329     albertel 1801: 	&Apache::lonxml::restore_problem_counter();
1.382     albertel 1802: 	$companswer=
                   1803: 	    &Apache::loncommon::get_student_answers($symb,$uname,$udom,
                   1804: 						    $env{'request.course.id'},
                   1805: 						    %form);
1.144     albertel 1806:     }
1.58      albertel 1807:     if ($removeform) {
                   1808: 	$companswer=~s|<form(.*?)>||g;
                   1809: 	$companswer=~s|</form>||g;
1.144     albertel 1810: 	$companswer=~s|name="submit"|name="would_have_been_submit"|g;
1.58      albertel 1811:     }
1.468     albertel 1812:     $rendered=
1.588     bisitz   1813:         '<div class="LC_Box">'
                   1814:        .'<h3 class="LC_hcell">'.&mt('View of the problem').'</h3>'
                   1815:        .$rendered
                   1816:        .'</div>';
1.468     albertel 1817:     $companswer=
1.588     bisitz   1818:         '<div class="LC_Box">'
                   1819:        .'<h3 class="LC_hcell">'.&mt('Correct answer').'</h3>'
                   1820:        .$companswer
                   1821:        .'</div>';
1.468     albertel 1822:     my $result;
1.144     albertel 1823:     if ($mode eq 'both') {
1.588     bisitz   1824:         $result=$rendered.$companswer;
1.144     albertel 1825:     } elsif ($mode eq 'text') {
1.588     bisitz   1826:         $result=$rendered;
1.144     albertel 1827:     } elsif ($mode eq 'answer') {
1.588     bisitz   1828:         $result=$companswer;
1.144     albertel 1829:     }
1.71      ng       1830:     return $result;
1.58      albertel 1831: }
1.397     albertel 1832: 
1.396     banghart 1833: sub files_exist {
                   1834:     my ($r, $symb) = @_;
                   1835:     my @students = &Apache::loncommon::get_env_multiple('form.stuinfo');
1.397     albertel 1836: 
1.396     banghart 1837:     foreach my $student (@students) {
                   1838:         my ($uname,$udom,$fullname) = split(/:/,$student);
1.397     albertel 1839:         my %record = &Apache::lonnet::restore($symb,$env{'request.course.id'},
                   1840: 					      $udom,$uname);
1.396     banghart 1841:         my ($string,$timestamp)= &get_last_submission(\%record);
1.397     albertel 1842:         foreach my $submission (@$string) {
                   1843:             my ($partid,$respid) =
                   1844: 		($submission =~ /^resource\.([^\.]*)\.([^\.]*)\.submission/);
                   1845:             my $files=&get_submitted_files($udom,$uname,$partid,$respid,
                   1846: 					   \%record);
                   1847:             return 1 if (@$files);
1.396     banghart 1848:         }
                   1849:     }
1.397     albertel 1850:     return 0;
1.396     banghart 1851: }
1.397     albertel 1852: 
1.394     banghart 1853: sub download_all_link {
                   1854:     my ($r,$symb) = @_;
1.395     albertel 1855:     my $all_students = 
                   1856: 	join("\n", &Apache::loncommon::get_env_multiple('form.stuinfo'));
                   1857: 
                   1858:     my $parts =
                   1859: 	join("\n",&Apache::loncommon::get_env_multiple('form.vPart'));
                   1860: 
1.394     banghart 1861:     my $identifier = &Apache::loncommon::get_cgi_id();
1.514     raeburn  1862:     &Apache::lonnet::appenv({'cgi.'.$identifier.'.students' => $all_students,
                   1863:                              'cgi.'.$identifier.'.symb' => $symb,
                   1864:                              'cgi.'.$identifier.'.parts' => $parts,});
1.395     albertel 1865:     $r->print('<a href="/cgi-bin/multidownload.pl?'.$identifier.'">'.
                   1866: 	      &mt('Download All Submitted Documents').'</a>');
1.394     banghart 1867:     return
                   1868: }
1.395     albertel 1869: 
1.432     banghart 1870: sub build_section_inputs {
                   1871:     my $section_inputs;
                   1872:     if ($env{'form.section'} eq '') {
                   1873:         $section_inputs .= '<input type="hidden" name="section" value="all" />'."\n";
                   1874:     } else {
                   1875:         my @sections = &Apache::loncommon::get_env_multiple('form.section');
1.434     albertel 1876:         foreach my $section (@sections) {
1.432     banghart 1877:             $section_inputs .= '<input type="hidden" name="section" value="'.$section.'" />'."\n";
                   1878:         }
                   1879:     }
                   1880:     return $section_inputs;
                   1881: }
                   1882: 
1.44      ng       1883: # --------------------------- show submissions of a student, option to grade 
                   1884: sub submission {
1.608     www      1885:     my ($request,$counter,$total,$symb) = @_;
1.257     albertel 1886:     my ($uname,$udom)     = ($env{'form.student'},$env{'form.userdom'});
                   1887:     $udom = ($udom eq '' ? $env{'user.domain'} : $udom); #has form.userdom changed for a student?
                   1888:     my $usec = &Apache::lonnet::getsection($udom,$uname,$env{'request.course.id'});
                   1889:     $env{'form.fullname'} = &Apache::loncommon::plainname($uname,$udom,'lastname') if $env{'form.fullname'} eq '';
1.608     www      1890: 
1.605     www      1891:     my $probtitle=&Apache::lonnet::gettitle($symb); 
1.324     albertel 1892:     if ($symb eq '') { $request->print("Unable to handle ambiguous references:."); return ''; }
1.104     albertel 1893: 
                   1894:     if (!&canview($usec)) {
1.398     albertel 1895: 	$request->print('<span class="LC_warning">Unable to view requested student.('.
                   1896: 			$uname.':'.$udom.' in section '.$usec.' in course id '.
                   1897: 			$env{'request.course.id'}.')</span>');
1.104     albertel 1898: 	return;
                   1899:     }
                   1900: 
1.257     albertel 1901:     if (!$env{'form.lastSub'}) { $env{'form.lastSub'} = 'datesub'; }
                   1902:     if (!$env{'form.vProb'}) { $env{'form.vProb'} = 'yes'; }
                   1903:     if (!$env{'form.vAns'}) { $env{'form.vAns'} = 'yes'; }
                   1904:     my $last = ($env{'form.lastSub'} eq 'last' ? 'last' : '');
1.381     albertel 1905:     my $checkIcon = '<img alt="'.&mt('Check Mark').
                   1906: 	'" src="'.$request->dir_config('lonIconsURL').
1.122     ng       1907: 	'/check.gif" height="16" border="0" />';
1.41      ng       1908: 
1.426     albertel 1909:     my %old_essays;
1.41      ng       1910:     # header info
                   1911:     if ($counter == 0) {
                   1912: 	&sub_page_js($request);
1.257     albertel 1913: 	&sub_page_kw_js($request) if ($env{'form.handgrade'} eq 'yes');
1.397     albertel 1914: 	if ($env{'form.handgrade'} eq 'yes' && &files_exist($request, $symb)) {
1.396     banghart 1915: 	    &download_all_link($request, $symb);
                   1916: 	}
1.605     www      1917: 	$request->print('<h3>&nbsp;<span class="LC_info">'.&mt('Submission Record').'</span></h3>');
1.118     ng       1918: 
1.44      ng       1919: 	# option to display problem, only once else it cause problems 
                   1920:         # with the form later since the problem has a form.
1.257     albertel 1921: 	if ($env{'form.vProb'} eq 'yes' or $env{'form.vAns'} eq 'yes') {
1.144     albertel 1922: 	    my $mode;
1.257     albertel 1923: 	    if ($env{'form.vProb'} eq 'yes' && $env{'form.vAns'} eq 'yes') {
1.144     albertel 1924: 		$mode='both';
1.257     albertel 1925: 	    } elsif ($env{'form.vProb'} eq 'yes') {
1.144     albertel 1926: 		$mode='text';
1.257     albertel 1927: 	    } elsif ($env{'form.vAns'} eq 'yes') {
1.144     albertel 1928: 		$mode='answer';
                   1929: 	    }
1.329     albertel 1930: 	    &Apache::lonxml::clear_problem_counter();
1.144     albertel 1931: 	    $request->print(&show_problem($request,$symb,$uname,$udom,0,1,$mode));
1.41      ng       1932: 	}
1.441     www      1933: 
1.44      ng       1934: 	# kwclr is the only variable that is guaranteed to be non blank 
                   1935:         # if this subroutine has been called once.
1.41      ng       1936: 	my %keyhash = ();
1.257     albertel 1937: 	if ($env{'form.kwclr'} eq '' && $env{'form.handgrade'} eq 'yes') {
1.41      ng       1938: 	    %keyhash = &Apache::lonnet::dump('nohist_handgrade',
1.257     albertel 1939: 					     $env{'course.'.$env{'request.course.id'}.'.domain'},
                   1940: 					     $env{'course.'.$env{'request.course.id'}.'.num'});
1.41      ng       1941: 
1.257     albertel 1942: 	    my $loginuser = $env{'user.name'}.':'.$env{'user.domain'};
                   1943: 	    $env{'form.keywords'} = $keyhash{$symb.'_keywords'} ne '' ? $keyhash{$symb.'_keywords'} : '';
                   1944: 	    $env{'form.kwclr'}    = $keyhash{$loginuser.'_kwclr'} ne '' ? $keyhash{$loginuser.'_kwclr'} : 'red';
                   1945: 	    $env{'form.kwsize'}   = $keyhash{$loginuser.'_kwsize'} ne '' ? $keyhash{$loginuser.'_kwsize'} : '0';
                   1946: 	    $env{'form.kwstyle'}  = $keyhash{$loginuser.'_kwstyle'} ne '' ? $keyhash{$loginuser.'_kwstyle'} : '';
                   1947: 	    $env{'form.msgsub'}   = $keyhash{$symb.'_subject'} ne '' ? 
1.605     www      1948: 		$keyhash{$symb.'_subject'} : $probtitle;
1.257     albertel 1949: 	    $env{'form.savemsgN'} = $keyhash{$symb.'_savemsgN'} ne '' ? $keyhash{$symb.'_savemsgN'} : '0';
1.41      ng       1950: 	}
1.257     albertel 1951: 	my $overRideScore = $env{'form.overRideScore'} eq '' ? 'no' : $env{'form.overRideScore'};
1.442     banghart 1952: 	my $stu_status = join(':',&Apache::loncommon::get_env_multiple('form.Status'));
1.303     banghart 1953: 	$request->print('<form action="/adm/grades" method="post" name="SCORE" enctype="multipart/form-data">'."\n".
1.41      ng       1954: 			'<input type="hidden" name="command"    value="handgrade" />'."\n".
1.442     banghart 1955: 			'<input type="hidden" name="Status"     value="'.$stu_status.'" />'."\n".
1.120     ng       1956: 			'<input type="hidden" name="overRideScore" value="'.$overRideScore.'" />'."\n".
1.41      ng       1957: 			'<input type="hidden" name="refresh"    value="off" />'."\n".
1.120     ng       1958: 			'<input type="hidden" name="studentNo"  value="" />'."\n".
                   1959: 			'<input type="hidden" name="gradeOpt"   value="" />'."\n".
1.418     albertel 1960: 			'<input type="hidden" name="symb"       value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
1.257     albertel 1961: 			'<input type="hidden" name="showgrading" value="'.$env{'form.showgrading'}.'" />'."\n".
                   1962: 			'<input type="hidden" name="vProb"      value="'.$env{'form.vProb'}.'" />'."\n".
                   1963: 			'<input type="hidden" name="vAns"       value="'.$env{'form.vAns'}.'" />'."\n".
                   1964: 			'<input type="hidden" name="lastSub"    value="'.$env{'form.lastSub'}.'" />'."\n".
1.432     banghart 1965: 			&build_section_inputs().
1.326     albertel 1966: 			'<input type="hidden" name="submitonly" value="'.$env{'form.submitonly'}.'" />'."\n".
                   1967: 			'<input type="hidden" name="handgrade"  value="'.$env{'form.handgrade'}.'" />'."\n".
1.41      ng       1968: 			'<input type="hidden" name="NCT"'.
1.257     albertel 1969: 			' value="'.($env{'form.NTSTU'} ne '' ? $env{'form.NTSTU'} : $total+1).'" />'."\n");
                   1970: 	if ($env{'form.handgrade'} eq 'yes') {
                   1971: 	    $request->print('<input type="hidden" name="keywords" value="'.$env{'form.keywords'}.'" />'."\n".
                   1972: 			    '<input type="hidden" name="kwclr"    value="'.$env{'form.kwclr'}.'" />'."\n".
                   1973: 			    '<input type="hidden" name="kwsize"   value="'.$env{'form.kwsize'}.'" />'."\n".
                   1974: 			    '<input type="hidden" name="kwstyle"  value="'.$env{'form.kwstyle'}.'" />'."\n".
                   1975: 			    '<input type="hidden" name="msgsub"   value="'.$env{'form.msgsub'}.'" />'."\n".
1.123     ng       1976: 			    '<input type="hidden" name="shownSub" value="0" />'."\n".
1.257     albertel 1977: 			    '<input type="hidden" name="savemsgN" value="'.$env{'form.savemsgN'}.'" />'."\n");
1.154     albertel 1978: 	    foreach my $partid (&Apache::loncommon::get_env_multiple('form.vPart')) {
                   1979: 		$request->print('<input type="hidden" name="vPart" value="'.$partid.'" />'."\n");
                   1980: 	    }
1.123     ng       1981: 	}
1.41      ng       1982: 	
                   1983: 	my ($cts,$prnmsg) = (1,'');
1.257     albertel 1984: 	while ($cts <= $env{'form.savemsgN'}) {
1.41      ng       1985: 	    $prnmsg.='<input type="hidden" name="savemsg'.$cts.'" value="'.
1.123     ng       1986: 		(!exists($keyhash{$symb.'_savemsg'.$cts}) ? 
1.257     albertel 1987: 		 &Apache::lonfeedback::clear_out_html($env{'form.savemsg'.$cts}) :
1.80      ng       1988: 		 &Apache::lonfeedback::clear_out_html($keyhash{$symb.'_savemsg'.$cts})).
1.123     ng       1989: 		'" />'."\n".
                   1990: 		'<input type="hidden" name="shownOnce'.$cts.'" value="0" />'."\n";
1.41      ng       1991: 	    $cts++;
                   1992: 	}
                   1993: 	$request->print($prnmsg);
1.32      ng       1994: 
1.257     albertel 1995: 	if ($env{'form.handgrade'} eq 'yes' && $env{'form.showgrading'} eq 'yes') {
1.88      www      1996: #
                   1997: # Print out the keyword options line
                   1998: #
1.41      ng       1999: 	    $request->print(<<KEYWORDS);
1.38      ng       2000: &nbsp;<b>Keyword Options:</b>&nbsp;
1.417     albertel 2001: <a href="javascript:keywords(document.SCORE);" target="_self">List</a>&nbsp; &nbsp;
1.589     bisitz   2002: <a href="#" onmousedown="javascript:getSel(); return false"
1.38      ng       2003:  CLASS="page">Paste Selection to List</a>&nbsp; &nbsp;
1.417     albertel 2004: <a href="javascript:kwhighlight();" target="_self">Highlight Attribute</a><br /><br />
1.38      ng       2005: KEYWORDS
1.88      www      2006: #
                   2007: # Load the other essays for similarity check
                   2008: #
1.324     albertel 2009:             my (undef,undef,$essayurl) = &Apache::lonnet::decode_symb($symb);
1.384     albertel 2010: 	    my ($adom,$aname,$apath)=($essayurl=~/^($LONCAPA::domain_re)\/($LONCAPA::username_re)\/(.*)$/);
1.359     www      2011: 	    $apath=&escape($apath);
1.88      www      2012: 	    $apath=~s/\W/\_/gs;
1.426     albertel 2013: 	    %old_essays=&Apache::lonnet::dump('nohist_essay_'.$apath,$adom,$aname);
1.41      ng       2014:         }
                   2015:     }
1.44      ng       2016: 
1.441     www      2017: # This is where output for one specific student would start
1.592     bisitz   2018:     my $add_class = ($counter%2) ? ' LC_grade_show_user_odd_row' : '';
                   2019:     $request->print(
                   2020:         "\n\n"
                   2021:        .'<div class="LC_grade_show_user'.$add_class.'">'
                   2022:        .'<h2>'.&nameUserString(undef,$env{'form.fullname'},$uname,$udom).'</h2>'
                   2023:        ."\n"
                   2024:     );
1.441     www      2025: 
1.592     bisitz   2026:     # Show additional functions if allowed
                   2027:     if ($perm{'vgr'}) {
                   2028:         $request->print(
                   2029:             &Apache::loncommon::track_student_link(
                   2030:                 &mt('View recent activity'),
                   2031:                 $uname,$udom,'check')
                   2032:            .' '
                   2033:         );
                   2034:     }
                   2035:     if ($perm{'opa'}) {
                   2036:         $request->print(
                   2037:             &Apache::loncommon::pprmlink(
                   2038:                 &mt('Set/Change parameters'),
                   2039:                 $uname,$udom,$symb,'check'));
                   2040:     }
                   2041: 
                   2042:     # Show Problem
1.257     albertel 2043:     if ($env{'form.vProb'} eq 'all' or $env{'form.vAns'} eq 'all') {
1.144     albertel 2044: 	my $mode;
1.257     albertel 2045: 	if ($env{'form.vProb'} eq 'all' && $env{'form.vAns'} eq 'all') {
1.144     albertel 2046: 	    $mode='both';
1.257     albertel 2047: 	} elsif ($env{'form.vProb'} eq 'all' ) {
1.144     albertel 2048: 	    $mode='text';
1.257     albertel 2049: 	} elsif ($env{'form.vAns'} eq 'all') {
1.144     albertel 2050: 	    $mode='answer';
                   2051: 	}
1.329     albertel 2052: 	&Apache::lonxml::clear_problem_counter();
1.475     albertel 2053: 	$request->print(&show_problem($request,$symb,$uname,$udom,1,1,$mode,{'request.prefix' => 'ctr'.$counter}));
1.58      albertel 2054:     }
1.144     albertel 2055: 
1.257     albertel 2056:     my %record = &Apache::lonnet::restore($symb,$env{'request.course.id'},$udom,$uname);
1.582     raeburn  2057:     my $res_error;
                   2058:     my ($partlist,$handgrade,$responseType) = &response_type($symb,\$res_error);
                   2059:     if ($res_error) {
                   2060:         $request->print(&navmap_errormsg());
                   2061:         return;
                   2062:     }
1.41      ng       2063: 
1.44      ng       2064:     # Display student info
1.41      ng       2065:     $request->print(($counter == 0 ? '' : '<br />'));
1.590     bisitz   2066: 
                   2067:     my $result='<div class="LC_Box">'
                   2068:               .'<h3 class="LC_hcell">'.&mt('Submissions').'</h3>';
1.45      ng       2069:     $result.='<input type="hidden" name="name'.$counter.
1.588     bisitz   2070:              '" value="'.$env{'form.fullname'}.'" />'."\n";
1.469     albertel 2071:     if ($env{'form.handgrade'} eq 'no') {
1.588     bisitz   2072:         $result.='<p class="LC_info">'
                   2073:                 .&mt('Part(s) graded correct by the computer is marked with a [_1] symbol.',$checkIcon)
                   2074:                 ."</p>\n";
1.469     albertel 2075:     }
                   2076: 
1.118     ng       2077:     # If any part of the problem is an essay-response (handgraded), then check for collaborators
1.464     albertel 2078:     my $fullname;
                   2079:     my $col_fullnames = [];
1.257     albertel 2080:     if ($env{'form.handgrade'} eq 'yes') {
1.464     albertel 2081: 	(my $sub_result,$fullname,$col_fullnames)=
                   2082: 	    &check_collaborators($symb,$uname,$udom,\%record,$handgrade,
                   2083: 				 $counter);
                   2084: 	$result.=$sub_result;
1.41      ng       2085:     }
1.44      ng       2086:     $request->print($result."\n");
1.588     bisitz   2087: 
1.44      ng       2088:     # print student answer/submission
1.588     bisitz   2089:     # Options are (1) Handgraded submission only
1.44      ng       2090:     #             (2) Last submission, includes submission that is not handgraded 
                   2091:     #                  (for multi-response type part)
                   2092:     #             (3) Last submission plus the parts info
                   2093:     #             (4) The whole record for this student
1.257     albertel 2094:     if ($env{'form.lastSub'} =~ /^(lastonly|hdgrade)$/) {
1.151     albertel 2095: 	my ($string,$timestamp)= &get_last_submission(\%record);
1.468     albertel 2096: 	
                   2097: 	my $lastsubonly;
                   2098: 
1.588     bisitz   2099:         if ($$timestamp eq '') {
                   2100:             $lastsubonly.='<div class="LC_grade_submissions_body">'.$$string[0].'</div>'; 
                   2101:         } else {
1.592     bisitz   2102:             $lastsubonly =
                   2103:                 '<div class="LC_grade_submissions_body">'
                   2104:                .'<b>'.&mt('Date Submitted:').'</b> '.$$timestamp."\n";
1.468     albertel 2105: 
1.151     albertel 2106: 	    my %seenparts;
1.375     albertel 2107: 	    my @part_response_id = &flatten_responseType($responseType);
                   2108: 	    foreach my $part (@part_response_id) {
1.393     albertel 2109: 		next if ($env{'form.lastSub'} eq 'hdgrade' 
                   2110: 			 && $$handgrade{$$part[0].'_'.$$part[1]} ne 'yes');
                   2111: 
1.375     albertel 2112: 		my ($partid,$respid) = @{ $part };
1.324     albertel 2113: 		my $display_part=&get_display_part($partid,$symb);
1.257     albertel 2114: 		if ($env{"form.$uname:$udom:$partid:submitted_by"}) {
1.151     albertel 2115: 		    if (exists($seenparts{$partid})) { next; }
                   2116: 		    $seenparts{$partid}=1;
1.207     albertel 2117: 		    my $submitby='<b>Part:</b> '.$display_part.
                   2118: 			' <b>Collaborative submission by:</b> '.
1.151     albertel 2119: 			'<a href="javascript:viewSubmitter(\''.
1.257     albertel 2120: 			$env{"form.$uname:$udom:$partid:submitted_by"}.
1.417     albertel 2121: 			'\');" target="_self">'.
1.257     albertel 2122: 			$$fullname{$env{"form.$uname:$udom:$partid:submitted_by"}}.'</a><br />';
1.151     albertel 2123: 		    $request->print($submitby);
                   2124: 		    next;
                   2125: 		}
                   2126: 		my $responsetype = $responseType->{$partid}->{$respid};
                   2127: 		if (!exists($record{"resource.$partid.$respid.submission"})) {
1.577     bisitz   2128:                     $lastsubonly.="\n".'<div class="LC_grade_submission_part">'.
                   2129:                         '<b>'.&mt('Part: [_1]',$display_part).'</b>'.
                   2130:                         ' <span class="LC_internal_info">'.
1.597     wenzelju 2131:                         '('.&mt('Part ID: [_1]',$respid).')'.
1.577     bisitz   2132:                         '</span>&nbsp; &nbsp;'.
1.539     riegler  2133: 			'<span class="LC_warning">'.&mt('Nothing submitted - no attempts.').'</span><br /><br /></div>';
1.151     albertel 2134: 		    next;
                   2135: 		}
1.468     albertel 2136: 		foreach my $submission (@$string) {
                   2137: 		    my ($partid,$respid) = ($submission =~ /^resource\.([^\.]*)\.([^\.]*)\.submission/);
1.375     albertel 2138: 		    if (join('_',@{$part}) ne ($partid.'_'.$respid)) { next; }
1.596     raeburn  2139: 		    my ($ressub,$hide,$subval) = split(/:/,$submission,3);
1.151     albertel 2140: 		    # Similarity check
                   2141: 		    my $similar='';
1.257     albertel 2142: 		    if($env{'form.checkPlag'}){
1.151     albertel 2143: 			my ($oname,$odom,$ocrsid,$oessay,$osim)=
1.426     albertel 2144: 			    &most_similar($uname,$udom,$subval,\%old_essays);
1.151     albertel 2145: 			if ($osim) {
                   2146: 			    $osim=int($osim*100.0);
1.426     albertel 2147: 			    my %old_course_desc = 
                   2148: 				&Apache::lonnet::coursedescription($ocrsid,
                   2149: 								   {'one_time' => 1});
                   2150: 
1.596     raeburn  2151:                             if ($hide) {
                   2152:                                 $similar='<hr /><span class="LC_warning">'.&mt("Essay was found to be similar to another essay submitted for this assignment.").'<br />'.
                   2153:                                          &mt('As the current submission is for an anonymous survey, no other details are available.').'</span><hr />';
                   2154:                             } else {
                   2155: 			        $similar="<hr /><h3><span class=\"LC_warning\">".
                   2156: 				    &mt('Essay is [_1]% similar to an essay by [_2] in course [_3] (course id [_4]:[_5])',
                   2157: 				        $osim,
                   2158: 				        &Apache::loncommon::plainname($oname,$odom).' ('.$oname.':'.$odom.')',
                   2159: 				        $old_course_desc{'description'},
                   2160: 				        $old_course_desc{'num'},
                   2161: 				        $old_course_desc{'domain'}).
                   2162: 				    '</span></h3><blockquote><i>'.
                   2163: 				    &keywords_highlight($oessay).
                   2164: 				    '</i></blockquote><hr />';
                   2165:                             }
1.151     albertel 2166: 			}
1.150     albertel 2167: 		    }
1.151     albertel 2168: 		    my $order=&get_order($partid,$respid,$symb,$uname,$udom);
1.257     albertel 2169: 		    if ($env{'form.lastSub'} eq 'lastonly' || 
                   2170: 			($env{'form.lastSub'} eq 'hdgrade' && 
1.377     albertel 2171: 			 $$handgrade{$$part[0].'_'.$$part[1]} eq 'yes')) {
1.324     albertel 2172: 			my $display_part=&get_display_part($partid,$symb);
1.577     bisitz   2173:                         $lastsubonly.='<div class="LC_grade_submission_part">'.
                   2174:                             '<b>'.&mt('Part: [_1]',$display_part).'</b>'.
                   2175:                             ' <span class="LC_internal_info">'.
                   2176:                             '('.&mt('Part ID: [_1]',$respid).')'.
1.597     wenzelju 2177:                             '</span>&nbsp; &nbsp;';
1.313     banghart 2178: 			my $files=&get_submitted_files($udom,$uname,$partid,$respid,\%record);
                   2179: 			if (@$files) {
1.596     raeburn  2180:                             if ($hide) {
                   2181:                                 $lastsubonly.='<br />'.&mt('[quant,_1,file] uploaded to this anonymous survey',scalar(@{$files}));
                   2182:                             } else {
                   2183:                                 $lastsubonly.='<br /><span class="LC_warning">'.&mt('Like all files provided by users, this file may contain viruses').'</span><br />';
                   2184:                                 foreach my $file (@$files) {
                   2185:                                     &Apache::lonnet::allowuploaded('/adm/grades',$file);
                   2186:                                     $lastsubonly.='<br /><a href="'.$file.'?rawmode=1" target="lonGRDs"><img src="'.&Apache::loncommon::icon($file).'" border="0" /> '.$file.'</a>';
                   2187:                                 }
                   2188:                             }
1.236     albertel 2189: 			    $lastsubonly.='<br />';
1.41      ng       2190: 			}
1.596     raeburn  2191:                         if ($hide) {
                   2192:                             $lastsubonly.='<b>'.&mt('Anonymous Survey').'</b>'; 
                   2193:                         } else {
                   2194: 			    $lastsubonly.='<b>'.&mt('Submitted Answer:').' </b>'.
                   2195: 			        &cleanRecord($subval,$responsetype,$symb,$partid,
                   2196: 					     $respid,\%record,$order,undef,$uname,$udom);
                   2197:                         }
1.151     albertel 2198: 			if ($similar) {$lastsubonly.="<br /><br />$similar\n";}
1.468     albertel 2199: 			$lastsubonly.='</div>';
1.41      ng       2200: 		    }
                   2201: 		}
                   2202: 	    }
1.588     bisitz   2203: 	    $lastsubonly.='</div>'."\n"; # End: LC_grade_submissions_body
1.151     albertel 2204: 	}
                   2205: 	$request->print($lastsubonly);
1.468     albertel 2206:    } elsif ($env{'form.lastSub'} eq 'datesub') {
1.598     www      2207: #	my (undef,$responseType,undef,$parts) = &showResourceInfo($symb);
                   2208:     my ($parts,$handgrade,$responseType) = &response_type($symb);
                   2209: 
1.148     albertel 2210: 	$request->print(&displaySubByDates($symb,\%record,$parts,$responseType,$checkIcon,$uname,$udom));
1.257     albertel 2211:     } elsif ($env{'form.lastSub'} =~ /^(last|all)$/) {
1.41      ng       2212: 	$request->print(&Apache::loncommon::get_previous_attempt($symb,$uname,$udom,
1.257     albertel 2213: 								 $env{'request.course.id'},
1.44      ng       2214: 								 $last,'.submission',
                   2215: 								 'Apache::grades::keywords_highlight'));
1.41      ng       2216:     }
1.120     ng       2217: 
1.121     ng       2218:     $request->print('<input type="hidden" name="unamedom'.$counter.'" value="'.$uname.':'
                   2219: 	.$udom.'" />'."\n");
1.44      ng       2220:     # return if view submission with no grading option
1.257     albertel 2221:     if ($env{'form.showgrading'} eq '' || (!&canmodify($usec))) {
1.120     ng       2222: 	my $toGrade.='<input type="button" value="Grade Student" '.
1.589     bisitz   2223: 	    'onclick="javascript:checksubmit(this.form,\'Grade Student\',\''
1.417     albertel 2224: 	    .$counter.'\');" target="_self" /> &nbsp;'."\n" if (&canmodify($usec));
1.468     albertel 2225: 	$toGrade.='</div>'."\n";
1.180     albertel 2226: 	$request->print($toGrade);
1.41      ng       2227: 	return;
1.180     albertel 2228:     } else {
1.468     albertel 2229: 	$request->print('</div>'."\n");
1.41      ng       2230:     }
1.33      ng       2231: 
1.121     ng       2232:     # essay grading message center
1.257     albertel 2233:     if ($env{'form.handgrade'} eq 'yes') {
1.468     albertel 2234: 	my $result='<div class="LC_grade_message_center">';
                   2235:     
                   2236: 	$result.='<div class="LC_grade_message_center_header">'.
                   2237: 	    &mt('Send Message').'</div><div class="LC_grade_message_center_body">';
1.257     albertel 2238: 	my ($lastname,$givenn) = split(/,/,$env{'form.fullname'});
1.118     ng       2239: 	my $msgfor = $givenn.' '.$lastname;
1.464     albertel 2240: 	if (scalar(@$col_fullnames) > 0) {
                   2241: 	    my $lastone = pop(@$col_fullnames);
                   2242: 	    $msgfor .= ', '.(join ', ',@$col_fullnames).' and '.$lastone.'.';
1.118     ng       2243: 	}
                   2244: 	$msgfor =~ s/\'/\\'/g; #' stupid emacs - no! javascript
1.468     albertel 2245: 	$result.='<input type="hidden" name="includemsg'.$counter.'" value="" />'."\n".
1.121     ng       2246: 	    '<input type="hidden" name="newmsg'.$counter.'" value="" />'."\n";
                   2247: 	$result.='&nbsp;<a href="javascript:msgCenter(document.SCORE,'.$counter.
1.417     albertel 2248: 	    ',\''.$msgfor.'\');" target="_self">'.
1.464     albertel 2249: 	    &mt('Compose message to student').(scalar(@$col_fullnames) >= 1 ? 's' : '').'</a><label> ('.
1.350     albertel 2250: 	    &mt('incl. grades').' <input type="checkbox" name="withgrades'.$counter.'" /></label>)'.
1.118     ng       2251: 	    '<img src="'.$request->dir_config('lonIconsURL').
                   2252: 	    '/mailbkgrd.gif" width="14" height="10" name="mailicon'.$counter.'" />'."\n".
1.298     www      2253: 	    '<br />&nbsp;('.
1.468     albertel 2254: 	    &mt('Message will be sent when you click on Save &amp; Next below.').")\n";
                   2255: 	$result.='</div></div>';
1.121     ng       2256: 	$request->print($result);
1.118     ng       2257:     }
1.41      ng       2258: 
                   2259:     my %seen = ();
                   2260:     my @partlist;
1.129     ng       2261:     my @gradePartRespid;
1.375     albertel 2262:     my @part_response_id = &flatten_responseType($responseType);
1.585     bisitz   2263:     $request->print(
1.588     bisitz   2264:         '<div class="LC_Box">'
                   2265:        .'<h3 class="LC_hcell">'.&mt('Assign Grades').'</h3>'
1.585     bisitz   2266:     );
1.592     bisitz   2267:     $request->print(&gradeBox_start());
1.375     albertel 2268:     foreach my $part_response_id (@part_response_id) {
                   2269:     	my ($partid,$respid) = @{ $part_response_id };
                   2270: 	my $part_resp = join('_',@{ $part_response_id });
1.322     albertel 2271: 	next if ($seen{$partid} > 0);
1.41      ng       2272: 	$seen{$partid}++;
1.393     albertel 2273: 	next if ($$handgrade{$part_resp} ne 'yes' 
                   2274: 		 && $env{'form.lastSub'} eq 'hdgrade');
1.524     raeburn  2275: 	push(@partlist,$partid);
                   2276: 	push(@gradePartRespid,$partid.'.'.$respid);
1.322     albertel 2277: 	$request->print(&gradeBox($request,$symb,$uname,$udom,$counter,$partid,\%record));
1.41      ng       2278:     }
1.585     bisitz   2279:     $request->print(&gradeBox_end()); # </div>
                   2280:     $request->print('</div>');
1.468     albertel 2281: 
                   2282:     $request->print('<div class="LC_grade_info_links">');
                   2283:     $request->print('</div>');
                   2284: 
1.45      ng       2285:     $result='<input type="hidden" name="partlist'.$counter.
                   2286: 	'" value="'.(join ":",@partlist).'" />'."\n";
1.129     ng       2287:     $result.='<input type="hidden" name="gradePartRespid'.
                   2288: 	'" value="'.(join ":",@gradePartRespid).'" />'."\n" if ($counter == 0);
1.45      ng       2289:     my $ctr = 0;
                   2290:     while ($ctr < scalar(@partlist)) {
                   2291: 	$result.='<input type="hidden" name="partid'.$counter.'_'.$ctr.'" value="'.
                   2292: 	    $partlist[$ctr].'" />'."\n";
                   2293: 	$ctr++;
                   2294:     }
1.468     albertel 2295:     $request->print($result.''."\n");
1.41      ng       2296: 
1.441     www      2297: # Done with printing info for one student
                   2298: 
1.468     albertel 2299:     $request->print('</div>');#LC_grade_show_user
1.441     www      2300: 
                   2301: 
1.41      ng       2302:     # print end of form
                   2303:     if ($counter == $total) {
1.592     bisitz   2304:         my $endform='<br /><hr /><table border="0"><tr><td>'."\n";
1.485     albertel 2305: 	$endform.='<input type="button" value="'.&mt('Save &amp; Next').'" '.
1.589     bisitz   2306: 	    'onclick="javascript:checksubmit(this.form,\'Save & Next\','.
1.417     albertel 2307: 	    $total.','.scalar(@partlist).');" target="_self" /> &nbsp;'."\n";
1.119     ng       2308: 	my $ntstu ='<select name="NTSTU">'.
                   2309: 	    '<option>1</option><option>2</option>'.
                   2310: 	    '<option>3</option><option>5</option>'.
                   2311: 	    '<option>7</option><option>10</option></select>'."\n";
1.257     albertel 2312: 	my $nsel = ($env{'form.NTSTU'} ne '' ? $env{'form.NTSTU'} : '1');
1.401     albertel 2313: 	$ntstu =~ s/<option>$nsel</<option selected="selected">$nsel</;
1.578     raeburn  2314:         $endform.=&mt('[_1]student(s)',$ntstu);
1.485     albertel 2315: 	$endform.='&nbsp;&nbsp;<input type="button" value="'.&mt('Previous').'" '.
1.589     bisitz   2316: 	    'onclick="javascript:checksubmit(this.form,\'Previous\');" target="_self" /> &nbsp;'."\n".
1.485     albertel 2317: 	    '<input type="button" value="'.&mt('Next').'" '.
1.589     bisitz   2318: 	    'onclick="javascript:checksubmit(this.form,\'Next\');" target="_self" /> &nbsp;';
1.592     bisitz   2319:         $endform.='<span class="LC_warning">'.
                   2320:                   &mt('(Next and Previous (student) do not save the scores.)').
                   2321:                   '</span>'."\n" ;
1.349     albertel 2322:         $endform.="<input type='hidden' value='".&get_increment().
1.348     bowersj2 2323:             "' name='increment' />";
1.485     albertel 2324: 	$endform.='</td></tr></table></form>';
1.41      ng       2325: 	$request->print($endform);
                   2326:     }
                   2327:     return '';
1.38      ng       2328: }
                   2329: 
1.464     albertel 2330: sub check_collaborators {
                   2331:     my ($symb,$uname,$udom,$record,$handgrade,$counter) = @_;
                   2332:     my ($result,@col_fullnames);
                   2333:     my ($classlist,undef,$fullname) = &getclasslist('all','0');
                   2334:     foreach my $part (keys(%$handgrade)) {
                   2335: 	my $ncol = &Apache::lonnet::EXT('resource.'.$part.
                   2336: 					'.maxcollaborators',
                   2337: 					$symb,$udom,$uname);
                   2338: 	next if ($ncol <= 0);
                   2339: 	$part =~ s/\_/\./g;
                   2340: 	next if ($record->{'resource.'.$part.'.collaborators'} eq '');
                   2341: 	my (@good_collaborators, @bad_collaborators);
                   2342: 	foreach my $possible_collaborator
                   2343: 	    (split(/,?\s+/,$record->{'resource.'.$part.'.collaborators'})) { 
                   2344: 	    $possible_collaborator =~ s/[\$\^\(\)]//g;
                   2345: 	    next if ($possible_collaborator eq '');
                   2346: 	    my ($co_name,$co_dom) = split(/\@|:/,$possible_collaborator);
                   2347: 	    $co_dom = $udom if (! defined($co_dom) || $co_dom =~ /^domain$/i);
                   2348: 	    next if ($co_name eq $uname && $co_dom eq $udom);
                   2349: 	    # Doing this grep allows 'fuzzy' specification
                   2350: 	    my @matches = grep(/^\Q$co_name\E:\Q$co_dom\E$/i, 
                   2351: 			       keys(%$classlist));
                   2352: 	    if (! scalar(@matches)) {
                   2353: 		push(@bad_collaborators, $possible_collaborator);
                   2354: 	    } else {
                   2355: 		push(@good_collaborators, @matches);
                   2356: 	    }
                   2357: 	}
                   2358: 	if (scalar(@good_collaborators) != 0) {
1.466     albertel 2359: 	    $result.='<br />'.&mt('Collaborators: ');
1.464     albertel 2360: 	    foreach my $name (@good_collaborators) {
                   2361: 		my ($lastname,$givenn) = split(/,/,$$fullname{$name});
                   2362: 		push(@col_fullnames, $givenn.' '.$lastname);
                   2363: 		$result.=$fullname->{$name}.'&nbsp; &nbsp; &nbsp;';
                   2364: 	    }
                   2365: 	    $result.='<br />'."\n";
1.466     albertel 2366: 	    my ($part)=split(/\./,$part);
1.464     albertel 2367: 	    $result.='<input type="hidden" name="collaborator'.$counter.
                   2368: 		'" value="'.$part.':'.(join ':',@good_collaborators).'" />'.
                   2369: 		"\n";
                   2370: 	}
                   2371: 	if (scalar(@bad_collaborators) > 0) {
1.466     albertel 2372: 	    $result.='<div class="LC_warning">';
1.464     albertel 2373: 	    $result.=&mt('This student has submitted [quant,_1,invalid collaborator]: [_2]',scalar(@bad_collaborators),join(', ',@bad_collaborators));
                   2374: 	    $result .= '</div>';
                   2375: 	}         
                   2376: 	if (scalar(@bad_collaborators > $ncol)) {
1.466     albertel 2377: 	    $result .= '<div class="LC_warning">';
1.464     albertel 2378: 	    $result .= &mt('This student has submitted too many '.
                   2379: 		'collaborators.  Maximum is [_1].',$ncol);
                   2380: 	    $result .= '</div>';
                   2381: 	}
                   2382:     }
                   2383:     return ($result,$fullname,\@col_fullnames);
                   2384: }
                   2385: 
1.44      ng       2386: #--- Retrieve the last submission for all the parts
1.38      ng       2387: sub get_last_submission {
1.119     ng       2388:     my ($returnhash)=@_;
1.596     raeburn  2389:     my (@string,$timestamp,%lasthidden);
1.119     ng       2390:     if ($$returnhash{'version'}) {
1.46      ng       2391: 	my %lasthash=();
                   2392: 	my ($version);
1.119     ng       2393: 	for ($version=1;$version<=$$returnhash{'version'};$version++) {
1.397     albertel 2394: 	    foreach my $key (sort(split(/\:/,
                   2395: 					$$returnhash{$version.':keys'}))) {
                   2396: 		$lasthash{$key}=$$returnhash{$version.':'.$key};
                   2397: 		$timestamp = 
1.545     raeburn  2398: 		    &Apache::lonlocal::locallocaltime($$returnhash{$version.':timestamp'});
1.46      ng       2399: 	    }
                   2400: 	}
1.596     raeburn  2401:         my %typeparts;
                   2402:         my $showsurv = 
                   2403:             &Apache::lonnet::allowed('vas',$env{'request.course.id'});
                   2404:         foreach my $key (sort(keys(%lasthash))) {
                   2405:             if ($key =~ /\.type$/) {
                   2406:                 if (($lasthash{$key} eq 'anonsurvey') || 
                   2407:                     ($lasthash{$key} eq 'anonsurveycred')) {
                   2408:                     my ($ign,@parts) = split(/\./,$key);
                   2409:                     pop(@parts);
                   2410:                     unless ($showsurv) {
                   2411:                         my $id = join(',',@parts);
                   2412:                         $typeparts{$ign.'.'.$id} = $lasthash{$key};
                   2413:                     }
                   2414:                     delete($lasthash{$key});
                   2415:                 }
                   2416:             }
                   2417:         }
                   2418:         my @hidden = keys(%typeparts);
1.397     albertel 2419: 	foreach my $key (keys(%lasthash)) {
                   2420: 	    next if ($key !~ /\.submission$/);
1.596     raeburn  2421:             my $hide;
                   2422:             if (@hidden) {
                   2423:                 foreach my $id (@hidden) {
                   2424:                     if ($key =~ /^\Q$id\E/) {
                   2425:                         $hide = 1;
                   2426:                         last;
                   2427:                     }
                   2428:                 }
                   2429:             }
1.397     albertel 2430: 	    my ($partid,$foo) = split(/submission$/,$key);
                   2431: 	    my $draft  = $lasthash{$partid.'awarddetail'} eq 'DRAFT' ?
1.398     albertel 2432: 		'<span class="LC_warning">Draft Copy</span> ' : '';
1.596     raeburn  2433: 	    push(@string, join(':', $key, $hide, $draft.$lasthash{$key}));
1.41      ng       2434: 	}
                   2435:     }
1.397     albertel 2436:     if (!@string) {
                   2437: 	$string[0] =
1.539     riegler  2438: 	    '<span class="LC_warning">'.&mt('Nothing submitted - no attempts.').'</span>';
1.397     albertel 2439:     }
                   2440:     return (\@string,\$timestamp);
1.38      ng       2441: }
1.35      ng       2442: 
1.44      ng       2443: #--- High light keywords, with style choosen by user.
1.38      ng       2444: sub keywords_highlight {
1.44      ng       2445:     my $string    = shift;
1.257     albertel 2446:     my $size      = $env{'form.kwsize'} eq '0' ? '' : 'size='.$env{'form.kwsize'};
                   2447:     my $styleon   = $env{'form.kwstyle'} eq ''  ? '' : $env{'form.kwstyle'};
1.41      ng       2448:     (my $styleoff = $styleon) =~ s/\</\<\//;
1.257     albertel 2449:     my @keylist   = split(/[,\s+]/,$env{'form.keywords'});
1.398     albertel 2450:     foreach my $keyword (@keylist) {
                   2451: 	$string =~ s/\b\Q$keyword\E(\b|\.)/<font color\=$env{'form.kwclr'} $size\>$styleon$keyword$styleoff<\/font>/gi;
1.41      ng       2452:     }
                   2453:     return $string;
1.38      ng       2454: }
1.36      ng       2455: 
1.44      ng       2456: #--- Called from submission routine
1.38      ng       2457: sub processHandGrade {
1.608     www      2458:     my ($request,$symb) = @_;
1.324     albertel 2459:     my (undef,undef,$url) = &Apache::lonnet::decode_symb($symb);
1.257     albertel 2460:     my $button = $env{'form.gradeOpt'};
                   2461:     my $ngrade = $env{'form.NCT'};
                   2462:     my $ntstu  = $env{'form.NTSTU'};
1.301     albertel 2463:     my $cdom   = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   2464:     my $cnum   = $env{'course.'.$env{'request.course.id'}.'.num'};
                   2465: 
1.44      ng       2466:     if ($button eq 'Save & Next') {
                   2467: 	my $ctr = 0;
                   2468: 	while ($ctr < $ngrade) {
1.257     albertel 2469: 	    my ($uname,$udom) = split(/:/,$env{'form.unamedom'.$ctr});
1.324     albertel 2470: 	    my ($errorflag,$pts,$wgt) = &saveHandGrade($request,$symb,$uname,$udom,$ctr);
1.71      ng       2471: 	    if ($errorflag eq 'no_score') {
                   2472: 		$ctr++;
                   2473: 		next;
                   2474: 	    }
1.104     albertel 2475: 	    if ($errorflag eq 'not_allowed') {
1.398     albertel 2476: 		$request->print("<span class=\"LC_warning\">Not allowed to modify grades for $uname:$udom</span>");
1.104     albertel 2477: 		$ctr++;
                   2478: 		next;
                   2479: 	    }
1.257     albertel 2480: 	    my $includemsg = $env{'form.includemsg'.$ctr};
1.44      ng       2481: 	    my ($subject,$message,$msgstatus) = ('','','');
1.418     albertel 2482: 	    my $restitle = &Apache::lonnet::gettitle($symb);
                   2483:             my ($feedurl,$showsymb) =
                   2484: 		&get_feedurl_and_symb($symb,$uname,$udom);
                   2485: 	    my $messagetail;
1.62      albertel 2486: 	    if ($includemsg =~ /savemsg|newmsg\Q$ctr\E/) {
1.298     www      2487: 		$subject = $env{'form.msgsub'} if ($includemsg =~ /msgsub/);
1.295     www      2488: 		unless ($subject=~/\w/) { $subject=&mt('Grading Feedback'); }
1.386     raeburn  2489: 		$subject.=' ['.$restitle.']';
1.44      ng       2490: 		my (@msgnum) = split(/,/,$includemsg);
                   2491: 		foreach (@msgnum) {
1.257     albertel 2492: 		    $message.=$env{'form.'.$_} if ($_ =~ /savemsg|newmsg/ && $_ ne '');
1.44      ng       2493: 		}
1.80      ng       2494: 		$message =&Apache::lonfeedback::clear_out_html($message);
1.298     www      2495: 		if ($env{'form.withgrades'.$ctr}) {
                   2496: 		    $message.="\n\nPoint".($pts > 1 ? 's':'').' awarded = '.$pts.' out of '.$wgt;
1.386     raeburn  2497: 		    $messagetail = " for <a href=\"".
1.605     www      2498: 		                   $feedurl."?symb=$showsymb\">$restitle</a>";
1.386     raeburn  2499: 		}
                   2500: 		$msgstatus = 
                   2501:                     &Apache::lonmsg::user_normal_msg($uname,$udom,$subject,
                   2502: 						     $message.$messagetail,
1.418     albertel 2503:                                                      undef,$feedurl,undef,
1.386     raeburn  2504:                                                      undef,undef,$showsymb,
                   2505:                                                      $restitle);
1.574     bisitz   2506: 		$request->print('<br />'.&mt('Sending message to [_1]',$uname.':'.$udom).': '.
1.296     www      2507: 				$msgstatus);
1.44      ng       2508: 	    }
1.257     albertel 2509: 	    if ($env{'form.collaborator'.$ctr}) {
1.155     albertel 2510: 		my @collabstrs=&Apache::loncommon::get_env_multiple("form.collaborator$ctr");
1.150     albertel 2511: 		foreach my $collabstr (@collabstrs) {
                   2512: 		    my ($part,@collaborators) = split(/:/,$collabstr);
1.310     banghart 2513: 		    foreach my $collaborator (@collaborators) {
1.150     albertel 2514: 			my ($errorflag,$pts,$wgt) = 
1.324     albertel 2515: 			    &saveHandGrade($request,$symb,$collaborator,$udom,$ctr,
1.257     albertel 2516: 					   $env{'form.unamedom'.$ctr},$part);
1.150     albertel 2517: 			if ($errorflag eq 'not_allowed') {
1.362     albertel 2518: 			    $request->print("<span class=\"LC_error\">".&mt('Not allowed to modify grades for [_1]',"$collaborator:$udom")."</span>");
1.150     albertel 2519: 			    next;
1.418     albertel 2520: 			} elsif ($message ne '') {
                   2521: 			    my ($baseurl,$showsymb) = 
                   2522: 				&get_feedurl_and_symb($symb,$collaborator,
                   2523: 						      $udom);
                   2524: 			    if ($env{'form.withgrades'.$ctr}) {
                   2525: 				$messagetail = " for <a href=\"".
1.605     www      2526:                                     $baseurl."?symb=$showsymb\">$restitle</a>";
1.150     albertel 2527: 			    }
1.418     albertel 2528: 			    $msgstatus = 
                   2529: 				&Apache::lonmsg::user_normal_msg($collaborator,$udom,$subject,$message.$messagetail,undef,$baseurl,undef,undef,undef,$showsymb,$restitle);
1.104     albertel 2530: 			}
1.44      ng       2531: 		    }
                   2532: 		}
                   2533: 	    }
                   2534: 	    $ctr++;
                   2535: 	}
                   2536:     }
                   2537: 
1.257     albertel 2538:     if ($env{'form.handgrade'} eq 'yes') {
1.119     ng       2539: 	# Keywords sorted in alphabatical order
1.257     albertel 2540: 	my $loginuser = $env{'user.name'}.':'.$env{'user.domain'};
1.119     ng       2541: 	my %keyhash = ();
1.257     albertel 2542: 	$env{'form.keywords'}           =~ s/,\s{0,}|\s+/ /g;
                   2543: 	$env{'form.keywords'}           =~ s/^\s+|\s+$//;
                   2544: 	my (@keywords) = sort(split(/\s+/,$env{'form.keywords'}));
                   2545: 	$env{'form.keywords'} = join(' ',@keywords);
                   2546: 	$keyhash{$symb.'_keywords'}     = $env{'form.keywords'};
                   2547: 	$keyhash{$symb.'_subject'}      = $env{'form.msgsub'};
                   2548: 	$keyhash{$loginuser.'_kwclr'}   = $env{'form.kwclr'};
                   2549: 	$keyhash{$loginuser.'_kwsize'}  = $env{'form.kwsize'};
                   2550: 	$keyhash{$loginuser.'_kwstyle'} = $env{'form.kwstyle'};
1.119     ng       2551: 
                   2552: 	# message center - Order of message gets changed. Blank line is eliminated.
1.257     albertel 2553: 	# New messages are saved in env for the next student.
1.119     ng       2554: 	# All messages are saved in nohist_handgrade.db
                   2555: 	my ($ctr,$idx) = (1,1);
1.257     albertel 2556: 	while ($ctr <= $env{'form.savemsgN'}) {
                   2557: 	    if ($env{'form.savemsg'.$ctr} ne '') {
                   2558: 		$keyhash{$symb.'_savemsg'.$idx} = $env{'form.savemsg'.$ctr};
1.119     ng       2559: 		$idx++;
                   2560: 	    }
                   2561: 	    $ctr++;
1.41      ng       2562: 	}
1.119     ng       2563: 	$ctr = 0;
                   2564: 	while ($ctr < $ngrade) {
1.257     albertel 2565: 	    if ($env{'form.newmsg'.$ctr} ne '') {
                   2566: 		$keyhash{$symb.'_savemsg'.$idx} = $env{'form.newmsg'.$ctr};
                   2567: 		$env{'form.savemsg'.$idx} = $env{'form.newmsg'.$ctr};
1.119     ng       2568: 		$idx++;
                   2569: 	    }
                   2570: 	    $ctr++;
1.41      ng       2571: 	}
1.257     albertel 2572: 	$env{'form.savemsgN'} = --$idx;
                   2573: 	$keyhash{$symb.'_savemsgN'} = $env{'form.savemsgN'};
1.119     ng       2574: 	my $putresult = &Apache::lonnet::put
1.301     albertel 2575: 	    ('nohist_handgrade',\%keyhash,$cdom,$cnum);
1.41      ng       2576:     }
1.44      ng       2577:     # Called by Save & Refresh from Highlight Attribute Window
1.257     albertel 2578:     my (undef,undef,$fullname) = &getclasslist($env{'form.section'},'1');
                   2579:     if ($env{'form.refresh'} eq 'on') {
1.86      ng       2580: 	my ($ctr,$total) = (0,0);
                   2581: 	while ($ctr < $ngrade) {
1.257     albertel 2582: 	    $total++ if  $env{'form.unamedom'.$ctr} ne '';
1.86      ng       2583: 	    $ctr++;
                   2584: 	}
1.257     albertel 2585: 	$env{'form.NTSTU'}=$ngrade;
1.86      ng       2586: 	$ctr = 0;
                   2587: 	while ($ctr < $total) {
1.257     albertel 2588: 	    my $processUser = $env{'form.unamedom'.$ctr};
                   2589: 	    ($env{'form.student'},$env{'form.userdom'}) = split(/:/,$processUser);
                   2590: 	    $env{'form.fullname'} = $$fullname{$processUser};
1.86      ng       2591: 	    &submission($request,$ctr,$total-1);
1.41      ng       2592: 	    $ctr++;
                   2593: 	}
                   2594: 	return '';
                   2595:     }
1.36      ng       2596: 
1.121     ng       2597: # Go directly to grade student - from submission or link from chart page
1.120     ng       2598:     if ($button eq 'Grade Student') {
1.598     www      2599: #	(undef,undef,$env{'form.handgrade'},undef,undef) = &showResourceInfo($symb);
1.257     albertel 2600: 	my $processUser = $env{'form.unamedom'.$env{'form.studentNo'}};
                   2601: 	($env{'form.student'},$env{'form.userdom'}) = split(/:/,$processUser);
                   2602: 	$env{'form.fullname'} = $$fullname{$processUser};
1.120     ng       2603: 	&submission($request,0,0);
                   2604: 	return '';
                   2605:     }
                   2606: 
1.44      ng       2607:     # Get the next/previous one or group of students
1.257     albertel 2608:     my $firststu = $env{'form.unamedom0'};
                   2609:     my $laststu = $env{'form.unamedom'.($ngrade-1)};
1.119     ng       2610:     my $ctr = 2;
1.41      ng       2611:     while ($laststu eq '') {
1.257     albertel 2612: 	$laststu  = $env{'form.unamedom'.($ngrade-$ctr)};
1.41      ng       2613: 	$ctr++;
                   2614: 	$laststu = $firststu if ($ctr > $ngrade);
                   2615:     }
1.44      ng       2616: 
1.41      ng       2617:     my (@parsedlist,@nextlist);
                   2618:     my ($nextflg) = 0;
1.524     raeburn  2619:     foreach my $item (sort 
1.294     albertel 2620: 	     {
                   2621: 		 if (lc($$fullname{$a}) ne lc($$fullname{$b})) {
                   2622: 		     return (lc($$fullname{$a}) cmp lc($$fullname{$b}));
                   2623: 		 }
                   2624: 		 return $a cmp $b;
                   2625: 	     } (keys(%$fullname))) {
1.605     www      2626: # FIXME: this is fishy, looks like the button label
1.41      ng       2627: 	if ($nextflg == 1 && $button =~ /Next$/) {
1.524     raeburn  2628: 	    push(@parsedlist,$item);
1.41      ng       2629: 	}
1.524     raeburn  2630: 	$nextflg = 1 if ($item eq $laststu);
1.41      ng       2631: 	if ($button eq 'Previous') {
1.524     raeburn  2632: 	    last if ($item eq $firststu);
                   2633: 	    push(@parsedlist,$item);
1.41      ng       2634: 	}
                   2635:     }
                   2636:     $ctr = 0;
1.605     www      2637: # FIXME: this is fishy, looks like the button label
1.41      ng       2638:     @parsedlist = reverse @parsedlist if ($button eq 'Previous');
1.582     raeburn  2639:     my $res_error;
                   2640:     my ($partlist) = &response_type($symb,\$res_error);
                   2641:     if ($res_error) {
                   2642:         $request->print(&navmap_errormsg());
                   2643:         return;
                   2644:     }
1.41      ng       2645:     foreach my $student (@parsedlist) {
1.257     albertel 2646: 	my $submitonly=$env{'form.submitonly'};
1.41      ng       2647: 	my ($uname,$udom) = split(/:/,$student);
1.301     albertel 2648: 	
                   2649: 	if ($submitonly eq 'queued') {
                   2650: 	    my %queue_status = 
                   2651: 		&Apache::bridgetask::get_student_status($symb,$cdom,$cnum,
                   2652: 							$udom,$uname);
                   2653: 	    next if (!defined($queue_status{'gradingqueue'}));
                   2654: 	}
                   2655: 
1.156     albertel 2656: 	if ($submitonly =~ /^(yes|graded|incorrect)$/) {
1.257     albertel 2657: #	    my %record = &Apache::lonnet::restore($symb,$env{'request.course.id'},$udom,$uname);
1.324     albertel 2658: 	    my %status=&student_gradeStatus($symb,$udom,$uname,$partlist);
1.145     albertel 2659: 	    my $submitted = 0;
1.248     albertel 2660: 	    my $ungraded = 0;
                   2661: 	    my $incorrect = 0;
1.524     raeburn  2662: 	    foreach my $item (keys(%status)) {
                   2663: 		$submitted = 1 if ($status{$item} ne 'nothing');
                   2664: 		$ungraded = 1 if ($status{$item} =~ /^ungraded/);
                   2665: 		$incorrect = 1 if ($status{$item} =~ /^incorrect/);
                   2666: 		my ($foo,$partid,$foo1) = split(/\./,$item);
1.145     albertel 2667: 		if ($status{'resource.'.$partid.'.submitted_by'} ne '') {
                   2668: 		    $submitted = 0;
                   2669: 		}
1.41      ng       2670: 	    }
1.156     albertel 2671: 	    next if (!$submitted && ($submitonly eq 'yes' ||
                   2672: 				     $submitonly eq 'incorrect' ||
                   2673: 				     $submitonly eq 'graded'));
1.248     albertel 2674: 	    next if (!$ungraded && ($submitonly eq 'graded'));
                   2675: 	    next if (!$incorrect && $submitonly eq 'incorrect');
1.41      ng       2676: 	}
1.524     raeburn  2677: 	push(@nextlist,$student) if ($ctr < $ntstu);
1.129     ng       2678: 	last if ($ctr == $ntstu);
1.41      ng       2679: 	$ctr++;
                   2680:     }
1.36      ng       2681: 
1.41      ng       2682:     $ctr = 0;
                   2683:     my $total = scalar(@nextlist)-1;
1.39      ng       2684: 
1.524     raeburn  2685:     foreach (sort(@nextlist)) {
1.41      ng       2686: 	my ($uname,$udom,$submitter) = split(/:/);
1.257     albertel 2687: 	$env{'form.student'}  = $uname;
                   2688: 	$env{'form.userdom'}  = $udom;
                   2689: 	$env{'form.fullname'} = $$fullname{$_};
1.41      ng       2690: 	&submission($request,$ctr,$total);
                   2691: 	$ctr++;
                   2692:     }
                   2693:     if ($total < 0) {
1.485     albertel 2694: 	my $the_end = '<h3><span class="LC_info">'.&mt('LON-CAPA User Message').'</span></h3><br />'."\n";
                   2695: 	$the_end.=&mt('<b>Message: </b> No more students for this section or class.').'<br /><br />'."\n";
                   2696: 	$the_end.=&mt('Click on the button below to return to the grading menu.').'<br /><br />'."\n";
1.41      ng       2697: 	$request->print($the_end);
                   2698:     }
                   2699:     return '';
1.38      ng       2700: }
1.36      ng       2701: 
1.44      ng       2702: #---- Save the score and award for each student, if changed
1.38      ng       2703: sub saveHandGrade {
1.324     albertel 2704:     my ($request,$symb,$stuname,$domain,$newflg,$submitter,$part) = @_;
1.342     banghart 2705:     my @version_parts;
1.104     albertel 2706:     my $usec = &Apache::lonnet::getsection($domain,$stuname,
1.257     albertel 2707: 					   $env{'request.course.id'});
1.104     albertel 2708:     if (!&canmodify($usec)) { return('not_allowed'); }
1.337     banghart 2709:     my %record = &Apache::lonnet::restore($symb,$env{'request.course.id'},$domain,$stuname);
1.251     banghart 2710:     my @parts_graded;
1.77      ng       2711:     my %newrecord  = ();
                   2712:     my ($pts,$wgt) = ('','');
1.269     raeburn  2713:     my %aggregate = ();
                   2714:     my $aggregateflag = 0;
1.301     albertel 2715:     my @parts = split(/:/,$env{'form.partlist'.$newflg});
                   2716:     foreach my $new_part (@parts) {
1.337     banghart 2717: 	#collaborator ($submi may vary for different parts
1.259     banghart 2718: 	if ($submitter && $new_part ne $part) { next; }
                   2719: 	my $dropMenu = $env{'form.GD_SEL'.$newflg.'_'.$new_part};
1.125     ng       2720: 	if ($dropMenu eq 'excused') {
1.259     banghart 2721: 	    if ($record{'resource.'.$new_part.'.solved'} ne 'excused') {
                   2722: 		$newrecord{'resource.'.$new_part.'.solved'} = 'excused';
                   2723: 		if (exists($record{'resource.'.$new_part.'.awarded'})) {
                   2724: 		    $newrecord{'resource.'.$new_part.'.awarded'} = '';
1.58      albertel 2725: 		}
1.364     banghart 2726: 	        $newrecord{'resource.'.$new_part.'.regrader'}="$env{'user.name'}:$env{'user.domain'}";
1.58      albertel 2727: 	    }
1.125     ng       2728: 	} elsif ($dropMenu eq 'reset status'
1.259     banghart 2729: 		 && exists($record{'resource.'.$new_part.'.solved'})) { #don't bother if no old records -> no attempts
1.524     raeburn  2730: 	    foreach my $key (keys(%record)) {
1.259     banghart 2731: 		if ($key=~/^resource\.\Q$new_part\E\./) { $newrecord{$key} = ''; }
1.197     albertel 2732: 	    }
1.259     banghart 2733: 	    $newrecord{'resource.'.$new_part.'.regrader'}=
1.257     albertel 2734: 		"$env{'user.name'}:$env{'user.domain'}";
1.270     albertel 2735:             my $totaltries = $record{'resource.'.$part.'.tries'};
                   2736: 
                   2737:             my %last_resets = &get_last_resets($symb,$env{'request.course.id'},
                   2738: 					       [$new_part]);
                   2739:             my $aggtries =$totaltries;
1.269     raeburn  2740:             if ($last_resets{$new_part}) {
1.270     albertel 2741:                 $aggtries = &get_num_tries(\%record,$last_resets{$new_part},
                   2742: 					   $new_part);
1.269     raeburn  2743:             }
1.270     albertel 2744: 
                   2745:             my $solvedstatus = $record{'resource.'.$new_part.'.solved'};
1.269     raeburn  2746:             if ($aggtries > 0) {
1.327     albertel 2747:                 &decrement_aggs($symb,$new_part,\%aggregate,$aggtries,$totaltries,$solvedstatus);
1.269     raeburn  2748:                 $aggregateflag = 1;
                   2749:             }
1.125     ng       2750: 	} elsif ($dropMenu eq '') {
1.259     banghart 2751: 	    $pts = ($env{'form.GD_BOX'.$newflg.'_'.$new_part} ne '' ? 
                   2752: 		    $env{'form.GD_BOX'.$newflg.'_'.$new_part} : 
                   2753: 		    $env{'form.RADVAL'.$newflg.'_'.$new_part});
                   2754: 	    if ($pts eq '' && $env{'form.GD_SEL'.$newflg.'_'.$new_part} eq '') {
1.153     albertel 2755: 		next;
                   2756: 	    }
1.259     banghart 2757: 	    $wgt = $env{'form.WGT'.$newflg.'_'.$new_part} eq '' ? 1 : 
                   2758: 		$env{'form.WGT'.$newflg.'_'.$new_part};
1.41      ng       2759: 	    my $partial= $pts/$wgt;
1.259     banghart 2760: 	    if ($partial eq $record{'resource.'.$new_part.'.awarded'}) {
1.153     albertel 2761: 		#do not update score for part if not changed.
1.346     banghart 2762:                 &handback_files($request,$symb,$stuname,$domain,$newflg,$new_part,\%newrecord);
1.153     albertel 2763: 		next;
1.251     banghart 2764: 	    } else {
1.524     raeburn  2765: 	        push(@parts_graded,$new_part);
1.153     albertel 2766: 	    }
1.259     banghart 2767: 	    if ($record{'resource.'.$new_part.'.awarded'} ne $partial) {
                   2768: 		$newrecord{'resource.'.$new_part.'.awarded'}  = $partial;
1.153     albertel 2769: 	    }
1.259     banghart 2770: 	    my $reckey = 'resource.'.$new_part.'.solved';
1.41      ng       2771: 	    if ($partial == 0) {
1.153     albertel 2772: 		if ($record{$reckey} ne 'incorrect_by_override') {
                   2773: 		    $newrecord{$reckey} = 'incorrect_by_override';
                   2774: 		}
1.41      ng       2775: 	    } else {
1.153     albertel 2776: 		if ($record{$reckey} ne 'correct_by_override') {
                   2777: 		    $newrecord{$reckey} = 'correct_by_override';
                   2778: 		}
                   2779: 	    }	    
                   2780: 	    if ($submitter && 
1.259     banghart 2781: 		($record{'resource.'.$new_part.'.submitted_by'} ne $submitter)) {
                   2782: 		$newrecord{'resource.'.$new_part.'.submitted_by'} = $submitter;
1.41      ng       2783: 	    }
1.259     banghart 2784: 	    $newrecord{'resource.'.$new_part.'.regrader'}=
1.257     albertel 2785: 		"$env{'user.name'}:$env{'user.domain'}";
1.41      ng       2786: 	}
1.259     banghart 2787: 	# unless problem has been graded, set flag to version the submitted files
1.305     banghart 2788: 	unless ($record{'resource.'.$new_part.'.solved'} =~ /^correct_/  || 
                   2789: 	        $record{'resource.'.$new_part.'.solved'} eq 'incorrect_by_override' ||
                   2790: 	        $dropMenu eq 'reset status')
                   2791: 	   {
1.524     raeburn  2792: 	    push(@version_parts,$new_part);
1.259     banghart 2793: 	}
1.41      ng       2794:     }
1.301     albertel 2795:     my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   2796:     my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   2797: 
1.344     albertel 2798:     if (%newrecord) {
                   2799:         if (@version_parts) {
1.364     banghart 2800:             my @changed_keys = &version_portfiles(\%record, \@parts_graded, 
                   2801:                                 $env{'request.course.id'}, $symb, $domain, $stuname, \@version_parts);
1.344     albertel 2802: 	    @newrecord{@changed_keys} = @record{@changed_keys};
1.367     albertel 2803: 	    foreach my $new_part (@version_parts) {
                   2804: 		&handback_files($request,$symb,$stuname,$domain,$newflg,
                   2805: 				$new_part,\%newrecord);
                   2806: 	    }
1.259     banghart 2807:         }
1.44      ng       2808: 	&Apache::lonnet::cstore(\%newrecord,$symb,
1.257     albertel 2809: 				$env{'request.course.id'},$domain,$stuname);
1.380     albertel 2810: 	&check_and_remove_from_queue(\@parts,\%record,\%newrecord,$symb,
                   2811: 				     $cdom,$cnum,$domain,$stuname);
1.41      ng       2812:     }
1.269     raeburn  2813:     if ($aggregateflag) {
                   2814:         &Apache::lonnet::cinc('nohist_resourcetracker',\%aggregate,
1.301     albertel 2815: 			      $cdom,$cnum);
1.269     raeburn  2816:     }
1.301     albertel 2817:     return ('',$pts,$wgt);
1.36      ng       2818: }
1.322     albertel 2819: 
1.380     albertel 2820: sub check_and_remove_from_queue {
                   2821:     my ($parts,$record,$newrecord,$symb,$cdom,$cnum,$domain,$stuname) = @_;
                   2822:     my @ungraded_parts;
                   2823:     foreach my $part (@{$parts}) {
                   2824: 	if (    $record->{   'resource.'.$part.'.awarded'} eq ''
                   2825: 	     && $record->{   'resource.'.$part.'.solved' } ne 'excused'
                   2826: 	     && $newrecord->{'resource.'.$part.'.awarded'} eq ''
                   2827: 	     && $newrecord->{'resource.'.$part.'.solved' } ne 'excused'
                   2828: 		) {
                   2829: 	    push(@ungraded_parts, $part);
                   2830: 	}
                   2831:     }
                   2832:     if ( !@ungraded_parts ) {
                   2833: 	&Apache::bridgetask::remove_from_queue('gradingqueue',$symb,$cdom,
                   2834: 					       $cnum,$domain,$stuname);
                   2835:     }
                   2836: }
                   2837: 
1.337     banghart 2838: sub handback_files {
                   2839:     my ($request,$symb,$stuname,$domain,$newflg,$new_part,$newrecord) = @_;
1.517     raeburn  2840:     my $portfolio_root = '/userfiles/portfolio';
1.582     raeburn  2841:     my $res_error;
                   2842:     my ($partlist,$handgrade,$responseType) = &response_type($symb,\$res_error);
                   2843:     if ($res_error) {
                   2844:         $request->print('<br />'.&navmap_errormsg().'<br />');
                   2845:         return;
                   2846:     }
1.375     albertel 2847:     my @part_response_id = &flatten_responseType($responseType);
                   2848:     foreach my $part_response_id (@part_response_id) {
                   2849:     	my ($part_id,$resp_id) = @{ $part_response_id };
                   2850: 	my $part_resp = join('_',@{ $part_response_id });
1.337     banghart 2851:             if (($env{'form.'.$newflg.'_'.$part_resp.'_returndoc1'}) && ($new_part == $part_id)) {
                   2852:                 # if multiple files are uploaded names will be 'returndoc2','returndoc3'
                   2853:                 my $file_counter = 1;
1.367     albertel 2854: 		my $file_msg;
1.337     banghart 2855:                 while ($env{'form.'.$newflg.'_'.$part_resp.'_returndoc'.$file_counter}) {
                   2856:                     my $fname=$env{'form.'.$newflg.'_'.$part_resp.'_returndoc'.$file_counter.'.filename'};
1.338     banghart 2857:                     my ($directory,$answer_file) = 
                   2858:                         ($env{'form.'.$newflg.'_'.$part_resp.'_origdoc'.$file_counter} =~ /^(.*?)([^\/]*)$/);
                   2859:                     my ($answer_name,$answer_ver,$answer_ext) =
                   2860: 		        &file_name_version_ext($answer_file);
1.355     banghart 2861: 		    my ($portfolio_path) = ($directory =~ /^.+$stuname\/portfolio(.*)/);
1.517     raeburn  2862:                     my $getpropath = 1;
                   2863: 		    my @dir_list = &Apache::lonnet::dirlist($portfolio_root.$portfolio_path,$domain,$stuname,$getpropath);
1.338     banghart 2864: 		    my $version = &get_next_version($answer_name, $answer_ext, \@dir_list);
1.355     banghart 2865:                     # fix file name
                   2866:                     my ($save_file_name) = (($directory.$answer_name.".$version.".$answer_ext) =~ /^.+\/${stuname}\/(.*)/);
                   2867:                     my $result=&Apache::lonnet::finishuserfileupload($stuname,$domain,
                   2868:             	                                $newflg.'_'.$part_resp.'_returndoc'.$file_counter,
                   2869:             	                                $save_file_name);
1.337     banghart 2870:                     if ($result !~ m|^/uploaded/|) {
1.536     raeburn  2871:                         $request->print('<br /><span class="LC_error">'.
                   2872:                             &mt('An error occurred ([_1]) while trying to upload [_2].',
                   2873:                                 $result,$newflg.'_'.$part_resp.'_returndoc'.$file_counter).
                   2874:                                         '</span>');
1.356     banghart 2875:                     } else {
1.360     banghart 2876:                         # mark the file as read only
                   2877:                         my @files = ($save_file_name);
1.372     albertel 2878:                         my @what = ($symb,$env{'request.course.id'},'handback');
1.360     banghart 2879:                         &Apache::lonnet::mark_as_readonly($domain,$stuname,\@files,\@what);
1.367     albertel 2880: 			if (exists($$newrecord{"resource.$new_part.$resp_id.handback"})) {
                   2881: 			    $$newrecord{"resource.$new_part.$resp_id.handback"}.=',';
                   2882: 			}
                   2883:                         $$newrecord{"resource.$new_part.$resp_id.handback"} .= $save_file_name;
                   2884: 			$file_msg.= "\n".'<br /><span class="LC_filename"><a href="/uploaded/'."$domain/$stuname/".$save_file_name.'">'.$save_file_name."</a></span><br />";
                   2885: 
1.337     banghart 2886:                     }
                   2887:                     $request->print("<br />".$fname." will be the uploaded file name");
1.354     albertel 2888:                     $request->print(" ".$env{'form.'.$newflg.'_'.$part_resp.'_origdoc'.$file_counter});
1.337     banghart 2889:                     $file_counter++;
                   2890:                 }
1.367     albertel 2891: 		my $subject = "File Handed Back by Instructor ";
                   2892: 		my $message = "A file has been returned that was originally submitted in reponse to: <br />";
                   2893: 		$message .= "<strong>".&Apache::lonnet::gettitle($symb)."</strong><br />";
                   2894: 		$message .= ' The returned file(s) are named: '. $file_msg;
                   2895: 		$message .= " and can be found in your portfolio space.";
1.418     albertel 2896: 		my ($feedurl,$showsymb) = 
                   2897: 		    &get_feedurl_and_symb($symb,$domain,$stuname);
1.386     raeburn  2898:                 my $restitle = &Apache::lonnet::gettitle($symb);
                   2899: 		my $msgstatus = 
                   2900:                    &Apache::lonmsg::user_normal_msg($stuname,$domain,$subject.
                   2901: 			 ' (File Returned) ['.$restitle.']',$message,undef,
1.418     albertel 2902:                          $feedurl,undef,undef,undef,$showsymb,$restitle);
1.337     banghart 2903:             }
                   2904:         }
1.338     banghart 2905:     return;
1.337     banghart 2906: }
                   2907: 
1.418     albertel 2908: sub get_feedurl_and_symb {
                   2909:     my ($symb,$uname,$udom) = @_;
                   2910:     my (undef,undef,$url) = &Apache::lonnet::decode_symb($symb);
                   2911:     $url = &Apache::lonnet::clutter($url);
                   2912:     my $encrypturl=&Apache::lonnet::EXT('resource.0.encrypturl',
                   2913: 					$symb,$udom,$uname);
                   2914:     if ($encrypturl =~ /^yes$/i) {
                   2915: 	&Apache::lonenc::encrypted(\$url,1);
                   2916: 	&Apache::lonenc::encrypted(\$symb,1);
                   2917:     }
                   2918:     return ($url,$symb);
                   2919: }
                   2920: 
1.313     banghart 2921: sub get_submitted_files {
                   2922:     my ($udom,$uname,$partid,$respid,$record) = @_;
                   2923:     my @files;
                   2924:     if ($$record{"resource.$partid.$respid.portfiles"}) {
                   2925:         my $file_url = '/uploaded/'.$udom.'/'.$uname.'/portfolio';
                   2926:         foreach my $file (split(',',$$record{"resource.$partid.$respid.portfiles"})) {
                   2927:     	    push(@files,$file_url.$file);
                   2928:         }
                   2929:     }
                   2930:     if ($$record{"resource.$partid.$respid.uploadedurl"}) {
                   2931:         push(@files,$$record{"resource.$partid.$respid.uploadedurl"});
                   2932:     }
                   2933:     return (\@files);
                   2934: }
1.322     albertel 2935: 
1.269     raeburn  2936: # ----------- Provides number of tries since last reset.
                   2937: sub get_num_tries {
                   2938:     my ($record,$last_reset,$part) = @_;
                   2939:     my $timestamp = '';
                   2940:     my $num_tries = 0;
                   2941:     if ($$record{'version'}) {
                   2942:         for (my $version=$$record{'version'};$version>=1;$version--) {
                   2943:             if (exists($$record{$version.':resource.'.$part.'.solved'})) {
                   2944:                 $timestamp = $$record{$version.':timestamp'};
                   2945:                 if ($timestamp > $last_reset) {
                   2946:                     $num_tries ++;
                   2947:                 } else {
                   2948:                     last;
                   2949:                 }
                   2950:             }
                   2951:         }
                   2952:     }
                   2953:     return $num_tries;
                   2954: }
                   2955: 
                   2956: # ----------- Determine decrements required in aggregate totals 
                   2957: sub decrement_aggs {
                   2958:     my ($symb,$part,$aggregate,$aggtries,$totaltries,$solvedstatus) = @_;
                   2959:     my %decrement = (
                   2960:                         attempts => 0,
                   2961:                         users => 0,
                   2962:                         correct => 0
                   2963:                     );
                   2964:     $decrement{'attempts'} = $aggtries;
                   2965:     if ($solvedstatus =~ /^correct/) {
                   2966:         $decrement{'correct'} = 1;
                   2967:     }
                   2968:     if ($aggtries == $totaltries) {
                   2969:         $decrement{'users'} = 1;
                   2970:     }
1.524     raeburn  2971:     foreach my $type (keys(%decrement)) {
1.269     raeburn  2972:         $$aggregate{$symb."\0".$part."\0".$type} = -$decrement{$type};
                   2973:     }
                   2974:     return;
                   2975: }
                   2976: 
                   2977: # ----------- Determine timestamps for last reset of aggregate totals for parts  
                   2978: sub get_last_resets {
1.270     albertel 2979:     my ($symb,$courseid,$partids) =@_;
                   2980:     my %last_resets;
1.269     raeburn  2981:     my $cdom = $env{'course.'.$courseid.'.domain'};
                   2982:     my $cname = $env{'course.'.$courseid.'.num'};
1.271     albertel 2983:     my @keys;
                   2984:     foreach my $part (@{$partids}) {
                   2985: 	push(@keys,"$symb\0$part\0resettime");
                   2986:     }
                   2987:     my %results=&Apache::lonnet::get('nohist_resourcetracker',\@keys,
                   2988: 				     $cdom,$cname);
                   2989:     foreach my $part (@{$partids}) {
                   2990: 	$last_resets{$part}=$results{"$symb\0$part\0resettime"};
1.269     raeburn  2991:     }
1.270     albertel 2992:     return %last_resets;
1.269     raeburn  2993: }
                   2994: 
1.251     banghart 2995: # ----------- Handles creating versions for portfolio files as answers
                   2996: sub version_portfiles {
1.343     banghart 2997:     my ($record, $parts_graded, $courseid, $symb, $domain, $stu_name, $v_flag) = @_;
1.263     banghart 2998:     my $version_parts = join('|',@$v_flag);
1.343     banghart 2999:     my @returned_keys;
1.255     banghart 3000:     my $parts = join('|', @$parts_graded);
1.517     raeburn  3001:     my $portfolio_root = '/userfiles/portfolio';
1.277     albertel 3002:     foreach my $key (keys(%$record)) {
1.259     banghart 3003:         my $new_portfiles;
1.263     banghart 3004:         if ($key =~ /^resource\.($version_parts)\./ && $key =~ /\.portfiles$/ ) {
1.342     banghart 3005:             my @versioned_portfiles;
1.367     albertel 3006:             my @portfiles = split(/\s*,\s*/,$$record{$key});
1.252     banghart 3007:             foreach my $file (@portfiles) {
1.306     banghart 3008:                 &Apache::lonnet::unmark_as_readonly($domain,$stu_name,[$symb,$env{'request.course.id'}],$file);
1.304     albertel 3009:                 my ($directory,$answer_file) =($file =~ /^(.*?)([^\/]*)$/);
                   3010: 		my ($answer_name,$answer_ver,$answer_ext) =
                   3011: 		    &file_name_version_ext($answer_file);
1.517     raeburn  3012:                 my $getpropath = 1;    
                   3013:                 my @dir_list = &Apache::lonnet::dirlist($portfolio_root.$directory,$domain,$stu_name,$getpropath);
1.342     banghart 3014:                 my $version = &get_next_version($answer_name, $answer_ext, \@dir_list);
1.306     banghart 3015:                 my $new_answer = &version_selected_portfile($domain, $stu_name, $directory, $answer_file, $version);
                   3016:                 if ($new_answer ne 'problem getting file') {
1.342     banghart 3017:                     push(@versioned_portfiles, $directory.$new_answer);
1.306     banghart 3018:                     &Apache::lonnet::mark_as_readonly($domain,$stu_name,
1.367     albertel 3019:                         [$directory.$new_answer],
1.306     banghart 3020:                         [$symb,$env{'request.course.id'},'graded']);
1.259     banghart 3021:                 }
1.252     banghart 3022:             }
1.343     banghart 3023:             $$record{$key} = join(',',@versioned_portfiles);
                   3024:             push(@returned_keys,$key);
1.251     banghart 3025:         }
                   3026:     } 
1.343     banghart 3027:     return (@returned_keys);   
1.305     banghart 3028: }
                   3029: 
1.307     banghart 3030: sub get_next_version {
1.341     banghart 3031:     my ($answer_name, $answer_ext, $dir_list) = @_;
1.307     banghart 3032:     my $version;
                   3033:     foreach my $row (@$dir_list) {
                   3034:         my ($file) = split(/\&/,$row,2);
                   3035:         my ($file_name,$file_version,$file_ext) =
                   3036: 	    &file_name_version_ext($file);
                   3037:         if (($file_name eq $answer_name) && 
                   3038: 	    ($file_ext eq $answer_ext)) {
                   3039:                 # gets here if filename and extension match, regardless of version
                   3040:                 if ($file_version ne '') {
                   3041:                 # a versioned file is found  so save it for later
                   3042:                 if ($file_version > $version) {
                   3043: 		    $version = $file_version;
                   3044: 	        }
                   3045:             }
                   3046:         }
                   3047:     } 
                   3048:     $version ++;
                   3049:     return($version);
                   3050: }
                   3051: 
1.305     banghart 3052: sub version_selected_portfile {
1.306     banghart 3053:     my ($domain,$stu_name,$directory,$file_name,$version) = @_;
                   3054:     my ($answer_name,$answer_ver,$answer_ext) =
                   3055:         &file_name_version_ext($file_name);
                   3056:     my $new_answer;
                   3057:     $env{'form.copy'} = &Apache::lonnet::getfile("/uploaded/$domain/$stu_name/portfolio$directory$file_name");
                   3058:     if($env{'form.copy'} eq '-1') {
                   3059:         $new_answer = 'problem getting file';
                   3060:     } else {
                   3061:         $new_answer = $answer_name.'.'.$version.'.'.$answer_ext;
                   3062:         my $copy_result = &Apache::lonnet::finishuserfileupload(
                   3063:                             $stu_name,$domain,'copy',
                   3064: 		        '/portfolio'.$directory.$new_answer);
                   3065:     }    
                   3066:     return ($new_answer);
1.251     banghart 3067: }
                   3068: 
1.304     albertel 3069: sub file_name_version_ext {
                   3070:     my ($file)=@_;
                   3071:     my @file_parts = split(/\./, $file);
                   3072:     my ($name,$version,$ext);
                   3073:     if (@file_parts > 1) {
                   3074: 	$ext=pop(@file_parts);
                   3075: 	if (@file_parts > 1 && $file_parts[-1] =~ /^\d+$/) {
                   3076: 	    $version=pop(@file_parts);
                   3077: 	}
                   3078: 	$name=join('.',@file_parts);
                   3079:     } else {
                   3080: 	$name=join('.',@file_parts);
                   3081:     }
                   3082:     return($name,$version,$ext);
                   3083: }
                   3084: 
1.44      ng       3085: #--------------------------------------------------------------------------------------
                   3086: #
                   3087: #-------------------------- Next few routines handles grading by section or whole class
                   3088: #
                   3089: #--- Javascript to handle grading by section or whole class
1.42      ng       3090: sub viewgrades_js {
                   3091:     my ($request) = shift;
                   3092: 
1.539     riegler  3093:     my $alertmsg = &mt('A number equal or greater than 0 is expected. Entered value = ');
1.597     wenzelju 3094:     $request->print(&Apache::lonhtmlcommon::scripttag(<<VIEWJAVASCRIPT));
1.45      ng       3095:    function writePoint(partid,weight,point) {
1.125     ng       3096: 	var radioButton = document.classgrade["RADVAL_"+partid];
                   3097: 	var textbox = document.classgrade["TEXTVAL_"+partid];
1.42      ng       3098: 	if (point == "textval") {
1.125     ng       3099: 	    point = document.classgrade["TEXTVAL_"+partid].value;
1.109     matthew  3100: 	    if (isNaN(point) || parseFloat(point) < 0) {
1.539     riegler  3101: 		alert("$alertmsg"+parseFloat(point));
1.42      ng       3102: 		var resetbox = false;
                   3103: 		for (var i=0; i<radioButton.length; i++) {
                   3104: 		    if (radioButton[i].checked) {
                   3105: 			textbox.value = i;
                   3106: 			resetbox = true;
                   3107: 		    }
                   3108: 		}
                   3109: 		if (!resetbox) {
                   3110: 		    textbox.value = "";
                   3111: 		}
                   3112: 		return;
                   3113: 	    }
1.109     matthew  3114: 	    if (parseFloat(point) > parseFloat(weight)) {
                   3115: 		var resp = confirm("You entered a value ("+parseFloat(point)+
1.44      ng       3116: 				   ") greater than the weight for the part. Accept?");
                   3117: 		if (resp == false) {
                   3118: 		    textbox.value = "";
                   3119: 		    return;
                   3120: 		}
                   3121: 	    }
1.42      ng       3122: 	    for (var i=0; i<radioButton.length; i++) {
                   3123: 		radioButton[i].checked=false;
1.109     matthew  3124: 		if (parseFloat(point) == i) {
1.42      ng       3125: 		    radioButton[i].checked=true;
                   3126: 		}
                   3127: 	    }
1.41      ng       3128: 
1.42      ng       3129: 	} else {
1.125     ng       3130: 	    textbox.value = parseFloat(point);
1.42      ng       3131: 	}
1.41      ng       3132: 	for (i=0;i<document.classgrade.total.value;i++) {
1.125     ng       3133: 	    var user = document.classgrade["ctr"+i].value;
1.289     albertel 3134: 	    user = user.replace(new RegExp(':', 'g'),"_");
1.125     ng       3135: 	    var scorename = document.classgrade["GD_"+user+"_"+partid+"_awarded"];
                   3136: 	    var saveval   = document.classgrade["GD_"+user+"_"+partid+"_solved_s"].value;
                   3137: 	    var selname   = document.classgrade["GD_"+user+"_"+partid+"_solved"];
1.42      ng       3138: 	    if (saveval != "correct") {
                   3139: 		scorename.value = point;
1.43      ng       3140: 		if (selname[0].selected != true) {
                   3141: 		    selname[0].selected = true;
                   3142: 		}
1.42      ng       3143: 	    }
                   3144: 	}
1.125     ng       3145: 	document.classgrade["SELVAL_"+partid][0].selected = true;
1.42      ng       3146:     }
                   3147: 
                   3148:     function writeRadText(partid,weight) {
1.125     ng       3149: 	var selval   = document.classgrade["SELVAL_"+partid];
                   3150: 	var radioButton = document.classgrade["RADVAL_"+partid];
1.265     www      3151:         var override = document.classgrade["FORCE_"+partid].checked;
1.125     ng       3152: 	var textbox = document.classgrade["TEXTVAL_"+partid];
                   3153: 	if (selval[1].selected || selval[2].selected) {
1.42      ng       3154: 	    for (var i=0; i<radioButton.length; i++) {
                   3155: 		radioButton[i].checked=false;
                   3156: 
                   3157: 	    }
                   3158: 	    textbox.value = "";
                   3159: 
                   3160: 	    for (i=0;i<document.classgrade.total.value;i++) {
1.125     ng       3161: 		var user = document.classgrade["ctr"+i].value;
1.289     albertel 3162: 		user = user.replace(new RegExp(':', 'g'),"_");
1.125     ng       3163: 		var scorename = document.classgrade["GD_"+user+"_"+partid+"_awarded"];
                   3164: 		var saveval   = document.classgrade["GD_"+user+"_"+partid+"_solved_s"].value;
                   3165: 		var selname   = document.classgrade["GD_"+user+"_"+partid+"_solved"];
1.265     www      3166: 		if ((saveval != "correct") || override) {
1.42      ng       3167: 		    scorename.value = "";
1.125     ng       3168: 		    if (selval[1].selected) {
                   3169: 			selname[1].selected = true;
                   3170: 		    } else {
                   3171: 			selname[2].selected = true;
                   3172: 			if (Number(document.classgrade["GD_"+user+"_"+partid+"_tries"].value)) 
                   3173: 			{document.classgrade["GD_"+user+"_"+partid+"_tries"].value = '0';}
                   3174: 		    }
1.42      ng       3175: 		}
                   3176: 	    }
1.43      ng       3177: 	} else {
                   3178: 	    for (i=0;i<document.classgrade.total.value;i++) {
1.125     ng       3179: 		var user = document.classgrade["ctr"+i].value;
1.289     albertel 3180: 		user = user.replace(new RegExp(':', 'g'),"_");
1.125     ng       3181: 		var scorename = document.classgrade["GD_"+user+"_"+partid+"_awarded"];
                   3182: 		var saveval   = document.classgrade["GD_"+user+"_"+partid+"_solved_s"].value;
                   3183: 		var selname   = document.classgrade["GD_"+user+"_"+partid+"_solved"];
1.265     www      3184: 		if ((saveval != "correct") || override) {
1.125     ng       3185: 		    scorename.value = document.classgrade["GD_"+user+"_"+partid+"_awarded_s"].value;
1.43      ng       3186: 		    selname[0].selected = true;
                   3187: 		}
                   3188: 	    }
                   3189: 	}	    
1.42      ng       3190:     }
                   3191: 
                   3192:     function changeSelect(partid,user) {
1.125     ng       3193: 	var selval = document.classgrade["GD_"+user+'_'+partid+"_solved"];
                   3194: 	var textbox = document.classgrade["GD_"+user+'_'+partid+"_awarded"];
1.44      ng       3195: 	var point  = textbox.value;
1.125     ng       3196: 	var weight = document.classgrade["weight_"+partid].value;
1.44      ng       3197: 
1.109     matthew  3198: 	if (isNaN(point) || parseFloat(point) < 0) {
1.539     riegler  3199: 	    alert("$alertmsg"+parseFloat(point));
1.44      ng       3200: 	    textbox.value = "";
                   3201: 	    return;
                   3202: 	}
1.109     matthew  3203: 	if (parseFloat(point) > parseFloat(weight)) {
                   3204: 	    var resp = confirm("You entered a value ("+parseFloat(point)+
1.44      ng       3205: 			       ") greater than the weight of the part. Accept?");
                   3206: 	    if (resp == false) {
                   3207: 		textbox.value = "";
                   3208: 		return;
                   3209: 	    }
                   3210: 	}
1.42      ng       3211: 	selval[0].selected = true;
                   3212:     }
                   3213: 
                   3214:     function changeOneScore(partid,user) {
1.125     ng       3215: 	var selval = document.classgrade["GD_"+user+'_'+partid+"_solved"];
                   3216: 	if (selval[1].selected || selval[2].selected) {
                   3217: 	    document.classgrade["GD_"+user+'_'+partid+"_awarded"].value = "";
                   3218: 	    if (selval[2].selected) {
                   3219: 		document.classgrade["GD_"+user+'_'+partid+"_tries"].value = "0";
                   3220: 	    }
1.269     raeburn  3221:         }
1.42      ng       3222:     }
                   3223: 
                   3224:     function resetEntry(numpart) {
                   3225: 	for (ctpart=0;ctpart<numpart;ctpart++) {
1.125     ng       3226: 	    var partid = document.classgrade["partid_"+ctpart].value;
                   3227: 	    var radioButton = document.classgrade["RADVAL_"+partid];
                   3228: 	    var textbox = document.classgrade["TEXTVAL_"+partid];
                   3229: 	    var selval  = document.classgrade["SELVAL_"+partid];
1.42      ng       3230: 	    for (var i=0; i<radioButton.length; i++) {
                   3231: 		radioButton[i].checked=false;
                   3232: 
                   3233: 	    }
                   3234: 	    textbox.value = "";
                   3235: 	    selval[0].selected = true;
                   3236: 
                   3237: 	    for (i=0;i<document.classgrade.total.value;i++) {
1.125     ng       3238: 		var user = document.classgrade["ctr"+i].value;
1.289     albertel 3239: 		user = user.replace(new RegExp(':', 'g'),"_");
1.125     ng       3240: 		var resetscore = document.classgrade["GD_"+user+"_"+partid+"_awarded"];
                   3241: 		resetscore.value = document.classgrade["GD_"+user+"_"+partid+"_awarded_s"].value;
                   3242: 		var resettries = document.classgrade["GD_"+user+"_"+partid+"_tries"];
                   3243: 		resettries.value = document.classgrade["GD_"+user+"_"+partid+"_tries_s"].value;
                   3244: 		var saveselval   = document.classgrade["GD_"+user+"_"+partid+"_solved_s"].value;
                   3245: 		var selname   = document.classgrade["GD_"+user+"_"+partid+"_solved"];
1.42      ng       3246: 		if (saveselval == "excused") {
1.43      ng       3247: 		    if (selname[1].selected == false) { selname[1].selected = true;}
1.42      ng       3248: 		} else {
1.43      ng       3249: 		    if (selname[0].selected == false) {selname[0].selected = true};
1.42      ng       3250: 		}
                   3251: 	    }
1.41      ng       3252: 	}
1.42      ng       3253:     }
                   3254: 
1.41      ng       3255: VIEWJAVASCRIPT
1.42      ng       3256: }
                   3257: 
1.44      ng       3258: #--- show scores for a section or whole class w/ option to change/update a score
1.42      ng       3259: sub viewgrades {
1.608     www      3260:     my ($request,$symb) = @_;
1.42      ng       3261:     &viewgrades_js($request);
1.41      ng       3262: 
1.168     albertel 3263:     #need to make sure we have the correct data for later EXT calls, 
                   3264:     #thus invalidate the cache
                   3265:     &Apache::lonnet::devalidatecourseresdata(
1.257     albertel 3266:                  $env{'course.'.$env{'request.course.id'}.'.num'},
                   3267:                  $env{'course.'.$env{'request.course.id'}.'.domain'});
1.168     albertel 3268:     &Apache::lonnet::clear_EXT_cache_status();
                   3269: 
1.398     albertel 3270:     my $result='<h3><span class="LC_info">'.&mt('Manual Grading').'</span></h3>';
1.41      ng       3271: 
                   3272:     #view individual student submission form - called using Javascript viewOneStudent
1.324     albertel 3273:     $result.=&jscriptNform($symb);
1.41      ng       3274: 
1.44      ng       3275:     #beginning of class grading form
1.442     banghart 3276:     my $stu_status = join(':',&Apache::loncommon::get_env_multiple('form.Status'));
1.41      ng       3277:     $result.= '<form action="/adm/grades" method="post" name="classgrade">'."\n".
1.418     albertel 3278: 	'<input type="hidden" name="symb"    value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
1.38      ng       3279: 	'<input type="hidden" name="command" value="editgrades" />'."\n".
1.432     banghart 3280: 	&build_section_inputs().
1.442     banghart 3281: 	'<input type="hidden" name="Status" value="'.$env{'stu_status'}.'" />'."\n".
1.72      ng       3282: 
1.560     raeburn  3283:     my ($common_header,$specific_header);
1.257     albertel 3284:     if ($env{'form.section'} eq 'all') {
1.560     raeburn  3285: 	$common_header = &mt('Assign Common Grade to Class');
                   3286:         $specific_header = &mt('Assign Grade to Specific Students in Class');
1.257     albertel 3287:     } elsif ($env{'form.section'} eq 'none') {
1.560     raeburn  3288:         $common_header = &mt('Assign Common Grade to Students in no Section');
                   3289: 	$specific_header = &mt('Assign Grade to Specific Students in no Section');
1.52      albertel 3290:     } else {
1.560     raeburn  3291:         my $section_display = join (", ",&Apache::loncommon::get_env_multiple('form.section'));
                   3292:         $common_header = &mt('Assign Common Grade to Students in Section(s) [_1]',$section_display);
                   3293: 	$specific_header = &mt('Assign Grade to Specific Students in Section(s) [_1]',$section_display);
1.52      albertel 3294:     }
1.560     raeburn  3295:     $result.= '<h3>'.$common_header.'</h3>'.&Apache::loncommon::start_data_table();
1.44      ng       3296:     #radio buttons/text box for assigning points for a section or class.
                   3297:     #handles different parts of a problem
1.582     raeburn  3298:     my $res_error;
                   3299:     my ($partlist,$handgrade,$responseType) = &response_type($symb,\$res_error);
                   3300:     if ($res_error) {
                   3301:         return &navmap_errormsg();
                   3302:     }
1.42      ng       3303:     my %weight = ();
                   3304:     my $ctsparts = 0;
1.45      ng       3305:     my %seen = ();
1.375     albertel 3306:     my @part_response_id = &flatten_responseType($responseType);
                   3307:     foreach my $part_response_id (@part_response_id) {
                   3308:     	my ($partid,$respid) = @{ $part_response_id };
                   3309: 	my $part_resp = join('_',@{ $part_response_id });
1.45      ng       3310: 	next if $seen{$partid};
                   3311: 	$seen{$partid}++;
1.375     albertel 3312: 	my $handgrade=$$handgrade{$part_resp};
1.42      ng       3313: 	my $wgt = &Apache::lonnet::EXT('resource.'.$partid.'.weight',$symb);
                   3314: 	$weight{$partid} = $wgt eq '' ? '1' : $wgt;
                   3315: 
1.324     albertel 3316: 	my $display_part=&get_display_part($partid,$symb);
1.485     albertel 3317: 	my $radio.='<table border="0"><tr>';  
1.41      ng       3318: 	my $ctr = 0;
1.42      ng       3319: 	while ($ctr<=$weight{$partid}) { # display radio buttons in a nice table 10 across
1.485     albertel 3320: 	    $radio.= '<td><label><input type="radio" name="RADVAL_'.$partid.'" '.
1.54      albertel 3321: 		'onclick="javascript:writePoint(\''.$partid.'\','.$weight{$partid}.
1.288     albertel 3322: 		','.$ctr.')" />'.$ctr."</label></td>\n";
1.41      ng       3323: 	    $result.=(($ctr+1)%10 == 0 ? '</tr><tr>' : '');
                   3324: 	    $ctr++;
                   3325: 	}
1.485     albertel 3326: 	$radio.='</tr></table>';
                   3327: 	my $line = '<input type="text" name="TEXTVAL_'.
1.589     bisitz   3328: 	    $partid.'" size="4" '.'onchange="javascript:writePoint(\''.
1.54      albertel 3329: 		$partid.'\','.$weight{$partid}.',\'textval\')" /> /'.
1.539     riegler  3330: 	    $weight{$partid}.' '.&mt('(problem weight)').'</td>'."\n";
                   3331: 	$line.= '<td><b>'.&mt('Grade Status').':</b><select name="SELVAL_'.$partid.'"'.
1.589     bisitz   3332: 	    'onchange="javascript:writeRadText(\''.$partid.'\','.
1.59      albertel 3333: 		$weight{$partid}.')"> '.
1.401     albertel 3334: 	    '<option selected="selected"> </option>'.
1.485     albertel 3335: 	    '<option value="excused">'.&mt('excused').'</option>'.
                   3336: 	    '<option value="reset status">'.&mt('reset status').'</option>'.
                   3337: 	    '</select></td>'.
                   3338:             '<td><label><input type="checkbox" name="FORCE_'.$partid.'" />'.&mt('Override "Correct"').'</label>';
                   3339: 	$line.='<input type="hidden" name="partid_'.
                   3340: 	    $ctsparts.'" value="'.$partid.'" />'."\n";
                   3341: 	$line.='<input type="hidden" name="weight_'.
                   3342: 	    $partid.'" value="'.$weight{$partid}.'" />'."\n";
                   3343: 
                   3344: 	$result.=
                   3345: 	    &Apache::loncommon::start_data_table_row()."\n".
1.577     bisitz   3346: 	    '<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 3347: 	    &Apache::loncommon::end_data_table_row()."\n";
1.42      ng       3348: 	$ctsparts++;
1.41      ng       3349:     }
1.474     albertel 3350:     $result.=&Apache::loncommon::end_data_table()."\n".
1.52      albertel 3351: 	'<input type="hidden" name="totalparts" value="'.$ctsparts.'" />';
1.485     albertel 3352:     $result.='<input type="button" value="'.&mt('Revert to Default').'" '.
1.589     bisitz   3353: 	'onclick="javascript:resetEntry('.$ctsparts.');" />';
1.41      ng       3354: 
1.44      ng       3355:     #table listing all the students in a section/class
                   3356:     #header of table
1.560     raeburn  3357:     $result.= '<h3>'.$specific_header.'</h3>'.
                   3358:               &Apache::loncommon::start_data_table().
                   3359: 	      &Apache::loncommon::start_data_table_header_row().
                   3360: 	      '<th>'.&mt('No.').'</th>'.
                   3361: 	      '<th>'.&nameUserString('header')."</th>\n";
1.582     raeburn  3362:     my $partserror;
                   3363:     my (@parts) = sort(&getpartlist($symb,\$partserror));
                   3364:     if ($partserror) {
                   3365:         return &navmap_errormsg();
                   3366:     }
1.324     albertel 3367:     my (undef,undef,$url)=&Apache::lonnet::decode_symb($symb);
1.269     raeburn  3368:     my @partids = ();
1.41      ng       3369:     foreach my $part (@parts) {
                   3370: 	my $display=&Apache::lonnet::metadata($url,$part.'.display');
1.539     riegler  3371:         my $narrowtext = &mt('Tries');
                   3372: 	$display =~ s|^Number of Attempts|$narrowtext <br />|; # makes the column narrower
1.41      ng       3373: 	if  (!$display) { $display = &Apache::lonnet::metadata($url,$part.'.name'); }
1.207     albertel 3374: 	my ($partid) = &split_part_type($part);
1.524     raeburn  3375:         push(@partids,$partid);
1.324     albertel 3376: 	my $display_part=&get_display_part($partid,$symb);
1.41      ng       3377: 	if ($display =~ /^Partial Credit Factor/) {
1.485     albertel 3378: 	    $result.='<th>'.
                   3379: 		&mt('Score Part: [_1]<br /> (weight = [_2])',
                   3380: 		    $display_part,$weight{$partid}).'</th>'."\n";
1.41      ng       3381: 	    next;
1.485     albertel 3382: 	    
1.207     albertel 3383: 	} else {
1.485     albertel 3384: 	    if ($display =~ /Problem Status/) {
                   3385: 		my $grade_status_mt = &mt('Grade Status');
                   3386: 		$display =~ s{Problem Status}{$grade_status_mt<br />};
                   3387: 	    }
                   3388: 	    my $part_mt = &mt('Part:');
                   3389: 	    $display =~s{\[Part: \Q$partid\E\]}{$part_mt $display_part};
1.41      ng       3390: 	}
1.485     albertel 3391: 
1.474     albertel 3392: 	$result.='<th>'.$display.'</th>'."\n";
1.41      ng       3393:     }
1.474     albertel 3394:     $result.=&Apache::loncommon::end_data_table_header_row();
1.44      ng       3395: 
1.270     albertel 3396:     my %last_resets = 
                   3397: 	&get_last_resets($symb,$env{'request.course.id'},\@partids);
1.269     raeburn  3398: 
1.41      ng       3399:     #get info for each student
1.44      ng       3400:     #list all the students - with points and grade status
1.257     albertel 3401:     my (undef,undef,$fullname) = &getclasslist($env{'form.section'},'1');
1.41      ng       3402:     my $ctr = 0;
1.294     albertel 3403:     foreach (sort 
                   3404: 	     {
                   3405: 		 if (lc($$fullname{$a}) ne lc($$fullname{$b})) {
                   3406: 		     return (lc($$fullname{$a}) cmp lc($$fullname{$b}));
                   3407: 		 }
                   3408: 		 return $a cmp $b;
                   3409: 	     } (keys(%$fullname))) {
1.126     ng       3410: 	$ctr++;
1.324     albertel 3411: 	$result.=&viewstudentgrade($symb,$env{'request.course.id'},
1.269     raeburn  3412: 				   $_,$$fullname{$_},\@parts,\%weight,$ctr,\%last_resets);
1.41      ng       3413:     }
1.474     albertel 3414:     $result.=&Apache::loncommon::end_data_table();
1.41      ng       3415:     $result.='<input type="hidden" name="total" value="'.$ctr.'" />'."\n";
1.485     albertel 3416:     $result.='<input type="button" value="'.&mt('Save').'" '.
1.589     bisitz   3417: 	'onclick="javascript:submit();" target="_self" /></form>'."\n";
1.96      albertel 3418:     if (scalar(%$fullname) eq 0) {
                   3419: 	my $colspan=3+scalar(@parts);
1.433     banghart 3420: 	my $section_display = join (", ",&Apache::loncommon::get_env_multiple('form.section'));
1.442     banghart 3421:         my $stu_status = join(' or ',&Apache::loncommon::get_env_multiple('form.Status'));
1.433     banghart 3422: 	$result='<span class="LC_warning">'.
1.485     albertel 3423: 	    &mt('There are no students in section(s) [_1] with enrollment status [_2] to modify or grade.',
1.442     banghart 3424: 	        $section_display, $stu_status).
1.433     banghart 3425: 	    '</span>';
1.96      albertel 3426:     }
1.41      ng       3427:     return $result;
                   3428: }
                   3429: 
1.44      ng       3430: #--- call by previous routine to display each student
1.41      ng       3431: sub viewstudentgrade {
1.324     albertel 3432:     my ($symb,$courseid,$student,$fullname,$parts,$weight,$ctr,$last_resets) = @_;
1.44      ng       3433:     my ($uname,$udom) = split(/:/,$student);
                   3434:     my %record=&Apache::lonnet::restore($symb,$courseid,$udom,$uname);
1.269     raeburn  3435:     my %aggregates = (); 
1.474     albertel 3436:     my $result=&Apache::loncommon::start_data_table_row().'<td align="right">'.
1.233     albertel 3437: 	'<input type="hidden" name="ctr'.($ctr-1).'" value="'.$student.'" />'.
                   3438: 	"\n".$ctr.'&nbsp;</td><td>&nbsp;'.
1.44      ng       3439: 	'<a href="javascript:viewOneStudent(\''.$uname.'\',\''.$udom.
1.417     albertel 3440: 	'\');" target="_self">'.$fullname.'</a> '.
1.398     albertel 3441: 	'<span class="LC_internal_info">('.$uname.($env{'user.domain'} eq $udom ? '' : ':'.$udom).')</span></td>'."\n";
1.281     albertel 3442:     $student=~s/:/_/; # colon doen't work in javascript for names
1.63      albertel 3443:     foreach my $apart (@$parts) {
                   3444: 	my ($part,$type) = &split_part_type($apart);
1.41      ng       3445: 	my $score=$record{"resource.$part.$type"};
1.276     albertel 3446:         $result.='<td align="center">';
1.269     raeburn  3447:         my ($aggtries,$totaltries);
                   3448:         unless (exists($aggregates{$part})) {
1.270     albertel 3449: 	    $totaltries = $record{'resource.'.$part.'.tries'};
                   3450: 
                   3451: 	    $aggtries = $totaltries;
1.269     raeburn  3452:             if ($$last_resets{$part}) {  
1.270     albertel 3453:                 $aggtries = &get_num_tries(\%record,$$last_resets{$part},
                   3454: 					   $part);
                   3455:             }
1.269     raeburn  3456:             $result.='<input type="hidden" name="'.
                   3457:                 'GD_'.$student.'_'.$part.'_aggtries" value="'.$aggtries.'" />'."\n";
                   3458:             $result.='<input type="hidden" name="'.
                   3459:                 'GD_'.$student.'_'.$part.'_totaltries" value="'.$totaltries.'" />'."\n";
                   3460:             $aggregates{$part} = 1;
                   3461:         }
1.41      ng       3462: 	if ($type eq 'awarded') {
1.320     albertel 3463: 	    my $pts = $score eq '' ? '' : &compute_points($score,$$weight{$part});
1.42      ng       3464: 	    $result.='<input type="hidden" name="'.
1.89      albertel 3465: 		'GD_'.$student.'_'.$part.'_awarded_s" value="'.$pts.'" />'."\n";
1.233     albertel 3466: 	    $result.='<input type="text" name="'.
1.89      albertel 3467: 		'GD_'.$student.'_'.$part.'_awarded" '.
1.589     bisitz   3468:                 'onchange="javascript:changeSelect(\''.$part.'\',\''.$student.
1.44      ng       3469: 		'\')" value="'.$pts.'" size="4" /></td>'."\n";
1.41      ng       3470: 	} elsif ($type eq 'solved') {
                   3471: 	    my ($status,$foo)=split(/_/,$score,2);
                   3472: 	    $status = 'nothing' if ($status eq '');
1.89      albertel 3473: 	    $result.='<input type="hidden" name="'.'GD_'.$student.'_'.
1.54      albertel 3474: 		$part.'_solved_s" value="'.$status.'" />'."\n";
1.233     albertel 3475: 	    $result.='&nbsp;<select name="'.
1.89      albertel 3476: 		'GD_'.$student.'_'.$part.'_solved" '.
1.589     bisitz   3477:                 'onchange="javascript:changeOneScore(\''.$part.'\',\''.$student.'\')" >'."\n";
1.485     albertel 3478: 	    $result.= (($status eq 'excused') ? '<option> </option><option selected="selected" value="excused">'.&mt('excused').'</option>' 
                   3479: 		: '<option selected="selected"> </option><option value="excused">'.&mt('excused').'</option>')."\n";
                   3480: 	    $result.='<option value="reset status">'.&mt('reset status').'</option>';
1.126     ng       3481: 	    $result.="</select>&nbsp;</td>\n";
1.122     ng       3482: 	} else {
                   3483: 	    $result.='<input type="hidden" name="'.
                   3484: 		'GD_'.$student.'_'.$part.'_'.$type.'_s" value="'.$score.'" />'.
                   3485: 		    "\n";
1.233     albertel 3486: 	    $result.='<input type="text" name="'.
1.122     ng       3487: 		'GD_'.$student.'_'.$part.'_'.$type.'" '.
                   3488: 		'value="'.$score.'" size="4" /></td>'."\n";
1.41      ng       3489: 	}
                   3490:     }
1.474     albertel 3491:     $result.=&Apache::loncommon::end_data_table_row();
1.41      ng       3492:     return $result;
1.38      ng       3493: }
                   3494: 
1.44      ng       3495: #--- change scores for all the students in a section/class
                   3496: #    record does not get update if unchanged
1.38      ng       3497: sub editgrades {
1.608     www      3498:     my ($request,$symb) = @_;
1.41      ng       3499: 
1.433     banghart 3500:     my $section_display = join (", ",&Apache::loncommon::get_env_multiple('form.section'));
1.477     albertel 3501:     my $title='<h2>'.&mt('Current Grade Status').'</h2>';
1.433     banghart 3502:     $title.='<h4>'.&mt('<b>Section: </b>[_1]',$section_display).'</h4>'."\n";
1.126     ng       3503: 
1.477     albertel 3504:     my $result= &Apache::loncommon::start_data_table().
                   3505: 	&Apache::loncommon::start_data_table_header_row().
                   3506: 	'<th rowspan="2" valign="middle">'.&mt('No.').'</th>'.
                   3507: 	'<th rowspan="2" valign="middle">'.&nameUserString('header')."</th>\n";
1.43      ng       3508:     my %scoreptr = (
                   3509: 		    'correct'  =>'correct_by_override',
                   3510: 		    'incorrect'=>'incorrect_by_override',
                   3511: 		    'excused'  =>'excused',
                   3512: 		    'ungraded' =>'ungraded_attempted',
1.596     raeburn  3513:                     'credited' =>'credit_attempted',
1.43      ng       3514: 		    'nothing'  => '',
                   3515: 		    );
1.257     albertel 3516:     my ($classlist,undef,$fullname) = &getclasslist($env{'form.section'},'0');
1.34      ng       3517: 
1.44      ng       3518:     my (@partid);
                   3519:     my %weight = ();
1.54      albertel 3520:     my %columns = ();
1.44      ng       3521:     my ($i,$ctr,$count,$rec_update) = (0,0,0,0);
1.54      albertel 3522: 
1.582     raeburn  3523:     my $partserror;
                   3524:     my (@parts) = sort(&getpartlist($symb,\$partserror));
                   3525:     if ($partserror) {
                   3526:         return &navmap_errormsg();
                   3527:     }
1.54      albertel 3528:     my $header;
1.257     albertel 3529:     while ($ctr < $env{'form.totalparts'}) {
                   3530: 	my $partid = $env{'form.partid_'.$ctr};
1.524     raeburn  3531: 	push(@partid,$partid);
1.257     albertel 3532: 	$weight{$partid} = $env{'form.weight_'.$partid};
1.44      ng       3533: 	$ctr++;
1.54      albertel 3534:     }
1.324     albertel 3535:     my (undef,undef,$url) = &Apache::lonnet::decode_symb($symb);
1.54      albertel 3536:     foreach my $partid (@partid) {
1.478     albertel 3537: 	$header .= '<th align="center">'.&mt('Old Score').'</th>'.
                   3538: 	    '<th align="center">'.&mt('New Score').'</th>';
1.54      albertel 3539: 	$columns{$partid}=2;
                   3540: 	foreach my $stores (@parts) {
                   3541: 	    my ($part,$type) = &split_part_type($stores);
                   3542: 	    if ($part !~ m/^\Q$partid\E/) { next;}
                   3543: 	    if ($type eq 'awarded' || $type eq 'solved') { next; }
                   3544: 	    my $display=&Apache::lonnet::metadata($url,$stores.'.display');
1.551     raeburn  3545: 	    $display =~ s/\[Part: \Q$part\E\]//;
1.539     riegler  3546:             my $narrowtext = &mt('Tries');
                   3547: 	    $display =~ s/Number of Attempts/$narrowtext/;
                   3548: 	    $header .= '<th align="center">'.&mt('Old').' '.$display.'</th>'.
                   3549: 		'<th align="center">'.&mt('New').' '.$display.'</th>';
1.54      albertel 3550: 	    $columns{$partid}+=2;
                   3551: 	}
                   3552:     }
                   3553:     foreach my $partid (@partid) {
1.324     albertel 3554: 	my $display_part=&get_display_part($partid,$symb);
1.478     albertel 3555: 	$result .= '<th colspan="'.$columns{$partid}.'" align="center">'.
                   3556: 	    &mt('Part: [_1] (Weight = [_2])',$display_part,$weight{$partid}).
                   3557: 	    '</th>';
1.54      albertel 3558: 
1.44      ng       3559:     }
1.477     albertel 3560:     $result .= &Apache::loncommon::end_data_table_header_row().
                   3561: 	&Apache::loncommon::start_data_table_header_row().
                   3562: 	$header.
                   3563: 	&Apache::loncommon::end_data_table_header_row();
                   3564:     my @noupdate;
1.126     ng       3565:     my ($updateCtr,$noupdateCtr) = (1,1);
1.257     albertel 3566:     for ($i=0; $i<$env{'form.total'}; $i++) {
1.93      albertel 3567: 	my $line;
1.257     albertel 3568: 	my $user = $env{'form.ctr'.$i};
1.281     albertel 3569: 	my ($uname,$udom)=split(/:/,$user);
1.44      ng       3570: 	my %newrecord;
                   3571: 	my $updateflag = 0;
1.281     albertel 3572: 	$line .= '<td>'.&nameUserString(undef,$$fullname{$user},$uname,$udom).'</td>';
1.108     albertel 3573: 	my $usec=$classlist->{"$uname:$udom"}[5];
1.105     albertel 3574: 	if (!&canmodify($usec)) {
1.126     ng       3575: 	    my $numcols=scalar(@partid)*4+2;
1.477     albertel 3576: 	    push(@noupdate,
1.478     albertel 3577: 		 $line."<td colspan=\"$numcols\"><span class=\"LC_warning\">".
                   3578: 		 &mt('Not allowed to modify student')."</span></td></tr>");
1.105     albertel 3579: 	    next;
                   3580: 	}
1.269     raeburn  3581:         my %aggregate = ();
                   3582:         my $aggregateflag = 0;
1.281     albertel 3583: 	$user=~s/:/_/; # colon doen't work in javascript for names
1.44      ng       3584: 	foreach (@partid) {
1.257     albertel 3585: 	    my $old_aw    = $env{'form.GD_'.$user.'_'.$_.'_awarded_s'};
1.54      albertel 3586: 	    my $old_part_pcr = $old_aw/($weight{$_} ne '0' ? $weight{$_}:1);
                   3587: 	    my $old_part  = $old_aw eq '' ? '' : $old_part_pcr;
1.257     albertel 3588: 	    my $old_score = $scoreptr{$env{'form.GD_'.$user.'_'.$_.'_solved_s'}};
                   3589: 	    my $awarded   = $env{'form.GD_'.$user.'_'.$_.'_awarded'};
1.54      albertel 3590: 	    my $pcr       = $awarded/($weight{$_} ne '0' ? $weight{$_} : 1);
                   3591: 	    my $partial   = $awarded eq '' ? '' : $pcr;
1.44      ng       3592: 	    my $score;
                   3593: 	    if ($partial eq '') {
1.257     albertel 3594: 		$score = $scoreptr{$env{'form.GD_'.$user.'_'.$_.'_solved_s'}};
1.44      ng       3595: 	    } elsif ($partial > 0) {
                   3596: 		$score = 'correct_by_override';
                   3597: 	    } elsif ($partial == 0) {
                   3598: 		$score = 'incorrect_by_override';
                   3599: 	    }
1.257     albertel 3600: 	    my $dropMenu = $env{'form.GD_'.$user.'_'.$_.'_solved'};
1.125     ng       3601: 	    $score = 'excused' if (($dropMenu eq 'excused') && ($score ne 'excused'));
                   3602: 
1.292     albertel 3603: 	    $newrecord{'resource.'.$_.'.regrader'}=
                   3604: 		"$env{'user.name'}:$env{'user.domain'}";
1.125     ng       3605: 	    if ($dropMenu eq 'reset status' &&
                   3606: 		$old_score ne '') { # ignore if no previous attempts => nothing to reset
1.299     albertel 3607: 		$newrecord{'resource.'.$_.'.tries'} = '';
1.125     ng       3608: 		$newrecord{'resource.'.$_.'.solved'} = '';
                   3609: 		$newrecord{'resource.'.$_.'.award'} = '';
1.299     albertel 3610: 		$newrecord{'resource.'.$_.'.awarded'} = '';
1.125     ng       3611: 		$updateflag = 1;
1.269     raeburn  3612:                 if ($env{'form.GD_'.$user.'_'.$_.'_aggtries'} > 0) {
                   3613:                     my $aggtries = $env{'form.GD_'.$user.'_'.$_.'_aggtries'};
                   3614:                     my $totaltries = $env{'form.GD_'.$user.'_'.$_.'_totaltries'};
                   3615:                     my $solvedstatus = $env{'form.GD_'.$user.'_'.$_.'_solved_s'};
                   3616:                     &decrement_aggs($symb,$_,\%aggregate,$aggtries,$totaltries,$solvedstatus);
                   3617:                     $aggregateflag = 1;
                   3618:                 }
1.139     albertel 3619: 	    } elsif (!($old_part eq $partial && $old_score eq $score)) {
                   3620: 		$updateflag = 1;
                   3621: 		$newrecord{'resource.'.$_.'.awarded'}  = $partial if $partial ne '';
                   3622: 		$newrecord{'resource.'.$_.'.solved'}   = $score;
                   3623: 		$rec_update++;
1.125     ng       3624: 	    }
                   3625: 
1.93      albertel 3626: 	    $line .= '<td align="center">'.$old_aw.'&nbsp;</td>'.
1.44      ng       3627: 		'<td align="center">'.$awarded.
                   3628: 		($score eq 'excused' ? $score : '').'&nbsp;</td>';
1.5       albertel 3629: 
1.54      albertel 3630: 
                   3631: 	    my $partid=$_;
                   3632: 	    foreach my $stores (@parts) {
                   3633: 		my ($part,$type) = &split_part_type($stores);
                   3634: 		if ($part !~ m/^\Q$partid\E/) { next;}
                   3635: 		if ($type eq 'awarded' || $type eq 'solved') { next; }
1.257     albertel 3636: 		my $old_aw    = $env{'form.GD_'.$user.'_'.$part.'_'.$type.'_s'};
                   3637: 		my $awarded   = $env{'form.GD_'.$user.'_'.$part.'_'.$type};
1.54      albertel 3638: 		if ($awarded ne '' && $awarded ne $old_aw) {
                   3639: 		    $newrecord{'resource.'.$part.'.'.$type}= $awarded;
1.257     albertel 3640: 		    $newrecord{'resource.'.$part.'.regrader'}="$env{'user.name'}:$env{'user.domain'}";
1.54      albertel 3641: 		    $updateflag=1;
                   3642: 		}
1.93      albertel 3643: 		$line .= '<td align="center">'.$old_aw.'&nbsp;</td>'.
1.54      albertel 3644: 		    '<td align="center">'.$awarded.'&nbsp;</td>';
                   3645: 	    }
1.44      ng       3646: 	}
1.477     albertel 3647: 	$line.="\n";
1.301     albertel 3648: 
                   3649: 	my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   3650: 	my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   3651: 
1.44      ng       3652: 	if ($updateflag) {
                   3653: 	    $count++;
1.257     albertel 3654: 	    &Apache::lonnet::cstore(\%newrecord,$symb,$env{'request.course.id'},
1.89      albertel 3655: 				    $udom,$uname);
1.301     albertel 3656: 
                   3657: 	    if (&Apache::bridgetask::in_queue('gradingqueue',$symb,$cdom,
                   3658: 					      $cnum,$udom,$uname)) {
                   3659: 		# need to figure out if should be in queue.
                   3660: 		my %record =  
                   3661: 		    &Apache::lonnet::restore($symb,$env{'request.course.id'},
                   3662: 					     $udom,$uname);
                   3663: 		my $all_graded = 1;
                   3664: 		my $none_graded = 1;
                   3665: 		foreach my $part (@parts) {
                   3666: 		    if ( $record{'resource.'.$part.'.awarded'} eq '' ) {
                   3667: 			$all_graded = 0;
                   3668: 		    } else {
                   3669: 			$none_graded = 0;
                   3670: 		    }
                   3671: 		}
                   3672: 
                   3673: 		if ($all_graded || $none_graded) {
                   3674: 		    &Apache::bridgetask::remove_from_queue('gradingqueue',
                   3675: 							   $symb,$cdom,$cnum,
                   3676: 							   $udom,$uname);
                   3677: 		}
                   3678: 	    }
                   3679: 
1.477     albertel 3680: 	    $result.=&Apache::loncommon::start_data_table_row().
                   3681: 		'<td align="right">&nbsp;'.$updateCtr.'&nbsp;</td>'.$line.
                   3682: 		&Apache::loncommon::end_data_table_row();
1.126     ng       3683: 	    $updateCtr++;
1.93      albertel 3684: 	} else {
1.477     albertel 3685: 	    push(@noupdate,
                   3686: 		 '<td align="right">&nbsp;'.$noupdateCtr.'&nbsp;</td>'.$line);
1.126     ng       3687: 	    $noupdateCtr++;
1.44      ng       3688: 	}
1.269     raeburn  3689:         if ($aggregateflag) {
                   3690:             &Apache::lonnet::cinc('nohist_resourcetracker',\%aggregate,
1.301     albertel 3691: 				  $cdom,$cnum);
1.269     raeburn  3692:         }
1.93      albertel 3693:     }
1.477     albertel 3694:     if (@noupdate) {
1.126     ng       3695: #	my $numcols=(scalar(@partid)*(scalar(@parts)-1)*2)+3;
                   3696: 	my $numcols=scalar(@partid)*4+2;
1.477     albertel 3697: 	$result .= &Apache::loncommon::start_data_table_row('LC_empty_row').
1.478     albertel 3698: 	    '<td align="center" colspan="'.$numcols.'">'.
                   3699: 	    &mt('No Changes Occurred For the Students Below').
                   3700: 	    '</td>'.
1.477     albertel 3701: 	    &Apache::loncommon::end_data_table_row();
                   3702: 	foreach my $line (@noupdate) {
                   3703: 	    $result.=
                   3704: 		&Apache::loncommon::start_data_table_row().
                   3705: 		$line.
                   3706: 		&Apache::loncommon::end_data_table_row();
                   3707: 	}
1.44      ng       3708:     }
1.614     www      3709:     $result .= &Apache::loncommon::end_data_table();
1.478     albertel 3710:     my $msg = '<p><b>'.
                   3711: 	&mt('Number of records updated = [_1] for [quant,_2,student].',
                   3712: 	    $rec_update,$count).'</b><br />'.
                   3713: 	'<b>'.&mt('Total number of students = [_1]',$env{'form.total'}).
                   3714: 	'</b></p>';
1.44      ng       3715:     return $title.$msg.$result;
1.5       albertel 3716: }
1.54      albertel 3717: 
                   3718: sub split_part_type {
                   3719:     my ($partstr) = @_;
                   3720:     my ($temp,@allparts)=split(/_/,$partstr);
                   3721:     my $type=pop(@allparts);
1.439     albertel 3722:     my $part=join('_',@allparts);
1.54      albertel 3723:     return ($part,$type);
                   3724: }
                   3725: 
1.44      ng       3726: #------------- end of section for handling grading by section/class ---------
                   3727: #
                   3728: #----------------------------------------------------------------------------
                   3729: 
1.5       albertel 3730: 
1.44      ng       3731: #----------------------------------------------------------------------------
                   3732: #
                   3733: #-------------------------- Next few routines handles grading by csv upload
                   3734: #
                   3735: #--- Javascript to handle csv upload
1.27      albertel 3736: sub csvupload_javascript_reverse_associate {
1.573     bisitz   3737:     my $error1=&mt('You need to specify the username or the student/employee ID');
1.246     albertel 3738:     my $error2=&mt('You need to specify at least one grading field');
1.27      albertel 3739:   return(<<ENDPICK);
                   3740:   function verify(vf) {
                   3741:     var foundsomething=0;
                   3742:     var founduname=0;
1.243     albertel 3743:     var foundID=0;
1.27      albertel 3744:     for (i=0;i<=vf.nfields.value;i++) {
                   3745:       tw=eval('vf.f'+i+'.selectedIndex');
1.243     albertel 3746:       if (i==0 && tw!=0) { foundID=1; }
                   3747:       if (i==1 && tw!=0) { founduname=1; }
                   3748:       if (i!=0 && i!=1 && i!=2 && tw!=0) { foundsomething=1; }
1.27      albertel 3749:     }
1.246     albertel 3750:     if (founduname==0 && foundID==0) {
                   3751: 	alert('$error1');
                   3752: 	return;
1.27      albertel 3753:     }
                   3754:     if (foundsomething==0) {
1.246     albertel 3755: 	alert('$error2');
                   3756: 	return;
1.27      albertel 3757:     }
                   3758:     vf.submit();
                   3759:   }
                   3760:   function flip(vf,tf) {
                   3761:     var nw=eval('vf.f'+tf+'.selectedIndex');
                   3762:     var i;
                   3763:     for (i=0;i<=vf.nfields.value;i++) {
                   3764:       //can not pick the same destination field for both name and domain
                   3765:       if (((i ==0)||(i ==1)) && 
                   3766:           ((tf==0)||(tf==1)) && 
                   3767:           (i!=tf) &&
                   3768:           (eval('vf.f'+i+'.selectedIndex')==nw)) {
                   3769:         eval('vf.f'+i+'.selectedIndex=0;')
                   3770:       }
                   3771:     }
                   3772:   }
                   3773: ENDPICK
                   3774: }
                   3775: 
                   3776: sub csvupload_javascript_forward_associate {
1.573     bisitz   3777:     my $error1=&mt('You need to specify the username or the student/employee ID');
1.246     albertel 3778:     my $error2=&mt('You need to specify at least one grading field');
1.27      albertel 3779:   return(<<ENDPICK);
                   3780:   function verify(vf) {
                   3781:     var foundsomething=0;
                   3782:     var founduname=0;
1.243     albertel 3783:     var foundID=0;
1.27      albertel 3784:     for (i=0;i<=vf.nfields.value;i++) {
                   3785:       tw=eval('vf.f'+i+'.selectedIndex');
1.243     albertel 3786:       if (tw==1) { foundID=1; }
                   3787:       if (tw==2) { founduname=1; }
                   3788:       if (tw>3) { foundsomething=1; }
1.27      albertel 3789:     }
1.246     albertel 3790:     if (founduname==0 && foundID==0) {
                   3791: 	alert('$error1');
                   3792: 	return;
1.27      albertel 3793:     }
                   3794:     if (foundsomething==0) {
1.246     albertel 3795: 	alert('$error2');
                   3796: 	return;
1.27      albertel 3797:     }
                   3798:     vf.submit();
                   3799:   }
                   3800:   function flip(vf,tf) {
                   3801:     var nw=eval('vf.f'+tf+'.selectedIndex');
                   3802:     var i;
                   3803:     //can not pick the same destination field twice
                   3804:     for (i=0;i<=vf.nfields.value;i++) {
                   3805:       if ((i!=tf) && (eval('vf.f'+i+'.selectedIndex')==nw)) {
                   3806:         eval('vf.f'+i+'.selectedIndex=0;')
                   3807:       }
                   3808:     }
                   3809:   }
                   3810: ENDPICK
                   3811: }
                   3812: 
1.26      albertel 3813: sub csvuploadmap_header {
1.324     albertel 3814:     my ($request,$symb,$datatoken,$distotal)= @_;
1.41      ng       3815:     my $javascript;
1.257     albertel 3816:     if ($env{'form.upfile_associate'} eq 'reverse') {
1.41      ng       3817: 	$javascript=&csvupload_javascript_reverse_associate();
                   3818:     } else {
                   3819: 	$javascript=&csvupload_javascript_forward_associate();
                   3820:     }
1.45      ng       3821: 
1.598     www      3822:     my $result='';
1.257     albertel 3823:     my $checked=(($env{'form.noFirstLine'})?' checked="checked"':'');
1.245     albertel 3824:     my $ignore=&mt('Ignore First Line');
1.418     albertel 3825:     $symb = &Apache::lonenc::check_encrypt($symb);
1.41      ng       3826:     $request->print(<<ENDPICK);
1.26      albertel 3827: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="gradesupload">
1.398     albertel 3828: <h3><span class="LC_info">Uploading Class Grades</span></h3>
1.45      ng       3829: $result
1.326     albertel 3830: <hr />
1.26      albertel 3831: <h3>Identify fields</h3>
                   3832: Total number of records found in file: $distotal <hr />
                   3833: Enter as many fields as you can. The system will inform you and bring you back
                   3834: to this page if the data selected is insufficient to run your class.<hr />
1.589     bisitz   3835: <input type="button" value="Reverse Association" onclick="javascript:this.form.associate.value='Reverse Association';submit(this.form);" />
1.245     albertel 3836: <label><input type="checkbox" name="noFirstLine" $checked />$ignore</label>
1.26      albertel 3837: <input type="hidden" name="associate"  value="" />
                   3838: <input type="hidden" name="phase"      value="three" />
                   3839: <input type="hidden" name="datatoken"  value="$datatoken" />
1.257     albertel 3840: <input type="hidden" name="fileupload" value="$env{'form.fileupload'}" />
                   3841: <input type="hidden" name="upfiletype" value="$env{'form.upfiletype'}" />
1.26      albertel 3842: <input type="hidden" name="upfile_associate" 
1.257     albertel 3843:                                        value="$env{'form.upfile_associate'}" />
1.26      albertel 3844: <input type="hidden" name="symb"       value="$symb" />
1.246     albertel 3845: <input type="hidden" name="command"    value="csvuploadoptions" />
1.26      albertel 3846: <hr />
                   3847: ENDPICK
1.597     wenzelju 3848:     $request->print(&Apache::lonhtmlcommon::scripttag($javascript));
1.118     ng       3849:     return '';
1.26      albertel 3850: 
                   3851: }
                   3852: 
                   3853: sub csvupload_fields {
1.582     raeburn  3854:     my ($symb,$errorref) = @_;
                   3855:     my (@parts) = &getpartlist($symb,$errorref);
                   3856:     if (ref($errorref)) {
                   3857:         if ($$errorref) {
                   3858:             return;
                   3859:         }
                   3860:     }
                   3861: 
1.556     weissno  3862:     my @fields=(['ID','Student/Employee ID'],
1.243     albertel 3863: 		['username','Student Username'],
                   3864: 		['domain','Student Domain']);
1.324     albertel 3865:     my (undef,undef,$url) = &Apache::lonnet::decode_symb($symb);
1.41      ng       3866:     foreach my $part (sort(@parts)) {
                   3867: 	my @datum;
                   3868: 	my $display=&Apache::lonnet::metadata($url,$part.'.display');
                   3869: 	my $name=$part;
                   3870: 	if  (!$display) { $display = $name; }
                   3871: 	@datum=($name,$display);
1.244     albertel 3872: 	if ($name=~/^stores_(.*)_awarded/) {
                   3873: 	    push(@fields,['stores_'.$1.'_points',"Points [Part: $1]"]);
                   3874: 	}
1.41      ng       3875: 	push(@fields,\@datum);
                   3876:     }
                   3877:     return (@fields);
1.26      albertel 3878: }
                   3879: 
                   3880: sub csvuploadmap_footer {
1.41      ng       3881:     my ($request,$i,$keyfields) =@_;
                   3882:     $request->print(<<ENDPICK);
1.26      albertel 3883: </table>
                   3884: <input type="hidden" name="nfields" value="$i" />
                   3885: <input type="hidden" name="keyfields" value="$keyfields" />
1.589     bisitz   3886: <input type="button" onclick="javascript:verify(this.form)" value="Assign Grades" /><br />
1.26      albertel 3887: </form>
                   3888: ENDPICK
                   3889: }
                   3890: 
1.283     albertel 3891: sub checkforfile_js {
1.539     riegler  3892:     my $alertmsg = &mt('Please use the browse button to select a file from your local directory.');
1.597     wenzelju 3893:     my $result = &Apache::lonhtmlcommon::scripttag(<<CSVFORMJS);
1.86      ng       3894:     function checkUpload(formname) {
                   3895: 	if (formname.upfile.value == "") {
1.539     riegler  3896: 	    alert("$alertmsg");
1.86      ng       3897: 	    return false;
                   3898: 	}
                   3899: 	formname.submit();
                   3900:     }
                   3901: CSVFORMJS
1.283     albertel 3902:     return $result;
                   3903: }
                   3904: 
                   3905: sub upcsvScores_form {
1.608     www      3906:     my ($request,$symb) = @_;
1.283     albertel 3907:     if (!$symb) {return '';}
                   3908:     my $result=&checkforfile_js();
1.326     albertel 3909:     $result.='<br /><table width="100%" border="0"><tr><td bgcolor="#777777">'."\n";
                   3910:     $result.='<table width="100%" border="0"><tr bgcolor="#e6ffff"><td>'."\n";
1.538     schulted 3911:     $result.='&nbsp;<b>'.&mt('Specify a file containing the class scores for current resource.').
                   3912: 	'</b></td></tr>'."\n";
1.86      ng       3913:     $result.='<tr bgcolor=#ffffe6><td>'."\n";
1.370     www      3914:     my $upload=&mt("Upload Scores");
1.86      ng       3915:     my $upfile_select=&Apache::loncommon::upfile_select_html();
1.245     albertel 3916:     my $ignore=&mt('Ignore First Line');
1.418     albertel 3917:     $symb = &Apache::lonenc::check_encrypt($symb);
1.86      ng       3918:     $result.=<<ENDUPFORM;
1.106     albertel 3919: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="gradesupload">
1.86      ng       3920: <input type="hidden" name="symb" value="$symb" />
                   3921: <input type="hidden" name="command" value="csvuploadmap" />
                   3922: $upfile_select
1.589     bisitz   3923: <br /><input type="button" onclick="javascript:checkUpload(this.form);" value="$upload" />
1.283     albertel 3924: <label><input type="checkbox" name="noFirstLine" />$ignore</label>
1.86      ng       3925: </form>
                   3926: ENDUPFORM
1.370     www      3927:     $result.=&Apache::loncommon::help_open_topic("Course_Convert_To_CSV",
                   3928:                            &mt("How do I create a CSV file from a spreadsheet"))
                   3929:     .'</td></tr></table>'."\n";
1.86      ng       3930:     $result.='</td></tr></table><br /><br />'."\n";
                   3931:     return $result;
                   3932: }
                   3933: 
                   3934: 
1.26      albertel 3935: sub csvuploadmap {
1.608     www      3936:     my ($request,$symb)= @_;
1.41      ng       3937:     if (!$symb) {return '';}
1.72      ng       3938: 
1.41      ng       3939:     my $datatoken;
1.257     albertel 3940:     if (!$env{'form.datatoken'}) {
1.41      ng       3941: 	$datatoken=&Apache::loncommon::upfile_store($request);
1.26      albertel 3942:     } else {
1.257     albertel 3943: 	$datatoken=$env{'form.datatoken'};
1.41      ng       3944: 	&Apache::loncommon::load_tmp_file($request);
1.26      albertel 3945:     }
1.41      ng       3946:     my @records=&Apache::loncommon::upfile_record_sep();
1.257     albertel 3947:     if ($env{'form.noFirstLine'}) { shift(@records); }
1.324     albertel 3948:     &csvuploadmap_header($request,$symb,$datatoken,$#records+1);
1.41      ng       3949:     my ($i,$keyfields);
                   3950:     if (@records) {
1.582     raeburn  3951:         my $fieldserror;
                   3952: 	my @fields=&csvupload_fields($symb,\$fieldserror);
                   3953:         if ($fieldserror) {
                   3954:             $request->print(&navmap_errormsg());
                   3955:             return;
                   3956:         }
1.257     albertel 3957: 	if ($env{'form.upfile_associate'} eq 'reverse') {	
1.41      ng       3958: 	    &Apache::loncommon::csv_print_samples($request,\@records);
                   3959: 	    $i=&Apache::loncommon::csv_print_select_table($request,\@records,
                   3960: 							  \@fields);
                   3961: 	    foreach (@fields) { $keyfields.=$_->[0].','; }
                   3962: 	    chop($keyfields);
                   3963: 	} else {
                   3964: 	    unshift(@fields,['none','']);
                   3965: 	    $i=&Apache::loncommon::csv_samples_select_table($request,\@records,
                   3966: 							    \@fields);
1.311     banghart 3967:             foreach my $rec (@records) {
                   3968:                 my %temp = &Apache::loncommon::record_sep($rec);
                   3969:                 if (%temp) {
                   3970:                     $keyfields=join(',',sort(keys(%temp)));
                   3971:                     last;
                   3972:                 }
                   3973:             }
1.41      ng       3974: 	}
                   3975:     }
                   3976:     &csvuploadmap_footer($request,$i,$keyfields);
1.72      ng       3977: 
1.41      ng       3978:     return '';
1.27      albertel 3979: }
                   3980: 
1.246     albertel 3981: sub csvuploadoptions {
1.608     www      3982:     my ($request,$symb)= @_;
1.257     albertel 3983:     my $checked=(($env{'form.noFirstLine'})?'1':'0');
1.246     albertel 3984:     my $ignore=&mt('Ignore First Line');
                   3985:     $request->print(<<ENDPICK);
                   3986: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="gradesupload">
1.398     albertel 3987: <h3><span class="LC_info">Uploading Class Grade Options</span></h3>
1.246     albertel 3988: <input type="hidden" name="command"    value="csvuploadassign" />
1.302     albertel 3989: <!--
1.246     albertel 3990: <p>
                   3991: <label>
                   3992:    <input type="checkbox" name="show_full_results" />
                   3993:    Show a table of all changes
                   3994: </label>
                   3995: </p>
1.302     albertel 3996: -->
1.246     albertel 3997: <p>
                   3998: <label>
                   3999:    <input type="checkbox" name="overwite_scores" checked="checked" />
                   4000:    Overwrite any existing score
                   4001: </label>
                   4002: </p>
                   4003: ENDPICK
                   4004:     my %fields=&get_fields();
                   4005:     if (!defined($fields{'domain'})) {
1.257     albertel 4006: 	my $domform = &Apache::loncommon::select_dom_form($env{'request.role.domain'},'default_domain');
1.246     albertel 4007: 	$request->print("\n<p> Users are in domain: ".$domform."</p>\n");
                   4008:     }
1.257     albertel 4009:     foreach my $key (sort(keys(%env))) {
1.246     albertel 4010: 	if ($key !~ /^form\.(.*)$/) { next; }
                   4011: 	my $cleankey=$1;
                   4012: 	if ($cleankey eq 'command') { next; }
                   4013: 	$request->print('<input type="hidden" name="'.$cleankey.
1.257     albertel 4014: 			'"  value="'.$env{$key}.'" />'."\n");
1.246     albertel 4015:     }
                   4016:     # FIXME do a check for any duplicated user ids...
                   4017:     # FIXME do a check for any invalid user ids?...
1.290     albertel 4018:     $request->print('<input type="submit" value="Assign Grades" /><br />
                   4019: <hr /></form>'."\n");
1.246     albertel 4020:     return '';
                   4021: }
                   4022: 
                   4023: sub get_fields {
                   4024:     my %fields;
1.257     albertel 4025:     my @keyfields = split(/\,/,$env{'form.keyfields'});
                   4026:     for (my $i=0; $i<=$env{'form.nfields'}; $i++) {
                   4027: 	if ($env{'form.upfile_associate'} eq 'reverse') {
                   4028: 	    if ($env{'form.f'.$i} ne 'none') {
                   4029: 		$fields{$keyfields[$i]}=$env{'form.f'.$i};
1.41      ng       4030: 	    }
                   4031: 	} else {
1.257     albertel 4032: 	    if ($env{'form.f'.$i} ne 'none') {
                   4033: 		$fields{$env{'form.f'.$i}}=$keyfields[$i];
1.41      ng       4034: 	    }
                   4035: 	}
1.27      albertel 4036:     }
1.246     albertel 4037:     return %fields;
                   4038: }
                   4039: 
                   4040: sub csvuploadassign {
1.608     www      4041:     my ($request,$symb)= @_;
1.246     albertel 4042:     if (!$symb) {return '';}
1.345     bowersj2 4043:     my $error_msg = '';
1.246     albertel 4044:     &Apache::loncommon::load_tmp_file($request);
                   4045:     my @gradedata = &Apache::loncommon::upfile_record_sep();
1.257     albertel 4046:     if ($env{'form.noFirstLine'}) { shift(@gradedata); }
1.246     albertel 4047:     my %fields=&get_fields();
1.41      ng       4048:     $request->print('<h3>Assigning Grades</h3>');
1.257     albertel 4049:     my $courseid=$env{'request.course.id'};
1.97      albertel 4050:     my ($classlist) = &getclasslist('all',0);
1.106     albertel 4051:     my @notallowed;
1.41      ng       4052:     my @skipped;
                   4053:     my $countdone=0;
                   4054:     foreach my $grade (@gradedata) {
                   4055: 	my %entries=&Apache::loncommon::record_sep($grade);
1.246     albertel 4056: 	my $domain;
                   4057: 	if ($entries{$fields{'domain'}}) {
                   4058: 	    $domain=$entries{$fields{'domain'}};
                   4059: 	} else {
1.257     albertel 4060: 	    $domain=$env{'form.default_domain'};
1.246     albertel 4061: 	}
1.243     albertel 4062: 	$domain=~s/\s//g;
1.41      ng       4063: 	my $username=$entries{$fields{'username'}};
1.160     albertel 4064: 	$username=~s/\s//g;
1.243     albertel 4065: 	if (!$username) {
                   4066: 	    my $id=$entries{$fields{'ID'}};
1.247     albertel 4067: 	    $id=~s/\s//g;
1.243     albertel 4068: 	    my %ids=&Apache::lonnet::idget($domain,$id);
                   4069: 	    $username=$ids{$id};
                   4070: 	}
1.41      ng       4071: 	if (!exists($$classlist{"$username:$domain"})) {
1.247     albertel 4072: 	    my $id=$entries{$fields{'ID'}};
                   4073: 	    $id=~s/\s//g;
                   4074: 	    if ($id) {
                   4075: 		push(@skipped,"$id:$domain");
                   4076: 	    } else {
                   4077: 		push(@skipped,"$username:$domain");
                   4078: 	    }
1.41      ng       4079: 	    next;
                   4080: 	}
1.108     albertel 4081: 	my $usec=$classlist->{"$username:$domain"}[5];
1.106     albertel 4082: 	if (!&canmodify($usec)) {
                   4083: 	    push(@notallowed,"$username:$domain");
                   4084: 	    next;
                   4085: 	}
1.244     albertel 4086: 	my %points;
1.41      ng       4087: 	my %grades;
                   4088: 	foreach my $dest (keys(%fields)) {
1.244     albertel 4089: 	    if ($dest eq 'ID' || $dest eq 'username' ||
                   4090: 		$dest eq 'domain') { next; }
                   4091: 	    if ($entries{$fields{$dest}} =~ /^\s*$/) { next; }
                   4092: 	    if ($dest=~/stores_(.*)_points/) {
                   4093: 		my $part=$1;
                   4094: 		my $wgt =&Apache::lonnet::EXT('resource.'.$part.'.weight',
                   4095: 					      $symb,$domain,$username);
1.345     bowersj2 4096:                 if ($wgt) {
                   4097:                     $entries{$fields{$dest}}=~s/\s//g;
                   4098:                     my $pcr=$entries{$fields{$dest}} / $wgt;
1.463     albertel 4099:                     my $award=($pcr == 0) ? 'incorrect_by_override'
                   4100:                                           : 'correct_by_override';
1.345     bowersj2 4101:                     $grades{"resource.$part.awarded"}=$pcr;
                   4102:                     $grades{"resource.$part.solved"}=$award;
                   4103:                     $points{$part}=1;
                   4104:                 } else {
                   4105:                     $error_msg = "<br />" .
                   4106:                         &mt("Some point values were assigned"
                   4107:                             ." for problems with a weight "
                   4108:                             ."of zero. These values were "
                   4109:                             ."ignored.");
                   4110:                 }
1.244     albertel 4111: 	    } else {
                   4112: 		if ($dest=~/stores_(.*)_awarded/) { if ($points{$1}) {next;} }
                   4113: 		if ($dest=~/stores_(.*)_solved/)  { if ($points{$1}) {next;} }
                   4114: 		my $store_key=$dest;
                   4115: 		$store_key=~s/^stores/resource/;
                   4116: 		$store_key=~s/_/\./g;
                   4117: 		$grades{$store_key}=$entries{$fields{$dest}};
                   4118: 	    }
1.41      ng       4119: 	}
1.508     www      4120: 	if (! %grades) { 
                   4121:            push(@skipped,&mt("[_1]: no data to save","$username:$domain")); 
                   4122:         } else {
                   4123: 	   $grades{"resource.regrader"}="$env{'user.name'}:$env{'user.domain'}";
                   4124: 	   my $result=&Apache::lonnet::cstore(\%grades,$symb,
1.302     albertel 4125: 					   $env{'request.course.id'},
                   4126: 					   $domain,$username);
1.508     www      4127: 	   if ($result eq 'ok') {
                   4128: 	      $request->print('.');
                   4129: 	   } else {
                   4130: 	      $request->print("<p><span class=\"LC_error\">".
                   4131:                               &mt("Failed to save data for student [_1]. Message when trying to save was: [_2]",
                   4132:                                   "$username:$domain",$result)."</span></p>");
                   4133: 	   }
                   4134: 	   $request->rflush();
                   4135: 	   $countdone++;
                   4136:         }
1.41      ng       4137:     }
1.570     www      4138:     $request->print('<br />'.&Apache::lonhtmlcommon::confirm_success(&mt("Saved scores for [quant,_1,student]",$countdone),$countdone==0));
1.41      ng       4139:     if (@skipped) {
1.571     www      4140: 	$request->print('<br />'.&Apache::lonhtmlcommon::confirm_success(&mt('No scores stored for the following username(s):'),1).'<br />');
                   4141:         $request->print(join(', ',@skipped));
1.106     albertel 4142:     }
                   4143:     if (@notallowed) {
1.571     www      4144: 	$request->print('<br />'.&Apache::lonhtmlcommon::confirm_success(&mt('Modification of scores not allowed for the following username(s):'),1).'<br />');
                   4145: 	$request->print(join(', ',@notallowed));
1.41      ng       4146:     }
1.106     albertel 4147:     $request->print("<br />\n");
1.345     bowersj2 4148:     return $error_msg;
1.26      albertel 4149: }
1.44      ng       4150: #------------- end of section for handling csv file upload ---------
                   4151: #
                   4152: #-------------------------------------------------------------------
                   4153: #
1.122     ng       4154: #-------------- Next few routines handle grading by page/sequence
1.72      ng       4155: #
                   4156: #--- Select a page/sequence and a student to grade
1.68      ng       4157: sub pickStudentPage {
1.608     www      4158:     my ($request,$symb) = @_;
1.68      ng       4159: 
1.539     riegler  4160:     my $alertmsg = &mt('Please select the student you wish to grade.');
1.597     wenzelju 4161:     $request->print(&Apache::lonhtmlcommon::scripttag(<<LISTJAVASCRIPT));
1.68      ng       4162: 
                   4163: function checkPickOne(formname) {
1.76      ng       4164:     if (radioSelection(formname.student) == null) {
1.539     riegler  4165: 	alert("$alertmsg");
1.68      ng       4166: 	return;
                   4167:     }
1.125     ng       4168:     ptr = pullDownSelection(formname.selectpage);
                   4169:     formname.page.value = formname["page"+ptr].value;
                   4170:     formname.title.value = formname["title"+ptr].value;
1.68      ng       4171:     formname.submit();
                   4172: }
                   4173: 
                   4174: LISTJAVASCRIPT
1.118     ng       4175:     &commonJSfunctions($request);
1.608     www      4176: 
1.257     albertel 4177:     my $cdom      = $env{"course.$env{'request.course.id'}.domain"};
                   4178:     my $cnum      = $env{"course.$env{'request.course.id'}.num"};
                   4179:     my $getsec    = $env{'form.section'} eq '' ? 'all' : $env{'form.section'};
1.68      ng       4180: 
1.398     albertel 4181:     my $result='<h3><span class="LC_info">&nbsp;'.
1.485     albertel 4182: 	&mt('Manual Grading by Page or Sequence').'</span></h3>';
1.68      ng       4183: 
1.80      ng       4184:     $result.='<form action="/adm/grades" method="post" name="displayPage">'."\n";
1.582     raeburn  4185:     my $map_error;
                   4186:     my ($titles,$symbx) = &getSymbMap($map_error);
                   4187:     if ($map_error) {
                   4188:         $request->print(&navmap_errormsg());
                   4189:         return; 
                   4190:     }
1.137     albertel 4191:     my ($curpage) =&Apache::lonnet::decode_symb($symb); 
                   4192: #    my ($curpage,$mapId) =&Apache::lonnet::decode_symb($symb); 
                   4193: #    my $type=($curpage =~ /\.(page|sequence)/);
1.485     albertel 4194:     my $select = '<select name="selectpage">'."\n";
1.70      ng       4195:     my $ctr=0;
1.68      ng       4196:     foreach (@$titles) {
                   4197: 	my ($minder,$showtitle) = ($_ =~ /(\d+)\.(.*)/);
1.485     albertel 4198: 	$select.='<option value="'.$ctr.'" '.
1.401     albertel 4199: 	    ($$symbx{$_} =~ /$curpage$/ ? 'selected="selected"' : '').
1.71      ng       4200: 	    '>'.$showtitle.'</option>'."\n";
1.70      ng       4201: 	$ctr++;
1.68      ng       4202:     }
1.485     albertel 4203:     $select.= '</select>';
1.539     riegler  4204:     $result.='&nbsp;<b>'.&mt('Problems from').':</b> '.$select."<br />\n";
1.485     albertel 4205: 
1.70      ng       4206:     $ctr=0;
                   4207:     foreach (@$titles) {
                   4208: 	my ($minder,$showtitle) = ($_ =~ /(\d+)\.(.*)/);
                   4209: 	$result.='<input type="hidden" name="page'.$ctr.'" value="'.$$symbx{$_}.'" />'."\n";
                   4210: 	$result.='<input type="hidden" name="title'.$ctr.'" value="'.$showtitle.'" />'."\n";
                   4211: 	$ctr++;
                   4212:     }
1.72      ng       4213:     $result.='<input type="hidden" name="page" />'."\n".
                   4214: 	'<input type="hidden" name="title" />'."\n";
1.68      ng       4215: 
1.485     albertel 4216:     my $options =
                   4217: 	'<label><input type="radio" name="vProb" value="no" checked="checked" /> '.&mt('no').' </label>'."\n".
                   4218: 	'<label><input type="radio" name="vProb" value="yes" /> '.&mt('yes').' </label>'."<br />\n";
1.539     riegler  4219:     $result.='&nbsp;<b>'.&mt('View Problem Text').': </b>'.$options;
1.485     albertel 4220: 
                   4221:     $options =
                   4222: 	'<label><input type="radio" name="lastSub" value="none" /> '.&mt('none').' </label>'."\n".
                   4223: 	'<label><input type="radio" name="lastSub" value="datesub" checked="checked" /> '.&mt('by dates and submissions').'</label>'."\n".
                   4224: 	'<label><input type="radio" name="lastSub" value="all" /> '.&mt('all details').' </label>'."\n";
1.539     riegler  4225:     $result.='&nbsp;<b>'.&mt('Submissions').': </b>'.$options;
1.432     banghart 4226:     
                   4227:     $result.=&build_section_inputs();
1.442     banghart 4228:     my $stu_status = join(':',&Apache::loncommon::get_env_multiple('form.Status'));
                   4229:     $result.='<input type="hidden" name="Status"  value="'.$stu_status.'" />'."\n".
1.72      ng       4230: 	'<input type="hidden" name="command" value="displayPage" />'."\n".
1.613     www      4231: 	'<input type="hidden" name="symb"    value="'.&Apache::lonenc::check_encrypt($symb).'" />'."<br />\n";
1.72      ng       4232: 
1.539     riegler  4233:     $result.='&nbsp;<b>'.&mt('Use CODE').': </b> <input type="text" name="CODE" value="" /> <br />'."\n";
1.382     albertel 4234: 
1.80      ng       4235:     $result.='&nbsp;<input type="button" '.
1.589     bisitz   4236:              'onclick="javascript:checkPickOne(this.form);" value="'.&mt('Next').' &rarr;" /><br />'."\n";
1.72      ng       4237: 
1.68      ng       4238:     $request->print($result);
                   4239: 
1.485     albertel 4240:     my $studentTable.='&nbsp;<b>'.&mt('Select a student you wish to grade and then click on the Next button.').'</b><br />'.
1.484     albertel 4241: 	&Apache::loncommon::start_data_table().
                   4242: 	&Apache::loncommon::start_data_table_header_row().
1.485     albertel 4243: 	'<th align="right">&nbsp;'.&mt('No.').'</th>'.
1.484     albertel 4244: 	'<th>'.&nameUserString('header').'</th>'.
1.485     albertel 4245: 	'<th align="right">&nbsp;'.&mt('No.').'</th>'.
1.484     albertel 4246: 	'<th>'.&nameUserString('header').'</th>'.
                   4247: 	&Apache::loncommon::end_data_table_header_row();
1.68      ng       4248:  
1.76      ng       4249:     my (undef,undef,$fullname) = &getclasslist($getsec,'1');
1.68      ng       4250:     my $ptr = 1;
1.294     albertel 4251:     foreach my $student (sort 
                   4252: 			 {
                   4253: 			     if (lc($$fullname{$a}) ne lc($$fullname{$b})) {
                   4254: 				 return (lc($$fullname{$a}) cmp lc($$fullname{$b}));
                   4255: 			     }
                   4256: 			     return $a cmp $b;
                   4257: 			 } (keys(%$fullname))) {
1.68      ng       4258: 	my ($uname,$udom) = split(/:/,$student);
1.484     albertel 4259: 	$studentTable.=($ptr%2==1 ? &Apache::loncommon::start_data_table_row()
                   4260:                                   : '</td>');
1.126     ng       4261: 	$studentTable.='<td align="right">'.$ptr.'&nbsp;</td>';
1.288     albertel 4262: 	$studentTable.='<td>&nbsp;<label><input type="radio" name="student" value="'.$student.'" /> '
                   4263: 	    .&nameUserString(undef,$$fullname{$student},$uname,$udom)."</label>\n";
1.484     albertel 4264: 	$studentTable.=
                   4265: 	    ($ptr%2 == 0 ? '</td>'.&Apache::loncommon::end_data_table_row() 
                   4266:                          : '');
1.68      ng       4267: 	$ptr++;
                   4268:     }
1.484     albertel 4269:     if ($ptr%2 == 0) {
                   4270: 	$studentTable.='</td><td>&nbsp;</td><td>&nbsp;</td>'.
                   4271: 	    &Apache::loncommon::end_data_table_row();
                   4272:     }
                   4273:     $studentTable.=&Apache::loncommon::end_data_table()."\n";
1.126     ng       4274:     $studentTable.='<input type="button" '.
1.589     bisitz   4275:                    'onclick="javascript:checkPickOne(this.form);" value="'.&mt('Next').' &rarr;" /></form>'."\n";
1.68      ng       4276: 
                   4277:     $request->print($studentTable);
                   4278: 
                   4279:     return '';
                   4280: }
                   4281: 
                   4282: sub getSymbMap {
1.582     raeburn  4283:     my ($map_error) = @_;
1.132     bowersj2 4284:     my $navmap = Apache::lonnavmaps::navmap->new();
1.582     raeburn  4285:     unless (ref($navmap)) {
                   4286:         if (ref($map_error)) {
                   4287:             $$map_error = 'navmap';
                   4288:         }
                   4289:         return;
                   4290:     }
1.68      ng       4291:     my %symbx = ();
                   4292:     my @titles = ();
1.117     bowersj2 4293:     my $minder = 0;
                   4294: 
                   4295:     # Gather every sequence that has problems.
1.240     albertel 4296:     my @sequences = $navmap->retrieveResources(undef, sub { shift->is_map(); },
                   4297: 					       1,0,1);
1.117     bowersj2 4298:     for my $sequence ($navmap->getById('0.0'), @sequences) {
1.241     albertel 4299: 	if ($navmap->hasResource($sequence, sub { shift->is_problem(); }, 0) ) {
1.381     albertel 4300: 	    my $title = $minder.'.'.
                   4301: 		&HTML::Entities::encode($sequence->compTitle(),'"\'&');
                   4302: 	    push(@titles, $title); # minder in case two titles are identical
                   4303: 	    $symbx{$title} = &HTML::Entities::encode($sequence->symb(),'"\'&');
1.117     bowersj2 4304: 	    $minder++;
1.241     albertel 4305: 	}
1.68      ng       4306:     }
                   4307:     return \@titles,\%symbx;
                   4308: }
                   4309: 
1.72      ng       4310: #
                   4311: #--- Displays a page/sequence w/wo problems, w/wo submissions
1.68      ng       4312: sub displayPage {
1.608     www      4313:     my ($request,$symb) = @_;
1.257     albertel 4314:     my $cdom      = $env{"course.$env{'request.course.id'}.domain"};
                   4315:     my $cnum      = $env{"course.$env{'request.course.id'}.num"};
                   4316:     my $getsec    = $env{'form.section'} eq '' ? 'all' : $env{'form.section'};
                   4317:     my $pageTitle = $env{'form.page'};
1.103     albertel 4318:     my ($classlist,undef,$fullname) = &getclasslist($getsec,'1');
1.257     albertel 4319:     my ($uname,$udom) = split(/:/,$env{'form.student'});
                   4320:     my $usec=$classlist->{$env{'form.student'}}[5];
1.168     albertel 4321: 
                   4322:     #need to make sure we have the correct data for later EXT calls, 
                   4323:     #thus invalidate the cache
                   4324:     &Apache::lonnet::devalidatecourseresdata(
1.257     albertel 4325:                  $env{'course.'.$env{'request.course.id'}.'.num'},
                   4326:                  $env{'course.'.$env{'request.course.id'}.'.domain'});
1.168     albertel 4327:     &Apache::lonnet::clear_EXT_cache_status();
                   4328: 
1.103     albertel 4329:     if (!&canview($usec)) {
1.485     albertel 4330: 	$request->print('<span class="LC_warning">'.&mt('Unable to view requested student. ([_1])',$env{'form.student'}).'</span>');
1.103     albertel 4331: 	return;
                   4332:     }
1.398     albertel 4333:     my $result='<h3><span class="LC_info">&nbsp;'.$env{'form.title'}.'</span></h3>';
1.485     albertel 4334:     $result.='<h3>&nbsp;'.&mt('Student: [_1]',&nameUserString(undef,$$fullname{$env{'form.student'}},$uname,$udom)).
1.129     ng       4335: 	'</h3>'."\n";
1.500     albertel 4336:     $env{'form.CODE'} = uc($env{'form.CODE'});
1.501     foxr     4337:     if (&Apache::lonnet::validCODE(uc($env{'form.CODE'}))) {
1.485     albertel 4338: 	$result.='<h3>&nbsp;'.&mt('CODE: [_1]',$env{'form.CODE'}).'</h3>'."\n";
1.382     albertel 4339:     } else {
                   4340: 	delete($env{'form.CODE'});
                   4341:     }
1.71      ng       4342:     &sub_page_js($request);
                   4343:     $request->print($result);
                   4344: 
1.132     bowersj2 4345:     my $navmap = Apache::lonnavmaps::navmap->new();
1.582     raeburn  4346:     unless (ref($navmap)) {
                   4347:         $request->print(&navmap_errormsg());
                   4348:         return;
                   4349:     }
1.257     albertel 4350:     my ($mapUrl, $id, $resUrl)=&Apache::lonnet::decode_symb($env{'form.page'});
1.68      ng       4351:     my $map = $navmap->getResourceByUrl($resUrl); # add to navmaps
1.288     albertel 4352:     if (!$map) {
1.485     albertel 4353: 	$request->print('<span class="LC_warning">'.&mt('Unable to view requested sequence. ([_1])',$resUrl).'</span>');
1.288     albertel 4354: 	return; 
                   4355:     }
1.68      ng       4356:     my $iterator = $navmap->getIterator($map->map_start(),
                   4357: 					$map->map_finish());
                   4358: 
1.71      ng       4359:     my $studentTable='<form action="/adm/grades" method="post" name="gradePage">'."\n".
1.72      ng       4360: 	'<input type="hidden" name="command" value="gradeByPage" />'."\n".
1.257     albertel 4361: 	'<input type="hidden" name="fullname" value="'.$$fullname{$env{'form.student'}}.'" />'."\n".
                   4362: 	'<input type="hidden" name="student" value="'.$env{'form.student'}.'" />'."\n".
1.72      ng       4363: 	'<input type="hidden" name="page"    value="'.$pageTitle.'" />'."\n".
1.257     albertel 4364: 	'<input type="hidden" name="title"   value="'.$env{'form.title'}.'" />'."\n".
1.418     albertel 4365: 	'<input type="hidden" name="symb"    value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
1.613     www      4366: 	'<input type="hidden" name="overRideScore" value="no" />'."\n";
1.71      ng       4367: 
1.382     albertel 4368:     if (defined($env{'form.CODE'})) {
                   4369: 	$studentTable.=
                   4370: 	    '<input type="hidden" name="CODE" value="'.$env{'form.CODE'}.'" />'."\n";
                   4371:     }
1.381     albertel 4372:     my $checkIcon = '<img alt="'.&mt('Check Mark').
1.485     albertel 4373: 	'" src="'.&Apache::loncommon::lonhttpdurl($request->dir_config('lonIconsURL').'/check.gif').'" height="16" border="0" />';
1.71      ng       4374: 
1.594     bisitz   4375:     $studentTable.='&nbsp;<span class="LC_info">'.
                   4376:         &mt('Problems graded correct by the computer are marked with a [_1] symbol.',$checkIcon).
                   4377:         '</span>'."\n".
1.484     albertel 4378: 	&Apache::loncommon::start_data_table().
                   4379: 	&Apache::loncommon::start_data_table_header_row().
                   4380: 	'<th align="center">&nbsp;Prob.&nbsp;</th>'.
1.485     albertel 4381: 	'<th>&nbsp;'.($env{'form.vProb'} eq 'no' ? &mt('Title') : &mt('Problem Text')).'/'.&mt('Grade').'</th>'.
1.484     albertel 4382: 	&Apache::loncommon::end_data_table_header_row();
1.71      ng       4383: 
1.329     albertel 4384:     &Apache::lonxml::clear_problem_counter();
1.196     albertel 4385:     my ($depth,$question,$prob) = (1,1,1);
1.68      ng       4386:     $iterator->next(); # skip the first BEGIN_MAP
                   4387:     my $curRes = $iterator->next(); # for "current resource"
1.101     albertel 4388:     while ($depth > 0) {
1.68      ng       4389:         if($curRes == $iterator->BEGIN_MAP) { $depth++; }
1.100     bowersj2 4390:         if($curRes == $iterator->END_MAP) { $depth--; }
1.68      ng       4391: 
1.385     albertel 4392:         if (ref($curRes) && $curRes->is_problem()) {
1.91      albertel 4393: 	    my $parts = $curRes->parts();
1.68      ng       4394:             my $title = $curRes->compTitle();
1.71      ng       4395: 	    my $symbx = $curRes->symb();
1.484     albertel 4396: 	    $studentTable.=
                   4397: 		&Apache::loncommon::start_data_table_row().
                   4398: 		'<td align="center" valign="top" >'.$prob.
1.485     albertel 4399: 		(scalar(@{$parts}) == 1 ? '' 
                   4400: 		                        : '<br />('.&mt('[_1]&nbsp;parts)',
                   4401: 							scalar(@{$parts}))
                   4402: 		 ).
                   4403: 		 '</td>';
1.71      ng       4404: 	    $studentTable.='<td valign="top">';
1.382     albertel 4405: 	    my %form = ('CODE' => $env{'form.CODE'},);
1.257     albertel 4406: 	    if ($env{'form.vProb'} eq 'yes' ) {
1.144     albertel 4407: 		$studentTable.=&show_problem($request,$symbx,$uname,$udom,1,
1.383     albertel 4408: 					     undef,'both',\%form);
1.71      ng       4409: 	    } else {
1.382     albertel 4410: 		my $companswer = &Apache::loncommon::get_student_answers($symbx,$uname,$udom,$env{'request.course.id'},%form);
1.80      ng       4411: 		$companswer =~ s|<form(.*?)>||g;
                   4412: 		$companswer =~ s|</form>||g;
1.71      ng       4413: #		while ($companswer =~ /(<a href\=\"javascript:newWindow.*?Script Vars<\/a>)/s) { #<a href="javascript:newWindow</a>
1.116     ng       4414: #		    $companswer =~ s/$1/ /ms;
1.326     albertel 4415: #		    $request->print('match='.$1."<br />\n");
1.71      ng       4416: #		}
1.116     ng       4417: #		$companswer =~ s|<table border=\"1\">|<table border=\"0\">|g;
1.539     riegler  4418: 		$studentTable.='&nbsp;<b>'.$title.'</b>&nbsp;<br />&nbsp;<b>'.&mt('Correct answer').':</b><br />'.$companswer;
1.71      ng       4419: 	    }
                   4420: 
1.257     albertel 4421: 	    my %record = &Apache::lonnet::restore($symbx,$env{'request.course.id'},$udom,$uname);
1.125     ng       4422: 
1.257     albertel 4423: 	    if ($env{'form.lastSub'} eq 'datesub') {
1.71      ng       4424: 		if ($record{'version'} eq '') {
1.485     albertel 4425: 		    $studentTable.='<br />&nbsp;<span class="LC_warning">'.&mt('No recorded submission for this problem.').'</span><br />';
1.71      ng       4426: 		} else {
1.116     ng       4427: 		    my %responseType = ();
                   4428: 		    foreach my $partid (@{$parts}) {
1.147     albertel 4429: 			my @responseIds =$curRes->responseIds($partid);
                   4430: 			my @responseType =$curRes->responseType($partid);
                   4431: 			my %responseIds;
                   4432: 			for (my $i=0;$i<=$#responseIds;$i++) {
                   4433: 			    $responseIds{$responseIds[$i]}=$responseType[$i];
                   4434: 			}
                   4435: 			$responseType{$partid} = \%responseIds;
1.116     ng       4436: 		    }
1.148     albertel 4437: 		    $studentTable.= &displaySubByDates($symbx,\%record,$parts,\%responseType,$checkIcon,$uname,$udom);
1.147     albertel 4438: 
1.71      ng       4439: 		}
1.257     albertel 4440: 	    } elsif ($env{'form.lastSub'} eq 'all') {
                   4441: 		my $last = ($env{'form.lastSub'} eq 'last' ? 'last' : '');
1.71      ng       4442: 		$studentTable.=&Apache::loncommon::get_previous_attempt($symbx,$uname,$udom,
1.257     albertel 4443: 									$env{'request.course.id'},
1.71      ng       4444: 									'','.submission');
                   4445:  
                   4446: 	    }
1.103     albertel 4447: 	    if (&canmodify($usec)) {
1.585     bisitz   4448:             $studentTable.=&gradeBox_start();
1.103     albertel 4449: 		foreach my $partid (@{$parts}) {
                   4450: 		    $studentTable.=&gradeBox($request,$symbx,$uname,$udom,$question,$partid,\%record);
                   4451: 		    $studentTable.='<input type="hidden" name="q_'.$question.'" value="'.$partid.'" />'."\n";
                   4452: 		    $question++;
                   4453: 		}
1.585     bisitz   4454:             $studentTable.=&gradeBox_end();
1.196     albertel 4455: 		$prob++;
1.71      ng       4456: 	    }
                   4457: 	    $studentTable.='</td></tr>';
1.68      ng       4458: 
1.103     albertel 4459: 	}
1.68      ng       4460:         $curRes = $iterator->next();
                   4461:     }
                   4462: 
1.589     bisitz   4463:     $studentTable.=
                   4464:         '</table>'."\n".
                   4465:         '<input type="button" value="'.&mt('Save').'" '.
                   4466:         'onclick="javascript:checkSubmitPage(this.form,'.$question.');" />'.
                   4467:         '</form>'."\n";
1.71      ng       4468:     $request->print($studentTable);
                   4469: 
                   4470:     return '';
1.119     ng       4471: }
                   4472: 
                   4473: sub displaySubByDates {
1.148     albertel 4474:     my ($symb,$record,$parts,$responseType,$checkIcon,$uname,$udom) = @_;
1.224     albertel 4475:     my $isCODE=0;
1.335     albertel 4476:     my $isTask = ($symb =~/\.task$/);
1.224     albertel 4477:     if (exists($record->{'resource.CODE'})) { $isCODE=1; }
1.467     albertel 4478:     my $studentTable=&Apache::loncommon::start_data_table().
                   4479: 	&Apache::loncommon::start_data_table_header_row().
                   4480: 	'<th>'.&mt('Date/Time').'</th>'.
                   4481: 	($isCODE?'<th>'.&mt('CODE').'</th>':'').
                   4482: 	'<th>'.&mt('Submission').'</th>'.
                   4483: 	'<th>'.&mt('Status').'</th>'.
                   4484: 	&Apache::loncommon::end_data_table_header_row();
1.119     ng       4485:     my ($version);
                   4486:     my %mark;
1.148     albertel 4487:     my %orders;
1.119     ng       4488:     $mark{'correct_by_student'} = $checkIcon;
1.147     albertel 4489:     if (!exists($$record{'1:timestamp'})) {
1.539     riegler  4490: 	return '<br />&nbsp;<span class="LC_warning">'.&mt('Nothing submitted - no attempts.').'</span><br />';
1.147     albertel 4491:     }
1.335     albertel 4492: 
                   4493:     my $interaction;
1.525     raeburn  4494:     my $no_increment = 1;
1.119     ng       4495:     for ($version=1;$version<=$$record{'version'};$version++) {
1.467     albertel 4496: 	my $timestamp = 
                   4497: 	    &Apache::lonlocal::locallocaltime($$record{$version.':timestamp'});
1.335     albertel 4498: 	if (exists($$record{$version.':resource.0.version'})) {
                   4499: 	    $interaction = $$record{$version.':resource.0.version'};
                   4500: 	}
                   4501: 
                   4502: 	my $where = ($isTask ? "$version:resource.$interaction"
                   4503: 		             : "$version:resource");
1.467     albertel 4504: 	$studentTable.=&Apache::loncommon::start_data_table_row().
                   4505: 	    '<td>'.$timestamp.'</td>';
1.224     albertel 4506: 	if ($isCODE) {
                   4507: 	    $studentTable.='<td>'.$record->{$version.':resource.CODE'}.'</td>';
                   4508: 	}
1.119     ng       4509: 	my @versionKeys = split(/\:/,$$record{$version.':keys'});
                   4510: 	my @displaySub = ();
                   4511: 	foreach my $partid (@{$parts}) {
1.596     raeburn  4512:             my $hidden;
                   4513:             if (($$record{$version.':resource.'.$partid.'.type'} eq 'anonsurvey') ||
                   4514:                 ($$record{$version.':resource.'.$partid.'.type'} eq 'anonsurveycred')) {
                   4515:                 $hidden = 1;
                   4516:             }
1.335     albertel 4517: 	    my @matchKey = ($isTask ? sort(grep /^resource\.\d+\.\Q$partid\E\.award$/,@versionKeys)
                   4518: 			            : sort(grep /^resource\.\Q$partid\E\..*?\.submission$/,@versionKeys));
                   4519: 	    
1.122     ng       4520: #	    next if ($$record{"$version:resource.$partid.solved"} eq '');
1.324     albertel 4521: 	    my $display_part=&get_display_part($partid,$symb);
1.147     albertel 4522: 	    foreach my $matchKey (@matchKey) {
1.198     albertel 4523: 		if (exists($$record{$version.':'.$matchKey}) &&
                   4524: 		    $$record{$version.':'.$matchKey} ne '') {
1.596     raeburn  4525:                     
1.335     albertel 4526: 		    my ($responseId)= ($isTask ? ($matchKey=~ /^resource\.(.*?)\.\Q$partid\E\.award$/)
                   4527: 				               : ($matchKey=~ /^resource\.\Q$partid\E\.(.*?)\.submission$/));
1.577     bisitz   4528:                     $displaySub[0].='<span class="LC_nobreak"';
                   4529:                     $displaySub[0].='<b>'.&mt('Part: [_1]',$display_part).'</b>'
                   4530:                                    .' <span class="LC_internal_info">'
                   4531:                                    .'('.&mt('Part ID: [_1]',$responseId).')'
                   4532:                                    .'</span>'
                   4533:                                    .' <b>';
1.596     raeburn  4534:                     if ($hidden) {
                   4535:                         $displaySub[0].= &mt('Anonymous Survey').'</b>';
                   4536:                     } else {
                   4537: 		        if ($$record{"$where.$partid.tries"} eq '') {
                   4538: 			    $displaySub[0].=&mt('Trial not counted');
                   4539: 		        } else {
                   4540: 			    $displaySub[0].=&mt('Trial: [_1]',
1.467     albertel 4541: 					    $$record{"$where.$partid.tries"});
1.596     raeburn  4542: 		        }
                   4543: 		        my $responseType=($isTask ? 'Task'
1.335     albertel 4544:                                               : $responseType->{$partid}->{$responseId});
1.596     raeburn  4545: 		        if (!exists($orders{$partid})) { $orders{$partid}={}; }
                   4546: 		        if (!exists($orders{$partid}->{$responseId})) {
                   4547: 			    $orders{$partid}->{$responseId}=
                   4548: 			        &get_order($partid,$responseId,$symb,$uname,$udom,
                   4549:                                            $no_increment);
                   4550: 		        }
                   4551: 		        $displaySub[0].='</b></span>'; # /nobreak
                   4552: 		        $displaySub[0].='&nbsp; '.
                   4553: 			    &cleanRecord($$record{$version.':'.$matchKey},$responseType,$symb,$partid,$responseId,$record,$orders{$partid}->{$responseId},"$version:",$uname,$udom).'<br />';
                   4554:                     }
1.147     albertel 4555: 		}
                   4556: 	    }
1.335     albertel 4557: 	    if (exists($$record{"$where.$partid.checkedin"})) {
1.485     albertel 4558: 		$displaySub[1].=&mt('Checked in by [_1] into slot [_2]',
                   4559: 				    $$record{"$where.$partid.checkedin"},
                   4560: 				    $$record{"$where.$partid.checkedin.slot"}).
                   4561: 					'<br />';
1.335     albertel 4562: 	    }
                   4563: 	    if (exists $$record{"$where.$partid.award"}) {
1.485     albertel 4564: 		$displaySub[1].='<b>'.&mt('Part:').'</b>&nbsp;'.$display_part.' &nbsp;'.
1.335     albertel 4565: 		    lc($$record{"$where.$partid.award"}).' '.
                   4566: 		    $mark{$$record{"$where.$partid.solved"}}.
1.147     albertel 4567: 		    '<br />';
                   4568: 	    }
1.335     albertel 4569: 	    if (exists $$record{"$where.$partid.regrader"}) {
                   4570: 		$displaySub[2].=$$record{"$where.$partid.regrader"}.
                   4571: 		    ' (<b>'.&mt('Part').':</b> '.$display_part.')';
                   4572: 	    } elsif ($$record{"$version:resource.$partid.regrader"} =~ /\S/) {
                   4573: 		$displaySub[2].=
                   4574: 		    $$record{"$version:resource.$partid.regrader"}.
1.207     albertel 4575: 		    ' (<b>'.&mt('Part').':</b> '.$display_part.')';
1.147     albertel 4576: 	    }
                   4577: 	}
                   4578: 	# needed because old essay regrader has not parts info
                   4579: 	if (exists $$record{"$version:resource.regrader"}) {
                   4580: 	    $displaySub[2].=$$record{"$version:resource.regrader"};
                   4581: 	}
                   4582: 	$studentTable.='<td>'.$displaySub[0].'&nbsp;</td><td>'.$displaySub[1];
                   4583: 	if ($displaySub[2]) {
1.467     albertel 4584: 	    $studentTable.=&mt('Manually graded by [_1]',$displaySub[2]);
1.147     albertel 4585: 	}
1.467     albertel 4586: 	$studentTable.='&nbsp;</td>'.
                   4587: 	    &Apache::loncommon::end_data_table_row();
1.119     ng       4588:     }
1.467     albertel 4589:     $studentTable.=&Apache::loncommon::end_data_table();
1.119     ng       4590:     return $studentTable;
1.71      ng       4591: }
                   4592: 
                   4593: sub updateGradeByPage {
1.608     www      4594:     my ($request,$symb) = @_;
1.71      ng       4595: 
1.257     albertel 4596:     my $cdom      = $env{"course.$env{'request.course.id'}.domain"};
                   4597:     my $cnum      = $env{"course.$env{'request.course.id'}.num"};
                   4598:     my $getsec    = $env{'form.section'} eq '' ? 'all' : $env{'form.section'};
                   4599:     my $pageTitle = $env{'form.page'};
1.103     albertel 4600:     my ($classlist,undef,$fullname) = &getclasslist($getsec,'1');
1.257     albertel 4601:     my ($uname,$udom) = split(/:/,$env{'form.student'});
                   4602:     my $usec=$classlist->{$env{'form.student'}}[5];
1.103     albertel 4603:     if (!&canmodify($usec)) {
1.526     raeburn  4604: 	$request->print('<span class="LC_warning">'.&mt('Unable to modify requested student ([_1])',$env{'form.student'}).'</span>');
1.103     albertel 4605: 	return;
                   4606:     }
1.398     albertel 4607:     my $result='<h3><span class="LC_info">&nbsp;'.$env{'form.title'}.'</span></h3>';
1.526     raeburn  4608:     $result.='<h3>&nbsp;'.&mt('Student: ').&nameUserString(undef,$env{'form.fullname'},$uname,$udom).
1.129     ng       4609: 	'</h3>'."\n";
1.70      ng       4610: 
1.68      ng       4611:     $request->print($result);
                   4612: 
1.582     raeburn  4613: 
1.132     bowersj2 4614:     my $navmap = Apache::lonnavmaps::navmap->new();
1.582     raeburn  4615:     unless (ref($navmap)) {
                   4616:         $request->print(&navmap_errormsg());
                   4617:         return;
                   4618:     }
1.257     albertel 4619:     my ($mapUrl, $id, $resUrl) = &Apache::lonnet::decode_symb( $env{'form.page'});
1.71      ng       4620:     my $map = $navmap->getResourceByUrl($resUrl); # add to navmaps
1.288     albertel 4621:     if (!$map) {
1.527     raeburn  4622: 	$request->print('<span class="LC_warning">'.&mt('Unable to grade requested sequence ([_1]).',$resUrl).'</span>');
1.288     albertel 4623: 	return; 
                   4624:     }
1.71      ng       4625:     my $iterator = $navmap->getIterator($map->map_start(),
                   4626: 					$map->map_finish());
1.70      ng       4627: 
1.484     albertel 4628:     my $studentTable=
                   4629: 	&Apache::loncommon::start_data_table().
                   4630: 	&Apache::loncommon::start_data_table_header_row().
1.485     albertel 4631: 	'<th align="center">&nbsp;'.&mt('Prob.').'&nbsp;</th>'.
                   4632: 	'<th>&nbsp;'.&mt('Title').'&nbsp;</th>'.
                   4633: 	'<th>&nbsp;'.&mt('Previous Score').'&nbsp;</th>'.
                   4634: 	'<th>&nbsp;'.&mt('New Score').'&nbsp;</th>'.
1.484     albertel 4635: 	&Apache::loncommon::end_data_table_header_row();
1.71      ng       4636: 
                   4637:     $iterator->next(); # skip the first BEGIN_MAP
                   4638:     my $curRes = $iterator->next(); # for "current resource"
1.196     albertel 4639:     my ($depth,$question,$prob,$changeflag)= (1,1,1,0);
1.101     albertel 4640:     while ($depth > 0) {
1.71      ng       4641:         if($curRes == $iterator->BEGIN_MAP) { $depth++; }
1.100     bowersj2 4642:         if($curRes == $iterator->END_MAP) { $depth--; }
1.71      ng       4643: 
1.385     albertel 4644:         if (ref($curRes) && $curRes->is_problem()) {
1.91      albertel 4645: 	    my $parts = $curRes->parts();
1.71      ng       4646:             my $title = $curRes->compTitle();
                   4647: 	    my $symbx = $curRes->symb();
1.484     albertel 4648: 	    $studentTable.=
                   4649: 		&Apache::loncommon::start_data_table_row().
                   4650: 		'<td align="center" valign="top" >'.$prob.
1.485     albertel 4651: 		(scalar(@{$parts}) == 1 ? '' 
1.526     raeburn  4652:                                         : '<br />('.&mt('[quant,_1,&nbsp;part]',scalar(@{$parts}))
                   4653: 		.')').'</td>';
1.71      ng       4654: 	    $studentTable.='<td valign="top">&nbsp;<b>'.$title.'</b>&nbsp;</td>';
                   4655: 
                   4656: 	    my %newrecord=();
                   4657: 	    my @displayPts=();
1.269     raeburn  4658:             my %aggregate = ();
                   4659:             my $aggregateflag = 0;
1.71      ng       4660: 	    foreach my $partid (@{$parts}) {
1.257     albertel 4661: 		my $newpts = $env{'form.GD_BOX'.$question.'_'.$partid};
                   4662: 		my $oldpts = $env{'form.oldpts'.$question.'_'.$partid};
1.71      ng       4663: 
1.257     albertel 4664: 		my $wgt = $env{'form.WGT'.$question.'_'.$partid} != 0 ? 
                   4665: 		    $env{'form.WGT'.$question.'_'.$partid} : 1;
1.71      ng       4666: 		my $partial = $newpts/$wgt;
                   4667: 		my $score;
                   4668: 		if ($partial > 0) {
                   4669: 		    $score = 'correct_by_override';
1.125     ng       4670: 		} elsif ($newpts ne '') { #empty is taken as 0
1.71      ng       4671: 		    $score = 'incorrect_by_override';
                   4672: 		}
1.257     albertel 4673: 		my $dropMenu = $env{'form.GD_SEL'.$question.'_'.$partid};
1.125     ng       4674: 		if ($dropMenu eq 'excused') {
1.71      ng       4675: 		    $partial = '';
                   4676: 		    $score = 'excused';
1.125     ng       4677: 		} elsif ($dropMenu eq 'reset status'
1.257     albertel 4678: 			 && $env{'form.solved'.$question.'_'.$partid} ne '') { #update only if previous record exists
1.125     ng       4679: 		    $newrecord{'resource.'.$partid.'.tries'} = 0;
                   4680: 		    $newrecord{'resource.'.$partid.'.solved'} = '';
                   4681: 		    $newrecord{'resource.'.$partid.'.award'} = '';
                   4682: 		    $newrecord{'resource.'.$partid.'.awarded'} = 0;
1.257     albertel 4683: 		    $newrecord{'resource.'.$partid.'.regrader'} = "$env{'user.name'}:$env{'user.domain'}";
1.125     ng       4684: 		    $changeflag++;
                   4685: 		    $newpts = '';
1.269     raeburn  4686:                     
                   4687:                     my $aggtries =  $env{'form.aggtries'.$question.'_'.$partid};
                   4688:                     my $totaltries = $env{'form.totaltries'.$question.'_'.$partid};
                   4689:                     my $solvedstatus = $env{'form.solved'.$question.'_'.$partid};
                   4690:                     if ($aggtries > 0) {
                   4691:                         &decrement_aggs($symbx,$partid,\%aggregate,$aggtries,$totaltries,$solvedstatus);
                   4692:                         $aggregateflag = 1;
                   4693:                     }
1.71      ng       4694: 		}
1.324     albertel 4695: 		my $display_part=&get_display_part($partid,$curRes->symb());
1.257     albertel 4696: 		my $oldstatus = $env{'form.solved'.$question.'_'.$partid};
1.526     raeburn  4697: 		$displayPts[0].='&nbsp;<b>'.&mt('Part').':</b> '.$display_part.' = '.
1.71      ng       4698: 		    (($oldstatus eq 'excused') ? 'excused' : $oldpts).
1.326     albertel 4699: 		    '&nbsp;<br />';
1.526     raeburn  4700: 		$displayPts[1].='&nbsp;<b>'.&mt('Part').':</b> '.$display_part.' = '.
1.125     ng       4701: 		     (($score eq 'excused') ? 'excused' : $newpts).
1.326     albertel 4702: 		    '&nbsp;<br />';
1.71      ng       4703: 		$question++;
1.380     albertel 4704: 		next if ($dropMenu eq 'reset status' || ($newpts eq $oldpts && $score ne 'excused'));
1.125     ng       4705: 
1.71      ng       4706: 		$newrecord{'resource.'.$partid.'.awarded'}  = $partial if $partial ne '';
1.125     ng       4707: 		$newrecord{'resource.'.$partid.'.solved'}   = $score if $score ne '';
1.257     albertel 4708: 		$newrecord{'resource.'.$partid.'.regrader'} = "$env{'user.name'}:$env{'user.domain'}"
1.125     ng       4709: 		    if (scalar(keys(%newrecord)) > 0);
1.71      ng       4710: 
                   4711: 		$changeflag++;
                   4712: 	    }
                   4713: 	    if (scalar(keys(%newrecord)) > 0) {
1.382     albertel 4714: 		my %record = 
                   4715: 		    &Apache::lonnet::restore($symbx,$env{'request.course.id'},
                   4716: 					     $udom,$uname);
                   4717: 
                   4718: 		if (&Apache::lonnet::validCODE($env{'form.CODE'})) {
                   4719: 		    $newrecord{'resource.CODE'} = $env{'form.CODE'};
                   4720: 		} elsif (&Apache::lonnet::validCODE($record{'resource.CODE'})) {
                   4721: 		    $newrecord{'resource.CODE'} = '';
                   4722: 		}
1.257     albertel 4723: 		&Apache::lonnet::cstore(\%newrecord,$symbx,$env{'request.course.id'},
1.71      ng       4724: 					$udom,$uname);
1.382     albertel 4725: 		%record = &Apache::lonnet::restore($symbx,
                   4726: 						   $env{'request.course.id'},
                   4727: 						   $udom,$uname);
1.380     albertel 4728: 		&check_and_remove_from_queue($parts,\%record,undef,$symbx,
                   4729: 					     $cdom,$cnum,$udom,$uname);
1.71      ng       4730: 	    }
1.380     albertel 4731: 	    
1.269     raeburn  4732:             if ($aggregateflag) {
                   4733:                 &Apache::lonnet::cinc('nohist_resourcetracker',\%aggregate,
                   4734:                       $env{'course.'.$env{'request.course.id'}.'.domain'},
                   4735:                       $env{'course.'.$env{'request.course.id'}.'.num'});
                   4736:             }
1.125     ng       4737: 
1.71      ng       4738: 	    $studentTable.='<td valign="top">'.$displayPts[0].'</td>'.
                   4739: 		'<td valign="top">'.$displayPts[1].'</td>'.
1.484     albertel 4740: 		&Apache::loncommon::end_data_table_row();
1.68      ng       4741: 
1.196     albertel 4742: 	    $prob++;
1.68      ng       4743: 	}
1.71      ng       4744:         $curRes = $iterator->next();
1.68      ng       4745:     }
1.98      albertel 4746: 
1.484     albertel 4747:     $studentTable.=&Apache::loncommon::end_data_table();
1.526     raeburn  4748:     my $grademsg=($changeflag == 0 ? &mt('No score was changed or updated.') :
                   4749: 		  &mt('The scores were changed for [quant,_1,problem].',
                   4750: 		  $changeflag));
1.76      ng       4751:     $request->print($grademsg.$studentTable);
1.68      ng       4752: 
1.70      ng       4753:     return '';
                   4754: }
                   4755: 
1.72      ng       4756: #-------- end of section for handling grading by page/sequence ---------
                   4757: #
                   4758: #-------------------------------------------------------------------
                   4759: 
1.581     www      4760: #-------------------- Bubblesheet (Scantron) Grading -------------------
1.75      albertel 4761: #
                   4762: #------ start of section for handling grading by page/sequence ---------
                   4763: 
1.423     albertel 4764: =pod
                   4765: 
                   4766: =head1 Bubble sheet grading routines
                   4767: 
1.424     albertel 4768:   For this documentation:
                   4769: 
                   4770:    'scanline' refers to the full line of characters
                   4771:    from the file that we are parsing that represents one entire sheet
                   4772: 
                   4773:    'bubble line' refers to the data
                   4774:    representing the line of bubbles that are on the physical bubble sheet
                   4775: 
                   4776: 
                   4777: The overall process is that a scanned in bubble sheet data is uploaded
                   4778: into a course. When a user wants to grade, they select a
                   4779: sequence/folder of resources, a file of bubble sheet info, and pick
                   4780: one of the predefined configurations for what each scanline looks
                   4781: like.
                   4782: 
                   4783: Next each scanline is checked for any errors of either 'missing
1.435     foxr     4784: bubbles' (it's an error because it may have been mis-scanned
1.424     albertel 4785: because too light bubbling), 'double bubble' (each bubble line should
                   4786: have no more that one letter picked), invalid or duplicated CODE,
1.556     weissno  4787: invalid student/employee ID
1.424     albertel 4788: 
                   4789: If the CODE option is used that determines the randomization of the
1.556     weissno  4790: homework problems, either way the student/employee ID is looked up into a
1.424     albertel 4791: username:domain.
                   4792: 
                   4793: During the validation phase the instructor can choose to skip scanlines. 
                   4794: 
1.435     foxr     4795: After the validation phase, there are now 3 bubble sheet files
1.424     albertel 4796: 
                   4797:   scantron_original_filename (unmodified original file)
                   4798:   scantron_corrected_filename (file where the corrected information has replaced the original information)
                   4799:   scantron_skipped_filename (contains the exact text of scanlines that where skipped)
                   4800: 
                   4801: Also there is a separate hash nohist_scantrondata that contains extra
                   4802: correction information that isn't representable in the bubble sheet
                   4803: file (see &scantron_getfile() for more information)
                   4804: 
                   4805: After all scanlines are either valid, marked as valid or skipped, then
                   4806: foreach line foreach problem in the picked sequence, an ssi request is
                   4807: made that simulates a user submitting their selected letter(s) against
                   4808: the homework problem.
1.423     albertel 4809: 
                   4810: =over 4
                   4811: 
                   4812: 
                   4813: 
                   4814: =item defaultFormData
                   4815: 
                   4816:   Returns html hidden inputs used to hold context/default values.
                   4817: 
                   4818:  Arguments:
                   4819:   $symb - $symb of the current resource 
                   4820: 
                   4821: =cut
1.422     foxr     4822: 
1.81      albertel 4823: sub defaultFormData {
1.324     albertel 4824:     my ($symb)=@_;
1.613     www      4825:     return '<input type="hidden" name="symb"    value="'.&Apache::lonenc::check_encrypt($symb).'" />';
1.81      albertel 4826: }
                   4827: 
1.447     foxr     4828: 
1.423     albertel 4829: =pod 
                   4830: 
                   4831: =item getSequenceDropDown
                   4832: 
                   4833:    Return html dropdown of possible sequences to grade
                   4834:  
                   4835:  Arguments:
1.582     raeburn  4836:    $symb - $symb of the current resource
                   4837:    $map_error - ref to scalar which will container error if
                   4838:                 $navmap object is unavailable in &getSymbMap().
1.423     albertel 4839: 
                   4840: =cut
1.422     foxr     4841: 
1.75      albertel 4842: sub getSequenceDropDown {
1.582     raeburn  4843:     my ($symb,$map_error)=@_;
1.75      albertel 4844:     my $result='<select name="selectpage">'."\n";
1.582     raeburn  4845:     my ($titles,$symbx) = &getSymbMap($map_error);
                   4846:     if (ref($map_error)) {
                   4847:         return if ($$map_error);
                   4848:     }
1.137     albertel 4849:     my ($curpage)=&Apache::lonnet::decode_symb($symb); 
1.75      albertel 4850:     my $ctr=0;
                   4851:     foreach (@$titles) {
                   4852: 	my ($minder,$showtitle) = ($_ =~ /(\d+)\.(.*)/);
                   4853: 	$result.='<option value="'.$$symbx{$_}.'" '.
1.401     albertel 4854: 	    ($$symbx{$_} =~ /$curpage$/ ? 'selected="selected"' : '').
1.75      albertel 4855: 	    '>'.$showtitle.'</option>'."\n";
                   4856: 	$ctr++;
                   4857:     }
                   4858:     $result.= '</select>';
                   4859:     return $result;
                   4860: }
                   4861: 
1.495     albertel 4862: my %bubble_lines_per_response;     # no. bubble lines for each response.
1.554     raeburn  4863:                                    # key is zero-based index - 0, 1, 2 ...
1.495     albertel 4864: 
                   4865: my %first_bubble_line;             # First bubble line no. for each bubble.
                   4866: 
1.509     raeburn  4867: my %subdivided_bubble_lines;       # no. bubble lines for optionresponse, 
                   4868:                                    # matchresponse or rankresponse, where 
                   4869:                                    # an individual response can have multiple 
                   4870:                                    # lines
1.503     raeburn  4871: 
                   4872: my %responsetype_per_response;     # responsetype for each response
                   4873: 
1.495     albertel 4874: # Save and restore the bubble lines array to the form env.
                   4875: 
                   4876: 
                   4877: sub save_bubble_lines {
                   4878:     foreach my $line (keys(%bubble_lines_per_response)) {
                   4879: 	$env{"form.scantron.bubblelines.$line"}  = $bubble_lines_per_response{$line};
                   4880: 	$env{"form.scantron.first_bubble_line.$line"} =
                   4881: 	    $first_bubble_line{$line};
1.503     raeburn  4882:         $env{"form.scantron.sub_bubblelines.$line"} = 
                   4883:             $subdivided_bubble_lines{$line};
                   4884:         $env{"form.scantron.responsetype.$line"} =
                   4885:             $responsetype_per_response{$line};
1.495     albertel 4886:     }
                   4887: }
                   4888: 
                   4889: 
                   4890: sub restore_bubble_lines {
                   4891:     my $line = 0;
                   4892:     %bubble_lines_per_response = ();
                   4893:     while ($env{"form.scantron.bubblelines.$line"}) {
                   4894: 	my $value = $env{"form.scantron.bubblelines.$line"};
                   4895: 	$bubble_lines_per_response{$line} = $value;
                   4896: 	$first_bubble_line{$line}  =
                   4897: 	    $env{"form.scantron.first_bubble_line.$line"};
1.503     raeburn  4898:         $subdivided_bubble_lines{$line} =
                   4899:             $env{"form.scantron.sub_bubblelines.$line"};
                   4900:         $responsetype_per_response{$line} =
                   4901:             $env{"form.scantron.responsetype.$line"};
1.495     albertel 4902: 	$line++;
                   4903:     }
                   4904: }
                   4905: 
                   4906: #  Given the parsed scanline, get the response for 
                   4907: #  'answer' number n:
                   4908: 
                   4909: sub get_response_bubbles {
                   4910:     my ($parsed_line, $response)  = @_;
                   4911: 
                   4912:     my $bubble_line = $first_bubble_line{$response-1} +1;
                   4913:     my $bubble_lines= $bubble_lines_per_response{$response-1};
                   4914:     
                   4915:     my $selected = "";
                   4916: 
                   4917:     for (my $bline = 0; $bline < $bubble_lines; $bline++) {
                   4918: 	$selected .= $$parsed_line{"scantron.$bubble_line.answer"}.":";
                   4919: 	$bubble_line++;
                   4920:     }
                   4921:     return $selected;
                   4922: }
1.423     albertel 4923: 
                   4924: =pod 
                   4925: 
                   4926: =item scantron_filenames
                   4927: 
                   4928:    Returns a list of the scantron files in the current course 
                   4929: 
                   4930: =cut
1.422     foxr     4931: 
1.202     albertel 4932: sub scantron_filenames {
1.257     albertel 4933:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
                   4934:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
1.517     raeburn  4935:     my $getpropath = 1;
1.157     albertel 4936:     my @files=&Apache::lonnet::dirlist('userfiles',$cdom,$cname,
1.517     raeburn  4937:                                        $getpropath);
1.202     albertel 4938:     my @possiblenames;
1.201     albertel 4939:     foreach my $filename (sort(@files)) {
1.157     albertel 4940: 	($filename)=split(/&/,$filename);
                   4941: 	if ($filename!~/^scantron_orig_/) { next ; }
                   4942: 	$filename=~s/^scantron_orig_//;
1.202     albertel 4943: 	push(@possiblenames,$filename);
                   4944:     }
                   4945:     return @possiblenames;
                   4946: }
                   4947: 
1.423     albertel 4948: =pod 
                   4949: 
                   4950: =item scantron_uploads
                   4951: 
                   4952:    Returns  html drop-down list of scantron files in current course.
                   4953: 
                   4954:  Arguments:
                   4955:    $file2grade - filename to set as selected in the dropdown
                   4956: 
                   4957: =cut
1.422     foxr     4958: 
1.202     albertel 4959: sub scantron_uploads {
1.209     ng       4960:     my ($file2grade) = @_;
1.202     albertel 4961:     my $result=	'<select name="scantron_selectfile">';
                   4962:     $result.="<option></option>";
                   4963:     foreach my $filename (sort(&scantron_filenames())) {
1.401     albertel 4964: 	$result.="<option".($filename eq $file2grade ? ' selected="selected"':'').">$filename</option>\n";
1.81      albertel 4965:     }
                   4966:     $result.="</select>";
                   4967:     return $result;
                   4968: }
                   4969: 
1.423     albertel 4970: =pod 
                   4971: 
                   4972: =item scantron_scantab
                   4973: 
                   4974:   Returns html drop down of the scantron formats in the scantronformat.tab
                   4975:   file.
                   4976: 
                   4977: =cut
1.422     foxr     4978: 
1.82      albertel 4979: sub scantron_scantab {
                   4980:     my $result='<select name="scantron_format">'."\n";
1.191     albertel 4981:     $result.='<option></option>'."\n";
1.518     raeburn  4982:     my @lines = &get_scantronformat_file();
                   4983:     if (@lines > 0) {
                   4984:         foreach my $line (@lines) {
                   4985:             next if (($line =~ /^\#/) || ($line eq ''));
                   4986: 	    my ($name,$descrip)=split(/:/,$line);
                   4987: 	    $result.='<option value="'.$name.'">'.$descrip.'</option>'."\n";
                   4988:         }
1.82      albertel 4989:     }
                   4990:     $result.='</select>'."\n";
1.518     raeburn  4991:     return $result;
                   4992: }
                   4993: 
                   4994: =pod
                   4995: 
                   4996: =item get_scantronformat_file
                   4997: 
                   4998:   Returns an array containing lines from the scantron format file for
                   4999:   the domain of the course.
                   5000: 
                   5001:   If a url for a custom.tab file is listed in domain's configuration.db, 
                   5002:   lines are from this file.
                   5003: 
                   5004:   Otherwise, if a default.tab has been published in RES space by the 
                   5005:   domainconfig user, lines are from this file.
                   5006: 
                   5007:   Otherwise, fall back to getting lines from the legacy file on the
1.519     raeburn  5008:   local server:  /home/httpd/lonTabs/default_scantronformat.tab    
1.82      albertel 5009: 
1.518     raeburn  5010: =cut
                   5011: 
                   5012: sub get_scantronformat_file {
                   5013:     my $cdom= $env{'course.'.$env{'request.course.id'}.'.domain'};
                   5014:     my %domconfig = &Apache::lonnet::get_dom('configuration',['scantron'],$cdom);
                   5015:     my $gottab = 0;
                   5016:     my @lines;
                   5017:     if (ref($domconfig{'scantron'}) eq 'HASH') {
                   5018:         if ($domconfig{'scantron'}{'scantronformat'} ne '') {
                   5019:             my $formatfile = &Apache::lonnet::getfile($Apache::lonnet::perlvar{'lonDocRoot'}.$domconfig{'scantron'}{'scantronformat'});
                   5020:             if ($formatfile ne '-1') {
                   5021:                 @lines = split("\n",$formatfile,-1);
                   5022:                 $gottab = 1;
                   5023:             }
                   5024:         }
                   5025:     }
                   5026:     if (!$gottab) {
                   5027:         my $confname = $cdom.'-domainconfig';
                   5028:         my $default = $Apache::lonnet::perlvar{'lonDocRoot'}.'/res/'.$cdom.'/'.$confname.'/default.tab';
                   5029:         my $formatfile =  &Apache::lonnet::getfile($default);
                   5030:         if ($formatfile ne '-1') {
                   5031:             @lines = split("\n",$formatfile,-1);
                   5032:             $gottab = 1;
                   5033:         }
                   5034:     }
                   5035:     if (!$gottab) {
1.519     raeburn  5036:         my @domains = &Apache::lonnet::current_machine_domains();
                   5037:         if (grep(/^\Q$cdom\E$/,@domains)) {
                   5038:             my $fh=Apache::File->new($Apache::lonnet::perlvar{'lonTabDir'}.'/scantronformat.tab');
                   5039:             @lines = <$fh>;
                   5040:             close($fh);
                   5041:         } else {
                   5042:             my $fh=Apache::File->new($Apache::lonnet::perlvar{'lonTabDir'}.'/default_scantronformat.tab');
                   5043:             @lines = <$fh>;
                   5044:             close($fh);
                   5045:         }
1.518     raeburn  5046:     }
                   5047:     return @lines;
1.82      albertel 5048: }
                   5049: 
1.423     albertel 5050: =pod 
                   5051: 
                   5052: =item scantron_CODElist
                   5053: 
                   5054:   Returns html drop down of the saved CODE lists from current course,
                   5055:   generated from earlier printings.
                   5056: 
                   5057: =cut
1.422     foxr     5058: 
1.186     albertel 5059: sub scantron_CODElist {
1.257     albertel 5060:     my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   5061:     my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
1.186     albertel 5062:     my @names=&Apache::lonnet::getkeys('CODEs',$cdom,$cnum);
                   5063:     my $namechoice='<option></option>';
1.225     albertel 5064:     foreach my $name (sort {uc($a) cmp uc($b)} @names) {
1.191     albertel 5065: 	if ($name =~ /^error: 2 /) { next; }
1.278     albertel 5066: 	if ($name =~ /^type\0/) { next; }
1.186     albertel 5067: 	$namechoice.='<option value="'.$name.'">'.$name.'</option>';
                   5068:     }
                   5069:     $namechoice='<select name="scantron_CODElist">'.$namechoice.'</select>';
                   5070:     return $namechoice;
                   5071: }
                   5072: 
1.423     albertel 5073: =pod 
                   5074: 
                   5075: =item scantron_CODEunique
                   5076: 
                   5077:   Returns the html for "Each CODE to be used once" radio.
                   5078: 
                   5079: =cut
1.422     foxr     5080: 
1.186     albertel 5081: sub scantron_CODEunique {
1.532     bisitz   5082:     my $result='<span class="LC_nobreak">
1.272     albertel 5083:                  <label><input type="radio" name="scantron_CODEunique"
1.423     albertel 5084:                         value="yes" checked="checked" />'.&mt('Yes').' </label>
1.381     albertel 5085:                 </span>
1.532     bisitz   5086:                 <span class="LC_nobreak">
1.272     albertel 5087:                  <label><input type="radio" name="scantron_CODEunique"
1.423     albertel 5088:                         value="no" />'.&mt('No').' </label>
1.381     albertel 5089:                 </span>';
1.186     albertel 5090:     return $result;
                   5091: }
1.423     albertel 5092: 
                   5093: =pod 
                   5094: 
                   5095: =item scantron_selectphase
                   5096: 
                   5097:   Generates the initial screen to start the bubble sheet process.
                   5098:   Allows for - starting a grading run.
1.424     albertel 5099:              - downloading existing scan data (original, corrected
1.423     albertel 5100:                                                 or skipped info)
                   5101: 
                   5102:              - uploading new scan data
                   5103: 
                   5104:  Arguments:
                   5105:   $r          - The Apache request object
                   5106:   $file2grade - name of the file that contain the scanned data to score
                   5107: 
                   5108: =cut
1.186     albertel 5109: 
1.75      albertel 5110: sub scantron_selectphase {
1.608     www      5111:     my ($r,$file2grade,$symb) = @_;
1.75      albertel 5112:     if (!$symb) {return '';}
1.582     raeburn  5113:     my $map_error;
                   5114:     my $sequence_selector=&getSequenceDropDown($symb,\$map_error);
                   5115:     if ($map_error) {
                   5116:         $r->print('<br />'.&navmap_errormsg().'<br />');
                   5117:         return;
                   5118:     }
1.324     albertel 5119:     my $default_form_data=&defaultFormData($symb);
1.209     ng       5120:     my $file_selector=&scantron_uploads($file2grade);
1.82      albertel 5121:     my $format_selector=&scantron_scantab();
1.186     albertel 5122:     my $CODE_selector=&scantron_CODElist();
                   5123:     my $CODE_unique=&scantron_CODEunique();
1.75      albertel 5124:     my $result;
1.422     foxr     5125: 
1.513     foxr     5126:     $ssi_error = 0;
                   5127: 
1.606     wenzelju 5128:     if (&Apache::lonnet::allowed('usc',$env{'request.role.domain'}) ||
                   5129:         &Apache::lonnet::allowed('usc',$env{'request.course.id'})) {
                   5130: 
                   5131: 	# Chunk of form to prompt for a scantron file upload.
                   5132: 
                   5133:         $r->print('
                   5134:     <br />
                   5135:     '.&Apache::loncommon::start_data_table('LC_scantron_action').'
                   5136:        '.&Apache::loncommon::start_data_table_header_row().'
                   5137:             <th>
                   5138:               &nbsp;'.&mt('Specify a bubblesheet data file to upload.').'
                   5139:             </th>
                   5140:        '.&Apache::loncommon::end_data_table_header_row().'
                   5141:        '.&Apache::loncommon::start_data_table_row().'
                   5142:             <td>
                   5143: ');
1.608     www      5144:     my $default_form_data=&defaultFormData($symb);
1.606     wenzelju 5145:     my $cdom= $env{'course.'.$env{'request.course.id'}.'.domain'};
                   5146:     my $cnum= $env{'course.'.$env{'request.course.id'}.'.num'};
                   5147:     $r->print(&Apache::lonhtmlcommon::scripttag('
                   5148:     function checkUpload(formname) {
                   5149: 	if (formname.upfile.value == "") {
                   5150: 	    alert("'.&mt('Please use the browse button to select a file from your local directory.').'");
                   5151: 	    return false;
                   5152: 	}
                   5153: 	formname.submit();
                   5154:     }'));
                   5155:     $r->print('
                   5156:               <form enctype="multipart/form-data" action="/adm/grades" name="rules" method="post">
                   5157:                 '.$default_form_data.'
                   5158:                 <input name="courseid" type="hidden" value="'.$cnum.'" />
                   5159:                 <input name="domainid" type="hidden" value="'.$cdom.'" />
                   5160:                 <input name="command" value="scantronupload_save" type="hidden" />
                   5161:                 '.&mt('File to upload: [_1]','<input type="file" name="upfile" size="50" />').'
                   5162:                 <br />
                   5163:                 <input type="button" onclick="javascript:checkUpload(this.form);" value="'.&mt('Upload Bubblesheet Data').'" />
                   5164:               </form>
                   5165: ');
                   5166: 
                   5167:         $r->print('
                   5168:             </td>
                   5169:        '.&Apache::loncommon::end_data_table_row().'
                   5170:        '.&Apache::loncommon::end_data_table().'
                   5171: ');
                   5172:     }
                   5173: 
1.422     foxr     5174:     # Chunk of form to prompt for a file to grade and how:
                   5175: 
1.489     albertel 5176:     $result.= '
                   5177:     <br />
                   5178:     <form method="post" enctype="multipart/form-data" action="/adm/grades" name="scantron_process">
                   5179:     <input type="hidden" name="command" value="scantron_warning" />
                   5180:     '.$default_form_data.'
                   5181:     '.&Apache::loncommon::start_data_table('LC_scantron_action').'
                   5182:        '.&Apache::loncommon::start_data_table_header_row().'
                   5183:             <th colspan="2">
1.492     albertel 5184:               &nbsp;'.&mt('Specify file and which Folder/Sequence to grade').'
1.489     albertel 5185:             </th>
                   5186:        '.&Apache::loncommon::end_data_table_header_row().'
                   5187:        '.&Apache::loncommon::start_data_table_row().'
1.492     albertel 5188:             <td> '.&mt('Sequence to grade:').' </td><td> '.$sequence_selector.' </td>
1.489     albertel 5189:        '.&Apache::loncommon::end_data_table_row().'
                   5190:        '.&Apache::loncommon::start_data_table_row().'
1.572     www      5191:             <td> '.&mt('Filename of bubblesheet data file:').' </td><td> '.$file_selector.' </td>
1.489     albertel 5192:        '.&Apache::loncommon::end_data_table_row().'
                   5193:        '.&Apache::loncommon::start_data_table_row().'
1.572     www      5194:             <td> '.&mt('Format of bubblesheet data file:').' </td><td> '.$format_selector.' </td>
1.489     albertel 5195:        '.&Apache::loncommon::end_data_table_row().'
                   5196:        '.&Apache::loncommon::start_data_table_row().'
1.492     albertel 5197:             <td> '.&mt('Saved CODEs to validate against:').' </td><td> '.$CODE_selector.' </td>
1.489     albertel 5198:        '.&Apache::loncommon::end_data_table_row().'
                   5199:        '.&Apache::loncommon::start_data_table_row().'
1.492     albertel 5200:             <td> '.&mt('Each CODE is only to be used once:').'</td><td> '.$CODE_unique.' </td>
1.489     albertel 5201:        '.&Apache::loncommon::end_data_table_row().'
                   5202:        '.&Apache::loncommon::start_data_table_row().'
1.492     albertel 5203: 	    <td> '.&mt('Options:').' </td>
1.187     albertel 5204:             <td>
1.492     albertel 5205: 	       <label><input type="checkbox" name="scantron_options_redo" value="redo_skipped"/> '.&mt('Do only previously skipped records').'</label> <br />
                   5206:                <label><input type="checkbox" name="scantron_options_ignore" value="ignore_corrections"/> '.&mt('Remove all existing corrections').'</label> <br />
                   5207:                <label><input type="checkbox" name="scantron_options_hidden" value="ignore_hidden"/> '.&mt('Skip hidden resources when grading').'</label>
1.187     albertel 5208: 	    </td>
1.489     albertel 5209:        '.&Apache::loncommon::end_data_table_row().'
                   5210:        '.&Apache::loncommon::start_data_table_row().'
1.174     albertel 5211:             <td colspan="2">
1.572     www      5212:               <input type="submit" value="'.&mt('Grading: Validate Bubblesheet Records').'" />
1.162     albertel 5213:             </td>
1.489     albertel 5214:        '.&Apache::loncommon::end_data_table_row().'
                   5215:     '.&Apache::loncommon::end_data_table().'
                   5216:     </form>
                   5217: ';
1.162     albertel 5218:    
                   5219:     $r->print($result);
                   5220: 
1.422     foxr     5221: 
                   5222: 
                   5223:     # Chunk of the form that prompts to view a scoring office file,
                   5224:     # corrected file, skipped records in a file.
                   5225: 
1.489     albertel 5226:     $r->print('
                   5227:    <br />
                   5228:    <form action="/adm/grades" name="scantron_download">
                   5229:      '.$default_form_data.'
                   5230:      <input type="hidden" name="command" value="scantron_download" />
                   5231:      '.&Apache::loncommon::start_data_table('LC_scantron_action').'
                   5232:        '.&Apache::loncommon::start_data_table_header_row().'
                   5233:               <th>
1.492     albertel 5234:                 &nbsp;'.&mt('Download a scoring office file').'
1.489     albertel 5235:               </th>
                   5236:        '.&Apache::loncommon::end_data_table_header_row().'
                   5237:        '.&Apache::loncommon::start_data_table_row().'
1.492     albertel 5238:               <td> '.&mt('Filename of scoring office file: [_1]',$file_selector).' 
1.489     albertel 5239:                 <br />
1.492     albertel 5240:                 <input type="submit" value="'.&mt('Download: Show List of Associated Files').'" />
1.489     albertel 5241:        '.&Apache::loncommon::end_data_table_row().'
                   5242:      '.&Apache::loncommon::end_data_table().'
                   5243:    </form>
                   5244:    <br />
                   5245: ');
1.162     albertel 5246: 
1.457     banghart 5247:     &Apache::lonpickcode::code_list($r,2);
1.523     raeburn  5248: 
1.528     raeburn  5249:     $r->print('<br /><form method="post" name="checkscantron">'.
1.523     raeburn  5250:              $default_form_data."\n".
                   5251:              &Apache::loncommon::start_data_table('LC_scantron_action')."\n".
                   5252:              &Apache::loncommon::start_data_table_header_row()."\n".
                   5253:              '<th colspan="2">
1.572     www      5254:               &nbsp;'.&mt('Review bubblesheet data and submissions for a previously graded folder/sequence')."\n".
1.523     raeburn  5255:              '</th>'."\n".
                   5256:               &Apache::loncommon::end_data_table_header_row()."\n".
                   5257:               &Apache::loncommon::start_data_table_row()."\n".
                   5258:               '<td> '.&mt('Graded folder/sequence:').' </td>'."\n".
                   5259:               '<td> '.$sequence_selector.' </td>'.
                   5260:               &Apache::loncommon::end_data_table_row()."\n".
                   5261:               &Apache::loncommon::start_data_table_row()."\n".
                   5262:               '<td> '.&mt('Filename of scoring office file:').' </td>'."\n".
                   5263:               '<td> '.$file_selector.' </td>'."\n".
                   5264:               &Apache::loncommon::end_data_table_row()."\n".
                   5265:               &Apache::loncommon::start_data_table_row()."\n".
                   5266:               '<td> '.&mt('Format of data file:').' </td>'."\n".
                   5267:               '<td> '.$format_selector.' </td>'."\n".
                   5268:               &Apache::loncommon::end_data_table_row()."\n".
                   5269:               &Apache::loncommon::start_data_table_row()."\n".
1.557     raeburn  5270:               '<td> '.&mt('Options').' </td>'."\n".
                   5271:               '<td> <label><input type="checkbox" name="scantron_options_hidden" value="ignore_hidden"/> '.&mt('Skip hidden resources').'</label></td>'.
                   5272:               &Apache::loncommon::end_data_table_row()."\n".
                   5273:               &Apache::loncommon::start_data_table_row()."\n".
1.523     raeburn  5274:               '<td colspan="2">'."\n".
                   5275:               '<input type="hidden" name="command" value="checksubmissions" />'."\n".
1.575     www      5276:               '<input type="submit" value="'.&mt('Review Bubblesheet Data and Submission Records').'" />'."\n".
1.523     raeburn  5277:               '</td>'."\n".
                   5278:               &Apache::loncommon::end_data_table_row()."\n".
                   5279:               &Apache::loncommon::end_data_table()."\n".
                   5280:               '</form><br />');
                   5281:     return;
1.75      albertel 5282: }
                   5283: 
1.423     albertel 5284: =pod
                   5285: 
                   5286: =item get_scantron_config
                   5287: 
                   5288:    Parse and return the scantron configuration line selected as a
                   5289:    hash of configuration file fields.
                   5290: 
                   5291:  Arguments:
                   5292:     which - the name of the configuration to parse from the file.
                   5293: 
                   5294: 
                   5295:  Returns:
                   5296:             If the named configuration is not in the file, an empty
                   5297:             hash is returned.
                   5298:     a hash with the fields
                   5299:       name         - internal name for the this configuration setup
                   5300:       description  - text to display to operator that describes this config
                   5301:       CODElocation - if 0 or the string 'none'
                   5302:                           - no CODE exists for this config
                   5303:                      if -1 || the string 'letter'
                   5304:                           - a CODE exists for this config and is
                   5305:                             a string of letters
                   5306:                      Unsupported value (but planned for future support)
                   5307:                           if a positive integer
                   5308:                                - The CODE exists as the first n items from
                   5309:                                  the question section of the form
                   5310:                           if the string 'number'
                   5311:                                - The CODE exists for this config and is
                   5312:                                  a string of numbers
                   5313:       CODEstart   - (only matter if a CODE exists) column in the line where
                   5314:                      the CODE starts
                   5315:       CODElength  - length of the CODE
1.573     bisitz   5316:       IDstart     - column where the student/employee ID starts
1.556     weissno  5317:       IDlength    - length of the student/employee ID info
1.423     albertel 5318:       Qstart      - column where the information from the bubbled
                   5319:                     'questions' start
                   5320:       Qlength     - number of columns comprising a single bubble line from
                   5321:                     the sheet. (usually either 1 or 10)
1.424     albertel 5322:       Qon         - either a single character representing the character used
1.423     albertel 5323:                     to signal a bubble was chosen in the positional setup, or
                   5324:                     the string 'letter' if the letter of the chosen bubble is
                   5325:                     in the final, or 'number' if a number representing the
                   5326:                     chosen bubble is in the file (1->A 0->J)
1.424     albertel 5327:       Qoff        - the character used to represent that a bubble was
                   5328:                     left blank
1.423     albertel 5329:       PaperID     - if the scanning process generates a unique number for each
                   5330:                     sheet scanned the column that this ID number starts in
                   5331:       PaperIDlength - number of columns that comprise the unique ID number
                   5332:                       for the sheet of paper
1.424     albertel 5333:       FirstName   - column that the first name starts in
1.423     albertel 5334:       FirstNameLength - number of columns that the first name spans
                   5335:  
                   5336:       LastName    - column that the last name starts in
                   5337:       LastNameLength - number of columns that the last name spans
                   5338: 
                   5339: =cut
1.422     foxr     5340: 
1.82      albertel 5341: sub get_scantron_config {
                   5342:     my ($which) = @_;
1.518     raeburn  5343:     my @lines = &get_scantronformat_file();
1.82      albertel 5344:     my %config;
1.157     albertel 5345:     #FIXME probably should move to XML it has already gotten a bit much now
1.518     raeburn  5346:     foreach my $line (@lines) {
1.82      albertel 5347: 	my ($name,$descrip)=split(/:/,$line);
                   5348: 	if ($name ne $which ) { next; }
                   5349: 	chomp($line);
                   5350: 	my @config=split(/:/,$line);
                   5351: 	$config{'name'}=$config[0];
                   5352: 	$config{'description'}=$config[1];
                   5353: 	$config{'CODElocation'}=$config[2];
                   5354: 	$config{'CODEstart'}=$config[3];
                   5355: 	$config{'CODElength'}=$config[4];
                   5356: 	$config{'IDstart'}=$config[5];
                   5357: 	$config{'IDlength'}=$config[6];
                   5358: 	$config{'Qstart'}=$config[7];
1.497     foxr     5359:  	$config{'Qlength'}=$config[8];
1.82      albertel 5360: 	$config{'Qoff'}=$config[9];
                   5361: 	$config{'Qon'}=$config[10];
1.157     albertel 5362: 	$config{'PaperID'}=$config[11];
                   5363: 	$config{'PaperIDlength'}=$config[12];
                   5364: 	$config{'FirstName'}=$config[13];
                   5365: 	$config{'FirstNamelength'}=$config[14];
                   5366: 	$config{'LastName'}=$config[15];
                   5367: 	$config{'LastNamelength'}=$config[16];
1.82      albertel 5368: 	last;
                   5369:     }
                   5370:     return %config;
                   5371: }
                   5372: 
1.423     albertel 5373: =pod 
                   5374: 
                   5375: =item username_to_idmap
                   5376: 
1.556     weissno  5377:     creates a hash keyed by student/employee ID with values of the corresponding
1.423     albertel 5378:     student username:domain.
                   5379: 
                   5380:   Arguments:
                   5381: 
                   5382:     $classlist - reference to the class list hash. This is a hash
                   5383:                  keyed by student name:domain  whose elements are references
1.424     albertel 5384:                  to arrays containing various chunks of information
1.423     albertel 5385:                  about the student. (See loncoursedata for more info).
                   5386: 
                   5387:   Returns
                   5388:     %idmap - the constructed hash
                   5389: 
                   5390: =cut
                   5391: 
1.82      albertel 5392: sub username_to_idmap {
                   5393:     my ($classlist)= @_;
                   5394:     my %idmap;
                   5395:     foreach my $student (keys(%$classlist)) {
                   5396: 	$idmap{$classlist->{$student}->[&Apache::loncoursedata::CL_ID]}=
                   5397: 	    $student;
                   5398:     }
                   5399:     return %idmap;
                   5400: }
1.423     albertel 5401: 
                   5402: =pod
                   5403: 
1.424     albertel 5404: =item scantron_fixup_scanline
1.423     albertel 5405: 
                   5406:    Process a requested correction to a scanline.
                   5407: 
                   5408:   Arguments:
                   5409:     $scantron_config   - hash from &get_scantron_config()
                   5410:     $scan_data         - hash of correction information 
                   5411:                           (see &scantron_getfile())
                   5412:     $line              - existing scanline
                   5413:     $whichline         - line number of the passed in scanline
                   5414:     $field             - type of change to process 
                   5415:                          (either 
1.573     bisitz   5416:                           'ID'     -> correct the student/employee ID
1.423     albertel 5417:                           'CODE'   -> correct the CODE
                   5418:                           'answer' -> fixup the submitted answers)
                   5419:     
                   5420:    $args               - hash of additional info,
                   5421:                           - 'ID' 
                   5422:                                'newid' -> studentID to use in replacement
1.424     albertel 5423:                                           of existing one
1.423     albertel 5424:                           - 'CODE' 
                   5425:                                'CODE_ignore_dup' - set to true if duplicates
                   5426:                                                    should be ignored.
                   5427: 	                       'CODE' - is new code or 'use_unfound'
1.424     albertel 5428:                                         if the existing unfound code should
1.423     albertel 5429:                                         be used as is
                   5430:                           - 'answer'
                   5431:                                'response' - new answer or 'none' if blank
                   5432:                                'question' - the bubble line to change
1.503     raeburn  5433:                                'questionnum' - the question identifier,
                   5434:                                                may include subquestion. 
1.423     albertel 5435: 
                   5436:   Returns:
                   5437:     $line - the modified scanline
                   5438: 
                   5439:   Side effects: 
                   5440:     $scan_data - may be updated
                   5441: 
                   5442: =cut
                   5443: 
1.82      albertel 5444: 
1.157     albertel 5445: sub scantron_fixup_scanline {
                   5446:     my ($scantron_config,$scan_data,$line,$whichline,$field,$args)=@_;
                   5447:     if ($field eq 'ID') {
                   5448: 	if (length($args->{'newid'}) > $$scantron_config{'IDlength'}) {
1.186     albertel 5449: 	    return ($line,1,'New value too large');
1.157     albertel 5450: 	}
                   5451: 	if (length($args->{'newid'}) < $$scantron_config{'IDlength'}) {
                   5452: 	    $args->{'newid'}=sprintf('%-'.$$scantron_config{'IDlength'}.'s',
                   5453: 				     $args->{'newid'});
                   5454: 	}
                   5455: 	substr($line,$$scantron_config{'IDstart'}-1,
                   5456: 	       $$scantron_config{'IDlength'})=$args->{'newid'};
                   5457: 	if ($args->{'newid'}=~/^\s*$/) {
                   5458: 	    &scan_data($scan_data,"$whichline.user",
                   5459: 		       $args->{'username'}.':'.$args->{'domain'});
                   5460: 	}
1.186     albertel 5461:     } elsif ($field eq 'CODE') {
1.192     albertel 5462: 	if ($args->{'CODE_ignore_dup'}) {
                   5463: 	    &scan_data($scan_data,"$whichline.CODE_ignore_dup",'1');
                   5464: 	}
                   5465: 	&scan_data($scan_data,"$whichline.useCODE",'1');
                   5466: 	if ($args->{'CODE'} ne 'use_unfound') {
1.191     albertel 5467: 	    if (length($args->{'CODE'}) > $$scantron_config{'CODElength'}) {
                   5468: 		return ($line,1,'New CODE value too large');
                   5469: 	    }
                   5470: 	    if (length($args->{'CODE'}) < $$scantron_config{'CODElength'}) {
                   5471: 		$args->{'CODE'}=sprintf('%-'.$$scantron_config{'CODElength'}.'s',$args->{'CODE'});
                   5472: 	    }
                   5473: 	    substr($line,$$scantron_config{'CODEstart'}-1,
                   5474: 		   $$scantron_config{'CODElength'})=$args->{'CODE'};
1.186     albertel 5475: 	}
1.157     albertel 5476:     } elsif ($field eq 'answer') {
1.497     foxr     5477: 	my $length=$scantron_config->{'Qlength'};
1.157     albertel 5478: 	my $off=$scantron_config->{'Qoff'};
                   5479: 	my $on=$scantron_config->{'Qon'};
1.497     foxr     5480: 	my $answer=${off}x$length;
                   5481: 	if ($args->{'response'} eq 'none') {
                   5482: 	    &scan_data($scan_data,
1.503     raeburn  5483: 		       "$whichline.no_bubble.".$args->{'questionnum'},'1');
1.497     foxr     5484: 	} else {
                   5485: 	    if ($on eq 'letter') {
                   5486: 		my @alphabet=('A'..'Z');
                   5487: 		$answer=$alphabet[$args->{'response'}];
                   5488: 	    } elsif ($on eq 'number') {
                   5489: 		$answer=$args->{'response'}+1;
                   5490: 		if ($answer == 10) { $answer = '0'; }
1.274     albertel 5491: 	    } else {
1.497     foxr     5492: 		substr($answer,$args->{'response'},1)=$on;
1.274     albertel 5493: 	    }
1.497     foxr     5494: 	    &scan_data($scan_data,
1.503     raeburn  5495: 		       "$whichline.no_bubble.".$args->{'questionnum'},undef,'1');
1.157     albertel 5496: 	}
1.497     foxr     5497: 	my $where=$length*($args->{'question'}-1)+$scantron_config->{'Qstart'};
                   5498: 	substr($line,$where-1,$length)=$answer;
1.157     albertel 5499:     }
                   5500:     return $line;
                   5501: }
1.423     albertel 5502: 
                   5503: =pod
                   5504: 
                   5505: =item scan_data
                   5506: 
                   5507:     Edit or look up  an item in the scan_data hash.
                   5508: 
                   5509:   Arguments:
                   5510:     $scan_data  - The hash (see scantron_getfile)
                   5511:     $key        - shorthand of the key to edit (actual key is
1.424     albertel 5512:                   scantronfilename_key).
1.423     albertel 5513:     $data        - New value of the hash entry.
                   5514:     $delete      - If true, the entry is removed from the hash.
                   5515: 
                   5516:   Returns:
                   5517:     The new value of the hash table field (undefined if deleted).
                   5518: 
                   5519: =cut
                   5520: 
                   5521: 
1.157     albertel 5522: sub scan_data {
                   5523:     my ($scan_data,$key,$value,$delete)=@_;
1.257     albertel 5524:     my $filename=$env{'form.scantron_selectfile'};
1.157     albertel 5525:     if (defined($value)) {
                   5526: 	$scan_data->{$filename.'_'.$key} = $value;
                   5527:     }
                   5528:     if ($delete) { delete($scan_data->{$filename.'_'.$key}); }
                   5529:     return $scan_data->{$filename.'_'.$key};
                   5530: }
1.423     albertel 5531: 
1.495     albertel 5532: # ----- These first few routines are general use routines.----
                   5533: 
                   5534: # Return the number of occurences of a pattern in a string.
                   5535: 
                   5536: sub occurence_count {
                   5537:     my ($string, $pattern) = @_;
                   5538: 
                   5539:     my @matches = ($string =~ /$pattern/g);
                   5540: 
                   5541:     return scalar(@matches);
                   5542: }
                   5543: 
                   5544: 
                   5545: # Take a string known to have digits and convert all the
                   5546: # digits into letters in the range J,A..I.
                   5547: 
                   5548: sub digits_to_letters {
                   5549:     my ($input) = @_;
                   5550: 
                   5551:     my @alphabet = ('J', 'A'..'I');
                   5552: 
                   5553:     my @input    = split(//, $input);
                   5554:     my $output ='';
                   5555:     for (my $i = 0; $i < scalar(@input); $i++) {
                   5556: 	if ($input[$i] =~ /\d/) {
                   5557: 	    $output .= $alphabet[$input[$i]];
                   5558: 	} else {
                   5559: 	    $output .= $input[$i];
                   5560: 	}
                   5561:     }
                   5562:     return $output;
                   5563: }
                   5564: 
1.423     albertel 5565: =pod 
                   5566: 
                   5567: =item scantron_parse_scanline
                   5568: 
                   5569:   Decodes a scanline from the selected scantron file
                   5570: 
                   5571:  Arguments:
                   5572:     line             - The text of the scantron file line to process
                   5573:     whichline        - Line number
                   5574:     scantron_config  - Hash describing the format of the scantron lines.
                   5575:     scan_data        - Hash of extra information about the scanline
                   5576:                        (see scantron_getfile for more information)
                   5577:     just_header      - True if should not process question answers but only
                   5578:                        the stuff to the left of the answers.
                   5579:  Returns:
                   5580:    Hash containing the result of parsing the scanline
                   5581: 
                   5582:    Keys are all proceeded by the string 'scantron.'
                   5583: 
                   5584:        CODE    - the CODE in use for this scanline
                   5585:        useCODE - 1 if the CODE is invalid but it usage has been forced
                   5586:                  by the operator
                   5587:        CODE_ignore_dup - 1 if the CODE is a duplicated use when unique
                   5588:                             CODEs were selected, but the usage has been
                   5589:                             forced by the operator
1.556     weissno  5590:        ID  - student/employee ID
1.423     albertel 5591:        PaperID - if used, the ID number printed on the sheet when the 
                   5592:                  paper was scanned
                   5593:        FirstName - first name from the sheet
                   5594:        LastName  - last name from the sheet
                   5595: 
                   5596:      if just_header was not true these key may also exist
                   5597: 
1.447     foxr     5598:        missingerror - a list of bubble ranges that are considered to be answers
                   5599:                       to a single question that don't have any bubbles filled in.
                   5600:                       Of the form questionnumber:firstbubblenumber:count.
                   5601:        doubleerror  - a list of bubble ranges that are considered to be answers
                   5602:                       to a single question that have more than one bubble filled in.
                   5603:                       Of the form questionnumber::firstbubblenumber:count
                   5604:    
                   5605:                 In the above, count is the number of bubble responses in the
                   5606:                 input line needed to represent the possible answers to the question.
                   5607:                 e.g. a radioresponse with 15 choices in an answer sheet with 10 choices
                   5608:                 per line would have count = 2.
                   5609: 
1.423     albertel 5610:        maxquest     - the number of the last bubble line that was parsed
                   5611: 
                   5612:        (<number> starts at 1)
                   5613:        <number>.answer - zero or more letters representing the selected
                   5614:                          letters from the scanline for the bubble line 
                   5615:                          <number>.
                   5616:                          if blank there was either no bubble or there where
                   5617:                          multiple bubbles, (consult the keys missingerror and
                   5618:                          doubleerror if this is an error condition)
                   5619: 
                   5620: =cut
                   5621: 
1.82      albertel 5622: sub scantron_parse_scanline {
1.423     albertel 5623:     my ($line,$whichline,$scantron_config,$scan_data,$just_header)=@_;
1.470     foxr     5624: 
1.82      albertel 5625:     my %record;
1.550     raeburn  5626:     my $lastpos = $env{'form.scantron_maxbubble'}*$$scantron_config{'Qlength'};
                   5627:     my $questions=substr($line,$$scantron_config{'Qstart'}-1,$lastpos);  # Answers
1.422     foxr     5628:     my $data=substr($line,0,$$scantron_config{'Qstart'}-1);     # earlier stuff
1.278     albertel 5629:     if (!($$scantron_config{'CODElocation'} eq 0 ||
                   5630: 	  $$scantron_config{'CODElocation'} eq 'none')) {
                   5631: 	if ($$scantron_config{'CODElocation'} < 0 ||
                   5632: 	    $$scantron_config{'CODElocation'} eq 'letter' ||
                   5633: 	    $$scantron_config{'CODElocation'} eq 'number') {
1.191     albertel 5634: 	    $record{'scantron.CODE'}=substr($data,
                   5635: 					    $$scantron_config{'CODEstart'}-1,
1.83      albertel 5636: 					    $$scantron_config{'CODElength'});
1.191     albertel 5637: 	    if (&scan_data($scan_data,"$whichline.useCODE")) {
                   5638: 		$record{'scantron.useCODE'}=1;
                   5639: 	    }
1.192     albertel 5640: 	    if (&scan_data($scan_data,"$whichline.CODE_ignore_dup")) {
                   5641: 		$record{'scantron.CODE_ignore_dup'}=1;
                   5642: 	    }
1.82      albertel 5643: 	} else {
                   5644: 	    #FIXME interpret first N questions
                   5645: 	}
                   5646:     }
1.83      albertel 5647:     $record{'scantron.ID'}=substr($data,$$scantron_config{'IDstart'}-1,
                   5648: 				  $$scantron_config{'IDlength'});
1.157     albertel 5649:     $record{'scantron.PaperID'}=
                   5650: 	substr($data,$$scantron_config{'PaperID'}-1,
                   5651: 	       $$scantron_config{'PaperIDlength'});
                   5652:     $record{'scantron.FirstName'}=
                   5653: 	substr($data,$$scantron_config{'FirstName'}-1,
                   5654: 	       $$scantron_config{'FirstNamelength'});
                   5655:     $record{'scantron.LastName'}=
                   5656: 	substr($data,$$scantron_config{'LastName'}-1,
                   5657: 	       $$scantron_config{'LastNamelength'});
1.423     albertel 5658:     if ($just_header) { return \%record; }
1.194     albertel 5659: 
1.82      albertel 5660:     my @alphabet=('A'..'Z');
                   5661:     my $questnum=0;
1.447     foxr     5662:     my $ansnum  =1;		# Multiple 'answer lines'/question.
                   5663: 
1.470     foxr     5664:     chomp($questions);		# Get rid of any trailing \n.
                   5665:     $questions =~ s/\r$//;      # Get rid of trailing \r too (MAC or Win uploads).
                   5666:     while (length($questions)) {
1.447     foxr     5667: 	my $answers_needed = $bubble_lines_per_response{$questnum};
1.503     raeburn  5668:         my $answer_length  = ($$scantron_config{'Qlength'} * $answers_needed)
                   5669:                              || 1;
                   5670:         $questnum++;
                   5671:         my $quest_id = $questnum;
                   5672:         my $currentquest = substr($questions,0,$answer_length);
                   5673:         $questions       = substr($questions,$answer_length);
                   5674:         if (length($currentquest) < $answer_length) { next; }
                   5675: 
                   5676:         if ($subdivided_bubble_lines{$questnum-1} =~ /,/) {
                   5677:             my $subquestnum = 1;
                   5678:             my $subquestions = $currentquest;
                   5679:             my @subanswers_needed = 
                   5680:                 split(/,/,$subdivided_bubble_lines{$questnum-1});  
                   5681:             foreach my $subans (@subanswers_needed) {
                   5682:                 my $subans_length =
                   5683:                     ($$scantron_config{'Qlength'} * $subans)  || 1;
                   5684:                 my $currsubquest = substr($subquestions,0,$subans_length);
                   5685:                 $subquestions   = substr($subquestions,$subans_length);
                   5686:                 $quest_id = "$questnum.$subquestnum";
                   5687:                 if (($$scantron_config{'Qon'} eq 'letter') ||
                   5688:                     ($$scantron_config{'Qon'} eq 'number')) {
                   5689:                     $ansnum = &scantron_validator_lettnum($ansnum, 
                   5690:                         $questnum,$quest_id,$subans,$currsubquest,$whichline,
                   5691:                         \@alphabet,\%record,$scantron_config,$scan_data);
                   5692:                 } else {
                   5693:                     $ansnum = &scantron_validator_positional($ansnum,
                   5694:                         $questnum,$quest_id,$subans,$currsubquest,$whichline,                        \@alphabet,\%record,$scantron_config,$scan_data);
                   5695:                 }
                   5696:                 $subquestnum ++;
                   5697:             }
                   5698:         } else {
                   5699:             if (($$scantron_config{'Qon'} eq 'letter') ||
                   5700:                 ($$scantron_config{'Qon'} eq 'number')) {
                   5701:                 $ansnum = &scantron_validator_lettnum($ansnum,$questnum,
                   5702:                     $quest_id,$answers_needed,$currentquest,$whichline,
                   5703:                     \@alphabet,\%record,$scantron_config,$scan_data);
                   5704:             } else {
                   5705:                 $ansnum = &scantron_validator_positional($ansnum,$questnum,
                   5706:                     $quest_id,$answers_needed,$currentquest,$whichline,
                   5707:                     \@alphabet,\%record,$scantron_config,$scan_data);
                   5708:             }
                   5709:         }
                   5710:     }
                   5711:     $record{'scantron.maxquest'}=$questnum;
                   5712:     return \%record;
                   5713: }
1.447     foxr     5714: 
1.503     raeburn  5715: sub scantron_validator_lettnum {
                   5716:     my ($ansnum,$questnum,$quest_id,$answers_needed,$currquest,$whichline,
                   5717:         $alphabet,$record,$scantron_config,$scan_data) = @_;
                   5718: 
                   5719:     # Qon 'letter' implies for each slot in currquest we have:
                   5720:     #    ? or * for doubles, a letter in A-Z for a bubble, and
                   5721:     #    about anything else (esp. a value of Qoff) for missing
                   5722:     #    bubbles.
                   5723:     #
                   5724:     # Qon 'number' implies each slot gives a digit that indexes the
                   5725:     #    bubbles filled, or Qoff, or a non-number for unbubbled lines,
                   5726:     #    and * or ? for double bubbles on a single line.
                   5727:     #
1.447     foxr     5728: 
1.503     raeburn  5729:     my $matchon;
                   5730:     if ($$scantron_config{'Qon'} eq 'letter') {
                   5731:         $matchon = '[A-Z]';
                   5732:     } elsif ($$scantron_config{'Qon'} eq 'number') {
                   5733:         $matchon = '\d';
                   5734:     }
                   5735:     my $occurrences = 0;
                   5736:     if (($responsetype_per_response{$questnum-1} eq 'essayresponse') ||
                   5737:         ($responsetype_per_response{$questnum-1} eq 'formularesponse') ||
1.510     raeburn  5738:         ($responsetype_per_response{$questnum-1} eq 'stringresponse') ||
                   5739:         ($responsetype_per_response{$questnum-1} eq 'imageresponse') ||
                   5740:         ($responsetype_per_response{$questnum-1} eq 'reactionresponse') ||
                   5741:         ($responsetype_per_response{$questnum-1} eq 'organicresponse')) {
1.503     raeburn  5742:         my @singlelines = split('',$currquest);
                   5743:         foreach my $entry (@singlelines) {
                   5744:             $occurrences = &occurence_count($entry,$matchon);
                   5745:             if ($occurrences > 1) {
                   5746:                 last;
                   5747:             }
                   5748:         } 
                   5749:     } else {
                   5750:         $occurrences = &occurence_count($currquest,$matchon); 
                   5751:     }
                   5752:     if (($currquest =~ /\?/ || $currquest =~ /\*/) || ($occurrences > 1)) {
                   5753:         push(@{$record->{'scantron.doubleerror'}},$quest_id);
                   5754:         for (my $ans=0; $ans<$answers_needed; $ans++) {
                   5755:             my $bubble = substr($currquest,$ans,1);
                   5756:             if ($bubble =~ /$matchon/ ) {
                   5757:                 if ($$scantron_config{'Qon'} eq 'number') {
                   5758:                     if ($bubble == 0) {
                   5759:                         $bubble = 10; 
                   5760:                     }
                   5761:                     $record->{"scantron.$ansnum.answer"} = 
                   5762:                         $alphabet->[$bubble-1];
                   5763:                 } else {
                   5764:                     $record->{"scantron.$ansnum.answer"} = $bubble;
                   5765:                 }
                   5766:             } else {
                   5767:                 $record->{"scantron.$ansnum.answer"}='';
                   5768:             }
                   5769:             $ansnum++;
                   5770:         }
                   5771:     } elsif (!defined($currquest)
                   5772:             || (&occurence_count($currquest, $$scantron_config{'Qoff'}) == length($currquest))
                   5773:             || (&occurence_count($currquest,$matchon) == 0)) {
                   5774:         for (my $ans=0; $ans<$answers_needed; $ans++ ) {
                   5775:             $record->{"scantron.$ansnum.answer"}='';
                   5776:             $ansnum++;
                   5777:         }
                   5778:         if (!&scan_data($scan_data,"$whichline.no_bubble.$quest_id")) {
                   5779:             push(@{$record->{'scantron.missingerror'}},$quest_id);
                   5780:         }
                   5781:     } else {
                   5782:         if ($$scantron_config{'Qon'} eq 'number') {
                   5783:             $currquest = &digits_to_letters($currquest);            
                   5784:         }
                   5785:         for (my $ans=0; $ans<$answers_needed; $ans++) {
                   5786:             my $bubble = substr($currquest,$ans,1);
                   5787:             $record->{"scantron.$ansnum.answer"} = $bubble;
                   5788:             $ansnum++;
                   5789:         }
                   5790:     }
                   5791:     return $ansnum;
                   5792: }
1.447     foxr     5793: 
1.503     raeburn  5794: sub scantron_validator_positional {
                   5795:     my ($ansnum,$questnum,$quest_id,$answers_needed,$currquest,
                   5796:         $whichline,$alphabet,$record,$scantron_config,$scan_data) = @_;
1.447     foxr     5797: 
1.503     raeburn  5798:     # Otherwise there's a positional notation;
                   5799:     # each bubble line requires Qlength items, and there are filled in
                   5800:     # bubbles for each case where there 'Qon' characters.
                   5801:     #
1.447     foxr     5802: 
1.503     raeburn  5803:     my @array=split($$scantron_config{'Qon'},$currquest,-1);
1.447     foxr     5804: 
1.503     raeburn  5805:     # If the split only gives us one element.. the full length of the
                   5806:     # answer string, no bubbles are filled in:
1.447     foxr     5807: 
1.507     raeburn  5808:     if ($answers_needed eq '') {
                   5809:         return;
                   5810:     }
                   5811: 
1.503     raeburn  5812:     if (length($array[0]) eq $$scantron_config{'Qlength'}*$answers_needed) {
                   5813:         for (my $ans=0; $ans<$answers_needed; $ans++ ) {
                   5814:             $record->{"scantron.$ansnum.answer"}='';
                   5815:             $ansnum++;
                   5816:         }
                   5817:         if (!&scan_data($scan_data,"$whichline.no_bubble.$quest_id")) {
                   5818:             push(@{$record->{"scantron.missingerror"}},$quest_id);
                   5819:         }
                   5820:     } elsif (scalar(@array) == 2) {
                   5821:         my $location = length($array[0]);
                   5822:         my $line_num = int($location / $$scantron_config{'Qlength'});
                   5823:         my $bubble   = $alphabet->[$location % $$scantron_config{'Qlength'}];
                   5824:         for (my $ans=0; $ans<$answers_needed; $ans++) {
                   5825:             if ($ans eq $line_num) {
                   5826:                 $record->{"scantron.$ansnum.answer"} = $bubble;
                   5827:             } else {
                   5828:                 $record->{"scantron.$ansnum.answer"} = ' ';
                   5829:             }
                   5830:             $ansnum++;
                   5831:          }
                   5832:     } else {
                   5833:         #  If there's more than one instance of a bubble character
                   5834:         #  That's a double bubble; with positional notation we can
                   5835:         #  record all the bubbles filled in as well as the
                   5836:         #  fact this response consists of multiple bubbles.
                   5837:         #
                   5838:         if (($responsetype_per_response{$questnum-1} eq 'essayresponse') ||
                   5839:             ($responsetype_per_response{$questnum-1} eq 'formularesponse') ||
1.510     raeburn  5840:             ($responsetype_per_response{$questnum-1} eq 'stringresponse') ||
                   5841:             ($responsetype_per_response{$questnum-1} eq 'imageresponse') ||
                   5842:             ($responsetype_per_response{$questnum-1} eq 'reactionresponse') ||
                   5843:             ($responsetype_per_response{$questnum-1} eq 'organicresponse')) {
1.503     raeburn  5844:             my $doubleerror = 0;
                   5845:             while (($currquest >= $$scantron_config{'Qlength'}) && 
                   5846:                    (!$doubleerror)) {
                   5847:                my $currline = substr($currquest,0,$$scantron_config{'Qlength'});
                   5848:                $currquest = substr($currquest,$$scantron_config{'Qlength'});
                   5849:                my @currarray = split($$scantron_config{'Qon'},$currline,-1);
                   5850:                if (length(@currarray) > 2) {
                   5851:                    $doubleerror = 1;
                   5852:                } 
                   5853:             }
                   5854:             if ($doubleerror) {
                   5855:                 push(@{$record->{'scantron.doubleerror'}},$quest_id);
                   5856:             }
                   5857:         } else {
                   5858:             push(@{$record->{'scantron.doubleerror'}},$quest_id);
                   5859:         }
                   5860:         my $item = $ansnum;
                   5861:         for (my $ans=0; $ans<$answers_needed; $ans++) {
                   5862:             $record->{"scantron.$item.answer"} = '';
                   5863:             $item ++;
                   5864:         }
1.447     foxr     5865: 
1.503     raeburn  5866:         my @ans=@array;
                   5867:         my $i=0;
                   5868:         my $increment = 0;
                   5869:         while ($#ans) {
                   5870:             $i+=length($ans[0]) + $increment;
                   5871:             my $line   = int($i/$$scantron_config{'Qlength'} + $ansnum);
                   5872:             my $bubble = $i%$$scantron_config{'Qlength'};
                   5873:             $record->{"scantron.$line.answer"}.=$alphabet->[$bubble];
                   5874:             shift(@ans);
                   5875:             $increment = 1;
                   5876:         }
                   5877:         $ansnum += $answers_needed;
1.82      albertel 5878:     }
1.503     raeburn  5879:     return $ansnum;
1.82      albertel 5880: }
                   5881: 
1.423     albertel 5882: =pod
                   5883: 
                   5884: =item scantron_add_delay
                   5885: 
                   5886:    Adds an error message that occurred during the grading phase to a
                   5887:    queue of messages to be shown after grading pass is complete
                   5888: 
                   5889:  Arguments:
1.424     albertel 5890:    $delayqueue  - arrary ref of hash ref of error messages
1.423     albertel 5891:    $scanline    - the scanline that caused the error
                   5892:    $errormesage - the error message
                   5893:    $errorcode   - a numeric code for the error
                   5894: 
                   5895:  Side Effects:
1.424     albertel 5896:    updates the $delayqueue to have a new hash ref of the error
1.423     albertel 5897: 
                   5898: =cut
                   5899: 
1.82      albertel 5900: sub scantron_add_delay {
1.140     albertel 5901:     my ($delayqueue,$scanline,$errormessage,$errorcode)=@_;
                   5902:     push(@$delayqueue,
                   5903: 	 {'line' => $scanline, 'emsg' => $errormessage,
                   5904: 	  'ecode' => $errorcode }
                   5905: 	 );
1.82      albertel 5906: }
                   5907: 
1.423     albertel 5908: =pod
                   5909: 
                   5910: =item scantron_find_student
                   5911: 
1.424     albertel 5912:    Finds the username for the current scanline
                   5913: 
                   5914:   Arguments:
                   5915:    $scantron_record - hash result from scantron_parse_scanline
                   5916:    $scan_data       - hash of correction information 
                   5917:                       (see &scantron_getfile() form more information)
                   5918:    $idmap           - hash from &username_to_idmap()
                   5919:    $line            - number of current scanline
                   5920:  
                   5921:   Returns:
                   5922:    Either 'username:domain' or undef if unknown
                   5923: 
1.423     albertel 5924: =cut
                   5925: 
1.82      albertel 5926: sub scantron_find_student {
1.157     albertel 5927:     my ($scantron_record,$scan_data,$idmap,$line)=@_;
1.83      albertel 5928:     my $scanID=$$scantron_record{'scantron.ID'};
1.157     albertel 5929:     if ($scanID =~ /^\s*$/) {
                   5930:  	return &scan_data($scan_data,"$line.user");
                   5931:     }
1.83      albertel 5932:     foreach my $id (keys(%$idmap)) {
1.157     albertel 5933:  	if (lc($id) eq lc($scanID)) {
                   5934:  	    return $$idmap{$id};
                   5935:  	}
1.83      albertel 5936:     }
                   5937:     return undef;
                   5938: }
                   5939: 
1.423     albertel 5940: =pod
                   5941: 
                   5942: =item scantron_filter
                   5943: 
1.424     albertel 5944:    Filter sub for lonnavmaps, filters out hidden resources if ignore
                   5945:    hidden resources was selected
                   5946: 
1.423     albertel 5947: =cut
                   5948: 
1.83      albertel 5949: sub scantron_filter {
                   5950:     my ($curres)=@_;
1.331     albertel 5951: 
                   5952:     if (ref($curres) && $curres->is_problem()) {
                   5953: 	# if the user has asked to not have either hidden
                   5954: 	# or 'randomout' controlled resources to be graded
                   5955: 	# don't include them
                   5956: 	if ($env{'form.scantron_options_hidden'} eq 'ignore_hidden'
                   5957: 	    && $curres->randomout) {
                   5958: 	    return 0;
                   5959: 	}
1.83      albertel 5960: 	return 1;
                   5961:     }
                   5962:     return 0;
1.82      albertel 5963: }
                   5964: 
1.423     albertel 5965: =pod
                   5966: 
                   5967: =item scantron_process_corrections
                   5968: 
1.424     albertel 5969:    Gets correction information out of submitted form data and corrects
                   5970:    the scanline
                   5971: 
1.423     albertel 5972: =cut
                   5973: 
1.157     albertel 5974: sub scantron_process_corrections {
                   5975:     my ($r) = @_;
1.257     albertel 5976:     my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
1.157     albertel 5977:     my ($scanlines,$scan_data)=&scantron_getfile();
                   5978:     my $classlist=&Apache::loncoursedata::get_classlist();
1.257     albertel 5979:     my $which=$env{'form.scantron_line'};
1.200     albertel 5980:     my $line=&scantron_get_line($scanlines,$scan_data,$which);
1.157     albertel 5981:     my ($skip,$err,$errmsg);
1.257     albertel 5982:     if ($env{'form.scantron_skip_record'}) {
1.157     albertel 5983: 	$skip=1;
1.257     albertel 5984:     } elsif ($env{'form.scantron_corrections'} =~ /^(duplicate|incorrect)ID$/) {
                   5985: 	my $newstudent=$env{'form.scantron_username'}.':'.
                   5986: 	    $env{'form.scantron_domain'};
1.157     albertel 5987: 	my $newid=$classlist->{$newstudent}->[&Apache::loncoursedata::CL_ID];
                   5988: 	($line,$err,$errmsg)=
                   5989: 	    &scantron_fixup_scanline(\%scantron_config,$scan_data,$line,$which,
                   5990: 				     'ID',{'newid'=>$newid,
1.257     albertel 5991: 				    'username'=>$env{'form.scantron_username'},
                   5992: 				    'domain'=>$env{'form.scantron_domain'}});
                   5993:     } elsif ($env{'form.scantron_corrections'} =~ /^(duplicate|incorrect)CODE$/) {
                   5994: 	my $resolution=$env{'form.scantron_CODE_resolution'};
1.190     albertel 5995: 	my $newCODE;
1.192     albertel 5996: 	my %args;
1.190     albertel 5997: 	if      ($resolution eq 'use_unfound') {
1.191     albertel 5998: 	    $newCODE='use_unfound';
1.190     albertel 5999: 	} elsif ($resolution eq 'use_found') {
1.257     albertel 6000: 	    $newCODE=$env{'form.scantron_CODE_selectedvalue'};
1.190     albertel 6001: 	} elsif ($resolution eq 'use_typed') {
1.257     albertel 6002: 	    $newCODE=$env{'form.scantron_CODE_newvalue'};
1.194     albertel 6003: 	} elsif ($resolution =~ /^use_closest_(\d+)/) {
1.257     albertel 6004: 	    $newCODE=$env{"form.scantron_CODE_closest_$1"};
1.190     albertel 6005: 	}
1.257     albertel 6006: 	if ($env{'form.scantron_corrections'} eq 'duplicateCODE') {
1.192     albertel 6007: 	    $args{'CODE_ignore_dup'}=1;
                   6008: 	}
                   6009: 	$args{'CODE'}=$newCODE;
1.186     albertel 6010: 	($line,$err,$errmsg)=
                   6011: 	    &scantron_fixup_scanline(\%scantron_config,$scan_data,$line,$which,
1.192     albertel 6012: 				     'CODE',\%args);
1.257     albertel 6013:     } elsif ($env{'form.scantron_corrections'} =~ /^(missing|double)bubble$/) {
                   6014: 	foreach my $question (split(',',$env{'form.scantron_questions'})) {
1.157     albertel 6015: 	    ($line,$err,$errmsg)=
                   6016: 		&scantron_fixup_scanline(\%scantron_config,$scan_data,$line,
                   6017: 					 $which,'answer',
                   6018: 					 { 'question'=>$question,
1.503     raeburn  6019: 		      		   'response'=>$env{"form.scantron_correct_Q_$question"},
                   6020:                                    'questionnum'=>$env{"form.scantron_questionnum_Q_$question"}});
1.157     albertel 6021: 	    if ($err) { last; }
                   6022: 	}
                   6023:     }
                   6024:     if ($err) {
1.398     albertel 6025: 	$r->print("<span class=\"LC_warning\">Unable to accept last correction, an error occurred :$errmsg:</span>");
1.157     albertel 6026:     } else {
1.200     albertel 6027: 	&scantron_put_line($scanlines,$scan_data,$which,$line,$skip);
1.157     albertel 6028: 	&scantron_putfile($scanlines,$scan_data);
                   6029:     }
                   6030: }
                   6031: 
1.423     albertel 6032: =pod
                   6033: 
                   6034: =item reset_skipping_status
                   6035: 
1.424     albertel 6036:    Forgets the current set of remember skipped scanlines (and thus
                   6037:    reverts back to considering all lines in the
                   6038:    scantron_skipped_<filename> file)
                   6039: 
1.423     albertel 6040: =cut
                   6041: 
1.200     albertel 6042: sub reset_skipping_status {
                   6043:     my ($scanlines,$scan_data)=&scantron_getfile();
                   6044:     &scan_data($scan_data,'remember_skipping',undef,1);
                   6045:     &scantron_putfile(undef,$scan_data);
                   6046: }
                   6047: 
1.423     albertel 6048: =pod
                   6049: 
                   6050: =item start_skipping
                   6051: 
1.424     albertel 6052:    Marks a scanline to be skipped. 
                   6053: 
1.423     albertel 6054: =cut
                   6055: 
1.376     albertel 6056: sub start_skipping {
1.200     albertel 6057:     my ($scan_data,$i)=@_;
                   6058:     my %remembered=split(':',&scan_data($scan_data,'remember_skipping'));
1.376     albertel 6059:     if ($env{'form.scantron_options_redo'} =~ /^redo_/) {
                   6060: 	$remembered{$i}=2;
                   6061:     } else {
                   6062: 	$remembered{$i}=1;
                   6063:     }
1.200     albertel 6064:     &scan_data($scan_data,'remember_skipping',join(':',%remembered));
                   6065: }
                   6066: 
1.423     albertel 6067: =pod
                   6068: 
                   6069: =item should_be_skipped
                   6070: 
1.424     albertel 6071:    Checks whether a scanline should be skipped.
                   6072: 
1.423     albertel 6073: =cut
                   6074: 
1.200     albertel 6075: sub should_be_skipped {
1.376     albertel 6076:     my ($scanlines,$scan_data,$i)=@_;
1.257     albertel 6077:     if ($env{'form.scantron_options_redo'} !~ /^redo_/) {
1.200     albertel 6078: 	# not redoing old skips
1.376     albertel 6079: 	if ($scanlines->{'skipped'}[$i]) { return 1; }
1.200     albertel 6080: 	return 0;
                   6081:     }
                   6082:     my %remembered=split(':',&scan_data($scan_data,'remember_skipping'));
1.376     albertel 6083: 
                   6084:     if (exists($remembered{$i}) && $remembered{$i} != 2 ) {
                   6085: 	return 0;
                   6086:     }
1.200     albertel 6087:     return 1;
                   6088: }
                   6089: 
1.423     albertel 6090: =pod
                   6091: 
                   6092: =item remember_current_skipped
                   6093: 
1.424     albertel 6094:    Discovers what scanlines are in the scantron_skipped_<filename>
                   6095:    file and remembers them into scan_data for later use.
                   6096: 
1.423     albertel 6097: =cut
                   6098: 
1.200     albertel 6099: sub remember_current_skipped {
                   6100:     my ($scanlines,$scan_data)=&scantron_getfile();
                   6101:     my %to_remember;
                   6102:     for (my $i=0;$i<=$scanlines->{'count'};$i++) {
                   6103: 	if ($scanlines->{'skipped'}[$i]) {
                   6104: 	    $to_remember{$i}=1;
                   6105: 	}
                   6106:     }
1.376     albertel 6107: 
1.200     albertel 6108:     &scan_data($scan_data,'remember_skipping',join(':',%to_remember));
                   6109:     &scantron_putfile(undef,$scan_data);
                   6110: }
                   6111: 
1.423     albertel 6112: =pod
                   6113: 
                   6114: =item check_for_error
                   6115: 
1.424     albertel 6116:     Checks if there was an error when attempting to remove a specific
                   6117:     scantron_.. bubble sheet data file. Prints out an error if
                   6118:     something went wrong.
                   6119: 
1.423     albertel 6120: =cut
                   6121: 
1.200     albertel 6122: sub check_for_error {
                   6123:     my ($r,$result)=@_;
                   6124:     if ($result ne 'ok' && $result ne 'not_found' ) {
1.492     albertel 6125: 	$r->print(&mt("An error occurred ([_1]) when trying to remove the existing corrections.",$result));
1.200     albertel 6126:     }
                   6127: }
1.157     albertel 6128: 
1.423     albertel 6129: =pod
                   6130: 
                   6131: =item scantron_warning_screen
                   6132: 
1.424     albertel 6133:    Interstitial screen to make sure the operator has selected the
                   6134:    correct options before we start the validation phase.
                   6135: 
1.423     albertel 6136: =cut
                   6137: 
1.203     albertel 6138: sub scantron_warning_screen {
                   6139:     my ($button_text)=@_;
1.257     albertel 6140:     my $title=&Apache::lonnet::gettitle($env{'form.selectpage'});
1.284     albertel 6141:     my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
1.373     albertel 6142:     my $CODElist;
1.284     albertel 6143:     if ($scantron_config{'CODElocation'} &&
                   6144: 	$scantron_config{'CODEstart'} &&
                   6145: 	$scantron_config{'CODElength'}) {
                   6146: 	$CODElist=$env{'form.scantron_CODElist'};
1.398     albertel 6147: 	if ($env{'form.scantron_CODElist'} eq '') { $CODElist='<span class="LC_warning">None</span>'; }
1.284     albertel 6148: 	$CODElist=
1.492     albertel 6149: 	    '<tr><td><b>'.&mt('List of CODES to validate against:').'</b></td><td><tt>'.
1.373     albertel 6150: 	    $env{'form.scantron_CODElist'}.'</tt></td></tr>';
1.284     albertel 6151:     }
1.492     albertel 6152:     return ('
1.203     albertel 6153: <p>
1.492     albertel 6154: <span class="LC_warning">
                   6155: '.&mt('Please double check the information below before clicking on \'[_1]\'',&mt($button_text)).'</span>
1.203     albertel 6156: </p>
                   6157: <table>
1.492     albertel 6158: <tr><td><b>'.&mt('Sequence to be Graded:').'</b></td><td>'.$title.'</td></tr>
                   6159: <tr><td><b>'.&mt('Data File that will be used:').'</b></td><td><tt>'.$env{'form.scantron_selectfile'}.'</tt></td></tr>
                   6160: '.$CODElist.'
1.203     albertel 6161: </table>
                   6162: <br />
1.492     albertel 6163: <p> '.&mt('If this information is correct, please click on \'[_1]\'.',&mt($button_text)).'</p>
                   6164: <p> '.&mt('If something is incorrect, please click the \'Grading Menu\' button to start over.').'</p>
1.203     albertel 6165: 
                   6166: <br />
1.492     albertel 6167: ');
1.203     albertel 6168: }
                   6169: 
1.423     albertel 6170: =pod
                   6171: 
                   6172: =item scantron_do_warning
                   6173: 
1.424     albertel 6174:    Check if the operator has picked something for all required
                   6175:    fields. Error out if something is missing.
                   6176: 
1.423     albertel 6177: =cut
                   6178: 
1.203     albertel 6179: sub scantron_do_warning {
1.608     www      6180:     my ($r,$symb)=@_;
1.203     albertel 6181:     if (!$symb) {return '';}
1.324     albertel 6182:     my $default_form_data=&defaultFormData($symb);
1.203     albertel 6183:     $r->print(&scantron_form_start().$default_form_data);
1.257     albertel 6184:     if ( $env{'form.selectpage'} eq '' ||
                   6185: 	 $env{'form.scantron_selectfile'} eq '' ||
                   6186: 	 $env{'form.scantron_format'} eq '' ) {
1.492     albertel 6187: 	$r->print("<p>".&mt('You have forgetten to specify some information. Please go Back and try again.')."</p>");
1.257     albertel 6188: 	if ( $env{'form.selectpage'} eq '') {
1.492     albertel 6189: 	    $r->print('<p><span class="LC_error">'.&mt('You have not selected a Sequence to grade').'</span></p>');
1.237     albertel 6190: 	} 
1.257     albertel 6191: 	if ( $env{'form.scantron_selectfile'} eq '') {
1.492     albertel 6192: 	    $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 6193: 	} 
1.257     albertel 6194: 	if ( $env{'form.scantron_format'} eq '') {
1.492     albertel 6195: 	    $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 6196: 	} 
                   6197:     } else {
1.265     www      6198: 	my $warning=&scantron_warning_screen('Grading: Validate Records');
1.492     albertel 6199: 	$r->print('
                   6200: '.$warning.'
                   6201: <input type="submit" name="submit" value="'.&mt('Grading: Validate Records').'" />
1.203     albertel 6202: <input type="hidden" name="command" value="scantron_validate" />
1.492     albertel 6203: ');
1.237     albertel 6204:     }
1.614     www      6205:     $r->print("</form><br />");
1.203     albertel 6206:     return '';
                   6207: }
                   6208: 
1.423     albertel 6209: =pod
                   6210: 
                   6211: =item scantron_form_start
                   6212: 
1.424     albertel 6213:     html hidden input for remembering all selected grading options
                   6214: 
1.423     albertel 6215: =cut
                   6216: 
1.203     albertel 6217: sub scantron_form_start {
                   6218:     my ($max_bubble)=@_;
                   6219:     my $result= <<SCANTRONFORM;
                   6220: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="scantronupload">
1.257     albertel 6221:   <input type="hidden" name="selectpage" value="$env{'form.selectpage'}" />
                   6222:   <input type="hidden" name="scantron_format" value="$env{'form.scantron_format'}" />
                   6223:   <input type="hidden" name="scantron_selectfile" value="$env{'form.scantron_selectfile'}" />
1.218     albertel 6224:   <input type="hidden" name="scantron_maxbubble" value="$max_bubble" />
1.257     albertel 6225:   <input type="hidden" name="scantron_CODElist" value="$env{'form.scantron_CODElist'}" />
                   6226:   <input type="hidden" name="scantron_CODEunique" value="$env{'form.scantron_CODEunique'}" />
                   6227:   <input type="hidden" name="scantron_options_redo" value="$env{'form.scantron_options_redo'}" />
                   6228:   <input type="hidden" name="scantron_options_ignore" value="$env{'form.scantron_options_ignore'}" />
1.331     albertel 6229:   <input type="hidden" name="scantron_options_hidden" value="$env{'form.scantron_options_hidden'}" />
1.203     albertel 6230: SCANTRONFORM
1.447     foxr     6231: 
                   6232:   my $line = 0;
                   6233:     while (defined($env{"form.scantron.bubblelines.$line"})) {
                   6234:        my $chunk =
                   6235: 	   '<input type="hidden" name="scantron.bubblelines.'.$line.'" value="'.$env{"form.scantron.bubblelines.$line"}.'" />'."\n";
1.448     foxr     6236:        $chunk .=
                   6237: 	   '<input type="hidden" name="scantron.first_bubble_line.'.$line.'" value="'.$env{"form.scantron.first_bubble_line.$line"}.'" />'."\n";
1.503     raeburn  6238:        $chunk .= 
                   6239:            '<input type="hidden" name="scantron.sub_bubblelines.'.$line.'" value="'.$env{"form.scantron.sub_bubblelines.$line"}.'" />'."\n";
1.504     raeburn  6240:        $chunk .=
                   6241:            '<input type="hidden" name="scantron.responsetype.'.$line.'" value="'.$env{"form.scantron.responsetype.$line"}.'" />'."\n";
1.447     foxr     6242:        $result .= $chunk;
                   6243:        $line++;
                   6244:    }
1.203     albertel 6245:     return $result;
                   6246: }
                   6247: 
1.423     albertel 6248: =pod
                   6249: 
                   6250: =item scantron_validate_file
                   6251: 
1.424     albertel 6252:     Dispatch routine for doing validation of a bubble sheet data file.
                   6253: 
                   6254:     Also processes any necessary information resets that need to
                   6255:     occur before validation begins (ignore previous corrections,
                   6256:     restarting the skipped records processing)
                   6257: 
1.423     albertel 6258: =cut
                   6259: 
1.157     albertel 6260: sub scantron_validate_file {
1.608     www      6261:     my ($r,$symb) = @_;
1.157     albertel 6262:     if (!$symb) {return '';}
1.324     albertel 6263:     my $default_form_data=&defaultFormData($symb);
1.200     albertel 6264:     
                   6265:     # do the detection of only doing skipped records first befroe we delete
1.424     albertel 6266:     # them when doing the corrections reset
1.257     albertel 6267:     if ($env{'form.scantron_options_redo'} ne 'redo_skipped_ready') {
1.200     albertel 6268: 	&reset_skipping_status();
                   6269:     }
1.257     albertel 6270:     if ($env{'form.scantron_options_redo'} eq 'redo_skipped') {
1.200     albertel 6271: 	&remember_current_skipped();
1.257     albertel 6272: 	$env{'form.scantron_options_redo'}='redo_skipped_ready';
1.200     albertel 6273:     }
                   6274: 
1.257     albertel 6275:     if ($env{'form.scantron_options_ignore'} eq 'ignore_corrections') {
1.200     albertel 6276: 	&check_for_error($r,&scantron_remove_file('corrected'));
                   6277: 	&check_for_error($r,&scantron_remove_file('skipped'));
                   6278: 	&check_for_error($r,&scantron_remove_scan_data());
1.257     albertel 6279: 	$env{'form.scantron_options_ignore'}='done';
1.192     albertel 6280:     }
1.200     albertel 6281: 
1.257     albertel 6282:     if ($env{'form.scantron_corrections'}) {
1.157     albertel 6283: 	&scantron_process_corrections($r);
                   6284:     }
1.503     raeburn  6285:     $r->print('<p>'.&mt('Gathering necessary information.').'</p>');$r->rflush();
1.157     albertel 6286:     #get the student pick code ready
                   6287:     $r->print(&Apache::loncommon::studentbrowser_javascript());
1.582     raeburn  6288:     my $nav_error;
                   6289:     my $max_bubble=&scantron_get_maxbubble(\$nav_error);
                   6290:     if ($nav_error) {
                   6291:         $r->print(&navmap_errormsg());
                   6292:         return '';
                   6293:     }
1.203     albertel 6294:     my $result=&scantron_form_start($max_bubble).$default_form_data;
1.157     albertel 6295:     $r->print($result);
                   6296:     
1.334     albertel 6297:     my @validate_phases=( 'sequence',
                   6298: 			  'ID',
1.157     albertel 6299: 			  'CODE',
                   6300: 			  'doublebubble',
                   6301: 			  'missingbubbles');
1.257     albertel 6302:     if (!$env{'form.validatepass'}) {
                   6303: 	$env{'form.validatepass'} = 0;
1.157     albertel 6304:     }
1.257     albertel 6305:     my $currentphase=$env{'form.validatepass'};
1.157     albertel 6306: 
1.448     foxr     6307: 
1.157     albertel 6308:     my $stop=0;
                   6309:     while (!$stop && $currentphase < scalar(@validate_phases)) {
1.503     raeburn  6310: 	$r->print(&mt('Validating '.$validate_phases[$currentphase]).'<br />');
1.157     albertel 6311: 	$r->rflush();
                   6312: 	my $which="scantron_validate_".$validate_phases[$currentphase];
                   6313: 	{
                   6314: 	    no strict 'refs';
                   6315: 	    ($stop,$currentphase)=&$which($r,$currentphase);
                   6316: 	}
                   6317:     }
                   6318:     if (!$stop) {
1.203     albertel 6319: 	my $warning=&scantron_warning_screen('Start Grading');
1.542     raeburn  6320: 	$r->print(&mt('Validation process complete.').'<br />'.
                   6321:                   $warning.
                   6322:                   &mt('Perform verification for each student after storage of submissions?').
                   6323:                   '&nbsp;<span class="LC_nobreak"><label>'.
                   6324:                   '<input type="radio" name="verifyrecord" value="1" />'.&mt('Yes').'</label>'.
                   6325:                   ('&nbsp;'x3).'<label>'.
                   6326:                   '<input type="radio" name="verifyrecord" value="0" checked="checked" />'.&mt('No').
                   6327:                   '</label></span><br />'.
                   6328:                   &mt('Grading will take longer if you use verification.').'<br />'.
1.572     www      6329:                   &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  6330:                   '<input type="submit" name="submit" value="'.&mt('Start Grading').'" />'.
                   6331:                   '<input type="hidden" name="command" value="scantron_process" />'."\n");
1.157     albertel 6332:     } else {
                   6333: 	$r->print('<input type="hidden" name="command" value="scantron_validate" />');
                   6334: 	$r->print("<input type='hidden' name='validatepass' value='".$currentphase."' />");
                   6335:     }
                   6336:     if ($stop) {
1.334     albertel 6337: 	if ($validate_phases[$currentphase] eq 'sequence') {
1.539     riegler  6338: 	    $r->print('<input type="submit" name="submit" value="'.&mt('Ignore').' &rarr; " />');
1.492     albertel 6339: 	    $r->print(' '.&mt('this error').' <br />');
1.334     albertel 6340: 
1.492     albertel 6341: 	    $r->print(" <p>".&mt("Or click the 'Grading Menu' button to start over.")."</p>");
1.334     albertel 6342: 	} else {
1.503     raeburn  6343:             if ($validate_phases[$currentphase] eq 'doublebubble' || $validate_phases[$currentphase] eq 'missingbubbles') {
1.539     riegler  6344: 	        $r->print('<input type="button" name="submitbutton" value="'.&mt('Continue').' &rarr;" onclick="javascript:verify_bubble_radio(this.form)" />');
1.503     raeburn  6345:             } else {
1.539     riegler  6346:                 $r->print('<input type="submit" name="submit" value="'.&mt('Continue').' &rarr;" />');
1.503     raeburn  6347:             }
1.492     albertel 6348: 	    $r->print(' '.&mt('using corrected info').' <br />');
                   6349: 	    $r->print("<input type='submit' value='".&mt("Skip")."' name='scantron_skip_record' />");
                   6350: 	    $r->print(" ".&mt("this scanline saving it for later."));
1.334     albertel 6351: 	}
1.157     albertel 6352:     }
1.614     www      6353:     $r->print(" </form><br />");
1.157     albertel 6354:     return '';
                   6355: }
                   6356: 
1.423     albertel 6357: 
                   6358: =pod
                   6359: 
                   6360: =item scantron_remove_file
                   6361: 
1.424     albertel 6362:    Removes the requested bubble sheet data file, makes sure that
                   6363:    scantron_original_<filename> is never removed
                   6364: 
                   6365: 
1.423     albertel 6366: =cut
                   6367: 
1.200     albertel 6368: sub scantron_remove_file {
1.192     albertel 6369:     my ($which)=@_;
1.257     albertel 6370:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   6371:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1.192     albertel 6372:     my $file='scantron_';
1.200     albertel 6373:     if ($which eq 'corrected' || $which eq 'skipped') {
                   6374: 	$file.=$which.'_';
1.192     albertel 6375:     } else {
                   6376: 	return 'refused';
                   6377:     }
1.257     albertel 6378:     $file.=$env{'form.scantron_selectfile'};
1.200     albertel 6379:     return &Apache::lonnet::removeuserfile($cname,$cdom,$file);
                   6380: }
                   6381: 
1.423     albertel 6382: 
                   6383: =pod
                   6384: 
                   6385: =item scantron_remove_scan_data
                   6386: 
1.424     albertel 6387:    Removes all scan_data correction for the requested bubble sheet
                   6388:    data file.  (In the case that both the are doing skipped records we need
                   6389:    to remember the old skipped lines for the time being so that element
                   6390:    persists for a while.)
                   6391: 
1.423     albertel 6392: =cut
                   6393: 
1.200     albertel 6394: sub scantron_remove_scan_data {
1.257     albertel 6395:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   6396:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1.192     albertel 6397:     my @keys=&Apache::lonnet::getkeys('nohist_scantrondata',$cdom,$cname);
                   6398:     my @todelete;
1.257     albertel 6399:     my $filename=$env{'form.scantron_selectfile'};
1.192     albertel 6400:     foreach my $key (@keys) {
                   6401: 	if ($key=~/^\Q$filename\E_/) {
1.257     albertel 6402: 	    if ($env{'form.scantron_options_redo'} eq 'redo_skipped_ready' &&
1.200     albertel 6403: 		$key=~/remember_skipping/) {
                   6404: 		next;
                   6405: 	    }
1.192     albertel 6406: 	    push(@todelete,$key);
                   6407: 	}
                   6408:     }
1.200     albertel 6409:     my $result;
1.192     albertel 6410:     if (@todelete) {
1.491     albertel 6411: 	$result = &Apache::lonnet::del('nohist_scantrondata',
                   6412: 				       \@todelete,$cdom,$cname);
                   6413:     } else {
                   6414: 	$result = 'ok';
1.192     albertel 6415:     }
                   6416:     return $result;
                   6417: }
                   6418: 
1.423     albertel 6419: 
                   6420: =pod
                   6421: 
                   6422: =item scantron_getfile
                   6423: 
1.424     albertel 6424:     Fetches the requested bubble sheet data file (all 3 versions), and
                   6425:     the scan_data hash
                   6426:   
                   6427:   Arguments:
                   6428:     None
                   6429: 
                   6430:   Returns:
                   6431:     2 hash references
                   6432: 
                   6433:      - first one has 
                   6434:          orig      -
                   6435:          corrected -
                   6436:          skipped   -  each of which points to an array ref of the specified
                   6437:                       file broken up into individual lines
                   6438:          count     - number of scanlines
                   6439:  
                   6440:      - second is the scan_data hash possible keys are
1.425     albertel 6441:        ($number refers to scanline numbered $number and thus the key affects
                   6442:         only that scanline
                   6443:         $bubline refers to the specific bubble line element and the aspects
                   6444:         refers to that specific bubble line element)
                   6445: 
                   6446:        $number.user - username:domain to use
                   6447:        $number.CODE_ignore_dup 
                   6448:                     - ignore the duplicate CODE error 
                   6449:        $number.useCODE
                   6450:                     - use the CODE in the scanline as is
                   6451:        $number.no_bubble.$bubline
                   6452:                     - it is valid that there is no bubbled in bubble
                   6453:                       at $number $bubline
                   6454:        remember_skipping
                   6455:                     - a frozen hash containing keys of $number and values
                   6456:                       of either 
                   6457:                         1 - we are on a 'do skipped records pass' and plan
                   6458:                             on processing this line
                   6459:                         2 - we are on a 'do skipped records pass' and this
                   6460:                             scanline has been marked to skip yet again
1.424     albertel 6461: 
1.423     albertel 6462: =cut
                   6463: 
1.157     albertel 6464: sub scantron_getfile {
1.200     albertel 6465:     #FIXME really would prefer a scantron directory
1.257     albertel 6466:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   6467:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1.157     albertel 6468:     my $lines;
                   6469:     $lines=&Apache::lonnet::getfile('/uploaded/'.$cdom.'/'.$cname.'/'.
1.257     albertel 6470: 		       'scantron_orig_'.$env{'form.scantron_selectfile'});
1.157     albertel 6471:     my %scanlines;
                   6472:     $scanlines{'orig'}=[(split("\n",$lines,-1))];
                   6473:     my $temp=$scanlines{'orig'};
                   6474:     $scanlines{'count'}=$#$temp;
                   6475: 
                   6476:     $lines=&Apache::lonnet::getfile('/uploaded/'.$cdom.'/'.$cname.'/'.
1.257     albertel 6477: 		       'scantron_corrected_'.$env{'form.scantron_selectfile'});
1.157     albertel 6478:     if ($lines eq '-1') {
                   6479: 	$scanlines{'corrected'}=[];
                   6480:     } else {
                   6481: 	$scanlines{'corrected'}=[(split("\n",$lines,-1))];
                   6482:     }
                   6483:     $lines=&Apache::lonnet::getfile('/uploaded/'.$cdom.'/'.$cname.'/'.
1.257     albertel 6484: 		       'scantron_skipped_'.$env{'form.scantron_selectfile'});
1.157     albertel 6485:     if ($lines eq '-1') {
                   6486: 	$scanlines{'skipped'}=[];
                   6487:     } else {
                   6488: 	$scanlines{'skipped'}=[(split("\n",$lines,-1))];
                   6489:     }
1.175     albertel 6490:     my @tmp=&Apache::lonnet::dump('nohist_scantrondata',$cdom,$cname);
1.157     albertel 6491:     if ($tmp[0] =~ /^(error:|no_such_host)/) { @tmp=(); }
                   6492:     my %scan_data = @tmp;
                   6493:     return (\%scanlines,\%scan_data);
                   6494: }
                   6495: 
1.423     albertel 6496: =pod
                   6497: 
                   6498: =item lonnet_putfile
                   6499: 
1.424     albertel 6500:    Wrapper routine to call &Apache::lonnet::finishuserfileupload
                   6501: 
                   6502:  Arguments:
                   6503:    $contents - data to store
                   6504:    $filename - filename to store $contents into
                   6505: 
                   6506:  Returns:
                   6507:    result value from &Apache::lonnet::finishuserfileupload
                   6508: 
1.423     albertel 6509: =cut
                   6510: 
1.157     albertel 6511: sub lonnet_putfile {
                   6512:     my ($contents,$filename)=@_;
1.257     albertel 6513:     my $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   6514:     my $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
                   6515:     $env{'form.sillywaytopassafilearound'}=$contents;
1.275     albertel 6516:     &Apache::lonnet::finishuserfileupload($docuname,$docudom,'sillywaytopassafilearound',$filename);
1.157     albertel 6517: 
                   6518: }
                   6519: 
1.423     albertel 6520: =pod
                   6521: 
                   6522: =item scantron_putfile
                   6523: 
1.424     albertel 6524:     Stores the current version of the bubble sheet data files, and the
                   6525:     scan_data hash. (Does not modify the original version only the
                   6526:     corrected and skipped versions.
                   6527: 
                   6528:  Arguments:
                   6529:     $scanlines - hash ref that looks like the first return value from
                   6530:                  &scantron_getfile()
                   6531:     $scan_data - hash ref that looks like the second return value from
                   6532:                  &scantron_getfile()
                   6533: 
1.423     albertel 6534: =cut
                   6535: 
1.157     albertel 6536: sub scantron_putfile {
                   6537:     my ($scanlines,$scan_data) = @_;
1.200     albertel 6538:     #FIXME really would prefer a scantron directory
1.257     albertel 6539:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   6540:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1.200     albertel 6541:     if ($scanlines) {
                   6542: 	my $prefix='scantron_';
1.157     albertel 6543: # no need to update orig, shouldn't change
                   6544: #   &lonnet_putfile(join("\n",@{$scanlines->{'orig'}}),$prefix.'orig_'.
1.257     albertel 6545: #		    $env{'form.scantron_selectfile'});
1.200     albertel 6546: 	&lonnet_putfile(join("\n",@{$scanlines->{'corrected'}}),
                   6547: 			$prefix.'corrected_'.
1.257     albertel 6548: 			$env{'form.scantron_selectfile'});
1.200     albertel 6549: 	&lonnet_putfile(join("\n",@{$scanlines->{'skipped'}}),
                   6550: 			$prefix.'skipped_'.
1.257     albertel 6551: 			$env{'form.scantron_selectfile'});
1.200     albertel 6552:     }
1.175     albertel 6553:     &Apache::lonnet::put('nohist_scantrondata',$scan_data,$cdom,$cname);
1.157     albertel 6554: }
                   6555: 
1.423     albertel 6556: =pod
                   6557: 
                   6558: =item scantron_get_line
                   6559: 
1.424     albertel 6560:    Returns the correct version of the scanline
                   6561: 
                   6562:  Arguments:
                   6563:     $scanlines - hash ref that looks like the first return value from
                   6564:                  &scantron_getfile()
                   6565:     $scan_data - hash ref that looks like the second return value from
                   6566:                  &scantron_getfile()
                   6567:     $i         - number of the requested line (starts at 0)
                   6568: 
                   6569:  Returns:
                   6570:    A scanline, (either the original or the corrected one if it
                   6571:    exists), or undef if the requested scanline should be
                   6572:    skipped. (Either because it's an skipped scanline, or it's an
                   6573:    unskipped scanline and we are not doing a 'do skipped scanlines'
                   6574:    pass.
                   6575: 
1.423     albertel 6576: =cut
                   6577: 
1.157     albertel 6578: sub scantron_get_line {
1.200     albertel 6579:     my ($scanlines,$scan_data,$i)=@_;
1.376     albertel 6580:     if (&should_be_skipped($scanlines,$scan_data,$i)) { return undef; }
                   6581:     #if ($scanlines->{'skipped'}[$i]) { return undef; }
1.157     albertel 6582:     if ($scanlines->{'corrected'}[$i]) {return $scanlines->{'corrected'}[$i];}
                   6583:     return $scanlines->{'orig'}[$i]; 
                   6584: }
                   6585: 
1.423     albertel 6586: =pod
                   6587: 
                   6588: =item scantron_todo_count
                   6589: 
1.424     albertel 6590:     Counts the number of scanlines that need processing.
                   6591: 
                   6592:  Arguments:
                   6593:     $scanlines - hash ref that looks like the first return value from
                   6594:                  &scantron_getfile()
                   6595:     $scan_data - hash ref that looks like the second return value from
                   6596:                  &scantron_getfile()
                   6597: 
                   6598:  Returns:
                   6599:     $count - number of scanlines to process
                   6600: 
1.423     albertel 6601: =cut
                   6602: 
1.200     albertel 6603: sub get_todo_count {
                   6604:     my ($scanlines,$scan_data)=@_;
                   6605:     my $count=0;
                   6606:     for (my $i=0;$i<=$scanlines->{'count'};$i++) {
                   6607: 	my $line=&scantron_get_line($scanlines,$scan_data,$i);
                   6608: 	if ($line=~/^[\s\cz]*$/) { next; }
                   6609: 	$count++;
                   6610:     }
                   6611:     return $count;
                   6612: }
                   6613: 
1.423     albertel 6614: =pod
                   6615: 
                   6616: =item scantron_put_line
                   6617: 
1.424     albertel 6618:     Updates the 'corrected' or 'skipped' versions of the bubble sheet
                   6619:     data file.
                   6620: 
                   6621:  Arguments:
                   6622:     $scanlines - hash ref that looks like the first return value from
                   6623:                  &scantron_getfile()
                   6624:     $scan_data - hash ref that looks like the second return value from
                   6625:                  &scantron_getfile()
                   6626:     $i         - line number to update
                   6627:     $newline   - contents of the updated scanline
                   6628:     $skip      - if true make the line for skipping and update the
                   6629:                  'skipped' file
                   6630: 
1.423     albertel 6631: =cut
                   6632: 
1.157     albertel 6633: sub scantron_put_line {
1.200     albertel 6634:     my ($scanlines,$scan_data,$i,$newline,$skip)=@_;
1.157     albertel 6635:     if ($skip) {
                   6636: 	$scanlines->{'skipped'}[$i]=$newline;
1.376     albertel 6637: 	&start_skipping($scan_data,$i);
1.157     albertel 6638: 	return;
                   6639:     }
                   6640:     $scanlines->{'corrected'}[$i]=$newline;
                   6641: }
                   6642: 
1.423     albertel 6643: =pod
                   6644: 
                   6645: =item scantron_clear_skip
                   6646: 
1.424     albertel 6647:    Remove a line from the 'skipped' file
                   6648: 
                   6649:  Arguments:
                   6650:     $scanlines - hash ref that looks like the first return value from
                   6651:                  &scantron_getfile()
                   6652:     $scan_data - hash ref that looks like the second return value from
                   6653:                  &scantron_getfile()
                   6654:     $i         - line number to update
                   6655: 
1.423     albertel 6656: =cut
                   6657: 
1.376     albertel 6658: sub scantron_clear_skip {
                   6659:     my ($scanlines,$scan_data,$i)=@_;
                   6660:     if (exists($scanlines->{'skipped'}[$i])) {
                   6661: 	undef($scanlines->{'skipped'}[$i]);
                   6662: 	return 1;
                   6663:     }
                   6664:     return 0;
                   6665: }
                   6666: 
1.423     albertel 6667: =pod
                   6668: 
                   6669: =item scantron_filter_not_exam
                   6670: 
1.424     albertel 6671:    Filter routine used by &Apache::lonnavmaps::retrieveResources(), to
                   6672:    filter out resources that are not marked as 'exam' mode
                   6673: 
1.423     albertel 6674: =cut
                   6675: 
1.334     albertel 6676: sub scantron_filter_not_exam {
                   6677:     my ($curres)=@_;
                   6678:     
                   6679:     if (ref($curres) && $curres->is_problem() && !$curres->is_exam()) {
                   6680: 	# if the user has asked to not have either hidden
                   6681: 	# or 'randomout' controlled resources to be graded
                   6682: 	# don't include them
                   6683: 	if ($env{'form.scantron_options_hidden'} eq 'ignore_hidden'
                   6684: 	    && $curres->randomout) {
                   6685: 	    return 0;
                   6686: 	}
                   6687: 	return 1;
                   6688:     }
                   6689:     return 0;
                   6690: }
                   6691: 
1.423     albertel 6692: =pod
                   6693: 
                   6694: =item scantron_validate_sequence
                   6695: 
1.424     albertel 6696:     Validates the selected sequence, checking for resource that are
                   6697:     not set to exam mode.
                   6698: 
1.423     albertel 6699: =cut
                   6700: 
1.334     albertel 6701: sub scantron_validate_sequence {
                   6702:     my ($r,$currentphase) = @_;
                   6703: 
                   6704:     my $navmap=Apache::lonnavmaps::navmap->new();
1.582     raeburn  6705:     unless (ref($navmap)) {
                   6706:         $r->print(&navmap_errormsg());
                   6707:         return (1,$currentphase);
                   6708:     }
1.334     albertel 6709:     my (undef,undef,$sequence)=
                   6710: 	&Apache::lonnet::decode_symb($env{'form.selectpage'});
                   6711: 
                   6712:     my $map=$navmap->getResourceByUrl($sequence);
                   6713: 
                   6714:     $r->print('<input type="hidden" name="validate_sequence_exam"
                   6715:                                     value="ignore" />');
                   6716:     if ($env{'form.validate_sequence_exam'} ne 'ignore') {
                   6717: 	my @resources=
                   6718: 	    $navmap->retrieveResources($map,\&scantron_filter_not_exam,1,0);
                   6719: 	if (@resources) {
1.357     banghart 6720: 	    $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 6721: 	    return (1,$currentphase);
                   6722: 	}
                   6723:     }
                   6724: 
                   6725:     return (0,$currentphase+1);
                   6726: }
                   6727: 
1.423     albertel 6728: 
                   6729: 
1.157     albertel 6730: sub scantron_validate_ID {
                   6731:     my ($r,$currentphase) = @_;
                   6732:     
                   6733:     #get student info
                   6734:     my $classlist=&Apache::loncoursedata::get_classlist();
                   6735:     my %idmap=&username_to_idmap($classlist);
                   6736: 
                   6737:     #get scantron line setup
1.257     albertel 6738:     my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
1.157     albertel 6739:     my ($scanlines,$scan_data)=&scantron_getfile();
1.582     raeburn  6740: 
                   6741:     my $nav_error;
                   6742:     &scantron_get_maxbubble(\$nav_error); # parse needs the bubble_lines.. array.
                   6743:     if ($nav_error) {
                   6744:         $r->print(&navmap_errormsg());
                   6745:         return(1,$currentphase);
                   6746:     }
1.157     albertel 6747: 
                   6748:     my %found=('ids'=>{},'usernames'=>{});
                   6749:     for (my $i=0;$i<=$scanlines->{'count'};$i++) {
1.200     albertel 6750: 	my $line=&scantron_get_line($scanlines,$scan_data,$i);
1.157     albertel 6751: 	if ($line=~/^[\s\cz]*$/) { next; }
                   6752: 	my $scan_record=&scantron_parse_scanline($line,$i,\%scantron_config,
                   6753: 						 $scan_data);
                   6754: 	my $id=$$scan_record{'scantron.ID'};
                   6755: 	my $found;
                   6756: 	foreach my $checkid (keys(%idmap)) {
                   6757: 	    if (lc($checkid) eq lc($id)) { $found=$checkid;last; }
                   6758: 	}
                   6759: 	if ($found) {
                   6760: 	    my $username=$idmap{$found};
                   6761: 	    if ($found{'ids'}{$found}) {
                   6762: 		&scantron_get_correction($r,$i,$scan_record,\%scantron_config,
                   6763: 					 $line,'duplicateID',$found);
1.194     albertel 6764: 		return(1,$currentphase);
1.157     albertel 6765: 	    } elsif ($found{'usernames'}{$username}) {
                   6766: 		&scantron_get_correction($r,$i,$scan_record,\%scantron_config,
                   6767: 					 $line,'duplicateID',$username);
1.194     albertel 6768: 		return(1,$currentphase);
1.157     albertel 6769: 	    }
1.186     albertel 6770: 	    #FIXME store away line we previously saw the ID on to use above
1.157     albertel 6771: 	    $found{'ids'}{$found}++;
                   6772: 	    $found{'usernames'}{$username}++;
                   6773: 	} else {
                   6774: 	    if ($id =~ /^\s*$/) {
1.158     albertel 6775: 		my $username=&scan_data($scan_data,"$i.user");
1.157     albertel 6776: 		if (defined($username) && $found{'usernames'}{$username}) {
                   6777: 		    &scantron_get_correction($r,$i,$scan_record,
                   6778: 					     \%scantron_config,
                   6779: 					     $line,'duplicateID',$username);
1.194     albertel 6780: 		    return(1,$currentphase);
1.157     albertel 6781: 		} elsif (!defined($username)) {
                   6782: 		    &scantron_get_correction($r,$i,$scan_record,
                   6783: 					     \%scantron_config,
                   6784: 					     $line,'incorrectID');
1.194     albertel 6785: 		    return(1,$currentphase);
1.157     albertel 6786: 		}
                   6787: 		$found{'usernames'}{$username}++;
                   6788: 	    } else {
                   6789: 		&scantron_get_correction($r,$i,$scan_record,\%scantron_config,
                   6790: 					 $line,'incorrectID');
1.194     albertel 6791: 		return(1,$currentphase);
1.157     albertel 6792: 	    }
                   6793: 	}
                   6794:     }
                   6795: 
                   6796:     return (0,$currentphase+1);
                   6797: }
                   6798: 
1.423     albertel 6799: 
1.157     albertel 6800: sub scantron_get_correction {
                   6801:     my ($r,$i,$scan_record,$scan_config,$line,$error,$arg)=@_;
1.454     banghart 6802: #FIXME in the case of a duplicated ID the previous line, probably need
1.157     albertel 6803: #to show both the current line and the previous one and allow skipping
                   6804: #the previous one or the current one
                   6805: 
1.333     albertel 6806:     if ( $$scan_record{'scantron.PaperID'} =~ /\S/) {
1.492     albertel 6807: 	$r->print("<p>".&mt("<b>An error was detected ($error)</b>".
                   6808: 			    " for PaperID <tt>[_1]</tt>",
                   6809: 			    $$scan_record{'scantron.PaperID'})."</p> \n");
1.157     albertel 6810:     } else {
1.492     albertel 6811: 	$r->print("<p>".&mt("<b>An error was detected ($error)</b>".
                   6812: 			    " in scanline [_1] <pre>[_2]</pre>",
                   6813: 			    $i,$line)."</p> \n");
                   6814:     }
                   6815:     my $message="<p>".&mt("The ID on the form is  <tt>[_1]</tt><br />".
                   6816: 			  "The name on the paper is [_2],[_3]",
                   6817: 			  $$scan_record{'scantron.ID'},
                   6818: 			  $$scan_record{'scantron.LastName'},
                   6819: 			  $$scan_record{'scantron.FirstName'})."</p>";
1.242     albertel 6820: 
1.157     albertel 6821:     $r->print('<input type="hidden" name="scantron_corrections" value="'.$error.'" />'."\n");
                   6822:     $r->print('<input type="hidden" name="scantron_line" value="'.$i.'" />'."\n");
1.503     raeburn  6823:                            # Array populated for doublebubble or
                   6824:     my @lines_to_correct;  # missingbubble errors to build javascript
                   6825:                            # to validate radio button checking   
                   6826: 
1.157     albertel 6827:     if ($error =~ /ID$/) {
1.186     albertel 6828: 	if ($error eq 'incorrectID') {
1.492     albertel 6829: 	    $r->print("<p>".&mt("The encoded ID is not in the classlist").
                   6830: 		      "</p>\n");
1.157     albertel 6831: 	} elsif ($error eq 'duplicateID') {
1.492     albertel 6832: 	    $r->print("<p>".&mt("The encoded ID has also been used by a previous paper [_1]",$arg)."</p>\n");
1.157     albertel 6833: 	}
1.242     albertel 6834: 	$r->print($message);
1.492     albertel 6835: 	$r->print("<p>".&mt("How should I handle this?")." <br /> \n");
1.157     albertel 6836: 	$r->print("\n<ul><li> ");
                   6837: 	#FIXME it would be nice if this sent back the user ID and
                   6838: 	#could do partial userID matches
                   6839: 	$r->print(&Apache::loncommon::selectstudent_link('scantronupload',
                   6840: 				       'scantron_username','scantron_domain'));
                   6841: 	$r->print(": <input type='text' name='scantron_username' value='' />");
                   6842: 	$r->print("\n@".
1.257     albertel 6843: 		 &Apache::loncommon::select_dom_form($env{'request.role.domain'},'scantron_domain'));
1.157     albertel 6844: 
                   6845: 	$r->print('</li>');
1.186     albertel 6846:     } elsif ($error =~ /CODE$/) {
                   6847: 	if ($error eq 'incorrectCODE') {
1.492     albertel 6848: 	    $r->print("<p>".&mt("The encoded CODE is not in the list of possible CODEs.")."</p>\n");
1.186     albertel 6849: 	} elsif ($error eq 'duplicateCODE') {
1.492     albertel 6850: 	    $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 6851: 	}
1.492     albertel 6852: 	$r->print("<p>".&mt("The CODE on the form is  <tt>'[_1]'</tt>",
                   6853: 			    $$scan_record{'scantron.CODE'})."<br />\n");
1.242     albertel 6854: 	$r->print($message);
1.492     albertel 6855: 	$r->print("<p>".&mt("How should I handle this?")." <br /> \n");
1.187     albertel 6856: 	$r->print("\n<br /> ");
1.194     albertel 6857: 	my $i=0;
1.273     albertel 6858: 	if ($error eq 'incorrectCODE' 
                   6859: 	    && $$scan_record{'scantron.CODE'}=~/\S/ ) {
1.194     albertel 6860: 	    my ($max,$closest)=&scantron_get_closely_matching_CODEs($arg,$$scan_record{'scantron.CODE'});
1.278     albertel 6861: 	    if ($closest > 0) {
                   6862: 		foreach my $testcode (@{$closest}) {
                   6863: 		    my $checked='';
1.569     bisitz   6864: 		    if (!$i) { $checked=' checked="checked"'; }
1.492     albertel 6865: 		    $r->print("
                   6866:    <label>
1.569     bisitz   6867:        <input type='radio' name='scantron_CODE_resolution' value='use_closest_$i'$checked />
1.492     albertel 6868:        ".&mt("Use the similar CODE [_1] instead.",
                   6869: 	    "<b><tt>".$testcode."</tt></b>")."
                   6870:     </label>
                   6871:     <input type='hidden' name='scantron_CODE_closest_$i' value='$testcode' />");
1.278     albertel 6872: 		    $r->print("\n<br />");
                   6873: 		    $i++;
                   6874: 		}
1.194     albertel 6875: 	    }
                   6876: 	}
1.273     albertel 6877: 	if ($$scan_record{'scantron.CODE'}=~/\S/ ) {
1.569     bisitz   6878: 	    my $checked; if (!$i) { $checked=' checked="checked"'; }
1.492     albertel 6879: 	    $r->print("
                   6880:     <label>
1.569     bisitz   6881:         <input type='radio' name='scantron_CODE_resolution' value='use_unfound'$checked />
1.492     albertel 6882:        ".&mt("Use the CODE [_1] that is was on the paper, ignoring the error.",
                   6883: 	     "<b><tt>".$$scan_record{'scantron.CODE'}."</tt></b>")."
                   6884:     </label>");
1.273     albertel 6885: 	    $r->print("\n<br />");
                   6886: 	}
1.194     albertel 6887: 
1.597     wenzelju 6888: 	$r->print(&Apache::lonhtmlcommon::scripttag(<<ENDSCRIPT));
1.188     albertel 6889: function change_radio(field) {
1.190     albertel 6890:     var slct=document.scantronupload.scantron_CODE_resolution;
1.188     albertel 6891:     var i;
                   6892:     for (i=0;i<slct.length;i++) {
                   6893:         if (slct[i].value==field) { slct[i].checked=true; }
                   6894:     }
                   6895: }
                   6896: ENDSCRIPT
1.187     albertel 6897: 	my $href="/adm/pickcode?".
1.359     www      6898: 	   "form=".&escape("scantronupload").
                   6899: 	   "&scantron_format=".&escape($env{'form.scantron_format'}).
                   6900: 	   "&scantron_CODElist=".&escape($env{'form.scantron_CODElist'}).
                   6901: 	   "&curCODE=".&escape($$scan_record{'scantron.CODE'}).
                   6902: 	   "&scantron_selectfile=".&escape($env{'form.scantron_selectfile'});
1.332     albertel 6903: 	if ($env{'form.scantron_CODElist'} =~ /\S/) { 
1.492     albertel 6904: 	    $r->print("
                   6905:     <label>
                   6906:        <input type='radio' name='scantron_CODE_resolution' value='use_found' />
                   6907:        ".&mt("[_1]Select[_2] a CODE from the list of all CODEs and use it.",
                   6908: 	     "<a target='_blank' href='$href'>","</a>")."
                   6909:     </label> 
1.558     bisitz   6910:     ".&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 6911: 	    $r->print("\n<br />");
                   6912: 	}
1.492     albertel 6913: 	$r->print("
                   6914:     <label>
                   6915:        <input type='radio' name='scantron_CODE_resolution' value='use_typed' />
                   6916:        ".&mt("Use [_1] as the CODE.",
                   6917: 	     "</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 6918: 	$r->print("\n<br /><br />");
1.157     albertel 6919:     } elsif ($error eq 'doublebubble') {
1.503     raeburn  6920: 	$r->print("<p>".&mt("There have been multiple bubbles scanned for some question(s)")."</p>\n");
1.497     foxr     6921: 
                   6922: 	# The form field scantron_questions is acutally a list of line numbers.
                   6923: 	# represented by this form so:
                   6924: 
                   6925: 	my $line_list = &questions_to_line_list($arg);
                   6926: 
1.157     albertel 6927: 	$r->print('<input type="hidden" name="scantron_questions" value="'.
1.497     foxr     6928: 		  $line_list.'" />');
1.242     albertel 6929: 	$r->print($message);
1.492     albertel 6930: 	$r->print("<p>".&mt("Please indicate which bubble should be used for grading")."</p>");
1.157     albertel 6931: 	foreach my $question (@{$arg}) {
1.503     raeburn  6932: 	    my @linenums = &prompt_for_corrections($r,$question,$scan_config,
                   6933:                                                    $scan_record, $error);
1.524     raeburn  6934:             push(@lines_to_correct,@linenums);
1.157     albertel 6935: 	}
1.503     raeburn  6936:         $r->print(&verify_bubbles_checked(@lines_to_correct));
1.157     albertel 6937:     } elsif ($error eq 'missingbubble') {
1.492     albertel 6938: 	$r->print("<p>".&mt("There have been <b>no</b> bubbles scanned for some question(s)")."</p>\n");
1.242     albertel 6939: 	$r->print($message);
1.492     albertel 6940: 	$r->print("<p>".&mt("Please indicate which bubble should be used for grading.")."</p>");
1.503     raeburn  6941: 	$r->print(&mt("Some questions have no scanned bubbles.")."\n");
1.497     foxr     6942: 
1.503     raeburn  6943: 	# The form field scantron_questions is actually a list of line numbers not
1.497     foxr     6944: 	# a list of question numbers. Therefore:
                   6945: 	#
                   6946: 	
                   6947: 	my $line_list = &questions_to_line_list($arg);
                   6948: 
1.157     albertel 6949: 	$r->print('<input type="hidden" name="scantron_questions" value="'.
1.497     foxr     6950: 		  $line_list.'" />');
1.157     albertel 6951: 	foreach my $question (@{$arg}) {
1.503     raeburn  6952: 	    my @linenums = &prompt_for_corrections($r,$question,$scan_config,
                   6953:                                                    $scan_record, $error);
1.524     raeburn  6954:             push(@lines_to_correct,@linenums);
1.157     albertel 6955: 	}
1.503     raeburn  6956:         $r->print(&verify_bubbles_checked(@lines_to_correct));
1.157     albertel 6957:     } else {
                   6958: 	$r->print("\n<ul>");
                   6959:     }
                   6960:     $r->print("\n</li></ul>");
1.497     foxr     6961: }
                   6962: 
1.503     raeburn  6963: sub verify_bubbles_checked {
                   6964:     my (@ansnums) = @_;
                   6965:     my $ansnumstr = join('","',@ansnums);
                   6966:     my $warning = &mt("A bubble or 'No bubble' selection has not been made for one or more lines.");
1.597     wenzelju 6967:     my $output = &Apache::lonhtmlcommon::scripttag((<<ENDSCRIPT));
1.503     raeburn  6968: function verify_bubble_radio(form) {
                   6969:     var ansnumArray = new Array ("$ansnumstr");
                   6970:     var need_bubble_count = 0;
                   6971:     for (var i=0; i<ansnumArray.length; i++) {
                   6972:         if (form.elements["scantron_correct_Q_"+ansnumArray[i]].length > 1) {
                   6973:             var bubble_picked = 0; 
                   6974:             for (var j=0; j<form.elements["scantron_correct_Q_"+ansnumArray[i]].length; j++) {
                   6975:                 if (form.elements["scantron_correct_Q_"+ansnumArray[i]][j].checked == true) {
                   6976:                     bubble_picked = 1;
                   6977:                 }
                   6978:             }
                   6979:             if (bubble_picked == 0) {
                   6980:                 need_bubble_count ++;
                   6981:             }
                   6982:         }
                   6983:     }
                   6984:     if (need_bubble_count) {
                   6985:         alert("$warning");
                   6986:         return;
                   6987:     }
                   6988:     form.submit(); 
                   6989: }
                   6990: ENDSCRIPT
                   6991:     return $output;
                   6992: }
                   6993: 
1.497     foxr     6994: =pod
                   6995: 
                   6996: =item  questions_to_line_list
1.157     albertel 6997: 
1.497     foxr     6998: Converts a list of questions into a string of comma separated
                   6999: line numbers in the answer sheet used by the questions.  This is
                   7000: used to fill in the scantron_questions form field.
                   7001: 
                   7002:   Arguments:
                   7003:      questions    - Reference to an array of questions.
                   7004: 
                   7005: =cut
                   7006: 
                   7007: 
                   7008: sub questions_to_line_list {
                   7009:     my ($questions) = @_;
                   7010:     my @lines;
                   7011: 
1.503     raeburn  7012:     foreach my $item (@{$questions}) {
                   7013:         my $question = $item;
                   7014:         my ($first,$count,$last);
                   7015:         if ($item =~ /^(\d+)\.(\d+)$/) {
                   7016:             $question = $1;
                   7017:             my $subquestion = $2;
                   7018:             $first = $first_bubble_line{$question-1} + 1;
                   7019:             my @subans = split(/,/,$subdivided_bubble_lines{$question-1});
                   7020:             my $subcount = 1;
                   7021:             while ($subcount<$subquestion) {
                   7022:                 $first += $subans[$subcount-1];
                   7023:                 $subcount ++;
                   7024:             }
                   7025:             $count = $subans[$subquestion-1];
                   7026:         } else {
                   7027: 	    $first   = $first_bubble_line{$question-1} + 1;
                   7028: 	    $count   = $bubble_lines_per_response{$question-1};
                   7029:         }
1.506     raeburn  7030:         $last = $first+$count-1;
1.503     raeburn  7031:         push(@lines, ($first..$last));
1.497     foxr     7032:     }
                   7033:     return join(',', @lines);
                   7034: }
                   7035: 
                   7036: =pod 
                   7037: 
                   7038: =item prompt_for_corrections
                   7039: 
                   7040: Prompts for a potentially multiline correction to the
                   7041: user's bubbling (factors out common code from scantron_get_correction
                   7042: for multi and missing bubble cases).
                   7043: 
                   7044:  Arguments:
                   7045:    $r           - Apache request object.
                   7046:    $question    - The question number to prompt for.
                   7047:    $scan_config - The scantron file configuration hash.
                   7048:    $scan_record - Reference to the hash that has the the parsed scanlines.
1.503     raeburn  7049:    $error       - Type of error
1.497     foxr     7050: 
                   7051:  Implicit inputs:
                   7052:    %bubble_lines_per_response   - Starting line numbers for each question.
                   7053:                                   Numbered from 0 (but question numbers are from
                   7054:                                   1.
                   7055:    %first_bubble_line           - Starting bubble line for each question.
1.509     raeburn  7056:    %subdivided_bubble_lines     - optionresponse, matchresponse and rankresponse 
                   7057:                                   type problems render as separate sub-questions, 
1.503     raeburn  7058:                                   in exam mode. This hash contains a 
                   7059:                                   comma-separated list of the lines per 
                   7060:                                   sub-question.
1.510     raeburn  7061:    %responsetype_per_response   - essayresponse, formularesponse,
                   7062:                                   stringresponse, imageresponse, reactionresponse,
                   7063:                                   and organicresponse type problem parts can have
1.503     raeburn  7064:                                   multiple lines per response if the weight
                   7065:                                   assigned exceeds 10.  In this case, only
                   7066:                                   one bubble per line is permitted, but more 
                   7067:                                   than one line might contain bubbles, e.g.
                   7068:                                   bubbling of: line 1 - J, line 2 - J, 
                   7069:                                   line 3 - B would assign 22 points.  
1.497     foxr     7070: 
                   7071: =cut
                   7072: 
                   7073: sub prompt_for_corrections {
1.503     raeburn  7074:     my ($r, $question, $scan_config, $scan_record, $error) = @_;
                   7075:     my ($current_line,$lines);
                   7076:     my @linenums;
                   7077:     my $questionnum = $question;
                   7078:     if ($question =~ /^(\d+)\.(\d+)$/) {
                   7079:         $question = $1;
                   7080:         $current_line = $first_bubble_line{$question-1} + 1 ;
                   7081:         my $subquestion = $2;
                   7082:         my @subans = split(/,/,$subdivided_bubble_lines{$question-1});
                   7083:         my $subcount = 1;
                   7084:         while ($subcount<$subquestion) {
                   7085:             $current_line += $subans[$subcount-1];
                   7086:             $subcount ++;
                   7087:         }
                   7088:         $lines = $subans[$subquestion-1];
                   7089:     } else {
                   7090:         $current_line = $first_bubble_line{$question-1} + 1 ;
                   7091:         $lines        = $bubble_lines_per_response{$question-1};
                   7092:     }
1.497     foxr     7093:     if ($lines > 1) {
1.503     raeburn  7094:         $r->print(&mt('The group of bubble lines below responds to a single question.').'<br />');
                   7095:         if (($responsetype_per_response{$question-1} eq 'essayresponse') ||
                   7096:             ($responsetype_per_response{$question-1} eq 'formularesponse') ||
1.510     raeburn  7097:             ($responsetype_per_response{$question-1} eq 'stringresponse') ||
                   7098:             ($responsetype_per_response{$question-1} eq 'imageresponse') ||
                   7099:             ($responsetype_per_response{$question-1} eq 'reactionresponse') ||
                   7100:             ($responsetype_per_response{$question-1} eq 'organicresponse')) {
1.572     www      7101:             $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  7102:         } else {
                   7103:             $r->print(&mt("Select at most one bubble in a single line and select 'No Bubble' in all the other lines. ")."<br />");
                   7104:         }
1.497     foxr     7105:     }
                   7106:     for (my $i =0; $i < $lines; $i++) {
1.503     raeburn  7107:         my $selected = $$scan_record{"scantron.$current_line.answer"};
                   7108: 	&scantron_bubble_selector($r,$scan_config,$current_line, 
                   7109: 	        		  $questionnum,$error,split('', $selected));
1.524     raeburn  7110:         push(@linenums,$current_line);
1.497     foxr     7111: 	$current_line++;
                   7112:     }
                   7113:     if ($lines > 1) {
                   7114: 	$r->print("<hr /><br />");
                   7115:     }
1.503     raeburn  7116:     return @linenums;
1.157     albertel 7117: }
1.423     albertel 7118: 
                   7119: =pod
                   7120: 
                   7121: =item scantron_bubble_selector
                   7122:   
                   7123:    Generates the html radiobuttons to correct a single bubble line
1.424     albertel 7124:    possibly showing the existing the selected bubbles if known
1.423     albertel 7125: 
                   7126:  Arguments:
                   7127:     $r           - Apache request object
                   7128:     $scan_config - hash from &get_scantron_config()
1.497     foxr     7129:     $line        - Number of the line being displayed.
1.503     raeburn  7130:     $questionnum - Question number (may include subquestion)
                   7131:     $error       - Type of error.
1.497     foxr     7132:     @selected    - Array of bubbles picked on this line.
1.423     albertel 7133: 
                   7134: =cut
                   7135: 
1.157     albertel 7136: sub scantron_bubble_selector {
1.503     raeburn  7137:     my ($r,$scan_config,$line,$questionnum,$error,@selected)=@_;
1.157     albertel 7138:     my $max=$$scan_config{'Qlength'};
1.274     albertel 7139: 
                   7140:     my $scmode=$$scan_config{'Qon'};
                   7141:     if ($scmode eq 'number' || $scmode eq 'letter') { $max=10; }	     
                   7142: 
1.157     albertel 7143:     my @alphabet=('A'..'Z');
1.503     raeburn  7144:     $r->print(&Apache::loncommon::start_data_table().
                   7145:               &Apache::loncommon::start_data_table_row());
                   7146:     $r->print('<td rowspan="2" class="LC_leftcol_header">'.$line.'</td>');
1.497     foxr     7147:     for (my $i=0;$i<$max+1;$i++) {
                   7148: 	$r->print("\n".'<td align="center">');
                   7149: 	if ($selected[0] eq $alphabet[$i]) { $r->print('X'); shift(@selected) }
                   7150: 	else { $r->print('&nbsp;'); }
                   7151: 	$r->print('</td>');
                   7152:     }
1.503     raeburn  7153:     $r->print(&Apache::loncommon::end_data_table_row().
                   7154:               &Apache::loncommon::start_data_table_row());
1.497     foxr     7155:     for (my $i=0;$i<$max;$i++) {
                   7156: 	$r->print("\n".
                   7157: 		  '<td><label><input type="radio" name="scantron_correct_Q_'.
                   7158: 		  $line.'" value="'.$i.'" />'.$alphabet[$i]."</label></td>");
                   7159:     }
1.503     raeburn  7160:     my $nobub_checked = ' ';
                   7161:     if ($error eq 'missingbubble') {
                   7162:         $nobub_checked = ' checked = "checked" ';
                   7163:     }
                   7164:     $r->print("\n".'<td><label><input type="radio" name="scantron_correct_Q_'.
                   7165: 	      $line.'" value="none"'.$nobub_checked.'/>'.&mt('No bubble').
                   7166:               '</label>'."\n".'<input type="hidden" name="scantron_questionnum_Q_'.
                   7167:               $line.'" value="'.$questionnum.'" /></td>');
                   7168:     $r->print(&Apache::loncommon::end_data_table_row().
                   7169:               &Apache::loncommon::end_data_table());
1.157     albertel 7170: }
                   7171: 
1.423     albertel 7172: =pod
                   7173: 
                   7174: =item num_matches
                   7175: 
1.424     albertel 7176:    Counts the number of characters that are the same between the two arguments.
                   7177: 
                   7178:  Arguments:
                   7179:    $orig - CODE from the scanline
                   7180:    $code - CODE to match against
                   7181: 
                   7182:  Returns:
                   7183:    $count - integer count of the number of same characters between the
                   7184:             two arguments
                   7185: 
1.423     albertel 7186: =cut
                   7187: 
1.194     albertel 7188: sub num_matches {
                   7189:     my ($orig,$code) = @_;
                   7190:     my @code=split(//,$code);
                   7191:     my @orig=split(//,$orig);
                   7192:     my $same=0;
                   7193:     for (my $i=0;$i<scalar(@code);$i++) {
                   7194: 	if ($code[$i] eq $orig[$i]) { $same++; }
                   7195:     }
                   7196:     return $same;
                   7197: }
                   7198: 
1.423     albertel 7199: =pod
                   7200: 
                   7201: =item scantron_get_closely_matching_CODEs
                   7202: 
1.424     albertel 7203:    Cycles through all CODEs and finds the set that has the greatest
                   7204:    number of same characters as the provided CODE
                   7205: 
                   7206:  Arguments:
                   7207:    $allcodes - hash ref returned by &get_codes()
                   7208:    $CODE     - CODE from the current scanline
                   7209: 
                   7210:  Returns:
                   7211:    2 element list
                   7212:     - first elements is number of how closely matching the best fit is 
                   7213:       (5 means best set has 5 matching characters)
                   7214:     - second element is an arrary ref containing the set of valid CODEs
                   7215:       that best fit the passed in CODE
                   7216: 
1.423     albertel 7217: =cut
                   7218: 
1.194     albertel 7219: sub scantron_get_closely_matching_CODEs {
                   7220:     my ($allcodes,$CODE)=@_;
                   7221:     my @CODEs;
                   7222:     foreach my $testcode (sort(keys(%{$allcodes}))) {
                   7223: 	push(@{$CODEs[&num_matches($CODE,$testcode)]},$testcode);
                   7224:     }
                   7225: 
                   7226:     return ($#CODEs,$CODEs[-1]);
                   7227: }
                   7228: 
1.423     albertel 7229: =pod
                   7230: 
                   7231: =item get_codes
                   7232: 
1.424     albertel 7233:    Builds a hash which has keys of all of the valid CODEs from the selected
                   7234:    set of remembered CODEs.
                   7235: 
                   7236:  Arguments:
                   7237:   $old_name - name of the set of remembered CODEs
                   7238:   $cdom     - domain of the course
                   7239:   $cnum     - internal course name
                   7240: 
                   7241:  Returns:
                   7242:   %allcodes - keys are the valid CODEs, values are all 1
                   7243: 
1.423     albertel 7244: =cut
                   7245: 
1.194     albertel 7246: sub get_codes {
1.280     foxr     7247:     my ($old_name, $cdom, $cnum) = @_;
                   7248:     if (!$old_name) {
                   7249: 	$old_name=$env{'form.scantron_CODElist'};
                   7250:     }
                   7251:     if (!$cdom) {
                   7252: 	$cdom =$env{'course.'.$env{'request.course.id'}.'.domain'};
                   7253:     }
                   7254:     if (!$cnum) {
                   7255: 	$cnum =$env{'course.'.$env{'request.course.id'}.'.num'};
                   7256:     }
1.278     albertel 7257:     my %result=&Apache::lonnet::get('CODEs',[$old_name,"type\0$old_name"],
                   7258: 				    $cdom,$cnum);
                   7259:     my %allcodes;
                   7260:     if ($result{"type\0$old_name"} eq 'number') {
                   7261: 	%allcodes=map {($_,1)} split(',',$result{$old_name});
                   7262:     } else {
                   7263: 	%allcodes=map {(&Apache::lonprintout::num_to_letters($_),1)} split(',',$result{$old_name});
                   7264:     }
1.194     albertel 7265:     return %allcodes;
                   7266: }
                   7267: 
1.423     albertel 7268: =pod
                   7269: 
                   7270: =item scantron_validate_CODE
                   7271: 
1.424     albertel 7272:    Validates all scanlines in the selected file to not have any
                   7273:    invalid or underspecified CODEs and that none of the codes are
                   7274:    duplicated if this was requested.
                   7275: 
1.423     albertel 7276: =cut
                   7277: 
1.157     albertel 7278: sub scantron_validate_CODE {
                   7279:     my ($r,$currentphase) = @_;
1.257     albertel 7280:     my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
1.186     albertel 7281:     if ($scantron_config{'CODElocation'} &&
                   7282: 	$scantron_config{'CODEstart'} &&
                   7283: 	$scantron_config{'CODElength'}) {
1.257     albertel 7284: 	if (!defined($env{'form.scantron_CODElist'})) {
1.186     albertel 7285: 	    &FIXME_blow_up()
                   7286: 	}
                   7287:     } else {
                   7288: 	return (0,$currentphase+1);
                   7289:     }
                   7290:     
                   7291:     my %usedCODEs;
                   7292: 
1.194     albertel 7293:     my %allcodes=&get_codes();
1.186     albertel 7294: 
1.582     raeburn  7295:     my $nav_error;
                   7296:     &scantron_get_maxbubble(\$nav_error); # parse needs the lines per response array.
                   7297:     if ($nav_error) {
                   7298:         $r->print(&navmap_errormsg());
                   7299:         return(1,$currentphase);
                   7300:     }
1.447     foxr     7301: 
1.186     albertel 7302:     my ($scanlines,$scan_data)=&scantron_getfile();
                   7303:     for (my $i=0;$i<=$scanlines->{'count'};$i++) {
1.200     albertel 7304: 	my $line=&scantron_get_line($scanlines,$scan_data,$i);
1.186     albertel 7305: 	if ($line=~/^[\s\cz]*$/) { next; }
                   7306: 	my $scan_record=&scantron_parse_scanline($line,$i,\%scantron_config,
                   7307: 						 $scan_data);
                   7308: 	my $CODE=$$scan_record{'scantron.CODE'};
                   7309: 	my $error=0;
1.224     albertel 7310: 	if (!&Apache::lonnet::validCODE($CODE)) {
                   7311: 	    &scantron_get_correction($r,$i,$scan_record,
                   7312: 				     \%scantron_config,
                   7313: 				     $line,'incorrectCODE',\%allcodes);
                   7314: 	    return(1,$currentphase);
                   7315: 	}
1.221     albertel 7316: 	if (%allcodes && !exists($allcodes{$CODE}) 
                   7317: 	    && !$$scan_record{'scantron.useCODE'}) {
1.186     albertel 7318: 	    &scantron_get_correction($r,$i,$scan_record,
                   7319: 				     \%scantron_config,
1.194     albertel 7320: 				     $line,'incorrectCODE',\%allcodes);
                   7321: 	    return(1,$currentphase);
1.186     albertel 7322: 	}
1.214     albertel 7323: 	if (exists($usedCODEs{$CODE}) 
1.257     albertel 7324: 	    && $env{'form.scantron_CODEunique'} eq 'yes'
1.192     albertel 7325: 	    && !$$scan_record{'scantron.CODE_ignore_dup'}) {
1.186     albertel 7326: 	    &scantron_get_correction($r,$i,$scan_record,
                   7327: 				     \%scantron_config,
1.194     albertel 7328: 				     $line,'duplicateCODE',$usedCODEs{$CODE});
                   7329: 	    return(1,$currentphase);
1.186     albertel 7330: 	}
1.524     raeburn  7331: 	push(@{$usedCODEs{$CODE}},$$scan_record{'scantron.PaperID'});
1.186     albertel 7332:     }
1.157     albertel 7333:     return (0,$currentphase+1);
                   7334: }
                   7335: 
1.423     albertel 7336: =pod
                   7337: 
                   7338: =item scantron_validate_doublebubble
                   7339: 
1.424     albertel 7340:    Validates all scanlines in the selected file to not have any
                   7341:    bubble lines with multiple bubbles marked.
                   7342: 
1.423     albertel 7343: =cut
                   7344: 
1.157     albertel 7345: sub scantron_validate_doublebubble {
                   7346:     my ($r,$currentphase) = @_;
                   7347:     #get student info
                   7348:     my $classlist=&Apache::loncoursedata::get_classlist();
                   7349:     my %idmap=&username_to_idmap($classlist);
                   7350: 
                   7351:     #get scantron line setup
1.257     albertel 7352:     my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
1.157     albertel 7353:     my ($scanlines,$scan_data)=&scantron_getfile();
1.583     raeburn  7354:     my $nav_error;
                   7355:     &scantron_get_maxbubble(\$nav_error); # parse needs the bubble line array.
                   7356:     if ($nav_error) {
                   7357:         $r->print(&navmap_errormsg());
                   7358:         return(1,$currentphase);
                   7359:     }
1.447     foxr     7360: 
1.157     albertel 7361:     for (my $i=0;$i<=$scanlines->{'count'};$i++) {
1.200     albertel 7362: 	my $line=&scantron_get_line($scanlines,$scan_data,$i);
1.157     albertel 7363: 	if ($line=~/^[\s\cz]*$/) { next; }
                   7364: 	my $scan_record=&scantron_parse_scanline($line,$i,\%scantron_config,
                   7365: 						 $scan_data);
                   7366: 	if (!defined($$scan_record{'scantron.doubleerror'})) { next; }
                   7367: 	&scantron_get_correction($r,$i,$scan_record,\%scantron_config,$line,
                   7368: 				 'doublebubble',
                   7369: 				 $$scan_record{'scantron.doubleerror'});
                   7370:     	return (1,$currentphase);
                   7371:     }
                   7372:     return (0,$currentphase+1);
                   7373: }
                   7374: 
1.423     albertel 7375: 
1.503     raeburn  7376: sub scantron_get_maxbubble {
1.582     raeburn  7377:     my ($nav_error) = @_;
1.257     albertel 7378:     if (defined($env{'form.scantron_maxbubble'}) &&
                   7379: 	$env{'form.scantron_maxbubble'}) {
1.447     foxr     7380: 	&restore_bubble_lines();
1.257     albertel 7381: 	return $env{'form.scantron_maxbubble'};
1.191     albertel 7382:     }
1.330     albertel 7383: 
1.447     foxr     7384:     my (undef, undef, $sequence) =
1.257     albertel 7385: 	&Apache::lonnet::decode_symb($env{'form.selectpage'});
1.330     albertel 7386: 
1.447     foxr     7387:     my $navmap=Apache::lonnavmaps::navmap->new();
1.582     raeburn  7388:     unless (ref($navmap)) {
                   7389:         if (ref($nav_error)) {
                   7390:             $$nav_error = 1;
                   7391:         }
1.591     raeburn  7392:         return;
1.582     raeburn  7393:     }
1.191     albertel 7394:     my $map=$navmap->getResourceByUrl($sequence);
                   7395:     my @resources=$navmap->retrieveResources($map,\&scantron_filter,1,0);
1.330     albertel 7396: 
                   7397:     &Apache::lonxml::clear_problem_counter();
                   7398: 
1.557     raeburn  7399:     my $uname       = $env{'user.name'};
                   7400:     my $udom        = $env{'user.domain'};
1.435     foxr     7401:     my $cid         = $env{'request.course.id'};
                   7402:     my $total_lines = 0;
                   7403:     %bubble_lines_per_response = ();
1.447     foxr     7404:     %first_bubble_line         = ();
1.503     raeburn  7405:     %subdivided_bubble_lines   = ();
                   7406:     %responsetype_per_response = ();
1.554     raeburn  7407: 
1.447     foxr     7408:     my $response_number = 0;
                   7409:     my $bubble_line     = 0;
1.191     albertel 7410:     foreach my $resource (@resources) {
1.542     raeburn  7411:         my ($analysis,$parts) = &scantron_partids_tograde($resource,$cid,$uname,$udom);
                   7412:         if ((ref($analysis) eq 'HASH') && (ref($parts) eq 'ARRAY')) {
                   7413: 	    foreach my $part_id (@{$parts}) {
                   7414:                 my $lines;
                   7415: 
                   7416: 	        # TODO - make this a persistent hash not an array.
                   7417: 
                   7418:                 # optionresponse, matchresponse and rankresponse type items 
                   7419:                 # render as separate sub-questions in exam mode.
                   7420:                 if (($analysis->{$part_id.'.type'} eq 'optionresponse') ||
                   7421:                     ($analysis->{$part_id.'.type'} eq 'matchresponse') ||
                   7422:                     ($analysis->{$part_id.'.type'} eq 'rankresponse')) {
                   7423:                     my ($numbub,$numshown);
                   7424:                     if ($analysis->{$part_id.'.type'} eq 'optionresponse') {
                   7425:                         if (ref($analysis->{$part_id.'.options'}) eq 'ARRAY') {
                   7426:                             $numbub = scalar(@{$analysis->{$part_id.'.options'}});
                   7427:                         }
                   7428:                     } elsif ($analysis->{$part_id.'.type'} eq 'matchresponse') {
                   7429:                         if (ref($analysis->{$part_id.'.items'}) eq 'ARRAY') {
                   7430:                             $numbub = scalar(@{$analysis->{$part_id.'.items'}});
                   7431:                         }
                   7432:                     } elsif ($analysis->{$part_id.'.type'} eq 'rankresponse') {
                   7433:                         if (ref($analysis->{$part_id.'.foils'}) eq 'ARRAY') {
                   7434:                             $numbub = scalar(@{$analysis->{$part_id.'.foils'}});
                   7435:                         }
                   7436:                     }
                   7437:                     if (ref($analysis->{$part_id.'.shown'}) eq 'ARRAY') {
                   7438:                         $numshown = scalar(@{$analysis->{$part_id.'.shown'}});
                   7439:                     }
                   7440:                     my $bubbles_per_line = 10;
                   7441:                     my $inner_bubble_lines = int($numbub/$bubbles_per_line);
                   7442:                     if (($numbub % $bubbles_per_line) != 0) {
                   7443:                         $inner_bubble_lines++;
                   7444:                     }
                   7445:                     for (my $i=0; $i<$numshown; $i++) {
                   7446:                         $subdivided_bubble_lines{$response_number} .= 
                   7447:                             $inner_bubble_lines.',';
                   7448:                     }
                   7449:                     $subdivided_bubble_lines{$response_number} =~ s/,$//;
                   7450:                     $lines = $numshown * $inner_bubble_lines;
                   7451:                 } else {
                   7452:                     $lines = $analysis->{"$part_id.bubble_lines"};
                   7453:                 } 
                   7454: 
                   7455:                 $first_bubble_line{$response_number} = $bubble_line;
                   7456: 	        $bubble_lines_per_response{$response_number} = $lines;
                   7457:                 $responsetype_per_response{$response_number} = 
                   7458:                     $analysis->{$part_id.'.type'};
                   7459: 	        $response_number++;
                   7460: 
                   7461: 	        $bubble_line +=  $lines;
                   7462: 	        $total_lines +=  $lines;
                   7463: 	    }
                   7464:         }
                   7465:     }
1.552     raeburn  7466:     &Apache::lonnet::delenv('scantron.');
1.542     raeburn  7467: 
                   7468:     &save_bubble_lines();
                   7469:     $env{'form.scantron_maxbubble'} =
                   7470: 	$total_lines;
                   7471:     return $env{'form.scantron_maxbubble'};
                   7472: }
1.523     raeburn  7473: 
1.157     albertel 7474: sub scantron_validate_missingbubbles {
                   7475:     my ($r,$currentphase) = @_;
                   7476:     #get student info
                   7477:     my $classlist=&Apache::loncoursedata::get_classlist();
                   7478:     my %idmap=&username_to_idmap($classlist);
                   7479: 
                   7480:     #get scantron line setup
1.257     albertel 7481:     my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
1.157     albertel 7482:     my ($scanlines,$scan_data)=&scantron_getfile();
1.582     raeburn  7483:     my $nav_error;
                   7484:     my $max_bubble=&scantron_get_maxbubble(\$nav_error);
                   7485:     if ($nav_error) {
                   7486:         return(1,$currentphase);
                   7487:     }
1.157     albertel 7488:     if (!$max_bubble) { $max_bubble=2**31; }
                   7489:     for (my $i=0;$i<=$scanlines->{'count'};$i++) {
1.200     albertel 7490: 	my $line=&scantron_get_line($scanlines,$scan_data,$i);
1.157     albertel 7491: 	if ($line=~/^[\s\cz]*$/) { next; }
                   7492: 	my $scan_record=&scantron_parse_scanline($line,$i,\%scantron_config,
                   7493: 						 $scan_data);
                   7494: 	if (!defined($$scan_record{'scantron.missingerror'})) { next; }
                   7495: 	my @to_correct;
1.470     foxr     7496: 	
                   7497: 	# Probably here's where the error is...
                   7498: 
1.157     albertel 7499: 	foreach my $missing (@{$$scan_record{'scantron.missingerror'}}) {
1.505     raeburn  7500:             my $lastbubble;
                   7501:             if ($missing =~ /^(\d+)\.(\d+)$/) {
                   7502:                my $question = $1;
                   7503:                my $subquestion = $2;
                   7504:                if (!defined($first_bubble_line{$question -1})) { next; }
                   7505:                my $first = $first_bubble_line{$question-1};
                   7506:                my @subans = split(/,/,$subdivided_bubble_lines{$question-1});
                   7507:                my $subcount = 1;
                   7508:                while ($subcount<$subquestion) {
                   7509:                    $first += $subans[$subcount-1];
                   7510:                    $subcount ++;
                   7511:                }
                   7512:                my $count = $subans[$subquestion-1];
                   7513:                $lastbubble = $first + $count;
                   7514:             } else {
                   7515:                 if (!defined($first_bubble_line{$missing - 1})) { next; }
                   7516:                 $lastbubble = $first_bubble_line{$missing - 1} + $bubble_lines_per_response{$missing - 1};
                   7517:             }
                   7518:             if ($lastbubble > $max_bubble) { next; }
1.157     albertel 7519: 	    push(@to_correct,$missing);
                   7520: 	}
                   7521: 	if (@to_correct) {
                   7522: 	    &scantron_get_correction($r,$i,$scan_record,\%scantron_config,
                   7523: 				     $line,'missingbubble',\@to_correct);
                   7524: 	    return (1,$currentphase);
                   7525: 	}
                   7526: 
                   7527:     }
                   7528:     return (0,$currentphase+1);
                   7529: }
                   7530: 
1.423     albertel 7531: 
1.82      albertel 7532: sub scantron_process_students {
1.608     www      7533:     my ($r,$symb) = @_;
1.513     foxr     7534: 
1.257     albertel 7535:     my (undef,undef,$sequence)=&Apache::lonnet::decode_symb($env{'form.selectpage'});
1.513     foxr     7536:     if (!$symb) {
                   7537: 	return '';
                   7538:     }
1.324     albertel 7539:     my $default_form_data=&defaultFormData($symb);
1.82      albertel 7540: 
1.257     albertel 7541:     my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
1.157     albertel 7542:     my ($scanlines,$scan_data)=&scantron_getfile();
1.82      albertel 7543:     my $classlist=&Apache::loncoursedata::get_classlist();
                   7544:     my %idmap=&username_to_idmap($classlist);
1.132     bowersj2 7545:     my $navmap=Apache::lonnavmaps::navmap->new();
1.582     raeburn  7546:     unless (ref($navmap)) {
                   7547:         $r->print(&navmap_errormsg());
                   7548:         return '';
                   7549:     }  
1.83      albertel 7550:     my $map=$navmap->getResourceByUrl($sequence);
                   7551:     my @resources=$navmap->retrieveResources($map,\&scantron_filter,1,0);
1.557     raeburn  7552:     my (%grader_partids_by_symb,%grader_randomlists_by_symb);
                   7553:     &graders_resources_pass(\@resources,\%grader_partids_by_symb,
                   7554:                             \%grader_randomlists_by_symb);
1.586     raeburn  7555:     my $resource_error;
1.557     raeburn  7556:     foreach my $resource (@resources) {
1.586     raeburn  7557:         my $ressymb;
                   7558:         if (ref($resource)) {
                   7559:             $ressymb = $resource->symb();
                   7560:         } else {
                   7561:             $resource_error = 1;
                   7562:             last;
                   7563:         }
1.557     raeburn  7564:         my ($analysis,$parts) =
                   7565:             &scantron_partids_tograde($resource,$env{'request.course.id'},
                   7566:                                       $env{'user.name'},$env{'user.domain'},1);
                   7567:         $grader_partids_by_symb{$ressymb} = $parts;
                   7568:         if (ref($analysis) eq 'HASH') {
                   7569:             if (ref($analysis->{'parts_withrandomlist'}) eq 'ARRAY') {
                   7570:                 $grader_randomlists_by_symb{$ressymb} = 
                   7571:                     $analysis->{'parts_withrandomlist'};
                   7572:             }
                   7573:         }
                   7574:     }
1.586     raeburn  7575:     if ($resource_error) {
                   7576:         $r->print(&navmap_errormsg());
                   7577:         return '';
                   7578:     }
1.557     raeburn  7579: 
1.554     raeburn  7580:     my ($uname,$udom);
1.82      albertel 7581:     my $result= <<SCANTRONFORM;
1.81      albertel 7582: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="scantronupload">
                   7583:   <input type="hidden" name="command" value="scantron_configphase" />
                   7584:   $default_form_data
                   7585: SCANTRONFORM
1.82      albertel 7586:     $r->print($result);
                   7587: 
                   7588:     my @delayqueue;
1.542     raeburn  7589:     my (%completedstudents,%scandata);
1.140     albertel 7590:     
1.520     www      7591:     my $lock=&Apache::lonnet::set_lock(&mt('Grading bubblesheet exam'));
1.200     albertel 7592:     my $count=&get_todo_count($scanlines,$scan_data);
1.575     www      7593:     my %prog_state=&Apache::lonhtmlcommon::Create_PrgWin($r,'Bubblesheet Status',
                   7594:  				    'Bubblesheet Progress',$count,
1.195     albertel 7595: 				    'inline',undef,'scantronupload');
1.140     albertel 7596:     &Apache::lonhtmlcommon::Update_PrgWin($r,\%prog_state,
                   7597: 					  'Processing first student');
1.542     raeburn  7598:     $r->print('<br />');
1.140     albertel 7599:     my $start=&Time::HiRes::time();
1.158     albertel 7600:     my $i=-1;
1.542     raeburn  7601:     my $started;
1.447     foxr     7602: 
1.582     raeburn  7603:     my $nav_error;
                   7604:     &scantron_get_maxbubble(\$nav_error); # Need the bubble lines array to parse.
                   7605:     if ($nav_error) {
                   7606:         $r->print(&navmap_errormsg());
                   7607:         return '';
                   7608:     }
                   7609: 
1.513     foxr     7610:     # If an ssi failed in scantron_get_maxbubble, put an error message out to
                   7611:     # the user and return.
                   7612: 
                   7613:     if ($ssi_error) {
                   7614: 	$r->print("</form>");
                   7615: 	&ssi_print_error($r);
1.520     www      7616:         &Apache::lonnet::remove_lock($lock);
1.513     foxr     7617: 	return '';		# Dunno why the other returns return '' rather than just returning.
                   7618:     }
1.447     foxr     7619: 
1.542     raeburn  7620:     my %lettdig = &letter_to_digits();
                   7621:     my $numletts = scalar(keys(%lettdig));
                   7622: 
1.157     albertel 7623:     while ($i<$scanlines->{'count'}) {
                   7624:  	($uname,$udom)=('','');
                   7625:  	$i++;
1.200     albertel 7626:  	my $line=&scantron_get_line($scanlines,$scan_data,$i);
1.157     albertel 7627:  	if ($line=~/^[\s\cz]*$/) { next; }
1.200     albertel 7628: 	if ($started) {
                   7629: 	    &Apache::lonhtmlcommon::Increment_PrgWin($r,\%prog_state,
                   7630: 						     'last student');
                   7631: 	}
                   7632: 	$started=1;
1.157     albertel 7633:  	my $scan_record=&scantron_parse_scanline($line,$i,\%scantron_config,
                   7634:  						 $scan_data);
                   7635:  	unless ($uname=&scantron_find_student($scan_record,$scan_data,
                   7636:  					      \%idmap,$i)) {
                   7637:   	    &scantron_add_delay(\@delayqueue,$line,
                   7638:  				'Unable to find a student that matches',1);
                   7639:  	    next;
                   7640:   	}
                   7641:  	if (exists $completedstudents{$uname}) {
                   7642:  	    &scantron_add_delay(\@delayqueue,$line,
                   7643:  				'Student '.$uname.' has multiple sheets',2);
                   7644:  	    next;
                   7645:  	}
                   7646:   	($uname,$udom)=split(/:/,$uname);
1.330     albertel 7647: 
1.586     raeburn  7648:         my (%partids_by_symb,$res_error);
1.554     raeburn  7649:         foreach my $resource (@resources) {
1.586     raeburn  7650:             my $ressymb;
                   7651:             if (ref($resource)) {
                   7652:                 $ressymb = $resource->symb();
                   7653:             } else {
                   7654:                 $res_error = 1;
                   7655:                 last;
                   7656:             }
1.557     raeburn  7657:             if ((exists($grader_randomlists_by_symb{$ressymb})) ||
                   7658:                 (ref($grader_partids_by_symb{$ressymb}) ne 'ARRAY')) {
                   7659:                 my ($analysis,$parts) =
                   7660:                     &scantron_partids_tograde($resource,$env{'request.course.id'},$uname,$udom);
                   7661:                 $partids_by_symb{$ressymb} = $parts;
                   7662:             } else {
                   7663:                 $partids_by_symb{$ressymb} = $grader_partids_by_symb{$ressymb};
                   7664:             }
1.554     raeburn  7665:         }
                   7666: 
1.586     raeburn  7667:         if ($res_error) {
                   7668:             &scantron_add_delay(\@delayqueue,$line,
                   7669:                                 'An error occurred while grading student '.$uname,2);
                   7670:             next;
                   7671:         }
                   7672: 
1.330     albertel 7673: 	&Apache::lonxml::clear_problem_counter();
1.514     raeburn  7674:   	&Apache::lonnet::appenv($scan_record);
1.376     albertel 7675: 
                   7676: 	if (&scantron_clear_skip($scanlines,$scan_data,$i)) {
                   7677: 	    &scantron_putfile($scanlines,$scan_data);
                   7678: 	}
1.161     albertel 7679: 	
1.542     raeburn  7680:         my $scancode;
                   7681:         if ((exists($scan_record->{'scantron.CODE'})) &&
                   7682:             (&Apache::lonnet::validCODE($scan_record->{'scantron.CODE'}))) {
                   7683:             $scancode = $scan_record->{'scantron.CODE'};
                   7684:         } else {
                   7685:             $scancode = '';
                   7686:         }
                   7687: 
                   7688:         if (&grade_student_bubbles($r,$uname,$udom,$scan_record,$scancode,
1.554     raeburn  7689:                                    \@resources,\%partids_by_symb) eq 'ssi_error') {
1.542     raeburn  7690:             $ssi_error = 0; # So end of handler error message does not trigger.
                   7691:             $r->print("</form>");
                   7692:             &ssi_print_error($r);
                   7693:             &Apache::lonnet::remove_lock($lock);
                   7694:             return '';      # Why return ''?  Beats me.
                   7695:         }
1.513     foxr     7696: 
1.140     albertel 7697: 	$completedstudents{$uname}={'line'=>$line};
1.542     raeburn  7698:         if ($env{'form.verifyrecord'}) {
                   7699:             my $lastpos = $env{'form.scantron_maxbubble'}*$scantron_config{'Qlength'};
                   7700:             my $studentdata = substr($line,$scantron_config{'Qstart'}-1,$lastpos);
                   7701:             chomp($studentdata);
                   7702:             $studentdata =~ s/\r$//;
                   7703:             my $studentrecord = '';
                   7704:             my $counter = -1;
                   7705:             foreach my $resource (@resources) {
1.554     raeburn  7706:                 my $ressymb = $resource->symb();
1.542     raeburn  7707:                 ($counter,my $recording) =
                   7708:                     &verify_scantron_grading($resource,$udom,$uname,$env{'request.course.id'},
1.554     raeburn  7709:                                              $counter,$studentdata,$partids_by_symb{$ressymb},
1.542     raeburn  7710:                                              \%scantron_config,\%lettdig,$numletts);
                   7711:                 $studentrecord .= $recording;
                   7712:             }
                   7713:             if ($studentrecord ne $studentdata) {
1.554     raeburn  7714:                 &Apache::lonxml::clear_problem_counter();
                   7715:                 if (&grade_student_bubbles($r,$uname,$udom,$scan_record,$scancode,
                   7716:                                            \@resources,\%partids_by_symb) eq 'ssi_error') {
                   7717:                     $ssi_error = 0; # So end of handler error message does not trigger.
                   7718:                     $r->print("</form>");
                   7719:                     &ssi_print_error($r);
                   7720:                     &Apache::lonnet::remove_lock($lock);
                   7721:                     delete($completedstudents{$uname});
                   7722:                     return '';
                   7723:                 }
1.542     raeburn  7724:                 $counter = -1;
                   7725:                 $studentrecord = '';
                   7726:                 foreach my $resource (@resources) {
1.554     raeburn  7727:                     my $ressymb = $resource->symb();
1.542     raeburn  7728:                     ($counter,my $recording) =
                   7729:                         &verify_scantron_grading($resource,$udom,$uname,$env{'request.course.id'},
1.554     raeburn  7730:                                                  $counter,$studentdata,$partids_by_symb{$ressymb},
1.542     raeburn  7731:                                                  \%scantron_config,\%lettdig,$numletts);
                   7732:                     $studentrecord .= $recording;
                   7733:                 }
                   7734:                 if ($studentrecord ne $studentdata) {
                   7735:                     $r->print('<p><span class="LC_error">');
                   7736:                     if ($scancode eq '') {
                   7737:                         $r->print(&mt('Mismatch grading bubble sheet for user: [_1] with ID: [_2].',
                   7738:                                   $uname.':'.$udom,$scan_record->{'scantron.ID'}));
                   7739:                     } else {
                   7740:                         $r->print(&mt('Mismatch grading bubble sheet for user: [_1] with ID: [_2] and CODE: [_3].',
                   7741:                                   $uname.':'.$udom,$scan_record->{'scantron.ID'},$scancode));
                   7742:                     }
                   7743:                     $r->print('</span><br />'.&Apache::loncommon::start_data_table()."\n".
                   7744:                               &Apache::loncommon::start_data_table_header_row()."\n".
                   7745:                               '<th>'.&mt('Source').'</th><th>'.&mt('Bubbled responses').'</th>'.
                   7746:                               &Apache::loncommon::end_data_table_header_row()."\n".
                   7747:                               &Apache::loncommon::start_data_table_row().
                   7748:                               '<td>'.&mt('Bubble Sheet').'</td>'.
                   7749:                               '<td><span class="LC_nobreak">'.$studentdata.'</span></td>'.
                   7750:                               &Apache::loncommon::end_data_table_row().
                   7751:                               &Apache::loncommon::start_data_table_row().
                   7752:                               '<td>Stored submissions</td>'.
                   7753:                               '<td><span class="LC_nobreak">'.$studentrecord.'</span></td>'."\n".
                   7754:                               &Apache::loncommon::end_data_table_row().
                   7755:                               &Apache::loncommon::end_data_table().'</p>');
                   7756:                 } else {
                   7757:                     $r->print('<br /><span class="LC_warning">'.
                   7758:                              &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 />'.
                   7759:                              &mt("As a consequence, this user's submission history records two tries.").
                   7760:                                  '</span><br />');
                   7761:                 }
                   7762:             }
                   7763:         }
1.543     raeburn  7764:         if (&Apache::loncommon::connection_aborted($r)) { last; }
1.140     albertel 7765:     } continue {
1.330     albertel 7766: 	&Apache::lonxml::clear_problem_counter();
1.552     raeburn  7767: 	&Apache::lonnet::delenv('scantron.');
1.82      albertel 7768:     }
1.140     albertel 7769:     &Apache::lonhtmlcommon::Close_PrgWin($r,\%prog_state);
1.520     www      7770:     &Apache::lonnet::remove_lock($lock);
1.172     albertel 7771: #    my $lasttime = &Time::HiRes::time()-$start;
                   7772: #    $r->print("<p>took $lasttime</p>");
1.140     albertel 7773: 
1.200     albertel 7774:     $r->print("</form>");
1.157     albertel 7775:     return '';
1.75      albertel 7776: }
1.157     albertel 7777: 
1.557     raeburn  7778: sub graders_resources_pass {
                   7779:     my ($resources,$grader_partids_by_symb,$grader_randomlists_by_symb) = @_;
                   7780:     if ((ref($resources) eq 'ARRAY') && (ref($grader_partids_by_symb)) && 
                   7781:         (ref($grader_randomlists_by_symb) eq 'HASH')) {
                   7782:         foreach my $resource (@{$resources}) {
                   7783:             my $ressymb = $resource->symb();
                   7784:             my ($analysis,$parts) =
                   7785:                 &scantron_partids_tograde($resource,$env{'request.course.id'},
                   7786:                                           $env{'user.name'},$env{'user.domain'},1);
                   7787:             $grader_partids_by_symb->{$ressymb} = $parts;
                   7788:             if (ref($analysis) eq 'HASH') {
                   7789:                 if (ref($analysis->{'parts_withrandomlist'}) eq 'ARRAY') {
                   7790:                     $grader_randomlists_by_symb->{$ressymb} =
                   7791:                         $analysis->{'parts_withrandomlist'};
                   7792:                 }
                   7793:             }
                   7794:         }
                   7795:     }
                   7796:     return;
                   7797: }
                   7798: 
1.542     raeburn  7799: sub grade_student_bubbles {
1.554     raeburn  7800:     my ($r,$uname,$udom,$scan_record,$scancode,$resources,$parts) = @_;
                   7801:     if (ref($resources) eq 'ARRAY') {
                   7802:         my $count = 0;
                   7803:         foreach my $resource (@{$resources}) {
                   7804:             my $ressymb = $resource->symb();
                   7805:             my %form = ('submitted'      => 'scantron',
                   7806:                         'grade_target'   => 'grade',
                   7807:                         'grade_username' => $uname,
                   7808:                         'grade_domain'   => $udom,
                   7809:                         'grade_courseid' => $env{'request.course.id'},
                   7810:                         'grade_symb'     => $ressymb,
                   7811:                         'CODE'           => $scancode
                   7812:                        );
                   7813:             if (ref($parts) eq 'HASH') {
                   7814:                 if (ref($parts->{$ressymb}) eq 'ARRAY') {
                   7815:                     foreach my $part (@{$parts->{$ressymb}}) {
                   7816:                         $form{'scantron_questnum_start.'.$part} =
                   7817:                             1+$env{'form.scantron.first_bubble_line.'.$count};
                   7818:                         $count++;
                   7819:                     }
                   7820:                 }
                   7821:             }
                   7822:             my $result=&ssi_with_retries($resource->src(),$ssi_retries,%form);
                   7823:             return 'ssi_error' if ($ssi_error);
                   7824:             last if (&Apache::loncommon::connection_aborted($r));
                   7825:         }
1.542     raeburn  7826:     }
                   7827:     return;
                   7828: }
                   7829: 
1.157     albertel 7830: sub scantron_upload_scantron_data {
1.608     www      7831:     my ($r,$symb)=@_;
1.565     raeburn  7832:     my $dom = $env{'request.role.domain'};
                   7833:     my $domdesc = &Apache::lonnet::domain($dom,'description');
                   7834:     $r->print(&Apache::loncommon::coursebrowser_javascript($dom));
1.157     albertel 7835:     my $select_link=&Apache::loncommon::selectcourse_link('rules','courseid',
1.181     albertel 7836: 							  'domainid',
1.565     raeburn  7837: 							  'coursename',$dom);
                   7838:     my $syllabuslink = '<a href="javascript:ToSyllabus();">'.&mt('Syllabus').'</a>'.
                   7839:                        ('&nbsp'x2).&mt('(shows course personnel)'); 
1.608     www      7840:     my $default_form_data=&defaultFormData($symb);
1.579     raeburn  7841:     my $nofile_alert = &mt('Please use the browse button to select a file from your local directory.');
                   7842:     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 7843:     $r->print(&Apache::lonhtmlcommon::scripttag('
1.157     albertel 7844:     function checkUpload(formname) {
                   7845: 	if (formname.upfile.value == "") {
1.579     raeburn  7846: 	    alert("'.$nofile_alert.'");
1.157     albertel 7847: 	    return false;
                   7848: 	}
1.565     raeburn  7849:         if (formname.courseid.value == "") {
1.579     raeburn  7850:             alert("'.$nocourseid_alert.'");
1.565     raeburn  7851:             return false;
                   7852:         }
1.157     albertel 7853: 	formname.submit();
                   7854:     }
1.565     raeburn  7855: 
                   7856:     function ToSyllabus() {
                   7857:         var cdom = '."'$dom'".';
                   7858:         var cnum = document.rules.courseid.value;
                   7859:         if (cdom == "" || cdom == null) {
                   7860:             return;
                   7861:         }
                   7862:         if (cnum == "" || cnum == null) {
                   7863:            return;
                   7864:         }
                   7865:         syllwin=window.open("/public/"+cdom+"/"+cnum+"/syllabus","LONCAPASyllabus",
                   7866:                             "height=350,width=350,scrollbars=yes,menubar=no");
                   7867:         return;
                   7868:     }
                   7869: 
1.597     wenzelju 7870: '));
                   7871:     $r->print('
1.566     raeburn  7872: <h3>'.&mt('Send scanned bubblesheet data to a course').'</h3>
                   7873: 
1.492     albertel 7874: <form enctype="multipart/form-data" action="/adm/grades" name="rules" method="post">
1.565     raeburn  7875: '.$default_form_data.
                   7876:   &Apache::lonhtmlcommon::start_pick_box().
                   7877:   &Apache::lonhtmlcommon::row_title(&mt('Course ID')).
                   7878:   '<input name="courseid" type="text" size="30" />'.$select_link.
                   7879:   &Apache::lonhtmlcommon::row_closure().
                   7880:   &Apache::lonhtmlcommon::row_title(&mt('Course Name')).
                   7881:   '<input name="coursename" type="text" size="30" />'.$syllabuslink.
                   7882:   &Apache::lonhtmlcommon::row_closure().
                   7883:   &Apache::lonhtmlcommon::row_title(&mt('Domain')).
                   7884:   '<input name="domainid" type="hidden" />'.$domdesc.
                   7885:   &Apache::lonhtmlcommon::row_closure().
                   7886:   &Apache::lonhtmlcommon::row_title(&mt('File to upload')).
                   7887:   '<input type="file" name="upfile" size="50" />'.
                   7888:   &Apache::lonhtmlcommon::row_closure(1).
                   7889:   &Apache::lonhtmlcommon::end_pick_box().'<br />
                   7890: 
1.492     albertel 7891: <input name="command" value="scantronupload_save" type="hidden" />
1.589     bisitz   7892: <input type="button" onclick="javascript:checkUpload(this.form);" value="'.&mt('Upload Bubblesheet Data').'" />
1.157     albertel 7893: </form>
1.492     albertel 7894: ');
1.157     albertel 7895:     return '';
                   7896: }
                   7897: 
1.423     albertel 7898: 
1.157     albertel 7899: sub scantron_upload_scantron_data_save {
1.608     www      7900:     my($r,$symb)=@_;
1.182     albertel 7901:     my $doanotherupload=
                   7902: 	'<br /><form action="/adm/grades" method="post">'."\n".
                   7903: 	'<input type="hidden" name="command" value="scantronupload" />'."\n".
1.492     albertel 7904: 	'<input type="submit" name="submit" value="'.&mt('Do Another Upload').'" />'."\n".
1.182     albertel 7905: 	'</form>'."\n";
1.257     albertel 7906:     if (!&Apache::lonnet::allowed('usc',$env{'form.domainid'}) &&
1.162     albertel 7907: 	!&Apache::lonnet::allowed('usc',
1.257     albertel 7908: 			    $env{'form.domainid'}.'_'.$env{'form.courseid'})) {
1.575     www      7909: 	$r->print(&mt("You are not allowed to upload bubblesheet data to the requested course.")."<br />");
1.614     www      7910: 	unless ($symb) {
1.182     albertel 7911: 	    $r->print($doanotherupload);
                   7912: 	}
1.162     albertel 7913: 	return '';
                   7914:     }
1.257     albertel 7915:     my %coursedata=&Apache::lonnet::coursedescription($env{'form.domainid'}.'_'.$env{'form.courseid'});
1.568     raeburn  7916:     my $uploadedfile;
1.567     raeburn  7917:     $r->print('<h3>'.&mt("Uploading file to [_1]",$coursedata{'description'}).'</h3>');
1.257     albertel 7918:     if (length($env{'form.upfile'}) < 2) {
1.568     raeburn  7919:         $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 7920:     } else {
1.568     raeburn  7921:         my $result = 
                   7922:             &Apache::lonnet::userfileupload('upfile','','scantron','','','',
                   7923:                                             $env{'form.courseid'},$env{'form.domainid'});
                   7924: 	if ($result =~ m{^/uploaded/}) {
1.567     raeburn  7925: 	    $r->print(&mt('[_1]Success:[_2] Successfully uploaded [_3] bytes of data into location: [_4]',
                   7926:                           '<span class="LC_success">','</span>',(length($env{'form.upfile'})-1),
                   7927: 			  '<span class="LC_filename">'.$result.'</span>'));
1.568     raeburn  7928:             ($uploadedfile) = ($result =~ m{/([^/]+)$});
1.567     raeburn  7929:             $r->print(&validate_uploaded_scantron_file($env{'form.domainid'},
1.568     raeburn  7930:                                                        $env{'form.courseid'},$uploadedfile));
1.210     albertel 7931: 	} else {
1.567     raeburn  7932: 	    $r->print(&mt('[_1]Error:[_2] An error ([_3]) occurred when attempting to upload the file, [_4]',
                   7933:                           '<span class="LC_error">','</span>',$result,
1.568     raeburn  7934: 			  '<span class="LC_filename">'.&HTML::Entities::encode($env{'form.upfile.filename'},'<>&"').'</span>'));
1.183     albertel 7935: 	}
                   7936:     }
1.174     albertel 7937:     if ($symb) {
1.612     www      7938: 	$r->print(&scantron_selectphase($r,$uploadedfile,$symb));
1.174     albertel 7939:     } else {
1.182     albertel 7940: 	$r->print($doanotherupload);
1.174     albertel 7941:     }
1.157     albertel 7942:     return '';
                   7943: }
                   7944: 
1.567     raeburn  7945: sub validate_uploaded_scantron_file {
                   7946:     my ($cdom,$cname,$fname) = @_;
                   7947:     my $scanlines=&Apache::lonnet::getfile('/uploaded/'.$cdom.'/'.$cname.'/'.$fname);
                   7948:     my @lines;
                   7949:     if ($scanlines ne '-1') {
                   7950:         @lines=split("\n",$scanlines,-1);
                   7951:     }
                   7952:     my $output;
                   7953:     if (@lines) {
                   7954:         my (%counts,$max_match_format);
                   7955:         my ($max_match_count,$max_match_pct) = (0,0);
                   7956:         my $classlist = &Apache::loncoursedata::get_classlist($cdom,$cname);
                   7957:         my %idmap = &username_to_idmap($classlist);
                   7958:         foreach my $key (keys(%idmap)) {
                   7959:             my $lckey = lc($key);
                   7960:             $idmap{$lckey} = $idmap{$key};
                   7961:         }
                   7962:         my %unique_formats;
                   7963:         my @formatlines = &get_scantronformat_file();
                   7964:         foreach my $line (@formatlines) {
                   7965:             chomp($line);
                   7966:             my @config = split(/:/,$line);
                   7967:             my $idstart = $config[5];
                   7968:             my $idlength = $config[6];
                   7969:             if (($idstart ne '') && ($idlength > 0)) {
                   7970:                 if (ref($unique_formats{$idstart.':'.$idlength}) eq 'ARRAY') {
                   7971:                     push(@{$unique_formats{$idstart.':'.$idlength}},$config[0].':'.$config[1]); 
                   7972:                 } else {
                   7973:                     $unique_formats{$idstart.':'.$idlength} = [$config[0].':'.$config[1]];
                   7974:                 }
                   7975:             }
                   7976:         }
                   7977:         foreach my $key (keys(%unique_formats)) {
                   7978:             my ($idstart,$idlength) = split(':',$key);
                   7979:             %{$counts{$key}} = (
                   7980:                                'found'   => 0,
                   7981:                                'total'   => 0,
                   7982:                               );
                   7983:             foreach my $line (@lines) {
                   7984:                 next if ($line =~ /^#/);
                   7985:                 next if ($line =~ /^[\s\cz]*$/);
                   7986:                 my $id = substr($line,$idstart-1,$idlength);
                   7987:                 $id = lc($id);
                   7988:                 if (exists($idmap{$id})) {
                   7989:                     $counts{$key}{'found'} ++;
                   7990:                 }
                   7991:                 $counts{$key}{'total'} ++;
                   7992:             }
                   7993:             if ($counts{$key}{'total'}) {
                   7994:                 my $percent_match = (100*$counts{$key}{'found'})/($counts{$key}{'total'});
                   7995:                 if (($max_match_format eq '') || ($percent_match > $max_match_pct)) {
                   7996:                     $max_match_pct = $percent_match;
                   7997:                     $max_match_format = $key;
                   7998:                     $max_match_count = $counts{$key}{'total'};
                   7999:                 }
                   8000:             }
                   8001:         }
                   8002:         if (ref($unique_formats{$max_match_format}) eq 'ARRAY') {
                   8003:             my $format_descs;
                   8004:             my $numwithformat = @{$unique_formats{$max_match_format}};
                   8005:             for (my $i=0; $i<$numwithformat; $i++) {
                   8006:                 my ($name,$desc) = split(':',$unique_formats{$max_match_format}[$i]);
                   8007:                 if ($i<$numwithformat-2) {
                   8008:                     $format_descs .= '"<i>'.$desc.'</i>", ';
                   8009:                 } elsif ($i==$numwithformat-2) {
                   8010:                     $format_descs .= '"<i>'.$desc.'</i>" '.&mt('and').' ';
                   8011:                 } elsif ($i==$numwithformat-1) {
                   8012:                     $format_descs .= '"<i>'.$desc.'</i>"';
                   8013:                 }
                   8014:             }
                   8015:             my $showpct = sprintf("%.0f",$max_match_pct).'%';
                   8016:             $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).
                   8017:                        '<br />'.&mt('A low percentage of matches results from one of the following:').'<ul>'.
                   8018:                        '<li>'.&mt('The file was uploaded to the wrong course').'</li>'.
                   8019:                        '<li>'.&mt('The data are not in the format expected for the domain: [_1]',
                   8020:                                   '<i>'.$cdom.'</i>').'</li>'.
                   8021:                        '<li>'.&mt('Students did not bubble their IDs, or mis-bubbled them').'</li>'.
                   8022:                        '<li>'.&mt('The course roster is not up to date').'</li>'.
                   8023:                        '</ul>';
                   8024:         }
                   8025:     } else {
                   8026:         $output = '<span class="LC_warning">'.&mt('Uploaded file contained no data').'</span>';
                   8027:     }
                   8028:     return $output;
                   8029: }
                   8030: 
1.202     albertel 8031: sub valid_file {
                   8032:     my ($requested_file)=@_;
                   8033:     foreach my $filename (sort(&scantron_filenames())) {
                   8034: 	if ($requested_file eq $filename) { return 1; }
                   8035:     }
                   8036:     return 0;
                   8037: }
                   8038: 
                   8039: sub scantron_download_scantron_data {
1.608     www      8040:     my ($r,$symb)=@_;
                   8041:     my $default_form_data=&defaultFormData($symb);
1.257     albertel 8042:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   8043:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
                   8044:     my $file=$env{'form.scantron_selectfile'};
1.202     albertel 8045:     if (! &valid_file($file)) {
1.492     albertel 8046: 	$r->print('
1.202     albertel 8047: 	<p>
1.492     albertel 8048: 	    '.&mt('The requested file name was invalid.').'
1.202     albertel 8049:         </p>
1.492     albertel 8050: ');
1.202     albertel 8051: 	return;
                   8052:     }
                   8053:     my $orig='/uploaded/'.$cdom.'/'.$cname.'/scantron_orig_'.$file;
                   8054:     my $corrected='/uploaded/'.$cdom.'/'.$cname.'/scantron_corrected_'.$file;
                   8055:     my $skipped='/uploaded/'.$cdom.'/'.$cname.'/scantron_skipped_'.$file;
                   8056:     &Apache::lonnet::allowuploaded('/adm/grades',$orig);
                   8057:     &Apache::lonnet::allowuploaded('/adm/grades',$corrected);
                   8058:     &Apache::lonnet::allowuploaded('/adm/grades',$skipped);
1.492     albertel 8059:     $r->print('
1.202     albertel 8060:     <p>
1.492     albertel 8061: 	'.&mt('[_1]Original[_2] file as uploaded by the scantron office.',
                   8062: 	      '<a href="'.$orig.'">','</a>').'
1.202     albertel 8063:     </p>
                   8064:     <p>
1.492     albertel 8065: 	'.&mt('[_1]Corrections[_2], a file of corrected records that were used in grading.',
                   8066: 	      '<a href="'.$corrected.'">','</a>').'
1.202     albertel 8067:     </p>
                   8068:     <p>
1.492     albertel 8069: 	'.&mt('[_1]Skipped[_2], a file of records that were skipped.',
                   8070: 	      '<a href="'.$skipped.'">','</a>').'
1.202     albertel 8071:     </p>
1.492     albertel 8072: ');
1.202     albertel 8073:     return '';
                   8074: }
1.157     albertel 8075: 
1.523     raeburn  8076: sub checkscantron_results {
1.608     www      8077:     my ($r,$symb) = @_;
1.523     raeburn  8078:     if (!$symb) {return '';}
                   8079:     my $cid = $env{'request.course.id'};
1.542     raeburn  8080:     my %lettdig = &letter_to_digits();
1.523     raeburn  8081:     my $numletts = scalar(keys(%lettdig));
                   8082:     my $cnum = $env{'course.'.$cid.'.num'};
                   8083:     my $cdom = $env{'course.'.$cid.'.domain'};
                   8084:     my (undef, undef, $sequence) = &Apache::lonnet::decode_symb($env{'form.selectpage'});
                   8085:     my %record;
                   8086:     my %scantron_config =
                   8087:         &Apache::grades::get_scantron_config($env{'form.scantron_format'});
                   8088:     my ($scanlines,$scan_data)=&Apache::grades::scantron_getfile();
                   8089:     my $classlist=&Apache::loncoursedata::get_classlist();
                   8090:     my %idmap=&Apache::grades::username_to_idmap($classlist);
                   8091:     my $navmap=Apache::lonnavmaps::navmap->new();
1.582     raeburn  8092:     unless (ref($navmap)) {
                   8093:         $r->print(&navmap_errormsg());
                   8094:         return '';
                   8095:     }
1.523     raeburn  8096:     my $map=$navmap->getResourceByUrl($sequence);
1.557     raeburn  8097:     my @resources=$navmap->retrieveResources($map,\&scantron_filter,1,0);
                   8098:     my (%grader_partids_by_symb,%grader_randomlists_by_symb);
                   8099:     &graders_resources_pass(\@resources,\%grader_partids_by_symb,                             \%grader_randomlists_by_symb);
                   8100: 
1.554     raeburn  8101:     my ($uname,$udom);
1.523     raeburn  8102:     my (%scandata,%lastname,%bylast);
                   8103:     $r->print('
                   8104: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="checkscantron">'."\n");
                   8105: 
                   8106:     my @delayqueue;
                   8107:     my %completedstudents;
                   8108: 
                   8109:     my $count=&Apache::grades::get_todo_count($scanlines,$scan_data);
1.581     www      8110:     my %prog_state=&Apache::lonhtmlcommon::Create_PrgWin($r,'Bubblesheet/Submissions Comparison Status',
                   8111:                                     'Progress of Bubblesheet Data/Submission Records Comparison',$count,
1.523     raeburn  8112:                                     'inline',undef,'checkscantron');
1.546     raeburn  8113:     my ($username,$domain,$started);
1.582     raeburn  8114:     my $nav_error;
                   8115:     &scantron_get_maxbubble(\$nav_error); # Need the bubble lines array to parse.
                   8116:     if ($nav_error) {
                   8117:         $r->print(&navmap_errormsg());
                   8118:         return '';
                   8119:     }
1.523     raeburn  8120: 
                   8121:     &Apache::lonhtmlcommon::Update_PrgWin($r,\%prog_state,
                   8122:                                           'Processing first student');
                   8123:     my $start=&Time::HiRes::time();
                   8124:     my $i=-1;
                   8125: 
                   8126:     while ($i<$scanlines->{'count'}) {
                   8127:         ($username,$domain,$uname)=('','','');
                   8128:         $i++;
                   8129:         my $line=&Apache::grades::scantron_get_line($scanlines,$scan_data,$i);
                   8130:         if ($line=~/^[\s\cz]*$/) { next; }
                   8131:         if ($started) {
                   8132:             &Apache::lonhtmlcommon::Increment_PrgWin($r,\%prog_state,
                   8133:                                                      'last student');
                   8134:         }
                   8135:         $started=1;
                   8136:         my $scan_record=
                   8137:             &Apache::grades::scantron_parse_scanline($line,$i,\%scantron_config,
                   8138:                                                      $scan_data);
                   8139:         unless ($uname=&Apache::grades::scantron_find_student($scan_record,$scan_data,
                   8140:                                                               \%idmap,$i)) {
                   8141:             &Apache::grades::scantron_add_delay(\@delayqueue,$line,
                   8142:                                 'Unable to find a student that matches',1);
                   8143:             next;
                   8144:         }
                   8145:         if (exists $completedstudents{$uname}) {
                   8146:             &Apache::grades::scantron_add_delay(\@delayqueue,$line,
                   8147:                                 'Student '.$uname.' has multiple sheets',2);
                   8148:             next;
                   8149:         }
                   8150:         my $pid = $scan_record->{'scantron.ID'};
                   8151:         $lastname{$pid} = $scan_record->{'scantron.LastName'};
                   8152:         push(@{$bylast{$lastname{$pid}}},$pid);
                   8153:         my $lastpos = $env{'form.scantron_maxbubble'}*$scantron_config{'Qlength'};
                   8154:         $scandata{$pid} = substr($line,$scantron_config{'Qstart'}-1,$lastpos);
                   8155:         chomp($scandata{$pid});
                   8156:         $scandata{$pid} =~ s/\r$//;
                   8157:         ($username,$domain)=split(/:/,$uname);
                   8158:         my $counter = -1;
                   8159:         foreach my $resource (@resources) {
1.557     raeburn  8160:             my $parts;
1.554     raeburn  8161:             my $ressymb = $resource->symb();
1.557     raeburn  8162:             if ((exists($grader_randomlists_by_symb{$ressymb})) ||
                   8163:                 (ref($grader_partids_by_symb{$ressymb}) ne 'ARRAY')) {
                   8164:                 (my $analysis,$parts) =
                   8165:                     &scantron_partids_tograde($resource,$env{'request.course.id'},$username,$domain);
                   8166:             } else {
                   8167:                 $parts = $grader_partids_by_symb{$ressymb};
                   8168:             }
1.542     raeburn  8169:             ($counter,my $recording) =
                   8170:                 &verify_scantron_grading($resource,$domain,$username,$cid,$counter,
1.554     raeburn  8171:                                          $scandata{$pid},$parts,
1.542     raeburn  8172:                                          \%scantron_config,\%lettdig,$numletts);
                   8173:             $record{$pid} .= $recording;
1.523     raeburn  8174:         }
                   8175:     }
                   8176:     &Apache::lonhtmlcommon::Close_PrgWin($r,\%prog_state);
                   8177:     $r->print('<br />');
                   8178:     my ($okstudents,$badstudents,$numstudents,$passed,$failed);
                   8179:     $passed = 0;
                   8180:     $failed = 0;
                   8181:     $numstudents = 0;
                   8182:     foreach my $last (sort(keys(%bylast))) {
                   8183:         if (ref($bylast{$last}) eq 'ARRAY') {
                   8184:             foreach my $pid (sort(@{$bylast{$last}})) {
                   8185:                 my $showscandata = $scandata{$pid};
                   8186:                 my $showrecord = $record{$pid};
                   8187:                 $showscandata =~ s/\s/&nbsp;/g;
                   8188:                 $showrecord =~ s/\s/&nbsp;/g;
                   8189:                 if ($scandata{$pid} eq $record{$pid}) {
                   8190:                     my $css_class = ($passed % 2)?'LC_odd_row':'LC_even_row';
                   8191:                     $okstudents .= '<tr class="'.$css_class.'">'.
1.581     www      8192: '<td>'.&mt('Bubblesheet').'</td><td>'.$showscandata.'</td><td rowspan="2">'.$last.'</td><td rowspan="2">'.$pid.'</td>'."\n".
1.523     raeburn  8193: '</tr>'."\n".
                   8194: '<tr class="'.$css_class.'">'."\n".
                   8195: '<td>Submissions</td><td>'.$showrecord.'</td></tr>'."\n";
                   8196:                     $passed ++;
                   8197:                 } else {
                   8198:                     my $css_class = ($failed % 2)?'LC_odd_row':'LC_even_row';
1.581     www      8199:                     $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  8200: '</tr>'."\n".
                   8201: '<tr class="'.$css_class.'">'."\n".
                   8202: '<td>Submissions</td><td><span class="LC_nobreak">'.$record{$pid}.'</span></td>'."\n".
                   8203: '</tr>'."\n";
                   8204:                     $failed ++;
                   8205:                 }
                   8206:                 $numstudents ++;
                   8207:             }
                   8208:         }
                   8209:     }
1.572     www      8210:     $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  8211:     $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>');
                   8212:     if ($passed) {
1.572     www      8213:         $r->print(&mt('Students with exact correspondence between bubblesheet data and submissions are as follows:').'<br /><br />');
1.523     raeburn  8214:         $r->print(&Apache::loncommon::start_data_table()."\n".
                   8215:                  &Apache::loncommon::start_data_table_header_row()."\n".
                   8216:                  '<th>'.&mt('Source').'</th><th>'.&mt('Bubble records').'</th><th>'.&mt('Name').'</th><th>'.&mt('ID').'</th>'.
                   8217:                  &Apache::loncommon::end_data_table_header_row()."\n".
                   8218:                  $okstudents."\n".
                   8219:                  &Apache::loncommon::end_data_table().'<br />');
                   8220:     }
                   8221:     if ($failed) {
1.572     www      8222:         $r->print(&mt('Students with differences between bubblesheet data and submissions are as follows:').'<br /><br />');
1.523     raeburn  8223:         $r->print(&Apache::loncommon::start_data_table()."\n".
                   8224:                  &Apache::loncommon::start_data_table_header_row()."\n".
                   8225:                  '<th>'.&mt('Source').'</th><th>'.&mt('Bubble records').'</th><th>'.&mt('Name').'</th><th>'.&mt('ID').'</th>'.
                   8226:                  &Apache::loncommon::end_data_table_header_row()."\n".
                   8227:                  $badstudents."\n".
                   8228:                  &Apache::loncommon::end_data_table()).'<br />'.
1.572     www      8229:                  &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  8230:     }
1.614     www      8231:     $r->print('</form><br />');
1.523     raeburn  8232:     return;
                   8233: }
                   8234: 
1.542     raeburn  8235: sub verify_scantron_grading {
1.554     raeburn  8236:     my ($resource,$domain,$username,$cid,$counter,$scandata,$partids,
1.542     raeburn  8237:         $scantron_config,$lettdig,$numletts) = @_;
                   8238:     my ($record,%expected,%startpos);
                   8239:     return ($counter,$record) if (!ref($resource));
                   8240:     return ($counter,$record) if (!$resource->is_problem());
                   8241:     my $symb = $resource->symb();
1.554     raeburn  8242:     return ($counter,$record) if (ref($partids) ne 'ARRAY');
                   8243:     foreach my $part_id (@{$partids}) {
1.542     raeburn  8244:         $counter ++;
                   8245:         $expected{$part_id} = 0;
                   8246:         if ($env{"form.scantron.sub_bubblelines.$counter"}) {
                   8247:             my @sub_lines = split(/,/,$env{"form.scantron.sub_bubblelines.$counter"});
                   8248:             foreach my $item (@sub_lines) {
                   8249:                 $expected{$part_id} += $item;
                   8250:             }
                   8251:         } else {
                   8252:             $expected{$part_id} = $env{"form.scantron.bubblelines.$counter"};
                   8253:         }
                   8254:         $startpos{$part_id} = $env{"form.scantron.first_bubble_line.$counter"};
                   8255:     }
                   8256:     if ($symb) {
                   8257:         my %recorded;
                   8258:         my (%returnhash) = &Apache::lonnet::restore($symb,$cid,$domain,$username);
                   8259:         if ($returnhash{'version'}) {
                   8260:             my %lasthash=();
                   8261:             my $version;
                   8262:             for ($version=1;$version<=$returnhash{'version'};$version++) {
                   8263:                 foreach my $key (sort(split(/\:/,$returnhash{$version.':keys'}))) {
                   8264:                     $lasthash{$key}=$returnhash{$version.':'.$key};
                   8265:                 }
                   8266:             }
                   8267:             foreach my $key (keys(%lasthash)) {
                   8268:                 if ($key =~ /\.scantron$/) {
                   8269:                     my $value = &unescape($lasthash{$key});
                   8270:                     my ($part_id) = ($key =~ /^resource\.(.+)\.scantron$/);
                   8271:                     if ($value eq '') {
                   8272:                         for (my $i=0; $i<$expected{$part_id}; $i++) {
                   8273:                             for (my $j=0; $j<$scantron_config->{'length'}; $j++) {
                   8274:                                 $recorded{$part_id} .= $scantron_config->{'Qoff'};
                   8275:                             }
                   8276:                         }
                   8277:                     } else {
                   8278:                         my @tocheck;
                   8279:                         my @items = split(//,$value);
                   8280:                         if (($scantron_config->{'Qon'} eq 'letter') ||
                   8281:                             ($scantron_config->{'Qon'} eq 'number')) {
                   8282:                             if (@items < $expected{$part_id}) {
                   8283:                                 my $fragment = substr($scandata,$startpos{$part_id},$expected{$part_id});
                   8284:                                 my @singles = split(//,$fragment);
                   8285:                                 foreach my $pos (@singles) {
                   8286:                                     if ($pos eq ' ') {
                   8287:                                         push(@tocheck,$pos);
                   8288:                                     } else {
                   8289:                                         my $next = shift(@items);
                   8290:                                         push(@tocheck,$next);
                   8291:                                     }
                   8292:                                 }
                   8293:                             } else {
                   8294:                                 @tocheck = @items;
                   8295:                             }
                   8296:                             foreach my $letter (@tocheck) {
                   8297:                                 if ($scantron_config->{'Qon'} eq 'letter') {
                   8298:                                     if ($letter !~ /^[A-J]$/) {
                   8299:                                         $letter = $scantron_config->{'Qoff'};
                   8300:                                     }
                   8301:                                     $recorded{$part_id} .= $letter;
                   8302:                                 } elsif ($scantron_config->{'Qon'} eq 'number') {
                   8303:                                     my $digit;
                   8304:                                     if ($letter !~ /^[A-J]$/) {
                   8305:                                         $digit = $scantron_config->{'Qoff'};
                   8306:                                     } else {
                   8307:                                         $digit = $lettdig->{$letter};
                   8308:                                     }
                   8309:                                     $recorded{$part_id} .= $digit;
                   8310:                                 }
                   8311:                             }
                   8312:                         } else {
                   8313:                             @tocheck = @items;
                   8314:                             for (my $i=0; $i<$expected{$part_id}; $i++) {
                   8315:                                 my $curr_sub = shift(@tocheck);
                   8316:                                 my $digit;
                   8317:                                 if ($curr_sub =~ /^[A-J]$/) {
                   8318:                                     $digit = $lettdig->{$curr_sub}-1;
                   8319:                                 }
                   8320:                                 if ($curr_sub eq 'J') {
                   8321:                                     $digit += scalar($numletts);
                   8322:                                 }
                   8323:                                 for (my $j=0; $j<$scantron_config->{'Qlength'}; $j++) {
                   8324:                                     if ($j == $digit) {
                   8325:                                         $recorded{$part_id} .= $scantron_config->{'Qon'};
                   8326:                                     } else {
                   8327:                                         $recorded{$part_id} .= $scantron_config->{'Qoff'};
                   8328:                                     }
                   8329:                                 }
                   8330:                             }
                   8331:                         }
                   8332:                     }
                   8333:                 }
                   8334:             }
                   8335:         }
1.554     raeburn  8336:         foreach my $part_id (@{$partids}) {
1.542     raeburn  8337:             if ($recorded{$part_id} eq '') {
                   8338:                 for (my $i=0; $i<$expected{$part_id}; $i++) {
                   8339:                     for (my $j=0; $j<$scantron_config->{'Qlength'}; $j++) {
                   8340:                         $recorded{$part_id} .= $scantron_config->{'Qoff'};
                   8341:                     }
                   8342:                 }
                   8343:             }
                   8344:             $record .= $recorded{$part_id};
                   8345:         }
                   8346:     }
                   8347:     return ($counter,$record);
                   8348: }
                   8349: 
                   8350: sub letter_to_digits { 
                   8351:     my %lettdig = (
                   8352:                     A => 1,
                   8353:                     B => 2,
                   8354:                     C => 3,
                   8355:                     D => 4,
                   8356:                     E => 5,
                   8357:                     F => 6,
                   8358:                     G => 7,
                   8359:                     H => 8,
                   8360:                     I => 9,
                   8361:                     J => 0,
                   8362:                   );
                   8363:     return %lettdig;
                   8364: }
                   8365: 
1.423     albertel 8366: 
1.75      albertel 8367: #-------- end of section for handling grading scantron forms -------
                   8368: #
                   8369: #-------------------------------------------------------------------
                   8370: 
1.72      ng       8371: #-------------------------- Menu interface -------------------------
                   8372: #
1.614     www      8373: #--- Href with symb and command ---
                   8374: 
                   8375: sub href_symb_cmd {
                   8376:     my ($symb,$cmd)=@_;
                   8377:     return '/adm/grades?symb='.&HTML::Entities::encode(&Apache::lonenc::check_encrypt($symb),'<>&"').'&command='.$cmd;
1.72      ng       8378: }
                   8379: 
1.443     banghart 8380: sub grading_menu {
1.608     www      8381:     my ($request,$symb) = @_;
1.443     banghart 8382:     if (!$symb) {return '';}
                   8383: 
                   8384:     my %fields = ('symb'=>&Apache::lonenc::check_encrypt($symb),
1.598     www      8385:                   'command'=>'individual',
1.443     banghart 8386:                   'gradingMenu'=>1,
                   8387:                   'showgrading'=>"yes");
1.538     schulted 8388:     
1.598     www      8389:     my $url1a = &Apache::lonhtmlcommon::build_url('grades/',\%fields);
                   8390: 
                   8391:     $fields{'command'}='ungraded';
                   8392:     my $url1b=&Apache::lonhtmlcommon::build_url('grades/',\%fields);
                   8393: 
                   8394:     $fields{'command'}='table';
                   8395:     my $url1c=&Apache::lonhtmlcommon::build_url('grades/',\%fields);
                   8396: 
                   8397:     $fields{'command'}='all_for_one';
                   8398:     my $url1d=&Apache::lonhtmlcommon::build_url('grades/',\%fields);
                   8399: 
1.443     banghart 8400:     $fields{'command'} = 'csvform';
1.538     schulted 8401:     my $url2 = &Apache::lonhtmlcommon::build_url('grades/',\%fields);
                   8402:     
1.443     banghart 8403:     $fields{'command'} = 'processclicker';
1.538     schulted 8404:     my $url3 = &Apache::lonhtmlcommon::build_url('grades/',\%fields);
                   8405:     
1.443     banghart 8406:     $fields{'command'} = 'scantron_selectphase';
1.538     schulted 8407:     my $url4 = &Apache::lonhtmlcommon::build_url('grades/',\%fields);
1.602     www      8408: 
                   8409:     $fields{'command'} = 'initialverifyreceipt';
                   8410:     my $url5 = &Apache::lonhtmlcommon::build_url('grades/',\%fields);
1.538     schulted 8411:     
1.598     www      8412:     my @menu = ({	categorytitle=>'Hand Grading',
1.538     schulted 8413:             items =>[
1.598     www      8414:                         {	linktext => 'Select individual students to grade',
                   8415:                     		url => $url1a,
1.538     schulted 8416:                     		permission => 'F',
                   8417:                     		icon => 'edit-find-replace.png',
1.598     www      8418:                     		linktitle => 'Grade current resource for a selection of students.'
                   8419:                         }, 
                   8420:                         {       linktext => 'Grade ungraded submissions.',
                   8421:                                 url => $url1b,
                   8422:                                 permission => 'F',
                   8423:                                 icon => 'edit-find-replace.png',
                   8424:                                 linktitle => 'Grade all submissions that have not been graded yet.'
1.538     schulted 8425:                         },
1.598     www      8426: 
                   8427:                         {       linktext => 'Grading table',
                   8428:                                 url => $url1c,
                   8429:                                 permission => 'F',
                   8430:                                 icon => 'edit-find-replace.png',
                   8431:                                 linktitle => 'Grade current resource for all students.'
                   8432:                         },
1.615     www      8433:                         {       linktext => 'Grade page/folder for one student',
1.598     www      8434:                                 url => $url1d,
                   8435:                                 permission => 'F',
                   8436:                                 icon => 'edit-find-replace.png',
                   8437:                                 linktitle => 'Grade all resources in current page/sequence/folder for one student.'
                   8438:                         }]},
                   8439:                          { categorytitle=>'Automated Grading',
                   8440:                items =>[
                   8441: 
1.538     schulted 8442:                 	    {	linktext => 'Upload Scores',
                   8443:                     		url => $url2,
                   8444:                     		permission => 'F',
                   8445:                     		icon => 'uploadscores.png',
                   8446:                     		linktitle => 'Specify a file containing the class scores for current resource.'
                   8447:                 	    },
                   8448:                 	    {	linktext => 'Process Clicker',
                   8449:                     		url => $url3,
                   8450:                     		permission => 'F',
                   8451:                     		icon => 'addClickerInfoFile.png',
                   8452:                     		linktitle => 'Specify a file containing the clicker information for this resource.'
                   8453:                 	    },
1.587     raeburn  8454:                 	    {	linktext => 'Grade/Manage/Review Bubblesheets',
1.538     schulted 8455:                     		url => $url4,
                   8456:                     		permission => 'F',
                   8457:                     		icon => 'stat.png',
                   8458:                     		linktitle => 'Grade scantron exams, upload/download scantron data files, and review previously graded scantron exams.'
1.602     www      8459:                 	    },
1.616   ! www      8460:                             {   linktext => 'Verify Receipt Number',
1.602     www      8461:                                 url => $url5,
                   8462:                                 permission => 'F',
                   8463:                                 icon => 'edit-find-replace.png',
                   8464:                                 linktitle => 'Verify a system-generated receipt number for correct problem solution.'
                   8465:                             }
                   8466: 
1.538     schulted 8467:                     ]
                   8468:             });
                   8469: 
1.443     banghart 8470:     # Create the menu
                   8471:     my $Str;
1.445     banghart 8472:     $Str .= '<form method="post" action="" name="gradingMenu">';
                   8473:     $Str .= '<input type="hidden" name="command" value="" />'.
                   8474:     	'<input type="hidden" name="symb"        value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
                   8475: 	'<input type="hidden" name="gradingMenu" value="1" />'."\n".
                   8476: 	'<input type="hidden" name="showgrading" value="yes" />'."\n";
                   8477: 
1.602     www      8478:     $Str .= &Apache::lonhtmlcommon::generate_menu(@menu);
1.443     banghart 8479:     return $Str;    
                   8480: }
                   8481: 
1.598     www      8482: 
                   8483: sub ungraded {
                   8484:     my ($request)=@_;
                   8485:     &submit_options($request);
                   8486: }
                   8487: 
1.599     www      8488: sub submit_options_sequence {
1.608     www      8489:     my ($request,$symb) = @_;
1.599     www      8490:     if (!$symb) {return '';}
1.600     www      8491:     &commonJSfunctions($request);
                   8492:     my $result;
1.599     www      8493: 
1.600     www      8494:     $result.='<form action="/adm/grades" method="post" name="gradingMenu">'."\n".
                   8495:         '<input type="hidden" name="symb"        value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
                   8496:         '<input type="hidden" name="gradingMenu" value="1" />'."\n".
                   8497:         '<input type="hidden" name="showgrading" value="yes" />'."\n";
                   8498: 
                   8499:     $result.='
                   8500: <h2>
1.615     www      8501:   '.&mt('Grade page/folder for one student').'
1.601     www      8502: </h2>'.
                   8503:             &selectfield(0).
                   8504:             '<input type="hidden" name="command" value="pickStudentPage" />
1.600     www      8505:             <div>
                   8506:               <input type="submit" value="'.&mt('Next').' &rarr;" />
                   8507:             </div>
                   8508:         </div>
                   8509:   </form>';
                   8510:     return $result;
                   8511: }
                   8512: 
                   8513: sub submit_options_table {
1.608     www      8514:     my ($request,$symb) = @_;
1.600     www      8515:     if (!$symb) {return '';}
1.599     www      8516:     &commonJSfunctions($request);
                   8517:     my $result;
                   8518: 
                   8519:     $result.='<form action="/adm/grades" method="post" name="gradingMenu">'."\n".
                   8520:         '<input type="hidden" name="symb"        value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
                   8521:         '<input type="hidden" name="gradingMenu" value="1" />'."\n".
                   8522:         '<input type="hidden" name="showgrading" value="yes" />'."\n";
                   8523: 
                   8524:     $result.='
                   8525: <h2>
1.600     www      8526:   '.&mt('Grading table').'
1.601     www      8527: </h2>'.
                   8528:             &selectfield(0).
                   8529:             '<input type="hidden" name="command" value="viewgrades" />
1.599     www      8530:             <div>
                   8531:               <input type="submit" value="'.&mt('Next').' &rarr;" />
                   8532:             </div>
                   8533:         </div>
                   8534:   </form>';
                   8535:     return $result;
                   8536: }
1.443     banghart 8537: 
1.600     www      8538: 
                   8539: 
1.443     banghart 8540: #--- Displays the submissions first page -------
                   8541: sub submit_options {
1.608     www      8542:     my ($request,$symb) = @_;
1.72      ng       8543:     if (!$symb) {return '';}
                   8544: 
1.118     ng       8545:     &commonJSfunctions($request);
1.473     albertel 8546:     my $result;
1.533     bisitz   8547: 
1.72      ng       8548:     $result.='<form action="/adm/grades" method="post" name="gradingMenu">'."\n".
1.418     albertel 8549: 	'<input type="hidden" name="symb"        value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
1.124     ng       8550: 	'<input type="hidden" name="gradingMenu" value="1" />'."\n".
1.72      ng       8551: 	'<input type="hidden" name="showgrading" value="yes" />'."\n";
                   8552: 
1.472     albertel 8553:     $result.='
1.533     bisitz   8554: <h2>
1.600     www      8555:   '.&mt('Select individual students to grade').'
1.601     www      8556: </h2>'.&selectfield(1).'
                   8557:                 <input type="hidden" name="command" value="submission" /> 
                   8558: 	      <input type="submit" value="'.&mt('Next').' &rarr;" />
                   8559:             </div>
                   8560:           </div>
                   8561: 
                   8562: 
                   8563:   </form>';
                   8564:     return $result;
                   8565: }
1.533     bisitz   8566: 
1.601     www      8567: sub selectfield {
                   8568:    my ($full)=@_;
                   8569:    my $result='<div class="LC_columnSection">
1.537     harmsja  8570:   
1.533     bisitz   8571:     <fieldset>
                   8572:       <legend>
                   8573:        '.&mt('Sections').'
                   8574:       </legend>
1.601     www      8575:       '.&Apache::lonstatistics::SectionSelect('section','multiple',5).'
1.533     bisitz   8576:     </fieldset>
1.537     harmsja  8577:   
1.533     bisitz   8578:     <fieldset>
                   8579:       <legend>
                   8580:         '.&mt('Groups').'
                   8581:       </legend>
                   8582:       '.&Apache::lonstatistics::GroupSelect('group','multiple',5).'
                   8583:     </fieldset>
1.537     harmsja  8584:   
1.533     bisitz   8585:     <fieldset>
                   8586:       <legend>
                   8587:         '.&mt('Access Status').'
                   8588:       </legend>
1.601     www      8589:       '.&Apache::lonhtmlcommon::StatusOptions(undef,undef,5,undef,'mult').'
                   8590:     </fieldset>';
                   8591:     if ($full) {
                   8592:        $result.='
1.533     bisitz   8593:     <fieldset>
                   8594:       <legend>
                   8595:         '.&mt('Submission Status').'
1.601     www      8596:       </legend>'.
                   8597:        &Apache::loncommon::select_form('all','submitonly',
                   8598:           (&Apache::lonlocal::texthash(
                   8599:              'yes'       => 'with submissions',
                   8600:              'queued'    => 'in grading queue',
                   8601:              'graded'    => 'with ungraded submissions',
                   8602:              'incorrect' => 'with incorrect submissions',
                   8603:              'all'       => 'with any status'),
                   8604:              'select_form_order' => ['yes','queued','graded','incorrect','all'])).
                   8605:    '</fieldset>';
                   8606:     }
                   8607:     $result.='</div><br />';
1.44      ng       8608:     return $result;
1.2       albertel 8609: }
                   8610: 
1.285     albertel 8611: sub reset_perm {
                   8612:     undef(%perm);
                   8613: }
                   8614: 
                   8615: sub init_perm {
                   8616:     &reset_perm();
1.300     albertel 8617:     foreach my $test_perm ('vgr','mgr','opa') {
                   8618: 
                   8619: 	my $scope = $env{'request.course.id'};
                   8620: 	if (!($perm{$test_perm}=&Apache::lonnet::allowed($test_perm,$scope))) {
                   8621: 
                   8622: 	    $scope .= '/'.$env{'request.course.sec'};
                   8623: 	    if ( $perm{$test_perm}=
                   8624: 		 &Apache::lonnet::allowed($test_perm,$scope)) {
                   8625: 		$perm{$test_perm.'_section'}=$env{'request.course.sec'};
                   8626: 	    } else {
                   8627: 		delete($perm{$test_perm});
                   8628: 	    }
1.285     albertel 8629: 	}
                   8630:     }
                   8631: }
                   8632: 
1.400     www      8633: sub gather_clicker_ids {
1.408     albertel 8634:     my %clicker_ids;
1.400     www      8635: 
                   8636:     my $classlist = &Apache::loncoursedata::get_classlist();
                   8637: 
                   8638:     # Set up a couple variables.
1.407     albertel 8639:     my $username_idx = &Apache::loncoursedata::CL_SNAME();
                   8640:     my $domain_idx   = &Apache::loncoursedata::CL_SDOM();
1.438     www      8641:     my $status_idx   = &Apache::loncoursedata::CL_STATUS();
1.400     www      8642: 
1.407     albertel 8643:     foreach my $student (keys(%$classlist)) {
1.438     www      8644:         if ($classlist->{$student}->[$status_idx] ne 'Active') { next; }
1.407     albertel 8645:         my $username = $classlist->{$student}->[$username_idx];
                   8646:         my $domain   = $classlist->{$student}->[$domain_idx];
1.400     www      8647:         my $clickers =
1.408     albertel 8648: 	    (&Apache::lonnet::userenvironment($domain,$username,'clickers'))[1];
1.400     www      8649:         foreach my $id (split(/\,/,$clickers)) {
1.414     www      8650:             $id=~s/^[\#0]+//;
1.421     www      8651:             $id=~s/[\-\:]//g;
1.407     albertel 8652:             if (exists($clicker_ids{$id})) {
1.408     albertel 8653: 		$clicker_ids{$id}.=','.$username.':'.$domain;
1.400     www      8654:             } else {
1.408     albertel 8655: 		$clicker_ids{$id}=$username.':'.$domain;
1.400     www      8656:             }
                   8657:         }
                   8658:     }
1.407     albertel 8659:     return %clicker_ids;
1.400     www      8660: }
                   8661: 
1.402     www      8662: sub gather_adv_clicker_ids {
1.408     albertel 8663:     my %clicker_ids;
1.402     www      8664:     my $cnum=$env{'course.'.$env{'request.course.id'}.'.num'};
                   8665:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
                   8666:     my %coursepersonnel=&Apache::lonnet::get_course_adv_roles($cdom.'/'.$cnum);
1.409     albertel 8667:     foreach my $element (sort(keys(%coursepersonnel))) {
1.402     www      8668:         foreach my $person (split(/\,/,$coursepersonnel{$element})) {
                   8669:             my ($puname,$pudom)=split(/\:/,$person);
                   8670:             my $clickers =
1.408     albertel 8671: 		(&Apache::lonnet::userenvironment($pudom,$puname,'clickers'))[1];
1.405     www      8672:             foreach my $id (split(/\,/,$clickers)) {
1.414     www      8673: 		$id=~s/^[\#0]+//;
1.421     www      8674:                 $id=~s/[\-\:]//g;
1.408     albertel 8675: 		if (exists($clicker_ids{$id})) {
                   8676: 		    $clicker_ids{$id}.=','.$puname.':'.$pudom;
                   8677: 		} else {
                   8678: 		    $clicker_ids{$id}=$puname.':'.$pudom;
                   8679: 		}
1.405     www      8680:             }
1.402     www      8681:         }
                   8682:     }
1.407     albertel 8683:     return %clicker_ids;
1.402     www      8684: }
                   8685: 
1.413     www      8686: sub clicker_grading_parameters {
                   8687:     return ('gradingmechanism' => 'scalar',
                   8688:             'upfiletype' => 'scalar',
                   8689:             'specificid' => 'scalar',
                   8690:             'pcorrect' => 'scalar',
                   8691:             'pincorrect' => 'scalar');
                   8692: }
                   8693: 
1.400     www      8694: sub process_clicker {
1.608     www      8695:     my ($r,$symb)=@_;
1.400     www      8696:     if (!$symb) {return '';}
                   8697:     my $result=&checkforfile_js();
                   8698:     $result.='<br /><table width="100%" border="0"><tr><td bgcolor="#777777">'."\n";
                   8699:     $result.='<table width="100%" border="0"><tr bgcolor="#e6ffff"><td>'."\n";
1.538     schulted 8700:     $result.='&nbsp;<b>'.&mt('Specify a file containing the clicker information for this resource.').
                   8701:         '</b></td></tr>'."\n";
1.601     www      8702:     $result.='<tr bgcolor="#ffffe6"><td>'."\n";
1.413     www      8703: # Attempt to restore parameters from last session, set defaults if not present
                   8704:     my %Saveable_Parameters=&clicker_grading_parameters();
                   8705:     &Apache::loncommon::restore_course_settings('grades_clicker',
                   8706:                                                  \%Saveable_Parameters);
                   8707:     if (!$env{'form.pcorrect'}) { $env{'form.pcorrect'}=100; }
                   8708:     if (!$env{'form.pincorrect'}) { $env{'form.pincorrect'}=100; }
                   8709:     if (!$env{'form.gradingmechanism'}) { $env{'form.gradingmechanism'}='attendance'; }
                   8710:     if (!$env{'form.upfiletype'}) { $env{'form.upfiletype'}='iclicker'; }
                   8711: 
                   8712:     my %checked;
1.521     www      8713:     foreach my $gradingmechanism ('attendance','personnel','specific','given') {
1.413     www      8714:        if ($env{'form.gradingmechanism'} eq $gradingmechanism) {
1.569     bisitz   8715:           $checked{$gradingmechanism}=' checked="checked"';
1.413     www      8716:        }
                   8717:     }
                   8718: 
1.400     www      8719:     my $upload=&mt("Upload File");
                   8720:     my $type=&mt("Type");
1.402     www      8721:     my $attendance=&mt("Award points just for participation");
                   8722:     my $personnel=&mt("Correctness determined from response by course personnel");
1.414     www      8723:     my $specific=&mt("Correctness determined from response with clicker ID(s)"); 
1.521     www      8724:     my $given=&mt("Correctness determined from given list of answers").' '.
                   8725:               '<font size="-2"><tt>('.&mt("Provide comma-separated list. Use '*' for any answer correct, '-' for skip").')</tt></font>';
1.402     www      8726:     my $pcorrect=&mt("Percentage points for correct solution");
                   8727:     my $pincorrect=&mt("Percentage points for incorrect solution");
1.413     www      8728:     my $selectform=&Apache::loncommon::select_form($env{'form.upfiletype'},'upfiletype',
1.419     www      8729: 						   ('iclicker' => 'i>clicker',
                   8730:                                                     'interwrite' => 'interwrite PRS'));
1.418     albertel 8731:     $symb = &Apache::lonenc::check_encrypt($symb);
1.597     wenzelju 8732:     $result.= &Apache::lonhtmlcommon::scripttag(<<ENDUPFORM);
1.402     www      8733: function sanitycheck() {
                   8734: // Accept only integer percentages
                   8735:    document.forms.gradesupload.pcorrect.value=Math.round(document.forms.gradesupload.pcorrect.value);
                   8736:    document.forms.gradesupload.pincorrect.value=Math.round(document.forms.gradesupload.pincorrect.value);
                   8737: // Find out grading choice
                   8738:    for (i=0; i<document.forms.gradesupload.gradingmechanism.length; i++) {
                   8739:       if (document.forms.gradesupload.gradingmechanism[i].checked) {
                   8740:          gradingchoice=document.forms.gradesupload.gradingmechanism[i].value;
                   8741:       }
                   8742:    }
                   8743: // By default, new choice equals user selection
                   8744:    newgradingchoice=gradingchoice;
                   8745: // Not good to give more points for false answers than correct ones
                   8746:    if (Math.round(document.forms.gradesupload.pcorrect.value)<Math.round(document.forms.gradesupload.pincorrect.value)) {
                   8747:       document.forms.gradesupload.pcorrect.value=document.forms.gradesupload.pincorrect.value;
                   8748:    }
                   8749: // If new choice is attendance only, and old choice was correctness-based, restore defaults
                   8750:    if ((gradingchoice=='attendance') && (document.forms.gradesupload.waschecked.value!='attendance')) {
                   8751:       document.forms.gradesupload.pcorrect.value=100;
                   8752:       document.forms.gradesupload.pincorrect.value=100;
                   8753:    }
                   8754: // If the values are different, cannot be attendance only
                   8755:    if ((Math.round(document.forms.gradesupload.pcorrect.value)!=Math.round(document.forms.gradesupload.pincorrect.value)) &&
                   8756:        (gradingchoice=='attendance')) {
                   8757:        newgradingchoice='personnel';
                   8758:    }
                   8759: // Change grading choice to new one
                   8760:    for (i=0; i<document.forms.gradesupload.gradingmechanism.length; i++) {
                   8761:       if (document.forms.gradesupload.gradingmechanism[i].value==newgradingchoice) {
                   8762:          document.forms.gradesupload.gradingmechanism[i].checked=true;
                   8763:       } else {
                   8764:          document.forms.gradesupload.gradingmechanism[i].checked=false;
                   8765:       }
                   8766:    }
                   8767: // Remember the old state
                   8768:    document.forms.gradesupload.waschecked.value=newgradingchoice;
                   8769: }
1.597     wenzelju 8770: ENDUPFORM
                   8771:     $result.= <<ENDUPFORM;
1.400     www      8772: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="gradesupload">
                   8773: <input type="hidden" name="symb" value="$symb" />
                   8774: <input type="hidden" name="command" value="processclickerfile" />
                   8775: <input type="file" name="upfile" size="50" />
                   8776: <br /><label>$type: $selectform</label>
1.589     bisitz   8777: <br /><label><input type="radio" name="gradingmechanism" value="attendance"$checked{'attendance'} onclick="sanitycheck()" />$attendance </label>
                   8778: <br /><label><input type="radio" name="gradingmechanism" value="personnel"$checked{'personnel'} onclick="sanitycheck()" />$personnel</label>
                   8779: <br /><label><input type="radio" name="gradingmechanism" value="specific"$checked{'specific'} onclick="sanitycheck()" />$specific </label>
1.414     www      8780: <input type="text" name="specificid" value="$env{'form.specificid'}" size="20" />
1.589     bisitz   8781: <br /><label><input type="radio" name="gradingmechanism" value="given"$checked{'given'} onclick="sanitycheck()" />$given </label>
1.521     www      8782: <br />&nbsp;&nbsp;&nbsp;
                   8783: <input type="text" name="givenanswer" size="50" />
1.413     www      8784: <input type="hidden" name="waschecked" value="$env{'form.gradingmechanism'}" />
1.589     bisitz   8785: <br /><label>$pcorrect: <input type="text" name="pcorrect" size="4" value="$env{'form.pcorrect'}" onchange="sanitycheck()" /></label>
                   8786: <br /><label>$pincorrect: <input type="text" name="pincorrect" size="4" value="$env{'form.pincorrect'}" onchange="sanitycheck()" /></label>
                   8787: <br /><input type="button" onclick="javascript:checkUpload(this.form);" value="$upload" />
1.597     wenzelju 8788: </form>'
1.400     www      8789: ENDUPFORM
                   8790:     $result.='</td></tr></table>'."\n".
                   8791:              '</td></tr></table><br /><br />'."\n";
                   8792:     return $result;
                   8793: }
                   8794: 
                   8795: sub process_clicker_file {
1.608     www      8796:     my ($r,$symb)=@_;
1.400     www      8797:     if (!$symb) {return '';}
1.413     www      8798: 
                   8799:     my %Saveable_Parameters=&clicker_grading_parameters();
                   8800:     &Apache::loncommon::store_course_settings('grades_clicker',
                   8801:                                               \%Saveable_Parameters);
1.598     www      8802:     my $result='';
1.404     www      8803:     if (($env{'form.gradingmechanism'} eq 'specific') && ($env{'form.specificid'}!~/\w/)) {
1.408     albertel 8804: 	$result.='<span class="LC_error">'.&mt('You need to specify a clicker ID for the correct answer').'</span>';
1.614     www      8805: 	return $result;
1.404     www      8806:     }
1.522     www      8807:     if (($env{'form.gradingmechanism'} eq 'given') && ($env{'form.givenanswer'}!~/\S/)) {
1.521     www      8808:         $result.='<span class="LC_error">'.&mt('You need to specify the correct answer').'</span>';
1.614     www      8809:         return $result;
1.521     www      8810:     }
1.522     www      8811:     my $foundgiven=0;
1.521     www      8812:     if ($env{'form.gradingmechanism'} eq 'given') {
                   8813:         $env{'form.givenanswer'}=~s/^\s*//gs;
                   8814:         $env{'form.givenanswer'}=~s/\s*$//gs;
                   8815:         $env{'form.givenanswer'}=~s/[^a-zA-Z0-9\.\*\-]+/\,/g;
                   8816:         $env{'form.givenanswer'}=uc($env{'form.givenanswer'});
1.522     www      8817:         my @answers=split(/\,/,$env{'form.givenanswer'});
                   8818:         $foundgiven=$#answers+1;
1.521     www      8819:     }
1.407     albertel 8820:     my %clicker_ids=&gather_clicker_ids();
1.408     albertel 8821:     my %correct_ids;
1.404     www      8822:     if ($env{'form.gradingmechanism'} eq 'personnel') {
1.408     albertel 8823: 	%correct_ids=&gather_adv_clicker_ids();
1.404     www      8824:     }
                   8825:     if ($env{'form.gradingmechanism'} eq 'specific') {
1.414     www      8826: 	foreach my $correct_id (split(/[\s\,]/,$env{'form.specificid'})) {;
                   8827: 	   $correct_id=~tr/a-z/A-Z/;
                   8828: 	   $correct_id=~s/\s//gs;
                   8829: 	   $correct_id=~s/^[\#0]+//;
1.421     www      8830:            $correct_id=~s/[\-\:]//g;
1.414     www      8831:            if ($correct_id) {
                   8832: 	      $correct_ids{$correct_id}='specified';
                   8833:            }
                   8834:         }
1.400     www      8835:     }
1.404     www      8836:     if ($env{'form.gradingmechanism'} eq 'attendance') {
1.408     albertel 8837: 	$result.=&mt('Score based on attendance only');
1.521     www      8838:     } elsif ($env{'form.gradingmechanism'} eq 'given') {
1.522     www      8839:         $result.=&mt('Score based on [_1] ([_2] answers)','<tt>'.$env{'form.givenanswer'}.'</tt>',$foundgiven);
1.404     www      8840:     } else {
1.408     albertel 8841: 	my $number=0;
1.411     www      8842: 	$result.='<p><b>'.&mt('Correctness determined by the following IDs').'</b>';
1.408     albertel 8843: 	foreach my $id (sort(keys(%correct_ids))) {
1.411     www      8844: 	    $result.='<br /><tt>'.$id.'</tt> - ';
1.408     albertel 8845: 	    if ($correct_ids{$id} eq 'specified') {
                   8846: 		$result.=&mt('specified');
                   8847: 	    } else {
                   8848: 		my ($uname,$udom)=split(/\:/,$correct_ids{$id});
                   8849: 		$result.=&Apache::loncommon::plainname($uname,$udom);
                   8850: 	    }
                   8851: 	    $number++;
                   8852: 	}
1.411     www      8853:         $result.="</p>\n";
1.408     albertel 8854: 	if ($number==0) {
                   8855: 	    $result.='<span class="LC_error">'.&mt('No IDs found to determine correct answer').'</span>';
1.614     www      8856: 	    return $result;
1.408     albertel 8857: 	}
1.404     www      8858:     }
1.405     www      8859:     if (length($env{'form.upfile'}) < 2) {
1.407     albertel 8860:         $result.=&mt('[_1] Error: [_2] The file you attempted to upload, [_3] contained no information. Please check that you entered the correct filename.',
                   8861: 		     '<span class="LC_error">',
                   8862: 		     '</span>',
                   8863: 		     '<span class="LC_filename">'.&HTML::Entities::encode($env{'form.upfile.filename'},'<>&"').'</span>');
1.614     www      8864:         return $result;
1.405     www      8865:     }
1.410     www      8866: 
                   8867: # Were able to get all the info needed, now analyze the file
                   8868: 
1.411     www      8869:     $result.=&Apache::loncommon::studentbrowser_javascript();
1.418     albertel 8870:     $symb = &Apache::lonenc::check_encrypt($symb);
1.410     www      8871:     my $heading=&mt('Scanning clicker file');
                   8872:     $result.=(<<ENDHEADER);
                   8873: <br /><table width="100%" border="0"><tr><td bgcolor="#777777">
                   8874: <table width="100%" border="0"><tr bgcolor="#e6ffff"><td>
                   8875: <b>$heading</b></td></tr><tr bgcolor=#ffffe6><td>
                   8876: <form method="post" action="/adm/grades" name="clickeranalysis">
                   8877: <input type="hidden" name="symb" value="$symb" />
                   8878: <input type="hidden" name="command" value="assignclickergrades" />
1.411     www      8879: <input type="hidden" name="gradingmechanism" value="$env{'form.gradingmechanism'}" />
                   8880: <input type="hidden" name="pcorrect" value="$env{'form.pcorrect'}" />
                   8881: <input type="hidden" name="pincorrect" value="$env{'form.pincorrect'}" />
1.410     www      8882: ENDHEADER
1.522     www      8883:     if ($env{'form.gradingmechanism'} eq 'given') {
                   8884:        $result.='<input type="hidden" name="correct:given" value="'.$env{'form.givenanswer'}.'" />';
                   8885:     } 
1.408     albertel 8886:     my %responses;
                   8887:     my @questiontitles;
1.405     www      8888:     my $errormsg='';
                   8889:     my $number=0;
                   8890:     if ($env{'form.upfiletype'} eq 'iclicker') {
1.408     albertel 8891: 	($errormsg,$number)=&iclicker_eval(\@questiontitles,\%responses);
1.406     www      8892:     }
1.419     www      8893:     if ($env{'form.upfiletype'} eq 'interwrite') {
                   8894:         ($errormsg,$number)=&interwrite_eval(\@questiontitles,\%responses);
                   8895:     }
1.411     www      8896:     $result.='<br />'.&mt('Found [_1] question(s)',$number).'<br />'.
                   8897:              '<input type="hidden" name="number" value="'.$number.'" />'.
                   8898:              &mt('Awarding [_1] percent for correct and [_2] percent for incorrect responses',
                   8899:                  $env{'form.pcorrect'},$env{'form.pincorrect'}).
                   8900:              '<br />';
1.522     www      8901:     if (($env{'form.gradingmechanism'} eq 'given') && ($number!=$foundgiven)) {
                   8902:        $result.='<span class="LC_error">'.&mt('Number of given answers does not agree with number of questions in file.').'</span>';
1.614     www      8903:        return $result;
1.522     www      8904:     } 
1.414     www      8905: # Remember Question Titles
                   8906: # FIXME: Possibly need delimiter other than ":"
                   8907:     for (my $i=0;$i<$number;$i++) {
                   8908:         $result.='<input type="hidden" name="question:'.$i.'" value="'.
                   8909:                  &HTML::Entities::encode($questiontitles[$i],'"&<>').'" />';
                   8910:     }
1.411     www      8911:     my $correct_count=0;
                   8912:     my $student_count=0;
                   8913:     my $unknown_count=0;
1.414     www      8914: # Match answers with usernames
                   8915: # FIXME: Possibly need delimiter other than ":"
1.409     albertel 8916:     foreach my $id (keys(%responses)) {
1.410     www      8917:        if ($correct_ids{$id}) {
1.414     www      8918:           $result.="\n".'<input type="hidden" name="correct:'.$correct_count.':'.$correct_ids{$id}.'" value="'.$responses{$id}.'" />';
1.411     www      8919:           $correct_count++;
1.410     www      8920:        } elsif ($clicker_ids{$id}) {
1.437     www      8921:           if ($clicker_ids{$id}=~/\,/) {
                   8922: # More than one user with the same clicker!
                   8923:              $result.="\n<hr />".&mt('Clicker registered more than once').": <tt>".$id."</tt><br />";
                   8924:              $result.="\n".'<input type="hidden" name="unknown:'.$id.'" value="'.$responses{$id}.'" />'.
                   8925:                            "<select name='multi".$id."'>";
                   8926:              foreach my $reguser (sort(split(/\,/,$clicker_ids{$id}))) {
                   8927:                  $result.="<option value='".$reguser."'>".&Apache::loncommon::plainname(split(/\:/,$reguser)).' ('.$reguser.')</option>';
                   8928:              }
                   8929:              $result.='</select>';
                   8930:              $unknown_count++;
                   8931:           } else {
                   8932: # Good: found one and only one user with the right clicker
                   8933:              $result.="\n".'<input type="hidden" name="student:'.$clicker_ids{$id}.'" value="'.$responses{$id}.'" />';
                   8934:              $student_count++;
                   8935:           }
1.410     www      8936:        } else {
1.411     www      8937:           $result.="\n<hr />".&mt('Unregistered Clicker')." <tt>".$id."</tt><br />";
                   8938:           $result.="\n".'<input type="hidden" name="unknown:'.$id.'" value="'.$responses{$id}.'" />'.
                   8939:                    "\n".&mt("Username").": <input type='text' name='uname".$id."' />&nbsp;".
                   8940:                    "\n".&mt("Domain").": ".
                   8941:                    &Apache::loncommon::select_dom_form($env{'course.'.$env{'request.course.id'}.'.domain'},'udom'.$id).'&nbsp;'.
                   8942:                    &Apache::loncommon::selectstudent_link('clickeranalysis','uname'.$id,'udom'.$id);
                   8943:           $unknown_count++;
1.410     www      8944:        }
1.405     www      8945:     }
1.412     www      8946:     $result.='<hr />'.
                   8947:              &mt('Found [_1] registered and [_2] unregistered clickers.',$student_count,$unknown_count);
1.521     www      8948:     if (($env{'form.gradingmechanism'} ne 'attendance') && ($env{'form.gradingmechanism'} ne 'given')) {
1.412     www      8949:        if ($correct_count==0) {
                   8950:           $errormsg.="Found no correct answers answers for grading!";
                   8951:        } elsif ($correct_count>1) {
1.414     www      8952:           $result.='<br /><span class="LC_warning">'.&mt("Found [_1] entries for grading!",$correct_count).'</span>';
1.412     www      8953:        }
                   8954:     }
1.428     www      8955:     if ($number<1) {
                   8956:        $errormsg.="Found no questions.";
                   8957:     }
1.412     www      8958:     if ($errormsg) {
                   8959:        $result.='<br /><span class="LC_error">'.&mt($errormsg).'</span>';
                   8960:     } else {
                   8961:        $result.='<br /><input type="submit" name="finalize" value="'.&mt('Finalize Grading').'" />';
                   8962:     }
                   8963:     $result.='</form></td></tr></table>'."\n".
1.410     www      8964:              '</td></tr></table><br /><br />'."\n";
1.614     www      8965:     return $result;
1.400     www      8966: }
                   8967: 
1.405     www      8968: sub iclicker_eval {
1.406     www      8969:     my ($questiontitles,$responses)=@_;
1.405     www      8970:     my $number=0;
                   8971:     my $errormsg='';
                   8972:     foreach my $line (split(/[\n\r]/,$env{'form.upfile'})) {
1.410     www      8973:         my %components=&Apache::loncommon::record_sep($line);
                   8974:         my @entries=map {$components{$_}} (sort(keys(%components)));
1.408     albertel 8975: 	if ($entries[0] eq 'Question') {
                   8976: 	    for (my $i=3;$i<$#entries;$i+=6) {
                   8977: 		$$questiontitles[$number]=$entries[$i];
                   8978: 		$number++;
                   8979: 	    }
                   8980: 	}
                   8981: 	if ($entries[0]=~/^\#/) {
                   8982: 	    my $id=$entries[0];
                   8983: 	    my @idresponses;
                   8984: 	    $id=~s/^[\#0]+//;
                   8985: 	    for (my $i=0;$i<$number;$i++) {
                   8986: 		my $idx=3+$i*6;
                   8987: 		push(@idresponses,$entries[$idx]);
                   8988: 	    }
                   8989: 	    $$responses{$id}=join(',',@idresponses);
                   8990: 	}
1.405     www      8991:     }
                   8992:     return ($errormsg,$number);
                   8993: }
                   8994: 
1.419     www      8995: sub interwrite_eval {
                   8996:     my ($questiontitles,$responses)=@_;
                   8997:     my $number=0;
                   8998:     my $errormsg='';
1.420     www      8999:     my $skipline=1;
                   9000:     my $questionnumber=0;
                   9001:     my %idresponses=();
1.419     www      9002:     foreach my $line (split(/[\n\r]/,$env{'form.upfile'})) {
                   9003:         my %components=&Apache::loncommon::record_sep($line);
                   9004:         my @entries=map {$components{$_}} (sort(keys(%components)));
1.420     www      9005:         if ($entries[1] eq 'Time') { $skipline=0; next; }
                   9006:         if ($entries[1] eq 'Response') { $skipline=1; }
                   9007:         next if $skipline;
                   9008:         if ($entries[0]!=$questionnumber) {
                   9009:            $questionnumber=$entries[0];
                   9010:            $$questiontitles[$number]=&mt('Question [_1]',$questionnumber);
                   9011:            $number++;
1.419     www      9012:         }
1.420     www      9013:         my $id=$entries[4];
                   9014:         $id=~s/^[\#0]+//;
1.421     www      9015:         $id=~s/^v\d*\://i;
                   9016:         $id=~s/[\-\:]//g;
1.420     www      9017:         $idresponses{$id}[$number]=$entries[6];
                   9018:     }
1.524     raeburn  9019:     foreach my $id (keys(%idresponses)) {
1.420     www      9020:        $$responses{$id}=join(',',@{$idresponses{$id}});
                   9021:        $$responses{$id}=~s/^\s*\,//;
1.419     www      9022:     }
                   9023:     return ($errormsg,$number);
                   9024: }
                   9025: 
1.414     www      9026: sub assign_clicker_grades {
1.608     www      9027:     my ($r,$symb)=@_;
1.414     www      9028:     if (!$symb) {return '';}
1.416     www      9029: # See which part we are saving to
1.582     raeburn  9030:     my $res_error;
                   9031:     my ($partlist,$handgrade,$responseType) = &response_type($symb,\$res_error);
                   9032:     if ($res_error) {
                   9033:         return &navmap_errormsg();
                   9034:     }
1.416     www      9035: # FIXME: This should probably look for the first handgradeable part
                   9036:     my $part=$$partlist[0];
                   9037: # Start screen output
1.598     www      9038:     my $result='';
1.416     www      9039: 
1.414     www      9040:     my $heading=&mt('Assigning grades based on clicker file');
                   9041:     $result.=(<<ENDHEADER);
                   9042: <br /><table width="100%" border="0"><tr><td bgcolor="#777777">
                   9043: <table width="100%" border="0"><tr bgcolor="#e6ffff"><td>
                   9044: <b>$heading</b></td></tr><tr bgcolor=#ffffe6><td>
                   9045: ENDHEADER
                   9046: # Get correct result
                   9047: # FIXME: Possibly need delimiter other than ":"
                   9048:     my @correct=();
1.415     www      9049:     my $gradingmechanism=$env{'form.gradingmechanism'};
                   9050:     my $number=$env{'form.number'};
                   9051:     if ($gradingmechanism ne 'attendance') {
1.414     www      9052:        foreach my $key (keys(%env)) {
                   9053:           if ($key=~/^form\.correct\:/) {
                   9054:              my @input=split(/\,/,$env{$key});
                   9055:              for (my $i=0;$i<=$#input;$i++) {
                   9056:                  if (($correct[$i]) && ($input[$i]) &&
                   9057:                      ($correct[$i] ne $input[$i])) {
                   9058:                     $result.='<br /><span class="LC_warning">'.
                   9059:                              &mt('More than one correct result given for question "[_1]": [_2] versus [_3].',
                   9060:                                  $env{'form.question:'.$i},$correct[$i],$input[$i]).'</span>';
                   9061:                  } elsif ($input[$i]) {
                   9062:                     $correct[$i]=$input[$i];
                   9063:                  }
                   9064:              }
                   9065:           }
                   9066:        }
1.415     www      9067:        for (my $i=0;$i<$number;$i++) {
1.414     www      9068:           if (!$correct[$i]) {
                   9069:              $result.='<br /><span class="LC_error">'.
                   9070:                       &mt('No correct result given for question "[_1]"!',
                   9071:                           $env{'form.question:'.$i}).'</span>';
                   9072:           }
                   9073:        }
                   9074:        $result.='<br />'.&mt("Correct answer: [_1]",join(', ',map { ($_?$_:'-') } @correct));
                   9075:     }
                   9076: # Start grading
1.415     www      9077:     my $pcorrect=$env{'form.pcorrect'};
                   9078:     my $pincorrect=$env{'form.pincorrect'};
1.416     www      9079:     my $storecount=0;
1.415     www      9080:     foreach my $key (keys(%env)) {
1.420     www      9081:        my $user='';
1.415     www      9082:        if ($key=~/^form\.student\:(.*)$/) {
1.420     www      9083:           $user=$1;
                   9084:        }
                   9085:        if ($key=~/^form\.unknown\:(.*)$/) {
                   9086:           my $id=$1;
                   9087:           if (($env{'form.uname'.$id}) && ($env{'form.udom'.$id})) {
                   9088:              $user=$env{'form.uname'.$id}.':'.$env{'form.udom'.$id};
1.437     www      9089:           } elsif ($env{'form.multi'.$id}) {
                   9090:              $user=$env{'form.multi'.$id};
1.420     www      9091:           }
                   9092:        }
                   9093:        if ($user) { 
1.415     www      9094:           my @answer=split(/\,/,$env{$key});
                   9095:           my $sum=0;
1.522     www      9096:           my $realnumber=$number;
1.415     www      9097:           for (my $i=0;$i<$number;$i++) {
1.576     www      9098:              if  ($correct[$i] eq '-') {
                   9099:                 $realnumber--;
                   9100:              } elsif ($answer[$i]) {
1.415     www      9101:                 if ($gradingmechanism eq 'attendance') {
                   9102:                    $sum+=$pcorrect;
1.576     www      9103:                 } elsif ($correct[$i] eq '*') {
1.522     www      9104:                    $sum+=$pcorrect;
1.415     www      9105:                 } else {
                   9106:                    if ($answer[$i] eq $correct[$i]) {
                   9107:                       $sum+=$pcorrect;
                   9108:                    } else {
                   9109:                       $sum+=$pincorrect;
                   9110:                    }
                   9111:                 }
                   9112:              }
                   9113:           }
1.522     www      9114:           my $ave=$sum/(100*$realnumber);
1.416     www      9115: # Store
                   9116:           my ($username,$domain)=split(/\:/,$user);
                   9117:           my %grades=();
                   9118:           $grades{"resource.$part.solved"}='correct_by_override';
                   9119:           $grades{"resource.$part.awarded"}=$ave;
                   9120:           $grades{"resource.regrader"}="$env{'user.name'}:$env{'user.domain'}";
                   9121:           my $returncode=&Apache::lonnet::cstore(\%grades,$symb,
                   9122:                                                  $env{'request.course.id'},
                   9123:                                                  $domain,$username);
                   9124:           if ($returncode ne 'ok') {
                   9125:              $result.="<br /><span class=\"LC_error\">Failed to save student $username:$domain. Message when trying to save was ($returncode)</span>";
                   9126:           } else {
                   9127:              $storecount++;
                   9128:           }
1.415     www      9129:        }
                   9130:     }
                   9131: # We are done
1.549     hauer    9132:     $result.='<br />'.&mt('Successfully stored grades for [quant,_1,student].',$storecount).
1.416     www      9133:              '</td></tr></table>'."\n".
1.414     www      9134:              '</td></tr></table><br /><br />'."\n";
1.614     www      9135:     return $result;
1.414     www      9136: }
                   9137: 
1.582     raeburn  9138: sub navmap_errormsg {
                   9139:     return '<div class="LC_error">'.
                   9140:            &mt('An error occurred retrieving information about resources in the course.').'<br />'.
1.595     raeburn  9141:            &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  9142:            '</div>';
                   9143: }
1.607     droeschl 9144: 
1.609     www      9145: sub startpage {
1.613     www      9146:     my ($r,$symb,$crumbs,$onlyfolderflag,$nodisplayflag) = @_;
1.614     www      9147:     unshift(@$crumbs,{href=>&href_symb_cmd($symb,'gradingmenu'),text=>"Grading"});
1.607     droeschl 9148:     $r->print(&Apache::loncommon::start_page('Grading',undef,
1.610     www      9149:                                           {'bread_crumbs' => $crumbs}));
1.613     www      9150:     unless ($nodisplayflag) {
                   9151:        $r->print(&Apache::lonhtmlcommon::resource_info_box($symb,$onlyfolderflag));
                   9152:     }
1.607     droeschl 9153: }
1.582     raeburn  9154: 
1.1       albertel 9155: sub handler {
1.41      ng       9156:     my $request=$_[0];
1.434     albertel 9157:     &reset_caches();
1.257     albertel 9158:     if ($env{'browser.mathml'}) {
1.141     www      9159: 	&Apache::loncommon::content_type($request,'text/xml');
1.41      ng       9160:     } else {
1.141     www      9161: 	&Apache::loncommon::content_type($request,'text/html');
1.41      ng       9162:     }
                   9163:     $request->send_http_header;
1.44      ng       9164:     return '' if $request->header_only;
1.41      ng       9165:     &Apache::loncommon::get_unprocessed_cgi($ENV{'QUERY_STRING'});
1.608     www      9166: 
                   9167: # see what command we need to execute
                   9168: 
1.160     albertel 9169:     my @commands=&Apache::loncommon::get_env_multiple('form.command');
                   9170:     my $command=$commands[0];
1.447     foxr     9171: 
1.160     albertel 9172:     if ($#commands > 0) {
                   9173: 	&Apache::lonnet::logthis("grades got multiple commands ".join(':',@commands));
                   9174:     }
1.608     www      9175: 
                   9176: # see what the symb is
                   9177: 
                   9178:     my $symb=$env{'form.symb'};
                   9179:     unless ($symb) {
                   9180:        (my $url=$env{'form.url'}) =~ s-^https*://($ENV{'SERVER_NAME'}|$ENV{'HTTP_HOST'})--;
                   9181:        $symb=&Apache::lonnet::symbread($url);
                   9182:     }
                   9183:     &Apache::lonenc::check_decrypt(\$symb);                             
                   9184: 
1.513     foxr     9185:     $ssi_error = 0;
1.324     albertel 9186:     if ($symb eq '' && $command eq '') {
1.601     www      9187: #
                   9188: # Not called from a resource
                   9189: #    
                   9190: 
1.41      ng       9191:     } else {
1.285     albertel 9192: 	&init_perm();
1.104     albertel 9193: 	if ($command eq 'submission' && $perm{'vgr'}) {
1.608     www      9194:             &startpage($request,$symb,[{href=>"", text=>"Student Submissions"}]);
1.611     www      9195: 	    ($env{'form.student'} eq '' ? &listStudents($request,$symb) : &submission($request,0,0,$symb));
1.103     albertel 9196: 	} elsif ($command eq 'pickStudentPage' && $perm{'vgr'}) {
1.615     www      9197:             &startpage($request,$symb,[{href=>&href_symb_cmd($symb,'all_for_one'),text=>'Grade page/folder for one student'},
                   9198:                                        {href=>'',text=>'Select student'}],1,1);
1.608     www      9199: 	    &pickStudentPage($request,$symb);
1.103     albertel 9200: 	} elsif ($command eq 'displayPage' && $perm{'vgr'}) {
1.615     www      9201:             &startpage($request,$symb,
                   9202:                                       [{href=>&href_symb_cmd($symb,'all_for_one'),text=>'Grade page/folder for one student'},
                   9203:                                        {href=>'',text=>'Select student'},
                   9204:                                        {href=>'',text=>'Grade student'}],1,1);
1.608     www      9205: 	    &displayPage($request,$symb);
1.104     albertel 9206: 	} elsif ($command eq 'gradeByPage' && $perm{'mgr'}) {
1.616   ! www      9207:             &startpage($request,$symb,[{href=>&href_symb_cmd($symb,'all_for_one'),text=>'Grade page/folder for one student'},
        !          9208:                                        {href=>'',text=>'Select student'},
        !          9209:                                        {href=>'',text=>'Grade student'},
        !          9210:                                        {href=>'',text=>'Store grades'}],1,1);
1.608     www      9211: 	    &updateGradeByPage($request,$symb);
1.104     albertel 9212: 	} elsif ($command eq 'processGroup' && $perm{'vgr'}) {
1.611     www      9213:             &startpage($request,$symb);
1.608     www      9214: 	    &processGroup($request,$symb);
1.104     albertel 9215: 	} elsif ($command eq 'gradingmenu' && $perm{'vgr'}) {
1.608     www      9216:             &startpage($request,$symb);
                   9217: 	    $request->print(&grading_menu($request,$symb));
1.598     www      9218: 	} elsif ($command eq 'individual' && $perm{'vgr'}) {
1.611     www      9219:             &startpage($request,$symb);
1.608     www      9220: 	    $request->print(&submit_options($request,$symb));
1.598     www      9221:         } elsif ($command eq 'ungraded' && $perm{'vgr'}) {
1.611     www      9222:             &startpage($request,$symb);
1.608     www      9223:             $request->print(&submit_options($request,$symb));
1.598     www      9224:         } elsif ($command eq 'table' && $perm{'vgr'}) {
1.614     www      9225:             &startpage($request,$symb,[{href=>"", text=>"Grading table"}]);
1.611     www      9226:             $request->print(&submit_options_table($request,$symb));
1.598     www      9227:         } elsif ($command eq 'all_for_one' && $perm{'vgr'}) {
1.615     www      9228:             &startpage($request,$symb,[{href=>'',text=>'Grade page/folder for one student'}],1,1);
1.608     www      9229:             $request->print(&submit_options_sequence($request,$symb));
1.104     albertel 9230: 	} elsif ($command eq 'viewgrades' && $perm{'vgr'}) {
1.614     www      9231:             &startpage($request,$symb,[{href=>&href_symb_cmd($symb,"table"), text=>"Grading table"},{href=>'', text=>"Modify grades"}]);
1.608     www      9232: 	    $request->print(&viewgrades($request,$symb));
1.104     albertel 9233: 	} elsif ($command eq 'handgrade' && $perm{'mgr'}) {
1.611     www      9234:             &startpage($request,$symb);
1.608     www      9235: 	    $request->print(&processHandGrade($request,$symb));
1.106     albertel 9236: 	} elsif ($command eq 'editgrades' && $perm{'mgr'}) {
1.614     www      9237:             &startpage($request,$symb,[{href=>&href_symb_cmd($symb,"table"), text=>"Grading table"},
                   9238:                                        {href=>&href_symb_cmd($symb,'viewgrades').'&group=all&section=all&Status=Active',
                   9239:                                                                              text=>"Modify grades"},
                   9240:                                        {href=>'', text=>"Store grades"}]);
1.608     www      9241: 	    $request->print(&editgrades($request,$symb));
1.602     www      9242:         } elsif ($command eq 'initialverifyreceipt' && $perm{'vgr'}) {
1.616   ! www      9243:             &startpage($request,$symb,[{href=>'',text=>'Verify Receipt Number'}]);
1.611     www      9244:             $request->print(&initialverifyreceipt($request,$symb));
1.106     albertel 9245: 	} elsif ($command eq 'verify' && $perm{'vgr'}) {
1.616   ! www      9246:             &startpage($request,$symb,[{href=>&href_symb_cmd($symb,"initialverifyreceipt"),text=>'Verify Receipt Number'},
        !          9247:                                        {href=>'',text=>'Verification Result'}]);
1.608     www      9248: 	    $request->print(&verifyreceipt($request,$symb));
1.400     www      9249:         } elsif ($command eq 'processclicker' && $perm{'mgr'}) {
1.615     www      9250:             &startpage($request,$symb,[{href=>'', text=>'Process clicker'}]);
1.608     www      9251:             $request->print(&process_clicker($request,$symb));
1.400     www      9252:         } elsif ($command eq 'processclickerfile' && $perm{'mgr'}) {
1.615     www      9253:             &startpage($request,$symb,[{href=>&href_symb_cmd($symb,'processclicker'), text=>'Process clicker'},
                   9254:                                        {href=>'', text=>'Process clicker file'}]);
1.608     www      9255:             $request->print(&process_clicker_file($request,$symb));
1.414     www      9256:         } elsif ($command eq 'assignclickergrades' && $perm{'mgr'}) {
1.615     www      9257:             &startpage($request,$symb,[{href=>&href_symb_cmd($symb,'processclicker'), text=>'Process clicker'},
                   9258:                                        {href=>'', text=>'Process clicker file'},
                   9259:                                        {href=>'', text=>'Store grades'}]);
1.608     www      9260:             $request->print(&assign_clicker_grades($request,$symb));
1.106     albertel 9261: 	} elsif ($command eq 'csvform' && $perm{'mgr'}) {
1.616   ! www      9262:             &startpage($request,$symb,[{href=>'', text=>'Grade/Manage/Review Bubblesheets'}],1,1);
1.608     www      9263: 	    $request->print(&upcsvScores_form($request,$symb));
1.106     albertel 9264: 	} elsif ($command eq 'csvupload' && $perm{'mgr'}) {
1.616   ! www      9265:             &startpage($request,$symb,[{href=>'', text=>'Grade/Manage/Review Bubblesheets'}],1,1);
1.608     www      9266: 	    $request->print(&csvupload($request,$symb));
1.106     albertel 9267: 	} elsif ($command eq 'csvuploadmap' && $perm{'mgr'} ) {
1.616   ! www      9268:             &startpage($request,$symb,[{href=>'', text=>'Grade/Manage/Review Bubblesheets'}],1,1);
1.608     www      9269: 	    $request->print(&csvuploadmap($request,$symb));
1.246     albertel 9270: 	} elsif ($command eq 'csvuploadoptions' && $perm{'mgr'}) {
1.257     albertel 9271: 	    if ($env{'form.associate'} ne 'Reverse Association') {
1.616   ! www      9272:                 &startpage($request,$symb,[{href=>'', text=>'Grade/Manage/Review Bubblesheets'}],1,1);
1.608     www      9273: 		$request->print(&csvuploadoptions($request,$symb));
1.41      ng       9274: 	    } else {
1.257     albertel 9275: 		if ( $env{'form.upfile_associate'} ne 'reverse' ) {
                   9276: 		    $env{'form.upfile_associate'} = 'reverse';
1.41      ng       9277: 		} else {
1.257     albertel 9278: 		    $env{'form.upfile_associate'} = 'forward';
1.41      ng       9279: 		}
1.616   ! www      9280:                 &startpage($request,$symb,[{href=>'', text=>'Grade/Manage/Review Bubblesheets'}],1,1);
1.608     www      9281: 		$request->print(&csvuploadmap($request,$symb));
1.41      ng       9282: 	    }
1.246     albertel 9283: 	} elsif ($command eq 'csvuploadassign' && $perm{'mgr'} ) {
1.616   ! www      9284:             &startpage($request,$symb,[{href=>'', text=>'Grade/Manage/Review Bubblesheets'}],1,1);
1.608     www      9285: 	    $request->print(&csvuploadassign($request,$symb));
1.106     albertel 9286: 	} elsif ($command eq 'scantron_selectphase' && $perm{'mgr'}) {
1.616   ! www      9287:             &startpage($request,$symb,[{href=>'', text=>'Grade/Manage/Review Bubblesheets'}],1,1);
1.612     www      9288: 	    $request->print(&scantron_selectphase($request,undef,$symb));
1.203     albertel 9289:  	} elsif ($command eq 'scantron_warning' && $perm{'mgr'}) {
1.616   ! www      9290:             &startpage($request,$symb,[{href=>'', text=>'Grade/Manage/Review Bubblesheets'}],1,1);
1.608     www      9291:  	    $request->print(&scantron_do_warning($request,$symb));
1.142     albertel 9292: 	} elsif ($command eq 'scantron_validate' && $perm{'mgr'}) {
1.616   ! www      9293:             &startpage($request,$symb,[{href=>'', text=>'Grade/Manage/Review Bubblesheets'}],1,1);
1.608     www      9294: 	    $request->print(&scantron_validate_file($request,$symb));
1.106     albertel 9295: 	} elsif ($command eq 'scantron_process' && $perm{'mgr'}) {
1.616   ! www      9296:             &startpage($request,$symb,[{href=>'', text=>'Grade/Manage/Review Bubblesheets'}],1,1);
1.608     www      9297: 	    $request->print(&scantron_process_students($request,$symb));
1.157     albertel 9298:  	} elsif ($command eq 'scantronupload' && 
1.257     albertel 9299:  		 (&Apache::lonnet::allowed('usc',$env{'request.role.domain'})||
                   9300: 		  &Apache::lonnet::allowed('usc',$env{'request.course.id'}))) {
1.616   ! www      9301:             &startpage($request,$symb,[{href=>'', text=>'Grade/Manage/Review Bubblesheets'}],1,1);
1.608     www      9302:  	    $request->print(&scantron_upload_scantron_data($request,$symb)); 
1.157     albertel 9303:  	} elsif ($command eq 'scantronupload_save' &&
1.257     albertel 9304:  		 (&Apache::lonnet::allowed('usc',$env{'request.role.domain'})||
                   9305: 		  &Apache::lonnet::allowed('usc',$env{'request.course.id'}))) {
1.616   ! www      9306:             &startpage($request,$symb,[{href=>'', text=>'Grade/Manage/Review Bubblesheets'}],1,1);
1.608     www      9307:  	    $request->print(&scantron_upload_scantron_data_save($request,$symb));
1.202     albertel 9308:  	} elsif ($command eq 'scantron_download' &&
1.257     albertel 9309: 		 &Apache::lonnet::allowed('usc',$env{'request.course.id'})) {
1.616   ! www      9310:             &startpage($request,$symb,[{href=>'', text=>'Grade/Manage/Review Bubblesheets'}],1,1);
1.608     www      9311:  	    $request->print(&scantron_download_scantron_data($request,$symb));
1.523     raeburn  9312:         } elsif ($command eq 'checksubmissions' && $perm{'vgr'}) {
1.616   ! www      9313:             &startpage($request,$symb,[{href=>'', text=>'Grade/Manage/Review Bubblesheets'}],1,1);
1.608     www      9314:             $request->print(&checkscantron_results($request,$symb));     
1.106     albertel 9315: 	} elsif ($command) {
1.611     www      9316:             &startpage($request,$symb);
1.562     bisitz   9317: 	    $request->print('<p class="LC_error">'.&mt('Access Denied ([_1])',$command).'</p>');
1.26      albertel 9318: 	}
1.2       albertel 9319:     }
1.513     foxr     9320:     if ($ssi_error) {
                   9321: 	&ssi_print_error($request);
                   9322:     }
1.353     albertel 9323:     $request->print(&Apache::loncommon::end_page());
1.434     albertel 9324:     &reset_caches();
1.44      ng       9325:     return '';
                   9326: }
                   9327: 
1.1       albertel 9328: 1;
                   9329: 
1.13      albertel 9330: __END__;
1.531     jms      9331: 
                   9332: 
                   9333: =head1 NAME
                   9334: 
                   9335: Apache::grades
                   9336: 
                   9337: =head1 SYNOPSIS
                   9338: 
                   9339: Handles the viewing of grades.
                   9340: 
                   9341: This is part of the LearningOnline Network with CAPA project
                   9342: described at http://www.lon-capa.org.
                   9343: 
                   9344: =head1 OVERVIEW
                   9345: 
                   9346: Do an ssi with retries:
                   9347: While I'd love to factor out this with the vesrion in lonprintout,
                   9348: 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
                   9349: I'm not quite ready to invent (e.g. an ssi_with_retry object).
                   9350: 
                   9351: At least the logic that drives this has been pulled out into loncommon.
                   9352: 
                   9353: 
                   9354: 
                   9355: ssi_with_retries - Does the server side include of a resource.
                   9356:                      if the ssi call returns an error we'll retry it up to
                   9357:                      the number of times requested by the caller.
                   9358:                      If we still have a proble, no text is appended to the
                   9359:                      output and we set some global variables.
                   9360:                      to indicate to the caller an SSI error occurred.  
                   9361:                      All of this is supposed to deal with the issues described
                   9362:                      in LonCAPA BZ 5631 see:
                   9363:                      http://bugs.lon-capa.org/show_bug.cgi?id=5631
                   9364:                      by informing the user that this happened.
                   9365: 
                   9366: Parameters:
                   9367:   resource   - The resource to include.  This is passed directly, without
                   9368:                interpretation to lonnet::ssi.
                   9369:   form       - The form hash parameters that guide the interpretation of the resource
                   9370:                
                   9371:   retries    - Number of retries allowed before giving up completely.
                   9372: Returns:
                   9373:   On success, returns the rendered resource identified by the resource parameter.
                   9374: Side Effects:
                   9375:   The following global variables can be set:
                   9376:    ssi_error                - If an unrecoverable error occurred this becomes true.
                   9377:                               It is up to the caller to initialize this to false
                   9378:                               if desired.
                   9379:    ssi_error_resource  - If an unrecoverable error occurred, this is the value
                   9380:                               of the resource that could not be rendered by the ssi
                   9381:                               call.
                   9382:    ssi_error_message   - The error string fetched from the ssi response
                   9383:                               in the event of an error.
                   9384: 
                   9385: 
                   9386: =head1 HANDLER SUBROUTINE
                   9387: 
                   9388: ssi_with_retries()
                   9389: 
                   9390: =head1 SUBROUTINES
                   9391: 
                   9392: =over
                   9393: 
                   9394: =item scantron_get_correction() : 
                   9395: 
                   9396:    Builds the interface screen to interact with the operator to fix a
                   9397:    specific error condition in a specific scanline
                   9398: 
                   9399:  Arguments:
                   9400:     $r           - Apache request object
                   9401:     $i           - number of the current scanline
                   9402:     $scan_record - hash ref as returned from &scantron_parse_scanline()
                   9403:     $scan_config - hash ref as returned from &get_scantron_config()
                   9404:     $line        - full contents of the current scanline
                   9405:     $error       - error condition, valid values are
                   9406:                    'incorrectCODE', 'duplicateCODE',
                   9407:                    'doublebubble', 'missingbubble',
                   9408:                    'duplicateID', 'incorrectID'
                   9409:     $arg         - extra information needed
                   9410:        For errors:
                   9411:          - duplicateID   - paper number that this studentID was seen before on
                   9412:          - duplicateCODE - array ref of the paper numbers this CODE was
                   9413:                            seen on before
                   9414:          - incorrectCODE - current incorrect CODE 
                   9415:          - doublebubble  - array ref of the bubble lines that have double
                   9416:                            bubble errors
                   9417:          - missingbubble - array ref of the bubble lines that have missing
                   9418:                            bubble errors
                   9419: 
                   9420: =item  scantron_get_maxbubble() : 
                   9421: 
1.582     raeburn  9422:    Arguments:
                   9423:        $nav_error  - Reference to scalar which is a flag to indicate a
                   9424:                       failure to retrieve a navmap object.
                   9425:        if $nav_error is set to 1 by scantron_get_maxbubble(), the 
                   9426:        calling routine should trap the error condition and display the warning
                   9427:        found in &navmap_errormsg().
                   9428: 
1.531     jms      9429:    Returns the maximum number of bubble lines that are expected to
                   9430:    occur. Does this by walking the selected sequence rendering the
                   9431:    resource and then checking &Apache::lonxml::get_problem_counter()
                   9432:    for what the current value of the problem counter is.
                   9433: 
                   9434:    Caches the results to $env{'form.scantron_maxbubble'},
                   9435:    $env{'form.scantron.bubble_lines.n'}, 
                   9436:    $env{'form.scantron.first_bubble_line.n'} and
                   9437:    $env{"form.scantron.sub_bubblelines.n"}
                   9438:    which are the total number of bubble, lines, the number of bubble
                   9439:    lines for response n and number of the first bubble line for response n,
                   9440:    and a comma separated list of numbers of bubble lines for sub-questions
                   9441:    (for optionresponse, matchresponse, and rankresponse items), for response n.  
                   9442: 
                   9443: 
                   9444: =item  scantron_validate_missingbubbles() : 
                   9445: 
                   9446:    Validates all scanlines in the selected file to not have any
                   9447:     answers that don't have bubbles that have not been verified
                   9448:     to be bubble free.
                   9449: 
                   9450: =item  scantron_process_students() : 
                   9451: 
                   9452:    Routine that does the actual grading of the bubble sheet information.
                   9453: 
                   9454:    The parsed scanline hash is added to %env 
                   9455: 
                   9456:    Then foreach unskipped scanline it does an &Apache::lonnet::ssi()
                   9457:    foreach resource , with the form data of
                   9458: 
                   9459: 	'submitted'     =>'scantron' 
                   9460: 	'grade_target'  =>'grade',
                   9461: 	'grade_username'=> username of student
                   9462: 	'grade_domain'  => domain of student
                   9463: 	'grade_courseid'=> of course
                   9464: 	'grade_symb'    => symb of resource to grade
                   9465: 
                   9466:     This triggers a grading pass. The problem grading code takes care
                   9467:     of converting the bubbled letter information (now in %env) into a
                   9468:     valid submission.
                   9469: 
                   9470: =item  scantron_upload_scantron_data() :
                   9471: 
                   9472:     Creates the screen for adding a new bubble sheet data file to a course.
                   9473: 
                   9474: =item  scantron_upload_scantron_data_save() : 
                   9475: 
                   9476:    Adds a provided bubble information data file to the course if user
                   9477:    has the correct privileges to do so. 
                   9478: 
                   9479: =item  valid_file() :
                   9480: 
                   9481:    Validates that the requested bubble data file exists in the course.
                   9482: 
                   9483: =item  scantron_download_scantron_data() : 
                   9484: 
                   9485:    Shows a list of the three internal files (original, corrected,
                   9486:    skipped) for a specific bubble sheet data file that exists in the
                   9487:    course.
                   9488: 
                   9489: =item  scantron_validate_ID() : 
                   9490: 
                   9491:    Validates all scanlines in the selected file to not have any
1.556     weissno  9492:    invalid or underspecified student/employee IDs
1.531     jms      9493: 
1.582     raeburn  9494: =item navmap_errormsg() :
                   9495: 
                   9496:    Returns HTML mark-up inside a <div></div> with a link to re-initialize the course.
                   9497:    Should be called whenever the request to instantiate a navmap object fails.  
                   9498: 
1.531     jms      9499: =back
                   9500: 
                   9501: =cut

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