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

1.17      albertel    1: # The LearningOnline Network with CAPA
1.13      albertel    2: # The LON-CAPA Grading handler
1.17      albertel    3: #
1.610   ! www         4: # $Id: grades.pm,v 1.609 2010/04/12 01:22:44 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.257     albertel  620: 	'<input type="hidden" name="saveState" value="'.$env{'form.saveState'}.'" />'."\n".
1.442     banghart  621: 	'<input type="hidden" name="Status"  value="'.$stu_status.'" />'."\n".
1.45      ng        622: 	'<input type="hidden" name="command" value="submission" />'."\n".
                    623: 	'<input type="hidden" name="student" value="" />'."\n".
                    624: 	'<input type="hidden" name="userdom" value="" />'."\n".
                    625: 	'</form>'."\n";
                    626:     return $jscript;
                    627: }
1.39      ng        628: 
1.447     foxr      629: 
                    630: 
1.315     bowersj2  631: # Given the score (as a number [0-1] and the weight) what is the final
                    632: # point value? This function will round to the nearest tenth, third,
                    633: # or quarter if one of those is within the tolerance of .00001.
1.316     albertel  634: sub compute_points {
1.315     bowersj2  635:     my ($score, $weight) = @_;
                    636:     
                    637:     my $tolerance = .00001;
                    638:     my $points = $score * $weight;
                    639: 
                    640:     # Check for nearness to 1/x.
                    641:     my $check_for_nearness = sub {
                    642:         my ($factor) = @_;
                    643:         my $num = ($points * $factor) + $tolerance;
                    644:         my $floored_num = floor($num);
1.316     albertel  645:         if ($num - $floored_num < 2 * $tolerance * $factor) {
1.315     bowersj2  646:             return $floored_num / $factor;
                    647:         }
                    648:         return $points;
                    649:     };
                    650: 
                    651:     $points = $check_for_nearness->(10);
                    652:     $points = $check_for_nearness->(3);
                    653:     $points = $check_for_nearness->(4);
                    654:     
                    655:     return $points;
                    656: }
                    657: 
1.44      ng        658: #------------------ End of general use routines --------------------
1.87      www       659: 
                    660: #
                    661: # Find most similar essay
                    662: #
                    663: 
                    664: sub most_similar {
1.426     albertel  665:     my ($uname,$udom,$uessay,$old_essays)=@_;
1.87      www       666: 
                    667: # ignore spaces and punctuation
                    668: 
                    669:     $uessay=~s/\W+/ /gs;
                    670: 
1.282     www       671: # ignore empty submissions (occuring when only files are sent)
                    672: 
1.598     www       673:     unless ($uessay=~/\w+/s) { return ''; }
1.282     www       674: 
1.87      www       675: # these will be returned. Do not care if not at least 50 percent similar
1.88      www       676:     my $limit=0.6;
1.87      www       677:     my $sname='';
                    678:     my $sdom='';
                    679:     my $scrsid='';
                    680:     my $sessay='';
                    681: # go through all essays ...
1.426     albertel  682:     foreach my $tkey (keys(%$old_essays)) {
                    683: 	my ($tname,$tdom,$tcrsid)=map {&unescape($_)} (split(/\./,$tkey));
1.87      www       684: # ... except the same student
1.426     albertel  685:         next if (($tname eq $uname) && ($tdom eq $udom));
                    686: 	my $tessay=$old_essays->{$tkey};
                    687: 	$tessay=~s/\W+/ /gs;
1.87      www       688: # String similarity gives up if not even limit
1.426     albertel  689: 	my $tsimilar=&String::Similarity::similarity($uessay,$tessay,$limit);
1.87      www       690: # Found one
1.426     albertel  691: 	if ($tsimilar>$limit) {
                    692: 	    $limit=$tsimilar;
                    693: 	    $sname=$tname;
                    694: 	    $sdom=$tdom;
                    695: 	    $scrsid=$tcrsid;
                    696: 	    $sessay=$old_essays->{$tkey};
                    697: 	}
1.87      www       698:     }
1.88      www       699:     if ($limit>0.6) {
1.87      www       700:        return ($sname,$sdom,$scrsid,$sessay,$limit);
                    701:     } else {
                    702:        return ('','','','',0);
                    703:     }
                    704: }
                    705: 
1.44      ng        706: #-------------------------------------------------------------------
                    707: 
                    708: #------------------------------------ Receipt Verification Routines
1.45      ng        709: #
1.602     www       710: 
                    711: sub initialverifyreceipt {
1.608     www       712:    my ($request,$symb) = @_;
1.602     www       713:    &commonJSfunctions($request);
1.605     www       714:    return '<form name="gradingMenu"><input type="submit" value="'.&mt('Verify Receipt Number.').'" />'.
1.602     www       715:         &Apache::lonnet::recprefix($env{'request.course.id'}).
                    716:         '-<input type="text" name="receipt" size="4" />'.
1.603     www       717:         '<input type="hidden" name="symb" value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
                    718:         '<input type="hidden" name="command" value="verify" />'.
                    719:         "</form>\n";
1.602     www       720: }
                    721: 
1.44      ng        722: #--- Check whether a receipt number is valid.---
                    723: sub verifyreceipt {
1.608     www       724:     my ($request,$symb)  = @_;
1.44      ng        725: 
1.257     albertel  726:     my $courseid = $env{'request.course.id'};
1.184     www       727:     my $receipt  = &Apache::lonnet::recprefix($courseid).'-'.
1.257     albertel  728: 	$env{'form.receipt'};
1.44      ng        729:     $receipt     =~ s/[^\-\d]//g;
                    730: 
1.487     albertel  731:     my $title.=
                    732: 	'<h3><span class="LC_info">'.
1.605     www       733: 	&mt('Verifying Receipt Number [_1]',$receipt).
                    734: 	'</span></h3>'."\n";
1.44      ng        735: 
                    736:     my ($string,$contents,$matches) = ('','',0);
1.56      matthew   737:     my (undef,undef,$fullname) = &getclasslist('all','0');
1.177     albertel  738:     
                    739:     my $receiptparts=0;
1.390     albertel  740:     if ($env{"course.$courseid.receiptalg"} eq 'receipt2' ||
                    741: 	$env{"course.$courseid.receiptalg"} eq 'receipt3') { $receiptparts=1; }
1.177     albertel  742:     my $parts=['0'];
1.582     raeburn   743:     if ($receiptparts) {
                    744:         my $res_error; 
                    745:         ($parts)=&response_type($symb,\$res_error);
                    746:         if ($res_error) {
                    747:             return &navmap_errormsg();
                    748:         } 
                    749:     }
1.486     albertel  750:     
                    751:     my $header = 
                    752: 	&Apache::loncommon::start_data_table().
                    753: 	&Apache::loncommon::start_data_table_header_row().
1.487     albertel  754: 	'<th>&nbsp;'.&mt('Fullname').'&nbsp;</th>'."\n".
                    755: 	'<th>&nbsp;'.&mt('Username').'&nbsp;</th>'."\n".
                    756: 	'<th>&nbsp;'.&mt('Domain').'&nbsp;</th>';
1.486     albertel  757:     if ($receiptparts) {
1.487     albertel  758: 	$header.='<th>&nbsp;'.&mt('Problem Part').'&nbsp;</th>';
1.486     albertel  759:     }
                    760:     $header.=
                    761: 	&Apache::loncommon::end_data_table_header_row();
                    762: 
1.294     albertel  763:     foreach (sort 
                    764: 	     {
                    765: 		 if (lc($$fullname{$a}) ne lc($$fullname{$b})) {
                    766: 		     return (lc($$fullname{$a}) cmp lc($$fullname{$b}));
                    767: 		 }
                    768: 		 return $a cmp $b;
                    769: 	     } (keys(%$fullname))) {
1.44      ng        770: 	my ($uname,$udom)=split(/\:/);
1.177     albertel  771: 	foreach my $part (@$parts) {
                    772: 	    if ($receipt eq &Apache::lonnet::ireceipt($uname,$udom,$courseid,$symb,$part)) {
1.486     albertel  773: 		$contents.=
                    774: 		    &Apache::loncommon::start_data_table_row().
                    775: 		    '<td>&nbsp;'."\n".
1.177     albertel  776: 		    '<a href="javascript:viewOneStudent(\''.$uname.'\',\''.$udom.
1.417     albertel  777: 		    '\');" target="_self">'.$$fullname{$_}.'</a>&nbsp;</td>'."\n".
1.177     albertel  778: 		    '<td>&nbsp;'.$uname.'&nbsp;</td>'.
                    779: 		    '<td>&nbsp;'.$udom.'&nbsp;</td>';
                    780: 		if ($receiptparts) {
                    781: 		    $contents.='<td>&nbsp;'.$part.'&nbsp;</td>';
                    782: 		}
1.486     albertel  783: 		$contents.= 
                    784: 		    &Apache::loncommon::end_data_table_row()."\n";
1.177     albertel  785: 		
                    786: 		$matches++;
                    787: 	    }
1.44      ng        788: 	}
                    789:     }
                    790:     if ($matches == 0) {
1.584     bisitz    791:         $string = $title
                    792:                  .'<p class="LC_warning">'
                    793:                  .&mt('No match found for the above receipt number.')
                    794:                  .'</p>';
1.44      ng        795:     } else {
1.324     albertel  796: 	$string = &jscriptNform($symb).$title.
1.487     albertel  797: 	    '<p>'.
1.584     bisitz    798: 	    &mt('The above receipt number matches the following [quant,_1,student].',$matches).
1.487     albertel  799: 	    '</p>'.
1.486     albertel  800: 	    $header.
                    801: 	    $contents.
                    802: 	    &Apache::loncommon::end_data_table()."\n";
1.44      ng        803:     }
1.324     albertel  804:     return $string.&show_grading_menu_form($symb);
1.44      ng        805: }
                    806: 
                    807: #--- This is called by a number of programs.
                    808: #--- Called from the Grading Menu - View/Grade an individual student
                    809: #--- Also called directly when one clicks on the subm button 
                    810: #    on the problem page.
1.30      ng        811: sub listStudents {
1.608     www       812:     my ($request,$symb) = @_;
1.49      albertel  813: 
1.257     albertel  814:     my $cdom      = $env{"course.$env{'request.course.id'}.domain"};
                    815:     my $cnum      = $env{"course.$env{'request.course.id'}.num"};
                    816:     my $getsec    = $env{'form.section'} eq '' ? 'all' : $env{'form.section'};
1.449     banghart  817:     my $getgroup  = $env{'form.group'} eq '' ? 'all' : $env{'form.group'};
1.257     albertel  818:     my $submitonly= $env{'form.submitonly'} eq '' ? 'all' : $env{'form.submitonly'};
1.548     bisitz    819:     my $viewgrade = $env{'form.showgrading'} eq 'yes' ? 'View/Grade/Regrade' : 'View';
1.49      albertel  820: 
1.548     bisitz    821:     my $result='<h3><span class="LC_info">&nbsp;'
                    822: 	.&mt("$viewgrade Submissions for a Student or a Group of Students")
1.485     albertel  823: 	.'</span></h3>';
1.118     ng        824: 
1.598     www       825:     my ($partlist,$handgrade,$responseType) = &response_type($symb
                    826: #,$res_error
                    827:     );
1.49      albertel  828: 
1.559     raeburn   829:     my %lt = &Apache::lonlocal::texthash (
                    830: 		'multiple' => 'Please select a student or group of students before clicking on the Next button.',
                    831: 		'single'   => 'Please select the student before clicking on the Next button.',
                    832: 	     );
1.597     wenzelju  833:     $request->print(&Apache::lonhtmlcommon::scripttag(<<LISTJAVASCRIPT));
1.110     ng        834:     function checkSelect(checkBox) {
                    835: 	var ctr=0;
                    836: 	var sense="";
                    837: 	if (checkBox.length > 1) {
                    838: 	    for (var i=0; i<checkBox.length; i++) {
                    839: 		if (checkBox[i].checked) {
                    840: 		    ctr++;
                    841: 		}
                    842: 	    }
1.485     albertel  843: 	    sense = '$lt{'multiple'}';
1.110     ng        844: 	} else {
                    845: 	    if (checkBox.checked) {
                    846: 		ctr = 1;
                    847: 	    }
1.485     albertel  848: 	    sense = '$lt{'single'}';
1.110     ng        849: 	}
                    850: 	if (ctr == 0) {
1.485     albertel  851: 	    alert(sense);
1.110     ng        852: 	    return false;
                    853: 	}
                    854: 	document.gradesub.submit();
                    855:     }
                    856: 
                    857:     function reLoadList(formname) {
1.112     ng        858: 	if (formname.saveStatusOld.value == pullDownSelection(formname.Status)) {return;}
1.110     ng        859: 	formname.command.value = 'submission';
                    860: 	formname.submit();
                    861:     }
1.45      ng        862: LISTJAVASCRIPT
                    863: 
1.118     ng        864:     &commonJSfunctions($request);
1.41      ng        865:     $request->print($result);
1.39      ng        866: 
1.401     albertel  867:     my $checkhdgrade = ($env{'form.handgrade'} eq 'yes' && scalar(@$partlist) > 1 ) ? 'checked="checked"' : '';
                    868:     my $checklastsub = $checkhdgrade eq '' ? 'checked="checked"' : '';
1.154     albertel  869:     my $gradeTable='<form action="/adm/grades" method="post" name="gradesub">'.
1.598     www       870: 	"\n";
1.485     albertel  871: 	
1.561     bisitz    872:     $gradeTable .= &Apache::lonhtmlcommon::start_pick_box();
                    873:     $gradeTable .= &Apache::lonhtmlcommon::row_title(&mt('View Problem Text'))
                    874:                   .'<label><input type="radio" name="vProb" value="no" checked="checked" /> '.&mt('no').' </label>'."\n"
                    875:                   .'<label><input type="radio" name="vProb" value="yes" /> '.&mt('one student').' </label>'."\n"
                    876:                   .'<label><input type="radio" name="vProb" value="all" /> '.&mt('all students').' </label><br />'."\n"
                    877:                   .&Apache::lonhtmlcommon::row_closure();
                    878:     $gradeTable .= &Apache::lonhtmlcommon::row_title(&mt('View Answer'))
                    879:                   .'<label><input type="radio" name="vAns" value="no"  /> '.&mt('no').' </label>'."\n"
                    880:                   .'<label><input type="radio" name="vAns" value="yes" /> '.&mt('one student').' </label>'."\n"
                    881:                   .'<label><input type="radio" name="vAns" value="all" checked="checked" /> '.&mt('all students').' </label><br />'."\n"
                    882:                   .&Apache::lonhtmlcommon::row_closure();
1.485     albertel  883: 
                    884:     my $submission_options;
1.257     albertel  885:     if ($env{'form.handgrade'} eq 'yes' && scalar(@$partlist) > 1) {
1.485     albertel  886: 	$submission_options.=
                    887: 	    '<label><input type="radio" name="lastSub" value="hdgrade" '.$checkhdgrade.' /> '.&mt('essay part only').' </label>'."\n";
1.49      albertel  888:     }
1.442     banghart  889:     my $stu_status = join(':',&Apache::loncommon::get_env_multiple('form.Status'));
                    890:     my $saveStatus = $stu_status eq '' ? 'Active' : $stu_status;
1.257     albertel  891:     $env{'form.Status'} = $saveStatus;
1.485     albertel  892:     $submission_options.=
1.592     bisitz    893:         '<span class="LC_nobreak">'.
                    894:         '<label><input type="radio" name="lastSub" value="lastonly" '.$checklastsub.' /> '.
                    895:         &mt('last submission only').' </label></span>'."\n".
                    896:         '<span class="LC_nobreak">'.
                    897:         '<label><input type="radio" name="lastSub" value="last" /> '.
                    898:         &mt('last submission &amp; parts info').' </label></span>'."\n".
                    899:         '<span class="LC_nobreak">'.
                    900:         '<label><input type="radio" name="lastSub" value="datesub" /> '.
                    901:         &mt('by dates and submissions').'</label></span>'."\n".
                    902:         '<span class="LC_nobreak">'.
                    903:         '<label><input type="radio" name="lastSub" value="all" /> '.
                    904:         &mt('all details').'</label></span>';
1.561     bisitz    905:     $gradeTable .= &Apache::lonhtmlcommon::row_title(&mt('Submissions'))
                    906:                   .$submission_options
                    907:                   .&Apache::lonhtmlcommon::row_closure();
                    908: 
                    909:     $gradeTable .= &Apache::lonhtmlcommon::row_title(&mt('Grading Increments'))
                    910:                   .'<select name="increment">'
                    911:                   .'<option value="1">'.&mt('Whole Points').'</option>'
                    912:                   .'<option value=".5">'.&mt('Half Points').'</option>'
                    913:                   .'<option value=".25">'.&mt('Quarter Points').'</option>'
                    914:                   .'<option value=".1">'.&mt('Tenths of a Point').'</option>'
                    915:                   .'</select>'
                    916:                   .&Apache::lonhtmlcommon::row_closure();
1.485     albertel  917: 
                    918:     $gradeTable .= 
1.432     banghart  919:         &build_section_inputs().
1.45      ng        920: 	'<input type="hidden" name="submitonly"  value="'.$submitonly.'" />'."\n".
1.257     albertel  921: 	'<input type="hidden" name="handgrade"   value="'.$env{'form.handgrade'}.'" /><br />'."\n".
                    922: 	'<input type="hidden" name="showgrading" value="'.$env{'form.showgrading'}.'" /><br />'."\n".
                    923: 	'<input type="hidden" name="saveState"   value="'.$env{'form.saveState'}.'" />'."\n".
1.418     albertel  924: 	'<input type="hidden" name="symb" value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
1.110     ng        925: 	'<input type="hidden" name="saveStatusOld" value="'.$saveStatus.'" />'."\n";
                    926: 
1.257     albertel  927:     if (exists($env{'form.gradingMenu'}) && exists($env{'form.Status'})) {
1.561     bisitz    928: 	$gradeTable .= '<input type="hidden" name="Status" value="'.$stu_status.'" />'."\n";
1.124     ng        929:     } else {
1.561     bisitz    930:         $gradeTable .= &Apache::lonhtmlcommon::row_title(&mt('Student Status'))
                    931:                       .&Apache::lonhtmlcommon::StatusOptions(
                    932:                            $saveStatus,undef,1,'javascript:reLoadList(this.form);')
                    933:                       .&Apache::lonhtmlcommon::row_closure();
1.124     ng        934:     }
1.112     ng        935: 
1.561     bisitz    936:     $gradeTable .= &Apache::lonhtmlcommon::row_title(&mt('Check For Plagiarism'))
                    937:                   .'<input type="checkbox" name="checkPlag" checked="checked" />'
                    938:                   .&Apache::lonhtmlcommon::row_closure(1)
                    939:                   .&Apache::lonhtmlcommon::end_pick_box();
                    940: 
                    941:     $gradeTable .= '<p>'
                    942:                   .&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"
                    943:                   .'<input type="hidden" name="command" value="processGroup" />'
                    944:                   .'</p>';
1.249     albertel  945: 
                    946: # checkall buttons
                    947:     $gradeTable.=&check_script('gradesub', 'stuinfo');
1.110     ng        948:     $gradeTable.='<input type="button" '."\n".
1.589     bisitz    949:         'onclick="javascript:checkSelect(this.form.stuinfo);" '."\n".
                    950:         'value="'.&mt('Next').' &rarr;" /> <br />'."\n";
1.249     albertel  951:     $gradeTable.=&check_buttons();
1.450     banghart  952:     my ($classlist, undef, $fullname) = &getclasslist($getsec,'1',$getgroup);
1.474     albertel  953:     $gradeTable.= &Apache::loncommon::start_data_table().
                    954: 	&Apache::loncommon::start_data_table_header_row();
1.110     ng        955:     my $loop = 0;
                    956:     while ($loop < 2) {
1.485     albertel  957: 	$gradeTable.='<th>'.&mt('No.').'</th><th>'.&mt('Select').'</th>'.
                    958: 	    '<th>'.&nameUserString('header').'&nbsp;'.&mt('Section/Group').'</th>';
1.301     albertel  959: 	if ($env{'form.showgrading'} eq 'yes' 
                    960: 	    && $submitonly ne 'queued'
                    961: 	    && $submitonly ne 'all') {
1.485     albertel  962: 	    foreach my $part (sort(@$partlist)) {
                    963: 		my $display_part=
                    964: 		    &get_display_part((split(/_/,$part))[0],$symb);
                    965: 		$gradeTable.=
                    966: 		    '<th>'.&mt('Part: [_1] Status',$display_part).'</th>';
1.110     ng        967: 	    }
1.301     albertel  968: 	} elsif ($submitonly eq 'queued') {
1.474     albertel  969: 	    $gradeTable.='<th>'.&mt('Queue Status').'&nbsp;</th>';
1.110     ng        970: 	}
                    971: 	$loop++;
1.126     ng        972: #	$gradeTable.='<td></td>' if ($loop%2 ==1);
1.41      ng        973:     }
1.474     albertel  974:     $gradeTable.=&Apache::loncommon::end_data_table_header_row()."\n";
1.41      ng        975: 
1.45      ng        976:     my $ctr = 0;
1.294     albertel  977:     foreach my $student (sort 
                    978: 			 {
                    979: 			     if (lc($$fullname{$a}) ne lc($$fullname{$b})) {
                    980: 				 return (lc($$fullname{$a}) cmp lc($$fullname{$b}));
                    981: 			     }
                    982: 			     return $a cmp $b;
                    983: 			 }
                    984: 			 (keys(%$fullname))) {
1.41      ng        985: 	my ($uname,$udom) = split(/:/,$student);
1.301     albertel  986: 
1.110     ng        987: 	my %status = ();
1.301     albertel  988: 
                    989: 	if ($submitonly eq 'queued') {
                    990: 	    my %queue_status = 
                    991: 		&Apache::bridgetask::get_student_status($symb,$cdom,$cnum,
                    992: 							$udom,$uname);
                    993: 	    next if (!defined($queue_status{'gradingqueue'}));
                    994: 	    $status{'gradingqueue'} = $queue_status{'gradingqueue'};
                    995: 	}
                    996: 
                    997: 	if ($env{'form.showgrading'} eq 'yes' 
                    998: 	    && $submitonly ne 'queued'
                    999: 	    && $submitonly ne 'all') {
1.324     albertel 1000: 	    (%status) =&student_gradeStatus($symb,$udom,$uname,$partlist);
1.145     albertel 1001: 	    my $submitted = 0;
1.164     albertel 1002: 	    my $graded = 0;
1.248     albertel 1003: 	    my $incorrect = 0;
1.110     ng       1004: 	    foreach (keys(%status)) {
1.145     albertel 1005: 		$submitted = 1 if ($status{$_} ne 'nothing');
1.248     albertel 1006: 		$graded = 1 if ($status{$_} =~ /^ungraded/);
                   1007: 		$incorrect = 1 if ($status{$_} =~ /^incorrect/);
                   1008: 		
1.110     ng       1009: 		my ($foo,$partid,$foo1) = split(/\./,$_);
                   1010: 		if ($status{'resource.'.$partid.'.submitted_by'} ne '') {
1.145     albertel 1011: 		    $submitted = 0;
1.150     albertel 1012: 		    my ($part)=split(/\./,$partid);
1.110     ng       1013: 		    $gradeTable.='<input type="hidden" name="'.
1.150     albertel 1014: 			$student.':'.$part.':submitted_by" value="'.
1.110     ng       1015: 			$status{'resource.'.$partid.'.submitted_by'}.'" />';
                   1016: 		}
1.41      ng       1017: 	    }
1.248     albertel 1018: 	    
1.156     albertel 1019: 	    next if (!$submitted && ($submitonly eq 'yes' ||
                   1020: 				     $submitonly eq 'incorrect' ||
                   1021: 				     $submitonly eq 'graded'));
1.248     albertel 1022: 	    next if (!$graded && ($submitonly eq 'graded'));
                   1023: 	    next if (!$incorrect && $submitonly eq 'incorrect');
1.41      ng       1024: 	}
1.34      ng       1025: 
1.45      ng       1026: 	$ctr++;
1.249     albertel 1027: 	my $section = $classlist->{$student}->[&Apache::loncoursedata::CL_SECTION()];
1.452     banghart 1028:         my $group = $classlist->{$student}->[&Apache::loncoursedata::CL_GROUP()];
1.104     albertel 1029: 	if ( $perm{'vgr'} eq 'F' ) {
1.474     albertel 1030: 	    if ($ctr%2 ==1) {
                   1031: 		$gradeTable.= &Apache::loncommon::start_data_table_row();
                   1032: 	    }
1.126     ng       1033: 	    $gradeTable.='<td align="right">'.$ctr.'&nbsp;</td>'.
1.563     bisitz   1034:                '<td align="center"><label><input type="checkbox" name="stuinfo" value="'.
1.249     albertel 1035:                $student.':'.$$fullname{$student}.':::SECTION'.$section.
                   1036: 	       ')&nbsp;" />&nbsp;&nbsp;</label></td>'."\n".'<td>'.
                   1037: 	       &nameUserString(undef,$$fullname{$student},$uname,$udom).
1.474     albertel 1038: 	       '&nbsp;'.$section.($group ne '' ?'/'.$group:'').'</td>'."\n";
1.110     ng       1039: 
1.257     albertel 1040: 	    if ($env{'form.showgrading'} eq 'yes' && $submitonly ne 'all') {
1.524     raeburn  1041: 		foreach (sort(keys(%status))) {
1.485     albertel 1042: 		    next if ($_ =~ /^resource.*?submitted_by$/);
                   1043: 		    $gradeTable.='<td align="center">&nbsp;'.&mt($status{$_}).'&nbsp;</td>'."\n";
1.110     ng       1044: 		}
1.41      ng       1045: 	    }
1.126     ng       1046: #	    $gradeTable.='<td></td>' if ($ctr%2 ==1);
1.474     albertel 1047: 	    if ($ctr%2 ==0) {
                   1048: 		$gradeTable.=&Apache::loncommon::end_data_table_row()."\n";
                   1049: 	    }
1.41      ng       1050: 	}
                   1051:     }
1.110     ng       1052:     if ($ctr%2 ==1) {
1.126     ng       1053: 	$gradeTable.='<td>&nbsp;</td><td>&nbsp;</td><td>&nbsp;</td>';
1.301     albertel 1054: 	    if ($env{'form.showgrading'} eq 'yes' 
                   1055: 		&& $submitonly ne 'queued'
                   1056: 		&& $submitonly ne 'all') {
1.110     ng       1057: 		foreach (@$partlist) {
                   1058: 		    $gradeTable.='<td>&nbsp;</td>';
                   1059: 		}
1.301     albertel 1060: 	    } elsif ($submitonly eq 'queued') {
                   1061: 		$gradeTable.='<td>&nbsp;</td>';
1.110     ng       1062: 	    }
1.474     albertel 1063: 	$gradeTable.=&Apache::loncommon::end_data_table_row();
1.110     ng       1064:     }
                   1065: 
1.474     albertel 1066:     $gradeTable.=&Apache::loncommon::end_data_table()."\n".
1.589     bisitz   1067:         '<input type="button" '.
                   1068:         'onclick="javascript:checkSelect(this.form.stuinfo);" '.
                   1069:         'value="'.&mt('Next').' &rarr;" /></form>'."\n";
1.45      ng       1070:     if ($ctr == 0) {
1.96      albertel 1071: 	my $num_students=(scalar(keys(%$fullname)));
                   1072: 	if ($num_students eq 0) {
1.485     albertel 1073: 	    $gradeTable='<br />&nbsp;<span class="LC_warning">'.&mt('There are no students currently enrolled.').'</span>';
1.96      albertel 1074: 	} else {
1.171     albertel 1075: 	    my $submissions='submissions';
                   1076: 	    if ($submitonly eq 'incorrect') { $submissions = 'incorrect submissions'; }
                   1077: 	    if ($submitonly eq 'graded'   ) { $submissions = 'ungraded submissions'; }
1.301     albertel 1078: 	    if ($submitonly eq 'queued'   ) { $submissions = 'queued submissions'; }
1.398     albertel 1079: 	    $gradeTable='<br />&nbsp;<span class="LC_warning">'.
1.485     albertel 1080: 		&mt('No '.$submissions.' found for this resource for any students. ([_1] students checked for '.$submissions.')',
                   1081: 		    $num_students).
                   1082: 		'</span><br />';
1.96      albertel 1083: 	}
1.46      ng       1084:     } elsif ($ctr == 1) {
1.474     albertel 1085: 	$gradeTable =~ s/type="checkbox"/type="checkbox" checked="checked"/;
1.45      ng       1086:     }
1.324     albertel 1087:     $gradeTable.=&show_grading_menu_form($symb);
1.45      ng       1088:     $request->print($gradeTable);
1.44      ng       1089:     return '';
1.10      ng       1090: }
                   1091: 
1.44      ng       1092: #---- Called from the listStudents routine
1.249     albertel 1093: 
                   1094: sub check_script {
                   1095:     my ($form, $type)=@_;
1.597     wenzelju 1096:     my $chkallscript= &Apache::lonhtmlcommon::scripttag('
1.249     albertel 1097:     function checkall() {
                   1098:         for (i=0; i<document.forms.'.$form.'.elements.length; i++) {
                   1099:             ele = document.forms.'.$form.'.elements[i];
                   1100:             if (ele.name == "'.$type.'") {
                   1101:             document.forms.'.$form.'.elements[i].checked=true;
                   1102:                                        }
                   1103:         }
                   1104:     }
                   1105: 
                   1106:     function checksec() {
                   1107:         for (i=0; i<document.forms.'.$form.'.elements.length; i++) {
                   1108:             ele = document.forms.'.$form.'.elements[i];
                   1109:            string = document.forms.'.$form.'.chksec.value;
                   1110:            if
                   1111:           (ele.value.indexOf(":::SECTION"+string)>0) {
                   1112:               document.forms.'.$form.'.elements[i].checked=true;
                   1113:             }
                   1114:         }
                   1115:     }
                   1116: 
                   1117: 
                   1118:     function uncheckall() {
                   1119:         for (i=0; i<document.forms.'.$form.'.elements.length; i++) {
                   1120:             ele = document.forms.'.$form.'.elements[i];
                   1121:             if (ele.name == "'.$type.'") {
                   1122:             document.forms.'.$form.'.elements[i].checked=false;
                   1123:                                        }
                   1124:         }
                   1125:     }
                   1126: 
1.597     wenzelju 1127: '."\n");
1.249     albertel 1128:     return $chkallscript;
                   1129: }
                   1130: 
                   1131: sub check_buttons {
1.485     albertel 1132:     my $buttons.='<input type="button" onclick="checkall()" value="'.&mt('Check All').'" />';
                   1133:     $buttons.='<input type="button" onclick="uncheckall()" value="'.&mt('Uncheck All').'" />&nbsp;';
                   1134:     $buttons.='<input type="button" onclick="checksec()" value="'.&mt('Check Section/Group').'" />';
1.249     albertel 1135:     $buttons.='<input type="text" size="5" name="chksec" />&nbsp;';
                   1136:     return $buttons;
                   1137: }
                   1138: 
1.44      ng       1139: #     Displays the submissions for one student or a group of students
1.34      ng       1140: sub processGroup {
1.41      ng       1141:     my ($request)  = shift;
                   1142:     my $ctr        = 0;
1.155     albertel 1143:     my @stuchecked = &Apache::loncommon::get_env_multiple('form.stuinfo');
1.41      ng       1144:     my $total      = scalar(@stuchecked)-1;
1.45      ng       1145: 
1.396     banghart 1146:     foreach my $student (@stuchecked) {
                   1147: 	my ($uname,$udom,$fullname) = split(/:/,$student);
1.257     albertel 1148: 	$env{'form.student'}        = $uname;
                   1149: 	$env{'form.userdom'}        = $udom;
                   1150: 	$env{'form.fullname'}       = $fullname;
1.41      ng       1151: 	&submission($request,$ctr,$total);
                   1152: 	$ctr++;
                   1153:     }
                   1154:     return '';
1.35      ng       1155: }
1.34      ng       1156: 
1.44      ng       1157: #------------------------------------------------------------------------------------
                   1158: #
                   1159: #-------------------------- Next few routines handles grading by student, essentially
                   1160: #                           handles essay response type problem/part
                   1161: #
                   1162: #--- Javascript to handle the submission page functionality ---
                   1163: sub sub_page_js {
                   1164:     my $request = shift;
1.539     riegler  1165: 	    my $alertmsg = &mt('A number equal or greater than 0 is expected. Entered value = ');
1.597     wenzelju 1166:     $request->print(&Apache::lonhtmlcommon::scripttag(<<SUBJAVASCRIPT));
1.71      ng       1167:     function updateRadio(formname,id,weight) {
1.125     ng       1168: 	var gradeBox = formname["GD_BOX"+id];
                   1169: 	var radioButton = formname["RADVAL"+id];
                   1170: 	var oldpts = formname["oldpts"+id].value;
1.72      ng       1171: 	var pts = checkSolved(formname,id) == 'update' ? gradeBox.value : oldpts;
1.71      ng       1172: 	gradeBox.value = pts;
                   1173: 	var resetbox = false;
                   1174: 	if (isNaN(pts) || pts < 0) {
1.539     riegler  1175: 	    alert("$alertmsg"+pts);
1.71      ng       1176: 	    for (var i=0; i<radioButton.length; i++) {
                   1177: 		if (radioButton[i].checked) {
                   1178: 		    gradeBox.value = i;
                   1179: 		    resetbox = true;
                   1180: 		}
                   1181: 	    }
                   1182: 	    if (!resetbox) {
                   1183: 		formtextbox.value = "";
                   1184: 	    }
                   1185: 	    return;
1.44      ng       1186: 	}
1.71      ng       1187: 
                   1188: 	if (pts > weight) {
                   1189: 	    var resp = confirm("You entered a value ("+pts+
                   1190: 			       ") greater than the weight for the part. Accept?");
                   1191: 	    if (resp == false) {
1.125     ng       1192: 		gradeBox.value = oldpts;
1.71      ng       1193: 		return;
                   1194: 	    }
1.44      ng       1195: 	}
1.13      albertel 1196: 
1.71      ng       1197: 	for (var i=0; i<radioButton.length; i++) {
                   1198: 	    radioButton[i].checked=false;
                   1199: 	    if (pts == i && pts != "") {
                   1200: 		radioButton[i].checked=true;
                   1201: 	    }
                   1202: 	}
                   1203: 	updateSelect(formname,id);
1.125     ng       1204: 	formname["stores"+id].value = "0";
1.41      ng       1205:     }
1.5       albertel 1206: 
1.72      ng       1207:     function writeBox(formname,id,pts) {
1.125     ng       1208: 	var gradeBox = formname["GD_BOX"+id];
1.71      ng       1209: 	if (checkSolved(formname,id) == 'update') {
                   1210: 	    gradeBox.value = pts;
                   1211: 	} else {
1.125     ng       1212: 	    var oldpts = formname["oldpts"+id].value;
1.72      ng       1213: 	    gradeBox.value = oldpts;
1.125     ng       1214: 	    var radioButton = formname["RADVAL"+id];
1.71      ng       1215: 	    for (var i=0; i<radioButton.length; i++) {
                   1216: 		radioButton[i].checked=false;
1.72      ng       1217: 		if (i == oldpts) {
1.71      ng       1218: 		    radioButton[i].checked=true;
                   1219: 		}
                   1220: 	    }
1.41      ng       1221: 	}
1.125     ng       1222: 	formname["stores"+id].value = "0";
1.71      ng       1223: 	updateSelect(formname,id);
                   1224: 	return;
1.41      ng       1225:     }
1.44      ng       1226: 
1.71      ng       1227:     function clearRadBox(formname,id) {
                   1228: 	if (checkSolved(formname,id) == 'noupdate') {
                   1229: 	    updateSelect(formname,id);
                   1230: 	    return;
                   1231: 	}
1.125     ng       1232: 	gradeSelect = formname["GD_SEL"+id];
1.71      ng       1233: 	for (var i=0; i<gradeSelect.length; i++) {
                   1234: 	    if (gradeSelect[i].selected) {
                   1235: 		var selectx=i;
                   1236: 	    }
                   1237: 	}
1.125     ng       1238: 	var stores = formname["stores"+id];
1.71      ng       1239: 	if (selectx == stores.value) { return };
1.125     ng       1240: 	var gradeBox = formname["GD_BOX"+id];
1.71      ng       1241: 	gradeBox.value = "";
1.125     ng       1242: 	var radioButton = formname["RADVAL"+id];
1.71      ng       1243: 	for (var i=0; i<radioButton.length; i++) {
                   1244: 	    radioButton[i].checked=false;
                   1245: 	}
                   1246: 	stores.value = selectx;
                   1247:     }
1.5       albertel 1248: 
1.71      ng       1249:     function checkSolved(formname,id) {
1.125     ng       1250: 	if (formname["solved"+id].value == "correct_by_student" && formname.overRideScore.value == 'no') {
1.118     ng       1251: 	    var reply = confirm("This problem has been graded correct by the computer. Do you want to change the score?");
                   1252: 	    if (!reply) {return "noupdate";}
1.120     ng       1253: 	    formname.overRideScore.value = 'yes';
1.41      ng       1254: 	}
1.71      ng       1255: 	return "update";
1.13      albertel 1256:     }
1.71      ng       1257: 
                   1258:     function updateSelect(formname,id) {
1.125     ng       1259: 	formname["GD_SEL"+id][0].selected = true;
1.71      ng       1260: 	return;
1.41      ng       1261:     }
1.33      ng       1262: 
1.121     ng       1263: //=========== Check that a point is assigned for all the parts  ============
1.71      ng       1264:     function checksubmit(formname,val,total,parttot) {
1.121     ng       1265: 	formname.gradeOpt.value = val;
1.71      ng       1266: 	if (val == "Save & Next") {
                   1267: 	    for (i=0;i<=total;i++) {
                   1268: 		for (j=0;j<parttot;j++) {
1.125     ng       1269: 		    var partid = formname["partid"+i+"_"+j].value;
1.127     ng       1270: 		    if (formname["GD_SEL"+i+"_"+partid][0].selected) {
1.125     ng       1271: 			var points = formname["GD_BOX"+i+"_"+partid].value;
1.71      ng       1272: 			if (points == "") {
1.125     ng       1273: 			    var name = formname["name"+i].value;
1.129     ng       1274: 			    var studentID = (name != '' ? name : formname["unamedom"+i].value);
                   1275: 			    var resp = confirm("You did not assign a score for "+studentID+
                   1276: 					       ", part "+partid+". Continue?");
1.71      ng       1277: 			    if (resp == false) {
1.125     ng       1278: 				formname["GD_BOX"+i+"_"+partid].focus();
1.71      ng       1279: 				return false;
                   1280: 			    }
                   1281: 			}
                   1282: 		    }
                   1283: 		    
                   1284: 		}
                   1285: 	    }
                   1286: 	    
                   1287: 	}
1.121     ng       1288: 	if (val == "Grade Student") {
                   1289: 	    formname.showgrading.value = "yes";
                   1290: 	    if (formname.Status.value == "") {
                   1291: 		formname.Status.value = "Active";
                   1292: 	    }
                   1293: 	    formname.studentNo.value = total;
                   1294: 	}
1.120     ng       1295: 	formname.submit();
                   1296:     }
                   1297: 
1.71      ng       1298: //======= Check that a score is assigned for all the problems (page/sequence grading only) =========
                   1299:     function checkSubmitPage(formname,total) {
                   1300: 	noscore = new Array(100);
                   1301: 	var ptr = 0;
                   1302: 	for (i=1;i<total;i++) {
1.125     ng       1303: 	    var partid = formname["q_"+i].value;
1.127     ng       1304: 	    if (formname["GD_SEL"+i+"_"+partid][0].selected) {
1.125     ng       1305: 		var points = formname["GD_BOX"+i+"_"+partid].value;
                   1306: 		var status = formname["solved"+i+"_"+partid].value;
1.71      ng       1307: 		if (points == "" && status != "correct_by_student") {
                   1308: 		    noscore[ptr] = i;
                   1309: 		    ptr++;
                   1310: 		}
                   1311: 	    }
                   1312: 	}
                   1313: 	if (ptr != 0) {
                   1314: 	    var sense = ptr == 1 ? ": " : "s: ";
                   1315: 	    var prolist = "";
                   1316: 	    if (ptr == 1) {
                   1317: 		prolist = noscore[0];
                   1318: 	    } else {
                   1319: 		var i = 0;
                   1320: 		while (i < ptr-1) {
                   1321: 		    prolist += noscore[i]+", ";
                   1322: 		    i++;
                   1323: 		}
                   1324: 		prolist += "and "+noscore[i];
                   1325: 	    }
                   1326: 	    var resp = confirm("You did not assign any score for the following problem"+sense+prolist+". Continue?");
                   1327: 	    if (resp == false) {
                   1328: 		return false;
                   1329: 	    }
                   1330: 	}
1.45      ng       1331: 
1.71      ng       1332: 	formname.submit();
                   1333:     }
                   1334: SUBJAVASCRIPT
                   1335: }
1.45      ng       1336: 
1.71      ng       1337: #--- javascript for essay type problem --
                   1338: sub sub_page_kw_js {
                   1339:     my $request = shift;
1.80      ng       1340:     my $iconpath = $request->dir_config('lonIconsURL');
1.118     ng       1341:     &commonJSfunctions($request);
1.350     albertel 1342: 
1.597     wenzelju 1343:     my $inner_js_msg_central= &Apache::lonhtmlcommon::scripttag(<<INNERJS);
1.350     albertel 1344:     function checkInput() {
                   1345:       opener.document.SCORE.msgsub.value = opener.checkEntities(document.msgcenter.msgsub.value);
                   1346:       var nmsg   = opener.document.SCORE.savemsgN.value;
                   1347:       var usrctr = document.msgcenter.usrctr.value;
                   1348:       var newval = opener.document.SCORE["newmsg"+usrctr];
                   1349:       newval.value = opener.checkEntities(document.msgcenter.newmsg.value);
                   1350: 
                   1351:       var msgchk = "";
                   1352:       if (document.msgcenter.subchk.checked) {
                   1353:          msgchk = "msgsub,";
                   1354:       }
                   1355:       var includemsg = 0;
                   1356:       for (var i=1; i<=nmsg; i++) {
                   1357:           var opnmsg = opener.document.SCORE["savemsg"+i];
                   1358:           var frmmsg = document.msgcenter["msg"+i];
                   1359:           opnmsg.value = opener.checkEntities(frmmsg.value);
                   1360:           var showflg = opener.document.SCORE["shownOnce"+i];
                   1361:           showflg.value = "1";
                   1362:           var chkbox = document.msgcenter["msgn"+i];
                   1363:           if (chkbox.checked) {
                   1364:              msgchk += "savemsg"+i+",";
                   1365:              includemsg = 1;
                   1366:           }
                   1367:       }
                   1368:       if (document.msgcenter.newmsgchk.checked) {
                   1369:          msgchk += "newmsg"+usrctr;
                   1370:          includemsg = 1;
                   1371:       }
                   1372:       imgformname = opener.document.SCORE["mailicon"+usrctr];
                   1373:       imgformname.src = "$iconpath/"+((includemsg) ? "mailto.gif" : "mailbkgrd.gif");
                   1374:       var includemsg = opener.document.SCORE["includemsg"+usrctr];
                   1375:       includemsg.value = msgchk;
                   1376: 
                   1377:       self.close()
                   1378: 
                   1379:     }
                   1380: INNERJS
                   1381: 
1.597     wenzelju 1382:     my $inner_js_highlight_central= &Apache::lonhtmlcommon::scripttag(<<INNERJS);
1.351     albertel 1383:     function updateChoice(flag) {
                   1384:       opener.document.SCORE.kwclr.value = opener.radioSelection(document.hlCenter.kwdclr);
                   1385:       opener.document.SCORE.kwsize.value = opener.radioSelection(document.hlCenter.kwdsize);
                   1386:       opener.document.SCORE.kwstyle.value = opener.radioSelection(document.hlCenter.kwdstyle);
                   1387:       opener.document.SCORE.refresh.value = "on";
                   1388:       if (opener.document.SCORE.keywords.value!=""){
                   1389:          opener.document.SCORE.submit();
                   1390:       }
                   1391:       self.close()
                   1392:     }
                   1393: INNERJS
                   1394: 
                   1395:     my $start_page_msg_central = 
                   1396:         &Apache::loncommon::start_page('Message Central',$inner_js_msg_central,
                   1397: 				       {'js_ready'  => 1,
                   1398: 					'only_body' => 1,
                   1399: 					'bgcolor'   =>'#FFFFFF',});
                   1400:     my $end_page_msg_central = 
                   1401: 	&Apache::loncommon::end_page({'js_ready' => 1});
                   1402: 
                   1403: 
                   1404:     my $start_page_highlight_central = 
                   1405:         &Apache::loncommon::start_page('Highlight Central',
                   1406: 				       $inner_js_highlight_central,
1.350     albertel 1407: 				       {'js_ready'  => 1,
                   1408: 					'only_body' => 1,
                   1409: 					'bgcolor'   =>'#FFFFFF',});
1.351     albertel 1410:     my $end_page_highlight_central = 
1.350     albertel 1411: 	&Apache::loncommon::end_page({'js_ready' => 1});
                   1412: 
1.219     www      1413:     my $docopen=&Apache::lonhtmlcommon::javascript_docopen();
1.236     albertel 1414:     $docopen=~s/^document\.//;
1.539     riegler  1415:     my $alertmsg = &mt('Please select a word or group of words from document and then click this link.');
1.597     wenzelju 1416:     $request->print(&Apache::lonhtmlcommon::scripttag(<<SUBJAVASCRIPT));
1.45      ng       1417: 
1.44      ng       1418: //===================== Show list of keywords ====================
1.122     ng       1419:   function keywords(formname) {
                   1420:     var nret = prompt("Keywords list, separated by a space. Add/delete to list if desired.",formname.keywords.value);
1.44      ng       1421:     if (nret==null) return;
1.122     ng       1422:     formname.keywords.value = nret;
1.44      ng       1423: 
1.122     ng       1424:     if (formname.keywords.value != "") {
1.128     ng       1425: 	formname.refresh.value = "on";
1.122     ng       1426: 	formname.submit();
1.44      ng       1427:     }
                   1428:     return;
                   1429:   }
                   1430: 
                   1431: //===================== Script to view submitted by ==================
                   1432:   function viewSubmitter(submitter) {
                   1433:     document.SCORE.refresh.value = "on";
                   1434:     document.SCORE.NCT.value = "1";
                   1435:     document.SCORE.unamedom0.value = submitter;
                   1436:     document.SCORE.submit();
                   1437:     return;
                   1438:   }
                   1439: 
                   1440: //===================== Script to add keyword(s) ==================
                   1441:   function getSel() {
                   1442:     if (document.getSelection) txt = document.getSelection();
                   1443:     else if (document.selection) txt = document.selection.createRange().text;
                   1444:     else return;
                   1445:     var cleantxt = txt.replace(new RegExp('([\\f\\n\\r\\t\\v ])+', 'g')," ");
                   1446:     if (cleantxt=="") {
1.539     riegler  1447: 	alert("$alertmsg");
1.44      ng       1448: 	return;
                   1449:     }
                   1450:     var nret = prompt("Add selection to keyword list? Edit if desired.",cleantxt);
                   1451:     if (nret==null) return;
1.127     ng       1452:     document.SCORE.keywords.value = document.SCORE.keywords.value+" "+nret;
1.44      ng       1453:     if (document.SCORE.keywords.value != "") {
1.127     ng       1454: 	document.SCORE.refresh.value = "on";
1.44      ng       1455: 	document.SCORE.submit();
                   1456:     }
                   1457:     return;
                   1458:   }
                   1459: 
                   1460: //====================== Script for composing message ==============
1.80      ng       1461:    // preload images
                   1462:    img1 = new Image();
                   1463:    img1.src = "$iconpath/mailbkgrd.gif";
                   1464:    img2 = new Image();
                   1465:    img2.src = "$iconpath/mailto.gif";
                   1466: 
1.44      ng       1467:   function msgCenter(msgform,usrctr,fullname) {
                   1468:     var Nmsg  = msgform.savemsgN.value;
                   1469:     savedMsgHeader(Nmsg,usrctr,fullname);
                   1470:     var subject = msgform.msgsub.value;
1.127     ng       1471:     var msgchk = document.SCORE["includemsg"+usrctr].value;
1.44      ng       1472:     re = /msgsub/;
                   1473:     var shwsel = "";
                   1474:     if (re.test(msgchk)) { shwsel = "checked" }
1.123     ng       1475:     subject = (document.SCORE.shownSub.value == 0 ? checkEntities(subject) : subject);
                   1476:     displaySubject(checkEntities(subject),shwsel);
1.44      ng       1477:     for (var i=1; i<=Nmsg; i++) {
1.123     ng       1478: 	var testmsg = "savemsg"+i+",";
                   1479: 	re = new RegExp(testmsg,"g");
1.44      ng       1480: 	shwsel = "";
                   1481: 	if (re.test(msgchk)) { shwsel = "checked" }
1.125     ng       1482: 	var message = document.SCORE["savemsg"+i].value;
1.126     ng       1483: 	message = (document.SCORE["shownOnce"+i].value == 0 ? checkEntities(message) : message);
1.123     ng       1484: 	displaySavedMsg(i,message,shwsel); //I do not get it. w/o checkEntities on saved messages,
                   1485: 	                                   //any &lt; is already converted to <, etc. However, only once!!
1.44      ng       1486:     }
1.125     ng       1487:     newmsg = document.SCORE["newmsg"+usrctr].value;
1.44      ng       1488:     shwsel = "";
                   1489:     re = /newmsg/;
                   1490:     if (re.test(msgchk)) { shwsel = "checked" }
                   1491:     newMsg(newmsg,shwsel);
                   1492:     msgTail(); 
                   1493:     return;
                   1494:   }
                   1495: 
1.123     ng       1496:   function checkEntities(strx) {
                   1497:     if (strx.length == 0) return strx;
                   1498:     var orgStr = ["&", "<", ">", '"']; 
                   1499:     var newStr = ["&amp;", "&lt;", "&gt;", "&quot;"];
                   1500:     var counter = 0;
                   1501:     while (counter < 4) {
                   1502: 	strx = strReplace(strx,orgStr[counter],newStr[counter]);
                   1503: 	counter++;
                   1504:     }
                   1505:     return strx;
                   1506:   }
                   1507: 
                   1508:   function strReplace(strx, orgStr, newStr) {
                   1509:     return strx.split(orgStr).join(newStr);
                   1510:   }
                   1511: 
1.44      ng       1512:   function savedMsgHeader(Nmsg,usrctr,fullname) {
1.76      ng       1513:     var height = 70*Nmsg+250;
1.44      ng       1514:     var scrollbar = "no";
                   1515:     if (height > 600) {
                   1516: 	height = 600;
                   1517: 	scrollbar = "yes";
                   1518:     }
1.118     ng       1519:     var xpos = (screen.width-600)/2;
                   1520:     xpos = (xpos < 0) ? '0' : xpos;
                   1521:     var ypos = (screen.height-height)/2-30;
                   1522:     ypos = (ypos < 0) ? '0' : ypos;
                   1523: 
1.206     albertel 1524:     pWin = window.open('', 'MessageCenter', 'resizable=yes,toolbar=no,location=no,scrollbars='+scrollbar+',screenx='+xpos+',screeny='+ypos+',width=600,height='+height);
1.76      ng       1525:     pWin.focus();
                   1526:     pDoc = pWin.document;
1.219     www      1527:     pDoc.$docopen;
1.351     albertel 1528:     pDoc.write('$start_page_msg_central');
1.76      ng       1529: 
                   1530:     pDoc.write("<form action=\\"inactive\\" name=\\"msgcenter\\">");
                   1531:     pDoc.write("<input value=\\""+usrctr+"\\" name=\\"usrctr\\" type=\\"hidden\\">");
1.465     albertel 1532:     pDoc.write("<h3><span class=\\"LC_info\\">&nbsp;Compose Message for \"+fullname+\"<\\/span><\\/h3><br /><br />");
1.76      ng       1533: 
1.564     bisitz   1534:     pDoc.write('<table border="0" width="100%"><tr><td bgcolor="#777777">');
                   1535:     pDoc.write('<table border="0" width="100%"><tr bgcolor="#DDFFFF">');
1.465     albertel 1536:     pDoc.write("<td><b>Type<\\/b><\\/td><td><b>Include<\\/b><\\/td><td><b>Message<\\/td><\\/tr>");
1.44      ng       1537: }
                   1538:     function displaySubject(msg,shwsel) {
1.76      ng       1539:     pDoc = pWin.document;
                   1540:     pDoc.write("<tr bgcolor=\\"#ffffdd\\">");
1.465     albertel 1541:     pDoc.write("<td>Subject<\\/td>");
                   1542:     pDoc.write("<td align=\\"center\\"><input name=\\"subchk\\" type=\\"checkbox\\"" +shwsel+"><\\/td>");
                   1543:     pDoc.write("<td><input name=\\"msgsub\\" type=\\"text\\" value=\\""+msg+"\\"size=\\"60\\" maxlength=\\"80\\"><\\/td><\\/tr>");
1.44      ng       1544: }
                   1545: 
1.72      ng       1546:   function displaySavedMsg(ctr,msg,shwsel) {
1.76      ng       1547:     pDoc = pWin.document;
                   1548:     pDoc.write("<tr bgcolor=\\"#ffffdd\\">");
1.465     albertel 1549:     pDoc.write("<td align=\\"center\\">"+ctr+"<\\/td>");
                   1550:     pDoc.write("<td align=\\"center\\"><input name=\\"msgn"+ctr+"\\" type=\\"checkbox\\"" +shwsel+"><\\/td>");
                   1551:     pDoc.write("<td><textarea name=\\"msg"+ctr+"\\" cols=\\"60\\" rows=\\"3\\">"+msg+"<\\/textarea><\\/td><\\/tr>");
1.44      ng       1552: }
                   1553: 
                   1554:   function newMsg(newmsg,shwsel) {
1.76      ng       1555:     pDoc = pWin.document;
                   1556:     pDoc.write("<tr bgcolor=\\"#ffffdd\\">");
1.465     albertel 1557:     pDoc.write("<td align=\\"center\\">New<\\/td>");
                   1558:     pDoc.write("<td align=\\"center\\"><input name=\\"newmsgchk\\" type=\\"checkbox\\"" +shwsel+"><\\/td>");
                   1559:     pDoc.write("<td><textarea name=\\"newmsg\\" cols=\\"60\\" rows=\\"3\\" onchange=\\"javascript:this.form.newmsgchk.checked=true\\" >"+newmsg+"<\\/textarea><\\/td><\\/tr>");
1.44      ng       1560: }
                   1561: 
                   1562:   function msgTail() {
1.76      ng       1563:     pDoc = pWin.document;
1.465     albertel 1564:     pDoc.write("<\\/table>");
                   1565:     pDoc.write("<\\/td><\\/tr><\\/table>&nbsp;");
1.589     bisitz   1566:     pDoc.write("<input type=\\"button\\" value=\\"Save\\" onclick=\\"javascript:checkInput()\\">&nbsp;&nbsp;");
                   1567:     pDoc.write("<input type=\\"button\\" value=\\"Cancel\\" onclick=\\"self.close()\\"><br /><br />");
1.465     albertel 1568:     pDoc.write("<\\/form>");
1.351     albertel 1569:     pDoc.write('$end_page_msg_central');
1.128     ng       1570:     pDoc.close();
1.44      ng       1571: }
                   1572: 
                   1573: //====================== Script for keyword highlight options ==============
                   1574:   function kwhighlight() {
                   1575:     var kwclr    = document.SCORE.kwclr.value;
                   1576:     var kwsize   = document.SCORE.kwsize.value;
                   1577:     var kwstyle  = document.SCORE.kwstyle.value;
                   1578:     var redsel = "";
                   1579:     var grnsel = "";
                   1580:     var blusel = "";
                   1581:     if (kwclr=="red")   {var redsel="checked"};
                   1582:     if (kwclr=="green") {var grnsel="checked"};
                   1583:     if (kwclr=="blue")  {var blusel="checked"};
                   1584:     var sznsel = "";
                   1585:     var sz1sel = "";
                   1586:     var sz2sel = "";
                   1587:     if (kwsize=="0")  {var sznsel="checked"};
                   1588:     if (kwsize=="+1") {var sz1sel="checked"};
                   1589:     if (kwsize=="+2") {var sz2sel="checked"};
                   1590:     var synsel = "";
                   1591:     var syisel = "";
                   1592:     var sybsel = "";
                   1593:     if (kwstyle=="")    {var synsel="checked"};
                   1594:     if (kwstyle=="<i>") {var syisel="checked"};
                   1595:     if (kwstyle=="<b>") {var sybsel="checked"};
                   1596:     highlightCentral();
                   1597:     highlightbody('red','red',redsel,'0','normal',sznsel,'','normal',synsel);
                   1598:     highlightbody('green','green',grnsel,'+1','+1',sz1sel,'<i>','italic',syisel);
                   1599:     highlightbody('blue','blue',blusel,'+2','+2',sz2sel,'<b>','bold',sybsel);
                   1600:     highlightend();
                   1601:     return;
                   1602:   }
                   1603: 
                   1604:   function highlightCentral() {
1.76      ng       1605: //    if (window.hwdWin) window.hwdWin.close();
1.118     ng       1606:     var xpos = (screen.width-400)/2;
                   1607:     xpos = (xpos < 0) ? '0' : xpos;
                   1608:     var ypos = (screen.height-330)/2-30;
                   1609:     ypos = (ypos < 0) ? '0' : ypos;
                   1610: 
1.206     albertel 1611:     hwdWin = window.open('', 'KeywordHighlightCentral', 'resizeable=yes,toolbar=no,location=no,scrollbars=no,width=400,height=300,screenx='+xpos+',screeny='+ypos);
1.76      ng       1612:     hwdWin.focus();
                   1613:     var hDoc = hwdWin.document;
1.219     www      1614:     hDoc.$docopen;
1.351     albertel 1615:     hDoc.write('$start_page_highlight_central');
1.76      ng       1616:     hDoc.write("<form action=\\"inactive\\" name=\\"hlCenter\\">");
1.465     albertel 1617:     hDoc.write("<h3><span class=\\"LC_info\\">&nbsp;Keyword Highlight Options<\\/span><\\/h3><br /><br />");
1.76      ng       1618: 
1.564     bisitz   1619:     hDoc.write('<table border="0" width="100%"><tr><td bgcolor="#777777">');
                   1620:     hDoc.write('<table border="0" width="100%"><tr bgcolor="#DDFFFF">');
1.465     albertel 1621:     hDoc.write("<td><b>Text Color<\\/b><\\/td><td><b>Font Size<\\/b><\\/td><td><b>Font Style<\\/td><\\/tr>");
1.44      ng       1622:   }
                   1623: 
                   1624:   function highlightbody(clrval,clrtxt,clrsel,szval,sztxt,szsel,syval,sytxt,sysel) { 
1.76      ng       1625:     var hDoc = hwdWin.document;
                   1626:     hDoc.write("<tr bgcolor=\\"#ffffdd\\">");
                   1627:     hDoc.write("<td align=\\"left\\">");
1.465     albertel 1628:     hDoc.write("<input name=\\"kwdclr\\" type=\\"radio\\" value=\\""+clrval+"\\" "+clrsel+">&nbsp;"+clrtxt+"<\\/td>");
1.76      ng       1629:     hDoc.write("<td align=\\"left\\">");
1.465     albertel 1630:     hDoc.write("<input name=\\"kwdsize\\" type=\\"radio\\" value=\\""+szval+"\\" "+szsel+">&nbsp;"+sztxt+"<\\/td>");
1.76      ng       1631:     hDoc.write("<td align=\\"left\\">");
1.465     albertel 1632:     hDoc.write("<input name=\\"kwdstyle\\" type=\\"radio\\" value=\\""+syval+"\\" "+sysel+">&nbsp;"+sytxt+"<\\/td>");
                   1633:     hDoc.write("<\\/tr>");
1.44      ng       1634:   }
                   1635: 
                   1636:   function highlightend() { 
1.76      ng       1637:     var hDoc = hwdWin.document;
1.465     albertel 1638:     hDoc.write("<\\/table>");
                   1639:     hDoc.write("<\\/td><\\/tr><\\/table>&nbsp;");
1.589     bisitz   1640:     hDoc.write("<input type=\\"button\\" value=\\"Save\\" onclick=\\"javascript:updateChoice(1)\\">&nbsp;&nbsp;");
                   1641:     hDoc.write("<input type=\\"button\\" value=\\"Cancel\\" onclick=\\"self.close()\\"><br /><br />");
1.465     albertel 1642:     hDoc.write("<\\/form>");
1.351     albertel 1643:     hDoc.write('$end_page_highlight_central');
1.128     ng       1644:     hDoc.close();
1.44      ng       1645:   }
                   1646: 
                   1647: SUBJAVASCRIPT
                   1648: }
                   1649: 
1.349     albertel 1650: sub get_increment {
1.348     bowersj2 1651:     my $increment = $env{'form.increment'};
                   1652:     if ($increment != 1 && $increment != .5 && $increment != .25 &&
                   1653:         $increment != .1) {
                   1654:         $increment = 1;
                   1655:     }
                   1656:     return $increment;
                   1657: }
                   1658: 
1.585     bisitz   1659: sub gradeBox_start {
                   1660:     return (
                   1661:         &Apache::loncommon::start_data_table()
                   1662:        .&Apache::loncommon::start_data_table_header_row()
                   1663:        .'<th>'.&mt('Part').'</th>'
                   1664:        .'<th>'.&mt('Points').'</th>'
                   1665:        .'<th>&nbsp;</th>'
                   1666:        .'<th>'.&mt('Assign Grade').'</th>'
                   1667:        .'<th>'.&mt('Weight').'</th>'
                   1668:        .'<th>'.&mt('Grade Status').'</th>'
                   1669:        .&Apache::loncommon::end_data_table_header_row()
                   1670:     );
                   1671: }
                   1672: 
                   1673: sub gradeBox_end {
                   1674:     return (
                   1675:         &Apache::loncommon::end_data_table()
                   1676:     );
                   1677: }
1.71      ng       1678: #--- displays the grading box, used in essay type problem and grading by page/sequence
                   1679: sub gradeBox {
1.322     albertel 1680:     my ($request,$symb,$uname,$udom,$counter,$partid,$record) = @_;
1.381     albertel 1681:     my $checkIcon = '<img alt="'.&mt('Check Mark').
1.485     albertel 1682: 	'" src="'.&Apache::loncommon::lonhttpdurl($request->dir_config('lonIconsURL').'/check.gif').'" height="16" border="0" />';
1.71      ng       1683:     my $wgt    = &Apache::lonnet::EXT('resource.'.$partid.'.weight',$symb,$udom,$uname);
1.466     albertel 1684:     my $wgtmsg = ($wgt > 0) ? &mt('(problem weight)') 
                   1685:                            : '<span class="LC_info">'.&mt('problem weight assigned by computer').'</span>';
1.71      ng       1686:     $wgt       = ($wgt > 0 ? $wgt : '1');
                   1687:     my $score  = ($$record{'resource.'.$partid.'.awarded'} eq '' ?
1.320     albertel 1688: 		  '' : &compute_points($$record{'resource.'.$partid.'.awarded'},$wgt));
1.71      ng       1689:     my $result='<input type="hidden" name="WGT'.$counter.'_'.$partid.'" value="'.$wgt.'" />'."\n";
1.466     albertel 1690:     my $display_part= &get_display_part($partid,$symb);
1.270     albertel 1691:     my %last_resets = &get_last_resets($symb,$env{'request.course.id'},
                   1692: 				       [$partid]);
                   1693:     my $aggtries = $$record{'resource.'.$partid.'.tries'};
1.269     raeburn  1694:     if ($last_resets{$partid}) {
                   1695:         $aggtries = &get_num_tries($record,$last_resets{$partid},$partid);
                   1696:     }
1.585     bisitz   1697:     $result.=&Apache::loncommon::start_data_table_row();
1.71      ng       1698:     my $ctr = 0;
1.348     bowersj2 1699:     my $thisweight = 0;
1.349     albertel 1700:     my $increment = &get_increment();
1.485     albertel 1701: 
                   1702:     my $radio.='<table border="0"><tr>'."\n";  # display radio buttons in a nice table 10 across
1.348     bowersj2 1703:     while ($thisweight<=$wgt) {
1.532     bisitz   1704: 	$radio.= '<td><span class="LC_nobreak"><label><input type="radio" name="RADVAL'.$counter.'_'.$partid.'" '.
1.589     bisitz   1705:         'onclick="javascript:writeBox(this.form,\''.$counter.'_'.$partid.'\','.
1.348     bowersj2 1706: 	    $thisweight.')" value="'.$thisweight.'" '.
1.401     albertel 1707: 	    ($score eq $thisweight ? 'checked="checked"':'').' /> '.$thisweight."</label></span></td>\n";
1.485     albertel 1708: 	$radio.=(($ctr+1)%10 == 0 ? '</tr><tr>' : '');
1.348     bowersj2 1709:         $thisweight += $increment;
1.71      ng       1710: 	$ctr++;
                   1711:     }
1.485     albertel 1712:     $radio.='</tr></table>';
                   1713: 
                   1714:     my $line.='<input type="text" name="GD_BOX'.$counter.'_'.$partid.'"'.
1.71      ng       1715: 	($score ne ''? ' value = "'.$score.'"':'').' size="4" '.
1.589     bisitz   1716: 	'onchange="javascript:updateRadio(this.form,\''.$counter.'_'.$partid.'\','.
1.71      ng       1717: 	$wgt.')" /></td>'."\n";
1.485     albertel 1718:     $line.='<td>/'.$wgt.' '.$wgtmsg.
1.71      ng       1719: 	($$record{'resource.'.$partid.'.solved'} eq 'correct_by_student' ? '&nbsp;'.$checkIcon : '').
1.585     bisitz   1720: 	' </td>'."\n";
                   1721:     $line.='<td><select name="GD_SEL'.$counter.'_'.$partid.'" '.
1.589     bisitz   1722: 	'onchange="javascript:clearRadBox(this.form,\''.$counter.'_'.$partid.'\')" >'."\n";
1.71      ng       1723:     if ($$record{'resource.'.$partid.'.solved'} eq 'excused') {
1.485     albertel 1724: 	$line.='<option></option>'.
                   1725: 	    '<option value="excused" selected="selected">'.&mt('excused').'</option>';
1.71      ng       1726:     } else {
1.485     albertel 1727: 	$line.='<option selected="selected"></option>'.
                   1728: 	    '<option value="excused" >'.&mt('excused').'</option>';
1.71      ng       1729:     }
1.485     albertel 1730:     $line.='<option value="reset status">'.&mt('reset status').'</option></select>'."\n";
                   1731: 
                   1732: 
                   1733:     $result .= 
1.585     bisitz   1734: 	    '<td>'.$display_part.'</td><td>'.$radio.'</td><td>'.&mt('or').'</td><td>'.$line.'</td>';
                   1735:     $result.=&Apache::loncommon::end_data_table_row();
1.71      ng       1736:     $result.='<input type="hidden" name="stores'.$counter.'_'.$partid.'" value="" />'."\n".
                   1737: 	'<input type="hidden" name="oldpts'.$counter.'_'.$partid.'" value="'.$score.'" />'."\n".
                   1738: 	'<input type="hidden" name="solved'.$counter.'_'.$partid.'" value="'.
1.269     raeburn  1739: 	$$record{'resource.'.$partid.'.solved'}.'" />'."\n".
                   1740:         '<input type="hidden" name="totaltries'.$counter.'_'.$partid.'" value="'.
                   1741:         $$record{'resource.'.$partid.'.tries'}.'" />'."\n".
                   1742:         '<input type="hidden" name="aggtries'.$counter.'_'.$partid.'" value="'.
                   1743:         $aggtries.'" />'."\n";
1.582     raeburn  1744:     my $res_error;
                   1745:     $result.=&handback_box($symb,$uname,$udom,$counter,$partid,$record,\$res_error);
                   1746:     if ($res_error) {
                   1747:         return &navmap_errormsg();
                   1748:     }
1.318     banghart 1749:     return $result;
                   1750: }
1.322     albertel 1751: 
                   1752: sub handback_box {
1.582     raeburn  1753:     my ($symb,$uname,$udom,$counter,$partid,$record,$res_error) = @_;
                   1754:     my ($partlist,$handgrade,$responseType) = &response_type($symb,$res_error);
1.323     banghart 1755:     my (@respids);
1.375     albertel 1756:      my @part_response_id = &flatten_responseType($responseType);
                   1757:     foreach my $part_response_id (@part_response_id) {
                   1758:     	my ($part,$resp) = @{ $part_response_id };
1.323     banghart 1759:         if ($part eq $partid) {
1.375     albertel 1760:             push(@respids,$resp);
1.323     banghart 1761:         }
                   1762:     }
1.318     banghart 1763:     my $result;
1.323     banghart 1764:     foreach my $respid (@respids) {
1.322     albertel 1765: 	my $prefix = $counter.'_'.$partid.'_'.$respid.'_';
                   1766: 	my $files=&get_submitted_files($udom,$uname,$partid,$respid,$record);
                   1767: 	next if (!@$files);
                   1768: 	my $file_counter = 1;
1.313     banghart 1769: 	foreach my $file (@$files) {
1.368     banghart 1770: 	    if ($file =~ /\/portfolio\//) {
                   1771:     	        my ($file_path, $file_disp) = ($file =~ m|(.+/)(.+)$|);
                   1772:     	        my ($name,$version,$ext) = &file_name_version_ext($file_disp);
                   1773:     	        $file_disp = "$name.$ext";
                   1774:     	        $file = $file_path.$file_disp;
                   1775:     	        $result.=&mt('Return commented version of [_1] to student.',
                   1776:     			 '<span class="LC_filename">'.$file_disp.'</span>');
                   1777:     	        $result.='<input type="file"   name="'.$prefix.'returndoc'.$file_counter.'" />'."\n";
                   1778:     	        $result.='<input type="hidden" name="'.$prefix.'origdoc'.$file_counter.'" value="'.$file.'" /><br />';
1.485     albertel 1779:     	        $result.='('.&mt('File will be uploaded when you click on Save &amp; Next below.').')<br />';
1.368     banghart 1780:     	        $file_counter++;
                   1781: 	    }
1.322     albertel 1782: 	}
1.313     banghart 1783:     }
1.318     banghart 1784:     return $result;    
1.71      ng       1785: }
1.44      ng       1786: 
1.58      albertel 1787: sub show_problem {
1.382     albertel 1788:     my ($request,$symb,$uname,$udom,$removeform,$viewon,$mode,$form) = @_;
1.144     albertel 1789:     my $rendered;
1.382     albertel 1790:     my %form = ((ref($form) eq 'HASH')? %{$form} : ());
1.329     albertel 1791:     &Apache::lonxml::remember_problem_counter();
1.144     albertel 1792:     if ($mode eq 'both' or $mode eq 'text') {
                   1793: 	$rendered=&Apache::loncommon::get_student_view($symb,$uname,$udom,
1.382     albertel 1794: 						       $env{'request.course.id'},
                   1795: 						       undef,\%form);
1.144     albertel 1796:     }
1.58      albertel 1797:     if ($removeform) {
                   1798: 	$rendered=~s|<form(.*?)>||g;
                   1799: 	$rendered=~s|</form>||g;
1.374     albertel 1800: 	$rendered=~s|(<input[^>]*name\s*=\s*"?)(\w+)("?)|$1would_have_been_$2$3|g;
1.58      albertel 1801:     }
1.144     albertel 1802:     my $companswer;
                   1803:     if ($mode eq 'both' or $mode eq 'answer') {
1.329     albertel 1804: 	&Apache::lonxml::restore_problem_counter();
1.382     albertel 1805: 	$companswer=
                   1806: 	    &Apache::loncommon::get_student_answers($symb,$uname,$udom,
                   1807: 						    $env{'request.course.id'},
                   1808: 						    %form);
1.144     albertel 1809:     }
1.58      albertel 1810:     if ($removeform) {
                   1811: 	$companswer=~s|<form(.*?)>||g;
                   1812: 	$companswer=~s|</form>||g;
1.144     albertel 1813: 	$companswer=~s|name="submit"|name="would_have_been_submit"|g;
1.58      albertel 1814:     }
1.468     albertel 1815:     $rendered=
1.588     bisitz   1816:         '<div class="LC_Box">'
                   1817:        .'<h3 class="LC_hcell">'.&mt('View of the problem').'</h3>'
                   1818:        .$rendered
                   1819:        .'</div>';
1.468     albertel 1820:     $companswer=
1.588     bisitz   1821:         '<div class="LC_Box">'
                   1822:        .'<h3 class="LC_hcell">'.&mt('Correct answer').'</h3>'
                   1823:        .$companswer
                   1824:        .'</div>';
1.468     albertel 1825:     my $result;
1.144     albertel 1826:     if ($mode eq 'both') {
1.588     bisitz   1827:         $result=$rendered.$companswer;
1.144     albertel 1828:     } elsif ($mode eq 'text') {
1.588     bisitz   1829:         $result=$rendered;
1.144     albertel 1830:     } elsif ($mode eq 'answer') {
1.588     bisitz   1831:         $result=$companswer;
1.144     albertel 1832:     }
1.71      ng       1833:     return $result;
1.58      albertel 1834: }
1.397     albertel 1835: 
1.396     banghart 1836: sub files_exist {
                   1837:     my ($r, $symb) = @_;
                   1838:     my @students = &Apache::loncommon::get_env_multiple('form.stuinfo');
1.397     albertel 1839: 
1.396     banghart 1840:     foreach my $student (@students) {
                   1841:         my ($uname,$udom,$fullname) = split(/:/,$student);
1.397     albertel 1842:         my %record = &Apache::lonnet::restore($symb,$env{'request.course.id'},
                   1843: 					      $udom,$uname);
1.396     banghart 1844:         my ($string,$timestamp)= &get_last_submission(\%record);
1.397     albertel 1845:         foreach my $submission (@$string) {
                   1846:             my ($partid,$respid) =
                   1847: 		($submission =~ /^resource\.([^\.]*)\.([^\.]*)\.submission/);
                   1848:             my $files=&get_submitted_files($udom,$uname,$partid,$respid,
                   1849: 					   \%record);
                   1850:             return 1 if (@$files);
1.396     banghart 1851:         }
                   1852:     }
1.397     albertel 1853:     return 0;
1.396     banghart 1854: }
1.397     albertel 1855: 
1.394     banghart 1856: sub download_all_link {
                   1857:     my ($r,$symb) = @_;
1.395     albertel 1858:     my $all_students = 
                   1859: 	join("\n", &Apache::loncommon::get_env_multiple('form.stuinfo'));
                   1860: 
                   1861:     my $parts =
                   1862: 	join("\n",&Apache::loncommon::get_env_multiple('form.vPart'));
                   1863: 
1.394     banghart 1864:     my $identifier = &Apache::loncommon::get_cgi_id();
1.514     raeburn  1865:     &Apache::lonnet::appenv({'cgi.'.$identifier.'.students' => $all_students,
                   1866:                              'cgi.'.$identifier.'.symb' => $symb,
                   1867:                              'cgi.'.$identifier.'.parts' => $parts,});
1.395     albertel 1868:     $r->print('<a href="/cgi-bin/multidownload.pl?'.$identifier.'">'.
                   1869: 	      &mt('Download All Submitted Documents').'</a>');
1.394     banghart 1870:     return
                   1871: }
1.395     albertel 1872: 
1.432     banghart 1873: sub build_section_inputs {
                   1874:     my $section_inputs;
                   1875:     if ($env{'form.section'} eq '') {
                   1876:         $section_inputs .= '<input type="hidden" name="section" value="all" />'."\n";
                   1877:     } else {
                   1878:         my @sections = &Apache::loncommon::get_env_multiple('form.section');
1.434     albertel 1879:         foreach my $section (@sections) {
1.432     banghart 1880:             $section_inputs .= '<input type="hidden" name="section" value="'.$section.'" />'."\n";
                   1881:         }
                   1882:     }
                   1883:     return $section_inputs;
                   1884: }
                   1885: 
1.44      ng       1886: # --------------------------- show submissions of a student, option to grade 
                   1887: sub submission {
1.608     www      1888:     my ($request,$counter,$total,$symb) = @_;
1.257     albertel 1889:     my ($uname,$udom)     = ($env{'form.student'},$env{'form.userdom'});
                   1890:     $udom = ($udom eq '' ? $env{'user.domain'} : $udom); #has form.userdom changed for a student?
                   1891:     my $usec = &Apache::lonnet::getsection($udom,$uname,$env{'request.course.id'});
                   1892:     $env{'form.fullname'} = &Apache::loncommon::plainname($uname,$udom,'lastname') if $env{'form.fullname'} eq '';
1.608     www      1893: 
1.605     www      1894:     my $probtitle=&Apache::lonnet::gettitle($symb); 
1.324     albertel 1895:     if ($symb eq '') { $request->print("Unable to handle ambiguous references:."); return ''; }
1.104     albertel 1896: 
                   1897:     if (!&canview($usec)) {
1.398     albertel 1898: 	$request->print('<span class="LC_warning">Unable to view requested student.('.
                   1899: 			$uname.':'.$udom.' in section '.$usec.' in course id '.
                   1900: 			$env{'request.course.id'}.')</span>');
1.324     albertel 1901: 	$request->print(&show_grading_menu_form($symb));
1.104     albertel 1902: 	return;
                   1903:     }
                   1904: 
1.257     albertel 1905:     if (!$env{'form.lastSub'}) { $env{'form.lastSub'} = 'datesub'; }
                   1906:     if (!$env{'form.vProb'}) { $env{'form.vProb'} = 'yes'; }
                   1907:     if (!$env{'form.vAns'}) { $env{'form.vAns'} = 'yes'; }
                   1908:     my $last = ($env{'form.lastSub'} eq 'last' ? 'last' : '');
1.381     albertel 1909:     my $checkIcon = '<img alt="'.&mt('Check Mark').
                   1910: 	'" src="'.$request->dir_config('lonIconsURL').
1.122     ng       1911: 	'/check.gif" height="16" border="0" />';
1.41      ng       1912: 
1.426     albertel 1913:     my %old_essays;
1.41      ng       1914:     # header info
                   1915:     if ($counter == 0) {
                   1916: 	&sub_page_js($request);
1.257     albertel 1917: 	&sub_page_kw_js($request) if ($env{'form.handgrade'} eq 'yes');
1.397     albertel 1918: 	if ($env{'form.handgrade'} eq 'yes' && &files_exist($request, $symb)) {
1.396     banghart 1919: 	    &download_all_link($request, $symb);
                   1920: 	}
1.605     www      1921: 	$request->print('<h3>&nbsp;<span class="LC_info">'.&mt('Submission Record').'</span></h3>');
1.118     ng       1922: 
1.44      ng       1923: 	# option to display problem, only once else it cause problems 
                   1924:         # with the form later since the problem has a form.
1.257     albertel 1925: 	if ($env{'form.vProb'} eq 'yes' or $env{'form.vAns'} eq 'yes') {
1.144     albertel 1926: 	    my $mode;
1.257     albertel 1927: 	    if ($env{'form.vProb'} eq 'yes' && $env{'form.vAns'} eq 'yes') {
1.144     albertel 1928: 		$mode='both';
1.257     albertel 1929: 	    } elsif ($env{'form.vProb'} eq 'yes') {
1.144     albertel 1930: 		$mode='text';
1.257     albertel 1931: 	    } elsif ($env{'form.vAns'} eq 'yes') {
1.144     albertel 1932: 		$mode='answer';
                   1933: 	    }
1.329     albertel 1934: 	    &Apache::lonxml::clear_problem_counter();
1.144     albertel 1935: 	    $request->print(&show_problem($request,$symb,$uname,$udom,0,1,$mode));
1.41      ng       1936: 	}
1.441     www      1937: 
1.44      ng       1938: 	# kwclr is the only variable that is guaranteed to be non blank 
                   1939:         # if this subroutine has been called once.
1.41      ng       1940: 	my %keyhash = ();
1.257     albertel 1941: 	if ($env{'form.kwclr'} eq '' && $env{'form.handgrade'} eq 'yes') {
1.41      ng       1942: 	    %keyhash = &Apache::lonnet::dump('nohist_handgrade',
1.257     albertel 1943: 					     $env{'course.'.$env{'request.course.id'}.'.domain'},
                   1944: 					     $env{'course.'.$env{'request.course.id'}.'.num'});
1.41      ng       1945: 
1.257     albertel 1946: 	    my $loginuser = $env{'user.name'}.':'.$env{'user.domain'};
                   1947: 	    $env{'form.keywords'} = $keyhash{$symb.'_keywords'} ne '' ? $keyhash{$symb.'_keywords'} : '';
                   1948: 	    $env{'form.kwclr'}    = $keyhash{$loginuser.'_kwclr'} ne '' ? $keyhash{$loginuser.'_kwclr'} : 'red';
                   1949: 	    $env{'form.kwsize'}   = $keyhash{$loginuser.'_kwsize'} ne '' ? $keyhash{$loginuser.'_kwsize'} : '0';
                   1950: 	    $env{'form.kwstyle'}  = $keyhash{$loginuser.'_kwstyle'} ne '' ? $keyhash{$loginuser.'_kwstyle'} : '';
                   1951: 	    $env{'form.msgsub'}   = $keyhash{$symb.'_subject'} ne '' ? 
1.605     www      1952: 		$keyhash{$symb.'_subject'} : $probtitle;
1.257     albertel 1953: 	    $env{'form.savemsgN'} = $keyhash{$symb.'_savemsgN'} ne '' ? $keyhash{$symb.'_savemsgN'} : '0';
1.41      ng       1954: 	}
1.257     albertel 1955: 	my $overRideScore = $env{'form.overRideScore'} eq '' ? 'no' : $env{'form.overRideScore'};
1.442     banghart 1956: 	my $stu_status = join(':',&Apache::loncommon::get_env_multiple('form.Status'));
1.303     banghart 1957: 	$request->print('<form action="/adm/grades" method="post" name="SCORE" enctype="multipart/form-data">'."\n".
1.41      ng       1958: 			'<input type="hidden" name="command"    value="handgrade" />'."\n".
1.257     albertel 1959: 			'<input type="hidden" name="saveState"  value="'.$env{'form.saveState'}.'" />'."\n".
1.442     banghart 1960: 			'<input type="hidden" name="Status"     value="'.$stu_status.'" />'."\n".
1.120     ng       1961: 			'<input type="hidden" name="overRideScore" value="'.$overRideScore.'" />'."\n".
1.41      ng       1962: 			'<input type="hidden" name="refresh"    value="off" />'."\n".
1.120     ng       1963: 			'<input type="hidden" name="studentNo"  value="" />'."\n".
                   1964: 			'<input type="hidden" name="gradeOpt"   value="" />'."\n".
1.418     albertel 1965: 			'<input type="hidden" name="symb"       value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
1.257     albertel 1966: 			'<input type="hidden" name="showgrading" value="'.$env{'form.showgrading'}.'" />'."\n".
                   1967: 			'<input type="hidden" name="vProb"      value="'.$env{'form.vProb'}.'" />'."\n".
                   1968: 			'<input type="hidden" name="vAns"       value="'.$env{'form.vAns'}.'" />'."\n".
                   1969: 			'<input type="hidden" name="lastSub"    value="'.$env{'form.lastSub'}.'" />'."\n".
1.432     banghart 1970: 			&build_section_inputs().
1.326     albertel 1971: 			'<input type="hidden" name="submitonly" value="'.$env{'form.submitonly'}.'" />'."\n".
                   1972: 			'<input type="hidden" name="handgrade"  value="'.$env{'form.handgrade'}.'" />'."\n".
1.41      ng       1973: 			'<input type="hidden" name="NCT"'.
1.257     albertel 1974: 			' value="'.($env{'form.NTSTU'} ne '' ? $env{'form.NTSTU'} : $total+1).'" />'."\n");
                   1975: 	if ($env{'form.handgrade'} eq 'yes') {
                   1976: 	    $request->print('<input type="hidden" name="keywords" value="'.$env{'form.keywords'}.'" />'."\n".
                   1977: 			    '<input type="hidden" name="kwclr"    value="'.$env{'form.kwclr'}.'" />'."\n".
                   1978: 			    '<input type="hidden" name="kwsize"   value="'.$env{'form.kwsize'}.'" />'."\n".
                   1979: 			    '<input type="hidden" name="kwstyle"  value="'.$env{'form.kwstyle'}.'" />'."\n".
                   1980: 			    '<input type="hidden" name="msgsub"   value="'.$env{'form.msgsub'}.'" />'."\n".
1.123     ng       1981: 			    '<input type="hidden" name="shownSub" value="0" />'."\n".
1.257     albertel 1982: 			    '<input type="hidden" name="savemsgN" value="'.$env{'form.savemsgN'}.'" />'."\n");
1.154     albertel 1983: 	    foreach my $partid (&Apache::loncommon::get_env_multiple('form.vPart')) {
                   1984: 		$request->print('<input type="hidden" name="vPart" value="'.$partid.'" />'."\n");
                   1985: 	    }
1.123     ng       1986: 	}
1.41      ng       1987: 	
                   1988: 	my ($cts,$prnmsg) = (1,'');
1.257     albertel 1989: 	while ($cts <= $env{'form.savemsgN'}) {
1.41      ng       1990: 	    $prnmsg.='<input type="hidden" name="savemsg'.$cts.'" value="'.
1.123     ng       1991: 		(!exists($keyhash{$symb.'_savemsg'.$cts}) ? 
1.257     albertel 1992: 		 &Apache::lonfeedback::clear_out_html($env{'form.savemsg'.$cts}) :
1.80      ng       1993: 		 &Apache::lonfeedback::clear_out_html($keyhash{$symb.'_savemsg'.$cts})).
1.123     ng       1994: 		'" />'."\n".
                   1995: 		'<input type="hidden" name="shownOnce'.$cts.'" value="0" />'."\n";
1.41      ng       1996: 	    $cts++;
                   1997: 	}
                   1998: 	$request->print($prnmsg);
1.32      ng       1999: 
1.257     albertel 2000: 	if ($env{'form.handgrade'} eq 'yes' && $env{'form.showgrading'} eq 'yes') {
1.88      www      2001: #
                   2002: # Print out the keyword options line
                   2003: #
1.41      ng       2004: 	    $request->print(<<KEYWORDS);
1.38      ng       2005: &nbsp;<b>Keyword Options:</b>&nbsp;
1.417     albertel 2006: <a href="javascript:keywords(document.SCORE);" target="_self">List</a>&nbsp; &nbsp;
1.589     bisitz   2007: <a href="#" onmousedown="javascript:getSel(); return false"
1.38      ng       2008:  CLASS="page">Paste Selection to List</a>&nbsp; &nbsp;
1.417     albertel 2009: <a href="javascript:kwhighlight();" target="_self">Highlight Attribute</a><br /><br />
1.38      ng       2010: KEYWORDS
1.88      www      2011: #
                   2012: # Load the other essays for similarity check
                   2013: #
1.324     albertel 2014:             my (undef,undef,$essayurl) = &Apache::lonnet::decode_symb($symb);
1.384     albertel 2015: 	    my ($adom,$aname,$apath)=($essayurl=~/^($LONCAPA::domain_re)\/($LONCAPA::username_re)\/(.*)$/);
1.359     www      2016: 	    $apath=&escape($apath);
1.88      www      2017: 	    $apath=~s/\W/\_/gs;
1.426     albertel 2018: 	    %old_essays=&Apache::lonnet::dump('nohist_essay_'.$apath,$adom,$aname);
1.41      ng       2019:         }
                   2020:     }
1.44      ng       2021: 
1.441     www      2022: # This is where output for one specific student would start
1.592     bisitz   2023:     my $add_class = ($counter%2) ? ' LC_grade_show_user_odd_row' : '';
                   2024:     $request->print(
                   2025:         "\n\n"
                   2026:        .'<div class="LC_grade_show_user'.$add_class.'">'
                   2027:        .'<h2>'.&nameUserString(undef,$env{'form.fullname'},$uname,$udom).'</h2>'
                   2028:        ."\n"
                   2029:     );
1.441     www      2030: 
1.592     bisitz   2031:     # Show additional functions if allowed
                   2032:     if ($perm{'vgr'}) {
                   2033:         $request->print(
                   2034:             &Apache::loncommon::track_student_link(
                   2035:                 &mt('View recent activity'),
                   2036:                 $uname,$udom,'check')
                   2037:            .' '
                   2038:         );
                   2039:     }
                   2040:     if ($perm{'opa'}) {
                   2041:         $request->print(
                   2042:             &Apache::loncommon::pprmlink(
                   2043:                 &mt('Set/Change parameters'),
                   2044:                 $uname,$udom,$symb,'check'));
                   2045:     }
                   2046: 
                   2047:     # Show Problem
1.257     albertel 2048:     if ($env{'form.vProb'} eq 'all' or $env{'form.vAns'} eq 'all') {
1.144     albertel 2049: 	my $mode;
1.257     albertel 2050: 	if ($env{'form.vProb'} eq 'all' && $env{'form.vAns'} eq 'all') {
1.144     albertel 2051: 	    $mode='both';
1.257     albertel 2052: 	} elsif ($env{'form.vProb'} eq 'all' ) {
1.144     albertel 2053: 	    $mode='text';
1.257     albertel 2054: 	} elsif ($env{'form.vAns'} eq 'all') {
1.144     albertel 2055: 	    $mode='answer';
                   2056: 	}
1.329     albertel 2057: 	&Apache::lonxml::clear_problem_counter();
1.475     albertel 2058: 	$request->print(&show_problem($request,$symb,$uname,$udom,1,1,$mode,{'request.prefix' => 'ctr'.$counter}));
1.58      albertel 2059:     }
1.144     albertel 2060: 
1.257     albertel 2061:     my %record = &Apache::lonnet::restore($symb,$env{'request.course.id'},$udom,$uname);
1.582     raeburn  2062:     my $res_error;
                   2063:     my ($partlist,$handgrade,$responseType) = &response_type($symb,\$res_error);
                   2064:     if ($res_error) {
                   2065:         $request->print(&navmap_errormsg());
                   2066:         return;
                   2067:     }
1.41      ng       2068: 
1.44      ng       2069:     # Display student info
1.41      ng       2070:     $request->print(($counter == 0 ? '' : '<br />'));
1.590     bisitz   2071: 
                   2072:     my $result='<div class="LC_Box">'
                   2073:               .'<h3 class="LC_hcell">'.&mt('Submissions').'</h3>';
1.45      ng       2074:     $result.='<input type="hidden" name="name'.$counter.
1.588     bisitz   2075:              '" value="'.$env{'form.fullname'}.'" />'."\n";
1.469     albertel 2076:     if ($env{'form.handgrade'} eq 'no') {
1.588     bisitz   2077:         $result.='<p class="LC_info">'
                   2078:                 .&mt('Part(s) graded correct by the computer is marked with a [_1] symbol.',$checkIcon)
                   2079:                 ."</p>\n";
1.469     albertel 2080:     }
                   2081: 
1.118     ng       2082:     # If any part of the problem is an essay-response (handgraded), then check for collaborators
1.464     albertel 2083:     my $fullname;
                   2084:     my $col_fullnames = [];
1.257     albertel 2085:     if ($env{'form.handgrade'} eq 'yes') {
1.464     albertel 2086: 	(my $sub_result,$fullname,$col_fullnames)=
                   2087: 	    &check_collaborators($symb,$uname,$udom,\%record,$handgrade,
                   2088: 				 $counter);
                   2089: 	$result.=$sub_result;
1.41      ng       2090:     }
1.44      ng       2091:     $request->print($result."\n");
1.588     bisitz   2092: 
1.44      ng       2093:     # print student answer/submission
1.588     bisitz   2094:     # Options are (1) Handgraded submission only
1.44      ng       2095:     #             (2) Last submission, includes submission that is not handgraded 
                   2096:     #                  (for multi-response type part)
                   2097:     #             (3) Last submission plus the parts info
                   2098:     #             (4) The whole record for this student
1.257     albertel 2099:     if ($env{'form.lastSub'} =~ /^(lastonly|hdgrade)$/) {
1.151     albertel 2100: 	my ($string,$timestamp)= &get_last_submission(\%record);
1.468     albertel 2101: 	
                   2102: 	my $lastsubonly;
                   2103: 
1.588     bisitz   2104:         if ($$timestamp eq '') {
                   2105:             $lastsubonly.='<div class="LC_grade_submissions_body">'.$$string[0].'</div>'; 
                   2106:         } else {
1.592     bisitz   2107:             $lastsubonly =
                   2108:                 '<div class="LC_grade_submissions_body">'
                   2109:                .'<b>'.&mt('Date Submitted:').'</b> '.$$timestamp."\n";
1.468     albertel 2110: 
1.151     albertel 2111: 	    my %seenparts;
1.375     albertel 2112: 	    my @part_response_id = &flatten_responseType($responseType);
                   2113: 	    foreach my $part (@part_response_id) {
1.393     albertel 2114: 		next if ($env{'form.lastSub'} eq 'hdgrade' 
                   2115: 			 && $$handgrade{$$part[0].'_'.$$part[1]} ne 'yes');
                   2116: 
1.375     albertel 2117: 		my ($partid,$respid) = @{ $part };
1.324     albertel 2118: 		my $display_part=&get_display_part($partid,$symb);
1.257     albertel 2119: 		if ($env{"form.$uname:$udom:$partid:submitted_by"}) {
1.151     albertel 2120: 		    if (exists($seenparts{$partid})) { next; }
                   2121: 		    $seenparts{$partid}=1;
1.207     albertel 2122: 		    my $submitby='<b>Part:</b> '.$display_part.
                   2123: 			' <b>Collaborative submission by:</b> '.
1.151     albertel 2124: 			'<a href="javascript:viewSubmitter(\''.
1.257     albertel 2125: 			$env{"form.$uname:$udom:$partid:submitted_by"}.
1.417     albertel 2126: 			'\');" target="_self">'.
1.257     albertel 2127: 			$$fullname{$env{"form.$uname:$udom:$partid:submitted_by"}}.'</a><br />';
1.151     albertel 2128: 		    $request->print($submitby);
                   2129: 		    next;
                   2130: 		}
                   2131: 		my $responsetype = $responseType->{$partid}->{$respid};
                   2132: 		if (!exists($record{"resource.$partid.$respid.submission"})) {
1.577     bisitz   2133:                     $lastsubonly.="\n".'<div class="LC_grade_submission_part">'.
                   2134:                         '<b>'.&mt('Part: [_1]',$display_part).'</b>'.
                   2135:                         ' <span class="LC_internal_info">'.
1.597     wenzelju 2136:                         '('.&mt('Part ID: [_1]',$respid).')'.
1.577     bisitz   2137:                         '</span>&nbsp; &nbsp;'.
1.539     riegler  2138: 			'<span class="LC_warning">'.&mt('Nothing submitted - no attempts.').'</span><br /><br /></div>';
1.151     albertel 2139: 		    next;
                   2140: 		}
1.468     albertel 2141: 		foreach my $submission (@$string) {
                   2142: 		    my ($partid,$respid) = ($submission =~ /^resource\.([^\.]*)\.([^\.]*)\.submission/);
1.375     albertel 2143: 		    if (join('_',@{$part}) ne ($partid.'_'.$respid)) { next; }
1.596     raeburn  2144: 		    my ($ressub,$hide,$subval) = split(/:/,$submission,3);
1.151     albertel 2145: 		    # Similarity check
                   2146: 		    my $similar='';
1.257     albertel 2147: 		    if($env{'form.checkPlag'}){
1.151     albertel 2148: 			my ($oname,$odom,$ocrsid,$oessay,$osim)=
1.426     albertel 2149: 			    &most_similar($uname,$udom,$subval,\%old_essays);
1.151     albertel 2150: 			if ($osim) {
                   2151: 			    $osim=int($osim*100.0);
1.426     albertel 2152: 			    my %old_course_desc = 
                   2153: 				&Apache::lonnet::coursedescription($ocrsid,
                   2154: 								   {'one_time' => 1});
                   2155: 
1.596     raeburn  2156:                             if ($hide) {
                   2157:                                 $similar='<hr /><span class="LC_warning">'.&mt("Essay was found to be similar to another essay submitted for this assignment.").'<br />'.
                   2158:                                          &mt('As the current submission is for an anonymous survey, no other details are available.').'</span><hr />';
                   2159:                             } else {
                   2160: 			        $similar="<hr /><h3><span class=\"LC_warning\">".
                   2161: 				    &mt('Essay is [_1]% similar to an essay by [_2] in course [_3] (course id [_4]:[_5])',
                   2162: 				        $osim,
                   2163: 				        &Apache::loncommon::plainname($oname,$odom).' ('.$oname.':'.$odom.')',
                   2164: 				        $old_course_desc{'description'},
                   2165: 				        $old_course_desc{'num'},
                   2166: 				        $old_course_desc{'domain'}).
                   2167: 				    '</span></h3><blockquote><i>'.
                   2168: 				    &keywords_highlight($oessay).
                   2169: 				    '</i></blockquote><hr />';
                   2170:                             }
1.151     albertel 2171: 			}
1.150     albertel 2172: 		    }
1.151     albertel 2173: 		    my $order=&get_order($partid,$respid,$symb,$uname,$udom);
1.257     albertel 2174: 		    if ($env{'form.lastSub'} eq 'lastonly' || 
                   2175: 			($env{'form.lastSub'} eq 'hdgrade' && 
1.377     albertel 2176: 			 $$handgrade{$$part[0].'_'.$$part[1]} eq 'yes')) {
1.324     albertel 2177: 			my $display_part=&get_display_part($partid,$symb);
1.577     bisitz   2178:                         $lastsubonly.='<div class="LC_grade_submission_part">'.
                   2179:                             '<b>'.&mt('Part: [_1]',$display_part).'</b>'.
                   2180:                             ' <span class="LC_internal_info">'.
                   2181:                             '('.&mt('Part ID: [_1]',$respid).')'.
1.597     wenzelju 2182:                             '</span>&nbsp; &nbsp;';
1.313     banghart 2183: 			my $files=&get_submitted_files($udom,$uname,$partid,$respid,\%record);
                   2184: 			if (@$files) {
1.596     raeburn  2185:                             if ($hide) {
                   2186:                                 $lastsubonly.='<br />'.&mt('[quant,_1,file] uploaded to this anonymous survey',scalar(@{$files}));
                   2187:                             } else {
                   2188:                                 $lastsubonly.='<br /><span class="LC_warning">'.&mt('Like all files provided by users, this file may contain viruses').'</span><br />';
                   2189:                                 foreach my $file (@$files) {
                   2190:                                     &Apache::lonnet::allowuploaded('/adm/grades',$file);
                   2191:                                     $lastsubonly.='<br /><a href="'.$file.'?rawmode=1" target="lonGRDs"><img src="'.&Apache::loncommon::icon($file).'" border="0" /> '.$file.'</a>';
                   2192:                                 }
                   2193:                             }
1.236     albertel 2194: 			    $lastsubonly.='<br />';
1.41      ng       2195: 			}
1.596     raeburn  2196:                         if ($hide) {
                   2197:                             $lastsubonly.='<b>'.&mt('Anonymous Survey').'</b>'; 
                   2198:                         } else {
                   2199: 			    $lastsubonly.='<b>'.&mt('Submitted Answer:').' </b>'.
                   2200: 			        &cleanRecord($subval,$responsetype,$symb,$partid,
                   2201: 					     $respid,\%record,$order,undef,$uname,$udom);
                   2202:                         }
1.151     albertel 2203: 			if ($similar) {$lastsubonly.="<br /><br />$similar\n";}
1.468     albertel 2204: 			$lastsubonly.='</div>';
1.41      ng       2205: 		    }
                   2206: 		}
                   2207: 	    }
1.588     bisitz   2208: 	    $lastsubonly.='</div>'."\n"; # End: LC_grade_submissions_body
1.151     albertel 2209: 	}
                   2210: 	$request->print($lastsubonly);
1.468     albertel 2211:    } elsif ($env{'form.lastSub'} eq 'datesub') {
1.598     www      2212: #	my (undef,$responseType,undef,$parts) = &showResourceInfo($symb);
                   2213:     my ($parts,$handgrade,$responseType) = &response_type($symb);
                   2214: 
1.148     albertel 2215: 	$request->print(&displaySubByDates($symb,\%record,$parts,$responseType,$checkIcon,$uname,$udom));
1.257     albertel 2216:     } elsif ($env{'form.lastSub'} =~ /^(last|all)$/) {
1.41      ng       2217: 	$request->print(&Apache::loncommon::get_previous_attempt($symb,$uname,$udom,
1.257     albertel 2218: 								 $env{'request.course.id'},
1.44      ng       2219: 								 $last,'.submission',
                   2220: 								 'Apache::grades::keywords_highlight'));
1.41      ng       2221:     }
1.120     ng       2222: 
1.121     ng       2223:     $request->print('<input type="hidden" name="unamedom'.$counter.'" value="'.$uname.':'
                   2224: 	.$udom.'" />'."\n");
1.44      ng       2225:     # return if view submission with no grading option
1.257     albertel 2226:     if ($env{'form.showgrading'} eq '' || (!&canmodify($usec))) {
1.120     ng       2227: 	my $toGrade.='<input type="button" value="Grade Student" '.
1.589     bisitz   2228: 	    'onclick="javascript:checksubmit(this.form,\'Grade Student\',\''
1.417     albertel 2229: 	    .$counter.'\');" target="_self" /> &nbsp;'."\n" if (&canmodify($usec));
1.468     albertel 2230: 	$toGrade.='</div>'."\n";
1.257     albertel 2231: 	if (($env{'form.command'} eq 'submission') || 
                   2232: 	    ($env{'form.command'} eq 'processGroup' && $counter == $total)) {
1.324     albertel 2233: 	    $toGrade.='</form>'.&show_grading_menu_form($symb); 
1.169     albertel 2234: 	}
1.180     albertel 2235: 	$request->print($toGrade);
1.41      ng       2236: 	return;
1.180     albertel 2237:     } else {
1.468     albertel 2238: 	$request->print('</div>'."\n");
1.41      ng       2239:     }
1.33      ng       2240: 
1.121     ng       2241:     # essay grading message center
1.257     albertel 2242:     if ($env{'form.handgrade'} eq 'yes') {
1.468     albertel 2243: 	my $result='<div class="LC_grade_message_center">';
                   2244:     
                   2245: 	$result.='<div class="LC_grade_message_center_header">'.
                   2246: 	    &mt('Send Message').'</div><div class="LC_grade_message_center_body">';
1.257     albertel 2247: 	my ($lastname,$givenn) = split(/,/,$env{'form.fullname'});
1.118     ng       2248: 	my $msgfor = $givenn.' '.$lastname;
1.464     albertel 2249: 	if (scalar(@$col_fullnames) > 0) {
                   2250: 	    my $lastone = pop(@$col_fullnames);
                   2251: 	    $msgfor .= ', '.(join ', ',@$col_fullnames).' and '.$lastone.'.';
1.118     ng       2252: 	}
                   2253: 	$msgfor =~ s/\'/\\'/g; #' stupid emacs - no! javascript
1.468     albertel 2254: 	$result.='<input type="hidden" name="includemsg'.$counter.'" value="" />'."\n".
1.121     ng       2255: 	    '<input type="hidden" name="newmsg'.$counter.'" value="" />'."\n";
                   2256: 	$result.='&nbsp;<a href="javascript:msgCenter(document.SCORE,'.$counter.
1.417     albertel 2257: 	    ',\''.$msgfor.'\');" target="_self">'.
1.464     albertel 2258: 	    &mt('Compose message to student').(scalar(@$col_fullnames) >= 1 ? 's' : '').'</a><label> ('.
1.350     albertel 2259: 	    &mt('incl. grades').' <input type="checkbox" name="withgrades'.$counter.'" /></label>)'.
1.118     ng       2260: 	    '<img src="'.$request->dir_config('lonIconsURL').
                   2261: 	    '/mailbkgrd.gif" width="14" height="10" name="mailicon'.$counter.'" />'."\n".
1.298     www      2262: 	    '<br />&nbsp;('.
1.468     albertel 2263: 	    &mt('Message will be sent when you click on Save &amp; Next below.').")\n";
                   2264: 	$result.='</div></div>';
1.121     ng       2265: 	$request->print($result);
1.118     ng       2266:     }
1.41      ng       2267: 
                   2268:     my %seen = ();
                   2269:     my @partlist;
1.129     ng       2270:     my @gradePartRespid;
1.375     albertel 2271:     my @part_response_id = &flatten_responseType($responseType);
1.585     bisitz   2272:     $request->print(
1.588     bisitz   2273:         '<div class="LC_Box">'
                   2274:        .'<h3 class="LC_hcell">'.&mt('Assign Grades').'</h3>'
1.585     bisitz   2275:     );
1.592     bisitz   2276:     $request->print(&gradeBox_start());
1.375     albertel 2277:     foreach my $part_response_id (@part_response_id) {
                   2278:     	my ($partid,$respid) = @{ $part_response_id };
                   2279: 	my $part_resp = join('_',@{ $part_response_id });
1.322     albertel 2280: 	next if ($seen{$partid} > 0);
1.41      ng       2281: 	$seen{$partid}++;
1.393     albertel 2282: 	next if ($$handgrade{$part_resp} ne 'yes' 
                   2283: 		 && $env{'form.lastSub'} eq 'hdgrade');
1.524     raeburn  2284: 	push(@partlist,$partid);
                   2285: 	push(@gradePartRespid,$partid.'.'.$respid);
1.322     albertel 2286: 	$request->print(&gradeBox($request,$symb,$uname,$udom,$counter,$partid,\%record));
1.41      ng       2287:     }
1.585     bisitz   2288:     $request->print(&gradeBox_end()); # </div>
                   2289:     $request->print('</div>');
1.468     albertel 2290: 
                   2291:     $request->print('<div class="LC_grade_info_links">');
                   2292:     $request->print('</div>');
                   2293: 
1.45      ng       2294:     $result='<input type="hidden" name="partlist'.$counter.
                   2295: 	'" value="'.(join ":",@partlist).'" />'."\n";
1.129     ng       2296:     $result.='<input type="hidden" name="gradePartRespid'.
                   2297: 	'" value="'.(join ":",@gradePartRespid).'" />'."\n" if ($counter == 0);
1.45      ng       2298:     my $ctr = 0;
                   2299:     while ($ctr < scalar(@partlist)) {
                   2300: 	$result.='<input type="hidden" name="partid'.$counter.'_'.$ctr.'" value="'.
                   2301: 	    $partlist[$ctr].'" />'."\n";
                   2302: 	$ctr++;
                   2303:     }
1.468     albertel 2304:     $request->print($result.''."\n");
1.41      ng       2305: 
1.441     www      2306: # Done with printing info for one student
                   2307: 
1.468     albertel 2308:     $request->print('</div>');#LC_grade_show_user
1.441     www      2309: 
                   2310: 
1.41      ng       2311:     # print end of form
                   2312:     if ($counter == $total) {
1.592     bisitz   2313:         my $endform='<br /><hr /><table border="0"><tr><td>'."\n";
1.485     albertel 2314: 	$endform.='<input type="button" value="'.&mt('Save &amp; Next').'" '.
1.589     bisitz   2315: 	    'onclick="javascript:checksubmit(this.form,\'Save & Next\','.
1.417     albertel 2316: 	    $total.','.scalar(@partlist).');" target="_self" /> &nbsp;'."\n";
1.119     ng       2317: 	my $ntstu ='<select name="NTSTU">'.
                   2318: 	    '<option>1</option><option>2</option>'.
                   2319: 	    '<option>3</option><option>5</option>'.
                   2320: 	    '<option>7</option><option>10</option></select>'."\n";
1.257     albertel 2321: 	my $nsel = ($env{'form.NTSTU'} ne '' ? $env{'form.NTSTU'} : '1');
1.401     albertel 2322: 	$ntstu =~ s/<option>$nsel</<option selected="selected">$nsel</;
1.578     raeburn  2323:         $endform.=&mt('[_1]student(s)',$ntstu);
1.485     albertel 2324: 	$endform.='&nbsp;&nbsp;<input type="button" value="'.&mt('Previous').'" '.
1.589     bisitz   2325: 	    'onclick="javascript:checksubmit(this.form,\'Previous\');" target="_self" /> &nbsp;'."\n".
1.485     albertel 2326: 	    '<input type="button" value="'.&mt('Next').'" '.
1.589     bisitz   2327: 	    'onclick="javascript:checksubmit(this.form,\'Next\');" target="_self" /> &nbsp;';
1.592     bisitz   2328:         $endform.='<span class="LC_warning">'.
                   2329:                   &mt('(Next and Previous (student) do not save the scores.)').
                   2330:                   '</span>'."\n" ;
1.349     albertel 2331:         $endform.="<input type='hidden' value='".&get_increment().
1.348     bowersj2 2332:             "' name='increment' />";
1.485     albertel 2333: 	$endform.='</td></tr></table></form>';
1.324     albertel 2334: 	$endform.=&show_grading_menu_form($symb);
1.41      ng       2335: 	$request->print($endform);
                   2336:     }
                   2337:     return '';
1.38      ng       2338: }
                   2339: 
1.464     albertel 2340: sub check_collaborators {
                   2341:     my ($symb,$uname,$udom,$record,$handgrade,$counter) = @_;
                   2342:     my ($result,@col_fullnames);
                   2343:     my ($classlist,undef,$fullname) = &getclasslist('all','0');
                   2344:     foreach my $part (keys(%$handgrade)) {
                   2345: 	my $ncol = &Apache::lonnet::EXT('resource.'.$part.
                   2346: 					'.maxcollaborators',
                   2347: 					$symb,$udom,$uname);
                   2348: 	next if ($ncol <= 0);
                   2349: 	$part =~ s/\_/\./g;
                   2350: 	next if ($record->{'resource.'.$part.'.collaborators'} eq '');
                   2351: 	my (@good_collaborators, @bad_collaborators);
                   2352: 	foreach my $possible_collaborator
                   2353: 	    (split(/,?\s+/,$record->{'resource.'.$part.'.collaborators'})) { 
                   2354: 	    $possible_collaborator =~ s/[\$\^\(\)]//g;
                   2355: 	    next if ($possible_collaborator eq '');
                   2356: 	    my ($co_name,$co_dom) = split(/\@|:/,$possible_collaborator);
                   2357: 	    $co_dom = $udom if (! defined($co_dom) || $co_dom =~ /^domain$/i);
                   2358: 	    next if ($co_name eq $uname && $co_dom eq $udom);
                   2359: 	    # Doing this grep allows 'fuzzy' specification
                   2360: 	    my @matches = grep(/^\Q$co_name\E:\Q$co_dom\E$/i, 
                   2361: 			       keys(%$classlist));
                   2362: 	    if (! scalar(@matches)) {
                   2363: 		push(@bad_collaborators, $possible_collaborator);
                   2364: 	    } else {
                   2365: 		push(@good_collaborators, @matches);
                   2366: 	    }
                   2367: 	}
                   2368: 	if (scalar(@good_collaborators) != 0) {
1.466     albertel 2369: 	    $result.='<br />'.&mt('Collaborators: ');
1.464     albertel 2370: 	    foreach my $name (@good_collaborators) {
                   2371: 		my ($lastname,$givenn) = split(/,/,$$fullname{$name});
                   2372: 		push(@col_fullnames, $givenn.' '.$lastname);
                   2373: 		$result.=$fullname->{$name}.'&nbsp; &nbsp; &nbsp;';
                   2374: 	    }
                   2375: 	    $result.='<br />'."\n";
1.466     albertel 2376: 	    my ($part)=split(/\./,$part);
1.464     albertel 2377: 	    $result.='<input type="hidden" name="collaborator'.$counter.
                   2378: 		'" value="'.$part.':'.(join ':',@good_collaborators).'" />'.
                   2379: 		"\n";
                   2380: 	}
                   2381: 	if (scalar(@bad_collaborators) > 0) {
1.466     albertel 2382: 	    $result.='<div class="LC_warning">';
1.464     albertel 2383: 	    $result.=&mt('This student has submitted [quant,_1,invalid collaborator]: [_2]',scalar(@bad_collaborators),join(', ',@bad_collaborators));
                   2384: 	    $result .= '</div>';
                   2385: 	}         
                   2386: 	if (scalar(@bad_collaborators > $ncol)) {
1.466     albertel 2387: 	    $result .= '<div class="LC_warning">';
1.464     albertel 2388: 	    $result .= &mt('This student has submitted too many '.
                   2389: 		'collaborators.  Maximum is [_1].',$ncol);
                   2390: 	    $result .= '</div>';
                   2391: 	}
                   2392:     }
                   2393:     return ($result,$fullname,\@col_fullnames);
                   2394: }
                   2395: 
1.44      ng       2396: #--- Retrieve the last submission for all the parts
1.38      ng       2397: sub get_last_submission {
1.119     ng       2398:     my ($returnhash)=@_;
1.596     raeburn  2399:     my (@string,$timestamp,%lasthidden);
1.119     ng       2400:     if ($$returnhash{'version'}) {
1.46      ng       2401: 	my %lasthash=();
                   2402: 	my ($version);
1.119     ng       2403: 	for ($version=1;$version<=$$returnhash{'version'};$version++) {
1.397     albertel 2404: 	    foreach my $key (sort(split(/\:/,
                   2405: 					$$returnhash{$version.':keys'}))) {
                   2406: 		$lasthash{$key}=$$returnhash{$version.':'.$key};
                   2407: 		$timestamp = 
1.545     raeburn  2408: 		    &Apache::lonlocal::locallocaltime($$returnhash{$version.':timestamp'});
1.46      ng       2409: 	    }
                   2410: 	}
1.596     raeburn  2411:         my %typeparts;
                   2412:         my $showsurv = 
                   2413:             &Apache::lonnet::allowed('vas',$env{'request.course.id'});
                   2414:         foreach my $key (sort(keys(%lasthash))) {
                   2415:             if ($key =~ /\.type$/) {
                   2416:                 if (($lasthash{$key} eq 'anonsurvey') || 
                   2417:                     ($lasthash{$key} eq 'anonsurveycred')) {
                   2418:                     my ($ign,@parts) = split(/\./,$key);
                   2419:                     pop(@parts);
                   2420:                     unless ($showsurv) {
                   2421:                         my $id = join(',',@parts);
                   2422:                         $typeparts{$ign.'.'.$id} = $lasthash{$key};
                   2423:                     }
                   2424:                     delete($lasthash{$key});
                   2425:                 }
                   2426:             }
                   2427:         }
                   2428:         my @hidden = keys(%typeparts);
1.397     albertel 2429: 	foreach my $key (keys(%lasthash)) {
                   2430: 	    next if ($key !~ /\.submission$/);
1.596     raeburn  2431:             my $hide;
                   2432:             if (@hidden) {
                   2433:                 foreach my $id (@hidden) {
                   2434:                     if ($key =~ /^\Q$id\E/) {
                   2435:                         $hide = 1;
                   2436:                         last;
                   2437:                     }
                   2438:                 }
                   2439:             }
1.397     albertel 2440: 	    my ($partid,$foo) = split(/submission$/,$key);
                   2441: 	    my $draft  = $lasthash{$partid.'awarddetail'} eq 'DRAFT' ?
1.398     albertel 2442: 		'<span class="LC_warning">Draft Copy</span> ' : '';
1.596     raeburn  2443: 	    push(@string, join(':', $key, $hide, $draft.$lasthash{$key}));
1.41      ng       2444: 	}
                   2445:     }
1.397     albertel 2446:     if (!@string) {
                   2447: 	$string[0] =
1.539     riegler  2448: 	    '<span class="LC_warning">'.&mt('Nothing submitted - no attempts.').'</span>';
1.397     albertel 2449:     }
                   2450:     return (\@string,\$timestamp);
1.38      ng       2451: }
1.35      ng       2452: 
1.44      ng       2453: #--- High light keywords, with style choosen by user.
1.38      ng       2454: sub keywords_highlight {
1.44      ng       2455:     my $string    = shift;
1.257     albertel 2456:     my $size      = $env{'form.kwsize'} eq '0' ? '' : 'size='.$env{'form.kwsize'};
                   2457:     my $styleon   = $env{'form.kwstyle'} eq ''  ? '' : $env{'form.kwstyle'};
1.41      ng       2458:     (my $styleoff = $styleon) =~ s/\</\<\//;
1.257     albertel 2459:     my @keylist   = split(/[,\s+]/,$env{'form.keywords'});
1.398     albertel 2460:     foreach my $keyword (@keylist) {
                   2461: 	$string =~ s/\b\Q$keyword\E(\b|\.)/<font color\=$env{'form.kwclr'} $size\>$styleon$keyword$styleoff<\/font>/gi;
1.41      ng       2462:     }
                   2463:     return $string;
1.38      ng       2464: }
1.36      ng       2465: 
1.44      ng       2466: #--- Called from submission routine
1.38      ng       2467: sub processHandGrade {
1.608     www      2468:     my ($request,$symb) = @_;
1.324     albertel 2469:     my (undef,undef,$url) = &Apache::lonnet::decode_symb($symb);
1.257     albertel 2470:     my $button = $env{'form.gradeOpt'};
                   2471:     my $ngrade = $env{'form.NCT'};
                   2472:     my $ntstu  = $env{'form.NTSTU'};
1.301     albertel 2473:     my $cdom   = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   2474:     my $cnum   = $env{'course.'.$env{'request.course.id'}.'.num'};
                   2475: 
1.44      ng       2476:     if ($button eq 'Save & Next') {
                   2477: 	my $ctr = 0;
                   2478: 	while ($ctr < $ngrade) {
1.257     albertel 2479: 	    my ($uname,$udom) = split(/:/,$env{'form.unamedom'.$ctr});
1.324     albertel 2480: 	    my ($errorflag,$pts,$wgt) = &saveHandGrade($request,$symb,$uname,$udom,$ctr);
1.71      ng       2481: 	    if ($errorflag eq 'no_score') {
                   2482: 		$ctr++;
                   2483: 		next;
                   2484: 	    }
1.104     albertel 2485: 	    if ($errorflag eq 'not_allowed') {
1.398     albertel 2486: 		$request->print("<span class=\"LC_warning\">Not allowed to modify grades for $uname:$udom</span>");
1.104     albertel 2487: 		$ctr++;
                   2488: 		next;
                   2489: 	    }
1.257     albertel 2490: 	    my $includemsg = $env{'form.includemsg'.$ctr};
1.44      ng       2491: 	    my ($subject,$message,$msgstatus) = ('','','');
1.418     albertel 2492: 	    my $restitle = &Apache::lonnet::gettitle($symb);
                   2493:             my ($feedurl,$showsymb) =
                   2494: 		&get_feedurl_and_symb($symb,$uname,$udom);
                   2495: 	    my $messagetail;
1.62      albertel 2496: 	    if ($includemsg =~ /savemsg|newmsg\Q$ctr\E/) {
1.298     www      2497: 		$subject = $env{'form.msgsub'} if ($includemsg =~ /msgsub/);
1.295     www      2498: 		unless ($subject=~/\w/) { $subject=&mt('Grading Feedback'); }
1.386     raeburn  2499: 		$subject.=' ['.$restitle.']';
1.44      ng       2500: 		my (@msgnum) = split(/,/,$includemsg);
                   2501: 		foreach (@msgnum) {
1.257     albertel 2502: 		    $message.=$env{'form.'.$_} if ($_ =~ /savemsg|newmsg/ && $_ ne '');
1.44      ng       2503: 		}
1.80      ng       2504: 		$message =&Apache::lonfeedback::clear_out_html($message);
1.298     www      2505: 		if ($env{'form.withgrades'.$ctr}) {
                   2506: 		    $message.="\n\nPoint".($pts > 1 ? 's':'').' awarded = '.$pts.' out of '.$wgt;
1.386     raeburn  2507: 		    $messagetail = " for <a href=\"".
1.605     www      2508: 		                   $feedurl."?symb=$showsymb\">$restitle</a>";
1.386     raeburn  2509: 		}
                   2510: 		$msgstatus = 
                   2511:                     &Apache::lonmsg::user_normal_msg($uname,$udom,$subject,
                   2512: 						     $message.$messagetail,
1.418     albertel 2513:                                                      undef,$feedurl,undef,
1.386     raeburn  2514:                                                      undef,undef,$showsymb,
                   2515:                                                      $restitle);
1.574     bisitz   2516: 		$request->print('<br />'.&mt('Sending message to [_1]',$uname.':'.$udom).': '.
1.296     www      2517: 				$msgstatus);
1.44      ng       2518: 	    }
1.257     albertel 2519: 	    if ($env{'form.collaborator'.$ctr}) {
1.155     albertel 2520: 		my @collabstrs=&Apache::loncommon::get_env_multiple("form.collaborator$ctr");
1.150     albertel 2521: 		foreach my $collabstr (@collabstrs) {
                   2522: 		    my ($part,@collaborators) = split(/:/,$collabstr);
1.310     banghart 2523: 		    foreach my $collaborator (@collaborators) {
1.150     albertel 2524: 			my ($errorflag,$pts,$wgt) = 
1.324     albertel 2525: 			    &saveHandGrade($request,$symb,$collaborator,$udom,$ctr,
1.257     albertel 2526: 					   $env{'form.unamedom'.$ctr},$part);
1.150     albertel 2527: 			if ($errorflag eq 'not_allowed') {
1.362     albertel 2528: 			    $request->print("<span class=\"LC_error\">".&mt('Not allowed to modify grades for [_1]',"$collaborator:$udom")."</span>");
1.150     albertel 2529: 			    next;
1.418     albertel 2530: 			} elsif ($message ne '') {
                   2531: 			    my ($baseurl,$showsymb) = 
                   2532: 				&get_feedurl_and_symb($symb,$collaborator,
                   2533: 						      $udom);
                   2534: 			    if ($env{'form.withgrades'.$ctr}) {
                   2535: 				$messagetail = " for <a href=\"".
1.605     www      2536:                                     $baseurl."?symb=$showsymb\">$restitle</a>";
1.150     albertel 2537: 			    }
1.418     albertel 2538: 			    $msgstatus = 
                   2539: 				&Apache::lonmsg::user_normal_msg($collaborator,$udom,$subject,$message.$messagetail,undef,$baseurl,undef,undef,undef,$showsymb,$restitle);
1.104     albertel 2540: 			}
1.44      ng       2541: 		    }
                   2542: 		}
                   2543: 	    }
                   2544: 	    $ctr++;
                   2545: 	}
                   2546:     }
                   2547: 
1.257     albertel 2548:     if ($env{'form.handgrade'} eq 'yes') {
1.119     ng       2549: 	# Keywords sorted in alphabatical order
1.257     albertel 2550: 	my $loginuser = $env{'user.name'}.':'.$env{'user.domain'};
1.119     ng       2551: 	my %keyhash = ();
1.257     albertel 2552: 	$env{'form.keywords'}           =~ s/,\s{0,}|\s+/ /g;
                   2553: 	$env{'form.keywords'}           =~ s/^\s+|\s+$//;
                   2554: 	my (@keywords) = sort(split(/\s+/,$env{'form.keywords'}));
                   2555: 	$env{'form.keywords'} = join(' ',@keywords);
                   2556: 	$keyhash{$symb.'_keywords'}     = $env{'form.keywords'};
                   2557: 	$keyhash{$symb.'_subject'}      = $env{'form.msgsub'};
                   2558: 	$keyhash{$loginuser.'_kwclr'}   = $env{'form.kwclr'};
                   2559: 	$keyhash{$loginuser.'_kwsize'}  = $env{'form.kwsize'};
                   2560: 	$keyhash{$loginuser.'_kwstyle'} = $env{'form.kwstyle'};
1.119     ng       2561: 
                   2562: 	# message center - Order of message gets changed. Blank line is eliminated.
1.257     albertel 2563: 	# New messages are saved in env for the next student.
1.119     ng       2564: 	# All messages are saved in nohist_handgrade.db
                   2565: 	my ($ctr,$idx) = (1,1);
1.257     albertel 2566: 	while ($ctr <= $env{'form.savemsgN'}) {
                   2567: 	    if ($env{'form.savemsg'.$ctr} ne '') {
                   2568: 		$keyhash{$symb.'_savemsg'.$idx} = $env{'form.savemsg'.$ctr};
1.119     ng       2569: 		$idx++;
                   2570: 	    }
                   2571: 	    $ctr++;
1.41      ng       2572: 	}
1.119     ng       2573: 	$ctr = 0;
                   2574: 	while ($ctr < $ngrade) {
1.257     albertel 2575: 	    if ($env{'form.newmsg'.$ctr} ne '') {
                   2576: 		$keyhash{$symb.'_savemsg'.$idx} = $env{'form.newmsg'.$ctr};
                   2577: 		$env{'form.savemsg'.$idx} = $env{'form.newmsg'.$ctr};
1.119     ng       2578: 		$idx++;
                   2579: 	    }
                   2580: 	    $ctr++;
1.41      ng       2581: 	}
1.257     albertel 2582: 	$env{'form.savemsgN'} = --$idx;
                   2583: 	$keyhash{$symb.'_savemsgN'} = $env{'form.savemsgN'};
1.119     ng       2584: 	my $putresult = &Apache::lonnet::put
1.301     albertel 2585: 	    ('nohist_handgrade',\%keyhash,$cdom,$cnum);
1.41      ng       2586:     }
1.44      ng       2587:     # Called by Save & Refresh from Highlight Attribute Window
1.257     albertel 2588:     my (undef,undef,$fullname) = &getclasslist($env{'form.section'},'1');
                   2589:     if ($env{'form.refresh'} eq 'on') {
1.86      ng       2590: 	my ($ctr,$total) = (0,0);
                   2591: 	while ($ctr < $ngrade) {
1.257     albertel 2592: 	    $total++ if  $env{'form.unamedom'.$ctr} ne '';
1.86      ng       2593: 	    $ctr++;
                   2594: 	}
1.257     albertel 2595: 	$env{'form.NTSTU'}=$ngrade;
1.86      ng       2596: 	$ctr = 0;
                   2597: 	while ($ctr < $total) {
1.257     albertel 2598: 	    my $processUser = $env{'form.unamedom'.$ctr};
                   2599: 	    ($env{'form.student'},$env{'form.userdom'}) = split(/:/,$processUser);
                   2600: 	    $env{'form.fullname'} = $$fullname{$processUser};
1.86      ng       2601: 	    &submission($request,$ctr,$total-1);
1.41      ng       2602: 	    $ctr++;
                   2603: 	}
                   2604: 	return '';
                   2605:     }
1.36      ng       2606: 
1.121     ng       2607: # Go directly to grade student - from submission or link from chart page
1.120     ng       2608:     if ($button eq 'Grade Student') {
1.598     www      2609: #	(undef,undef,$env{'form.handgrade'},undef,undef) = &showResourceInfo($symb);
1.257     albertel 2610: 	my $processUser = $env{'form.unamedom'.$env{'form.studentNo'}};
                   2611: 	($env{'form.student'},$env{'form.userdom'}) = split(/:/,$processUser);
                   2612: 	$env{'form.fullname'} = $$fullname{$processUser};
1.120     ng       2613: 	&submission($request,0,0);
                   2614: 	return '';
                   2615:     }
                   2616: 
1.44      ng       2617:     # Get the next/previous one or group of students
1.257     albertel 2618:     my $firststu = $env{'form.unamedom0'};
                   2619:     my $laststu = $env{'form.unamedom'.($ngrade-1)};
1.119     ng       2620:     my $ctr = 2;
1.41      ng       2621:     while ($laststu eq '') {
1.257     albertel 2622: 	$laststu  = $env{'form.unamedom'.($ngrade-$ctr)};
1.41      ng       2623: 	$ctr++;
                   2624: 	$laststu = $firststu if ($ctr > $ngrade);
                   2625:     }
1.44      ng       2626: 
1.41      ng       2627:     my (@parsedlist,@nextlist);
                   2628:     my ($nextflg) = 0;
1.524     raeburn  2629:     foreach my $item (sort 
1.294     albertel 2630: 	     {
                   2631: 		 if (lc($$fullname{$a}) ne lc($$fullname{$b})) {
                   2632: 		     return (lc($$fullname{$a}) cmp lc($$fullname{$b}));
                   2633: 		 }
                   2634: 		 return $a cmp $b;
                   2635: 	     } (keys(%$fullname))) {
1.605     www      2636: # FIXME: this is fishy, looks like the button label
1.41      ng       2637: 	if ($nextflg == 1 && $button =~ /Next$/) {
1.524     raeburn  2638: 	    push(@parsedlist,$item);
1.41      ng       2639: 	}
1.524     raeburn  2640: 	$nextflg = 1 if ($item eq $laststu);
1.41      ng       2641: 	if ($button eq 'Previous') {
1.524     raeburn  2642: 	    last if ($item eq $firststu);
                   2643: 	    push(@parsedlist,$item);
1.41      ng       2644: 	}
                   2645:     }
                   2646:     $ctr = 0;
1.605     www      2647: # FIXME: this is fishy, looks like the button label
1.41      ng       2648:     @parsedlist = reverse @parsedlist if ($button eq 'Previous');
1.582     raeburn  2649:     my $res_error;
                   2650:     my ($partlist) = &response_type($symb,\$res_error);
                   2651:     if ($res_error) {
                   2652:         $request->print(&navmap_errormsg());
                   2653:         return;
                   2654:     }
1.41      ng       2655:     foreach my $student (@parsedlist) {
1.257     albertel 2656: 	my $submitonly=$env{'form.submitonly'};
1.41      ng       2657: 	my ($uname,$udom) = split(/:/,$student);
1.301     albertel 2658: 	
                   2659: 	if ($submitonly eq 'queued') {
                   2660: 	    my %queue_status = 
                   2661: 		&Apache::bridgetask::get_student_status($symb,$cdom,$cnum,
                   2662: 							$udom,$uname);
                   2663: 	    next if (!defined($queue_status{'gradingqueue'}));
                   2664: 	}
                   2665: 
1.156     albertel 2666: 	if ($submitonly =~ /^(yes|graded|incorrect)$/) {
1.257     albertel 2667: #	    my %record = &Apache::lonnet::restore($symb,$env{'request.course.id'},$udom,$uname);
1.324     albertel 2668: 	    my %status=&student_gradeStatus($symb,$udom,$uname,$partlist);
1.145     albertel 2669: 	    my $submitted = 0;
1.248     albertel 2670: 	    my $ungraded = 0;
                   2671: 	    my $incorrect = 0;
1.524     raeburn  2672: 	    foreach my $item (keys(%status)) {
                   2673: 		$submitted = 1 if ($status{$item} ne 'nothing');
                   2674: 		$ungraded = 1 if ($status{$item} =~ /^ungraded/);
                   2675: 		$incorrect = 1 if ($status{$item} =~ /^incorrect/);
                   2676: 		my ($foo,$partid,$foo1) = split(/\./,$item);
1.145     albertel 2677: 		if ($status{'resource.'.$partid.'.submitted_by'} ne '') {
                   2678: 		    $submitted = 0;
                   2679: 		}
1.41      ng       2680: 	    }
1.156     albertel 2681: 	    next if (!$submitted && ($submitonly eq 'yes' ||
                   2682: 				     $submitonly eq 'incorrect' ||
                   2683: 				     $submitonly eq 'graded'));
1.248     albertel 2684: 	    next if (!$ungraded && ($submitonly eq 'graded'));
                   2685: 	    next if (!$incorrect && $submitonly eq 'incorrect');
1.41      ng       2686: 	}
1.524     raeburn  2687: 	push(@nextlist,$student) if ($ctr < $ntstu);
1.129     ng       2688: 	last if ($ctr == $ntstu);
1.41      ng       2689: 	$ctr++;
                   2690:     }
1.36      ng       2691: 
1.41      ng       2692:     $ctr = 0;
                   2693:     my $total = scalar(@nextlist)-1;
1.39      ng       2694: 
1.524     raeburn  2695:     foreach (sort(@nextlist)) {
1.41      ng       2696: 	my ($uname,$udom,$submitter) = split(/:/);
1.257     albertel 2697: 	$env{'form.student'}  = $uname;
                   2698: 	$env{'form.userdom'}  = $udom;
                   2699: 	$env{'form.fullname'} = $$fullname{$_};
1.41      ng       2700: 	&submission($request,$ctr,$total);
                   2701: 	$ctr++;
                   2702:     }
                   2703:     if ($total < 0) {
1.485     albertel 2704: 	my $the_end = '<h3><span class="LC_info">'.&mt('LON-CAPA User Message').'</span></h3><br />'."\n";
                   2705: 	$the_end.=&mt('<b>Message: </b> No more students for this section or class.').'<br /><br />'."\n";
                   2706: 	$the_end.=&mt('Click on the button below to return to the grading menu.').'<br /><br />'."\n";
1.324     albertel 2707: 	$the_end.=&show_grading_menu_form($symb);
1.41      ng       2708: 	$request->print($the_end);
                   2709:     }
                   2710:     return '';
1.38      ng       2711: }
1.36      ng       2712: 
1.44      ng       2713: #---- Save the score and award for each student, if changed
1.38      ng       2714: sub saveHandGrade {
1.324     albertel 2715:     my ($request,$symb,$stuname,$domain,$newflg,$submitter,$part) = @_;
1.342     banghart 2716:     my @version_parts;
1.104     albertel 2717:     my $usec = &Apache::lonnet::getsection($domain,$stuname,
1.257     albertel 2718: 					   $env{'request.course.id'});
1.104     albertel 2719:     if (!&canmodify($usec)) { return('not_allowed'); }
1.337     banghart 2720:     my %record = &Apache::lonnet::restore($symb,$env{'request.course.id'},$domain,$stuname);
1.251     banghart 2721:     my @parts_graded;
1.77      ng       2722:     my %newrecord  = ();
                   2723:     my ($pts,$wgt) = ('','');
1.269     raeburn  2724:     my %aggregate = ();
                   2725:     my $aggregateflag = 0;
1.301     albertel 2726:     my @parts = split(/:/,$env{'form.partlist'.$newflg});
                   2727:     foreach my $new_part (@parts) {
1.337     banghart 2728: 	#collaborator ($submi may vary for different parts
1.259     banghart 2729: 	if ($submitter && $new_part ne $part) { next; }
                   2730: 	my $dropMenu = $env{'form.GD_SEL'.$newflg.'_'.$new_part};
1.125     ng       2731: 	if ($dropMenu eq 'excused') {
1.259     banghart 2732: 	    if ($record{'resource.'.$new_part.'.solved'} ne 'excused') {
                   2733: 		$newrecord{'resource.'.$new_part.'.solved'} = 'excused';
                   2734: 		if (exists($record{'resource.'.$new_part.'.awarded'})) {
                   2735: 		    $newrecord{'resource.'.$new_part.'.awarded'} = '';
1.58      albertel 2736: 		}
1.364     banghart 2737: 	        $newrecord{'resource.'.$new_part.'.regrader'}="$env{'user.name'}:$env{'user.domain'}";
1.58      albertel 2738: 	    }
1.125     ng       2739: 	} elsif ($dropMenu eq 'reset status'
1.259     banghart 2740: 		 && exists($record{'resource.'.$new_part.'.solved'})) { #don't bother if no old records -> no attempts
1.524     raeburn  2741: 	    foreach my $key (keys(%record)) {
1.259     banghart 2742: 		if ($key=~/^resource\.\Q$new_part\E\./) { $newrecord{$key} = ''; }
1.197     albertel 2743: 	    }
1.259     banghart 2744: 	    $newrecord{'resource.'.$new_part.'.regrader'}=
1.257     albertel 2745: 		"$env{'user.name'}:$env{'user.domain'}";
1.270     albertel 2746:             my $totaltries = $record{'resource.'.$part.'.tries'};
                   2747: 
                   2748:             my %last_resets = &get_last_resets($symb,$env{'request.course.id'},
                   2749: 					       [$new_part]);
                   2750:             my $aggtries =$totaltries;
1.269     raeburn  2751:             if ($last_resets{$new_part}) {
1.270     albertel 2752:                 $aggtries = &get_num_tries(\%record,$last_resets{$new_part},
                   2753: 					   $new_part);
1.269     raeburn  2754:             }
1.270     albertel 2755: 
                   2756:             my $solvedstatus = $record{'resource.'.$new_part.'.solved'};
1.269     raeburn  2757:             if ($aggtries > 0) {
1.327     albertel 2758:                 &decrement_aggs($symb,$new_part,\%aggregate,$aggtries,$totaltries,$solvedstatus);
1.269     raeburn  2759:                 $aggregateflag = 1;
                   2760:             }
1.125     ng       2761: 	} elsif ($dropMenu eq '') {
1.259     banghart 2762: 	    $pts = ($env{'form.GD_BOX'.$newflg.'_'.$new_part} ne '' ? 
                   2763: 		    $env{'form.GD_BOX'.$newflg.'_'.$new_part} : 
                   2764: 		    $env{'form.RADVAL'.$newflg.'_'.$new_part});
                   2765: 	    if ($pts eq '' && $env{'form.GD_SEL'.$newflg.'_'.$new_part} eq '') {
1.153     albertel 2766: 		next;
                   2767: 	    }
1.259     banghart 2768: 	    $wgt = $env{'form.WGT'.$newflg.'_'.$new_part} eq '' ? 1 : 
                   2769: 		$env{'form.WGT'.$newflg.'_'.$new_part};
1.41      ng       2770: 	    my $partial= $pts/$wgt;
1.259     banghart 2771: 	    if ($partial eq $record{'resource.'.$new_part.'.awarded'}) {
1.153     albertel 2772: 		#do not update score for part if not changed.
1.346     banghart 2773:                 &handback_files($request,$symb,$stuname,$domain,$newflg,$new_part,\%newrecord);
1.153     albertel 2774: 		next;
1.251     banghart 2775: 	    } else {
1.524     raeburn  2776: 	        push(@parts_graded,$new_part);
1.153     albertel 2777: 	    }
1.259     banghart 2778: 	    if ($record{'resource.'.$new_part.'.awarded'} ne $partial) {
                   2779: 		$newrecord{'resource.'.$new_part.'.awarded'}  = $partial;
1.153     albertel 2780: 	    }
1.259     banghart 2781: 	    my $reckey = 'resource.'.$new_part.'.solved';
1.41      ng       2782: 	    if ($partial == 0) {
1.153     albertel 2783: 		if ($record{$reckey} ne 'incorrect_by_override') {
                   2784: 		    $newrecord{$reckey} = 'incorrect_by_override';
                   2785: 		}
1.41      ng       2786: 	    } else {
1.153     albertel 2787: 		if ($record{$reckey} ne 'correct_by_override') {
                   2788: 		    $newrecord{$reckey} = 'correct_by_override';
                   2789: 		}
                   2790: 	    }	    
                   2791: 	    if ($submitter && 
1.259     banghart 2792: 		($record{'resource.'.$new_part.'.submitted_by'} ne $submitter)) {
                   2793: 		$newrecord{'resource.'.$new_part.'.submitted_by'} = $submitter;
1.41      ng       2794: 	    }
1.259     banghart 2795: 	    $newrecord{'resource.'.$new_part.'.regrader'}=
1.257     albertel 2796: 		"$env{'user.name'}:$env{'user.domain'}";
1.41      ng       2797: 	}
1.259     banghart 2798: 	# unless problem has been graded, set flag to version the submitted files
1.305     banghart 2799: 	unless ($record{'resource.'.$new_part.'.solved'} =~ /^correct_/  || 
                   2800: 	        $record{'resource.'.$new_part.'.solved'} eq 'incorrect_by_override' ||
                   2801: 	        $dropMenu eq 'reset status')
                   2802: 	   {
1.524     raeburn  2803: 	    push(@version_parts,$new_part);
1.259     banghart 2804: 	}
1.41      ng       2805:     }
1.301     albertel 2806:     my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   2807:     my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   2808: 
1.344     albertel 2809:     if (%newrecord) {
                   2810:         if (@version_parts) {
1.364     banghart 2811:             my @changed_keys = &version_portfiles(\%record, \@parts_graded, 
                   2812:                                 $env{'request.course.id'}, $symb, $domain, $stuname, \@version_parts);
1.344     albertel 2813: 	    @newrecord{@changed_keys} = @record{@changed_keys};
1.367     albertel 2814: 	    foreach my $new_part (@version_parts) {
                   2815: 		&handback_files($request,$symb,$stuname,$domain,$newflg,
                   2816: 				$new_part,\%newrecord);
                   2817: 	    }
1.259     banghart 2818:         }
1.44      ng       2819: 	&Apache::lonnet::cstore(\%newrecord,$symb,
1.257     albertel 2820: 				$env{'request.course.id'},$domain,$stuname);
1.380     albertel 2821: 	&check_and_remove_from_queue(\@parts,\%record,\%newrecord,$symb,
                   2822: 				     $cdom,$cnum,$domain,$stuname);
1.41      ng       2823:     }
1.269     raeburn  2824:     if ($aggregateflag) {
                   2825:         &Apache::lonnet::cinc('nohist_resourcetracker',\%aggregate,
1.301     albertel 2826: 			      $cdom,$cnum);
1.269     raeburn  2827:     }
1.301     albertel 2828:     return ('',$pts,$wgt);
1.36      ng       2829: }
1.322     albertel 2830: 
1.380     albertel 2831: sub check_and_remove_from_queue {
                   2832:     my ($parts,$record,$newrecord,$symb,$cdom,$cnum,$domain,$stuname) = @_;
                   2833:     my @ungraded_parts;
                   2834:     foreach my $part (@{$parts}) {
                   2835: 	if (    $record->{   'resource.'.$part.'.awarded'} eq ''
                   2836: 	     && $record->{   'resource.'.$part.'.solved' } ne 'excused'
                   2837: 	     && $newrecord->{'resource.'.$part.'.awarded'} eq ''
                   2838: 	     && $newrecord->{'resource.'.$part.'.solved' } ne 'excused'
                   2839: 		) {
                   2840: 	    push(@ungraded_parts, $part);
                   2841: 	}
                   2842:     }
                   2843:     if ( !@ungraded_parts ) {
                   2844: 	&Apache::bridgetask::remove_from_queue('gradingqueue',$symb,$cdom,
                   2845: 					       $cnum,$domain,$stuname);
                   2846:     }
                   2847: }
                   2848: 
1.337     banghart 2849: sub handback_files {
                   2850:     my ($request,$symb,$stuname,$domain,$newflg,$new_part,$newrecord) = @_;
1.517     raeburn  2851:     my $portfolio_root = '/userfiles/portfolio';
1.582     raeburn  2852:     my $res_error;
                   2853:     my ($partlist,$handgrade,$responseType) = &response_type($symb,\$res_error);
                   2854:     if ($res_error) {
                   2855:         $request->print('<br />'.&navmap_errormsg().'<br />');
                   2856:         return;
                   2857:     }
1.375     albertel 2858:     my @part_response_id = &flatten_responseType($responseType);
                   2859:     foreach my $part_response_id (@part_response_id) {
                   2860:     	my ($part_id,$resp_id) = @{ $part_response_id };
                   2861: 	my $part_resp = join('_',@{ $part_response_id });
1.337     banghart 2862:             if (($env{'form.'.$newflg.'_'.$part_resp.'_returndoc1'}) && ($new_part == $part_id)) {
                   2863:                 # if multiple files are uploaded names will be 'returndoc2','returndoc3'
                   2864:                 my $file_counter = 1;
1.367     albertel 2865: 		my $file_msg;
1.337     banghart 2866:                 while ($env{'form.'.$newflg.'_'.$part_resp.'_returndoc'.$file_counter}) {
                   2867:                     my $fname=$env{'form.'.$newflg.'_'.$part_resp.'_returndoc'.$file_counter.'.filename'};
1.338     banghart 2868:                     my ($directory,$answer_file) = 
                   2869:                         ($env{'form.'.$newflg.'_'.$part_resp.'_origdoc'.$file_counter} =~ /^(.*?)([^\/]*)$/);
                   2870:                     my ($answer_name,$answer_ver,$answer_ext) =
                   2871: 		        &file_name_version_ext($answer_file);
1.355     banghart 2872: 		    my ($portfolio_path) = ($directory =~ /^.+$stuname\/portfolio(.*)/);
1.517     raeburn  2873:                     my $getpropath = 1;
                   2874: 		    my @dir_list = &Apache::lonnet::dirlist($portfolio_root.$portfolio_path,$domain,$stuname,$getpropath);
1.338     banghart 2875: 		    my $version = &get_next_version($answer_name, $answer_ext, \@dir_list);
1.355     banghart 2876:                     # fix file name
                   2877:                     my ($save_file_name) = (($directory.$answer_name.".$version.".$answer_ext) =~ /^.+\/${stuname}\/(.*)/);
                   2878:                     my $result=&Apache::lonnet::finishuserfileupload($stuname,$domain,
                   2879:             	                                $newflg.'_'.$part_resp.'_returndoc'.$file_counter,
                   2880:             	                                $save_file_name);
1.337     banghart 2881:                     if ($result !~ m|^/uploaded/|) {
1.536     raeburn  2882:                         $request->print('<br /><span class="LC_error">'.
                   2883:                             &mt('An error occurred ([_1]) while trying to upload [_2].',
                   2884:                                 $result,$newflg.'_'.$part_resp.'_returndoc'.$file_counter).
                   2885:                                         '</span>');
1.356     banghart 2886:                     } else {
1.360     banghart 2887:                         # mark the file as read only
                   2888:                         my @files = ($save_file_name);
1.372     albertel 2889:                         my @what = ($symb,$env{'request.course.id'},'handback');
1.360     banghart 2890:                         &Apache::lonnet::mark_as_readonly($domain,$stuname,\@files,\@what);
1.367     albertel 2891: 			if (exists($$newrecord{"resource.$new_part.$resp_id.handback"})) {
                   2892: 			    $$newrecord{"resource.$new_part.$resp_id.handback"}.=',';
                   2893: 			}
                   2894:                         $$newrecord{"resource.$new_part.$resp_id.handback"} .= $save_file_name;
                   2895: 			$file_msg.= "\n".'<br /><span class="LC_filename"><a href="/uploaded/'."$domain/$stuname/".$save_file_name.'">'.$save_file_name."</a></span><br />";
                   2896: 
1.337     banghart 2897:                     }
                   2898:                     $request->print("<br />".$fname." will be the uploaded file name");
1.354     albertel 2899:                     $request->print(" ".$env{'form.'.$newflg.'_'.$part_resp.'_origdoc'.$file_counter});
1.337     banghart 2900:                     $file_counter++;
                   2901:                 }
1.367     albertel 2902: 		my $subject = "File Handed Back by Instructor ";
                   2903: 		my $message = "A file has been returned that was originally submitted in reponse to: <br />";
                   2904: 		$message .= "<strong>".&Apache::lonnet::gettitle($symb)."</strong><br />";
                   2905: 		$message .= ' The returned file(s) are named: '. $file_msg;
                   2906: 		$message .= " and can be found in your portfolio space.";
1.418     albertel 2907: 		my ($feedurl,$showsymb) = 
                   2908: 		    &get_feedurl_and_symb($symb,$domain,$stuname);
1.386     raeburn  2909:                 my $restitle = &Apache::lonnet::gettitle($symb);
                   2910: 		my $msgstatus = 
                   2911:                    &Apache::lonmsg::user_normal_msg($stuname,$domain,$subject.
                   2912: 			 ' (File Returned) ['.$restitle.']',$message,undef,
1.418     albertel 2913:                          $feedurl,undef,undef,undef,$showsymb,$restitle);
1.337     banghart 2914:             }
                   2915:         }
1.338     banghart 2916:     return;
1.337     banghart 2917: }
                   2918: 
1.418     albertel 2919: sub get_feedurl_and_symb {
                   2920:     my ($symb,$uname,$udom) = @_;
                   2921:     my (undef,undef,$url) = &Apache::lonnet::decode_symb($symb);
                   2922:     $url = &Apache::lonnet::clutter($url);
                   2923:     my $encrypturl=&Apache::lonnet::EXT('resource.0.encrypturl',
                   2924: 					$symb,$udom,$uname);
                   2925:     if ($encrypturl =~ /^yes$/i) {
                   2926: 	&Apache::lonenc::encrypted(\$url,1);
                   2927: 	&Apache::lonenc::encrypted(\$symb,1);
                   2928:     }
                   2929:     return ($url,$symb);
                   2930: }
                   2931: 
1.313     banghart 2932: sub get_submitted_files {
                   2933:     my ($udom,$uname,$partid,$respid,$record) = @_;
                   2934:     my @files;
                   2935:     if ($$record{"resource.$partid.$respid.portfiles"}) {
                   2936:         my $file_url = '/uploaded/'.$udom.'/'.$uname.'/portfolio';
                   2937:         foreach my $file (split(',',$$record{"resource.$partid.$respid.portfiles"})) {
                   2938:     	    push(@files,$file_url.$file);
                   2939:         }
                   2940:     }
                   2941:     if ($$record{"resource.$partid.$respid.uploadedurl"}) {
                   2942:         push(@files,$$record{"resource.$partid.$respid.uploadedurl"});
                   2943:     }
                   2944:     return (\@files);
                   2945: }
1.322     albertel 2946: 
1.269     raeburn  2947: # ----------- Provides number of tries since last reset.
                   2948: sub get_num_tries {
                   2949:     my ($record,$last_reset,$part) = @_;
                   2950:     my $timestamp = '';
                   2951:     my $num_tries = 0;
                   2952:     if ($$record{'version'}) {
                   2953:         for (my $version=$$record{'version'};$version>=1;$version--) {
                   2954:             if (exists($$record{$version.':resource.'.$part.'.solved'})) {
                   2955:                 $timestamp = $$record{$version.':timestamp'};
                   2956:                 if ($timestamp > $last_reset) {
                   2957:                     $num_tries ++;
                   2958:                 } else {
                   2959:                     last;
                   2960:                 }
                   2961:             }
                   2962:         }
                   2963:     }
                   2964:     return $num_tries;
                   2965: }
                   2966: 
                   2967: # ----------- Determine decrements required in aggregate totals 
                   2968: sub decrement_aggs {
                   2969:     my ($symb,$part,$aggregate,$aggtries,$totaltries,$solvedstatus) = @_;
                   2970:     my %decrement = (
                   2971:                         attempts => 0,
                   2972:                         users => 0,
                   2973:                         correct => 0
                   2974:                     );
                   2975:     $decrement{'attempts'} = $aggtries;
                   2976:     if ($solvedstatus =~ /^correct/) {
                   2977:         $decrement{'correct'} = 1;
                   2978:     }
                   2979:     if ($aggtries == $totaltries) {
                   2980:         $decrement{'users'} = 1;
                   2981:     }
1.524     raeburn  2982:     foreach my $type (keys(%decrement)) {
1.269     raeburn  2983:         $$aggregate{$symb."\0".$part."\0".$type} = -$decrement{$type};
                   2984:     }
                   2985:     return;
                   2986: }
                   2987: 
                   2988: # ----------- Determine timestamps for last reset of aggregate totals for parts  
                   2989: sub get_last_resets {
1.270     albertel 2990:     my ($symb,$courseid,$partids) =@_;
                   2991:     my %last_resets;
1.269     raeburn  2992:     my $cdom = $env{'course.'.$courseid.'.domain'};
                   2993:     my $cname = $env{'course.'.$courseid.'.num'};
1.271     albertel 2994:     my @keys;
                   2995:     foreach my $part (@{$partids}) {
                   2996: 	push(@keys,"$symb\0$part\0resettime");
                   2997:     }
                   2998:     my %results=&Apache::lonnet::get('nohist_resourcetracker',\@keys,
                   2999: 				     $cdom,$cname);
                   3000:     foreach my $part (@{$partids}) {
                   3001: 	$last_resets{$part}=$results{"$symb\0$part\0resettime"};
1.269     raeburn  3002:     }
1.270     albertel 3003:     return %last_resets;
1.269     raeburn  3004: }
                   3005: 
1.251     banghart 3006: # ----------- Handles creating versions for portfolio files as answers
                   3007: sub version_portfiles {
1.343     banghart 3008:     my ($record, $parts_graded, $courseid, $symb, $domain, $stu_name, $v_flag) = @_;
1.263     banghart 3009:     my $version_parts = join('|',@$v_flag);
1.343     banghart 3010:     my @returned_keys;
1.255     banghart 3011:     my $parts = join('|', @$parts_graded);
1.517     raeburn  3012:     my $portfolio_root = '/userfiles/portfolio';
1.277     albertel 3013:     foreach my $key (keys(%$record)) {
1.259     banghart 3014:         my $new_portfiles;
1.263     banghart 3015:         if ($key =~ /^resource\.($version_parts)\./ && $key =~ /\.portfiles$/ ) {
1.342     banghart 3016:             my @versioned_portfiles;
1.367     albertel 3017:             my @portfiles = split(/\s*,\s*/,$$record{$key});
1.252     banghart 3018:             foreach my $file (@portfiles) {
1.306     banghart 3019:                 &Apache::lonnet::unmark_as_readonly($domain,$stu_name,[$symb,$env{'request.course.id'}],$file);
1.304     albertel 3020:                 my ($directory,$answer_file) =($file =~ /^(.*?)([^\/]*)$/);
                   3021: 		my ($answer_name,$answer_ver,$answer_ext) =
                   3022: 		    &file_name_version_ext($answer_file);
1.517     raeburn  3023:                 my $getpropath = 1;    
                   3024:                 my @dir_list = &Apache::lonnet::dirlist($portfolio_root.$directory,$domain,$stu_name,$getpropath);
1.342     banghart 3025:                 my $version = &get_next_version($answer_name, $answer_ext, \@dir_list);
1.306     banghart 3026:                 my $new_answer = &version_selected_portfile($domain, $stu_name, $directory, $answer_file, $version);
                   3027:                 if ($new_answer ne 'problem getting file') {
1.342     banghart 3028:                     push(@versioned_portfiles, $directory.$new_answer);
1.306     banghart 3029:                     &Apache::lonnet::mark_as_readonly($domain,$stu_name,
1.367     albertel 3030:                         [$directory.$new_answer],
1.306     banghart 3031:                         [$symb,$env{'request.course.id'},'graded']);
1.259     banghart 3032:                 }
1.252     banghart 3033:             }
1.343     banghart 3034:             $$record{$key} = join(',',@versioned_portfiles);
                   3035:             push(@returned_keys,$key);
1.251     banghart 3036:         }
                   3037:     } 
1.343     banghart 3038:     return (@returned_keys);   
1.305     banghart 3039: }
                   3040: 
1.307     banghart 3041: sub get_next_version {
1.341     banghart 3042:     my ($answer_name, $answer_ext, $dir_list) = @_;
1.307     banghart 3043:     my $version;
                   3044:     foreach my $row (@$dir_list) {
                   3045:         my ($file) = split(/\&/,$row,2);
                   3046:         my ($file_name,$file_version,$file_ext) =
                   3047: 	    &file_name_version_ext($file);
                   3048:         if (($file_name eq $answer_name) && 
                   3049: 	    ($file_ext eq $answer_ext)) {
                   3050:                 # gets here if filename and extension match, regardless of version
                   3051:                 if ($file_version ne '') {
                   3052:                 # a versioned file is found  so save it for later
                   3053:                 if ($file_version > $version) {
                   3054: 		    $version = $file_version;
                   3055: 	        }
                   3056:             }
                   3057:         }
                   3058:     } 
                   3059:     $version ++;
                   3060:     return($version);
                   3061: }
                   3062: 
1.305     banghart 3063: sub version_selected_portfile {
1.306     banghart 3064:     my ($domain,$stu_name,$directory,$file_name,$version) = @_;
                   3065:     my ($answer_name,$answer_ver,$answer_ext) =
                   3066:         &file_name_version_ext($file_name);
                   3067:     my $new_answer;
                   3068:     $env{'form.copy'} = &Apache::lonnet::getfile("/uploaded/$domain/$stu_name/portfolio$directory$file_name");
                   3069:     if($env{'form.copy'} eq '-1') {
                   3070:         $new_answer = 'problem getting file';
                   3071:     } else {
                   3072:         $new_answer = $answer_name.'.'.$version.'.'.$answer_ext;
                   3073:         my $copy_result = &Apache::lonnet::finishuserfileupload(
                   3074:                             $stu_name,$domain,'copy',
                   3075: 		        '/portfolio'.$directory.$new_answer);
                   3076:     }    
                   3077:     return ($new_answer);
1.251     banghart 3078: }
                   3079: 
1.304     albertel 3080: sub file_name_version_ext {
                   3081:     my ($file)=@_;
                   3082:     my @file_parts = split(/\./, $file);
                   3083:     my ($name,$version,$ext);
                   3084:     if (@file_parts > 1) {
                   3085: 	$ext=pop(@file_parts);
                   3086: 	if (@file_parts > 1 && $file_parts[-1] =~ /^\d+$/) {
                   3087: 	    $version=pop(@file_parts);
                   3088: 	}
                   3089: 	$name=join('.',@file_parts);
                   3090:     } else {
                   3091: 	$name=join('.',@file_parts);
                   3092:     }
                   3093:     return($name,$version,$ext);
                   3094: }
                   3095: 
1.44      ng       3096: #--------------------------------------------------------------------------------------
                   3097: #
                   3098: #-------------------------- Next few routines handles grading by section or whole class
                   3099: #
                   3100: #--- Javascript to handle grading by section or whole class
1.42      ng       3101: sub viewgrades_js {
                   3102:     my ($request) = shift;
                   3103: 
1.539     riegler  3104:     my $alertmsg = &mt('A number equal or greater than 0 is expected. Entered value = ');
1.597     wenzelju 3105:     $request->print(&Apache::lonhtmlcommon::scripttag(<<VIEWJAVASCRIPT));
1.45      ng       3106:    function writePoint(partid,weight,point) {
1.125     ng       3107: 	var radioButton = document.classgrade["RADVAL_"+partid];
                   3108: 	var textbox = document.classgrade["TEXTVAL_"+partid];
1.42      ng       3109: 	if (point == "textval") {
1.125     ng       3110: 	    point = document.classgrade["TEXTVAL_"+partid].value;
1.109     matthew  3111: 	    if (isNaN(point) || parseFloat(point) < 0) {
1.539     riegler  3112: 		alert("$alertmsg"+parseFloat(point));
1.42      ng       3113: 		var resetbox = false;
                   3114: 		for (var i=0; i<radioButton.length; i++) {
                   3115: 		    if (radioButton[i].checked) {
                   3116: 			textbox.value = i;
                   3117: 			resetbox = true;
                   3118: 		    }
                   3119: 		}
                   3120: 		if (!resetbox) {
                   3121: 		    textbox.value = "";
                   3122: 		}
                   3123: 		return;
                   3124: 	    }
1.109     matthew  3125: 	    if (parseFloat(point) > parseFloat(weight)) {
                   3126: 		var resp = confirm("You entered a value ("+parseFloat(point)+
1.44      ng       3127: 				   ") greater than the weight for the part. Accept?");
                   3128: 		if (resp == false) {
                   3129: 		    textbox.value = "";
                   3130: 		    return;
                   3131: 		}
                   3132: 	    }
1.42      ng       3133: 	    for (var i=0; i<radioButton.length; i++) {
                   3134: 		radioButton[i].checked=false;
1.109     matthew  3135: 		if (parseFloat(point) == i) {
1.42      ng       3136: 		    radioButton[i].checked=true;
                   3137: 		}
                   3138: 	    }
1.41      ng       3139: 
1.42      ng       3140: 	} else {
1.125     ng       3141: 	    textbox.value = parseFloat(point);
1.42      ng       3142: 	}
1.41      ng       3143: 	for (i=0;i<document.classgrade.total.value;i++) {
1.125     ng       3144: 	    var user = document.classgrade["ctr"+i].value;
1.289     albertel 3145: 	    user = user.replace(new RegExp(':', 'g'),"_");
1.125     ng       3146: 	    var scorename = document.classgrade["GD_"+user+"_"+partid+"_awarded"];
                   3147: 	    var saveval   = document.classgrade["GD_"+user+"_"+partid+"_solved_s"].value;
                   3148: 	    var selname   = document.classgrade["GD_"+user+"_"+partid+"_solved"];
1.42      ng       3149: 	    if (saveval != "correct") {
                   3150: 		scorename.value = point;
1.43      ng       3151: 		if (selname[0].selected != true) {
                   3152: 		    selname[0].selected = true;
                   3153: 		}
1.42      ng       3154: 	    }
                   3155: 	}
1.125     ng       3156: 	document.classgrade["SELVAL_"+partid][0].selected = true;
1.42      ng       3157:     }
                   3158: 
                   3159:     function writeRadText(partid,weight) {
1.125     ng       3160: 	var selval   = document.classgrade["SELVAL_"+partid];
                   3161: 	var radioButton = document.classgrade["RADVAL_"+partid];
1.265     www      3162:         var override = document.classgrade["FORCE_"+partid].checked;
1.125     ng       3163: 	var textbox = document.classgrade["TEXTVAL_"+partid];
                   3164: 	if (selval[1].selected || selval[2].selected) {
1.42      ng       3165: 	    for (var i=0; i<radioButton.length; i++) {
                   3166: 		radioButton[i].checked=false;
                   3167: 
                   3168: 	    }
                   3169: 	    textbox.value = "";
                   3170: 
                   3171: 	    for (i=0;i<document.classgrade.total.value;i++) {
1.125     ng       3172: 		var user = document.classgrade["ctr"+i].value;
1.289     albertel 3173: 		user = user.replace(new RegExp(':', 'g'),"_");
1.125     ng       3174: 		var scorename = document.classgrade["GD_"+user+"_"+partid+"_awarded"];
                   3175: 		var saveval   = document.classgrade["GD_"+user+"_"+partid+"_solved_s"].value;
                   3176: 		var selname   = document.classgrade["GD_"+user+"_"+partid+"_solved"];
1.265     www      3177: 		if ((saveval != "correct") || override) {
1.42      ng       3178: 		    scorename.value = "";
1.125     ng       3179: 		    if (selval[1].selected) {
                   3180: 			selname[1].selected = true;
                   3181: 		    } else {
                   3182: 			selname[2].selected = true;
                   3183: 			if (Number(document.classgrade["GD_"+user+"_"+partid+"_tries"].value)) 
                   3184: 			{document.classgrade["GD_"+user+"_"+partid+"_tries"].value = '0';}
                   3185: 		    }
1.42      ng       3186: 		}
                   3187: 	    }
1.43      ng       3188: 	} else {
                   3189: 	    for (i=0;i<document.classgrade.total.value;i++) {
1.125     ng       3190: 		var user = document.classgrade["ctr"+i].value;
1.289     albertel 3191: 		user = user.replace(new RegExp(':', 'g'),"_");
1.125     ng       3192: 		var scorename = document.classgrade["GD_"+user+"_"+partid+"_awarded"];
                   3193: 		var saveval   = document.classgrade["GD_"+user+"_"+partid+"_solved_s"].value;
                   3194: 		var selname   = document.classgrade["GD_"+user+"_"+partid+"_solved"];
1.265     www      3195: 		if ((saveval != "correct") || override) {
1.125     ng       3196: 		    scorename.value = document.classgrade["GD_"+user+"_"+partid+"_awarded_s"].value;
1.43      ng       3197: 		    selname[0].selected = true;
                   3198: 		}
                   3199: 	    }
                   3200: 	}	    
1.42      ng       3201:     }
                   3202: 
                   3203:     function changeSelect(partid,user) {
1.125     ng       3204: 	var selval = document.classgrade["GD_"+user+'_'+partid+"_solved"];
                   3205: 	var textbox = document.classgrade["GD_"+user+'_'+partid+"_awarded"];
1.44      ng       3206: 	var point  = textbox.value;
1.125     ng       3207: 	var weight = document.classgrade["weight_"+partid].value;
1.44      ng       3208: 
1.109     matthew  3209: 	if (isNaN(point) || parseFloat(point) < 0) {
1.539     riegler  3210: 	    alert("$alertmsg"+parseFloat(point));
1.44      ng       3211: 	    textbox.value = "";
                   3212: 	    return;
                   3213: 	}
1.109     matthew  3214: 	if (parseFloat(point) > parseFloat(weight)) {
                   3215: 	    var resp = confirm("You entered a value ("+parseFloat(point)+
1.44      ng       3216: 			       ") greater than the weight of the part. Accept?");
                   3217: 	    if (resp == false) {
                   3218: 		textbox.value = "";
                   3219: 		return;
                   3220: 	    }
                   3221: 	}
1.42      ng       3222: 	selval[0].selected = true;
                   3223:     }
                   3224: 
                   3225:     function changeOneScore(partid,user) {
1.125     ng       3226: 	var selval = document.classgrade["GD_"+user+'_'+partid+"_solved"];
                   3227: 	if (selval[1].selected || selval[2].selected) {
                   3228: 	    document.classgrade["GD_"+user+'_'+partid+"_awarded"].value = "";
                   3229: 	    if (selval[2].selected) {
                   3230: 		document.classgrade["GD_"+user+'_'+partid+"_tries"].value = "0";
                   3231: 	    }
1.269     raeburn  3232:         }
1.42      ng       3233:     }
                   3234: 
                   3235:     function resetEntry(numpart) {
                   3236: 	for (ctpart=0;ctpart<numpart;ctpart++) {
1.125     ng       3237: 	    var partid = document.classgrade["partid_"+ctpart].value;
                   3238: 	    var radioButton = document.classgrade["RADVAL_"+partid];
                   3239: 	    var textbox = document.classgrade["TEXTVAL_"+partid];
                   3240: 	    var selval  = document.classgrade["SELVAL_"+partid];
1.42      ng       3241: 	    for (var i=0; i<radioButton.length; i++) {
                   3242: 		radioButton[i].checked=false;
                   3243: 
                   3244: 	    }
                   3245: 	    textbox.value = "";
                   3246: 	    selval[0].selected = true;
                   3247: 
                   3248: 	    for (i=0;i<document.classgrade.total.value;i++) {
1.125     ng       3249: 		var user = document.classgrade["ctr"+i].value;
1.289     albertel 3250: 		user = user.replace(new RegExp(':', 'g'),"_");
1.125     ng       3251: 		var resetscore = document.classgrade["GD_"+user+"_"+partid+"_awarded"];
                   3252: 		resetscore.value = document.classgrade["GD_"+user+"_"+partid+"_awarded_s"].value;
                   3253: 		var resettries = document.classgrade["GD_"+user+"_"+partid+"_tries"];
                   3254: 		resettries.value = document.classgrade["GD_"+user+"_"+partid+"_tries_s"].value;
                   3255: 		var saveselval   = document.classgrade["GD_"+user+"_"+partid+"_solved_s"].value;
                   3256: 		var selname   = document.classgrade["GD_"+user+"_"+partid+"_solved"];
1.42      ng       3257: 		if (saveselval == "excused") {
1.43      ng       3258: 		    if (selname[1].selected == false) { selname[1].selected = true;}
1.42      ng       3259: 		} else {
1.43      ng       3260: 		    if (selname[0].selected == false) {selname[0].selected = true};
1.42      ng       3261: 		}
                   3262: 	    }
1.41      ng       3263: 	}
1.42      ng       3264:     }
                   3265: 
1.41      ng       3266: VIEWJAVASCRIPT
1.42      ng       3267: }
                   3268: 
1.44      ng       3269: #--- show scores for a section or whole class w/ option to change/update a score
1.42      ng       3270: sub viewgrades {
1.608     www      3271:     my ($request,$symb) = @_;
1.42      ng       3272:     &viewgrades_js($request);
1.41      ng       3273: 
1.168     albertel 3274:     #need to make sure we have the correct data for later EXT calls, 
                   3275:     #thus invalidate the cache
                   3276:     &Apache::lonnet::devalidatecourseresdata(
1.257     albertel 3277:                  $env{'course.'.$env{'request.course.id'}.'.num'},
                   3278:                  $env{'course.'.$env{'request.course.id'}.'.domain'});
1.168     albertel 3279:     &Apache::lonnet::clear_EXT_cache_status();
                   3280: 
1.398     albertel 3281:     my $result='<h3><span class="LC_info">'.&mt('Manual Grading').'</span></h3>';
1.41      ng       3282: 
                   3283:     #view individual student submission form - called using Javascript viewOneStudent
1.324     albertel 3284:     $result.=&jscriptNform($symb);
1.41      ng       3285: 
1.44      ng       3286:     #beginning of class grading form
1.442     banghart 3287:     my $stu_status = join(':',&Apache::loncommon::get_env_multiple('form.Status'));
1.41      ng       3288:     $result.= '<form action="/adm/grades" method="post" name="classgrade">'."\n".
1.418     albertel 3289: 	'<input type="hidden" name="symb"    value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
1.38      ng       3290: 	'<input type="hidden" name="command" value="editgrades" />'."\n".
1.432     banghart 3291: 	&build_section_inputs().
1.257     albertel 3292: 	'<input type="hidden" name="saveState" value="'.$env{'form.saveState'}.'" />'."\n".
1.442     banghart 3293: 	'<input type="hidden" name="Status" value="'.$env{'stu_status'}.'" />'."\n".
1.72      ng       3294: 
1.560     raeburn  3295:     my ($common_header,$specific_header);
1.257     albertel 3296:     if ($env{'form.section'} eq 'all') {
1.560     raeburn  3297: 	$common_header = &mt('Assign Common Grade to Class');
                   3298:         $specific_header = &mt('Assign Grade to Specific Students in Class');
1.257     albertel 3299:     } elsif ($env{'form.section'} eq 'none') {
1.560     raeburn  3300:         $common_header = &mt('Assign Common Grade to Students in no Section');
                   3301: 	$specific_header = &mt('Assign Grade to Specific Students in no Section');
1.52      albertel 3302:     } else {
1.560     raeburn  3303:         my $section_display = join (", ",&Apache::loncommon::get_env_multiple('form.section'));
                   3304:         $common_header = &mt('Assign Common Grade to Students in Section(s) [_1]',$section_display);
                   3305: 	$specific_header = &mt('Assign Grade to Specific Students in Section(s) [_1]',$section_display);
1.52      albertel 3306:     }
1.560     raeburn  3307:     $result.= '<h3>'.$common_header.'</h3>'.&Apache::loncommon::start_data_table();
1.44      ng       3308:     #radio buttons/text box for assigning points for a section or class.
                   3309:     #handles different parts of a problem
1.582     raeburn  3310:     my $res_error;
                   3311:     my ($partlist,$handgrade,$responseType) = &response_type($symb,\$res_error);
                   3312:     if ($res_error) {
                   3313:         return &navmap_errormsg();
                   3314:     }
1.42      ng       3315:     my %weight = ();
                   3316:     my $ctsparts = 0;
1.45      ng       3317:     my %seen = ();
1.375     albertel 3318:     my @part_response_id = &flatten_responseType($responseType);
                   3319:     foreach my $part_response_id (@part_response_id) {
                   3320:     	my ($partid,$respid) = @{ $part_response_id };
                   3321: 	my $part_resp = join('_',@{ $part_response_id });
1.45      ng       3322: 	next if $seen{$partid};
                   3323: 	$seen{$partid}++;
1.375     albertel 3324: 	my $handgrade=$$handgrade{$part_resp};
1.42      ng       3325: 	my $wgt = &Apache::lonnet::EXT('resource.'.$partid.'.weight',$symb);
                   3326: 	$weight{$partid} = $wgt eq '' ? '1' : $wgt;
                   3327: 
1.324     albertel 3328: 	my $display_part=&get_display_part($partid,$symb);
1.485     albertel 3329: 	my $radio.='<table border="0"><tr>';  
1.41      ng       3330: 	my $ctr = 0;
1.42      ng       3331: 	while ($ctr<=$weight{$partid}) { # display radio buttons in a nice table 10 across
1.485     albertel 3332: 	    $radio.= '<td><label><input type="radio" name="RADVAL_'.$partid.'" '.
1.54      albertel 3333: 		'onclick="javascript:writePoint(\''.$partid.'\','.$weight{$partid}.
1.288     albertel 3334: 		','.$ctr.')" />'.$ctr."</label></td>\n";
1.41      ng       3335: 	    $result.=(($ctr+1)%10 == 0 ? '</tr><tr>' : '');
                   3336: 	    $ctr++;
                   3337: 	}
1.485     albertel 3338: 	$radio.='</tr></table>';
                   3339: 	my $line = '<input type="text" name="TEXTVAL_'.
1.589     bisitz   3340: 	    $partid.'" size="4" '.'onchange="javascript:writePoint(\''.
1.54      albertel 3341: 		$partid.'\','.$weight{$partid}.',\'textval\')" /> /'.
1.539     riegler  3342: 	    $weight{$partid}.' '.&mt('(problem weight)').'</td>'."\n";
                   3343: 	$line.= '<td><b>'.&mt('Grade Status').':</b><select name="SELVAL_'.$partid.'"'.
1.589     bisitz   3344: 	    'onchange="javascript:writeRadText(\''.$partid.'\','.
1.59      albertel 3345: 		$weight{$partid}.')"> '.
1.401     albertel 3346: 	    '<option selected="selected"> </option>'.
1.485     albertel 3347: 	    '<option value="excused">'.&mt('excused').'</option>'.
                   3348: 	    '<option value="reset status">'.&mt('reset status').'</option>'.
                   3349: 	    '</select></td>'.
                   3350:             '<td><label><input type="checkbox" name="FORCE_'.$partid.'" />'.&mt('Override "Correct"').'</label>';
                   3351: 	$line.='<input type="hidden" name="partid_'.
                   3352: 	    $ctsparts.'" value="'.$partid.'" />'."\n";
                   3353: 	$line.='<input type="hidden" name="weight_'.
                   3354: 	    $partid.'" value="'.$weight{$partid}.'" />'."\n";
                   3355: 
                   3356: 	$result.=
                   3357: 	    &Apache::loncommon::start_data_table_row()."\n".
1.577     bisitz   3358: 	    '<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 3359: 	    &Apache::loncommon::end_data_table_row()."\n";
1.42      ng       3360: 	$ctsparts++;
1.41      ng       3361:     }
1.474     albertel 3362:     $result.=&Apache::loncommon::end_data_table()."\n".
1.52      albertel 3363: 	'<input type="hidden" name="totalparts" value="'.$ctsparts.'" />';
1.485     albertel 3364:     $result.='<input type="button" value="'.&mt('Revert to Default').'" '.
1.589     bisitz   3365: 	'onclick="javascript:resetEntry('.$ctsparts.');" />';
1.41      ng       3366: 
1.44      ng       3367:     #table listing all the students in a section/class
                   3368:     #header of table
1.560     raeburn  3369:     $result.= '<h3>'.$specific_header.'</h3>'.
                   3370:               &Apache::loncommon::start_data_table().
                   3371: 	      &Apache::loncommon::start_data_table_header_row().
                   3372: 	      '<th>'.&mt('No.').'</th>'.
                   3373: 	      '<th>'.&nameUserString('header')."</th>\n";
1.582     raeburn  3374:     my $partserror;
                   3375:     my (@parts) = sort(&getpartlist($symb,\$partserror));
                   3376:     if ($partserror) {
                   3377:         return &navmap_errormsg();
                   3378:     }
1.324     albertel 3379:     my (undef,undef,$url)=&Apache::lonnet::decode_symb($symb);
1.269     raeburn  3380:     my @partids = ();
1.41      ng       3381:     foreach my $part (@parts) {
                   3382: 	my $display=&Apache::lonnet::metadata($url,$part.'.display');
1.539     riegler  3383:         my $narrowtext = &mt('Tries');
                   3384: 	$display =~ s|^Number of Attempts|$narrowtext <br />|; # makes the column narrower
1.41      ng       3385: 	if  (!$display) { $display = &Apache::lonnet::metadata($url,$part.'.name'); }
1.207     albertel 3386: 	my ($partid) = &split_part_type($part);
1.524     raeburn  3387:         push(@partids,$partid);
1.324     albertel 3388: 	my $display_part=&get_display_part($partid,$symb);
1.41      ng       3389: 	if ($display =~ /^Partial Credit Factor/) {
1.485     albertel 3390: 	    $result.='<th>'.
                   3391: 		&mt('Score Part: [_1]<br /> (weight = [_2])',
                   3392: 		    $display_part,$weight{$partid}).'</th>'."\n";
1.41      ng       3393: 	    next;
1.485     albertel 3394: 	    
1.207     albertel 3395: 	} else {
1.485     albertel 3396: 	    if ($display =~ /Problem Status/) {
                   3397: 		my $grade_status_mt = &mt('Grade Status');
                   3398: 		$display =~ s{Problem Status}{$grade_status_mt<br />};
                   3399: 	    }
                   3400: 	    my $part_mt = &mt('Part:');
                   3401: 	    $display =~s{\[Part: \Q$partid\E\]}{$part_mt $display_part};
1.41      ng       3402: 	}
1.485     albertel 3403: 
1.474     albertel 3404: 	$result.='<th>'.$display.'</th>'."\n";
1.41      ng       3405:     }
1.474     albertel 3406:     $result.=&Apache::loncommon::end_data_table_header_row();
1.44      ng       3407: 
1.270     albertel 3408:     my %last_resets = 
                   3409: 	&get_last_resets($symb,$env{'request.course.id'},\@partids);
1.269     raeburn  3410: 
1.41      ng       3411:     #get info for each student
1.44      ng       3412:     #list all the students - with points and grade status
1.257     albertel 3413:     my (undef,undef,$fullname) = &getclasslist($env{'form.section'},'1');
1.41      ng       3414:     my $ctr = 0;
1.294     albertel 3415:     foreach (sort 
                   3416: 	     {
                   3417: 		 if (lc($$fullname{$a}) ne lc($$fullname{$b})) {
                   3418: 		     return (lc($$fullname{$a}) cmp lc($$fullname{$b}));
                   3419: 		 }
                   3420: 		 return $a cmp $b;
                   3421: 	     } (keys(%$fullname))) {
1.126     ng       3422: 	$ctr++;
1.324     albertel 3423: 	$result.=&viewstudentgrade($symb,$env{'request.course.id'},
1.269     raeburn  3424: 				   $_,$$fullname{$_},\@parts,\%weight,$ctr,\%last_resets);
1.41      ng       3425:     }
1.474     albertel 3426:     $result.=&Apache::loncommon::end_data_table();
1.41      ng       3427:     $result.='<input type="hidden" name="total" value="'.$ctr.'" />'."\n";
1.485     albertel 3428:     $result.='<input type="button" value="'.&mt('Save').'" '.
1.589     bisitz   3429: 	'onclick="javascript:submit();" target="_self" /></form>'."\n";
1.96      albertel 3430:     if (scalar(%$fullname) eq 0) {
                   3431: 	my $colspan=3+scalar(@parts);
1.433     banghart 3432: 	my $section_display = join (", ",&Apache::loncommon::get_env_multiple('form.section'));
1.442     banghart 3433:         my $stu_status = join(' or ',&Apache::loncommon::get_env_multiple('form.Status'));
1.433     banghart 3434: 	$result='<span class="LC_warning">'.
1.485     albertel 3435: 	    &mt('There are no students in section(s) [_1] with enrollment status [_2] to modify or grade.',
1.442     banghart 3436: 	        $section_display, $stu_status).
1.433     banghart 3437: 	    '</span>';
1.96      albertel 3438:     }
1.324     albertel 3439:     $result.=&show_grading_menu_form($symb);
1.41      ng       3440:     return $result;
                   3441: }
                   3442: 
1.44      ng       3443: #--- call by previous routine to display each student
1.41      ng       3444: sub viewstudentgrade {
1.324     albertel 3445:     my ($symb,$courseid,$student,$fullname,$parts,$weight,$ctr,$last_resets) = @_;
1.44      ng       3446:     my ($uname,$udom) = split(/:/,$student);
                   3447:     my %record=&Apache::lonnet::restore($symb,$courseid,$udom,$uname);
1.269     raeburn  3448:     my %aggregates = (); 
1.474     albertel 3449:     my $result=&Apache::loncommon::start_data_table_row().'<td align="right">'.
1.233     albertel 3450: 	'<input type="hidden" name="ctr'.($ctr-1).'" value="'.$student.'" />'.
                   3451: 	"\n".$ctr.'&nbsp;</td><td>&nbsp;'.
1.44      ng       3452: 	'<a href="javascript:viewOneStudent(\''.$uname.'\',\''.$udom.
1.417     albertel 3453: 	'\');" target="_self">'.$fullname.'</a> '.
1.398     albertel 3454: 	'<span class="LC_internal_info">('.$uname.($env{'user.domain'} eq $udom ? '' : ':'.$udom).')</span></td>'."\n";
1.281     albertel 3455:     $student=~s/:/_/; # colon doen't work in javascript for names
1.63      albertel 3456:     foreach my $apart (@$parts) {
                   3457: 	my ($part,$type) = &split_part_type($apart);
1.41      ng       3458: 	my $score=$record{"resource.$part.$type"};
1.276     albertel 3459:         $result.='<td align="center">';
1.269     raeburn  3460:         my ($aggtries,$totaltries);
                   3461:         unless (exists($aggregates{$part})) {
1.270     albertel 3462: 	    $totaltries = $record{'resource.'.$part.'.tries'};
                   3463: 
                   3464: 	    $aggtries = $totaltries;
1.269     raeburn  3465:             if ($$last_resets{$part}) {  
1.270     albertel 3466:                 $aggtries = &get_num_tries(\%record,$$last_resets{$part},
                   3467: 					   $part);
                   3468:             }
1.269     raeburn  3469:             $result.='<input type="hidden" name="'.
                   3470:                 'GD_'.$student.'_'.$part.'_aggtries" value="'.$aggtries.'" />'."\n";
                   3471:             $result.='<input type="hidden" name="'.
                   3472:                 'GD_'.$student.'_'.$part.'_totaltries" value="'.$totaltries.'" />'."\n";
                   3473:             $aggregates{$part} = 1;
                   3474:         }
1.41      ng       3475: 	if ($type eq 'awarded') {
1.320     albertel 3476: 	    my $pts = $score eq '' ? '' : &compute_points($score,$$weight{$part});
1.42      ng       3477: 	    $result.='<input type="hidden" name="'.
1.89      albertel 3478: 		'GD_'.$student.'_'.$part.'_awarded_s" value="'.$pts.'" />'."\n";
1.233     albertel 3479: 	    $result.='<input type="text" name="'.
1.89      albertel 3480: 		'GD_'.$student.'_'.$part.'_awarded" '.
1.589     bisitz   3481:                 'onchange="javascript:changeSelect(\''.$part.'\',\''.$student.
1.44      ng       3482: 		'\')" value="'.$pts.'" size="4" /></td>'."\n";
1.41      ng       3483: 	} elsif ($type eq 'solved') {
                   3484: 	    my ($status,$foo)=split(/_/,$score,2);
                   3485: 	    $status = 'nothing' if ($status eq '');
1.89      albertel 3486: 	    $result.='<input type="hidden" name="'.'GD_'.$student.'_'.
1.54      albertel 3487: 		$part.'_solved_s" value="'.$status.'" />'."\n";
1.233     albertel 3488: 	    $result.='&nbsp;<select name="'.
1.89      albertel 3489: 		'GD_'.$student.'_'.$part.'_solved" '.
1.589     bisitz   3490:                 'onchange="javascript:changeOneScore(\''.$part.'\',\''.$student.'\')" >'."\n";
1.485     albertel 3491: 	    $result.= (($status eq 'excused') ? '<option> </option><option selected="selected" value="excused">'.&mt('excused').'</option>' 
                   3492: 		: '<option selected="selected"> </option><option value="excused">'.&mt('excused').'</option>')."\n";
                   3493: 	    $result.='<option value="reset status">'.&mt('reset status').'</option>';
1.126     ng       3494: 	    $result.="</select>&nbsp;</td>\n";
1.122     ng       3495: 	} else {
                   3496: 	    $result.='<input type="hidden" name="'.
                   3497: 		'GD_'.$student.'_'.$part.'_'.$type.'_s" value="'.$score.'" />'.
                   3498: 		    "\n";
1.233     albertel 3499: 	    $result.='<input type="text" name="'.
1.122     ng       3500: 		'GD_'.$student.'_'.$part.'_'.$type.'" '.
                   3501: 		'value="'.$score.'" size="4" /></td>'."\n";
1.41      ng       3502: 	}
                   3503:     }
1.474     albertel 3504:     $result.=&Apache::loncommon::end_data_table_row();
1.41      ng       3505:     return $result;
1.38      ng       3506: }
                   3507: 
1.44      ng       3508: #--- change scores for all the students in a section/class
                   3509: #    record does not get update if unchanged
1.38      ng       3510: sub editgrades {
1.608     www      3511:     my ($request,$symb) = @_;
1.41      ng       3512: 
1.433     banghart 3513:     my $section_display = join (", ",&Apache::loncommon::get_env_multiple('form.section'));
1.477     albertel 3514:     my $title='<h2>'.&mt('Current Grade Status').'</h2>';
1.433     banghart 3515:     $title.='<h4>'.&mt('<b>Section: </b>[_1]',$section_display).'</h4>'."\n";
1.126     ng       3516: 
1.477     albertel 3517:     my $result= &Apache::loncommon::start_data_table().
                   3518: 	&Apache::loncommon::start_data_table_header_row().
                   3519: 	'<th rowspan="2" valign="middle">'.&mt('No.').'</th>'.
                   3520: 	'<th rowspan="2" valign="middle">'.&nameUserString('header')."</th>\n";
1.43      ng       3521:     my %scoreptr = (
                   3522: 		    'correct'  =>'correct_by_override',
                   3523: 		    'incorrect'=>'incorrect_by_override',
                   3524: 		    'excused'  =>'excused',
                   3525: 		    'ungraded' =>'ungraded_attempted',
1.596     raeburn  3526:                     'credited' =>'credit_attempted',
1.43      ng       3527: 		    'nothing'  => '',
                   3528: 		    );
1.257     albertel 3529:     my ($classlist,undef,$fullname) = &getclasslist($env{'form.section'},'0');
1.34      ng       3530: 
1.44      ng       3531:     my (@partid);
                   3532:     my %weight = ();
1.54      albertel 3533:     my %columns = ();
1.44      ng       3534:     my ($i,$ctr,$count,$rec_update) = (0,0,0,0);
1.54      albertel 3535: 
1.582     raeburn  3536:     my $partserror;
                   3537:     my (@parts) = sort(&getpartlist($symb,\$partserror));
                   3538:     if ($partserror) {
                   3539:         return &navmap_errormsg();
                   3540:     }
1.54      albertel 3541:     my $header;
1.257     albertel 3542:     while ($ctr < $env{'form.totalparts'}) {
                   3543: 	my $partid = $env{'form.partid_'.$ctr};
1.524     raeburn  3544: 	push(@partid,$partid);
1.257     albertel 3545: 	$weight{$partid} = $env{'form.weight_'.$partid};
1.44      ng       3546: 	$ctr++;
1.54      albertel 3547:     }
1.324     albertel 3548:     my (undef,undef,$url) = &Apache::lonnet::decode_symb($symb);
1.54      albertel 3549:     foreach my $partid (@partid) {
1.478     albertel 3550: 	$header .= '<th align="center">'.&mt('Old Score').'</th>'.
                   3551: 	    '<th align="center">'.&mt('New Score').'</th>';
1.54      albertel 3552: 	$columns{$partid}=2;
                   3553: 	foreach my $stores (@parts) {
                   3554: 	    my ($part,$type) = &split_part_type($stores);
                   3555: 	    if ($part !~ m/^\Q$partid\E/) { next;}
                   3556: 	    if ($type eq 'awarded' || $type eq 'solved') { next; }
                   3557: 	    my $display=&Apache::lonnet::metadata($url,$stores.'.display');
1.551     raeburn  3558: 	    $display =~ s/\[Part: \Q$part\E\]//;
1.539     riegler  3559:             my $narrowtext = &mt('Tries');
                   3560: 	    $display =~ s/Number of Attempts/$narrowtext/;
                   3561: 	    $header .= '<th align="center">'.&mt('Old').' '.$display.'</th>'.
                   3562: 		'<th align="center">'.&mt('New').' '.$display.'</th>';
1.54      albertel 3563: 	    $columns{$partid}+=2;
                   3564: 	}
                   3565:     }
                   3566:     foreach my $partid (@partid) {
1.324     albertel 3567: 	my $display_part=&get_display_part($partid,$symb);
1.478     albertel 3568: 	$result .= '<th colspan="'.$columns{$partid}.'" align="center">'.
                   3569: 	    &mt('Part: [_1] (Weight = [_2])',$display_part,$weight{$partid}).
                   3570: 	    '</th>';
1.54      albertel 3571: 
1.44      ng       3572:     }
1.477     albertel 3573:     $result .= &Apache::loncommon::end_data_table_header_row().
                   3574: 	&Apache::loncommon::start_data_table_header_row().
                   3575: 	$header.
                   3576: 	&Apache::loncommon::end_data_table_header_row();
                   3577:     my @noupdate;
1.126     ng       3578:     my ($updateCtr,$noupdateCtr) = (1,1);
1.257     albertel 3579:     for ($i=0; $i<$env{'form.total'}; $i++) {
1.93      albertel 3580: 	my $line;
1.257     albertel 3581: 	my $user = $env{'form.ctr'.$i};
1.281     albertel 3582: 	my ($uname,$udom)=split(/:/,$user);
1.44      ng       3583: 	my %newrecord;
                   3584: 	my $updateflag = 0;
1.281     albertel 3585: 	$line .= '<td>'.&nameUserString(undef,$$fullname{$user},$uname,$udom).'</td>';
1.108     albertel 3586: 	my $usec=$classlist->{"$uname:$udom"}[5];
1.105     albertel 3587: 	if (!&canmodify($usec)) {
1.126     ng       3588: 	    my $numcols=scalar(@partid)*4+2;
1.477     albertel 3589: 	    push(@noupdate,
1.478     albertel 3590: 		 $line."<td colspan=\"$numcols\"><span class=\"LC_warning\">".
                   3591: 		 &mt('Not allowed to modify student')."</span></td></tr>");
1.105     albertel 3592: 	    next;
                   3593: 	}
1.269     raeburn  3594:         my %aggregate = ();
                   3595:         my $aggregateflag = 0;
1.281     albertel 3596: 	$user=~s/:/_/; # colon doen't work in javascript for names
1.44      ng       3597: 	foreach (@partid) {
1.257     albertel 3598: 	    my $old_aw    = $env{'form.GD_'.$user.'_'.$_.'_awarded_s'};
1.54      albertel 3599: 	    my $old_part_pcr = $old_aw/($weight{$_} ne '0' ? $weight{$_}:1);
                   3600: 	    my $old_part  = $old_aw eq '' ? '' : $old_part_pcr;
1.257     albertel 3601: 	    my $old_score = $scoreptr{$env{'form.GD_'.$user.'_'.$_.'_solved_s'}};
                   3602: 	    my $awarded   = $env{'form.GD_'.$user.'_'.$_.'_awarded'};
1.54      albertel 3603: 	    my $pcr       = $awarded/($weight{$_} ne '0' ? $weight{$_} : 1);
                   3604: 	    my $partial   = $awarded eq '' ? '' : $pcr;
1.44      ng       3605: 	    my $score;
                   3606: 	    if ($partial eq '') {
1.257     albertel 3607: 		$score = $scoreptr{$env{'form.GD_'.$user.'_'.$_.'_solved_s'}};
1.44      ng       3608: 	    } elsif ($partial > 0) {
                   3609: 		$score = 'correct_by_override';
                   3610: 	    } elsif ($partial == 0) {
                   3611: 		$score = 'incorrect_by_override';
                   3612: 	    }
1.257     albertel 3613: 	    my $dropMenu = $env{'form.GD_'.$user.'_'.$_.'_solved'};
1.125     ng       3614: 	    $score = 'excused' if (($dropMenu eq 'excused') && ($score ne 'excused'));
                   3615: 
1.292     albertel 3616: 	    $newrecord{'resource.'.$_.'.regrader'}=
                   3617: 		"$env{'user.name'}:$env{'user.domain'}";
1.125     ng       3618: 	    if ($dropMenu eq 'reset status' &&
                   3619: 		$old_score ne '') { # ignore if no previous attempts => nothing to reset
1.299     albertel 3620: 		$newrecord{'resource.'.$_.'.tries'} = '';
1.125     ng       3621: 		$newrecord{'resource.'.$_.'.solved'} = '';
                   3622: 		$newrecord{'resource.'.$_.'.award'} = '';
1.299     albertel 3623: 		$newrecord{'resource.'.$_.'.awarded'} = '';
1.125     ng       3624: 		$updateflag = 1;
1.269     raeburn  3625:                 if ($env{'form.GD_'.$user.'_'.$_.'_aggtries'} > 0) {
                   3626:                     my $aggtries = $env{'form.GD_'.$user.'_'.$_.'_aggtries'};
                   3627:                     my $totaltries = $env{'form.GD_'.$user.'_'.$_.'_totaltries'};
                   3628:                     my $solvedstatus = $env{'form.GD_'.$user.'_'.$_.'_solved_s'};
                   3629:                     &decrement_aggs($symb,$_,\%aggregate,$aggtries,$totaltries,$solvedstatus);
                   3630:                     $aggregateflag = 1;
                   3631:                 }
1.139     albertel 3632: 	    } elsif (!($old_part eq $partial && $old_score eq $score)) {
                   3633: 		$updateflag = 1;
                   3634: 		$newrecord{'resource.'.$_.'.awarded'}  = $partial if $partial ne '';
                   3635: 		$newrecord{'resource.'.$_.'.solved'}   = $score;
                   3636: 		$rec_update++;
1.125     ng       3637: 	    }
                   3638: 
1.93      albertel 3639: 	    $line .= '<td align="center">'.$old_aw.'&nbsp;</td>'.
1.44      ng       3640: 		'<td align="center">'.$awarded.
                   3641: 		($score eq 'excused' ? $score : '').'&nbsp;</td>';
1.5       albertel 3642: 
1.54      albertel 3643: 
                   3644: 	    my $partid=$_;
                   3645: 	    foreach my $stores (@parts) {
                   3646: 		my ($part,$type) = &split_part_type($stores);
                   3647: 		if ($part !~ m/^\Q$partid\E/) { next;}
                   3648: 		if ($type eq 'awarded' || $type eq 'solved') { next; }
1.257     albertel 3649: 		my $old_aw    = $env{'form.GD_'.$user.'_'.$part.'_'.$type.'_s'};
                   3650: 		my $awarded   = $env{'form.GD_'.$user.'_'.$part.'_'.$type};
1.54      albertel 3651: 		if ($awarded ne '' && $awarded ne $old_aw) {
                   3652: 		    $newrecord{'resource.'.$part.'.'.$type}= $awarded;
1.257     albertel 3653: 		    $newrecord{'resource.'.$part.'.regrader'}="$env{'user.name'}:$env{'user.domain'}";
1.54      albertel 3654: 		    $updateflag=1;
                   3655: 		}
1.93      albertel 3656: 		$line .= '<td align="center">'.$old_aw.'&nbsp;</td>'.
1.54      albertel 3657: 		    '<td align="center">'.$awarded.'&nbsp;</td>';
                   3658: 	    }
1.44      ng       3659: 	}
1.477     albertel 3660: 	$line.="\n";
1.301     albertel 3661: 
                   3662: 	my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   3663: 	my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   3664: 
1.44      ng       3665: 	if ($updateflag) {
                   3666: 	    $count++;
1.257     albertel 3667: 	    &Apache::lonnet::cstore(\%newrecord,$symb,$env{'request.course.id'},
1.89      albertel 3668: 				    $udom,$uname);
1.301     albertel 3669: 
                   3670: 	    if (&Apache::bridgetask::in_queue('gradingqueue',$symb,$cdom,
                   3671: 					      $cnum,$udom,$uname)) {
                   3672: 		# need to figure out if should be in queue.
                   3673: 		my %record =  
                   3674: 		    &Apache::lonnet::restore($symb,$env{'request.course.id'},
                   3675: 					     $udom,$uname);
                   3676: 		my $all_graded = 1;
                   3677: 		my $none_graded = 1;
                   3678: 		foreach my $part (@parts) {
                   3679: 		    if ( $record{'resource.'.$part.'.awarded'} eq '' ) {
                   3680: 			$all_graded = 0;
                   3681: 		    } else {
                   3682: 			$none_graded = 0;
                   3683: 		    }
                   3684: 		}
                   3685: 
                   3686: 		if ($all_graded || $none_graded) {
                   3687: 		    &Apache::bridgetask::remove_from_queue('gradingqueue',
                   3688: 							   $symb,$cdom,$cnum,
                   3689: 							   $udom,$uname);
                   3690: 		}
                   3691: 	    }
                   3692: 
1.477     albertel 3693: 	    $result.=&Apache::loncommon::start_data_table_row().
                   3694: 		'<td align="right">&nbsp;'.$updateCtr.'&nbsp;</td>'.$line.
                   3695: 		&Apache::loncommon::end_data_table_row();
1.126     ng       3696: 	    $updateCtr++;
1.93      albertel 3697: 	} else {
1.477     albertel 3698: 	    push(@noupdate,
                   3699: 		 '<td align="right">&nbsp;'.$noupdateCtr.'&nbsp;</td>'.$line);
1.126     ng       3700: 	    $noupdateCtr++;
1.44      ng       3701: 	}
1.269     raeburn  3702:         if ($aggregateflag) {
                   3703:             &Apache::lonnet::cinc('nohist_resourcetracker',\%aggregate,
1.301     albertel 3704: 				  $cdom,$cnum);
1.269     raeburn  3705:         }
1.93      albertel 3706:     }
1.477     albertel 3707:     if (@noupdate) {
1.126     ng       3708: #	my $numcols=(scalar(@partid)*(scalar(@parts)-1)*2)+3;
                   3709: 	my $numcols=scalar(@partid)*4+2;
1.477     albertel 3710: 	$result .= &Apache::loncommon::start_data_table_row('LC_empty_row').
1.478     albertel 3711: 	    '<td align="center" colspan="'.$numcols.'">'.
                   3712: 	    &mt('No Changes Occurred For the Students Below').
                   3713: 	    '</td>'.
1.477     albertel 3714: 	    &Apache::loncommon::end_data_table_row();
                   3715: 	foreach my $line (@noupdate) {
                   3716: 	    $result.=
                   3717: 		&Apache::loncommon::start_data_table_row().
                   3718: 		$line.
                   3719: 		&Apache::loncommon::end_data_table_row();
                   3720: 	}
1.44      ng       3721:     }
1.477     albertel 3722:     $result .= &Apache::loncommon::end_data_table().
                   3723: 	&show_grading_menu_form($symb);
1.478     albertel 3724:     my $msg = '<p><b>'.
                   3725: 	&mt('Number of records updated = [_1] for [quant,_2,student].',
                   3726: 	    $rec_update,$count).'</b><br />'.
                   3727: 	'<b>'.&mt('Total number of students = [_1]',$env{'form.total'}).
                   3728: 	'</b></p>';
1.44      ng       3729:     return $title.$msg.$result;
1.5       albertel 3730: }
1.54      albertel 3731: 
                   3732: sub split_part_type {
                   3733:     my ($partstr) = @_;
                   3734:     my ($temp,@allparts)=split(/_/,$partstr);
                   3735:     my $type=pop(@allparts);
1.439     albertel 3736:     my $part=join('_',@allparts);
1.54      albertel 3737:     return ($part,$type);
                   3738: }
                   3739: 
1.44      ng       3740: #------------- end of section for handling grading by section/class ---------
                   3741: #
                   3742: #----------------------------------------------------------------------------
                   3743: 
1.5       albertel 3744: 
1.44      ng       3745: #----------------------------------------------------------------------------
                   3746: #
                   3747: #-------------------------- Next few routines handles grading by csv upload
                   3748: #
                   3749: #--- Javascript to handle csv upload
1.27      albertel 3750: sub csvupload_javascript_reverse_associate {
1.573     bisitz   3751:     my $error1=&mt('You need to specify the username or the student/employee ID');
1.246     albertel 3752:     my $error2=&mt('You need to specify at least one grading field');
1.27      albertel 3753:   return(<<ENDPICK);
                   3754:   function verify(vf) {
                   3755:     var foundsomething=0;
                   3756:     var founduname=0;
1.243     albertel 3757:     var foundID=0;
1.27      albertel 3758:     for (i=0;i<=vf.nfields.value;i++) {
                   3759:       tw=eval('vf.f'+i+'.selectedIndex');
1.243     albertel 3760:       if (i==0 && tw!=0) { foundID=1; }
                   3761:       if (i==1 && tw!=0) { founduname=1; }
                   3762:       if (i!=0 && i!=1 && i!=2 && tw!=0) { foundsomething=1; }
1.27      albertel 3763:     }
1.246     albertel 3764:     if (founduname==0 && foundID==0) {
                   3765: 	alert('$error1');
                   3766: 	return;
1.27      albertel 3767:     }
                   3768:     if (foundsomething==0) {
1.246     albertel 3769: 	alert('$error2');
                   3770: 	return;
1.27      albertel 3771:     }
                   3772:     vf.submit();
                   3773:   }
                   3774:   function flip(vf,tf) {
                   3775:     var nw=eval('vf.f'+tf+'.selectedIndex');
                   3776:     var i;
                   3777:     for (i=0;i<=vf.nfields.value;i++) {
                   3778:       //can not pick the same destination field for both name and domain
                   3779:       if (((i ==0)||(i ==1)) && 
                   3780:           ((tf==0)||(tf==1)) && 
                   3781:           (i!=tf) &&
                   3782:           (eval('vf.f'+i+'.selectedIndex')==nw)) {
                   3783:         eval('vf.f'+i+'.selectedIndex=0;')
                   3784:       }
                   3785:     }
                   3786:   }
                   3787: ENDPICK
                   3788: }
                   3789: 
                   3790: sub csvupload_javascript_forward_associate {
1.573     bisitz   3791:     my $error1=&mt('You need to specify the username or the student/employee ID');
1.246     albertel 3792:     my $error2=&mt('You need to specify at least one grading field');
1.27      albertel 3793:   return(<<ENDPICK);
                   3794:   function verify(vf) {
                   3795:     var foundsomething=0;
                   3796:     var founduname=0;
1.243     albertel 3797:     var foundID=0;
1.27      albertel 3798:     for (i=0;i<=vf.nfields.value;i++) {
                   3799:       tw=eval('vf.f'+i+'.selectedIndex');
1.243     albertel 3800:       if (tw==1) { foundID=1; }
                   3801:       if (tw==2) { founduname=1; }
                   3802:       if (tw>3) { foundsomething=1; }
1.27      albertel 3803:     }
1.246     albertel 3804:     if (founduname==0 && foundID==0) {
                   3805: 	alert('$error1');
                   3806: 	return;
1.27      albertel 3807:     }
                   3808:     if (foundsomething==0) {
1.246     albertel 3809: 	alert('$error2');
                   3810: 	return;
1.27      albertel 3811:     }
                   3812:     vf.submit();
                   3813:   }
                   3814:   function flip(vf,tf) {
                   3815:     var nw=eval('vf.f'+tf+'.selectedIndex');
                   3816:     var i;
                   3817:     //can not pick the same destination field twice
                   3818:     for (i=0;i<=vf.nfields.value;i++) {
                   3819:       if ((i!=tf) && (eval('vf.f'+i+'.selectedIndex')==nw)) {
                   3820:         eval('vf.f'+i+'.selectedIndex=0;')
                   3821:       }
                   3822:     }
                   3823:   }
                   3824: ENDPICK
                   3825: }
                   3826: 
1.26      albertel 3827: sub csvuploadmap_header {
1.324     albertel 3828:     my ($request,$symb,$datatoken,$distotal)= @_;
1.41      ng       3829:     my $javascript;
1.257     albertel 3830:     if ($env{'form.upfile_associate'} eq 'reverse') {
1.41      ng       3831: 	$javascript=&csvupload_javascript_reverse_associate();
                   3832:     } else {
                   3833: 	$javascript=&csvupload_javascript_forward_associate();
                   3834:     }
1.45      ng       3835: 
1.598     www      3836:     my $result='';
1.257     albertel 3837:     my $checked=(($env{'form.noFirstLine'})?' checked="checked"':'');
1.245     albertel 3838:     my $ignore=&mt('Ignore First Line');
1.418     albertel 3839:     $symb = &Apache::lonenc::check_encrypt($symb);
1.41      ng       3840:     $request->print(<<ENDPICK);
1.26      albertel 3841: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="gradesupload">
1.398     albertel 3842: <h3><span class="LC_info">Uploading Class Grades</span></h3>
1.45      ng       3843: $result
1.326     albertel 3844: <hr />
1.26      albertel 3845: <h3>Identify fields</h3>
                   3846: Total number of records found in file: $distotal <hr />
                   3847: Enter as many fields as you can. The system will inform you and bring you back
                   3848: to this page if the data selected is insufficient to run your class.<hr />
1.589     bisitz   3849: <input type="button" value="Reverse Association" onclick="javascript:this.form.associate.value='Reverse Association';submit(this.form);" />
1.245     albertel 3850: <label><input type="checkbox" name="noFirstLine" $checked />$ignore</label>
1.26      albertel 3851: <input type="hidden" name="associate"  value="" />
                   3852: <input type="hidden" name="phase"      value="three" />
                   3853: <input type="hidden" name="datatoken"  value="$datatoken" />
1.257     albertel 3854: <input type="hidden" name="fileupload" value="$env{'form.fileupload'}" />
                   3855: <input type="hidden" name="upfiletype" value="$env{'form.upfiletype'}" />
1.26      albertel 3856: <input type="hidden" name="upfile_associate" 
1.257     albertel 3857:                                        value="$env{'form.upfile_associate'}" />
1.26      albertel 3858: <input type="hidden" name="symb"       value="$symb" />
1.257     albertel 3859: <input type="hidden" name="saveState"  value="$env{'form.saveState'}" />
1.246     albertel 3860: <input type="hidden" name="command"    value="csvuploadoptions" />
1.26      albertel 3861: <hr />
                   3862: ENDPICK
1.597     wenzelju 3863:     $request->print(&Apache::lonhtmlcommon::scripttag($javascript));
1.118     ng       3864:     return '';
1.26      albertel 3865: 
                   3866: }
                   3867: 
                   3868: sub csvupload_fields {
1.582     raeburn  3869:     my ($symb,$errorref) = @_;
                   3870:     my (@parts) = &getpartlist($symb,$errorref);
                   3871:     if (ref($errorref)) {
                   3872:         if ($$errorref) {
                   3873:             return;
                   3874:         }
                   3875:     }
                   3876: 
1.556     weissno  3877:     my @fields=(['ID','Student/Employee ID'],
1.243     albertel 3878: 		['username','Student Username'],
                   3879: 		['domain','Student Domain']);
1.324     albertel 3880:     my (undef,undef,$url) = &Apache::lonnet::decode_symb($symb);
1.41      ng       3881:     foreach my $part (sort(@parts)) {
                   3882: 	my @datum;
                   3883: 	my $display=&Apache::lonnet::metadata($url,$part.'.display');
                   3884: 	my $name=$part;
                   3885: 	if  (!$display) { $display = $name; }
                   3886: 	@datum=($name,$display);
1.244     albertel 3887: 	if ($name=~/^stores_(.*)_awarded/) {
                   3888: 	    push(@fields,['stores_'.$1.'_points',"Points [Part: $1]"]);
                   3889: 	}
1.41      ng       3890: 	push(@fields,\@datum);
                   3891:     }
                   3892:     return (@fields);
1.26      albertel 3893: }
                   3894: 
                   3895: sub csvuploadmap_footer {
1.41      ng       3896:     my ($request,$i,$keyfields) =@_;
                   3897:     $request->print(<<ENDPICK);
1.26      albertel 3898: </table>
                   3899: <input type="hidden" name="nfields" value="$i" />
                   3900: <input type="hidden" name="keyfields" value="$keyfields" />
1.589     bisitz   3901: <input type="button" onclick="javascript:verify(this.form)" value="Assign Grades" /><br />
1.26      albertel 3902: </form>
                   3903: ENDPICK
                   3904: }
                   3905: 
1.283     albertel 3906: sub checkforfile_js {
1.539     riegler  3907:     my $alertmsg = &mt('Please use the browse button to select a file from your local directory.');
1.597     wenzelju 3908:     my $result = &Apache::lonhtmlcommon::scripttag(<<CSVFORMJS);
1.86      ng       3909:     function checkUpload(formname) {
                   3910: 	if (formname.upfile.value == "") {
1.539     riegler  3911: 	    alert("$alertmsg");
1.86      ng       3912: 	    return false;
                   3913: 	}
                   3914: 	formname.submit();
                   3915:     }
                   3916: CSVFORMJS
1.283     albertel 3917:     return $result;
                   3918: }
                   3919: 
                   3920: sub upcsvScores_form {
1.608     www      3921:     my ($request,$symb) = @_;
1.283     albertel 3922:     if (!$symb) {return '';}
                   3923:     my $result=&checkforfile_js();
1.326     albertel 3924:     $result.='<br /><table width="100%" border="0"><tr><td bgcolor="#777777">'."\n";
                   3925:     $result.='<table width="100%" border="0"><tr bgcolor="#e6ffff"><td>'."\n";
1.538     schulted 3926:     $result.='&nbsp;<b>'.&mt('Specify a file containing the class scores for current resource.').
                   3927: 	'</b></td></tr>'."\n";
1.86      ng       3928:     $result.='<tr bgcolor=#ffffe6><td>'."\n";
1.370     www      3929:     my $upload=&mt("Upload Scores");
1.86      ng       3930:     my $upfile_select=&Apache::loncommon::upfile_select_html();
1.245     albertel 3931:     my $ignore=&mt('Ignore First Line');
1.418     albertel 3932:     $symb = &Apache::lonenc::check_encrypt($symb);
1.86      ng       3933:     $result.=<<ENDUPFORM;
1.106     albertel 3934: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="gradesupload">
1.86      ng       3935: <input type="hidden" name="symb" value="$symb" />
                   3936: <input type="hidden" name="command" value="csvuploadmap" />
1.257     albertel 3937: <input type="hidden" name="saveState"  value="$env{'form.saveState'}" />
1.86      ng       3938: $upfile_select
1.589     bisitz   3939: <br /><input type="button" onclick="javascript:checkUpload(this.form);" value="$upload" />
1.283     albertel 3940: <label><input type="checkbox" name="noFirstLine" />$ignore</label>
1.86      ng       3941: </form>
                   3942: ENDUPFORM
1.370     www      3943:     $result.=&Apache::loncommon::help_open_topic("Course_Convert_To_CSV",
                   3944:                            &mt("How do I create a CSV file from a spreadsheet"))
                   3945:     .'</td></tr></table>'."\n";
1.86      ng       3946:     $result.='</td></tr></table><br /><br />'."\n";
1.324     albertel 3947:     $result.=&show_grading_menu_form($symb);
1.86      ng       3948:     return $result;
                   3949: }
                   3950: 
                   3951: 
1.26      albertel 3952: sub csvuploadmap {
1.608     www      3953:     my ($request,$symb)= @_;
1.41      ng       3954:     if (!$symb) {return '';}
1.72      ng       3955: 
1.41      ng       3956:     my $datatoken;
1.257     albertel 3957:     if (!$env{'form.datatoken'}) {
1.41      ng       3958: 	$datatoken=&Apache::loncommon::upfile_store($request);
1.26      albertel 3959:     } else {
1.257     albertel 3960: 	$datatoken=$env{'form.datatoken'};
1.41      ng       3961: 	&Apache::loncommon::load_tmp_file($request);
1.26      albertel 3962:     }
1.41      ng       3963:     my @records=&Apache::loncommon::upfile_record_sep();
1.257     albertel 3964:     if ($env{'form.noFirstLine'}) { shift(@records); }
1.324     albertel 3965:     &csvuploadmap_header($request,$symb,$datatoken,$#records+1);
1.41      ng       3966:     my ($i,$keyfields);
                   3967:     if (@records) {
1.582     raeburn  3968:         my $fieldserror;
                   3969: 	my @fields=&csvupload_fields($symb,\$fieldserror);
                   3970:         if ($fieldserror) {
                   3971:             $request->print(&navmap_errormsg());
                   3972:             return;
                   3973:         }
1.257     albertel 3974: 	if ($env{'form.upfile_associate'} eq 'reverse') {	
1.41      ng       3975: 	    &Apache::loncommon::csv_print_samples($request,\@records);
                   3976: 	    $i=&Apache::loncommon::csv_print_select_table($request,\@records,
                   3977: 							  \@fields);
                   3978: 	    foreach (@fields) { $keyfields.=$_->[0].','; }
                   3979: 	    chop($keyfields);
                   3980: 	} else {
                   3981: 	    unshift(@fields,['none','']);
                   3982: 	    $i=&Apache::loncommon::csv_samples_select_table($request,\@records,
                   3983: 							    \@fields);
1.311     banghart 3984:             foreach my $rec (@records) {
                   3985:                 my %temp = &Apache::loncommon::record_sep($rec);
                   3986:                 if (%temp) {
                   3987:                     $keyfields=join(',',sort(keys(%temp)));
                   3988:                     last;
                   3989:                 }
                   3990:             }
1.41      ng       3991: 	}
                   3992:     }
                   3993:     &csvuploadmap_footer($request,$i,$keyfields);
1.324     albertel 3994:     $request->print(&show_grading_menu_form($symb));
1.72      ng       3995: 
1.41      ng       3996:     return '';
1.27      albertel 3997: }
                   3998: 
1.246     albertel 3999: sub csvuploadoptions {
1.608     www      4000:     my ($request,$symb)= @_;
1.257     albertel 4001:     my $checked=(($env{'form.noFirstLine'})?'1':'0');
1.246     albertel 4002:     my $ignore=&mt('Ignore First Line');
                   4003:     $request->print(<<ENDPICK);
                   4004: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="gradesupload">
1.398     albertel 4005: <h3><span class="LC_info">Uploading Class Grade Options</span></h3>
1.246     albertel 4006: <input type="hidden" name="command"    value="csvuploadassign" />
1.302     albertel 4007: <!--
1.246     albertel 4008: <p>
                   4009: <label>
                   4010:    <input type="checkbox" name="show_full_results" />
                   4011:    Show a table of all changes
                   4012: </label>
                   4013: </p>
1.302     albertel 4014: -->
1.246     albertel 4015: <p>
                   4016: <label>
                   4017:    <input type="checkbox" name="overwite_scores" checked="checked" />
                   4018:    Overwrite any existing score
                   4019: </label>
                   4020: </p>
                   4021: ENDPICK
                   4022:     my %fields=&get_fields();
                   4023:     if (!defined($fields{'domain'})) {
1.257     albertel 4024: 	my $domform = &Apache::loncommon::select_dom_form($env{'request.role.domain'},'default_domain');
1.246     albertel 4025: 	$request->print("\n<p> Users are in domain: ".$domform."</p>\n");
                   4026:     }
1.257     albertel 4027:     foreach my $key (sort(keys(%env))) {
1.246     albertel 4028: 	if ($key !~ /^form\.(.*)$/) { next; }
                   4029: 	my $cleankey=$1;
                   4030: 	if ($cleankey eq 'command') { next; }
                   4031: 	$request->print('<input type="hidden" name="'.$cleankey.
1.257     albertel 4032: 			'"  value="'.$env{$key}.'" />'."\n");
1.246     albertel 4033:     }
                   4034:     # FIXME do a check for any duplicated user ids...
                   4035:     # FIXME do a check for any invalid user ids?...
1.290     albertel 4036:     $request->print('<input type="submit" value="Assign Grades" /><br />
                   4037: <hr /></form>'."\n");
1.324     albertel 4038:     $request->print(&show_grading_menu_form($symb));
1.246     albertel 4039:     return '';
                   4040: }
                   4041: 
                   4042: sub get_fields {
                   4043:     my %fields;
1.257     albertel 4044:     my @keyfields = split(/\,/,$env{'form.keyfields'});
                   4045:     for (my $i=0; $i<=$env{'form.nfields'}; $i++) {
                   4046: 	if ($env{'form.upfile_associate'} eq 'reverse') {
                   4047: 	    if ($env{'form.f'.$i} ne 'none') {
                   4048: 		$fields{$keyfields[$i]}=$env{'form.f'.$i};
1.41      ng       4049: 	    }
                   4050: 	} else {
1.257     albertel 4051: 	    if ($env{'form.f'.$i} ne 'none') {
                   4052: 		$fields{$env{'form.f'.$i}}=$keyfields[$i];
1.41      ng       4053: 	    }
                   4054: 	}
1.27      albertel 4055:     }
1.246     albertel 4056:     return %fields;
                   4057: }
                   4058: 
                   4059: sub csvuploadassign {
1.608     www      4060:     my ($request,$symb)= @_;
1.246     albertel 4061:     if (!$symb) {return '';}
1.345     bowersj2 4062:     my $error_msg = '';
1.246     albertel 4063:     &Apache::loncommon::load_tmp_file($request);
                   4064:     my @gradedata = &Apache::loncommon::upfile_record_sep();
1.257     albertel 4065:     if ($env{'form.noFirstLine'}) { shift(@gradedata); }
1.246     albertel 4066:     my %fields=&get_fields();
1.41      ng       4067:     $request->print('<h3>Assigning Grades</h3>');
1.257     albertel 4068:     my $courseid=$env{'request.course.id'};
1.97      albertel 4069:     my ($classlist) = &getclasslist('all',0);
1.106     albertel 4070:     my @notallowed;
1.41      ng       4071:     my @skipped;
                   4072:     my $countdone=0;
                   4073:     foreach my $grade (@gradedata) {
                   4074: 	my %entries=&Apache::loncommon::record_sep($grade);
1.246     albertel 4075: 	my $domain;
                   4076: 	if ($entries{$fields{'domain'}}) {
                   4077: 	    $domain=$entries{$fields{'domain'}};
                   4078: 	} else {
1.257     albertel 4079: 	    $domain=$env{'form.default_domain'};
1.246     albertel 4080: 	}
1.243     albertel 4081: 	$domain=~s/\s//g;
1.41      ng       4082: 	my $username=$entries{$fields{'username'}};
1.160     albertel 4083: 	$username=~s/\s//g;
1.243     albertel 4084: 	if (!$username) {
                   4085: 	    my $id=$entries{$fields{'ID'}};
1.247     albertel 4086: 	    $id=~s/\s//g;
1.243     albertel 4087: 	    my %ids=&Apache::lonnet::idget($domain,$id);
                   4088: 	    $username=$ids{$id};
                   4089: 	}
1.41      ng       4090: 	if (!exists($$classlist{"$username:$domain"})) {
1.247     albertel 4091: 	    my $id=$entries{$fields{'ID'}};
                   4092: 	    $id=~s/\s//g;
                   4093: 	    if ($id) {
                   4094: 		push(@skipped,"$id:$domain");
                   4095: 	    } else {
                   4096: 		push(@skipped,"$username:$domain");
                   4097: 	    }
1.41      ng       4098: 	    next;
                   4099: 	}
1.108     albertel 4100: 	my $usec=$classlist->{"$username:$domain"}[5];
1.106     albertel 4101: 	if (!&canmodify($usec)) {
                   4102: 	    push(@notallowed,"$username:$domain");
                   4103: 	    next;
                   4104: 	}
1.244     albertel 4105: 	my %points;
1.41      ng       4106: 	my %grades;
                   4107: 	foreach my $dest (keys(%fields)) {
1.244     albertel 4108: 	    if ($dest eq 'ID' || $dest eq 'username' ||
                   4109: 		$dest eq 'domain') { next; }
                   4110: 	    if ($entries{$fields{$dest}} =~ /^\s*$/) { next; }
                   4111: 	    if ($dest=~/stores_(.*)_points/) {
                   4112: 		my $part=$1;
                   4113: 		my $wgt =&Apache::lonnet::EXT('resource.'.$part.'.weight',
                   4114: 					      $symb,$domain,$username);
1.345     bowersj2 4115:                 if ($wgt) {
                   4116:                     $entries{$fields{$dest}}=~s/\s//g;
                   4117:                     my $pcr=$entries{$fields{$dest}} / $wgt;
1.463     albertel 4118:                     my $award=($pcr == 0) ? 'incorrect_by_override'
                   4119:                                           : 'correct_by_override';
1.345     bowersj2 4120:                     $grades{"resource.$part.awarded"}=$pcr;
                   4121:                     $grades{"resource.$part.solved"}=$award;
                   4122:                     $points{$part}=1;
                   4123:                 } else {
                   4124:                     $error_msg = "<br />" .
                   4125:                         &mt("Some point values were assigned"
                   4126:                             ." for problems with a weight "
                   4127:                             ."of zero. These values were "
                   4128:                             ."ignored.");
                   4129:                 }
1.244     albertel 4130: 	    } else {
                   4131: 		if ($dest=~/stores_(.*)_awarded/) { if ($points{$1}) {next;} }
                   4132: 		if ($dest=~/stores_(.*)_solved/)  { if ($points{$1}) {next;} }
                   4133: 		my $store_key=$dest;
                   4134: 		$store_key=~s/^stores/resource/;
                   4135: 		$store_key=~s/_/\./g;
                   4136: 		$grades{$store_key}=$entries{$fields{$dest}};
                   4137: 	    }
1.41      ng       4138: 	}
1.508     www      4139: 	if (! %grades) { 
                   4140:            push(@skipped,&mt("[_1]: no data to save","$username:$domain")); 
                   4141:         } else {
                   4142: 	   $grades{"resource.regrader"}="$env{'user.name'}:$env{'user.domain'}";
                   4143: 	   my $result=&Apache::lonnet::cstore(\%grades,$symb,
1.302     albertel 4144: 					   $env{'request.course.id'},
                   4145: 					   $domain,$username);
1.508     www      4146: 	   if ($result eq 'ok') {
                   4147: 	      $request->print('.');
                   4148: 	   } else {
                   4149: 	      $request->print("<p><span class=\"LC_error\">".
                   4150:                               &mt("Failed to save data for student [_1]. Message when trying to save was: [_2]",
                   4151:                                   "$username:$domain",$result)."</span></p>");
                   4152: 	   }
                   4153: 	   $request->rflush();
                   4154: 	   $countdone++;
                   4155:         }
1.41      ng       4156:     }
1.570     www      4157:     $request->print('<br />'.&Apache::lonhtmlcommon::confirm_success(&mt("Saved scores for [quant,_1,student]",$countdone),$countdone==0));
1.41      ng       4158:     if (@skipped) {
1.571     www      4159: 	$request->print('<br />'.&Apache::lonhtmlcommon::confirm_success(&mt('No scores stored for the following username(s):'),1).'<br />');
                   4160:         $request->print(join(', ',@skipped));
1.106     albertel 4161:     }
                   4162:     if (@notallowed) {
1.571     www      4163: 	$request->print('<br />'.&Apache::lonhtmlcommon::confirm_success(&mt('Modification of scores not allowed for the following username(s):'),1).'<br />');
                   4164: 	$request->print(join(', ',@notallowed));
1.41      ng       4165:     }
1.106     albertel 4166:     $request->print("<br />\n");
1.324     albertel 4167:     $request->print(&show_grading_menu_form($symb));
1.345     bowersj2 4168:     return $error_msg;
1.26      albertel 4169: }
1.44      ng       4170: #------------- end of section for handling csv file upload ---------
                   4171: #
                   4172: #-------------------------------------------------------------------
                   4173: #
1.122     ng       4174: #-------------- Next few routines handle grading by page/sequence
1.72      ng       4175: #
                   4176: #--- Select a page/sequence and a student to grade
1.68      ng       4177: sub pickStudentPage {
1.608     www      4178:     my ($request,$symb) = @_;
1.68      ng       4179: 
1.539     riegler  4180:     my $alertmsg = &mt('Please select the student you wish to grade.');
1.597     wenzelju 4181:     $request->print(&Apache::lonhtmlcommon::scripttag(<<LISTJAVASCRIPT));
1.68      ng       4182: 
                   4183: function checkPickOne(formname) {
1.76      ng       4184:     if (radioSelection(formname.student) == null) {
1.539     riegler  4185: 	alert("$alertmsg");
1.68      ng       4186: 	return;
                   4187:     }
1.125     ng       4188:     ptr = pullDownSelection(formname.selectpage);
                   4189:     formname.page.value = formname["page"+ptr].value;
                   4190:     formname.title.value = formname["title"+ptr].value;
1.68      ng       4191:     formname.submit();
                   4192: }
                   4193: 
                   4194: LISTJAVASCRIPT
1.118     ng       4195:     &commonJSfunctions($request);
1.608     www      4196: 
1.257     albertel 4197:     my $cdom      = $env{"course.$env{'request.course.id'}.domain"};
                   4198:     my $cnum      = $env{"course.$env{'request.course.id'}.num"};
                   4199:     my $getsec    = $env{'form.section'} eq '' ? 'all' : $env{'form.section'};
1.68      ng       4200: 
1.398     albertel 4201:     my $result='<h3><span class="LC_info">&nbsp;'.
1.485     albertel 4202: 	&mt('Manual Grading by Page or Sequence').'</span></h3>';
1.68      ng       4203: 
1.80      ng       4204:     $result.='<form action="/adm/grades" method="post" name="displayPage">'."\n";
1.582     raeburn  4205:     my $map_error;
                   4206:     my ($titles,$symbx) = &getSymbMap($map_error);
                   4207:     if ($map_error) {
                   4208:         $request->print(&navmap_errormsg());
                   4209:         return; 
                   4210:     }
1.137     albertel 4211:     my ($curpage) =&Apache::lonnet::decode_symb($symb); 
                   4212: #    my ($curpage,$mapId) =&Apache::lonnet::decode_symb($symb); 
                   4213: #    my $type=($curpage =~ /\.(page|sequence)/);
1.485     albertel 4214:     my $select = '<select name="selectpage">'."\n";
1.70      ng       4215:     my $ctr=0;
1.68      ng       4216:     foreach (@$titles) {
                   4217: 	my ($minder,$showtitle) = ($_ =~ /(\d+)\.(.*)/);
1.485     albertel 4218: 	$select.='<option value="'.$ctr.'" '.
1.401     albertel 4219: 	    ($$symbx{$_} =~ /$curpage$/ ? 'selected="selected"' : '').
1.71      ng       4220: 	    '>'.$showtitle.'</option>'."\n";
1.70      ng       4221: 	$ctr++;
1.68      ng       4222:     }
1.485     albertel 4223:     $select.= '</select>';
1.539     riegler  4224:     $result.='&nbsp;<b>'.&mt('Problems from').':</b> '.$select."<br />\n";
1.485     albertel 4225: 
1.70      ng       4226:     $ctr=0;
                   4227:     foreach (@$titles) {
                   4228: 	my ($minder,$showtitle) = ($_ =~ /(\d+)\.(.*)/);
                   4229: 	$result.='<input type="hidden" name="page'.$ctr.'" value="'.$$symbx{$_}.'" />'."\n";
                   4230: 	$result.='<input type="hidden" name="title'.$ctr.'" value="'.$showtitle.'" />'."\n";
                   4231: 	$ctr++;
                   4232:     }
1.72      ng       4233:     $result.='<input type="hidden" name="page" />'."\n".
                   4234: 	'<input type="hidden" name="title" />'."\n";
1.68      ng       4235: 
1.485     albertel 4236:     my $options =
                   4237: 	'<label><input type="radio" name="vProb" value="no" checked="checked" /> '.&mt('no').' </label>'."\n".
                   4238: 	'<label><input type="radio" name="vProb" value="yes" /> '.&mt('yes').' </label>'."<br />\n";
1.539     riegler  4239:     $result.='&nbsp;<b>'.&mt('View Problem Text').': </b>'.$options;
1.485     albertel 4240: 
                   4241:     $options =
                   4242: 	'<label><input type="radio" name="lastSub" value="none" /> '.&mt('none').' </label>'."\n".
                   4243: 	'<label><input type="radio" name="lastSub" value="datesub" checked="checked" /> '.&mt('by dates and submissions').'</label>'."\n".
                   4244: 	'<label><input type="radio" name="lastSub" value="all" /> '.&mt('all details').' </label>'."\n";
1.539     riegler  4245:     $result.='&nbsp;<b>'.&mt('Submissions').': </b>'.$options;
1.432     banghart 4246:     
                   4247:     $result.=&build_section_inputs();
1.442     banghart 4248:     my $stu_status = join(':',&Apache::loncommon::get_env_multiple('form.Status'));
                   4249:     $result.='<input type="hidden" name="Status"  value="'.$stu_status.'" />'."\n".
1.72      ng       4250: 	'<input type="hidden" name="command" value="displayPage" />'."\n".
1.418     albertel 4251: 	'<input type="hidden" name="symb"    value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
1.257     albertel 4252: 	'<input type="hidden" name="saveState" value="'.$env{'form.saveState'}.'" />'."<br />\n";
1.72      ng       4253: 
1.539     riegler  4254:     $result.='&nbsp;<b>'.&mt('Use CODE').': </b> <input type="text" name="CODE" value="" /> <br />'."\n";
1.382     albertel 4255: 
1.80      ng       4256:     $result.='&nbsp;<input type="button" '.
1.589     bisitz   4257:              'onclick="javascript:checkPickOne(this.form);" value="'.&mt('Next').' &rarr;" /><br />'."\n";
1.72      ng       4258: 
1.68      ng       4259:     $request->print($result);
                   4260: 
1.485     albertel 4261:     my $studentTable.='&nbsp;<b>'.&mt('Select a student you wish to grade and then click on the Next button.').'</b><br />'.
1.484     albertel 4262: 	&Apache::loncommon::start_data_table().
                   4263: 	&Apache::loncommon::start_data_table_header_row().
1.485     albertel 4264: 	'<th align="right">&nbsp;'.&mt('No.').'</th>'.
1.484     albertel 4265: 	'<th>'.&nameUserString('header').'</th>'.
1.485     albertel 4266: 	'<th align="right">&nbsp;'.&mt('No.').'</th>'.
1.484     albertel 4267: 	'<th>'.&nameUserString('header').'</th>'.
                   4268: 	&Apache::loncommon::end_data_table_header_row();
1.68      ng       4269:  
1.76      ng       4270:     my (undef,undef,$fullname) = &getclasslist($getsec,'1');
1.68      ng       4271:     my $ptr = 1;
1.294     albertel 4272:     foreach my $student (sort 
                   4273: 			 {
                   4274: 			     if (lc($$fullname{$a}) ne lc($$fullname{$b})) {
                   4275: 				 return (lc($$fullname{$a}) cmp lc($$fullname{$b}));
                   4276: 			     }
                   4277: 			     return $a cmp $b;
                   4278: 			 } (keys(%$fullname))) {
1.68      ng       4279: 	my ($uname,$udom) = split(/:/,$student);
1.484     albertel 4280: 	$studentTable.=($ptr%2==1 ? &Apache::loncommon::start_data_table_row()
                   4281:                                   : '</td>');
1.126     ng       4282: 	$studentTable.='<td align="right">'.$ptr.'&nbsp;</td>';
1.288     albertel 4283: 	$studentTable.='<td>&nbsp;<label><input type="radio" name="student" value="'.$student.'" /> '
                   4284: 	    .&nameUserString(undef,$$fullname{$student},$uname,$udom)."</label>\n";
1.484     albertel 4285: 	$studentTable.=
                   4286: 	    ($ptr%2 == 0 ? '</td>'.&Apache::loncommon::end_data_table_row() 
                   4287:                          : '');
1.68      ng       4288: 	$ptr++;
                   4289:     }
1.484     albertel 4290:     if ($ptr%2 == 0) {
                   4291: 	$studentTable.='</td><td>&nbsp;</td><td>&nbsp;</td>'.
                   4292: 	    &Apache::loncommon::end_data_table_row();
                   4293:     }
                   4294:     $studentTable.=&Apache::loncommon::end_data_table()."\n";
1.126     ng       4295:     $studentTable.='<input type="button" '.
1.589     bisitz   4296:                    'onclick="javascript:checkPickOne(this.form);" value="'.&mt('Next').' &rarr;" /></form>'."\n";
1.68      ng       4297: 
1.324     albertel 4298:     $studentTable.=&show_grading_menu_form($symb);
1.68      ng       4299:     $request->print($studentTable);
                   4300: 
                   4301:     return '';
                   4302: }
                   4303: 
                   4304: sub getSymbMap {
1.582     raeburn  4305:     my ($map_error) = @_;
1.132     bowersj2 4306:     my $navmap = Apache::lonnavmaps::navmap->new();
1.582     raeburn  4307:     unless (ref($navmap)) {
                   4308:         if (ref($map_error)) {
                   4309:             $$map_error = 'navmap';
                   4310:         }
                   4311:         return;
                   4312:     }
1.68      ng       4313:     my %symbx = ();
                   4314:     my @titles = ();
1.117     bowersj2 4315:     my $minder = 0;
                   4316: 
                   4317:     # Gather every sequence that has problems.
1.240     albertel 4318:     my @sequences = $navmap->retrieveResources(undef, sub { shift->is_map(); },
                   4319: 					       1,0,1);
1.117     bowersj2 4320:     for my $sequence ($navmap->getById('0.0'), @sequences) {
1.241     albertel 4321: 	if ($navmap->hasResource($sequence, sub { shift->is_problem(); }, 0) ) {
1.381     albertel 4322: 	    my $title = $minder.'.'.
                   4323: 		&HTML::Entities::encode($sequence->compTitle(),'"\'&');
                   4324: 	    push(@titles, $title); # minder in case two titles are identical
                   4325: 	    $symbx{$title} = &HTML::Entities::encode($sequence->symb(),'"\'&');
1.117     bowersj2 4326: 	    $minder++;
1.241     albertel 4327: 	}
1.68      ng       4328:     }
                   4329:     return \@titles,\%symbx;
                   4330: }
                   4331: 
1.72      ng       4332: #
                   4333: #--- Displays a page/sequence w/wo problems, w/wo submissions
1.68      ng       4334: sub displayPage {
1.608     www      4335:     my ($request,$symb) = @_;
1.257     albertel 4336:     my $cdom      = $env{"course.$env{'request.course.id'}.domain"};
                   4337:     my $cnum      = $env{"course.$env{'request.course.id'}.num"};
                   4338:     my $getsec    = $env{'form.section'} eq '' ? 'all' : $env{'form.section'};
                   4339:     my $pageTitle = $env{'form.page'};
1.103     albertel 4340:     my ($classlist,undef,$fullname) = &getclasslist($getsec,'1');
1.257     albertel 4341:     my ($uname,$udom) = split(/:/,$env{'form.student'});
                   4342:     my $usec=$classlist->{$env{'form.student'}}[5];
1.168     albertel 4343: 
                   4344:     #need to make sure we have the correct data for later EXT calls, 
                   4345:     #thus invalidate the cache
                   4346:     &Apache::lonnet::devalidatecourseresdata(
1.257     albertel 4347:                  $env{'course.'.$env{'request.course.id'}.'.num'},
                   4348:                  $env{'course.'.$env{'request.course.id'}.'.domain'});
1.168     albertel 4349:     &Apache::lonnet::clear_EXT_cache_status();
                   4350: 
1.103     albertel 4351:     if (!&canview($usec)) {
1.485     albertel 4352: 	$request->print('<span class="LC_warning">'.&mt('Unable to view requested student. ([_1])',$env{'form.student'}).'</span>');
1.324     albertel 4353: 	$request->print(&show_grading_menu_form($symb));
1.103     albertel 4354: 	return;
                   4355:     }
1.398     albertel 4356:     my $result='<h3><span class="LC_info">&nbsp;'.$env{'form.title'}.'</span></h3>';
1.485     albertel 4357:     $result.='<h3>&nbsp;'.&mt('Student: [_1]',&nameUserString(undef,$$fullname{$env{'form.student'}},$uname,$udom)).
1.129     ng       4358: 	'</h3>'."\n";
1.500     albertel 4359:     $env{'form.CODE'} = uc($env{'form.CODE'});
1.501     foxr     4360:     if (&Apache::lonnet::validCODE(uc($env{'form.CODE'}))) {
1.485     albertel 4361: 	$result.='<h3>&nbsp;'.&mt('CODE: [_1]',$env{'form.CODE'}).'</h3>'."\n";
1.382     albertel 4362:     } else {
                   4363: 	delete($env{'form.CODE'});
                   4364:     }
1.71      ng       4365:     &sub_page_js($request);
                   4366:     $request->print($result);
                   4367: 
1.132     bowersj2 4368:     my $navmap = Apache::lonnavmaps::navmap->new();
1.582     raeburn  4369:     unless (ref($navmap)) {
                   4370:         $request->print(&navmap_errormsg());
                   4371:         $request->print(&show_grading_menu_form($symb));
                   4372:         return;
                   4373:     }
1.257     albertel 4374:     my ($mapUrl, $id, $resUrl)=&Apache::lonnet::decode_symb($env{'form.page'});
1.68      ng       4375:     my $map = $navmap->getResourceByUrl($resUrl); # add to navmaps
1.288     albertel 4376:     if (!$map) {
1.485     albertel 4377: 	$request->print('<span class="LC_warning">'.&mt('Unable to view requested sequence. ([_1])',$resUrl).'</span>');
1.324     albertel 4378: 	$request->print(&show_grading_menu_form($symb));
1.288     albertel 4379: 	return; 
                   4380:     }
1.68      ng       4381:     my $iterator = $navmap->getIterator($map->map_start(),
                   4382: 					$map->map_finish());
                   4383: 
1.71      ng       4384:     my $studentTable='<form action="/adm/grades" method="post" name="gradePage">'."\n".
1.72      ng       4385: 	'<input type="hidden" name="command" value="gradeByPage" />'."\n".
1.257     albertel 4386: 	'<input type="hidden" name="fullname" value="'.$$fullname{$env{'form.student'}}.'" />'."\n".
                   4387: 	'<input type="hidden" name="student" value="'.$env{'form.student'}.'" />'."\n".
1.72      ng       4388: 	'<input type="hidden" name="page"    value="'.$pageTitle.'" />'."\n".
1.257     albertel 4389: 	'<input type="hidden" name="title"   value="'.$env{'form.title'}.'" />'."\n".
1.418     albertel 4390: 	'<input type="hidden" name="symb"    value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
1.125     ng       4391: 	'<input type="hidden" name="overRideScore" value="no" />'."\n".
1.257     albertel 4392: 	'<input type="hidden" name="saveState" value="'.$env{'form.saveState'}.'" />'."\n";
1.71      ng       4393: 
1.382     albertel 4394:     if (defined($env{'form.CODE'})) {
                   4395: 	$studentTable.=
                   4396: 	    '<input type="hidden" name="CODE" value="'.$env{'form.CODE'}.'" />'."\n";
                   4397:     }
1.381     albertel 4398:     my $checkIcon = '<img alt="'.&mt('Check Mark').
1.485     albertel 4399: 	'" src="'.&Apache::loncommon::lonhttpdurl($request->dir_config('lonIconsURL').'/check.gif').'" height="16" border="0" />';
1.71      ng       4400: 
1.594     bisitz   4401:     $studentTable.='&nbsp;<span class="LC_info">'.
                   4402:         &mt('Problems graded correct by the computer are marked with a [_1] symbol.',$checkIcon).
                   4403:         '</span>'."\n".
1.484     albertel 4404: 	&Apache::loncommon::start_data_table().
                   4405: 	&Apache::loncommon::start_data_table_header_row().
                   4406: 	'<th align="center">&nbsp;Prob.&nbsp;</th>'.
1.485     albertel 4407: 	'<th>&nbsp;'.($env{'form.vProb'} eq 'no' ? &mt('Title') : &mt('Problem Text')).'/'.&mt('Grade').'</th>'.
1.484     albertel 4408: 	&Apache::loncommon::end_data_table_header_row();
1.71      ng       4409: 
1.329     albertel 4410:     &Apache::lonxml::clear_problem_counter();
1.196     albertel 4411:     my ($depth,$question,$prob) = (1,1,1);
1.68      ng       4412:     $iterator->next(); # skip the first BEGIN_MAP
                   4413:     my $curRes = $iterator->next(); # for "current resource"
1.101     albertel 4414:     while ($depth > 0) {
1.68      ng       4415:         if($curRes == $iterator->BEGIN_MAP) { $depth++; }
1.100     bowersj2 4416:         if($curRes == $iterator->END_MAP) { $depth--; }
1.68      ng       4417: 
1.385     albertel 4418:         if (ref($curRes) && $curRes->is_problem()) {
1.91      albertel 4419: 	    my $parts = $curRes->parts();
1.68      ng       4420:             my $title = $curRes->compTitle();
1.71      ng       4421: 	    my $symbx = $curRes->symb();
1.484     albertel 4422: 	    $studentTable.=
                   4423: 		&Apache::loncommon::start_data_table_row().
                   4424: 		'<td align="center" valign="top" >'.$prob.
1.485     albertel 4425: 		(scalar(@{$parts}) == 1 ? '' 
                   4426: 		                        : '<br />('.&mt('[_1]&nbsp;parts)',
                   4427: 							scalar(@{$parts}))
                   4428: 		 ).
                   4429: 		 '</td>';
1.71      ng       4430: 	    $studentTable.='<td valign="top">';
1.382     albertel 4431: 	    my %form = ('CODE' => $env{'form.CODE'},);
1.257     albertel 4432: 	    if ($env{'form.vProb'} eq 'yes' ) {
1.144     albertel 4433: 		$studentTable.=&show_problem($request,$symbx,$uname,$udom,1,
1.383     albertel 4434: 					     undef,'both',\%form);
1.71      ng       4435: 	    } else {
1.382     albertel 4436: 		my $companswer = &Apache::loncommon::get_student_answers($symbx,$uname,$udom,$env{'request.course.id'},%form);
1.80      ng       4437: 		$companswer =~ s|<form(.*?)>||g;
                   4438: 		$companswer =~ s|</form>||g;
1.71      ng       4439: #		while ($companswer =~ /(<a href\=\"javascript:newWindow.*?Script Vars<\/a>)/s) { #<a href="javascript:newWindow</a>
1.116     ng       4440: #		    $companswer =~ s/$1/ /ms;
1.326     albertel 4441: #		    $request->print('match='.$1."<br />\n");
1.71      ng       4442: #		}
1.116     ng       4443: #		$companswer =~ s|<table border=\"1\">|<table border=\"0\">|g;
1.539     riegler  4444: 		$studentTable.='&nbsp;<b>'.$title.'</b>&nbsp;<br />&nbsp;<b>'.&mt('Correct answer').':</b><br />'.$companswer;
1.71      ng       4445: 	    }
                   4446: 
1.257     albertel 4447: 	    my %record = &Apache::lonnet::restore($symbx,$env{'request.course.id'},$udom,$uname);
1.125     ng       4448: 
1.257     albertel 4449: 	    if ($env{'form.lastSub'} eq 'datesub') {
1.71      ng       4450: 		if ($record{'version'} eq '') {
1.485     albertel 4451: 		    $studentTable.='<br />&nbsp;<span class="LC_warning">'.&mt('No recorded submission for this problem.').'</span><br />';
1.71      ng       4452: 		} else {
1.116     ng       4453: 		    my %responseType = ();
                   4454: 		    foreach my $partid (@{$parts}) {
1.147     albertel 4455: 			my @responseIds =$curRes->responseIds($partid);
                   4456: 			my @responseType =$curRes->responseType($partid);
                   4457: 			my %responseIds;
                   4458: 			for (my $i=0;$i<=$#responseIds;$i++) {
                   4459: 			    $responseIds{$responseIds[$i]}=$responseType[$i];
                   4460: 			}
                   4461: 			$responseType{$partid} = \%responseIds;
1.116     ng       4462: 		    }
1.148     albertel 4463: 		    $studentTable.= &displaySubByDates($symbx,\%record,$parts,\%responseType,$checkIcon,$uname,$udom);
1.147     albertel 4464: 
1.71      ng       4465: 		}
1.257     albertel 4466: 	    } elsif ($env{'form.lastSub'} eq 'all') {
                   4467: 		my $last = ($env{'form.lastSub'} eq 'last' ? 'last' : '');
1.71      ng       4468: 		$studentTable.=&Apache::loncommon::get_previous_attempt($symbx,$uname,$udom,
1.257     albertel 4469: 									$env{'request.course.id'},
1.71      ng       4470: 									'','.submission');
                   4471:  
                   4472: 	    }
1.103     albertel 4473: 	    if (&canmodify($usec)) {
1.585     bisitz   4474:             $studentTable.=&gradeBox_start();
1.103     albertel 4475: 		foreach my $partid (@{$parts}) {
                   4476: 		    $studentTable.=&gradeBox($request,$symbx,$uname,$udom,$question,$partid,\%record);
                   4477: 		    $studentTable.='<input type="hidden" name="q_'.$question.'" value="'.$partid.'" />'."\n";
                   4478: 		    $question++;
                   4479: 		}
1.585     bisitz   4480:             $studentTable.=&gradeBox_end();
1.196     albertel 4481: 		$prob++;
1.71      ng       4482: 	    }
                   4483: 	    $studentTable.='</td></tr>';
1.68      ng       4484: 
1.103     albertel 4485: 	}
1.68      ng       4486:         $curRes = $iterator->next();
                   4487:     }
                   4488: 
1.589     bisitz   4489:     $studentTable.=
                   4490:         '</table>'."\n".
                   4491:         '<input type="button" value="'.&mt('Save').'" '.
                   4492:         'onclick="javascript:checkSubmitPage(this.form,'.$question.');" />'.
                   4493:         '</form>'."\n";
1.324     albertel 4494:     $studentTable.=&show_grading_menu_form($symb);
1.71      ng       4495:     $request->print($studentTable);
                   4496: 
                   4497:     return '';
1.119     ng       4498: }
                   4499: 
                   4500: sub displaySubByDates {
1.148     albertel 4501:     my ($symb,$record,$parts,$responseType,$checkIcon,$uname,$udom) = @_;
1.224     albertel 4502:     my $isCODE=0;
1.335     albertel 4503:     my $isTask = ($symb =~/\.task$/);
1.224     albertel 4504:     if (exists($record->{'resource.CODE'})) { $isCODE=1; }
1.467     albertel 4505:     my $studentTable=&Apache::loncommon::start_data_table().
                   4506: 	&Apache::loncommon::start_data_table_header_row().
                   4507: 	'<th>'.&mt('Date/Time').'</th>'.
                   4508: 	($isCODE?'<th>'.&mt('CODE').'</th>':'').
                   4509: 	'<th>'.&mt('Submission').'</th>'.
                   4510: 	'<th>'.&mt('Status').'</th>'.
                   4511: 	&Apache::loncommon::end_data_table_header_row();
1.119     ng       4512:     my ($version);
                   4513:     my %mark;
1.148     albertel 4514:     my %orders;
1.119     ng       4515:     $mark{'correct_by_student'} = $checkIcon;
1.147     albertel 4516:     if (!exists($$record{'1:timestamp'})) {
1.539     riegler  4517: 	return '<br />&nbsp;<span class="LC_warning">'.&mt('Nothing submitted - no attempts.').'</span><br />';
1.147     albertel 4518:     }
1.335     albertel 4519: 
                   4520:     my $interaction;
1.525     raeburn  4521:     my $no_increment = 1;
1.119     ng       4522:     for ($version=1;$version<=$$record{'version'};$version++) {
1.467     albertel 4523: 	my $timestamp = 
                   4524: 	    &Apache::lonlocal::locallocaltime($$record{$version.':timestamp'});
1.335     albertel 4525: 	if (exists($$record{$version.':resource.0.version'})) {
                   4526: 	    $interaction = $$record{$version.':resource.0.version'};
                   4527: 	}
                   4528: 
                   4529: 	my $where = ($isTask ? "$version:resource.$interaction"
                   4530: 		             : "$version:resource");
1.467     albertel 4531: 	$studentTable.=&Apache::loncommon::start_data_table_row().
                   4532: 	    '<td>'.$timestamp.'</td>';
1.224     albertel 4533: 	if ($isCODE) {
                   4534: 	    $studentTable.='<td>'.$record->{$version.':resource.CODE'}.'</td>';
                   4535: 	}
1.119     ng       4536: 	my @versionKeys = split(/\:/,$$record{$version.':keys'});
                   4537: 	my @displaySub = ();
                   4538: 	foreach my $partid (@{$parts}) {
1.596     raeburn  4539:             my $hidden;
                   4540:             if (($$record{$version.':resource.'.$partid.'.type'} eq 'anonsurvey') ||
                   4541:                 ($$record{$version.':resource.'.$partid.'.type'} eq 'anonsurveycred')) {
                   4542:                 $hidden = 1;
                   4543:             }
1.335     albertel 4544: 	    my @matchKey = ($isTask ? sort(grep /^resource\.\d+\.\Q$partid\E\.award$/,@versionKeys)
                   4545: 			            : sort(grep /^resource\.\Q$partid\E\..*?\.submission$/,@versionKeys));
                   4546: 	    
1.122     ng       4547: #	    next if ($$record{"$version:resource.$partid.solved"} eq '');
1.324     albertel 4548: 	    my $display_part=&get_display_part($partid,$symb);
1.147     albertel 4549: 	    foreach my $matchKey (@matchKey) {
1.198     albertel 4550: 		if (exists($$record{$version.':'.$matchKey}) &&
                   4551: 		    $$record{$version.':'.$matchKey} ne '') {
1.596     raeburn  4552:                     
1.335     albertel 4553: 		    my ($responseId)= ($isTask ? ($matchKey=~ /^resource\.(.*?)\.\Q$partid\E\.award$/)
                   4554: 				               : ($matchKey=~ /^resource\.\Q$partid\E\.(.*?)\.submission$/));
1.577     bisitz   4555:                     $displaySub[0].='<span class="LC_nobreak"';
                   4556:                     $displaySub[0].='<b>'.&mt('Part: [_1]',$display_part).'</b>'
                   4557:                                    .' <span class="LC_internal_info">'
                   4558:                                    .'('.&mt('Part ID: [_1]',$responseId).')'
                   4559:                                    .'</span>'
                   4560:                                    .' <b>';
1.596     raeburn  4561:                     if ($hidden) {
                   4562:                         $displaySub[0].= &mt('Anonymous Survey').'</b>';
                   4563:                     } else {
                   4564: 		        if ($$record{"$where.$partid.tries"} eq '') {
                   4565: 			    $displaySub[0].=&mt('Trial not counted');
                   4566: 		        } else {
                   4567: 			    $displaySub[0].=&mt('Trial: [_1]',
1.467     albertel 4568: 					    $$record{"$where.$partid.tries"});
1.596     raeburn  4569: 		        }
                   4570: 		        my $responseType=($isTask ? 'Task'
1.335     albertel 4571:                                               : $responseType->{$partid}->{$responseId});
1.596     raeburn  4572: 		        if (!exists($orders{$partid})) { $orders{$partid}={}; }
                   4573: 		        if (!exists($orders{$partid}->{$responseId})) {
                   4574: 			    $orders{$partid}->{$responseId}=
                   4575: 			        &get_order($partid,$responseId,$symb,$uname,$udom,
                   4576:                                            $no_increment);
                   4577: 		        }
                   4578: 		        $displaySub[0].='</b></span>'; # /nobreak
                   4579: 		        $displaySub[0].='&nbsp; '.
                   4580: 			    &cleanRecord($$record{$version.':'.$matchKey},$responseType,$symb,$partid,$responseId,$record,$orders{$partid}->{$responseId},"$version:",$uname,$udom).'<br />';
                   4581:                     }
1.147     albertel 4582: 		}
                   4583: 	    }
1.335     albertel 4584: 	    if (exists($$record{"$where.$partid.checkedin"})) {
1.485     albertel 4585: 		$displaySub[1].=&mt('Checked in by [_1] into slot [_2]',
                   4586: 				    $$record{"$where.$partid.checkedin"},
                   4587: 				    $$record{"$where.$partid.checkedin.slot"}).
                   4588: 					'<br />';
1.335     albertel 4589: 	    }
                   4590: 	    if (exists $$record{"$where.$partid.award"}) {
1.485     albertel 4591: 		$displaySub[1].='<b>'.&mt('Part:').'</b>&nbsp;'.$display_part.' &nbsp;'.
1.335     albertel 4592: 		    lc($$record{"$where.$partid.award"}).' '.
                   4593: 		    $mark{$$record{"$where.$partid.solved"}}.
1.147     albertel 4594: 		    '<br />';
                   4595: 	    }
1.335     albertel 4596: 	    if (exists $$record{"$where.$partid.regrader"}) {
                   4597: 		$displaySub[2].=$$record{"$where.$partid.regrader"}.
                   4598: 		    ' (<b>'.&mt('Part').':</b> '.$display_part.')';
                   4599: 	    } elsif ($$record{"$version:resource.$partid.regrader"} =~ /\S/) {
                   4600: 		$displaySub[2].=
                   4601: 		    $$record{"$version:resource.$partid.regrader"}.
1.207     albertel 4602: 		    ' (<b>'.&mt('Part').':</b> '.$display_part.')';
1.147     albertel 4603: 	    }
                   4604: 	}
                   4605: 	# needed because old essay regrader has not parts info
                   4606: 	if (exists $$record{"$version:resource.regrader"}) {
                   4607: 	    $displaySub[2].=$$record{"$version:resource.regrader"};
                   4608: 	}
                   4609: 	$studentTable.='<td>'.$displaySub[0].'&nbsp;</td><td>'.$displaySub[1];
                   4610: 	if ($displaySub[2]) {
1.467     albertel 4611: 	    $studentTable.=&mt('Manually graded by [_1]',$displaySub[2]);
1.147     albertel 4612: 	}
1.467     albertel 4613: 	$studentTable.='&nbsp;</td>'.
                   4614: 	    &Apache::loncommon::end_data_table_row();
1.119     ng       4615:     }
1.467     albertel 4616:     $studentTable.=&Apache::loncommon::end_data_table();
1.119     ng       4617:     return $studentTable;
1.71      ng       4618: }
                   4619: 
                   4620: sub updateGradeByPage {
1.608     www      4621:     my ($request,$symb) = @_;
1.71      ng       4622: 
1.257     albertel 4623:     my $cdom      = $env{"course.$env{'request.course.id'}.domain"};
                   4624:     my $cnum      = $env{"course.$env{'request.course.id'}.num"};
                   4625:     my $getsec    = $env{'form.section'} eq '' ? 'all' : $env{'form.section'};
                   4626:     my $pageTitle = $env{'form.page'};
1.103     albertel 4627:     my ($classlist,undef,$fullname) = &getclasslist($getsec,'1');
1.257     albertel 4628:     my ($uname,$udom) = split(/:/,$env{'form.student'});
                   4629:     my $usec=$classlist->{$env{'form.student'}}[5];
1.103     albertel 4630:     if (!&canmodify($usec)) {
1.526     raeburn  4631: 	$request->print('<span class="LC_warning">'.&mt('Unable to modify requested student ([_1])',$env{'form.student'}).'</span>');
1.324     albertel 4632: 	$request->print(&show_grading_menu_form($env{'form.symb'}));
1.103     albertel 4633: 	return;
                   4634:     }
1.398     albertel 4635:     my $result='<h3><span class="LC_info">&nbsp;'.$env{'form.title'}.'</span></h3>';
1.526     raeburn  4636:     $result.='<h3>&nbsp;'.&mt('Student: ').&nameUserString(undef,$env{'form.fullname'},$uname,$udom).
1.129     ng       4637: 	'</h3>'."\n";
1.70      ng       4638: 
1.68      ng       4639:     $request->print($result);
                   4640: 
1.582     raeburn  4641: 
1.132     bowersj2 4642:     my $navmap = Apache::lonnavmaps::navmap->new();
1.582     raeburn  4643:     unless (ref($navmap)) {
                   4644:         $request->print(&navmap_errormsg());
                   4645:         return;
                   4646:     }
1.257     albertel 4647:     my ($mapUrl, $id, $resUrl) = &Apache::lonnet::decode_symb( $env{'form.page'});
1.71      ng       4648:     my $map = $navmap->getResourceByUrl($resUrl); # add to navmaps
1.288     albertel 4649:     if (!$map) {
1.527     raeburn  4650: 	$request->print('<span class="LC_warning">'.&mt('Unable to grade requested sequence ([_1]).',$resUrl).'</span>');
1.324     albertel 4651: 	$request->print(&show_grading_menu_form($symb));
1.288     albertel 4652: 	return; 
                   4653:     }
1.71      ng       4654:     my $iterator = $navmap->getIterator($map->map_start(),
                   4655: 					$map->map_finish());
1.70      ng       4656: 
1.484     albertel 4657:     my $studentTable=
                   4658: 	&Apache::loncommon::start_data_table().
                   4659: 	&Apache::loncommon::start_data_table_header_row().
1.485     albertel 4660: 	'<th align="center">&nbsp;'.&mt('Prob.').'&nbsp;</th>'.
                   4661: 	'<th>&nbsp;'.&mt('Title').'&nbsp;</th>'.
                   4662: 	'<th>&nbsp;'.&mt('Previous Score').'&nbsp;</th>'.
                   4663: 	'<th>&nbsp;'.&mt('New Score').'&nbsp;</th>'.
1.484     albertel 4664: 	&Apache::loncommon::end_data_table_header_row();
1.71      ng       4665: 
                   4666:     $iterator->next(); # skip the first BEGIN_MAP
                   4667:     my $curRes = $iterator->next(); # for "current resource"
1.196     albertel 4668:     my ($depth,$question,$prob,$changeflag)= (1,1,1,0);
1.101     albertel 4669:     while ($depth > 0) {
1.71      ng       4670:         if($curRes == $iterator->BEGIN_MAP) { $depth++; }
1.100     bowersj2 4671:         if($curRes == $iterator->END_MAP) { $depth--; }
1.71      ng       4672: 
1.385     albertel 4673:         if (ref($curRes) && $curRes->is_problem()) {
1.91      albertel 4674: 	    my $parts = $curRes->parts();
1.71      ng       4675:             my $title = $curRes->compTitle();
                   4676: 	    my $symbx = $curRes->symb();
1.484     albertel 4677: 	    $studentTable.=
                   4678: 		&Apache::loncommon::start_data_table_row().
                   4679: 		'<td align="center" valign="top" >'.$prob.
1.485     albertel 4680: 		(scalar(@{$parts}) == 1 ? '' 
1.526     raeburn  4681:                                         : '<br />('.&mt('[quant,_1,&nbsp;part]',scalar(@{$parts}))
                   4682: 		.')').'</td>';
1.71      ng       4683: 	    $studentTable.='<td valign="top">&nbsp;<b>'.$title.'</b>&nbsp;</td>';
                   4684: 
                   4685: 	    my %newrecord=();
                   4686: 	    my @displayPts=();
1.269     raeburn  4687:             my %aggregate = ();
                   4688:             my $aggregateflag = 0;
1.71      ng       4689: 	    foreach my $partid (@{$parts}) {
1.257     albertel 4690: 		my $newpts = $env{'form.GD_BOX'.$question.'_'.$partid};
                   4691: 		my $oldpts = $env{'form.oldpts'.$question.'_'.$partid};
1.71      ng       4692: 
1.257     albertel 4693: 		my $wgt = $env{'form.WGT'.$question.'_'.$partid} != 0 ? 
                   4694: 		    $env{'form.WGT'.$question.'_'.$partid} : 1;
1.71      ng       4695: 		my $partial = $newpts/$wgt;
                   4696: 		my $score;
                   4697: 		if ($partial > 0) {
                   4698: 		    $score = 'correct_by_override';
1.125     ng       4699: 		} elsif ($newpts ne '') { #empty is taken as 0
1.71      ng       4700: 		    $score = 'incorrect_by_override';
                   4701: 		}
1.257     albertel 4702: 		my $dropMenu = $env{'form.GD_SEL'.$question.'_'.$partid};
1.125     ng       4703: 		if ($dropMenu eq 'excused') {
1.71      ng       4704: 		    $partial = '';
                   4705: 		    $score = 'excused';
1.125     ng       4706: 		} elsif ($dropMenu eq 'reset status'
1.257     albertel 4707: 			 && $env{'form.solved'.$question.'_'.$partid} ne '') { #update only if previous record exists
1.125     ng       4708: 		    $newrecord{'resource.'.$partid.'.tries'} = 0;
                   4709: 		    $newrecord{'resource.'.$partid.'.solved'} = '';
                   4710: 		    $newrecord{'resource.'.$partid.'.award'} = '';
                   4711: 		    $newrecord{'resource.'.$partid.'.awarded'} = 0;
1.257     albertel 4712: 		    $newrecord{'resource.'.$partid.'.regrader'} = "$env{'user.name'}:$env{'user.domain'}";
1.125     ng       4713: 		    $changeflag++;
                   4714: 		    $newpts = '';
1.269     raeburn  4715:                     
                   4716:                     my $aggtries =  $env{'form.aggtries'.$question.'_'.$partid};
                   4717:                     my $totaltries = $env{'form.totaltries'.$question.'_'.$partid};
                   4718:                     my $solvedstatus = $env{'form.solved'.$question.'_'.$partid};
                   4719:                     if ($aggtries > 0) {
                   4720:                         &decrement_aggs($symbx,$partid,\%aggregate,$aggtries,$totaltries,$solvedstatus);
                   4721:                         $aggregateflag = 1;
                   4722:                     }
1.71      ng       4723: 		}
1.324     albertel 4724: 		my $display_part=&get_display_part($partid,$curRes->symb());
1.257     albertel 4725: 		my $oldstatus = $env{'form.solved'.$question.'_'.$partid};
1.526     raeburn  4726: 		$displayPts[0].='&nbsp;<b>'.&mt('Part').':</b> '.$display_part.' = '.
1.71      ng       4727: 		    (($oldstatus eq 'excused') ? 'excused' : $oldpts).
1.326     albertel 4728: 		    '&nbsp;<br />';
1.526     raeburn  4729: 		$displayPts[1].='&nbsp;<b>'.&mt('Part').':</b> '.$display_part.' = '.
1.125     ng       4730: 		     (($score eq 'excused') ? 'excused' : $newpts).
1.326     albertel 4731: 		    '&nbsp;<br />';
1.71      ng       4732: 		$question++;
1.380     albertel 4733: 		next if ($dropMenu eq 'reset status' || ($newpts eq $oldpts && $score ne 'excused'));
1.125     ng       4734: 
1.71      ng       4735: 		$newrecord{'resource.'.$partid.'.awarded'}  = $partial if $partial ne '';
1.125     ng       4736: 		$newrecord{'resource.'.$partid.'.solved'}   = $score if $score ne '';
1.257     albertel 4737: 		$newrecord{'resource.'.$partid.'.regrader'} = "$env{'user.name'}:$env{'user.domain'}"
1.125     ng       4738: 		    if (scalar(keys(%newrecord)) > 0);
1.71      ng       4739: 
                   4740: 		$changeflag++;
                   4741: 	    }
                   4742: 	    if (scalar(keys(%newrecord)) > 0) {
1.382     albertel 4743: 		my %record = 
                   4744: 		    &Apache::lonnet::restore($symbx,$env{'request.course.id'},
                   4745: 					     $udom,$uname);
                   4746: 
                   4747: 		if (&Apache::lonnet::validCODE($env{'form.CODE'})) {
                   4748: 		    $newrecord{'resource.CODE'} = $env{'form.CODE'};
                   4749: 		} elsif (&Apache::lonnet::validCODE($record{'resource.CODE'})) {
                   4750: 		    $newrecord{'resource.CODE'} = '';
                   4751: 		}
1.257     albertel 4752: 		&Apache::lonnet::cstore(\%newrecord,$symbx,$env{'request.course.id'},
1.71      ng       4753: 					$udom,$uname);
1.382     albertel 4754: 		%record = &Apache::lonnet::restore($symbx,
                   4755: 						   $env{'request.course.id'},
                   4756: 						   $udom,$uname);
1.380     albertel 4757: 		&check_and_remove_from_queue($parts,\%record,undef,$symbx,
                   4758: 					     $cdom,$cnum,$udom,$uname);
1.71      ng       4759: 	    }
1.380     albertel 4760: 	    
1.269     raeburn  4761:             if ($aggregateflag) {
                   4762:                 &Apache::lonnet::cinc('nohist_resourcetracker',\%aggregate,
                   4763:                       $env{'course.'.$env{'request.course.id'}.'.domain'},
                   4764:                       $env{'course.'.$env{'request.course.id'}.'.num'});
                   4765:             }
1.125     ng       4766: 
1.71      ng       4767: 	    $studentTable.='<td valign="top">'.$displayPts[0].'</td>'.
                   4768: 		'<td valign="top">'.$displayPts[1].'</td>'.
1.484     albertel 4769: 		&Apache::loncommon::end_data_table_row();
1.68      ng       4770: 
1.196     albertel 4771: 	    $prob++;
1.68      ng       4772: 	}
1.71      ng       4773:         $curRes = $iterator->next();
1.68      ng       4774:     }
1.98      albertel 4775: 
1.484     albertel 4776:     $studentTable.=&Apache::loncommon::end_data_table();
1.324     albertel 4777:     $studentTable.=&show_grading_menu_form($env{'form.symb'});
1.526     raeburn  4778:     my $grademsg=($changeflag == 0 ? &mt('No score was changed or updated.') :
                   4779: 		  &mt('The scores were changed for [quant,_1,problem].',
                   4780: 		  $changeflag));
1.76      ng       4781:     $request->print($grademsg.$studentTable);
1.68      ng       4782: 
1.70      ng       4783:     return '';
                   4784: }
                   4785: 
1.72      ng       4786: #-------- end of section for handling grading by page/sequence ---------
                   4787: #
                   4788: #-------------------------------------------------------------------
                   4789: 
1.581     www      4790: #-------------------- Bubblesheet (Scantron) Grading -------------------
1.75      albertel 4791: #
                   4792: #------ start of section for handling grading by page/sequence ---------
                   4793: 
1.423     albertel 4794: =pod
                   4795: 
                   4796: =head1 Bubble sheet grading routines
                   4797: 
1.424     albertel 4798:   For this documentation:
                   4799: 
                   4800:    'scanline' refers to the full line of characters
                   4801:    from the file that we are parsing that represents one entire sheet
                   4802: 
                   4803:    'bubble line' refers to the data
                   4804:    representing the line of bubbles that are on the physical bubble sheet
                   4805: 
                   4806: 
                   4807: The overall process is that a scanned in bubble sheet data is uploaded
                   4808: into a course. When a user wants to grade, they select a
                   4809: sequence/folder of resources, a file of bubble sheet info, and pick
                   4810: one of the predefined configurations for what each scanline looks
                   4811: like.
                   4812: 
                   4813: Next each scanline is checked for any errors of either 'missing
1.435     foxr     4814: bubbles' (it's an error because it may have been mis-scanned
1.424     albertel 4815: because too light bubbling), 'double bubble' (each bubble line should
                   4816: have no more that one letter picked), invalid or duplicated CODE,
1.556     weissno  4817: invalid student/employee ID
1.424     albertel 4818: 
                   4819: If the CODE option is used that determines the randomization of the
1.556     weissno  4820: homework problems, either way the student/employee ID is looked up into a
1.424     albertel 4821: username:domain.
                   4822: 
                   4823: During the validation phase the instructor can choose to skip scanlines. 
                   4824: 
1.435     foxr     4825: After the validation phase, there are now 3 bubble sheet files
1.424     albertel 4826: 
                   4827:   scantron_original_filename (unmodified original file)
                   4828:   scantron_corrected_filename (file where the corrected information has replaced the original information)
                   4829:   scantron_skipped_filename (contains the exact text of scanlines that where skipped)
                   4830: 
                   4831: Also there is a separate hash nohist_scantrondata that contains extra
                   4832: correction information that isn't representable in the bubble sheet
                   4833: file (see &scantron_getfile() for more information)
                   4834: 
                   4835: After all scanlines are either valid, marked as valid or skipped, then
                   4836: foreach line foreach problem in the picked sequence, an ssi request is
                   4837: made that simulates a user submitting their selected letter(s) against
                   4838: the homework problem.
1.423     albertel 4839: 
                   4840: =over 4
                   4841: 
                   4842: 
                   4843: 
                   4844: =item defaultFormData
                   4845: 
                   4846:   Returns html hidden inputs used to hold context/default values.
                   4847: 
                   4848:  Arguments:
                   4849:   $symb - $symb of the current resource 
                   4850: 
                   4851: =cut
1.422     foxr     4852: 
1.81      albertel 4853: sub defaultFormData {
1.324     albertel 4854:     my ($symb)=@_;
1.447     foxr     4855:     return '<input type="hidden" name="symb"    value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
1.605     www      4856:      '<input type="hidden" name="saveState" value="'.$env{'form.saveState'}.'" />';
1.81      albertel 4857: }
                   4858: 
1.447     foxr     4859: 
1.423     albertel 4860: =pod 
                   4861: 
                   4862: =item getSequenceDropDown
                   4863: 
                   4864:    Return html dropdown of possible sequences to grade
                   4865:  
                   4866:  Arguments:
1.582     raeburn  4867:    $symb - $symb of the current resource
                   4868:    $map_error - ref to scalar which will container error if
                   4869:                 $navmap object is unavailable in &getSymbMap().
1.423     albertel 4870: 
                   4871: =cut
1.422     foxr     4872: 
1.75      albertel 4873: sub getSequenceDropDown {
1.582     raeburn  4874:     my ($symb,$map_error)=@_;
1.75      albertel 4875:     my $result='<select name="selectpage">'."\n";
1.582     raeburn  4876:     my ($titles,$symbx) = &getSymbMap($map_error);
                   4877:     if (ref($map_error)) {
                   4878:         return if ($$map_error);
                   4879:     }
1.137     albertel 4880:     my ($curpage)=&Apache::lonnet::decode_symb($symb); 
1.75      albertel 4881:     my $ctr=0;
                   4882:     foreach (@$titles) {
                   4883: 	my ($minder,$showtitle) = ($_ =~ /(\d+)\.(.*)/);
                   4884: 	$result.='<option value="'.$$symbx{$_}.'" '.
1.401     albertel 4885: 	    ($$symbx{$_} =~ /$curpage$/ ? 'selected="selected"' : '').
1.75      albertel 4886: 	    '>'.$showtitle.'</option>'."\n";
                   4887: 	$ctr++;
                   4888:     }
                   4889:     $result.= '</select>';
                   4890:     return $result;
                   4891: }
                   4892: 
1.495     albertel 4893: my %bubble_lines_per_response;     # no. bubble lines for each response.
1.554     raeburn  4894:                                    # key is zero-based index - 0, 1, 2 ...
1.495     albertel 4895: 
                   4896: my %first_bubble_line;             # First bubble line no. for each bubble.
                   4897: 
1.509     raeburn  4898: my %subdivided_bubble_lines;       # no. bubble lines for optionresponse, 
                   4899:                                    # matchresponse or rankresponse, where 
                   4900:                                    # an individual response can have multiple 
                   4901:                                    # lines
1.503     raeburn  4902: 
                   4903: my %responsetype_per_response;     # responsetype for each response
                   4904: 
1.495     albertel 4905: # Save and restore the bubble lines array to the form env.
                   4906: 
                   4907: 
                   4908: sub save_bubble_lines {
                   4909:     foreach my $line (keys(%bubble_lines_per_response)) {
                   4910: 	$env{"form.scantron.bubblelines.$line"}  = $bubble_lines_per_response{$line};
                   4911: 	$env{"form.scantron.first_bubble_line.$line"} =
                   4912: 	    $first_bubble_line{$line};
1.503     raeburn  4913:         $env{"form.scantron.sub_bubblelines.$line"} = 
                   4914:             $subdivided_bubble_lines{$line};
                   4915:         $env{"form.scantron.responsetype.$line"} =
                   4916:             $responsetype_per_response{$line};
1.495     albertel 4917:     }
                   4918: }
                   4919: 
                   4920: 
                   4921: sub restore_bubble_lines {
                   4922:     my $line = 0;
                   4923:     %bubble_lines_per_response = ();
                   4924:     while ($env{"form.scantron.bubblelines.$line"}) {
                   4925: 	my $value = $env{"form.scantron.bubblelines.$line"};
                   4926: 	$bubble_lines_per_response{$line} = $value;
                   4927: 	$first_bubble_line{$line}  =
                   4928: 	    $env{"form.scantron.first_bubble_line.$line"};
1.503     raeburn  4929:         $subdivided_bubble_lines{$line} =
                   4930:             $env{"form.scantron.sub_bubblelines.$line"};
                   4931:         $responsetype_per_response{$line} =
                   4932:             $env{"form.scantron.responsetype.$line"};
1.495     albertel 4933: 	$line++;
                   4934:     }
                   4935: }
                   4936: 
                   4937: #  Given the parsed scanline, get the response for 
                   4938: #  'answer' number n:
                   4939: 
                   4940: sub get_response_bubbles {
                   4941:     my ($parsed_line, $response)  = @_;
                   4942: 
                   4943:     my $bubble_line = $first_bubble_line{$response-1} +1;
                   4944:     my $bubble_lines= $bubble_lines_per_response{$response-1};
                   4945:     
                   4946:     my $selected = "";
                   4947: 
                   4948:     for (my $bline = 0; $bline < $bubble_lines; $bline++) {
                   4949: 	$selected .= $$parsed_line{"scantron.$bubble_line.answer"}.":";
                   4950: 	$bubble_line++;
                   4951:     }
                   4952:     return $selected;
                   4953: }
1.423     albertel 4954: 
                   4955: =pod 
                   4956: 
                   4957: =item scantron_filenames
                   4958: 
                   4959:    Returns a list of the scantron files in the current course 
                   4960: 
                   4961: =cut
1.422     foxr     4962: 
1.202     albertel 4963: sub scantron_filenames {
1.257     albertel 4964:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
                   4965:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
1.517     raeburn  4966:     my $getpropath = 1;
1.157     albertel 4967:     my @files=&Apache::lonnet::dirlist('userfiles',$cdom,$cname,
1.517     raeburn  4968:                                        $getpropath);
1.202     albertel 4969:     my @possiblenames;
1.201     albertel 4970:     foreach my $filename (sort(@files)) {
1.157     albertel 4971: 	($filename)=split(/&/,$filename);
                   4972: 	if ($filename!~/^scantron_orig_/) { next ; }
                   4973: 	$filename=~s/^scantron_orig_//;
1.202     albertel 4974: 	push(@possiblenames,$filename);
                   4975:     }
                   4976:     return @possiblenames;
                   4977: }
                   4978: 
1.423     albertel 4979: =pod 
                   4980: 
                   4981: =item scantron_uploads
                   4982: 
                   4983:    Returns  html drop-down list of scantron files in current course.
                   4984: 
                   4985:  Arguments:
                   4986:    $file2grade - filename to set as selected in the dropdown
                   4987: 
                   4988: =cut
1.422     foxr     4989: 
1.202     albertel 4990: sub scantron_uploads {
1.209     ng       4991:     my ($file2grade) = @_;
1.202     albertel 4992:     my $result=	'<select name="scantron_selectfile">';
                   4993:     $result.="<option></option>";
                   4994:     foreach my $filename (sort(&scantron_filenames())) {
1.401     albertel 4995: 	$result.="<option".($filename eq $file2grade ? ' selected="selected"':'').">$filename</option>\n";
1.81      albertel 4996:     }
                   4997:     $result.="</select>";
                   4998:     return $result;
                   4999: }
                   5000: 
1.423     albertel 5001: =pod 
                   5002: 
                   5003: =item scantron_scantab
                   5004: 
                   5005:   Returns html drop down of the scantron formats in the scantronformat.tab
                   5006:   file.
                   5007: 
                   5008: =cut
1.422     foxr     5009: 
1.82      albertel 5010: sub scantron_scantab {
                   5011:     my $result='<select name="scantron_format">'."\n";
1.191     albertel 5012:     $result.='<option></option>'."\n";
1.518     raeburn  5013:     my @lines = &get_scantronformat_file();
                   5014:     if (@lines > 0) {
                   5015:         foreach my $line (@lines) {
                   5016:             next if (($line =~ /^\#/) || ($line eq ''));
                   5017: 	    my ($name,$descrip)=split(/:/,$line);
                   5018: 	    $result.='<option value="'.$name.'">'.$descrip.'</option>'."\n";
                   5019:         }
1.82      albertel 5020:     }
                   5021:     $result.='</select>'."\n";
1.518     raeburn  5022:     return $result;
                   5023: }
                   5024: 
                   5025: =pod
                   5026: 
                   5027: =item get_scantronformat_file
                   5028: 
                   5029:   Returns an array containing lines from the scantron format file for
                   5030:   the domain of the course.
                   5031: 
                   5032:   If a url for a custom.tab file is listed in domain's configuration.db, 
                   5033:   lines are from this file.
                   5034: 
                   5035:   Otherwise, if a default.tab has been published in RES space by the 
                   5036:   domainconfig user, lines are from this file.
                   5037: 
                   5038:   Otherwise, fall back to getting lines from the legacy file on the
1.519     raeburn  5039:   local server:  /home/httpd/lonTabs/default_scantronformat.tab    
1.82      albertel 5040: 
1.518     raeburn  5041: =cut
                   5042: 
                   5043: sub get_scantronformat_file {
                   5044:     my $cdom= $env{'course.'.$env{'request.course.id'}.'.domain'};
                   5045:     my %domconfig = &Apache::lonnet::get_dom('configuration',['scantron'],$cdom);
                   5046:     my $gottab = 0;
                   5047:     my @lines;
                   5048:     if (ref($domconfig{'scantron'}) eq 'HASH') {
                   5049:         if ($domconfig{'scantron'}{'scantronformat'} ne '') {
                   5050:             my $formatfile = &Apache::lonnet::getfile($Apache::lonnet::perlvar{'lonDocRoot'}.$domconfig{'scantron'}{'scantronformat'});
                   5051:             if ($formatfile ne '-1') {
                   5052:                 @lines = split("\n",$formatfile,-1);
                   5053:                 $gottab = 1;
                   5054:             }
                   5055:         }
                   5056:     }
                   5057:     if (!$gottab) {
                   5058:         my $confname = $cdom.'-domainconfig';
                   5059:         my $default = $Apache::lonnet::perlvar{'lonDocRoot'}.'/res/'.$cdom.'/'.$confname.'/default.tab';
                   5060:         my $formatfile =  &Apache::lonnet::getfile($default);
                   5061:         if ($formatfile ne '-1') {
                   5062:             @lines = split("\n",$formatfile,-1);
                   5063:             $gottab = 1;
                   5064:         }
                   5065:     }
                   5066:     if (!$gottab) {
1.519     raeburn  5067:         my @domains = &Apache::lonnet::current_machine_domains();
                   5068:         if (grep(/^\Q$cdom\E$/,@domains)) {
                   5069:             my $fh=Apache::File->new($Apache::lonnet::perlvar{'lonTabDir'}.'/scantronformat.tab');
                   5070:             @lines = <$fh>;
                   5071:             close($fh);
                   5072:         } else {
                   5073:             my $fh=Apache::File->new($Apache::lonnet::perlvar{'lonTabDir'}.'/default_scantronformat.tab');
                   5074:             @lines = <$fh>;
                   5075:             close($fh);
                   5076:         }
1.518     raeburn  5077:     }
                   5078:     return @lines;
1.82      albertel 5079: }
                   5080: 
1.423     albertel 5081: =pod 
                   5082: 
                   5083: =item scantron_CODElist
                   5084: 
                   5085:   Returns html drop down of the saved CODE lists from current course,
                   5086:   generated from earlier printings.
                   5087: 
                   5088: =cut
1.422     foxr     5089: 
1.186     albertel 5090: sub scantron_CODElist {
1.257     albertel 5091:     my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   5092:     my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
1.186     albertel 5093:     my @names=&Apache::lonnet::getkeys('CODEs',$cdom,$cnum);
                   5094:     my $namechoice='<option></option>';
1.225     albertel 5095:     foreach my $name (sort {uc($a) cmp uc($b)} @names) {
1.191     albertel 5096: 	if ($name =~ /^error: 2 /) { next; }
1.278     albertel 5097: 	if ($name =~ /^type\0/) { next; }
1.186     albertel 5098: 	$namechoice.='<option value="'.$name.'">'.$name.'</option>';
                   5099:     }
                   5100:     $namechoice='<select name="scantron_CODElist">'.$namechoice.'</select>';
                   5101:     return $namechoice;
                   5102: }
                   5103: 
1.423     albertel 5104: =pod 
                   5105: 
                   5106: =item scantron_CODEunique
                   5107: 
                   5108:   Returns the html for "Each CODE to be used once" radio.
                   5109: 
                   5110: =cut
1.422     foxr     5111: 
1.186     albertel 5112: sub scantron_CODEunique {
1.532     bisitz   5113:     my $result='<span class="LC_nobreak">
1.272     albertel 5114:                  <label><input type="radio" name="scantron_CODEunique"
1.423     albertel 5115:                         value="yes" checked="checked" />'.&mt('Yes').' </label>
1.381     albertel 5116:                 </span>
1.532     bisitz   5117:                 <span class="LC_nobreak">
1.272     albertel 5118:                  <label><input type="radio" name="scantron_CODEunique"
1.423     albertel 5119:                         value="no" />'.&mt('No').' </label>
1.381     albertel 5120:                 </span>';
1.186     albertel 5121:     return $result;
                   5122: }
1.423     albertel 5123: 
                   5124: =pod 
                   5125: 
                   5126: =item scantron_selectphase
                   5127: 
                   5128:   Generates the initial screen to start the bubble sheet process.
                   5129:   Allows for - starting a grading run.
1.424     albertel 5130:              - downloading existing scan data (original, corrected
1.423     albertel 5131:                                                 or skipped info)
                   5132: 
                   5133:              - uploading new scan data
                   5134: 
                   5135:  Arguments:
                   5136:   $r          - The Apache request object
                   5137:   $file2grade - name of the file that contain the scanned data to score
                   5138: 
                   5139: =cut
1.186     albertel 5140: 
1.75      albertel 5141: sub scantron_selectphase {
1.608     www      5142:     my ($r,$file2grade,$symb) = @_;
1.75      albertel 5143:     if (!$symb) {return '';}
1.582     raeburn  5144:     my $map_error;
                   5145:     my $sequence_selector=&getSequenceDropDown($symb,\$map_error);
                   5146:     if ($map_error) {
                   5147:         $r->print('<br />'.&navmap_errormsg().'<br />');
                   5148:         return;
                   5149:     }
1.324     albertel 5150:     my $default_form_data=&defaultFormData($symb);
                   5151:     my $grading_menu_button=&show_grading_menu_form($symb);
1.209     ng       5152:     my $file_selector=&scantron_uploads($file2grade);
1.82      albertel 5153:     my $format_selector=&scantron_scantab();
1.186     albertel 5154:     my $CODE_selector=&scantron_CODElist();
                   5155:     my $CODE_unique=&scantron_CODEunique();
1.75      albertel 5156:     my $result;
1.422     foxr     5157: 
1.513     foxr     5158:     $ssi_error = 0;
                   5159: 
1.606     wenzelju 5160:     if (&Apache::lonnet::allowed('usc',$env{'request.role.domain'}) ||
                   5161:         &Apache::lonnet::allowed('usc',$env{'request.course.id'})) {
                   5162: 
                   5163: 	# Chunk of form to prompt for a scantron file upload.
                   5164: 
                   5165:         $r->print('
                   5166:     <br />
                   5167:     '.&Apache::loncommon::start_data_table('LC_scantron_action').'
                   5168:        '.&Apache::loncommon::start_data_table_header_row().'
                   5169:             <th>
                   5170:               &nbsp;'.&mt('Specify a bubblesheet data file to upload.').'
                   5171:             </th>
                   5172:        '.&Apache::loncommon::end_data_table_header_row().'
                   5173:        '.&Apache::loncommon::start_data_table_row().'
                   5174:             <td>
                   5175: ');
1.608     www      5176:     my $default_form_data=&defaultFormData($symb);
1.606     wenzelju 5177:     my $cdom= $env{'course.'.$env{'request.course.id'}.'.domain'};
                   5178:     my $cnum= $env{'course.'.$env{'request.course.id'}.'.num'};
                   5179:     $r->print(&Apache::lonhtmlcommon::scripttag('
                   5180:     function checkUpload(formname) {
                   5181: 	if (formname.upfile.value == "") {
                   5182: 	    alert("'.&mt('Please use the browse button to select a file from your local directory.').'");
                   5183: 	    return false;
                   5184: 	}
                   5185: 	formname.submit();
                   5186:     }'));
                   5187:     $r->print('
                   5188:               <form enctype="multipart/form-data" action="/adm/grades" name="rules" method="post">
                   5189:                 '.$default_form_data.'
                   5190:                 <input name="courseid" type="hidden" value="'.$cnum.'" />
                   5191:                 <input name="domainid" type="hidden" value="'.$cdom.'" />
                   5192:                 <input name="command" value="scantronupload_save" type="hidden" />
                   5193:                 '.&mt('File to upload: [_1]','<input type="file" name="upfile" size="50" />').'
                   5194:                 <br />
                   5195:                 <input type="button" onclick="javascript:checkUpload(this.form);" value="'.&mt('Upload Bubblesheet Data').'" />
                   5196:               </form>
                   5197: ');
                   5198: 
                   5199:         $r->print('
                   5200:             </td>
                   5201:        '.&Apache::loncommon::end_data_table_row().'
                   5202:        '.&Apache::loncommon::end_data_table().'
                   5203: ');
                   5204:     }
                   5205: 
1.422     foxr     5206:     # Chunk of form to prompt for a file to grade and how:
                   5207: 
1.489     albertel 5208:     $result.= '
                   5209:     <br />
                   5210:     <form method="post" enctype="multipart/form-data" action="/adm/grades" name="scantron_process">
                   5211:     <input type="hidden" name="command" value="scantron_warning" />
                   5212:     '.$default_form_data.'
                   5213:     '.&Apache::loncommon::start_data_table('LC_scantron_action').'
                   5214:        '.&Apache::loncommon::start_data_table_header_row().'
                   5215:             <th colspan="2">
1.492     albertel 5216:               &nbsp;'.&mt('Specify file and which Folder/Sequence to grade').'
1.489     albertel 5217:             </th>
                   5218:        '.&Apache::loncommon::end_data_table_header_row().'
                   5219:        '.&Apache::loncommon::start_data_table_row().'
1.492     albertel 5220:             <td> '.&mt('Sequence to grade:').' </td><td> '.$sequence_selector.' </td>
1.489     albertel 5221:        '.&Apache::loncommon::end_data_table_row().'
                   5222:        '.&Apache::loncommon::start_data_table_row().'
1.572     www      5223:             <td> '.&mt('Filename of bubblesheet data file:').' </td><td> '.$file_selector.' </td>
1.489     albertel 5224:        '.&Apache::loncommon::end_data_table_row().'
                   5225:        '.&Apache::loncommon::start_data_table_row().'
1.572     www      5226:             <td> '.&mt('Format of bubblesheet data file:').' </td><td> '.$format_selector.' </td>
1.489     albertel 5227:        '.&Apache::loncommon::end_data_table_row().'
                   5228:        '.&Apache::loncommon::start_data_table_row().'
1.492     albertel 5229:             <td> '.&mt('Saved CODEs to validate against:').' </td><td> '.$CODE_selector.' </td>
1.489     albertel 5230:        '.&Apache::loncommon::end_data_table_row().'
                   5231:        '.&Apache::loncommon::start_data_table_row().'
1.492     albertel 5232:             <td> '.&mt('Each CODE is only to be used once:').'</td><td> '.$CODE_unique.' </td>
1.489     albertel 5233:        '.&Apache::loncommon::end_data_table_row().'
                   5234:        '.&Apache::loncommon::start_data_table_row().'
1.492     albertel 5235: 	    <td> '.&mt('Options:').' </td>
1.187     albertel 5236:             <td>
1.492     albertel 5237: 	       <label><input type="checkbox" name="scantron_options_redo" value="redo_skipped"/> '.&mt('Do only previously skipped records').'</label> <br />
                   5238:                <label><input type="checkbox" name="scantron_options_ignore" value="ignore_corrections"/> '.&mt('Remove all existing corrections').'</label> <br />
                   5239:                <label><input type="checkbox" name="scantron_options_hidden" value="ignore_hidden"/> '.&mt('Skip hidden resources when grading').'</label>
1.187     albertel 5240: 	    </td>
1.489     albertel 5241:        '.&Apache::loncommon::end_data_table_row().'
                   5242:        '.&Apache::loncommon::start_data_table_row().'
1.174     albertel 5243:             <td colspan="2">
1.572     www      5244:               <input type="submit" value="'.&mt('Grading: Validate Bubblesheet Records').'" />
1.162     albertel 5245:             </td>
1.489     albertel 5246:        '.&Apache::loncommon::end_data_table_row().'
                   5247:     '.&Apache::loncommon::end_data_table().'
                   5248:     </form>
                   5249: ';
1.162     albertel 5250:    
                   5251:     $r->print($result);
                   5252: 
1.422     foxr     5253: 
                   5254: 
                   5255:     # Chunk of the form that prompts to view a scoring office file,
                   5256:     # corrected file, skipped records in a file.
                   5257: 
1.489     albertel 5258:     $r->print('
                   5259:    <br />
                   5260:    <form action="/adm/grades" name="scantron_download">
                   5261:      '.$default_form_data.'
                   5262:      <input type="hidden" name="command" value="scantron_download" />
                   5263:      '.&Apache::loncommon::start_data_table('LC_scantron_action').'
                   5264:        '.&Apache::loncommon::start_data_table_header_row().'
                   5265:               <th>
1.492     albertel 5266:                 &nbsp;'.&mt('Download a scoring office file').'
1.489     albertel 5267:               </th>
                   5268:        '.&Apache::loncommon::end_data_table_header_row().'
                   5269:        '.&Apache::loncommon::start_data_table_row().'
1.492     albertel 5270:               <td> '.&mt('Filename of scoring office file: [_1]',$file_selector).' 
1.489     albertel 5271:                 <br />
1.492     albertel 5272:                 <input type="submit" value="'.&mt('Download: Show List of Associated Files').'" />
1.489     albertel 5273:        '.&Apache::loncommon::end_data_table_row().'
                   5274:      '.&Apache::loncommon::end_data_table().'
                   5275:    </form>
                   5276:    <br />
                   5277: ');
1.162     albertel 5278: 
1.457     banghart 5279:     &Apache::lonpickcode::code_list($r,2);
1.523     raeburn  5280: 
1.528     raeburn  5281:     $r->print('<br /><form method="post" name="checkscantron">'.
1.523     raeburn  5282:              $default_form_data."\n".
                   5283:              &Apache::loncommon::start_data_table('LC_scantron_action')."\n".
                   5284:              &Apache::loncommon::start_data_table_header_row()."\n".
                   5285:              '<th colspan="2">
1.572     www      5286:               &nbsp;'.&mt('Review bubblesheet data and submissions for a previously graded folder/sequence')."\n".
1.523     raeburn  5287:              '</th>'."\n".
                   5288:               &Apache::loncommon::end_data_table_header_row()."\n".
                   5289:               &Apache::loncommon::start_data_table_row()."\n".
                   5290:               '<td> '.&mt('Graded folder/sequence:').' </td>'."\n".
                   5291:               '<td> '.$sequence_selector.' </td>'.
                   5292:               &Apache::loncommon::end_data_table_row()."\n".
                   5293:               &Apache::loncommon::start_data_table_row()."\n".
                   5294:               '<td> '.&mt('Filename of scoring office file:').' </td>'."\n".
                   5295:               '<td> '.$file_selector.' </td>'."\n".
                   5296:               &Apache::loncommon::end_data_table_row()."\n".
                   5297:               &Apache::loncommon::start_data_table_row()."\n".
                   5298:               '<td> '.&mt('Format of data file:').' </td>'."\n".
                   5299:               '<td> '.$format_selector.' </td>'."\n".
                   5300:               &Apache::loncommon::end_data_table_row()."\n".
                   5301:               &Apache::loncommon::start_data_table_row()."\n".
1.557     raeburn  5302:               '<td> '.&mt('Options').' </td>'."\n".
                   5303:               '<td> <label><input type="checkbox" name="scantron_options_hidden" value="ignore_hidden"/> '.&mt('Skip hidden resources').'</label></td>'.
                   5304:               &Apache::loncommon::end_data_table_row()."\n".
                   5305:               &Apache::loncommon::start_data_table_row()."\n".
1.523     raeburn  5306:               '<td colspan="2">'."\n".
                   5307:               '<input type="hidden" name="command" value="checksubmissions" />'."\n".
1.575     www      5308:               '<input type="submit" value="'.&mt('Review Bubblesheet Data and Submission Records').'" />'."\n".
1.523     raeburn  5309:               '</td>'."\n".
                   5310:               &Apache::loncommon::end_data_table_row()."\n".
                   5311:               &Apache::loncommon::end_data_table()."\n".
                   5312:               '</form><br />');
1.457     banghart 5313:     $r->print($grading_menu_button);
1.523     raeburn  5314:     return;
1.75      albertel 5315: }
                   5316: 
1.423     albertel 5317: =pod
                   5318: 
                   5319: =item get_scantron_config
                   5320: 
                   5321:    Parse and return the scantron configuration line selected as a
                   5322:    hash of configuration file fields.
                   5323: 
                   5324:  Arguments:
                   5325:     which - the name of the configuration to parse from the file.
                   5326: 
                   5327: 
                   5328:  Returns:
                   5329:             If the named configuration is not in the file, an empty
                   5330:             hash is returned.
                   5331:     a hash with the fields
                   5332:       name         - internal name for the this configuration setup
                   5333:       description  - text to display to operator that describes this config
                   5334:       CODElocation - if 0 or the string 'none'
                   5335:                           - no CODE exists for this config
                   5336:                      if -1 || the string 'letter'
                   5337:                           - a CODE exists for this config and is
                   5338:                             a string of letters
                   5339:                      Unsupported value (but planned for future support)
                   5340:                           if a positive integer
                   5341:                                - The CODE exists as the first n items from
                   5342:                                  the question section of the form
                   5343:                           if the string 'number'
                   5344:                                - The CODE exists for this config and is
                   5345:                                  a string of numbers
                   5346:       CODEstart   - (only matter if a CODE exists) column in the line where
                   5347:                      the CODE starts
                   5348:       CODElength  - length of the CODE
1.573     bisitz   5349:       IDstart     - column where the student/employee ID starts
1.556     weissno  5350:       IDlength    - length of the student/employee ID info
1.423     albertel 5351:       Qstart      - column where the information from the bubbled
                   5352:                     'questions' start
                   5353:       Qlength     - number of columns comprising a single bubble line from
                   5354:                     the sheet. (usually either 1 or 10)
1.424     albertel 5355:       Qon         - either a single character representing the character used
1.423     albertel 5356:                     to signal a bubble was chosen in the positional setup, or
                   5357:                     the string 'letter' if the letter of the chosen bubble is
                   5358:                     in the final, or 'number' if a number representing the
                   5359:                     chosen bubble is in the file (1->A 0->J)
1.424     albertel 5360:       Qoff        - the character used to represent that a bubble was
                   5361:                     left blank
1.423     albertel 5362:       PaperID     - if the scanning process generates a unique number for each
                   5363:                     sheet scanned the column that this ID number starts in
                   5364:       PaperIDlength - number of columns that comprise the unique ID number
                   5365:                       for the sheet of paper
1.424     albertel 5366:       FirstName   - column that the first name starts in
1.423     albertel 5367:       FirstNameLength - number of columns that the first name spans
                   5368:  
                   5369:       LastName    - column that the last name starts in
                   5370:       LastNameLength - number of columns that the last name spans
                   5371: 
                   5372: =cut
1.422     foxr     5373: 
1.82      albertel 5374: sub get_scantron_config {
                   5375:     my ($which) = @_;
1.518     raeburn  5376:     my @lines = &get_scantronformat_file();
1.82      albertel 5377:     my %config;
1.157     albertel 5378:     #FIXME probably should move to XML it has already gotten a bit much now
1.518     raeburn  5379:     foreach my $line (@lines) {
1.82      albertel 5380: 	my ($name,$descrip)=split(/:/,$line);
                   5381: 	if ($name ne $which ) { next; }
                   5382: 	chomp($line);
                   5383: 	my @config=split(/:/,$line);
                   5384: 	$config{'name'}=$config[0];
                   5385: 	$config{'description'}=$config[1];
                   5386: 	$config{'CODElocation'}=$config[2];
                   5387: 	$config{'CODEstart'}=$config[3];
                   5388: 	$config{'CODElength'}=$config[4];
                   5389: 	$config{'IDstart'}=$config[5];
                   5390: 	$config{'IDlength'}=$config[6];
                   5391: 	$config{'Qstart'}=$config[7];
1.497     foxr     5392:  	$config{'Qlength'}=$config[8];
1.82      albertel 5393: 	$config{'Qoff'}=$config[9];
                   5394: 	$config{'Qon'}=$config[10];
1.157     albertel 5395: 	$config{'PaperID'}=$config[11];
                   5396: 	$config{'PaperIDlength'}=$config[12];
                   5397: 	$config{'FirstName'}=$config[13];
                   5398: 	$config{'FirstNamelength'}=$config[14];
                   5399: 	$config{'LastName'}=$config[15];
                   5400: 	$config{'LastNamelength'}=$config[16];
1.82      albertel 5401: 	last;
                   5402:     }
                   5403:     return %config;
                   5404: }
                   5405: 
1.423     albertel 5406: =pod 
                   5407: 
                   5408: =item username_to_idmap
                   5409: 
1.556     weissno  5410:     creates a hash keyed by student/employee ID with values of the corresponding
1.423     albertel 5411:     student username:domain.
                   5412: 
                   5413:   Arguments:
                   5414: 
                   5415:     $classlist - reference to the class list hash. This is a hash
                   5416:                  keyed by student name:domain  whose elements are references
1.424     albertel 5417:                  to arrays containing various chunks of information
1.423     albertel 5418:                  about the student. (See loncoursedata for more info).
                   5419: 
                   5420:   Returns
                   5421:     %idmap - the constructed hash
                   5422: 
                   5423: =cut
                   5424: 
1.82      albertel 5425: sub username_to_idmap {
                   5426:     my ($classlist)= @_;
                   5427:     my %idmap;
                   5428:     foreach my $student (keys(%$classlist)) {
                   5429: 	$idmap{$classlist->{$student}->[&Apache::loncoursedata::CL_ID]}=
                   5430: 	    $student;
                   5431:     }
                   5432:     return %idmap;
                   5433: }
1.423     albertel 5434: 
                   5435: =pod
                   5436: 
1.424     albertel 5437: =item scantron_fixup_scanline
1.423     albertel 5438: 
                   5439:    Process a requested correction to a scanline.
                   5440: 
                   5441:   Arguments:
                   5442:     $scantron_config   - hash from &get_scantron_config()
                   5443:     $scan_data         - hash of correction information 
                   5444:                           (see &scantron_getfile())
                   5445:     $line              - existing scanline
                   5446:     $whichline         - line number of the passed in scanline
                   5447:     $field             - type of change to process 
                   5448:                          (either 
1.573     bisitz   5449:                           'ID'     -> correct the student/employee ID
1.423     albertel 5450:                           'CODE'   -> correct the CODE
                   5451:                           'answer' -> fixup the submitted answers)
                   5452:     
                   5453:    $args               - hash of additional info,
                   5454:                           - 'ID' 
                   5455:                                'newid' -> studentID to use in replacement
1.424     albertel 5456:                                           of existing one
1.423     albertel 5457:                           - 'CODE' 
                   5458:                                'CODE_ignore_dup' - set to true if duplicates
                   5459:                                                    should be ignored.
                   5460: 	                       'CODE' - is new code or 'use_unfound'
1.424     albertel 5461:                                         if the existing unfound code should
1.423     albertel 5462:                                         be used as is
                   5463:                           - 'answer'
                   5464:                                'response' - new answer or 'none' if blank
                   5465:                                'question' - the bubble line to change
1.503     raeburn  5466:                                'questionnum' - the question identifier,
                   5467:                                                may include subquestion. 
1.423     albertel 5468: 
                   5469:   Returns:
                   5470:     $line - the modified scanline
                   5471: 
                   5472:   Side effects: 
                   5473:     $scan_data - may be updated
                   5474: 
                   5475: =cut
                   5476: 
1.82      albertel 5477: 
1.157     albertel 5478: sub scantron_fixup_scanline {
                   5479:     my ($scantron_config,$scan_data,$line,$whichline,$field,$args)=@_;
                   5480:     if ($field eq 'ID') {
                   5481: 	if (length($args->{'newid'}) > $$scantron_config{'IDlength'}) {
1.186     albertel 5482: 	    return ($line,1,'New value too large');
1.157     albertel 5483: 	}
                   5484: 	if (length($args->{'newid'}) < $$scantron_config{'IDlength'}) {
                   5485: 	    $args->{'newid'}=sprintf('%-'.$$scantron_config{'IDlength'}.'s',
                   5486: 				     $args->{'newid'});
                   5487: 	}
                   5488: 	substr($line,$$scantron_config{'IDstart'}-1,
                   5489: 	       $$scantron_config{'IDlength'})=$args->{'newid'};
                   5490: 	if ($args->{'newid'}=~/^\s*$/) {
                   5491: 	    &scan_data($scan_data,"$whichline.user",
                   5492: 		       $args->{'username'}.':'.$args->{'domain'});
                   5493: 	}
1.186     albertel 5494:     } elsif ($field eq 'CODE') {
1.192     albertel 5495: 	if ($args->{'CODE_ignore_dup'}) {
                   5496: 	    &scan_data($scan_data,"$whichline.CODE_ignore_dup",'1');
                   5497: 	}
                   5498: 	&scan_data($scan_data,"$whichline.useCODE",'1');
                   5499: 	if ($args->{'CODE'} ne 'use_unfound') {
1.191     albertel 5500: 	    if (length($args->{'CODE'}) > $$scantron_config{'CODElength'}) {
                   5501: 		return ($line,1,'New CODE value too large');
                   5502: 	    }
                   5503: 	    if (length($args->{'CODE'}) < $$scantron_config{'CODElength'}) {
                   5504: 		$args->{'CODE'}=sprintf('%-'.$$scantron_config{'CODElength'}.'s',$args->{'CODE'});
                   5505: 	    }
                   5506: 	    substr($line,$$scantron_config{'CODEstart'}-1,
                   5507: 		   $$scantron_config{'CODElength'})=$args->{'CODE'};
1.186     albertel 5508: 	}
1.157     albertel 5509:     } elsif ($field eq 'answer') {
1.497     foxr     5510: 	my $length=$scantron_config->{'Qlength'};
1.157     albertel 5511: 	my $off=$scantron_config->{'Qoff'};
                   5512: 	my $on=$scantron_config->{'Qon'};
1.497     foxr     5513: 	my $answer=${off}x$length;
                   5514: 	if ($args->{'response'} eq 'none') {
                   5515: 	    &scan_data($scan_data,
1.503     raeburn  5516: 		       "$whichline.no_bubble.".$args->{'questionnum'},'1');
1.497     foxr     5517: 	} else {
                   5518: 	    if ($on eq 'letter') {
                   5519: 		my @alphabet=('A'..'Z');
                   5520: 		$answer=$alphabet[$args->{'response'}];
                   5521: 	    } elsif ($on eq 'number') {
                   5522: 		$answer=$args->{'response'}+1;
                   5523: 		if ($answer == 10) { $answer = '0'; }
1.274     albertel 5524: 	    } else {
1.497     foxr     5525: 		substr($answer,$args->{'response'},1)=$on;
1.274     albertel 5526: 	    }
1.497     foxr     5527: 	    &scan_data($scan_data,
1.503     raeburn  5528: 		       "$whichline.no_bubble.".$args->{'questionnum'},undef,'1');
1.157     albertel 5529: 	}
1.497     foxr     5530: 	my $where=$length*($args->{'question'}-1)+$scantron_config->{'Qstart'};
                   5531: 	substr($line,$where-1,$length)=$answer;
1.157     albertel 5532:     }
                   5533:     return $line;
                   5534: }
1.423     albertel 5535: 
                   5536: =pod
                   5537: 
                   5538: =item scan_data
                   5539: 
                   5540:     Edit or look up  an item in the scan_data hash.
                   5541: 
                   5542:   Arguments:
                   5543:     $scan_data  - The hash (see scantron_getfile)
                   5544:     $key        - shorthand of the key to edit (actual key is
1.424     albertel 5545:                   scantronfilename_key).
1.423     albertel 5546:     $data        - New value of the hash entry.
                   5547:     $delete      - If true, the entry is removed from the hash.
                   5548: 
                   5549:   Returns:
                   5550:     The new value of the hash table field (undefined if deleted).
                   5551: 
                   5552: =cut
                   5553: 
                   5554: 
1.157     albertel 5555: sub scan_data {
                   5556:     my ($scan_data,$key,$value,$delete)=@_;
1.257     albertel 5557:     my $filename=$env{'form.scantron_selectfile'};
1.157     albertel 5558:     if (defined($value)) {
                   5559: 	$scan_data->{$filename.'_'.$key} = $value;
                   5560:     }
                   5561:     if ($delete) { delete($scan_data->{$filename.'_'.$key}); }
                   5562:     return $scan_data->{$filename.'_'.$key};
                   5563: }
1.423     albertel 5564: 
1.495     albertel 5565: # ----- These first few routines are general use routines.----
                   5566: 
                   5567: # Return the number of occurences of a pattern in a string.
                   5568: 
                   5569: sub occurence_count {
                   5570:     my ($string, $pattern) = @_;
                   5571: 
                   5572:     my @matches = ($string =~ /$pattern/g);
                   5573: 
                   5574:     return scalar(@matches);
                   5575: }
                   5576: 
                   5577: 
                   5578: # Take a string known to have digits and convert all the
                   5579: # digits into letters in the range J,A..I.
                   5580: 
                   5581: sub digits_to_letters {
                   5582:     my ($input) = @_;
                   5583: 
                   5584:     my @alphabet = ('J', 'A'..'I');
                   5585: 
                   5586:     my @input    = split(//, $input);
                   5587:     my $output ='';
                   5588:     for (my $i = 0; $i < scalar(@input); $i++) {
                   5589: 	if ($input[$i] =~ /\d/) {
                   5590: 	    $output .= $alphabet[$input[$i]];
                   5591: 	} else {
                   5592: 	    $output .= $input[$i];
                   5593: 	}
                   5594:     }
                   5595:     return $output;
                   5596: }
                   5597: 
1.423     albertel 5598: =pod 
                   5599: 
                   5600: =item scantron_parse_scanline
                   5601: 
                   5602:   Decodes a scanline from the selected scantron file
                   5603: 
                   5604:  Arguments:
                   5605:     line             - The text of the scantron file line to process
                   5606:     whichline        - Line number
                   5607:     scantron_config  - Hash describing the format of the scantron lines.
                   5608:     scan_data        - Hash of extra information about the scanline
                   5609:                        (see scantron_getfile for more information)
                   5610:     just_header      - True if should not process question answers but only
                   5611:                        the stuff to the left of the answers.
                   5612:  Returns:
                   5613:    Hash containing the result of parsing the scanline
                   5614: 
                   5615:    Keys are all proceeded by the string 'scantron.'
                   5616: 
                   5617:        CODE    - the CODE in use for this scanline
                   5618:        useCODE - 1 if the CODE is invalid but it usage has been forced
                   5619:                  by the operator
                   5620:        CODE_ignore_dup - 1 if the CODE is a duplicated use when unique
                   5621:                             CODEs were selected, but the usage has been
                   5622:                             forced by the operator
1.556     weissno  5623:        ID  - student/employee ID
1.423     albertel 5624:        PaperID - if used, the ID number printed on the sheet when the 
                   5625:                  paper was scanned
                   5626:        FirstName - first name from the sheet
                   5627:        LastName  - last name from the sheet
                   5628: 
                   5629:      if just_header was not true these key may also exist
                   5630: 
1.447     foxr     5631:        missingerror - a list of bubble ranges that are considered to be answers
                   5632:                       to a single question that don't have any bubbles filled in.
                   5633:                       Of the form questionnumber:firstbubblenumber:count.
                   5634:        doubleerror  - a list of bubble ranges that are considered to be answers
                   5635:                       to a single question that have more than one bubble filled in.
                   5636:                       Of the form questionnumber::firstbubblenumber:count
                   5637:    
                   5638:                 In the above, count is the number of bubble responses in the
                   5639:                 input line needed to represent the possible answers to the question.
                   5640:                 e.g. a radioresponse with 15 choices in an answer sheet with 10 choices
                   5641:                 per line would have count = 2.
                   5642: 
1.423     albertel 5643:        maxquest     - the number of the last bubble line that was parsed
                   5644: 
                   5645:        (<number> starts at 1)
                   5646:        <number>.answer - zero or more letters representing the selected
                   5647:                          letters from the scanline for the bubble line 
                   5648:                          <number>.
                   5649:                          if blank there was either no bubble or there where
                   5650:                          multiple bubbles, (consult the keys missingerror and
                   5651:                          doubleerror if this is an error condition)
                   5652: 
                   5653: =cut
                   5654: 
1.82      albertel 5655: sub scantron_parse_scanline {
1.423     albertel 5656:     my ($line,$whichline,$scantron_config,$scan_data,$just_header)=@_;
1.470     foxr     5657: 
1.82      albertel 5658:     my %record;
1.550     raeburn  5659:     my $lastpos = $env{'form.scantron_maxbubble'}*$$scantron_config{'Qlength'};
                   5660:     my $questions=substr($line,$$scantron_config{'Qstart'}-1,$lastpos);  # Answers
1.422     foxr     5661:     my $data=substr($line,0,$$scantron_config{'Qstart'}-1);     # earlier stuff
1.278     albertel 5662:     if (!($$scantron_config{'CODElocation'} eq 0 ||
                   5663: 	  $$scantron_config{'CODElocation'} eq 'none')) {
                   5664: 	if ($$scantron_config{'CODElocation'} < 0 ||
                   5665: 	    $$scantron_config{'CODElocation'} eq 'letter' ||
                   5666: 	    $$scantron_config{'CODElocation'} eq 'number') {
1.191     albertel 5667: 	    $record{'scantron.CODE'}=substr($data,
                   5668: 					    $$scantron_config{'CODEstart'}-1,
1.83      albertel 5669: 					    $$scantron_config{'CODElength'});
1.191     albertel 5670: 	    if (&scan_data($scan_data,"$whichline.useCODE")) {
                   5671: 		$record{'scantron.useCODE'}=1;
                   5672: 	    }
1.192     albertel 5673: 	    if (&scan_data($scan_data,"$whichline.CODE_ignore_dup")) {
                   5674: 		$record{'scantron.CODE_ignore_dup'}=1;
                   5675: 	    }
1.82      albertel 5676: 	} else {
                   5677: 	    #FIXME interpret first N questions
                   5678: 	}
                   5679:     }
1.83      albertel 5680:     $record{'scantron.ID'}=substr($data,$$scantron_config{'IDstart'}-1,
                   5681: 				  $$scantron_config{'IDlength'});
1.157     albertel 5682:     $record{'scantron.PaperID'}=
                   5683: 	substr($data,$$scantron_config{'PaperID'}-1,
                   5684: 	       $$scantron_config{'PaperIDlength'});
                   5685:     $record{'scantron.FirstName'}=
                   5686: 	substr($data,$$scantron_config{'FirstName'}-1,
                   5687: 	       $$scantron_config{'FirstNamelength'});
                   5688:     $record{'scantron.LastName'}=
                   5689: 	substr($data,$$scantron_config{'LastName'}-1,
                   5690: 	       $$scantron_config{'LastNamelength'});
1.423     albertel 5691:     if ($just_header) { return \%record; }
1.194     albertel 5692: 
1.82      albertel 5693:     my @alphabet=('A'..'Z');
                   5694:     my $questnum=0;
1.447     foxr     5695:     my $ansnum  =1;		# Multiple 'answer lines'/question.
                   5696: 
1.470     foxr     5697:     chomp($questions);		# Get rid of any trailing \n.
                   5698:     $questions =~ s/\r$//;      # Get rid of trailing \r too (MAC or Win uploads).
                   5699:     while (length($questions)) {
1.447     foxr     5700: 	my $answers_needed = $bubble_lines_per_response{$questnum};
1.503     raeburn  5701:         my $answer_length  = ($$scantron_config{'Qlength'} * $answers_needed)
                   5702:                              || 1;
                   5703:         $questnum++;
                   5704:         my $quest_id = $questnum;
                   5705:         my $currentquest = substr($questions,0,$answer_length);
                   5706:         $questions       = substr($questions,$answer_length);
                   5707:         if (length($currentquest) < $answer_length) { next; }
                   5708: 
                   5709:         if ($subdivided_bubble_lines{$questnum-1} =~ /,/) {
                   5710:             my $subquestnum = 1;
                   5711:             my $subquestions = $currentquest;
                   5712:             my @subanswers_needed = 
                   5713:                 split(/,/,$subdivided_bubble_lines{$questnum-1});  
                   5714:             foreach my $subans (@subanswers_needed) {
                   5715:                 my $subans_length =
                   5716:                     ($$scantron_config{'Qlength'} * $subans)  || 1;
                   5717:                 my $currsubquest = substr($subquestions,0,$subans_length);
                   5718:                 $subquestions   = substr($subquestions,$subans_length);
                   5719:                 $quest_id = "$questnum.$subquestnum";
                   5720:                 if (($$scantron_config{'Qon'} eq 'letter') ||
                   5721:                     ($$scantron_config{'Qon'} eq 'number')) {
                   5722:                     $ansnum = &scantron_validator_lettnum($ansnum, 
                   5723:                         $questnum,$quest_id,$subans,$currsubquest,$whichline,
                   5724:                         \@alphabet,\%record,$scantron_config,$scan_data);
                   5725:                 } else {
                   5726:                     $ansnum = &scantron_validator_positional($ansnum,
                   5727:                         $questnum,$quest_id,$subans,$currsubquest,$whichline,                        \@alphabet,\%record,$scantron_config,$scan_data);
                   5728:                 }
                   5729:                 $subquestnum ++;
                   5730:             }
                   5731:         } else {
                   5732:             if (($$scantron_config{'Qon'} eq 'letter') ||
                   5733:                 ($$scantron_config{'Qon'} eq 'number')) {
                   5734:                 $ansnum = &scantron_validator_lettnum($ansnum,$questnum,
                   5735:                     $quest_id,$answers_needed,$currentquest,$whichline,
                   5736:                     \@alphabet,\%record,$scantron_config,$scan_data);
                   5737:             } else {
                   5738:                 $ansnum = &scantron_validator_positional($ansnum,$questnum,
                   5739:                     $quest_id,$answers_needed,$currentquest,$whichline,
                   5740:                     \@alphabet,\%record,$scantron_config,$scan_data);
                   5741:             }
                   5742:         }
                   5743:     }
                   5744:     $record{'scantron.maxquest'}=$questnum;
                   5745:     return \%record;
                   5746: }
1.447     foxr     5747: 
1.503     raeburn  5748: sub scantron_validator_lettnum {
                   5749:     my ($ansnum,$questnum,$quest_id,$answers_needed,$currquest,$whichline,
                   5750:         $alphabet,$record,$scantron_config,$scan_data) = @_;
                   5751: 
                   5752:     # Qon 'letter' implies for each slot in currquest we have:
                   5753:     #    ? or * for doubles, a letter in A-Z for a bubble, and
                   5754:     #    about anything else (esp. a value of Qoff) for missing
                   5755:     #    bubbles.
                   5756:     #
                   5757:     # Qon 'number' implies each slot gives a digit that indexes the
                   5758:     #    bubbles filled, or Qoff, or a non-number for unbubbled lines,
                   5759:     #    and * or ? for double bubbles on a single line.
                   5760:     #
1.447     foxr     5761: 
1.503     raeburn  5762:     my $matchon;
                   5763:     if ($$scantron_config{'Qon'} eq 'letter') {
                   5764:         $matchon = '[A-Z]';
                   5765:     } elsif ($$scantron_config{'Qon'} eq 'number') {
                   5766:         $matchon = '\d';
                   5767:     }
                   5768:     my $occurrences = 0;
                   5769:     if (($responsetype_per_response{$questnum-1} eq 'essayresponse') ||
                   5770:         ($responsetype_per_response{$questnum-1} eq 'formularesponse') ||
1.510     raeburn  5771:         ($responsetype_per_response{$questnum-1} eq 'stringresponse') ||
                   5772:         ($responsetype_per_response{$questnum-1} eq 'imageresponse') ||
                   5773:         ($responsetype_per_response{$questnum-1} eq 'reactionresponse') ||
                   5774:         ($responsetype_per_response{$questnum-1} eq 'organicresponse')) {
1.503     raeburn  5775:         my @singlelines = split('',$currquest);
                   5776:         foreach my $entry (@singlelines) {
                   5777:             $occurrences = &occurence_count($entry,$matchon);
                   5778:             if ($occurrences > 1) {
                   5779:                 last;
                   5780:             }
                   5781:         } 
                   5782:     } else {
                   5783:         $occurrences = &occurence_count($currquest,$matchon); 
                   5784:     }
                   5785:     if (($currquest =~ /\?/ || $currquest =~ /\*/) || ($occurrences > 1)) {
                   5786:         push(@{$record->{'scantron.doubleerror'}},$quest_id);
                   5787:         for (my $ans=0; $ans<$answers_needed; $ans++) {
                   5788:             my $bubble = substr($currquest,$ans,1);
                   5789:             if ($bubble =~ /$matchon/ ) {
                   5790:                 if ($$scantron_config{'Qon'} eq 'number') {
                   5791:                     if ($bubble == 0) {
                   5792:                         $bubble = 10; 
                   5793:                     }
                   5794:                     $record->{"scantron.$ansnum.answer"} = 
                   5795:                         $alphabet->[$bubble-1];
                   5796:                 } else {
                   5797:                     $record->{"scantron.$ansnum.answer"} = $bubble;
                   5798:                 }
                   5799:             } else {
                   5800:                 $record->{"scantron.$ansnum.answer"}='';
                   5801:             }
                   5802:             $ansnum++;
                   5803:         }
                   5804:     } elsif (!defined($currquest)
                   5805:             || (&occurence_count($currquest, $$scantron_config{'Qoff'}) == length($currquest))
                   5806:             || (&occurence_count($currquest,$matchon) == 0)) {
                   5807:         for (my $ans=0; $ans<$answers_needed; $ans++ ) {
                   5808:             $record->{"scantron.$ansnum.answer"}='';
                   5809:             $ansnum++;
                   5810:         }
                   5811:         if (!&scan_data($scan_data,"$whichline.no_bubble.$quest_id")) {
                   5812:             push(@{$record->{'scantron.missingerror'}},$quest_id);
                   5813:         }
                   5814:     } else {
                   5815:         if ($$scantron_config{'Qon'} eq 'number') {
                   5816:             $currquest = &digits_to_letters($currquest);            
                   5817:         }
                   5818:         for (my $ans=0; $ans<$answers_needed; $ans++) {
                   5819:             my $bubble = substr($currquest,$ans,1);
                   5820:             $record->{"scantron.$ansnum.answer"} = $bubble;
                   5821:             $ansnum++;
                   5822:         }
                   5823:     }
                   5824:     return $ansnum;
                   5825: }
1.447     foxr     5826: 
1.503     raeburn  5827: sub scantron_validator_positional {
                   5828:     my ($ansnum,$questnum,$quest_id,$answers_needed,$currquest,
                   5829:         $whichline,$alphabet,$record,$scantron_config,$scan_data) = @_;
1.447     foxr     5830: 
1.503     raeburn  5831:     # Otherwise there's a positional notation;
                   5832:     # each bubble line requires Qlength items, and there are filled in
                   5833:     # bubbles for each case where there 'Qon' characters.
                   5834:     #
1.447     foxr     5835: 
1.503     raeburn  5836:     my @array=split($$scantron_config{'Qon'},$currquest,-1);
1.447     foxr     5837: 
1.503     raeburn  5838:     # If the split only gives us one element.. the full length of the
                   5839:     # answer string, no bubbles are filled in:
1.447     foxr     5840: 
1.507     raeburn  5841:     if ($answers_needed eq '') {
                   5842:         return;
                   5843:     }
                   5844: 
1.503     raeburn  5845:     if (length($array[0]) eq $$scantron_config{'Qlength'}*$answers_needed) {
                   5846:         for (my $ans=0; $ans<$answers_needed; $ans++ ) {
                   5847:             $record->{"scantron.$ansnum.answer"}='';
                   5848:             $ansnum++;
                   5849:         }
                   5850:         if (!&scan_data($scan_data,"$whichline.no_bubble.$quest_id")) {
                   5851:             push(@{$record->{"scantron.missingerror"}},$quest_id);
                   5852:         }
                   5853:     } elsif (scalar(@array) == 2) {
                   5854:         my $location = length($array[0]);
                   5855:         my $line_num = int($location / $$scantron_config{'Qlength'});
                   5856:         my $bubble   = $alphabet->[$location % $$scantron_config{'Qlength'}];
                   5857:         for (my $ans=0; $ans<$answers_needed; $ans++) {
                   5858:             if ($ans eq $line_num) {
                   5859:                 $record->{"scantron.$ansnum.answer"} = $bubble;
                   5860:             } else {
                   5861:                 $record->{"scantron.$ansnum.answer"} = ' ';
                   5862:             }
                   5863:             $ansnum++;
                   5864:          }
                   5865:     } else {
                   5866:         #  If there's more than one instance of a bubble character
                   5867:         #  That's a double bubble; with positional notation we can
                   5868:         #  record all the bubbles filled in as well as the
                   5869:         #  fact this response consists of multiple bubbles.
                   5870:         #
                   5871:         if (($responsetype_per_response{$questnum-1} eq 'essayresponse') ||
                   5872:             ($responsetype_per_response{$questnum-1} eq 'formularesponse') ||
1.510     raeburn  5873:             ($responsetype_per_response{$questnum-1} eq 'stringresponse') ||
                   5874:             ($responsetype_per_response{$questnum-1} eq 'imageresponse') ||
                   5875:             ($responsetype_per_response{$questnum-1} eq 'reactionresponse') ||
                   5876:             ($responsetype_per_response{$questnum-1} eq 'organicresponse')) {
1.503     raeburn  5877:             my $doubleerror = 0;
                   5878:             while (($currquest >= $$scantron_config{'Qlength'}) && 
                   5879:                    (!$doubleerror)) {
                   5880:                my $currline = substr($currquest,0,$$scantron_config{'Qlength'});
                   5881:                $currquest = substr($currquest,$$scantron_config{'Qlength'});
                   5882:                my @currarray = split($$scantron_config{'Qon'},$currline,-1);
                   5883:                if (length(@currarray) > 2) {
                   5884:                    $doubleerror = 1;
                   5885:                } 
                   5886:             }
                   5887:             if ($doubleerror) {
                   5888:                 push(@{$record->{'scantron.doubleerror'}},$quest_id);
                   5889:             }
                   5890:         } else {
                   5891:             push(@{$record->{'scantron.doubleerror'}},$quest_id);
                   5892:         }
                   5893:         my $item = $ansnum;
                   5894:         for (my $ans=0; $ans<$answers_needed; $ans++) {
                   5895:             $record->{"scantron.$item.answer"} = '';
                   5896:             $item ++;
                   5897:         }
1.447     foxr     5898: 
1.503     raeburn  5899:         my @ans=@array;
                   5900:         my $i=0;
                   5901:         my $increment = 0;
                   5902:         while ($#ans) {
                   5903:             $i+=length($ans[0]) + $increment;
                   5904:             my $line   = int($i/$$scantron_config{'Qlength'} + $ansnum);
                   5905:             my $bubble = $i%$$scantron_config{'Qlength'};
                   5906:             $record->{"scantron.$line.answer"}.=$alphabet->[$bubble];
                   5907:             shift(@ans);
                   5908:             $increment = 1;
                   5909:         }
                   5910:         $ansnum += $answers_needed;
1.82      albertel 5911:     }
1.503     raeburn  5912:     return $ansnum;
1.82      albertel 5913: }
                   5914: 
1.423     albertel 5915: =pod
                   5916: 
                   5917: =item scantron_add_delay
                   5918: 
                   5919:    Adds an error message that occurred during the grading phase to a
                   5920:    queue of messages to be shown after grading pass is complete
                   5921: 
                   5922:  Arguments:
1.424     albertel 5923:    $delayqueue  - arrary ref of hash ref of error messages
1.423     albertel 5924:    $scanline    - the scanline that caused the error
                   5925:    $errormesage - the error message
                   5926:    $errorcode   - a numeric code for the error
                   5927: 
                   5928:  Side Effects:
1.424     albertel 5929:    updates the $delayqueue to have a new hash ref of the error
1.423     albertel 5930: 
                   5931: =cut
                   5932: 
1.82      albertel 5933: sub scantron_add_delay {
1.140     albertel 5934:     my ($delayqueue,$scanline,$errormessage,$errorcode)=@_;
                   5935:     push(@$delayqueue,
                   5936: 	 {'line' => $scanline, 'emsg' => $errormessage,
                   5937: 	  'ecode' => $errorcode }
                   5938: 	 );
1.82      albertel 5939: }
                   5940: 
1.423     albertel 5941: =pod
                   5942: 
                   5943: =item scantron_find_student
                   5944: 
1.424     albertel 5945:    Finds the username for the current scanline
                   5946: 
                   5947:   Arguments:
                   5948:    $scantron_record - hash result from scantron_parse_scanline
                   5949:    $scan_data       - hash of correction information 
                   5950:                       (see &scantron_getfile() form more information)
                   5951:    $idmap           - hash from &username_to_idmap()
                   5952:    $line            - number of current scanline
                   5953:  
                   5954:   Returns:
                   5955:    Either 'username:domain' or undef if unknown
                   5956: 
1.423     albertel 5957: =cut
                   5958: 
1.82      albertel 5959: sub scantron_find_student {
1.157     albertel 5960:     my ($scantron_record,$scan_data,$idmap,$line)=@_;
1.83      albertel 5961:     my $scanID=$$scantron_record{'scantron.ID'};
1.157     albertel 5962:     if ($scanID =~ /^\s*$/) {
                   5963:  	return &scan_data($scan_data,"$line.user");
                   5964:     }
1.83      albertel 5965:     foreach my $id (keys(%$idmap)) {
1.157     albertel 5966:  	if (lc($id) eq lc($scanID)) {
                   5967:  	    return $$idmap{$id};
                   5968:  	}
1.83      albertel 5969:     }
                   5970:     return undef;
                   5971: }
                   5972: 
1.423     albertel 5973: =pod
                   5974: 
                   5975: =item scantron_filter
                   5976: 
1.424     albertel 5977:    Filter sub for lonnavmaps, filters out hidden resources if ignore
                   5978:    hidden resources was selected
                   5979: 
1.423     albertel 5980: =cut
                   5981: 
1.83      albertel 5982: sub scantron_filter {
                   5983:     my ($curres)=@_;
1.331     albertel 5984: 
                   5985:     if (ref($curres) && $curres->is_problem()) {
                   5986: 	# if the user has asked to not have either hidden
                   5987: 	# or 'randomout' controlled resources to be graded
                   5988: 	# don't include them
                   5989: 	if ($env{'form.scantron_options_hidden'} eq 'ignore_hidden'
                   5990: 	    && $curres->randomout) {
                   5991: 	    return 0;
                   5992: 	}
1.83      albertel 5993: 	return 1;
                   5994:     }
                   5995:     return 0;
1.82      albertel 5996: }
                   5997: 
1.423     albertel 5998: =pod
                   5999: 
                   6000: =item scantron_process_corrections
                   6001: 
1.424     albertel 6002:    Gets correction information out of submitted form data and corrects
                   6003:    the scanline
                   6004: 
1.423     albertel 6005: =cut
                   6006: 
1.157     albertel 6007: sub scantron_process_corrections {
                   6008:     my ($r) = @_;
1.257     albertel 6009:     my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
1.157     albertel 6010:     my ($scanlines,$scan_data)=&scantron_getfile();
                   6011:     my $classlist=&Apache::loncoursedata::get_classlist();
1.257     albertel 6012:     my $which=$env{'form.scantron_line'};
1.200     albertel 6013:     my $line=&scantron_get_line($scanlines,$scan_data,$which);
1.157     albertel 6014:     my ($skip,$err,$errmsg);
1.257     albertel 6015:     if ($env{'form.scantron_skip_record'}) {
1.157     albertel 6016: 	$skip=1;
1.257     albertel 6017:     } elsif ($env{'form.scantron_corrections'} =~ /^(duplicate|incorrect)ID$/) {
                   6018: 	my $newstudent=$env{'form.scantron_username'}.':'.
                   6019: 	    $env{'form.scantron_domain'};
1.157     albertel 6020: 	my $newid=$classlist->{$newstudent}->[&Apache::loncoursedata::CL_ID];
                   6021: 	($line,$err,$errmsg)=
                   6022: 	    &scantron_fixup_scanline(\%scantron_config,$scan_data,$line,$which,
                   6023: 				     'ID',{'newid'=>$newid,
1.257     albertel 6024: 				    'username'=>$env{'form.scantron_username'},
                   6025: 				    'domain'=>$env{'form.scantron_domain'}});
                   6026:     } elsif ($env{'form.scantron_corrections'} =~ /^(duplicate|incorrect)CODE$/) {
                   6027: 	my $resolution=$env{'form.scantron_CODE_resolution'};
1.190     albertel 6028: 	my $newCODE;
1.192     albertel 6029: 	my %args;
1.190     albertel 6030: 	if      ($resolution eq 'use_unfound') {
1.191     albertel 6031: 	    $newCODE='use_unfound';
1.190     albertel 6032: 	} elsif ($resolution eq 'use_found') {
1.257     albertel 6033: 	    $newCODE=$env{'form.scantron_CODE_selectedvalue'};
1.190     albertel 6034: 	} elsif ($resolution eq 'use_typed') {
1.257     albertel 6035: 	    $newCODE=$env{'form.scantron_CODE_newvalue'};
1.194     albertel 6036: 	} elsif ($resolution =~ /^use_closest_(\d+)/) {
1.257     albertel 6037: 	    $newCODE=$env{"form.scantron_CODE_closest_$1"};
1.190     albertel 6038: 	}
1.257     albertel 6039: 	if ($env{'form.scantron_corrections'} eq 'duplicateCODE') {
1.192     albertel 6040: 	    $args{'CODE_ignore_dup'}=1;
                   6041: 	}
                   6042: 	$args{'CODE'}=$newCODE;
1.186     albertel 6043: 	($line,$err,$errmsg)=
                   6044: 	    &scantron_fixup_scanline(\%scantron_config,$scan_data,$line,$which,
1.192     albertel 6045: 				     'CODE',\%args);
1.257     albertel 6046:     } elsif ($env{'form.scantron_corrections'} =~ /^(missing|double)bubble$/) {
                   6047: 	foreach my $question (split(',',$env{'form.scantron_questions'})) {
1.157     albertel 6048: 	    ($line,$err,$errmsg)=
                   6049: 		&scantron_fixup_scanline(\%scantron_config,$scan_data,$line,
                   6050: 					 $which,'answer',
                   6051: 					 { 'question'=>$question,
1.503     raeburn  6052: 		      		   'response'=>$env{"form.scantron_correct_Q_$question"},
                   6053:                                    'questionnum'=>$env{"form.scantron_questionnum_Q_$question"}});
1.157     albertel 6054: 	    if ($err) { last; }
                   6055: 	}
                   6056:     }
                   6057:     if ($err) {
1.398     albertel 6058: 	$r->print("<span class=\"LC_warning\">Unable to accept last correction, an error occurred :$errmsg:</span>");
1.157     albertel 6059:     } else {
1.200     albertel 6060: 	&scantron_put_line($scanlines,$scan_data,$which,$line,$skip);
1.157     albertel 6061: 	&scantron_putfile($scanlines,$scan_data);
                   6062:     }
                   6063: }
                   6064: 
1.423     albertel 6065: =pod
                   6066: 
                   6067: =item reset_skipping_status
                   6068: 
1.424     albertel 6069:    Forgets the current set of remember skipped scanlines (and thus
                   6070:    reverts back to considering all lines in the
                   6071:    scantron_skipped_<filename> file)
                   6072: 
1.423     albertel 6073: =cut
                   6074: 
1.200     albertel 6075: sub reset_skipping_status {
                   6076:     my ($scanlines,$scan_data)=&scantron_getfile();
                   6077:     &scan_data($scan_data,'remember_skipping',undef,1);
                   6078:     &scantron_putfile(undef,$scan_data);
                   6079: }
                   6080: 
1.423     albertel 6081: =pod
                   6082: 
                   6083: =item start_skipping
                   6084: 
1.424     albertel 6085:    Marks a scanline to be skipped. 
                   6086: 
1.423     albertel 6087: =cut
                   6088: 
1.376     albertel 6089: sub start_skipping {
1.200     albertel 6090:     my ($scan_data,$i)=@_;
                   6091:     my %remembered=split(':',&scan_data($scan_data,'remember_skipping'));
1.376     albertel 6092:     if ($env{'form.scantron_options_redo'} =~ /^redo_/) {
                   6093: 	$remembered{$i}=2;
                   6094:     } else {
                   6095: 	$remembered{$i}=1;
                   6096:     }
1.200     albertel 6097:     &scan_data($scan_data,'remember_skipping',join(':',%remembered));
                   6098: }
                   6099: 
1.423     albertel 6100: =pod
                   6101: 
                   6102: =item should_be_skipped
                   6103: 
1.424     albertel 6104:    Checks whether a scanline should be skipped.
                   6105: 
1.423     albertel 6106: =cut
                   6107: 
1.200     albertel 6108: sub should_be_skipped {
1.376     albertel 6109:     my ($scanlines,$scan_data,$i)=@_;
1.257     albertel 6110:     if ($env{'form.scantron_options_redo'} !~ /^redo_/) {
1.200     albertel 6111: 	# not redoing old skips
1.376     albertel 6112: 	if ($scanlines->{'skipped'}[$i]) { return 1; }
1.200     albertel 6113: 	return 0;
                   6114:     }
                   6115:     my %remembered=split(':',&scan_data($scan_data,'remember_skipping'));
1.376     albertel 6116: 
                   6117:     if (exists($remembered{$i}) && $remembered{$i} != 2 ) {
                   6118: 	return 0;
                   6119:     }
1.200     albertel 6120:     return 1;
                   6121: }
                   6122: 
1.423     albertel 6123: =pod
                   6124: 
                   6125: =item remember_current_skipped
                   6126: 
1.424     albertel 6127:    Discovers what scanlines are in the scantron_skipped_<filename>
                   6128:    file and remembers them into scan_data for later use.
                   6129: 
1.423     albertel 6130: =cut
                   6131: 
1.200     albertel 6132: sub remember_current_skipped {
                   6133:     my ($scanlines,$scan_data)=&scantron_getfile();
                   6134:     my %to_remember;
                   6135:     for (my $i=0;$i<=$scanlines->{'count'};$i++) {
                   6136: 	if ($scanlines->{'skipped'}[$i]) {
                   6137: 	    $to_remember{$i}=1;
                   6138: 	}
                   6139:     }
1.376     albertel 6140: 
1.200     albertel 6141:     &scan_data($scan_data,'remember_skipping',join(':',%to_remember));
                   6142:     &scantron_putfile(undef,$scan_data);
                   6143: }
                   6144: 
1.423     albertel 6145: =pod
                   6146: 
                   6147: =item check_for_error
                   6148: 
1.424     albertel 6149:     Checks if there was an error when attempting to remove a specific
                   6150:     scantron_.. bubble sheet data file. Prints out an error if
                   6151:     something went wrong.
                   6152: 
1.423     albertel 6153: =cut
                   6154: 
1.200     albertel 6155: sub check_for_error {
                   6156:     my ($r,$result)=@_;
                   6157:     if ($result ne 'ok' && $result ne 'not_found' ) {
1.492     albertel 6158: 	$r->print(&mt("An error occurred ([_1]) when trying to remove the existing corrections.",$result));
1.200     albertel 6159:     }
                   6160: }
1.157     albertel 6161: 
1.423     albertel 6162: =pod
                   6163: 
                   6164: =item scantron_warning_screen
                   6165: 
1.424     albertel 6166:    Interstitial screen to make sure the operator has selected the
                   6167:    correct options before we start the validation phase.
                   6168: 
1.423     albertel 6169: =cut
                   6170: 
1.203     albertel 6171: sub scantron_warning_screen {
                   6172:     my ($button_text)=@_;
1.257     albertel 6173:     my $title=&Apache::lonnet::gettitle($env{'form.selectpage'});
1.284     albertel 6174:     my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
1.373     albertel 6175:     my $CODElist;
1.284     albertel 6176:     if ($scantron_config{'CODElocation'} &&
                   6177: 	$scantron_config{'CODEstart'} &&
                   6178: 	$scantron_config{'CODElength'}) {
                   6179: 	$CODElist=$env{'form.scantron_CODElist'};
1.398     albertel 6180: 	if ($env{'form.scantron_CODElist'} eq '') { $CODElist='<span class="LC_warning">None</span>'; }
1.284     albertel 6181: 	$CODElist=
1.492     albertel 6182: 	    '<tr><td><b>'.&mt('List of CODES to validate against:').'</b></td><td><tt>'.
1.373     albertel 6183: 	    $env{'form.scantron_CODElist'}.'</tt></td></tr>';
1.284     albertel 6184:     }
1.492     albertel 6185:     return ('
1.203     albertel 6186: <p>
1.492     albertel 6187: <span class="LC_warning">
                   6188: '.&mt('Please double check the information below before clicking on \'[_1]\'',&mt($button_text)).'</span>
1.203     albertel 6189: </p>
                   6190: <table>
1.492     albertel 6191: <tr><td><b>'.&mt('Sequence to be Graded:').'</b></td><td>'.$title.'</td></tr>
                   6192: <tr><td><b>'.&mt('Data File that will be used:').'</b></td><td><tt>'.$env{'form.scantron_selectfile'}.'</tt></td></tr>
                   6193: '.$CODElist.'
1.203     albertel 6194: </table>
                   6195: <br />
1.492     albertel 6196: <p> '.&mt('If this information is correct, please click on \'[_1]\'.',&mt($button_text)).'</p>
                   6197: <p> '.&mt('If something is incorrect, please click the \'Grading Menu\' button to start over.').'</p>
1.203     albertel 6198: 
                   6199: <br />
1.492     albertel 6200: ');
1.203     albertel 6201: }
                   6202: 
1.423     albertel 6203: =pod
                   6204: 
                   6205: =item scantron_do_warning
                   6206: 
1.424     albertel 6207:    Check if the operator has picked something for all required
                   6208:    fields. Error out if something is missing.
                   6209: 
1.423     albertel 6210: =cut
                   6211: 
1.203     albertel 6212: sub scantron_do_warning {
1.608     www      6213:     my ($r,$symb)=@_;
1.203     albertel 6214:     if (!$symb) {return '';}
1.324     albertel 6215:     my $default_form_data=&defaultFormData($symb);
1.203     albertel 6216:     $r->print(&scantron_form_start().$default_form_data);
1.257     albertel 6217:     if ( $env{'form.selectpage'} eq '' ||
                   6218: 	 $env{'form.scantron_selectfile'} eq '' ||
                   6219: 	 $env{'form.scantron_format'} eq '' ) {
1.492     albertel 6220: 	$r->print("<p>".&mt('You have forgetten to specify some information. Please go Back and try again.')."</p>");
1.257     albertel 6221: 	if ( $env{'form.selectpage'} eq '') {
1.492     albertel 6222: 	    $r->print('<p><span class="LC_error">'.&mt('You have not selected a Sequence to grade').'</span></p>');
1.237     albertel 6223: 	} 
1.257     albertel 6224: 	if ( $env{'form.scantron_selectfile'} eq '') {
1.492     albertel 6225: 	    $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 6226: 	} 
1.257     albertel 6227: 	if ( $env{'form.scantron_format'} eq '') {
1.492     albertel 6228: 	    $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 6229: 	} 
                   6230:     } else {
1.265     www      6231: 	my $warning=&scantron_warning_screen('Grading: Validate Records');
1.492     albertel 6232: 	$r->print('
                   6233: '.$warning.'
                   6234: <input type="submit" name="submit" value="'.&mt('Grading: Validate Records').'" />
1.203     albertel 6235: <input type="hidden" name="command" value="scantron_validate" />
1.492     albertel 6236: ');
1.237     albertel 6237:     }
1.352     albertel 6238:     $r->print("</form><br />".&show_grading_menu_form($symb));
1.203     albertel 6239:     return '';
                   6240: }
                   6241: 
1.423     albertel 6242: =pod
                   6243: 
                   6244: =item scantron_form_start
                   6245: 
1.424     albertel 6246:     html hidden input for remembering all selected grading options
                   6247: 
1.423     albertel 6248: =cut
                   6249: 
1.203     albertel 6250: sub scantron_form_start {
                   6251:     my ($max_bubble)=@_;
                   6252:     my $result= <<SCANTRONFORM;
                   6253: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="scantronupload">
1.257     albertel 6254:   <input type="hidden" name="selectpage" value="$env{'form.selectpage'}" />
                   6255:   <input type="hidden" name="scantron_format" value="$env{'form.scantron_format'}" />
                   6256:   <input type="hidden" name="scantron_selectfile" value="$env{'form.scantron_selectfile'}" />
1.218     albertel 6257:   <input type="hidden" name="scantron_maxbubble" value="$max_bubble" />
1.257     albertel 6258:   <input type="hidden" name="scantron_CODElist" value="$env{'form.scantron_CODElist'}" />
                   6259:   <input type="hidden" name="scantron_CODEunique" value="$env{'form.scantron_CODEunique'}" />
                   6260:   <input type="hidden" name="scantron_options_redo" value="$env{'form.scantron_options_redo'}" />
                   6261:   <input type="hidden" name="scantron_options_ignore" value="$env{'form.scantron_options_ignore'}" />
1.331     albertel 6262:   <input type="hidden" name="scantron_options_hidden" value="$env{'form.scantron_options_hidden'}" />
1.203     albertel 6263: SCANTRONFORM
1.447     foxr     6264: 
                   6265:   my $line = 0;
                   6266:     while (defined($env{"form.scantron.bubblelines.$line"})) {
                   6267:        my $chunk =
                   6268: 	   '<input type="hidden" name="scantron.bubblelines.'.$line.'" value="'.$env{"form.scantron.bubblelines.$line"}.'" />'."\n";
1.448     foxr     6269:        $chunk .=
                   6270: 	   '<input type="hidden" name="scantron.first_bubble_line.'.$line.'" value="'.$env{"form.scantron.first_bubble_line.$line"}.'" />'."\n";
1.503     raeburn  6271:        $chunk .= 
                   6272:            '<input type="hidden" name="scantron.sub_bubblelines.'.$line.'" value="'.$env{"form.scantron.sub_bubblelines.$line"}.'" />'."\n";
1.504     raeburn  6273:        $chunk .=
                   6274:            '<input type="hidden" name="scantron.responsetype.'.$line.'" value="'.$env{"form.scantron.responsetype.$line"}.'" />'."\n";
1.447     foxr     6275:        $result .= $chunk;
                   6276:        $line++;
                   6277:    }
1.203     albertel 6278:     return $result;
                   6279: }
                   6280: 
1.423     albertel 6281: =pod
                   6282: 
                   6283: =item scantron_validate_file
                   6284: 
1.424     albertel 6285:     Dispatch routine for doing validation of a bubble sheet data file.
                   6286: 
                   6287:     Also processes any necessary information resets that need to
                   6288:     occur before validation begins (ignore previous corrections,
                   6289:     restarting the skipped records processing)
                   6290: 
1.423     albertel 6291: =cut
                   6292: 
1.157     albertel 6293: sub scantron_validate_file {
1.608     www      6294:     my ($r,$symb) = @_;
1.157     albertel 6295:     if (!$symb) {return '';}
1.324     albertel 6296:     my $default_form_data=&defaultFormData($symb);
1.200     albertel 6297:     
                   6298:     # do the detection of only doing skipped records first befroe we delete
1.424     albertel 6299:     # them when doing the corrections reset
1.257     albertel 6300:     if ($env{'form.scantron_options_redo'} ne 'redo_skipped_ready') {
1.200     albertel 6301: 	&reset_skipping_status();
                   6302:     }
1.257     albertel 6303:     if ($env{'form.scantron_options_redo'} eq 'redo_skipped') {
1.200     albertel 6304: 	&remember_current_skipped();
1.257     albertel 6305: 	$env{'form.scantron_options_redo'}='redo_skipped_ready';
1.200     albertel 6306:     }
                   6307: 
1.257     albertel 6308:     if ($env{'form.scantron_options_ignore'} eq 'ignore_corrections') {
1.200     albertel 6309: 	&check_for_error($r,&scantron_remove_file('corrected'));
                   6310: 	&check_for_error($r,&scantron_remove_file('skipped'));
                   6311: 	&check_for_error($r,&scantron_remove_scan_data());
1.257     albertel 6312: 	$env{'form.scantron_options_ignore'}='done';
1.192     albertel 6313:     }
1.200     albertel 6314: 
1.257     albertel 6315:     if ($env{'form.scantron_corrections'}) {
1.157     albertel 6316: 	&scantron_process_corrections($r);
                   6317:     }
1.503     raeburn  6318:     $r->print('<p>'.&mt('Gathering necessary information.').'</p>');$r->rflush();
1.157     albertel 6319:     #get the student pick code ready
                   6320:     $r->print(&Apache::loncommon::studentbrowser_javascript());
1.582     raeburn  6321:     my $nav_error;
                   6322:     my $max_bubble=&scantron_get_maxbubble(\$nav_error);
                   6323:     if ($nav_error) {
                   6324:         $r->print(&navmap_errormsg());
                   6325:         return '';
                   6326:     }
1.203     albertel 6327:     my $result=&scantron_form_start($max_bubble).$default_form_data;
1.157     albertel 6328:     $r->print($result);
                   6329:     
1.334     albertel 6330:     my @validate_phases=( 'sequence',
                   6331: 			  'ID',
1.157     albertel 6332: 			  'CODE',
                   6333: 			  'doublebubble',
                   6334: 			  'missingbubbles');
1.257     albertel 6335:     if (!$env{'form.validatepass'}) {
                   6336: 	$env{'form.validatepass'} = 0;
1.157     albertel 6337:     }
1.257     albertel 6338:     my $currentphase=$env{'form.validatepass'};
1.157     albertel 6339: 
1.448     foxr     6340: 
1.157     albertel 6341:     my $stop=0;
                   6342:     while (!$stop && $currentphase < scalar(@validate_phases)) {
1.503     raeburn  6343: 	$r->print(&mt('Validating '.$validate_phases[$currentphase]).'<br />');
1.157     albertel 6344: 	$r->rflush();
                   6345: 	my $which="scantron_validate_".$validate_phases[$currentphase];
                   6346: 	{
                   6347: 	    no strict 'refs';
                   6348: 	    ($stop,$currentphase)=&$which($r,$currentphase);
                   6349: 	}
                   6350:     }
                   6351:     if (!$stop) {
1.203     albertel 6352: 	my $warning=&scantron_warning_screen('Start Grading');
1.542     raeburn  6353: 	$r->print(&mt('Validation process complete.').'<br />'.
                   6354:                   $warning.
                   6355:                   &mt('Perform verification for each student after storage of submissions?').
                   6356:                   '&nbsp;<span class="LC_nobreak"><label>'.
                   6357:                   '<input type="radio" name="verifyrecord" value="1" />'.&mt('Yes').'</label>'.
                   6358:                   ('&nbsp;'x3).'<label>'.
                   6359:                   '<input type="radio" name="verifyrecord" value="0" checked="checked" />'.&mt('No').
                   6360:                   '</label></span><br />'.
                   6361:                   &mt('Grading will take longer if you use verification.').'<br />'.
1.572     www      6362:                   &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  6363:                   '<input type="submit" name="submit" value="'.&mt('Start Grading').'" />'.
                   6364:                   '<input type="hidden" name="command" value="scantron_process" />'."\n");
1.157     albertel 6365:     } else {
                   6366: 	$r->print('<input type="hidden" name="command" value="scantron_validate" />');
                   6367: 	$r->print("<input type='hidden' name='validatepass' value='".$currentphase."' />");
                   6368:     }
                   6369:     if ($stop) {
1.334     albertel 6370: 	if ($validate_phases[$currentphase] eq 'sequence') {
1.539     riegler  6371: 	    $r->print('<input type="submit" name="submit" value="'.&mt('Ignore').' &rarr; " />');
1.492     albertel 6372: 	    $r->print(' '.&mt('this error').' <br />');
1.334     albertel 6373: 
1.492     albertel 6374: 	    $r->print(" <p>".&mt("Or click the 'Grading Menu' button to start over.")."</p>");
1.334     albertel 6375: 	} else {
1.503     raeburn  6376:             if ($validate_phases[$currentphase] eq 'doublebubble' || $validate_phases[$currentphase] eq 'missingbubbles') {
1.539     riegler  6377: 	        $r->print('<input type="button" name="submitbutton" value="'.&mt('Continue').' &rarr;" onclick="javascript:verify_bubble_radio(this.form)" />');
1.503     raeburn  6378:             } else {
1.539     riegler  6379:                 $r->print('<input type="submit" name="submit" value="'.&mt('Continue').' &rarr;" />');
1.503     raeburn  6380:             }
1.492     albertel 6381: 	    $r->print(' '.&mt('using corrected info').' <br />');
                   6382: 	    $r->print("<input type='submit' value='".&mt("Skip")."' name='scantron_skip_record' />");
                   6383: 	    $r->print(" ".&mt("this scanline saving it for later."));
1.334     albertel 6384: 	}
1.157     albertel 6385:     }
1.352     albertel 6386:     $r->print(" </form><br />".&show_grading_menu_form($symb));
1.157     albertel 6387:     return '';
                   6388: }
                   6389: 
1.423     albertel 6390: 
                   6391: =pod
                   6392: 
                   6393: =item scantron_remove_file
                   6394: 
1.424     albertel 6395:    Removes the requested bubble sheet data file, makes sure that
                   6396:    scantron_original_<filename> is never removed
                   6397: 
                   6398: 
1.423     albertel 6399: =cut
                   6400: 
1.200     albertel 6401: sub scantron_remove_file {
1.192     albertel 6402:     my ($which)=@_;
1.257     albertel 6403:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   6404:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1.192     albertel 6405:     my $file='scantron_';
1.200     albertel 6406:     if ($which eq 'corrected' || $which eq 'skipped') {
                   6407: 	$file.=$which.'_';
1.192     albertel 6408:     } else {
                   6409: 	return 'refused';
                   6410:     }
1.257     albertel 6411:     $file.=$env{'form.scantron_selectfile'};
1.200     albertel 6412:     return &Apache::lonnet::removeuserfile($cname,$cdom,$file);
                   6413: }
                   6414: 
1.423     albertel 6415: 
                   6416: =pod
                   6417: 
                   6418: =item scantron_remove_scan_data
                   6419: 
1.424     albertel 6420:    Removes all scan_data correction for the requested bubble sheet
                   6421:    data file.  (In the case that both the are doing skipped records we need
                   6422:    to remember the old skipped lines for the time being so that element
                   6423:    persists for a while.)
                   6424: 
1.423     albertel 6425: =cut
                   6426: 
1.200     albertel 6427: sub scantron_remove_scan_data {
1.257     albertel 6428:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   6429:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1.192     albertel 6430:     my @keys=&Apache::lonnet::getkeys('nohist_scantrondata',$cdom,$cname);
                   6431:     my @todelete;
1.257     albertel 6432:     my $filename=$env{'form.scantron_selectfile'};
1.192     albertel 6433:     foreach my $key (@keys) {
                   6434: 	if ($key=~/^\Q$filename\E_/) {
1.257     albertel 6435: 	    if ($env{'form.scantron_options_redo'} eq 'redo_skipped_ready' &&
1.200     albertel 6436: 		$key=~/remember_skipping/) {
                   6437: 		next;
                   6438: 	    }
1.192     albertel 6439: 	    push(@todelete,$key);
                   6440: 	}
                   6441:     }
1.200     albertel 6442:     my $result;
1.192     albertel 6443:     if (@todelete) {
1.491     albertel 6444: 	$result = &Apache::lonnet::del('nohist_scantrondata',
                   6445: 				       \@todelete,$cdom,$cname);
                   6446:     } else {
                   6447: 	$result = 'ok';
1.192     albertel 6448:     }
                   6449:     return $result;
                   6450: }
                   6451: 
1.423     albertel 6452: 
                   6453: =pod
                   6454: 
                   6455: =item scantron_getfile
                   6456: 
1.424     albertel 6457:     Fetches the requested bubble sheet data file (all 3 versions), and
                   6458:     the scan_data hash
                   6459:   
                   6460:   Arguments:
                   6461:     None
                   6462: 
                   6463:   Returns:
                   6464:     2 hash references
                   6465: 
                   6466:      - first one has 
                   6467:          orig      -
                   6468:          corrected -
                   6469:          skipped   -  each of which points to an array ref of the specified
                   6470:                       file broken up into individual lines
                   6471:          count     - number of scanlines
                   6472:  
                   6473:      - second is the scan_data hash possible keys are
1.425     albertel 6474:        ($number refers to scanline numbered $number and thus the key affects
                   6475:         only that scanline
                   6476:         $bubline refers to the specific bubble line element and the aspects
                   6477:         refers to that specific bubble line element)
                   6478: 
                   6479:        $number.user - username:domain to use
                   6480:        $number.CODE_ignore_dup 
                   6481:                     - ignore the duplicate CODE error 
                   6482:        $number.useCODE
                   6483:                     - use the CODE in the scanline as is
                   6484:        $number.no_bubble.$bubline
                   6485:                     - it is valid that there is no bubbled in bubble
                   6486:                       at $number $bubline
                   6487:        remember_skipping
                   6488:                     - a frozen hash containing keys of $number and values
                   6489:                       of either 
                   6490:                         1 - we are on a 'do skipped records pass' and plan
                   6491:                             on processing this line
                   6492:                         2 - we are on a 'do skipped records pass' and this
                   6493:                             scanline has been marked to skip yet again
1.424     albertel 6494: 
1.423     albertel 6495: =cut
                   6496: 
1.157     albertel 6497: sub scantron_getfile {
1.200     albertel 6498:     #FIXME really would prefer a scantron directory
1.257     albertel 6499:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   6500:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1.157     albertel 6501:     my $lines;
                   6502:     $lines=&Apache::lonnet::getfile('/uploaded/'.$cdom.'/'.$cname.'/'.
1.257     albertel 6503: 		       'scantron_orig_'.$env{'form.scantron_selectfile'});
1.157     albertel 6504:     my %scanlines;
                   6505:     $scanlines{'orig'}=[(split("\n",$lines,-1))];
                   6506:     my $temp=$scanlines{'orig'};
                   6507:     $scanlines{'count'}=$#$temp;
                   6508: 
                   6509:     $lines=&Apache::lonnet::getfile('/uploaded/'.$cdom.'/'.$cname.'/'.
1.257     albertel 6510: 		       'scantron_corrected_'.$env{'form.scantron_selectfile'});
1.157     albertel 6511:     if ($lines eq '-1') {
                   6512: 	$scanlines{'corrected'}=[];
                   6513:     } else {
                   6514: 	$scanlines{'corrected'}=[(split("\n",$lines,-1))];
                   6515:     }
                   6516:     $lines=&Apache::lonnet::getfile('/uploaded/'.$cdom.'/'.$cname.'/'.
1.257     albertel 6517: 		       'scantron_skipped_'.$env{'form.scantron_selectfile'});
1.157     albertel 6518:     if ($lines eq '-1') {
                   6519: 	$scanlines{'skipped'}=[];
                   6520:     } else {
                   6521: 	$scanlines{'skipped'}=[(split("\n",$lines,-1))];
                   6522:     }
1.175     albertel 6523:     my @tmp=&Apache::lonnet::dump('nohist_scantrondata',$cdom,$cname);
1.157     albertel 6524:     if ($tmp[0] =~ /^(error:|no_such_host)/) { @tmp=(); }
                   6525:     my %scan_data = @tmp;
                   6526:     return (\%scanlines,\%scan_data);
                   6527: }
                   6528: 
1.423     albertel 6529: =pod
                   6530: 
                   6531: =item lonnet_putfile
                   6532: 
1.424     albertel 6533:    Wrapper routine to call &Apache::lonnet::finishuserfileupload
                   6534: 
                   6535:  Arguments:
                   6536:    $contents - data to store
                   6537:    $filename - filename to store $contents into
                   6538: 
                   6539:  Returns:
                   6540:    result value from &Apache::lonnet::finishuserfileupload
                   6541: 
1.423     albertel 6542: =cut
                   6543: 
1.157     albertel 6544: sub lonnet_putfile {
                   6545:     my ($contents,$filename)=@_;
1.257     albertel 6546:     my $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   6547:     my $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
                   6548:     $env{'form.sillywaytopassafilearound'}=$contents;
1.275     albertel 6549:     &Apache::lonnet::finishuserfileupload($docuname,$docudom,'sillywaytopassafilearound',$filename);
1.157     albertel 6550: 
                   6551: }
                   6552: 
1.423     albertel 6553: =pod
                   6554: 
                   6555: =item scantron_putfile
                   6556: 
1.424     albertel 6557:     Stores the current version of the bubble sheet data files, and the
                   6558:     scan_data hash. (Does not modify the original version only the
                   6559:     corrected and skipped versions.
                   6560: 
                   6561:  Arguments:
                   6562:     $scanlines - hash ref that looks like the first return value from
                   6563:                  &scantron_getfile()
                   6564:     $scan_data - hash ref that looks like the second return value from
                   6565:                  &scantron_getfile()
                   6566: 
1.423     albertel 6567: =cut
                   6568: 
1.157     albertel 6569: sub scantron_putfile {
                   6570:     my ($scanlines,$scan_data) = @_;
1.200     albertel 6571:     #FIXME really would prefer a scantron directory
1.257     albertel 6572:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   6573:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1.200     albertel 6574:     if ($scanlines) {
                   6575: 	my $prefix='scantron_';
1.157     albertel 6576: # no need to update orig, shouldn't change
                   6577: #   &lonnet_putfile(join("\n",@{$scanlines->{'orig'}}),$prefix.'orig_'.
1.257     albertel 6578: #		    $env{'form.scantron_selectfile'});
1.200     albertel 6579: 	&lonnet_putfile(join("\n",@{$scanlines->{'corrected'}}),
                   6580: 			$prefix.'corrected_'.
1.257     albertel 6581: 			$env{'form.scantron_selectfile'});
1.200     albertel 6582: 	&lonnet_putfile(join("\n",@{$scanlines->{'skipped'}}),
                   6583: 			$prefix.'skipped_'.
1.257     albertel 6584: 			$env{'form.scantron_selectfile'});
1.200     albertel 6585:     }
1.175     albertel 6586:     &Apache::lonnet::put('nohist_scantrondata',$scan_data,$cdom,$cname);
1.157     albertel 6587: }
                   6588: 
1.423     albertel 6589: =pod
                   6590: 
                   6591: =item scantron_get_line
                   6592: 
1.424     albertel 6593:    Returns the correct version of the scanline
                   6594: 
                   6595:  Arguments:
                   6596:     $scanlines - hash ref that looks like the first return value from
                   6597:                  &scantron_getfile()
                   6598:     $scan_data - hash ref that looks like the second return value from
                   6599:                  &scantron_getfile()
                   6600:     $i         - number of the requested line (starts at 0)
                   6601: 
                   6602:  Returns:
                   6603:    A scanline, (either the original or the corrected one if it
                   6604:    exists), or undef if the requested scanline should be
                   6605:    skipped. (Either because it's an skipped scanline, or it's an
                   6606:    unskipped scanline and we are not doing a 'do skipped scanlines'
                   6607:    pass.
                   6608: 
1.423     albertel 6609: =cut
                   6610: 
1.157     albertel 6611: sub scantron_get_line {
1.200     albertel 6612:     my ($scanlines,$scan_data,$i)=@_;
1.376     albertel 6613:     if (&should_be_skipped($scanlines,$scan_data,$i)) { return undef; }
                   6614:     #if ($scanlines->{'skipped'}[$i]) { return undef; }
1.157     albertel 6615:     if ($scanlines->{'corrected'}[$i]) {return $scanlines->{'corrected'}[$i];}
                   6616:     return $scanlines->{'orig'}[$i]; 
                   6617: }
                   6618: 
1.423     albertel 6619: =pod
                   6620: 
                   6621: =item scantron_todo_count
                   6622: 
1.424     albertel 6623:     Counts the number of scanlines that need processing.
                   6624: 
                   6625:  Arguments:
                   6626:     $scanlines - hash ref that looks like the first return value from
                   6627:                  &scantron_getfile()
                   6628:     $scan_data - hash ref that looks like the second return value from
                   6629:                  &scantron_getfile()
                   6630: 
                   6631:  Returns:
                   6632:     $count - number of scanlines to process
                   6633: 
1.423     albertel 6634: =cut
                   6635: 
1.200     albertel 6636: sub get_todo_count {
                   6637:     my ($scanlines,$scan_data)=@_;
                   6638:     my $count=0;
                   6639:     for (my $i=0;$i<=$scanlines->{'count'};$i++) {
                   6640: 	my $line=&scantron_get_line($scanlines,$scan_data,$i);
                   6641: 	if ($line=~/^[\s\cz]*$/) { next; }
                   6642: 	$count++;
                   6643:     }
                   6644:     return $count;
                   6645: }
                   6646: 
1.423     albertel 6647: =pod
                   6648: 
                   6649: =item scantron_put_line
                   6650: 
1.424     albertel 6651:     Updates the 'corrected' or 'skipped' versions of the bubble sheet
                   6652:     data file.
                   6653: 
                   6654:  Arguments:
                   6655:     $scanlines - hash ref that looks like the first return value from
                   6656:                  &scantron_getfile()
                   6657:     $scan_data - hash ref that looks like the second return value from
                   6658:                  &scantron_getfile()
                   6659:     $i         - line number to update
                   6660:     $newline   - contents of the updated scanline
                   6661:     $skip      - if true make the line for skipping and update the
                   6662:                  'skipped' file
                   6663: 
1.423     albertel 6664: =cut
                   6665: 
1.157     albertel 6666: sub scantron_put_line {
1.200     albertel 6667:     my ($scanlines,$scan_data,$i,$newline,$skip)=@_;
1.157     albertel 6668:     if ($skip) {
                   6669: 	$scanlines->{'skipped'}[$i]=$newline;
1.376     albertel 6670: 	&start_skipping($scan_data,$i);
1.157     albertel 6671: 	return;
                   6672:     }
                   6673:     $scanlines->{'corrected'}[$i]=$newline;
                   6674: }
                   6675: 
1.423     albertel 6676: =pod
                   6677: 
                   6678: =item scantron_clear_skip
                   6679: 
1.424     albertel 6680:    Remove a line from the 'skipped' file
                   6681: 
                   6682:  Arguments:
                   6683:     $scanlines - hash ref that looks like the first return value from
                   6684:                  &scantron_getfile()
                   6685:     $scan_data - hash ref that looks like the second return value from
                   6686:                  &scantron_getfile()
                   6687:     $i         - line number to update
                   6688: 
1.423     albertel 6689: =cut
                   6690: 
1.376     albertel 6691: sub scantron_clear_skip {
                   6692:     my ($scanlines,$scan_data,$i)=@_;
                   6693:     if (exists($scanlines->{'skipped'}[$i])) {
                   6694: 	undef($scanlines->{'skipped'}[$i]);
                   6695: 	return 1;
                   6696:     }
                   6697:     return 0;
                   6698: }
                   6699: 
1.423     albertel 6700: =pod
                   6701: 
                   6702: =item scantron_filter_not_exam
                   6703: 
1.424     albertel 6704:    Filter routine used by &Apache::lonnavmaps::retrieveResources(), to
                   6705:    filter out resources that are not marked as 'exam' mode
                   6706: 
1.423     albertel 6707: =cut
                   6708: 
1.334     albertel 6709: sub scantron_filter_not_exam {
                   6710:     my ($curres)=@_;
                   6711:     
                   6712:     if (ref($curres) && $curres->is_problem() && !$curres->is_exam()) {
                   6713: 	# if the user has asked to not have either hidden
                   6714: 	# or 'randomout' controlled resources to be graded
                   6715: 	# don't include them
                   6716: 	if ($env{'form.scantron_options_hidden'} eq 'ignore_hidden'
                   6717: 	    && $curres->randomout) {
                   6718: 	    return 0;
                   6719: 	}
                   6720: 	return 1;
                   6721:     }
                   6722:     return 0;
                   6723: }
                   6724: 
1.423     albertel 6725: =pod
                   6726: 
                   6727: =item scantron_validate_sequence
                   6728: 
1.424     albertel 6729:     Validates the selected sequence, checking for resource that are
                   6730:     not set to exam mode.
                   6731: 
1.423     albertel 6732: =cut
                   6733: 
1.334     albertel 6734: sub scantron_validate_sequence {
                   6735:     my ($r,$currentphase) = @_;
                   6736: 
                   6737:     my $navmap=Apache::lonnavmaps::navmap->new();
1.582     raeburn  6738:     unless (ref($navmap)) {
                   6739:         $r->print(&navmap_errormsg());
                   6740:         return (1,$currentphase);
                   6741:     }
1.334     albertel 6742:     my (undef,undef,$sequence)=
                   6743: 	&Apache::lonnet::decode_symb($env{'form.selectpage'});
                   6744: 
                   6745:     my $map=$navmap->getResourceByUrl($sequence);
                   6746: 
                   6747:     $r->print('<input type="hidden" name="validate_sequence_exam"
                   6748:                                     value="ignore" />');
                   6749:     if ($env{'form.validate_sequence_exam'} ne 'ignore') {
                   6750: 	my @resources=
                   6751: 	    $navmap->retrieveResources($map,\&scantron_filter_not_exam,1,0);
                   6752: 	if (@resources) {
1.357     banghart 6753: 	    $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 6754: 	    return (1,$currentphase);
                   6755: 	}
                   6756:     }
                   6757: 
                   6758:     return (0,$currentphase+1);
                   6759: }
                   6760: 
1.423     albertel 6761: 
                   6762: 
1.157     albertel 6763: sub scantron_validate_ID {
                   6764:     my ($r,$currentphase) = @_;
                   6765:     
                   6766:     #get student info
                   6767:     my $classlist=&Apache::loncoursedata::get_classlist();
                   6768:     my %idmap=&username_to_idmap($classlist);
                   6769: 
                   6770:     #get scantron line setup
1.257     albertel 6771:     my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
1.157     albertel 6772:     my ($scanlines,$scan_data)=&scantron_getfile();
1.582     raeburn  6773: 
                   6774:     my $nav_error;
                   6775:     &scantron_get_maxbubble(\$nav_error); # parse needs the bubble_lines.. array.
                   6776:     if ($nav_error) {
                   6777:         $r->print(&navmap_errormsg());
                   6778:         return(1,$currentphase);
                   6779:     }
1.157     albertel 6780: 
                   6781:     my %found=('ids'=>{},'usernames'=>{});
                   6782:     for (my $i=0;$i<=$scanlines->{'count'};$i++) {
1.200     albertel 6783: 	my $line=&scantron_get_line($scanlines,$scan_data,$i);
1.157     albertel 6784: 	if ($line=~/^[\s\cz]*$/) { next; }
                   6785: 	my $scan_record=&scantron_parse_scanline($line,$i,\%scantron_config,
                   6786: 						 $scan_data);
                   6787: 	my $id=$$scan_record{'scantron.ID'};
                   6788: 	my $found;
                   6789: 	foreach my $checkid (keys(%idmap)) {
                   6790: 	    if (lc($checkid) eq lc($id)) { $found=$checkid;last; }
                   6791: 	}
                   6792: 	if ($found) {
                   6793: 	    my $username=$idmap{$found};
                   6794: 	    if ($found{'ids'}{$found}) {
                   6795: 		&scantron_get_correction($r,$i,$scan_record,\%scantron_config,
                   6796: 					 $line,'duplicateID',$found);
1.194     albertel 6797: 		return(1,$currentphase);
1.157     albertel 6798: 	    } elsif ($found{'usernames'}{$username}) {
                   6799: 		&scantron_get_correction($r,$i,$scan_record,\%scantron_config,
                   6800: 					 $line,'duplicateID',$username);
1.194     albertel 6801: 		return(1,$currentphase);
1.157     albertel 6802: 	    }
1.186     albertel 6803: 	    #FIXME store away line we previously saw the ID on to use above
1.157     albertel 6804: 	    $found{'ids'}{$found}++;
                   6805: 	    $found{'usernames'}{$username}++;
                   6806: 	} else {
                   6807: 	    if ($id =~ /^\s*$/) {
1.158     albertel 6808: 		my $username=&scan_data($scan_data,"$i.user");
1.157     albertel 6809: 		if (defined($username) && $found{'usernames'}{$username}) {
                   6810: 		    &scantron_get_correction($r,$i,$scan_record,
                   6811: 					     \%scantron_config,
                   6812: 					     $line,'duplicateID',$username);
1.194     albertel 6813: 		    return(1,$currentphase);
1.157     albertel 6814: 		} elsif (!defined($username)) {
                   6815: 		    &scantron_get_correction($r,$i,$scan_record,
                   6816: 					     \%scantron_config,
                   6817: 					     $line,'incorrectID');
1.194     albertel 6818: 		    return(1,$currentphase);
1.157     albertel 6819: 		}
                   6820: 		$found{'usernames'}{$username}++;
                   6821: 	    } else {
                   6822: 		&scantron_get_correction($r,$i,$scan_record,\%scantron_config,
                   6823: 					 $line,'incorrectID');
1.194     albertel 6824: 		return(1,$currentphase);
1.157     albertel 6825: 	    }
                   6826: 	}
                   6827:     }
                   6828: 
                   6829:     return (0,$currentphase+1);
                   6830: }
                   6831: 
1.423     albertel 6832: 
1.157     albertel 6833: sub scantron_get_correction {
                   6834:     my ($r,$i,$scan_record,$scan_config,$line,$error,$arg)=@_;
1.454     banghart 6835: #FIXME in the case of a duplicated ID the previous line, probably need
1.157     albertel 6836: #to show both the current line and the previous one and allow skipping
                   6837: #the previous one or the current one
                   6838: 
1.333     albertel 6839:     if ( $$scan_record{'scantron.PaperID'} =~ /\S/) {
1.492     albertel 6840: 	$r->print("<p>".&mt("<b>An error was detected ($error)</b>".
                   6841: 			    " for PaperID <tt>[_1]</tt>",
                   6842: 			    $$scan_record{'scantron.PaperID'})."</p> \n");
1.157     albertel 6843:     } else {
1.492     albertel 6844: 	$r->print("<p>".&mt("<b>An error was detected ($error)</b>".
                   6845: 			    " in scanline [_1] <pre>[_2]</pre>",
                   6846: 			    $i,$line)."</p> \n");
                   6847:     }
                   6848:     my $message="<p>".&mt("The ID on the form is  <tt>[_1]</tt><br />".
                   6849: 			  "The name on the paper is [_2],[_3]",
                   6850: 			  $$scan_record{'scantron.ID'},
                   6851: 			  $$scan_record{'scantron.LastName'},
                   6852: 			  $$scan_record{'scantron.FirstName'})."</p>";
1.242     albertel 6853: 
1.157     albertel 6854:     $r->print('<input type="hidden" name="scantron_corrections" value="'.$error.'" />'."\n");
                   6855:     $r->print('<input type="hidden" name="scantron_line" value="'.$i.'" />'."\n");
1.503     raeburn  6856:                            # Array populated for doublebubble or
                   6857:     my @lines_to_correct;  # missingbubble errors to build javascript
                   6858:                            # to validate radio button checking   
                   6859: 
1.157     albertel 6860:     if ($error =~ /ID$/) {
1.186     albertel 6861: 	if ($error eq 'incorrectID') {
1.492     albertel 6862: 	    $r->print("<p>".&mt("The encoded ID is not in the classlist").
                   6863: 		      "</p>\n");
1.157     albertel 6864: 	} elsif ($error eq 'duplicateID') {
1.492     albertel 6865: 	    $r->print("<p>".&mt("The encoded ID has also been used by a previous paper [_1]",$arg)."</p>\n");
1.157     albertel 6866: 	}
1.242     albertel 6867: 	$r->print($message);
1.492     albertel 6868: 	$r->print("<p>".&mt("How should I handle this?")." <br /> \n");
1.157     albertel 6869: 	$r->print("\n<ul><li> ");
                   6870: 	#FIXME it would be nice if this sent back the user ID and
                   6871: 	#could do partial userID matches
                   6872: 	$r->print(&Apache::loncommon::selectstudent_link('scantronupload',
                   6873: 				       'scantron_username','scantron_domain'));
                   6874: 	$r->print(": <input type='text' name='scantron_username' value='' />");
                   6875: 	$r->print("\n@".
1.257     albertel 6876: 		 &Apache::loncommon::select_dom_form($env{'request.role.domain'},'scantron_domain'));
1.157     albertel 6877: 
                   6878: 	$r->print('</li>');
1.186     albertel 6879:     } elsif ($error =~ /CODE$/) {
                   6880: 	if ($error eq 'incorrectCODE') {
1.492     albertel 6881: 	    $r->print("<p>".&mt("The encoded CODE is not in the list of possible CODEs.")."</p>\n");
1.186     albertel 6882: 	} elsif ($error eq 'duplicateCODE') {
1.492     albertel 6883: 	    $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 6884: 	}
1.492     albertel 6885: 	$r->print("<p>".&mt("The CODE on the form is  <tt>'[_1]'</tt>",
                   6886: 			    $$scan_record{'scantron.CODE'})."<br />\n");
1.242     albertel 6887: 	$r->print($message);
1.492     albertel 6888: 	$r->print("<p>".&mt("How should I handle this?")." <br /> \n");
1.187     albertel 6889: 	$r->print("\n<br /> ");
1.194     albertel 6890: 	my $i=0;
1.273     albertel 6891: 	if ($error eq 'incorrectCODE' 
                   6892: 	    && $$scan_record{'scantron.CODE'}=~/\S/ ) {
1.194     albertel 6893: 	    my ($max,$closest)=&scantron_get_closely_matching_CODEs($arg,$$scan_record{'scantron.CODE'});
1.278     albertel 6894: 	    if ($closest > 0) {
                   6895: 		foreach my $testcode (@{$closest}) {
                   6896: 		    my $checked='';
1.569     bisitz   6897: 		    if (!$i) { $checked=' checked="checked"'; }
1.492     albertel 6898: 		    $r->print("
                   6899:    <label>
1.569     bisitz   6900:        <input type='radio' name='scantron_CODE_resolution' value='use_closest_$i'$checked />
1.492     albertel 6901:        ".&mt("Use the similar CODE [_1] instead.",
                   6902: 	    "<b><tt>".$testcode."</tt></b>")."
                   6903:     </label>
                   6904:     <input type='hidden' name='scantron_CODE_closest_$i' value='$testcode' />");
1.278     albertel 6905: 		    $r->print("\n<br />");
                   6906: 		    $i++;
                   6907: 		}
1.194     albertel 6908: 	    }
                   6909: 	}
1.273     albertel 6910: 	if ($$scan_record{'scantron.CODE'}=~/\S/ ) {
1.569     bisitz   6911: 	    my $checked; if (!$i) { $checked=' checked="checked"'; }
1.492     albertel 6912: 	    $r->print("
                   6913:     <label>
1.569     bisitz   6914:         <input type='radio' name='scantron_CODE_resolution' value='use_unfound'$checked />
1.492     albertel 6915:        ".&mt("Use the CODE [_1] that is was on the paper, ignoring the error.",
                   6916: 	     "<b><tt>".$$scan_record{'scantron.CODE'}."</tt></b>")."
                   6917:     </label>");
1.273     albertel 6918: 	    $r->print("\n<br />");
                   6919: 	}
1.194     albertel 6920: 
1.597     wenzelju 6921: 	$r->print(&Apache::lonhtmlcommon::scripttag(<<ENDSCRIPT));
1.188     albertel 6922: function change_radio(field) {
1.190     albertel 6923:     var slct=document.scantronupload.scantron_CODE_resolution;
1.188     albertel 6924:     var i;
                   6925:     for (i=0;i<slct.length;i++) {
                   6926:         if (slct[i].value==field) { slct[i].checked=true; }
                   6927:     }
                   6928: }
                   6929: ENDSCRIPT
1.187     albertel 6930: 	my $href="/adm/pickcode?".
1.359     www      6931: 	   "form=".&escape("scantronupload").
                   6932: 	   "&scantron_format=".&escape($env{'form.scantron_format'}).
                   6933: 	   "&scantron_CODElist=".&escape($env{'form.scantron_CODElist'}).
                   6934: 	   "&curCODE=".&escape($$scan_record{'scantron.CODE'}).
                   6935: 	   "&scantron_selectfile=".&escape($env{'form.scantron_selectfile'});
1.332     albertel 6936: 	if ($env{'form.scantron_CODElist'} =~ /\S/) { 
1.492     albertel 6937: 	    $r->print("
                   6938:     <label>
                   6939:        <input type='radio' name='scantron_CODE_resolution' value='use_found' />
                   6940:        ".&mt("[_1]Select[_2] a CODE from the list of all CODEs and use it.",
                   6941: 	     "<a target='_blank' href='$href'>","</a>")."
                   6942:     </label> 
1.558     bisitz   6943:     ".&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 6944: 	    $r->print("\n<br />");
                   6945: 	}
1.492     albertel 6946: 	$r->print("
                   6947:     <label>
                   6948:        <input type='radio' name='scantron_CODE_resolution' value='use_typed' />
                   6949:        ".&mt("Use [_1] as the CODE.",
                   6950: 	     "</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 6951: 	$r->print("\n<br /><br />");
1.157     albertel 6952:     } elsif ($error eq 'doublebubble') {
1.503     raeburn  6953: 	$r->print("<p>".&mt("There have been multiple bubbles scanned for some question(s)")."</p>\n");
1.497     foxr     6954: 
                   6955: 	# The form field scantron_questions is acutally a list of line numbers.
                   6956: 	# represented by this form so:
                   6957: 
                   6958: 	my $line_list = &questions_to_line_list($arg);
                   6959: 
1.157     albertel 6960: 	$r->print('<input type="hidden" name="scantron_questions" value="'.
1.497     foxr     6961: 		  $line_list.'" />');
1.242     albertel 6962: 	$r->print($message);
1.492     albertel 6963: 	$r->print("<p>".&mt("Please indicate which bubble should be used for grading")."</p>");
1.157     albertel 6964: 	foreach my $question (@{$arg}) {
1.503     raeburn  6965: 	    my @linenums = &prompt_for_corrections($r,$question,$scan_config,
                   6966:                                                    $scan_record, $error);
1.524     raeburn  6967:             push(@lines_to_correct,@linenums);
1.157     albertel 6968: 	}
1.503     raeburn  6969:         $r->print(&verify_bubbles_checked(@lines_to_correct));
1.157     albertel 6970:     } elsif ($error eq 'missingbubble') {
1.492     albertel 6971: 	$r->print("<p>".&mt("There have been <b>no</b> bubbles scanned for some question(s)")."</p>\n");
1.242     albertel 6972: 	$r->print($message);
1.492     albertel 6973: 	$r->print("<p>".&mt("Please indicate which bubble should be used for grading.")."</p>");
1.503     raeburn  6974: 	$r->print(&mt("Some questions have no scanned bubbles.")."\n");
1.497     foxr     6975: 
1.503     raeburn  6976: 	# The form field scantron_questions is actually a list of line numbers not
1.497     foxr     6977: 	# a list of question numbers. Therefore:
                   6978: 	#
                   6979: 	
                   6980: 	my $line_list = &questions_to_line_list($arg);
                   6981: 
1.157     albertel 6982: 	$r->print('<input type="hidden" name="scantron_questions" value="'.
1.497     foxr     6983: 		  $line_list.'" />');
1.157     albertel 6984: 	foreach my $question (@{$arg}) {
1.503     raeburn  6985: 	    my @linenums = &prompt_for_corrections($r,$question,$scan_config,
                   6986:                                                    $scan_record, $error);
1.524     raeburn  6987:             push(@lines_to_correct,@linenums);
1.157     albertel 6988: 	}
1.503     raeburn  6989:         $r->print(&verify_bubbles_checked(@lines_to_correct));
1.157     albertel 6990:     } else {
                   6991: 	$r->print("\n<ul>");
                   6992:     }
                   6993:     $r->print("\n</li></ul>");
1.497     foxr     6994: }
                   6995: 
1.503     raeburn  6996: sub verify_bubbles_checked {
                   6997:     my (@ansnums) = @_;
                   6998:     my $ansnumstr = join('","',@ansnums);
                   6999:     my $warning = &mt("A bubble or 'No bubble' selection has not been made for one or more lines.");
1.597     wenzelju 7000:     my $output = &Apache::lonhtmlcommon::scripttag((<<ENDSCRIPT));
1.503     raeburn  7001: function verify_bubble_radio(form) {
                   7002:     var ansnumArray = new Array ("$ansnumstr");
                   7003:     var need_bubble_count = 0;
                   7004:     for (var i=0; i<ansnumArray.length; i++) {
                   7005:         if (form.elements["scantron_correct_Q_"+ansnumArray[i]].length > 1) {
                   7006:             var bubble_picked = 0; 
                   7007:             for (var j=0; j<form.elements["scantron_correct_Q_"+ansnumArray[i]].length; j++) {
                   7008:                 if (form.elements["scantron_correct_Q_"+ansnumArray[i]][j].checked == true) {
                   7009:                     bubble_picked = 1;
                   7010:                 }
                   7011:             }
                   7012:             if (bubble_picked == 0) {
                   7013:                 need_bubble_count ++;
                   7014:             }
                   7015:         }
                   7016:     }
                   7017:     if (need_bubble_count) {
                   7018:         alert("$warning");
                   7019:         return;
                   7020:     }
                   7021:     form.submit(); 
                   7022: }
                   7023: ENDSCRIPT
                   7024:     return $output;
                   7025: }
                   7026: 
1.497     foxr     7027: =pod
                   7028: 
                   7029: =item  questions_to_line_list
1.157     albertel 7030: 
1.497     foxr     7031: Converts a list of questions into a string of comma separated
                   7032: line numbers in the answer sheet used by the questions.  This is
                   7033: used to fill in the scantron_questions form field.
                   7034: 
                   7035:   Arguments:
                   7036:      questions    - Reference to an array of questions.
                   7037: 
                   7038: =cut
                   7039: 
                   7040: 
                   7041: sub questions_to_line_list {
                   7042:     my ($questions) = @_;
                   7043:     my @lines;
                   7044: 
1.503     raeburn  7045:     foreach my $item (@{$questions}) {
                   7046:         my $question = $item;
                   7047:         my ($first,$count,$last);
                   7048:         if ($item =~ /^(\d+)\.(\d+)$/) {
                   7049:             $question = $1;
                   7050:             my $subquestion = $2;
                   7051:             $first = $first_bubble_line{$question-1} + 1;
                   7052:             my @subans = split(/,/,$subdivided_bubble_lines{$question-1});
                   7053:             my $subcount = 1;
                   7054:             while ($subcount<$subquestion) {
                   7055:                 $first += $subans[$subcount-1];
                   7056:                 $subcount ++;
                   7057:             }
                   7058:             $count = $subans[$subquestion-1];
                   7059:         } else {
                   7060: 	    $first   = $first_bubble_line{$question-1} + 1;
                   7061: 	    $count   = $bubble_lines_per_response{$question-1};
                   7062:         }
1.506     raeburn  7063:         $last = $first+$count-1;
1.503     raeburn  7064:         push(@lines, ($first..$last));
1.497     foxr     7065:     }
                   7066:     return join(',', @lines);
                   7067: }
                   7068: 
                   7069: =pod 
                   7070: 
                   7071: =item prompt_for_corrections
                   7072: 
                   7073: Prompts for a potentially multiline correction to the
                   7074: user's bubbling (factors out common code from scantron_get_correction
                   7075: for multi and missing bubble cases).
                   7076: 
                   7077:  Arguments:
                   7078:    $r           - Apache request object.
                   7079:    $question    - The question number to prompt for.
                   7080:    $scan_config - The scantron file configuration hash.
                   7081:    $scan_record - Reference to the hash that has the the parsed scanlines.
1.503     raeburn  7082:    $error       - Type of error
1.497     foxr     7083: 
                   7084:  Implicit inputs:
                   7085:    %bubble_lines_per_response   - Starting line numbers for each question.
                   7086:                                   Numbered from 0 (but question numbers are from
                   7087:                                   1.
                   7088:    %first_bubble_line           - Starting bubble line for each question.
1.509     raeburn  7089:    %subdivided_bubble_lines     - optionresponse, matchresponse and rankresponse 
                   7090:                                   type problems render as separate sub-questions, 
1.503     raeburn  7091:                                   in exam mode. This hash contains a 
                   7092:                                   comma-separated list of the lines per 
                   7093:                                   sub-question.
1.510     raeburn  7094:    %responsetype_per_response   - essayresponse, formularesponse,
                   7095:                                   stringresponse, imageresponse, reactionresponse,
                   7096:                                   and organicresponse type problem parts can have
1.503     raeburn  7097:                                   multiple lines per response if the weight
                   7098:                                   assigned exceeds 10.  In this case, only
                   7099:                                   one bubble per line is permitted, but more 
                   7100:                                   than one line might contain bubbles, e.g.
                   7101:                                   bubbling of: line 1 - J, line 2 - J, 
                   7102:                                   line 3 - B would assign 22 points.  
1.497     foxr     7103: 
                   7104: =cut
                   7105: 
                   7106: sub prompt_for_corrections {
1.503     raeburn  7107:     my ($r, $question, $scan_config, $scan_record, $error) = @_;
                   7108:     my ($current_line,$lines);
                   7109:     my @linenums;
                   7110:     my $questionnum = $question;
                   7111:     if ($question =~ /^(\d+)\.(\d+)$/) {
                   7112:         $question = $1;
                   7113:         $current_line = $first_bubble_line{$question-1} + 1 ;
                   7114:         my $subquestion = $2;
                   7115:         my @subans = split(/,/,$subdivided_bubble_lines{$question-1});
                   7116:         my $subcount = 1;
                   7117:         while ($subcount<$subquestion) {
                   7118:             $current_line += $subans[$subcount-1];
                   7119:             $subcount ++;
                   7120:         }
                   7121:         $lines = $subans[$subquestion-1];
                   7122:     } else {
                   7123:         $current_line = $first_bubble_line{$question-1} + 1 ;
                   7124:         $lines        = $bubble_lines_per_response{$question-1};
                   7125:     }
1.497     foxr     7126:     if ($lines > 1) {
1.503     raeburn  7127:         $r->print(&mt('The group of bubble lines below responds to a single question.').'<br />');
                   7128:         if (($responsetype_per_response{$question-1} eq 'essayresponse') ||
                   7129:             ($responsetype_per_response{$question-1} eq 'formularesponse') ||
1.510     raeburn  7130:             ($responsetype_per_response{$question-1} eq 'stringresponse') ||
                   7131:             ($responsetype_per_response{$question-1} eq 'imageresponse') ||
                   7132:             ($responsetype_per_response{$question-1} eq 'reactionresponse') ||
                   7133:             ($responsetype_per_response{$question-1} eq 'organicresponse')) {
1.572     www      7134:             $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  7135:         } else {
                   7136:             $r->print(&mt("Select at most one bubble in a single line and select 'No Bubble' in all the other lines. ")."<br />");
                   7137:         }
1.497     foxr     7138:     }
                   7139:     for (my $i =0; $i < $lines; $i++) {
1.503     raeburn  7140:         my $selected = $$scan_record{"scantron.$current_line.answer"};
                   7141: 	&scantron_bubble_selector($r,$scan_config,$current_line, 
                   7142: 	        		  $questionnum,$error,split('', $selected));
1.524     raeburn  7143:         push(@linenums,$current_line);
1.497     foxr     7144: 	$current_line++;
                   7145:     }
                   7146:     if ($lines > 1) {
                   7147: 	$r->print("<hr /><br />");
                   7148:     }
1.503     raeburn  7149:     return @linenums;
1.157     albertel 7150: }
1.423     albertel 7151: 
                   7152: =pod
                   7153: 
                   7154: =item scantron_bubble_selector
                   7155:   
                   7156:    Generates the html radiobuttons to correct a single bubble line
1.424     albertel 7157:    possibly showing the existing the selected bubbles if known
1.423     albertel 7158: 
                   7159:  Arguments:
                   7160:     $r           - Apache request object
                   7161:     $scan_config - hash from &get_scantron_config()
1.497     foxr     7162:     $line        - Number of the line being displayed.
1.503     raeburn  7163:     $questionnum - Question number (may include subquestion)
                   7164:     $error       - Type of error.
1.497     foxr     7165:     @selected    - Array of bubbles picked on this line.
1.423     albertel 7166: 
                   7167: =cut
                   7168: 
1.157     albertel 7169: sub scantron_bubble_selector {
1.503     raeburn  7170:     my ($r,$scan_config,$line,$questionnum,$error,@selected)=@_;
1.157     albertel 7171:     my $max=$$scan_config{'Qlength'};
1.274     albertel 7172: 
                   7173:     my $scmode=$$scan_config{'Qon'};
                   7174:     if ($scmode eq 'number' || $scmode eq 'letter') { $max=10; }	     
                   7175: 
1.157     albertel 7176:     my @alphabet=('A'..'Z');
1.503     raeburn  7177:     $r->print(&Apache::loncommon::start_data_table().
                   7178:               &Apache::loncommon::start_data_table_row());
                   7179:     $r->print('<td rowspan="2" class="LC_leftcol_header">'.$line.'</td>');
1.497     foxr     7180:     for (my $i=0;$i<$max+1;$i++) {
                   7181: 	$r->print("\n".'<td align="center">');
                   7182: 	if ($selected[0] eq $alphabet[$i]) { $r->print('X'); shift(@selected) }
                   7183: 	else { $r->print('&nbsp;'); }
                   7184: 	$r->print('</td>');
                   7185:     }
1.503     raeburn  7186:     $r->print(&Apache::loncommon::end_data_table_row().
                   7187:               &Apache::loncommon::start_data_table_row());
1.497     foxr     7188:     for (my $i=0;$i<$max;$i++) {
                   7189: 	$r->print("\n".
                   7190: 		  '<td><label><input type="radio" name="scantron_correct_Q_'.
                   7191: 		  $line.'" value="'.$i.'" />'.$alphabet[$i]."</label></td>");
                   7192:     }
1.503     raeburn  7193:     my $nobub_checked = ' ';
                   7194:     if ($error eq 'missingbubble') {
                   7195:         $nobub_checked = ' checked = "checked" ';
                   7196:     }
                   7197:     $r->print("\n".'<td><label><input type="radio" name="scantron_correct_Q_'.
                   7198: 	      $line.'" value="none"'.$nobub_checked.'/>'.&mt('No bubble').
                   7199:               '</label>'."\n".'<input type="hidden" name="scantron_questionnum_Q_'.
                   7200:               $line.'" value="'.$questionnum.'" /></td>');
                   7201:     $r->print(&Apache::loncommon::end_data_table_row().
                   7202:               &Apache::loncommon::end_data_table());
1.157     albertel 7203: }
                   7204: 
1.423     albertel 7205: =pod
                   7206: 
                   7207: =item num_matches
                   7208: 
1.424     albertel 7209:    Counts the number of characters that are the same between the two arguments.
                   7210: 
                   7211:  Arguments:
                   7212:    $orig - CODE from the scanline
                   7213:    $code - CODE to match against
                   7214: 
                   7215:  Returns:
                   7216:    $count - integer count of the number of same characters between the
                   7217:             two arguments
                   7218: 
1.423     albertel 7219: =cut
                   7220: 
1.194     albertel 7221: sub num_matches {
                   7222:     my ($orig,$code) = @_;
                   7223:     my @code=split(//,$code);
                   7224:     my @orig=split(//,$orig);
                   7225:     my $same=0;
                   7226:     for (my $i=0;$i<scalar(@code);$i++) {
                   7227: 	if ($code[$i] eq $orig[$i]) { $same++; }
                   7228:     }
                   7229:     return $same;
                   7230: }
                   7231: 
1.423     albertel 7232: =pod
                   7233: 
                   7234: =item scantron_get_closely_matching_CODEs
                   7235: 
1.424     albertel 7236:    Cycles through all CODEs and finds the set that has the greatest
                   7237:    number of same characters as the provided CODE
                   7238: 
                   7239:  Arguments:
                   7240:    $allcodes - hash ref returned by &get_codes()
                   7241:    $CODE     - CODE from the current scanline
                   7242: 
                   7243:  Returns:
                   7244:    2 element list
                   7245:     - first elements is number of how closely matching the best fit is 
                   7246:       (5 means best set has 5 matching characters)
                   7247:     - second element is an arrary ref containing the set of valid CODEs
                   7248:       that best fit the passed in CODE
                   7249: 
1.423     albertel 7250: =cut
                   7251: 
1.194     albertel 7252: sub scantron_get_closely_matching_CODEs {
                   7253:     my ($allcodes,$CODE)=@_;
                   7254:     my @CODEs;
                   7255:     foreach my $testcode (sort(keys(%{$allcodes}))) {
                   7256: 	push(@{$CODEs[&num_matches($CODE,$testcode)]},$testcode);
                   7257:     }
                   7258: 
                   7259:     return ($#CODEs,$CODEs[-1]);
                   7260: }
                   7261: 
1.423     albertel 7262: =pod
                   7263: 
                   7264: =item get_codes
                   7265: 
1.424     albertel 7266:    Builds a hash which has keys of all of the valid CODEs from the selected
                   7267:    set of remembered CODEs.
                   7268: 
                   7269:  Arguments:
                   7270:   $old_name - name of the set of remembered CODEs
                   7271:   $cdom     - domain of the course
                   7272:   $cnum     - internal course name
                   7273: 
                   7274:  Returns:
                   7275:   %allcodes - keys are the valid CODEs, values are all 1
                   7276: 
1.423     albertel 7277: =cut
                   7278: 
1.194     albertel 7279: sub get_codes {
1.280     foxr     7280:     my ($old_name, $cdom, $cnum) = @_;
                   7281:     if (!$old_name) {
                   7282: 	$old_name=$env{'form.scantron_CODElist'};
                   7283:     }
                   7284:     if (!$cdom) {
                   7285: 	$cdom =$env{'course.'.$env{'request.course.id'}.'.domain'};
                   7286:     }
                   7287:     if (!$cnum) {
                   7288: 	$cnum =$env{'course.'.$env{'request.course.id'}.'.num'};
                   7289:     }
1.278     albertel 7290:     my %result=&Apache::lonnet::get('CODEs',[$old_name,"type\0$old_name"],
                   7291: 				    $cdom,$cnum);
                   7292:     my %allcodes;
                   7293:     if ($result{"type\0$old_name"} eq 'number') {
                   7294: 	%allcodes=map {($_,1)} split(',',$result{$old_name});
                   7295:     } else {
                   7296: 	%allcodes=map {(&Apache::lonprintout::num_to_letters($_),1)} split(',',$result{$old_name});
                   7297:     }
1.194     albertel 7298:     return %allcodes;
                   7299: }
                   7300: 
1.423     albertel 7301: =pod
                   7302: 
                   7303: =item scantron_validate_CODE
                   7304: 
1.424     albertel 7305:    Validates all scanlines in the selected file to not have any
                   7306:    invalid or underspecified CODEs and that none of the codes are
                   7307:    duplicated if this was requested.
                   7308: 
1.423     albertel 7309: =cut
                   7310: 
1.157     albertel 7311: sub scantron_validate_CODE {
                   7312:     my ($r,$currentphase) = @_;
1.257     albertel 7313:     my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
1.186     albertel 7314:     if ($scantron_config{'CODElocation'} &&
                   7315: 	$scantron_config{'CODEstart'} &&
                   7316: 	$scantron_config{'CODElength'}) {
1.257     albertel 7317: 	if (!defined($env{'form.scantron_CODElist'})) {
1.186     albertel 7318: 	    &FIXME_blow_up()
                   7319: 	}
                   7320:     } else {
                   7321: 	return (0,$currentphase+1);
                   7322:     }
                   7323:     
                   7324:     my %usedCODEs;
                   7325: 
1.194     albertel 7326:     my %allcodes=&get_codes();
1.186     albertel 7327: 
1.582     raeburn  7328:     my $nav_error;
                   7329:     &scantron_get_maxbubble(\$nav_error); # parse needs the lines per response array.
                   7330:     if ($nav_error) {
                   7331:         $r->print(&navmap_errormsg());
                   7332:         return(1,$currentphase);
                   7333:     }
1.447     foxr     7334: 
1.186     albertel 7335:     my ($scanlines,$scan_data)=&scantron_getfile();
                   7336:     for (my $i=0;$i<=$scanlines->{'count'};$i++) {
1.200     albertel 7337: 	my $line=&scantron_get_line($scanlines,$scan_data,$i);
1.186     albertel 7338: 	if ($line=~/^[\s\cz]*$/) { next; }
                   7339: 	my $scan_record=&scantron_parse_scanline($line,$i,\%scantron_config,
                   7340: 						 $scan_data);
                   7341: 	my $CODE=$$scan_record{'scantron.CODE'};
                   7342: 	my $error=0;
1.224     albertel 7343: 	if (!&Apache::lonnet::validCODE($CODE)) {
                   7344: 	    &scantron_get_correction($r,$i,$scan_record,
                   7345: 				     \%scantron_config,
                   7346: 				     $line,'incorrectCODE',\%allcodes);
                   7347: 	    return(1,$currentphase);
                   7348: 	}
1.221     albertel 7349: 	if (%allcodes && !exists($allcodes{$CODE}) 
                   7350: 	    && !$$scan_record{'scantron.useCODE'}) {
1.186     albertel 7351: 	    &scantron_get_correction($r,$i,$scan_record,
                   7352: 				     \%scantron_config,
1.194     albertel 7353: 				     $line,'incorrectCODE',\%allcodes);
                   7354: 	    return(1,$currentphase);
1.186     albertel 7355: 	}
1.214     albertel 7356: 	if (exists($usedCODEs{$CODE}) 
1.257     albertel 7357: 	    && $env{'form.scantron_CODEunique'} eq 'yes'
1.192     albertel 7358: 	    && !$$scan_record{'scantron.CODE_ignore_dup'}) {
1.186     albertel 7359: 	    &scantron_get_correction($r,$i,$scan_record,
                   7360: 				     \%scantron_config,
1.194     albertel 7361: 				     $line,'duplicateCODE',$usedCODEs{$CODE});
                   7362: 	    return(1,$currentphase);
1.186     albertel 7363: 	}
1.524     raeburn  7364: 	push(@{$usedCODEs{$CODE}},$$scan_record{'scantron.PaperID'});
1.186     albertel 7365:     }
1.157     albertel 7366:     return (0,$currentphase+1);
                   7367: }
                   7368: 
1.423     albertel 7369: =pod
                   7370: 
                   7371: =item scantron_validate_doublebubble
                   7372: 
1.424     albertel 7373:    Validates all scanlines in the selected file to not have any
                   7374:    bubble lines with multiple bubbles marked.
                   7375: 
1.423     albertel 7376: =cut
                   7377: 
1.157     albertel 7378: sub scantron_validate_doublebubble {
                   7379:     my ($r,$currentphase) = @_;
                   7380:     #get student info
                   7381:     my $classlist=&Apache::loncoursedata::get_classlist();
                   7382:     my %idmap=&username_to_idmap($classlist);
                   7383: 
                   7384:     #get scantron line setup
1.257     albertel 7385:     my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
1.157     albertel 7386:     my ($scanlines,$scan_data)=&scantron_getfile();
1.583     raeburn  7387:     my $nav_error;
                   7388:     &scantron_get_maxbubble(\$nav_error); # parse needs the bubble line array.
                   7389:     if ($nav_error) {
                   7390:         $r->print(&navmap_errormsg());
                   7391:         return(1,$currentphase);
                   7392:     }
1.447     foxr     7393: 
1.157     albertel 7394:     for (my $i=0;$i<=$scanlines->{'count'};$i++) {
1.200     albertel 7395: 	my $line=&scantron_get_line($scanlines,$scan_data,$i);
1.157     albertel 7396: 	if ($line=~/^[\s\cz]*$/) { next; }
                   7397: 	my $scan_record=&scantron_parse_scanline($line,$i,\%scantron_config,
                   7398: 						 $scan_data);
                   7399: 	if (!defined($$scan_record{'scantron.doubleerror'})) { next; }
                   7400: 	&scantron_get_correction($r,$i,$scan_record,\%scantron_config,$line,
                   7401: 				 'doublebubble',
                   7402: 				 $$scan_record{'scantron.doubleerror'});
                   7403:     	return (1,$currentphase);
                   7404:     }
                   7405:     return (0,$currentphase+1);
                   7406: }
                   7407: 
1.423     albertel 7408: 
1.503     raeburn  7409: sub scantron_get_maxbubble {
1.582     raeburn  7410:     my ($nav_error) = @_;
1.257     albertel 7411:     if (defined($env{'form.scantron_maxbubble'}) &&
                   7412: 	$env{'form.scantron_maxbubble'}) {
1.447     foxr     7413: 	&restore_bubble_lines();
1.257     albertel 7414: 	return $env{'form.scantron_maxbubble'};
1.191     albertel 7415:     }
1.330     albertel 7416: 
1.447     foxr     7417:     my (undef, undef, $sequence) =
1.257     albertel 7418: 	&Apache::lonnet::decode_symb($env{'form.selectpage'});
1.330     albertel 7419: 
1.447     foxr     7420:     my $navmap=Apache::lonnavmaps::navmap->new();
1.582     raeburn  7421:     unless (ref($navmap)) {
                   7422:         if (ref($nav_error)) {
                   7423:             $$nav_error = 1;
                   7424:         }
1.591     raeburn  7425:         return;
1.582     raeburn  7426:     }
1.191     albertel 7427:     my $map=$navmap->getResourceByUrl($sequence);
                   7428:     my @resources=$navmap->retrieveResources($map,\&scantron_filter,1,0);
1.330     albertel 7429: 
                   7430:     &Apache::lonxml::clear_problem_counter();
                   7431: 
1.557     raeburn  7432:     my $uname       = $env{'user.name'};
                   7433:     my $udom        = $env{'user.domain'};
1.435     foxr     7434:     my $cid         = $env{'request.course.id'};
                   7435:     my $total_lines = 0;
                   7436:     %bubble_lines_per_response = ();
1.447     foxr     7437:     %first_bubble_line         = ();
1.503     raeburn  7438:     %subdivided_bubble_lines   = ();
                   7439:     %responsetype_per_response = ();
1.554     raeburn  7440: 
1.447     foxr     7441:     my $response_number = 0;
                   7442:     my $bubble_line     = 0;
1.191     albertel 7443:     foreach my $resource (@resources) {
1.542     raeburn  7444:         my ($analysis,$parts) = &scantron_partids_tograde($resource,$cid,$uname,$udom);
                   7445:         if ((ref($analysis) eq 'HASH') && (ref($parts) eq 'ARRAY')) {
                   7446: 	    foreach my $part_id (@{$parts}) {
                   7447:                 my $lines;
                   7448: 
                   7449: 	        # TODO - make this a persistent hash not an array.
                   7450: 
                   7451:                 # optionresponse, matchresponse and rankresponse type items 
                   7452:                 # render as separate sub-questions in exam mode.
                   7453:                 if (($analysis->{$part_id.'.type'} eq 'optionresponse') ||
                   7454:                     ($analysis->{$part_id.'.type'} eq 'matchresponse') ||
                   7455:                     ($analysis->{$part_id.'.type'} eq 'rankresponse')) {
                   7456:                     my ($numbub,$numshown);
                   7457:                     if ($analysis->{$part_id.'.type'} eq 'optionresponse') {
                   7458:                         if (ref($analysis->{$part_id.'.options'}) eq 'ARRAY') {
                   7459:                             $numbub = scalar(@{$analysis->{$part_id.'.options'}});
                   7460:                         }
                   7461:                     } elsif ($analysis->{$part_id.'.type'} eq 'matchresponse') {
                   7462:                         if (ref($analysis->{$part_id.'.items'}) eq 'ARRAY') {
                   7463:                             $numbub = scalar(@{$analysis->{$part_id.'.items'}});
                   7464:                         }
                   7465:                     } elsif ($analysis->{$part_id.'.type'} eq 'rankresponse') {
                   7466:                         if (ref($analysis->{$part_id.'.foils'}) eq 'ARRAY') {
                   7467:                             $numbub = scalar(@{$analysis->{$part_id.'.foils'}});
                   7468:                         }
                   7469:                     }
                   7470:                     if (ref($analysis->{$part_id.'.shown'}) eq 'ARRAY') {
                   7471:                         $numshown = scalar(@{$analysis->{$part_id.'.shown'}});
                   7472:                     }
                   7473:                     my $bubbles_per_line = 10;
                   7474:                     my $inner_bubble_lines = int($numbub/$bubbles_per_line);
                   7475:                     if (($numbub % $bubbles_per_line) != 0) {
                   7476:                         $inner_bubble_lines++;
                   7477:                     }
                   7478:                     for (my $i=0; $i<$numshown; $i++) {
                   7479:                         $subdivided_bubble_lines{$response_number} .= 
                   7480:                             $inner_bubble_lines.',';
                   7481:                     }
                   7482:                     $subdivided_bubble_lines{$response_number} =~ s/,$//;
                   7483:                     $lines = $numshown * $inner_bubble_lines;
                   7484:                 } else {
                   7485:                     $lines = $analysis->{"$part_id.bubble_lines"};
                   7486:                 } 
                   7487: 
                   7488:                 $first_bubble_line{$response_number} = $bubble_line;
                   7489: 	        $bubble_lines_per_response{$response_number} = $lines;
                   7490:                 $responsetype_per_response{$response_number} = 
                   7491:                     $analysis->{$part_id.'.type'};
                   7492: 	        $response_number++;
                   7493: 
                   7494: 	        $bubble_line +=  $lines;
                   7495: 	        $total_lines +=  $lines;
                   7496: 	    }
                   7497:         }
                   7498:     }
1.552     raeburn  7499:     &Apache::lonnet::delenv('scantron.');
1.542     raeburn  7500: 
                   7501:     &save_bubble_lines();
                   7502:     $env{'form.scantron_maxbubble'} =
                   7503: 	$total_lines;
                   7504:     return $env{'form.scantron_maxbubble'};
                   7505: }
1.523     raeburn  7506: 
1.157     albertel 7507: sub scantron_validate_missingbubbles {
                   7508:     my ($r,$currentphase) = @_;
                   7509:     #get student info
                   7510:     my $classlist=&Apache::loncoursedata::get_classlist();
                   7511:     my %idmap=&username_to_idmap($classlist);
                   7512: 
                   7513:     #get scantron line setup
1.257     albertel 7514:     my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
1.157     albertel 7515:     my ($scanlines,$scan_data)=&scantron_getfile();
1.582     raeburn  7516:     my $nav_error;
                   7517:     my $max_bubble=&scantron_get_maxbubble(\$nav_error);
                   7518:     if ($nav_error) {
                   7519:         return(1,$currentphase);
                   7520:     }
1.157     albertel 7521:     if (!$max_bubble) { $max_bubble=2**31; }
                   7522:     for (my $i=0;$i<=$scanlines->{'count'};$i++) {
1.200     albertel 7523: 	my $line=&scantron_get_line($scanlines,$scan_data,$i);
1.157     albertel 7524: 	if ($line=~/^[\s\cz]*$/) { next; }
                   7525: 	my $scan_record=&scantron_parse_scanline($line,$i,\%scantron_config,
                   7526: 						 $scan_data);
                   7527: 	if (!defined($$scan_record{'scantron.missingerror'})) { next; }
                   7528: 	my @to_correct;
1.470     foxr     7529: 	
                   7530: 	# Probably here's where the error is...
                   7531: 
1.157     albertel 7532: 	foreach my $missing (@{$$scan_record{'scantron.missingerror'}}) {
1.505     raeburn  7533:             my $lastbubble;
                   7534:             if ($missing =~ /^(\d+)\.(\d+)$/) {
                   7535:                my $question = $1;
                   7536:                my $subquestion = $2;
                   7537:                if (!defined($first_bubble_line{$question -1})) { next; }
                   7538:                my $first = $first_bubble_line{$question-1};
                   7539:                my @subans = split(/,/,$subdivided_bubble_lines{$question-1});
                   7540:                my $subcount = 1;
                   7541:                while ($subcount<$subquestion) {
                   7542:                    $first += $subans[$subcount-1];
                   7543:                    $subcount ++;
                   7544:                }
                   7545:                my $count = $subans[$subquestion-1];
                   7546:                $lastbubble = $first + $count;
                   7547:             } else {
                   7548:                 if (!defined($first_bubble_line{$missing - 1})) { next; }
                   7549:                 $lastbubble = $first_bubble_line{$missing - 1} + $bubble_lines_per_response{$missing - 1};
                   7550:             }
                   7551:             if ($lastbubble > $max_bubble) { next; }
1.157     albertel 7552: 	    push(@to_correct,$missing);
                   7553: 	}
                   7554: 	if (@to_correct) {
                   7555: 	    &scantron_get_correction($r,$i,$scan_record,\%scantron_config,
                   7556: 				     $line,'missingbubble',\@to_correct);
                   7557: 	    return (1,$currentphase);
                   7558: 	}
                   7559: 
                   7560:     }
                   7561:     return (0,$currentphase+1);
                   7562: }
                   7563: 
1.423     albertel 7564: 
1.82      albertel 7565: sub scantron_process_students {
1.608     www      7566:     my ($r,$symb) = @_;
1.513     foxr     7567: 
1.257     albertel 7568:     my (undef,undef,$sequence)=&Apache::lonnet::decode_symb($env{'form.selectpage'});
1.513     foxr     7569:     if (!$symb) {
                   7570: 	return '';
                   7571:     }
1.324     albertel 7572:     my $default_form_data=&defaultFormData($symb);
1.82      albertel 7573: 
1.257     albertel 7574:     my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
1.157     albertel 7575:     my ($scanlines,$scan_data)=&scantron_getfile();
1.82      albertel 7576:     my $classlist=&Apache::loncoursedata::get_classlist();
                   7577:     my %idmap=&username_to_idmap($classlist);
1.132     bowersj2 7578:     my $navmap=Apache::lonnavmaps::navmap->new();
1.582     raeburn  7579:     unless (ref($navmap)) {
                   7580:         $r->print(&navmap_errormsg());
                   7581:         return '';
                   7582:     }  
1.83      albertel 7583:     my $map=$navmap->getResourceByUrl($sequence);
                   7584:     my @resources=$navmap->retrieveResources($map,\&scantron_filter,1,0);
1.557     raeburn  7585:     my (%grader_partids_by_symb,%grader_randomlists_by_symb);
                   7586:     &graders_resources_pass(\@resources,\%grader_partids_by_symb,
                   7587:                             \%grader_randomlists_by_symb);
1.586     raeburn  7588:     my $resource_error;
1.557     raeburn  7589:     foreach my $resource (@resources) {
1.586     raeburn  7590:         my $ressymb;
                   7591:         if (ref($resource)) {
                   7592:             $ressymb = $resource->symb();
                   7593:         } else {
                   7594:             $resource_error = 1;
                   7595:             last;
                   7596:         }
1.557     raeburn  7597:         my ($analysis,$parts) =
                   7598:             &scantron_partids_tograde($resource,$env{'request.course.id'},
                   7599:                                       $env{'user.name'},$env{'user.domain'},1);
                   7600:         $grader_partids_by_symb{$ressymb} = $parts;
                   7601:         if (ref($analysis) eq 'HASH') {
                   7602:             if (ref($analysis->{'parts_withrandomlist'}) eq 'ARRAY') {
                   7603:                 $grader_randomlists_by_symb{$ressymb} = 
                   7604:                     $analysis->{'parts_withrandomlist'};
                   7605:             }
                   7606:         }
                   7607:     }
1.586     raeburn  7608:     if ($resource_error) {
                   7609:         $r->print(&navmap_errormsg());
                   7610:         return '';
                   7611:     }
1.557     raeburn  7612: 
1.554     raeburn  7613:     my ($uname,$udom);
1.82      albertel 7614:     my $result= <<SCANTRONFORM;
1.81      albertel 7615: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="scantronupload">
                   7616:   <input type="hidden" name="command" value="scantron_configphase" />
                   7617:   $default_form_data
                   7618: SCANTRONFORM
1.82      albertel 7619:     $r->print($result);
                   7620: 
                   7621:     my @delayqueue;
1.542     raeburn  7622:     my (%completedstudents,%scandata);
1.140     albertel 7623:     
1.520     www      7624:     my $lock=&Apache::lonnet::set_lock(&mt('Grading bubblesheet exam'));
1.200     albertel 7625:     my $count=&get_todo_count($scanlines,$scan_data);
1.575     www      7626:     my %prog_state=&Apache::lonhtmlcommon::Create_PrgWin($r,'Bubblesheet Status',
                   7627:  				    'Bubblesheet Progress',$count,
1.195     albertel 7628: 				    'inline',undef,'scantronupload');
1.140     albertel 7629:     &Apache::lonhtmlcommon::Update_PrgWin($r,\%prog_state,
                   7630: 					  'Processing first student');
1.542     raeburn  7631:     $r->print('<br />');
1.140     albertel 7632:     my $start=&Time::HiRes::time();
1.158     albertel 7633:     my $i=-1;
1.542     raeburn  7634:     my $started;
1.447     foxr     7635: 
1.582     raeburn  7636:     my $nav_error;
                   7637:     &scantron_get_maxbubble(\$nav_error); # Need the bubble lines array to parse.
                   7638:     if ($nav_error) {
                   7639:         $r->print(&navmap_errormsg());
                   7640:         return '';
                   7641:     }
                   7642: 
1.513     foxr     7643:     # If an ssi failed in scantron_get_maxbubble, put an error message out to
                   7644:     # the user and return.
                   7645: 
                   7646:     if ($ssi_error) {
                   7647: 	$r->print("</form>");
                   7648: 	&ssi_print_error($r);
                   7649: 	$r->print(&show_grading_menu_form($symb));
1.520     www      7650:         &Apache::lonnet::remove_lock($lock);
1.513     foxr     7651: 	return '';		# Dunno why the other returns return '' rather than just returning.
                   7652:     }
1.447     foxr     7653: 
1.542     raeburn  7654:     my %lettdig = &letter_to_digits();
                   7655:     my $numletts = scalar(keys(%lettdig));
                   7656: 
1.157     albertel 7657:     while ($i<$scanlines->{'count'}) {
                   7658:  	($uname,$udom)=('','');
                   7659:  	$i++;
1.200     albertel 7660:  	my $line=&scantron_get_line($scanlines,$scan_data,$i);
1.157     albertel 7661:  	if ($line=~/^[\s\cz]*$/) { next; }
1.200     albertel 7662: 	if ($started) {
                   7663: 	    &Apache::lonhtmlcommon::Increment_PrgWin($r,\%prog_state,
                   7664: 						     'last student');
                   7665: 	}
                   7666: 	$started=1;
1.157     albertel 7667:  	my $scan_record=&scantron_parse_scanline($line,$i,\%scantron_config,
                   7668:  						 $scan_data);
                   7669:  	unless ($uname=&scantron_find_student($scan_record,$scan_data,
                   7670:  					      \%idmap,$i)) {
                   7671:   	    &scantron_add_delay(\@delayqueue,$line,
                   7672:  				'Unable to find a student that matches',1);
                   7673:  	    next;
                   7674:   	}
                   7675:  	if (exists $completedstudents{$uname}) {
                   7676:  	    &scantron_add_delay(\@delayqueue,$line,
                   7677:  				'Student '.$uname.' has multiple sheets',2);
                   7678:  	    next;
                   7679:  	}
                   7680:   	($uname,$udom)=split(/:/,$uname);
1.330     albertel 7681: 
1.586     raeburn  7682:         my (%partids_by_symb,$res_error);
1.554     raeburn  7683:         foreach my $resource (@resources) {
1.586     raeburn  7684:             my $ressymb;
                   7685:             if (ref($resource)) {
                   7686:                 $ressymb = $resource->symb();
                   7687:             } else {
                   7688:                 $res_error = 1;
                   7689:                 last;
                   7690:             }
1.557     raeburn  7691:             if ((exists($grader_randomlists_by_symb{$ressymb})) ||
                   7692:                 (ref($grader_partids_by_symb{$ressymb}) ne 'ARRAY')) {
                   7693:                 my ($analysis,$parts) =
                   7694:                     &scantron_partids_tograde($resource,$env{'request.course.id'},$uname,$udom);
                   7695:                 $partids_by_symb{$ressymb} = $parts;
                   7696:             } else {
                   7697:                 $partids_by_symb{$ressymb} = $grader_partids_by_symb{$ressymb};
                   7698:             }
1.554     raeburn  7699:         }
                   7700: 
1.586     raeburn  7701:         if ($res_error) {
                   7702:             &scantron_add_delay(\@delayqueue,$line,
                   7703:                                 'An error occurred while grading student '.$uname,2);
                   7704:             next;
                   7705:         }
                   7706: 
1.330     albertel 7707: 	&Apache::lonxml::clear_problem_counter();
1.514     raeburn  7708:   	&Apache::lonnet::appenv($scan_record);
1.376     albertel 7709: 
                   7710: 	if (&scantron_clear_skip($scanlines,$scan_data,$i)) {
                   7711: 	    &scantron_putfile($scanlines,$scan_data);
                   7712: 	}
1.161     albertel 7713: 	
1.542     raeburn  7714:         my $scancode;
                   7715:         if ((exists($scan_record->{'scantron.CODE'})) &&
                   7716:             (&Apache::lonnet::validCODE($scan_record->{'scantron.CODE'}))) {
                   7717:             $scancode = $scan_record->{'scantron.CODE'};
                   7718:         } else {
                   7719:             $scancode = '';
                   7720:         }
                   7721: 
                   7722:         if (&grade_student_bubbles($r,$uname,$udom,$scan_record,$scancode,
1.554     raeburn  7723:                                    \@resources,\%partids_by_symb) eq 'ssi_error') {
1.542     raeburn  7724:             $ssi_error = 0; # So end of handler error message does not trigger.
                   7725:             $r->print("</form>");
                   7726:             &ssi_print_error($r);
                   7727:             $r->print(&show_grading_menu_form($symb));
                   7728:             &Apache::lonnet::remove_lock($lock);
                   7729:             return '';      # Why return ''?  Beats me.
                   7730:         }
1.513     foxr     7731: 
1.140     albertel 7732: 	$completedstudents{$uname}={'line'=>$line};
1.542     raeburn  7733:         if ($env{'form.verifyrecord'}) {
                   7734:             my $lastpos = $env{'form.scantron_maxbubble'}*$scantron_config{'Qlength'};
                   7735:             my $studentdata = substr($line,$scantron_config{'Qstart'}-1,$lastpos);
                   7736:             chomp($studentdata);
                   7737:             $studentdata =~ s/\r$//;
                   7738:             my $studentrecord = '';
                   7739:             my $counter = -1;
                   7740:             foreach my $resource (@resources) {
1.554     raeburn  7741:                 my $ressymb = $resource->symb();
1.542     raeburn  7742:                 ($counter,my $recording) =
                   7743:                     &verify_scantron_grading($resource,$udom,$uname,$env{'request.course.id'},
1.554     raeburn  7744:                                              $counter,$studentdata,$partids_by_symb{$ressymb},
1.542     raeburn  7745:                                              \%scantron_config,\%lettdig,$numletts);
                   7746:                 $studentrecord .= $recording;
                   7747:             }
                   7748:             if ($studentrecord ne $studentdata) {
1.554     raeburn  7749:                 &Apache::lonxml::clear_problem_counter();
                   7750:                 if (&grade_student_bubbles($r,$uname,$udom,$scan_record,$scancode,
                   7751:                                            \@resources,\%partids_by_symb) eq 'ssi_error') {
                   7752:                     $ssi_error = 0; # So end of handler error message does not trigger.
                   7753:                     $r->print("</form>");
                   7754:                     &ssi_print_error($r);
                   7755:                     $r->print(&show_grading_menu_form($symb));
                   7756:                     &Apache::lonnet::remove_lock($lock);
                   7757:                     delete($completedstudents{$uname});
                   7758:                     return '';
                   7759:                 }
1.542     raeburn  7760:                 $counter = -1;
                   7761:                 $studentrecord = '';
                   7762:                 foreach my $resource (@resources) {
1.554     raeburn  7763:                     my $ressymb = $resource->symb();
1.542     raeburn  7764:                     ($counter,my $recording) =
                   7765:                         &verify_scantron_grading($resource,$udom,$uname,$env{'request.course.id'},
1.554     raeburn  7766:                                                  $counter,$studentdata,$partids_by_symb{$ressymb},
1.542     raeburn  7767:                                                  \%scantron_config,\%lettdig,$numletts);
                   7768:                     $studentrecord .= $recording;
                   7769:                 }
                   7770:                 if ($studentrecord ne $studentdata) {
                   7771:                     $r->print('<p><span class="LC_error">');
                   7772:                     if ($scancode eq '') {
                   7773:                         $r->print(&mt('Mismatch grading bubble sheet for user: [_1] with ID: [_2].',
                   7774:                                   $uname.':'.$udom,$scan_record->{'scantron.ID'}));
                   7775:                     } else {
                   7776:                         $r->print(&mt('Mismatch grading bubble sheet for user: [_1] with ID: [_2] and CODE: [_3].',
                   7777:                                   $uname.':'.$udom,$scan_record->{'scantron.ID'},$scancode));
                   7778:                     }
                   7779:                     $r->print('</span><br />'.&Apache::loncommon::start_data_table()."\n".
                   7780:                               &Apache::loncommon::start_data_table_header_row()."\n".
                   7781:                               '<th>'.&mt('Source').'</th><th>'.&mt('Bubbled responses').'</th>'.
                   7782:                               &Apache::loncommon::end_data_table_header_row()."\n".
                   7783:                               &Apache::loncommon::start_data_table_row().
                   7784:                               '<td>'.&mt('Bubble Sheet').'</td>'.
                   7785:                               '<td><span class="LC_nobreak">'.$studentdata.'</span></td>'.
                   7786:                               &Apache::loncommon::end_data_table_row().
                   7787:                               &Apache::loncommon::start_data_table_row().
                   7788:                               '<td>Stored submissions</td>'.
                   7789:                               '<td><span class="LC_nobreak">'.$studentrecord.'</span></td>'."\n".
                   7790:                               &Apache::loncommon::end_data_table_row().
                   7791:                               &Apache::loncommon::end_data_table().'</p>');
                   7792:                 } else {
                   7793:                     $r->print('<br /><span class="LC_warning">'.
                   7794:                              &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 />'.
                   7795:                              &mt("As a consequence, this user's submission history records two tries.").
                   7796:                                  '</span><br />');
                   7797:                 }
                   7798:             }
                   7799:         }
1.543     raeburn  7800:         if (&Apache::loncommon::connection_aborted($r)) { last; }
1.140     albertel 7801:     } continue {
1.330     albertel 7802: 	&Apache::lonxml::clear_problem_counter();
1.552     raeburn  7803: 	&Apache::lonnet::delenv('scantron.');
1.82      albertel 7804:     }
1.140     albertel 7805:     &Apache::lonhtmlcommon::Close_PrgWin($r,\%prog_state);
1.520     www      7806:     &Apache::lonnet::remove_lock($lock);
1.172     albertel 7807: #    my $lasttime = &Time::HiRes::time()-$start;
                   7808: #    $r->print("<p>took $lasttime</p>");
1.140     albertel 7809: 
1.200     albertel 7810:     $r->print("</form>");
1.324     albertel 7811:     $r->print(&show_grading_menu_form($symb));
1.157     albertel 7812:     return '';
1.75      albertel 7813: }
1.157     albertel 7814: 
1.557     raeburn  7815: sub graders_resources_pass {
                   7816:     my ($resources,$grader_partids_by_symb,$grader_randomlists_by_symb) = @_;
                   7817:     if ((ref($resources) eq 'ARRAY') && (ref($grader_partids_by_symb)) && 
                   7818:         (ref($grader_randomlists_by_symb) eq 'HASH')) {
                   7819:         foreach my $resource (@{$resources}) {
                   7820:             my $ressymb = $resource->symb();
                   7821:             my ($analysis,$parts) =
                   7822:                 &scantron_partids_tograde($resource,$env{'request.course.id'},
                   7823:                                           $env{'user.name'},$env{'user.domain'},1);
                   7824:             $grader_partids_by_symb->{$ressymb} = $parts;
                   7825:             if (ref($analysis) eq 'HASH') {
                   7826:                 if (ref($analysis->{'parts_withrandomlist'}) eq 'ARRAY') {
                   7827:                     $grader_randomlists_by_symb->{$ressymb} =
                   7828:                         $analysis->{'parts_withrandomlist'};
                   7829:                 }
                   7830:             }
                   7831:         }
                   7832:     }
                   7833:     return;
                   7834: }
                   7835: 
1.542     raeburn  7836: sub grade_student_bubbles {
1.554     raeburn  7837:     my ($r,$uname,$udom,$scan_record,$scancode,$resources,$parts) = @_;
                   7838:     if (ref($resources) eq 'ARRAY') {
                   7839:         my $count = 0;
                   7840:         foreach my $resource (@{$resources}) {
                   7841:             my $ressymb = $resource->symb();
                   7842:             my %form = ('submitted'      => 'scantron',
                   7843:                         'grade_target'   => 'grade',
                   7844:                         'grade_username' => $uname,
                   7845:                         'grade_domain'   => $udom,
                   7846:                         'grade_courseid' => $env{'request.course.id'},
                   7847:                         'grade_symb'     => $ressymb,
                   7848:                         'CODE'           => $scancode
                   7849:                        );
                   7850:             if (ref($parts) eq 'HASH') {
                   7851:                 if (ref($parts->{$ressymb}) eq 'ARRAY') {
                   7852:                     foreach my $part (@{$parts->{$ressymb}}) {
                   7853:                         $form{'scantron_questnum_start.'.$part} =
                   7854:                             1+$env{'form.scantron.first_bubble_line.'.$count};
                   7855:                         $count++;
                   7856:                     }
                   7857:                 }
                   7858:             }
                   7859:             my $result=&ssi_with_retries($resource->src(),$ssi_retries,%form);
                   7860:             return 'ssi_error' if ($ssi_error);
                   7861:             last if (&Apache::loncommon::connection_aborted($r));
                   7862:         }
1.542     raeburn  7863:     }
                   7864:     return;
                   7865: }
                   7866: 
1.157     albertel 7867: sub scantron_upload_scantron_data {
1.608     www      7868:     my ($r,$symb)=@_;
1.565     raeburn  7869:     my $dom = $env{'request.role.domain'};
                   7870:     my $domdesc = &Apache::lonnet::domain($dom,'description');
                   7871:     $r->print(&Apache::loncommon::coursebrowser_javascript($dom));
1.157     albertel 7872:     my $select_link=&Apache::loncommon::selectcourse_link('rules','courseid',
1.181     albertel 7873: 							  'domainid',
1.565     raeburn  7874: 							  'coursename',$dom);
                   7875:     my $syllabuslink = '<a href="javascript:ToSyllabus();">'.&mt('Syllabus').'</a>'.
                   7876:                        ('&nbsp'x2).&mt('(shows course personnel)'); 
1.608     www      7877:     my $default_form_data=&defaultFormData($symb);
1.579     raeburn  7878:     my $nofile_alert = &mt('Please use the browse button to select a file from your local directory.');
                   7879:     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 7880:     $r->print(&Apache::lonhtmlcommon::scripttag('
1.157     albertel 7881:     function checkUpload(formname) {
                   7882: 	if (formname.upfile.value == "") {
1.579     raeburn  7883: 	    alert("'.$nofile_alert.'");
1.157     albertel 7884: 	    return false;
                   7885: 	}
1.565     raeburn  7886:         if (formname.courseid.value == "") {
1.579     raeburn  7887:             alert("'.$nocourseid_alert.'");
1.565     raeburn  7888:             return false;
                   7889:         }
1.157     albertel 7890: 	formname.submit();
                   7891:     }
1.565     raeburn  7892: 
                   7893:     function ToSyllabus() {
                   7894:         var cdom = '."'$dom'".';
                   7895:         var cnum = document.rules.courseid.value;
                   7896:         if (cdom == "" || cdom == null) {
                   7897:             return;
                   7898:         }
                   7899:         if (cnum == "" || cnum == null) {
                   7900:            return;
                   7901:         }
                   7902:         syllwin=window.open("/public/"+cdom+"/"+cnum+"/syllabus","LONCAPASyllabus",
                   7903:                             "height=350,width=350,scrollbars=yes,menubar=no");
                   7904:         return;
                   7905:     }
                   7906: 
1.597     wenzelju 7907: '));
                   7908:     $r->print('
1.566     raeburn  7909: <h3>'.&mt('Send scanned bubblesheet data to a course').'</h3>
                   7910: 
1.492     albertel 7911: <form enctype="multipart/form-data" action="/adm/grades" name="rules" method="post">
1.565     raeburn  7912: '.$default_form_data.
                   7913:   &Apache::lonhtmlcommon::start_pick_box().
                   7914:   &Apache::lonhtmlcommon::row_title(&mt('Course ID')).
                   7915:   '<input name="courseid" type="text" size="30" />'.$select_link.
                   7916:   &Apache::lonhtmlcommon::row_closure().
                   7917:   &Apache::lonhtmlcommon::row_title(&mt('Course Name')).
                   7918:   '<input name="coursename" type="text" size="30" />'.$syllabuslink.
                   7919:   &Apache::lonhtmlcommon::row_closure().
                   7920:   &Apache::lonhtmlcommon::row_title(&mt('Domain')).
                   7921:   '<input name="domainid" type="hidden" />'.$domdesc.
                   7922:   &Apache::lonhtmlcommon::row_closure().
                   7923:   &Apache::lonhtmlcommon::row_title(&mt('File to upload')).
                   7924:   '<input type="file" name="upfile" size="50" />'.
                   7925:   &Apache::lonhtmlcommon::row_closure(1).
                   7926:   &Apache::lonhtmlcommon::end_pick_box().'<br />
                   7927: 
1.492     albertel 7928: <input name="command" value="scantronupload_save" type="hidden" />
1.589     bisitz   7929: <input type="button" onclick="javascript:checkUpload(this.form);" value="'.&mt('Upload Bubblesheet Data').'" />
1.157     albertel 7930: </form>
1.492     albertel 7931: ');
1.157     albertel 7932:     return '';
                   7933: }
                   7934: 
1.423     albertel 7935: 
1.157     albertel 7936: sub scantron_upload_scantron_data_save {
1.608     www      7937:     my($r,$symb)=@_;
1.182     albertel 7938:     my $doanotherupload=
                   7939: 	'<br /><form action="/adm/grades" method="post">'."\n".
                   7940: 	'<input type="hidden" name="command" value="scantronupload" />'."\n".
1.492     albertel 7941: 	'<input type="submit" name="submit" value="'.&mt('Do Another Upload').'" />'."\n".
1.182     albertel 7942: 	'</form>'."\n";
1.257     albertel 7943:     if (!&Apache::lonnet::allowed('usc',$env{'form.domainid'}) &&
1.162     albertel 7944: 	!&Apache::lonnet::allowed('usc',
1.257     albertel 7945: 			    $env{'form.domainid'}.'_'.$env{'form.courseid'})) {
1.575     www      7946: 	$r->print(&mt("You are not allowed to upload bubblesheet data to the requested course.")."<br />");
1.182     albertel 7947: 	if ($symb) {
1.324     albertel 7948: 	    $r->print(&show_grading_menu_form($symb));
1.182     albertel 7949: 	} else {
                   7950: 	    $r->print($doanotherupload);
                   7951: 	}
1.162     albertel 7952: 	return '';
                   7953:     }
1.257     albertel 7954:     my %coursedata=&Apache::lonnet::coursedescription($env{'form.domainid'}.'_'.$env{'form.courseid'});
1.568     raeburn  7955:     my $uploadedfile;
1.567     raeburn  7956:     $r->print('<h3>'.&mt("Uploading file to [_1]",$coursedata{'description'}).'</h3>');
1.257     albertel 7957:     if (length($env{'form.upfile'}) < 2) {
1.568     raeburn  7958:         $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 7959:     } else {
1.568     raeburn  7960:         my $result = 
                   7961:             &Apache::lonnet::userfileupload('upfile','','scantron','','','',
                   7962:                                             $env{'form.courseid'},$env{'form.domainid'});
                   7963: 	if ($result =~ m{^/uploaded/}) {
1.567     raeburn  7964: 	    $r->print(&mt('[_1]Success:[_2] Successfully uploaded [_3] bytes of data into location: [_4]',
                   7965:                           '<span class="LC_success">','</span>',(length($env{'form.upfile'})-1),
                   7966: 			  '<span class="LC_filename">'.$result.'</span>'));
1.568     raeburn  7967:             ($uploadedfile) = ($result =~ m{/([^/]+)$});
1.567     raeburn  7968:             $r->print(&validate_uploaded_scantron_file($env{'form.domainid'},
1.568     raeburn  7969:                                                        $env{'form.courseid'},$uploadedfile));
1.210     albertel 7970: 	} else {
1.567     raeburn  7971: 	    $r->print(&mt('[_1]Error:[_2] An error ([_3]) occurred when attempting to upload the file, [_4]',
                   7972:                           '<span class="LC_error">','</span>',$result,
1.568     raeburn  7973: 			  '<span class="LC_filename">'.&HTML::Entities::encode($env{'form.upfile.filename'},'<>&"').'</span>'));
1.183     albertel 7974: 	}
                   7975:     }
1.174     albertel 7976:     if ($symb) {
1.209     ng       7977: 	$r->print(&scantron_selectphase($r,$uploadedfile));
1.174     albertel 7978:     } else {
1.182     albertel 7979: 	$r->print($doanotherupload);
1.174     albertel 7980:     }
1.157     albertel 7981:     return '';
                   7982: }
                   7983: 
1.567     raeburn  7984: sub validate_uploaded_scantron_file {
                   7985:     my ($cdom,$cname,$fname) = @_;
                   7986:     my $scanlines=&Apache::lonnet::getfile('/uploaded/'.$cdom.'/'.$cname.'/'.$fname);
                   7987:     my @lines;
                   7988:     if ($scanlines ne '-1') {
                   7989:         @lines=split("\n",$scanlines,-1);
                   7990:     }
                   7991:     my $output;
                   7992:     if (@lines) {
                   7993:         my (%counts,$max_match_format);
                   7994:         my ($max_match_count,$max_match_pct) = (0,0);
                   7995:         my $classlist = &Apache::loncoursedata::get_classlist($cdom,$cname);
                   7996:         my %idmap = &username_to_idmap($classlist);
                   7997:         foreach my $key (keys(%idmap)) {
                   7998:             my $lckey = lc($key);
                   7999:             $idmap{$lckey} = $idmap{$key};
                   8000:         }
                   8001:         my %unique_formats;
                   8002:         my @formatlines = &get_scantronformat_file();
                   8003:         foreach my $line (@formatlines) {
                   8004:             chomp($line);
                   8005:             my @config = split(/:/,$line);
                   8006:             my $idstart = $config[5];
                   8007:             my $idlength = $config[6];
                   8008:             if (($idstart ne '') && ($idlength > 0)) {
                   8009:                 if (ref($unique_formats{$idstart.':'.$idlength}) eq 'ARRAY') {
                   8010:                     push(@{$unique_formats{$idstart.':'.$idlength}},$config[0].':'.$config[1]); 
                   8011:                 } else {
                   8012:                     $unique_formats{$idstart.':'.$idlength} = [$config[0].':'.$config[1]];
                   8013:                 }
                   8014:             }
                   8015:         }
                   8016:         foreach my $key (keys(%unique_formats)) {
                   8017:             my ($idstart,$idlength) = split(':',$key);
                   8018:             %{$counts{$key}} = (
                   8019:                                'found'   => 0,
                   8020:                                'total'   => 0,
                   8021:                               );
                   8022:             foreach my $line (@lines) {
                   8023:                 next if ($line =~ /^#/);
                   8024:                 next if ($line =~ /^[\s\cz]*$/);
                   8025:                 my $id = substr($line,$idstart-1,$idlength);
                   8026:                 $id = lc($id);
                   8027:                 if (exists($idmap{$id})) {
                   8028:                     $counts{$key}{'found'} ++;
                   8029:                 }
                   8030:                 $counts{$key}{'total'} ++;
                   8031:             }
                   8032:             if ($counts{$key}{'total'}) {
                   8033:                 my $percent_match = (100*$counts{$key}{'found'})/($counts{$key}{'total'});
                   8034:                 if (($max_match_format eq '') || ($percent_match > $max_match_pct)) {
                   8035:                     $max_match_pct = $percent_match;
                   8036:                     $max_match_format = $key;
                   8037:                     $max_match_count = $counts{$key}{'total'};
                   8038:                 }
                   8039:             }
                   8040:         }
                   8041:         if (ref($unique_formats{$max_match_format}) eq 'ARRAY') {
                   8042:             my $format_descs;
                   8043:             my $numwithformat = @{$unique_formats{$max_match_format}};
                   8044:             for (my $i=0; $i<$numwithformat; $i++) {
                   8045:                 my ($name,$desc) = split(':',$unique_formats{$max_match_format}[$i]);
                   8046:                 if ($i<$numwithformat-2) {
                   8047:                     $format_descs .= '"<i>'.$desc.'</i>", ';
                   8048:                 } elsif ($i==$numwithformat-2) {
                   8049:                     $format_descs .= '"<i>'.$desc.'</i>" '.&mt('and').' ';
                   8050:                 } elsif ($i==$numwithformat-1) {
                   8051:                     $format_descs .= '"<i>'.$desc.'</i>"';
                   8052:                 }
                   8053:             }
                   8054:             my $showpct = sprintf("%.0f",$max_match_pct).'%';
                   8055:             $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).
                   8056:                        '<br />'.&mt('A low percentage of matches results from one of the following:').'<ul>'.
                   8057:                        '<li>'.&mt('The file was uploaded to the wrong course').'</li>'.
                   8058:                        '<li>'.&mt('The data are not in the format expected for the domain: [_1]',
                   8059:                                   '<i>'.$cdom.'</i>').'</li>'.
                   8060:                        '<li>'.&mt('Students did not bubble their IDs, or mis-bubbled them').'</li>'.
                   8061:                        '<li>'.&mt('The course roster is not up to date').'</li>'.
                   8062:                        '</ul>';
                   8063:         }
                   8064:     } else {
                   8065:         $output = '<span class="LC_warning">'.&mt('Uploaded file contained no data').'</span>';
                   8066:     }
                   8067:     return $output;
                   8068: }
                   8069: 
1.202     albertel 8070: sub valid_file {
                   8071:     my ($requested_file)=@_;
                   8072:     foreach my $filename (sort(&scantron_filenames())) {
                   8073: 	if ($requested_file eq $filename) { return 1; }
                   8074:     }
                   8075:     return 0;
                   8076: }
                   8077: 
                   8078: sub scantron_download_scantron_data {
1.608     www      8079:     my ($r,$symb)=@_;
                   8080:     my $default_form_data=&defaultFormData($symb);
1.257     albertel 8081:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   8082:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
                   8083:     my $file=$env{'form.scantron_selectfile'};
1.202     albertel 8084:     if (! &valid_file($file)) {
1.492     albertel 8085: 	$r->print('
1.202     albertel 8086: 	<p>
1.492     albertel 8087: 	    '.&mt('The requested file name was invalid.').'
1.202     albertel 8088:         </p>
1.492     albertel 8089: ');
1.608     www      8090: 	$r->print(&show_grading_menu_form($symb));
1.202     albertel 8091: 	return;
                   8092:     }
                   8093:     my $orig='/uploaded/'.$cdom.'/'.$cname.'/scantron_orig_'.$file;
                   8094:     my $corrected='/uploaded/'.$cdom.'/'.$cname.'/scantron_corrected_'.$file;
                   8095:     my $skipped='/uploaded/'.$cdom.'/'.$cname.'/scantron_skipped_'.$file;
                   8096:     &Apache::lonnet::allowuploaded('/adm/grades',$orig);
                   8097:     &Apache::lonnet::allowuploaded('/adm/grades',$corrected);
                   8098:     &Apache::lonnet::allowuploaded('/adm/grades',$skipped);
1.492     albertel 8099:     $r->print('
1.202     albertel 8100:     <p>
1.492     albertel 8101: 	'.&mt('[_1]Original[_2] file as uploaded by the scantron office.',
                   8102: 	      '<a href="'.$orig.'">','</a>').'
1.202     albertel 8103:     </p>
                   8104:     <p>
1.492     albertel 8105: 	'.&mt('[_1]Corrections[_2], a file of corrected records that were used in grading.',
                   8106: 	      '<a href="'.$corrected.'">','</a>').'
1.202     albertel 8107:     </p>
                   8108:     <p>
1.492     albertel 8109: 	'.&mt('[_1]Skipped[_2], a file of records that were skipped.',
                   8110: 	      '<a href="'.$skipped.'">','</a>').'
1.202     albertel 8111:     </p>
1.492     albertel 8112: ');
1.608     www      8113:     $r->print(&show_grading_menu_form($symb));
1.202     albertel 8114:     return '';
                   8115: }
1.157     albertel 8116: 
1.523     raeburn  8117: sub checkscantron_results {
1.608     www      8118:     my ($r,$symb) = @_;
1.523     raeburn  8119:     if (!$symb) {return '';}
                   8120:     my $grading_menu_button=&show_grading_menu_form($symb);
                   8121:     my $cid = $env{'request.course.id'};
1.542     raeburn  8122:     my %lettdig = &letter_to_digits();
1.523     raeburn  8123:     my $numletts = scalar(keys(%lettdig));
                   8124:     my $cnum = $env{'course.'.$cid.'.num'};
                   8125:     my $cdom = $env{'course.'.$cid.'.domain'};
                   8126:     my (undef, undef, $sequence) = &Apache::lonnet::decode_symb($env{'form.selectpage'});
                   8127:     my %record;
                   8128:     my %scantron_config =
                   8129:         &Apache::grades::get_scantron_config($env{'form.scantron_format'});
                   8130:     my ($scanlines,$scan_data)=&Apache::grades::scantron_getfile();
                   8131:     my $classlist=&Apache::loncoursedata::get_classlist();
                   8132:     my %idmap=&Apache::grades::username_to_idmap($classlist);
                   8133:     my $navmap=Apache::lonnavmaps::navmap->new();
1.582     raeburn  8134:     unless (ref($navmap)) {
                   8135:         $r->print(&navmap_errormsg());
                   8136:         return '';
                   8137:     }
1.523     raeburn  8138:     my $map=$navmap->getResourceByUrl($sequence);
1.557     raeburn  8139:     my @resources=$navmap->retrieveResources($map,\&scantron_filter,1,0);
                   8140:     my (%grader_partids_by_symb,%grader_randomlists_by_symb);
                   8141:     &graders_resources_pass(\@resources,\%grader_partids_by_symb,                             \%grader_randomlists_by_symb);
                   8142: 
1.554     raeburn  8143:     my ($uname,$udom);
1.523     raeburn  8144:     my (%scandata,%lastname,%bylast);
                   8145:     $r->print('
                   8146: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="checkscantron">'."\n");
                   8147: 
                   8148:     my @delayqueue;
                   8149:     my %completedstudents;
                   8150: 
                   8151:     my $count=&Apache::grades::get_todo_count($scanlines,$scan_data);
1.581     www      8152:     my %prog_state=&Apache::lonhtmlcommon::Create_PrgWin($r,'Bubblesheet/Submissions Comparison Status',
                   8153:                                     'Progress of Bubblesheet Data/Submission Records Comparison',$count,
1.523     raeburn  8154:                                     'inline',undef,'checkscantron');
1.546     raeburn  8155:     my ($username,$domain,$started);
1.582     raeburn  8156:     my $nav_error;
                   8157:     &scantron_get_maxbubble(\$nav_error); # Need the bubble lines array to parse.
                   8158:     if ($nav_error) {
                   8159:         $r->print(&navmap_errormsg());
                   8160:         return '';
                   8161:     }
1.523     raeburn  8162: 
                   8163:     &Apache::lonhtmlcommon::Update_PrgWin($r,\%prog_state,
                   8164:                                           'Processing first student');
                   8165:     my $start=&Time::HiRes::time();
                   8166:     my $i=-1;
                   8167: 
                   8168:     while ($i<$scanlines->{'count'}) {
                   8169:         ($username,$domain,$uname)=('','','');
                   8170:         $i++;
                   8171:         my $line=&Apache::grades::scantron_get_line($scanlines,$scan_data,$i);
                   8172:         if ($line=~/^[\s\cz]*$/) { next; }
                   8173:         if ($started) {
                   8174:             &Apache::lonhtmlcommon::Increment_PrgWin($r,\%prog_state,
                   8175:                                                      'last student');
                   8176:         }
                   8177:         $started=1;
                   8178:         my $scan_record=
                   8179:             &Apache::grades::scantron_parse_scanline($line,$i,\%scantron_config,
                   8180:                                                      $scan_data);
                   8181:         unless ($uname=&Apache::grades::scantron_find_student($scan_record,$scan_data,
                   8182:                                                               \%idmap,$i)) {
                   8183:             &Apache::grades::scantron_add_delay(\@delayqueue,$line,
                   8184:                                 'Unable to find a student that matches',1);
                   8185:             next;
                   8186:         }
                   8187:         if (exists $completedstudents{$uname}) {
                   8188:             &Apache::grades::scantron_add_delay(\@delayqueue,$line,
                   8189:                                 'Student '.$uname.' has multiple sheets',2);
                   8190:             next;
                   8191:         }
                   8192:         my $pid = $scan_record->{'scantron.ID'};
                   8193:         $lastname{$pid} = $scan_record->{'scantron.LastName'};
                   8194:         push(@{$bylast{$lastname{$pid}}},$pid);
                   8195:         my $lastpos = $env{'form.scantron_maxbubble'}*$scantron_config{'Qlength'};
                   8196:         $scandata{$pid} = substr($line,$scantron_config{'Qstart'}-1,$lastpos);
                   8197:         chomp($scandata{$pid});
                   8198:         $scandata{$pid} =~ s/\r$//;
                   8199:         ($username,$domain)=split(/:/,$uname);
                   8200:         my $counter = -1;
                   8201:         foreach my $resource (@resources) {
1.557     raeburn  8202:             my $parts;
1.554     raeburn  8203:             my $ressymb = $resource->symb();
1.557     raeburn  8204:             if ((exists($grader_randomlists_by_symb{$ressymb})) ||
                   8205:                 (ref($grader_partids_by_symb{$ressymb}) ne 'ARRAY')) {
                   8206:                 (my $analysis,$parts) =
                   8207:                     &scantron_partids_tograde($resource,$env{'request.course.id'},$username,$domain);
                   8208:             } else {
                   8209:                 $parts = $grader_partids_by_symb{$ressymb};
                   8210:             }
1.542     raeburn  8211:             ($counter,my $recording) =
                   8212:                 &verify_scantron_grading($resource,$domain,$username,$cid,$counter,
1.554     raeburn  8213:                                          $scandata{$pid},$parts,
1.542     raeburn  8214:                                          \%scantron_config,\%lettdig,$numletts);
                   8215:             $record{$pid} .= $recording;
1.523     raeburn  8216:         }
                   8217:     }
                   8218:     &Apache::lonhtmlcommon::Close_PrgWin($r,\%prog_state);
                   8219:     $r->print('<br />');
                   8220:     my ($okstudents,$badstudents,$numstudents,$passed,$failed);
                   8221:     $passed = 0;
                   8222:     $failed = 0;
                   8223:     $numstudents = 0;
                   8224:     foreach my $last (sort(keys(%bylast))) {
                   8225:         if (ref($bylast{$last}) eq 'ARRAY') {
                   8226:             foreach my $pid (sort(@{$bylast{$last}})) {
                   8227:                 my $showscandata = $scandata{$pid};
                   8228:                 my $showrecord = $record{$pid};
                   8229:                 $showscandata =~ s/\s/&nbsp;/g;
                   8230:                 $showrecord =~ s/\s/&nbsp;/g;
                   8231:                 if ($scandata{$pid} eq $record{$pid}) {
                   8232:                     my $css_class = ($passed % 2)?'LC_odd_row':'LC_even_row';
                   8233:                     $okstudents .= '<tr class="'.$css_class.'">'.
1.581     www      8234: '<td>'.&mt('Bubblesheet').'</td><td>'.$showscandata.'</td><td rowspan="2">'.$last.'</td><td rowspan="2">'.$pid.'</td>'."\n".
1.523     raeburn  8235: '</tr>'."\n".
                   8236: '<tr class="'.$css_class.'">'."\n".
                   8237: '<td>Submissions</td><td>'.$showrecord.'</td></tr>'."\n";
                   8238:                     $passed ++;
                   8239:                 } else {
                   8240:                     my $css_class = ($failed % 2)?'LC_odd_row':'LC_even_row';
1.581     www      8241:                     $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  8242: '</tr>'."\n".
                   8243: '<tr class="'.$css_class.'">'."\n".
                   8244: '<td>Submissions</td><td><span class="LC_nobreak">'.$record{$pid}.'</span></td>'."\n".
                   8245: '</tr>'."\n";
                   8246:                     $failed ++;
                   8247:                 }
                   8248:                 $numstudents ++;
                   8249:             }
                   8250:         }
                   8251:     }
1.572     www      8252:     $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  8253:     $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>');
                   8254:     if ($passed) {
1.572     www      8255:         $r->print(&mt('Students with exact correspondence between bubblesheet data and submissions are as follows:').'<br /><br />');
1.523     raeburn  8256:         $r->print(&Apache::loncommon::start_data_table()."\n".
                   8257:                  &Apache::loncommon::start_data_table_header_row()."\n".
                   8258:                  '<th>'.&mt('Source').'</th><th>'.&mt('Bubble records').'</th><th>'.&mt('Name').'</th><th>'.&mt('ID').'</th>'.
                   8259:                  &Apache::loncommon::end_data_table_header_row()."\n".
                   8260:                  $okstudents."\n".
                   8261:                  &Apache::loncommon::end_data_table().'<br />');
                   8262:     }
                   8263:     if ($failed) {
1.572     www      8264:         $r->print(&mt('Students with differences between bubblesheet data and submissions are as follows:').'<br /><br />');
1.523     raeburn  8265:         $r->print(&Apache::loncommon::start_data_table()."\n".
                   8266:                  &Apache::loncommon::start_data_table_header_row()."\n".
                   8267:                  '<th>'.&mt('Source').'</th><th>'.&mt('Bubble records').'</th><th>'.&mt('Name').'</th><th>'.&mt('ID').'</th>'.
                   8268:                  &Apache::loncommon::end_data_table_header_row()."\n".
                   8269:                  $badstudents."\n".
                   8270:                  &Apache::loncommon::end_data_table()).'<br />'.
1.572     www      8271:                  &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  8272:     }
                   8273:     $r->print('</form><br />'.$grading_menu_button);
                   8274:     return;
                   8275: }
                   8276: 
1.542     raeburn  8277: sub verify_scantron_grading {
1.554     raeburn  8278:     my ($resource,$domain,$username,$cid,$counter,$scandata,$partids,
1.542     raeburn  8279:         $scantron_config,$lettdig,$numletts) = @_;
                   8280:     my ($record,%expected,%startpos);
                   8281:     return ($counter,$record) if (!ref($resource));
                   8282:     return ($counter,$record) if (!$resource->is_problem());
                   8283:     my $symb = $resource->symb();
1.554     raeburn  8284:     return ($counter,$record) if (ref($partids) ne 'ARRAY');
                   8285:     foreach my $part_id (@{$partids}) {
1.542     raeburn  8286:         $counter ++;
                   8287:         $expected{$part_id} = 0;
                   8288:         if ($env{"form.scantron.sub_bubblelines.$counter"}) {
                   8289:             my @sub_lines = split(/,/,$env{"form.scantron.sub_bubblelines.$counter"});
                   8290:             foreach my $item (@sub_lines) {
                   8291:                 $expected{$part_id} += $item;
                   8292:             }
                   8293:         } else {
                   8294:             $expected{$part_id} = $env{"form.scantron.bubblelines.$counter"};
                   8295:         }
                   8296:         $startpos{$part_id} = $env{"form.scantron.first_bubble_line.$counter"};
                   8297:     }
                   8298:     if ($symb) {
                   8299:         my %recorded;
                   8300:         my (%returnhash) = &Apache::lonnet::restore($symb,$cid,$domain,$username);
                   8301:         if ($returnhash{'version'}) {
                   8302:             my %lasthash=();
                   8303:             my $version;
                   8304:             for ($version=1;$version<=$returnhash{'version'};$version++) {
                   8305:                 foreach my $key (sort(split(/\:/,$returnhash{$version.':keys'}))) {
                   8306:                     $lasthash{$key}=$returnhash{$version.':'.$key};
                   8307:                 }
                   8308:             }
                   8309:             foreach my $key (keys(%lasthash)) {
                   8310:                 if ($key =~ /\.scantron$/) {
                   8311:                     my $value = &unescape($lasthash{$key});
                   8312:                     my ($part_id) = ($key =~ /^resource\.(.+)\.scantron$/);
                   8313:                     if ($value eq '') {
                   8314:                         for (my $i=0; $i<$expected{$part_id}; $i++) {
                   8315:                             for (my $j=0; $j<$scantron_config->{'length'}; $j++) {
                   8316:                                 $recorded{$part_id} .= $scantron_config->{'Qoff'};
                   8317:                             }
                   8318:                         }
                   8319:                     } else {
                   8320:                         my @tocheck;
                   8321:                         my @items = split(//,$value);
                   8322:                         if (($scantron_config->{'Qon'} eq 'letter') ||
                   8323:                             ($scantron_config->{'Qon'} eq 'number')) {
                   8324:                             if (@items < $expected{$part_id}) {
                   8325:                                 my $fragment = substr($scandata,$startpos{$part_id},$expected{$part_id});
                   8326:                                 my @singles = split(//,$fragment);
                   8327:                                 foreach my $pos (@singles) {
                   8328:                                     if ($pos eq ' ') {
                   8329:                                         push(@tocheck,$pos);
                   8330:                                     } else {
                   8331:                                         my $next = shift(@items);
                   8332:                                         push(@tocheck,$next);
                   8333:                                     }
                   8334:                                 }
                   8335:                             } else {
                   8336:                                 @tocheck = @items;
                   8337:                             }
                   8338:                             foreach my $letter (@tocheck) {
                   8339:                                 if ($scantron_config->{'Qon'} eq 'letter') {
                   8340:                                     if ($letter !~ /^[A-J]$/) {
                   8341:                                         $letter = $scantron_config->{'Qoff'};
                   8342:                                     }
                   8343:                                     $recorded{$part_id} .= $letter;
                   8344:                                 } elsif ($scantron_config->{'Qon'} eq 'number') {
                   8345:                                     my $digit;
                   8346:                                     if ($letter !~ /^[A-J]$/) {
                   8347:                                         $digit = $scantron_config->{'Qoff'};
                   8348:                                     } else {
                   8349:                                         $digit = $lettdig->{$letter};
                   8350:                                     }
                   8351:                                     $recorded{$part_id} .= $digit;
                   8352:                                 }
                   8353:                             }
                   8354:                         } else {
                   8355:                             @tocheck = @items;
                   8356:                             for (my $i=0; $i<$expected{$part_id}; $i++) {
                   8357:                                 my $curr_sub = shift(@tocheck);
                   8358:                                 my $digit;
                   8359:                                 if ($curr_sub =~ /^[A-J]$/) {
                   8360:                                     $digit = $lettdig->{$curr_sub}-1;
                   8361:                                 }
                   8362:                                 if ($curr_sub eq 'J') {
                   8363:                                     $digit += scalar($numletts);
                   8364:                                 }
                   8365:                                 for (my $j=0; $j<$scantron_config->{'Qlength'}; $j++) {
                   8366:                                     if ($j == $digit) {
                   8367:                                         $recorded{$part_id} .= $scantron_config->{'Qon'};
                   8368:                                     } else {
                   8369:                                         $recorded{$part_id} .= $scantron_config->{'Qoff'};
                   8370:                                     }
                   8371:                                 }
                   8372:                             }
                   8373:                         }
                   8374:                     }
                   8375:                 }
                   8376:             }
                   8377:         }
1.554     raeburn  8378:         foreach my $part_id (@{$partids}) {
1.542     raeburn  8379:             if ($recorded{$part_id} eq '') {
                   8380:                 for (my $i=0; $i<$expected{$part_id}; $i++) {
                   8381:                     for (my $j=0; $j<$scantron_config->{'Qlength'}; $j++) {
                   8382:                         $recorded{$part_id} .= $scantron_config->{'Qoff'};
                   8383:                     }
                   8384:                 }
                   8385:             }
                   8386:             $record .= $recorded{$part_id};
                   8387:         }
                   8388:     }
                   8389:     return ($counter,$record);
                   8390: }
                   8391: 
                   8392: sub letter_to_digits { 
                   8393:     my %lettdig = (
                   8394:                     A => 1,
                   8395:                     B => 2,
                   8396:                     C => 3,
                   8397:                     D => 4,
                   8398:                     E => 5,
                   8399:                     F => 6,
                   8400:                     G => 7,
                   8401:                     H => 8,
                   8402:                     I => 9,
                   8403:                     J => 0,
                   8404:                   );
                   8405:     return %lettdig;
                   8406: }
                   8407: 
1.423     albertel 8408: 
1.75      albertel 8409: #-------- end of section for handling grading scantron forms -------
                   8410: #
                   8411: #-------------------------------------------------------------------
                   8412: 
1.72      ng       8413: #-------------------------- Menu interface -------------------------
                   8414: #
                   8415: #--- Show a Grading Menu button - Calls the next routine ---
                   8416: sub show_grading_menu_form {
1.324     albertel 8417:     my ($symb)=@_;
1.125     ng       8418:     my $result.='<br /><form action="/adm/grades" method="post">'."\n".
1.418     albertel 8419: 	'<input type="hidden" name="symb" value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
1.257     albertel 8420: 	'<input type="hidden" name="saveState"  value="'.$env{'form.saveState'}.'" />'."\n".
1.72      ng       8421: 	'<input type="hidden" name="command" value="gradingmenu" />'."\n".
1.478     albertel 8422: 	'<input type="submit" name="submit" value="'.&mt('Grading Menu').'" />'."\n".
1.72      ng       8423: 	'</form>'."\n";
                   8424:     return $result;
                   8425: }
                   8426: 
1.443     banghart 8427: sub grading_menu {
1.608     www      8428:     my ($request,$symb) = @_;
1.443     banghart 8429:     if (!$symb) {return '';}
                   8430: 
                   8431:     my %fields = ('symb'=>&Apache::lonenc::check_encrypt($symb),
1.598     www      8432:                   'command'=>'individual',
1.443     banghart 8433:                   'gradingMenu'=>1,
                   8434:                   'showgrading'=>"yes");
1.538     schulted 8435:     
1.598     www      8436:     my $url1a = &Apache::lonhtmlcommon::build_url('grades/',\%fields);
                   8437: 
                   8438:     $fields{'command'}='ungraded';
                   8439:     my $url1b=&Apache::lonhtmlcommon::build_url('grades/',\%fields);
                   8440: 
                   8441:     $fields{'command'}='table';
                   8442:     my $url1c=&Apache::lonhtmlcommon::build_url('grades/',\%fields);
                   8443: 
                   8444:     $fields{'command'}='all_for_one';
                   8445:     my $url1d=&Apache::lonhtmlcommon::build_url('grades/',\%fields);
                   8446: 
1.443     banghart 8447:     $fields{'command'} = 'csvform';
1.538     schulted 8448:     my $url2 = &Apache::lonhtmlcommon::build_url('grades/',\%fields);
                   8449:     
1.443     banghart 8450:     $fields{'command'} = 'processclicker';
1.538     schulted 8451:     my $url3 = &Apache::lonhtmlcommon::build_url('grades/',\%fields);
                   8452:     
1.443     banghart 8453:     $fields{'command'} = 'scantron_selectphase';
1.538     schulted 8454:     my $url4 = &Apache::lonhtmlcommon::build_url('grades/',\%fields);
1.602     www      8455: 
                   8456:     $fields{'command'} = 'initialverifyreceipt';
                   8457:     my $url5 = &Apache::lonhtmlcommon::build_url('grades/',\%fields);
1.538     schulted 8458:     
1.598     www      8459:     my @menu = ({	categorytitle=>'Hand Grading',
1.538     schulted 8460:             items =>[
1.598     www      8461:                         {	linktext => 'Select individual students to grade',
                   8462:                     		url => $url1a,
1.538     schulted 8463:                     		permission => 'F',
                   8464:                     		icon => 'edit-find-replace.png',
1.598     www      8465:                     		linktitle => 'Grade current resource for a selection of students.'
                   8466:                         }, 
                   8467:                         {       linktext => 'Grade ungraded submissions.',
                   8468:                                 url => $url1b,
                   8469:                                 permission => 'F',
                   8470:                                 icon => 'edit-find-replace.png',
                   8471:                                 linktitle => 'Grade all submissions that have not been graded yet.'
1.538     schulted 8472:                         },
1.598     www      8473: 
                   8474:                         {       linktext => 'Grading table',
                   8475:                                 url => $url1c,
                   8476:                                 permission => 'F',
                   8477:                                 icon => 'edit-find-replace.png',
                   8478:                                 linktitle => 'Grade current resource for all students.'
                   8479:                         },
1.600     www      8480:                         {       linktext => 'Grade complete page/sequence/folder for one student',
1.598     www      8481:                                 url => $url1d,
                   8482:                                 permission => 'F',
                   8483:                                 icon => 'edit-find-replace.png',
                   8484:                                 linktitle => 'Grade all resources in current page/sequence/folder for one student.'
                   8485:                         }]},
                   8486:                          { categorytitle=>'Automated Grading',
                   8487:                items =>[
                   8488: 
1.538     schulted 8489:                 	    {	linktext => 'Upload Scores',
                   8490:                     		url => $url2,
                   8491:                     		permission => 'F',
                   8492:                     		icon => 'uploadscores.png',
                   8493:                     		linktitle => 'Specify a file containing the class scores for current resource.'
                   8494:                 	    },
                   8495:                 	    {	linktext => 'Process Clicker',
                   8496:                     		url => $url3,
                   8497:                     		permission => 'F',
                   8498:                     		icon => 'addClickerInfoFile.png',
                   8499:                     		linktitle => 'Specify a file containing the clicker information for this resource.'
                   8500:                 	    },
1.587     raeburn  8501:                 	    {	linktext => 'Grade/Manage/Review Bubblesheets',
1.538     schulted 8502:                     		url => $url4,
                   8503:                     		permission => 'F',
                   8504:                     		icon => 'stat.png',
                   8505:                     		linktitle => 'Grade scantron exams, upload/download scantron data files, and review previously graded scantron exams.'
1.602     www      8506:                 	    },
                   8507:                             {   linktext => 'Verify Receipt No.',
                   8508:                                 url => $url5,
                   8509:                                 permission => 'F',
                   8510:                                 icon => 'edit-find-replace.png',
                   8511:                                 linktitle => 'Verify a system-generated receipt number for correct problem solution.'
                   8512:                             }
                   8513: 
1.538     schulted 8514:                     ]
                   8515:             });
                   8516: 
1.443     banghart 8517:     # Create the menu
                   8518:     my $Str;
1.445     banghart 8519:     $Str .= '<form method="post" action="" name="gradingMenu">';
                   8520:     $Str .= '<input type="hidden" name="command" value="" />'.
                   8521:     	'<input type="hidden" name="symb"        value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
                   8522: 	'<input type="hidden" name="gradingMenu" value="1" />'."\n".
                   8523: 	'<input type="hidden" name="showgrading" value="yes" />'."\n";
                   8524: 
1.602     www      8525:     $Str .= &Apache::lonhtmlcommon::generate_menu(@menu);
1.443     banghart 8526:     return $Str;    
                   8527: }
                   8528: 
1.598     www      8529: 
                   8530: sub ungraded {
                   8531:     my ($request)=@_;
                   8532:     &submit_options($request);
                   8533: }
                   8534: 
1.599     www      8535: sub submit_options_sequence {
1.608     www      8536:     my ($request,$symb) = @_;
1.599     www      8537:     if (!$symb) {return '';}
1.600     www      8538:     &commonJSfunctions($request);
                   8539:     my $result;
1.599     www      8540: 
1.600     www      8541:     $result.='<form action="/adm/grades" method="post" name="gradingMenu">'."\n".
                   8542:         '<input type="hidden" name="symb"        value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
                   8543:         '<input type="hidden" name="gradingMenu" value="1" />'."\n".
                   8544:         '<input type="hidden" name="showgrading" value="yes" />'."\n";
                   8545: 
                   8546:     $result.='
                   8547: <h2>
                   8548:   '.&mt('Grade complete page/sequence/folder for one student').'
1.601     www      8549: </h2>'.
                   8550:             &selectfield(0).
                   8551:             '<input type="hidden" name="command" value="pickStudentPage" />
1.600     www      8552:             <div>
                   8553:               <input type="submit" value="'.&mt('Next').' &rarr;" />
                   8554:             </div>
                   8555:         </div>
                   8556:   </form>';
                   8557:     $result .= &show_grading_menu_form($symb);
                   8558:     return $result;
                   8559: }
                   8560: 
                   8561: sub submit_options_table {
1.608     www      8562:     my ($request,$symb) = @_;
1.600     www      8563:     if (!$symb) {return '';}
1.599     www      8564:     &commonJSfunctions($request);
                   8565:     my $result;
                   8566: 
                   8567:     $result.='<form action="/adm/grades" method="post" name="gradingMenu">'."\n".
                   8568:         '<input type="hidden" name="symb"        value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
                   8569:         '<input type="hidden" name="gradingMenu" value="1" />'."\n".
                   8570:         '<input type="hidden" name="showgrading" value="yes" />'."\n";
                   8571: 
                   8572:     $result.='
                   8573: <h2>
1.600     www      8574:   '.&mt('Grading table').'
1.601     www      8575: </h2>'.
                   8576:             &selectfield(0).
                   8577:             '<input type="hidden" name="command" value="viewgrades" />
1.599     www      8578:             <div>
                   8579:               <input type="submit" value="'.&mt('Next').' &rarr;" />
                   8580:             </div>
                   8581:         </div>
                   8582:   </form>';
                   8583:     $result .= &show_grading_menu_form($symb);
                   8584:     return $result;
                   8585: }
1.443     banghart 8586: 
1.600     www      8587: 
                   8588: 
1.443     banghart 8589: #--- Displays the submissions first page -------
                   8590: sub submit_options {
1.608     www      8591:     my ($request,$symb) = @_;
1.72      ng       8592:     if (!$symb) {return '';}
                   8593: 
1.118     ng       8594:     &commonJSfunctions($request);
1.473     albertel 8595:     my $result;
1.533     bisitz   8596: 
1.72      ng       8597:     $result.='<form action="/adm/grades" method="post" name="gradingMenu">'."\n".
1.418     albertel 8598: 	'<input type="hidden" name="symb"        value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
1.124     ng       8599: 	'<input type="hidden" name="gradingMenu" value="1" />'."\n".
1.72      ng       8600: 	'<input type="hidden" name="showgrading" value="yes" />'."\n";
                   8601: 
1.472     albertel 8602:     $result.='
1.533     bisitz   8603: <h2>
1.600     www      8604:   '.&mt('Select individual students to grade').'
1.601     www      8605: </h2>'.&selectfield(1).'
                   8606:                 <input type="hidden" name="command" value="submission" /> 
                   8607: 	      <input type="submit" value="'.&mt('Next').' &rarr;" />
                   8608:             </div>
                   8609:           </div>
                   8610: 
                   8611: 
                   8612:   </form>';
                   8613:     $result .= &show_grading_menu_form($symb);
                   8614:     return $result;
                   8615: }
1.533     bisitz   8616: 
1.601     www      8617: sub selectfield {
                   8618:    my ($full)=@_;
                   8619:    my $result='<div class="LC_columnSection">
1.537     harmsja  8620:   
1.533     bisitz   8621:     <fieldset>
                   8622:       <legend>
                   8623:        '.&mt('Sections').'
                   8624:       </legend>
1.601     www      8625:       '.&Apache::lonstatistics::SectionSelect('section','multiple',5).'
1.533     bisitz   8626:     </fieldset>
1.537     harmsja  8627:   
1.533     bisitz   8628:     <fieldset>
                   8629:       <legend>
                   8630:         '.&mt('Groups').'
                   8631:       </legend>
                   8632:       '.&Apache::lonstatistics::GroupSelect('group','multiple',5).'
                   8633:     </fieldset>
1.537     harmsja  8634:   
1.533     bisitz   8635:     <fieldset>
                   8636:       <legend>
                   8637:         '.&mt('Access Status').'
                   8638:       </legend>
1.601     www      8639:       '.&Apache::lonhtmlcommon::StatusOptions(undef,undef,5,undef,'mult').'
                   8640:     </fieldset>';
                   8641:     if ($full) {
                   8642:        $result.='
1.533     bisitz   8643:     <fieldset>
                   8644:       <legend>
                   8645:         '.&mt('Submission Status').'
1.601     www      8646:       </legend>'.
                   8647:        &Apache::loncommon::select_form('all','submitonly',
                   8648:           (&Apache::lonlocal::texthash(
                   8649:              'yes'       => 'with submissions',
                   8650:              'queued'    => 'in grading queue',
                   8651:              'graded'    => 'with ungraded submissions',
                   8652:              'incorrect' => 'with incorrect submissions',
                   8653:              'all'       => 'with any status'),
                   8654:              'select_form_order' => ['yes','queued','graded','incorrect','all'])).
                   8655:    '</fieldset>';
                   8656:     }
                   8657:     $result.='</div><br />';
1.44      ng       8658:     return $result;
1.2       albertel 8659: }
                   8660: 
1.285     albertel 8661: sub reset_perm {
                   8662:     undef(%perm);
                   8663: }
                   8664: 
                   8665: sub init_perm {
                   8666:     &reset_perm();
1.300     albertel 8667:     foreach my $test_perm ('vgr','mgr','opa') {
                   8668: 
                   8669: 	my $scope = $env{'request.course.id'};
                   8670: 	if (!($perm{$test_perm}=&Apache::lonnet::allowed($test_perm,$scope))) {
                   8671: 
                   8672: 	    $scope .= '/'.$env{'request.course.sec'};
                   8673: 	    if ( $perm{$test_perm}=
                   8674: 		 &Apache::lonnet::allowed($test_perm,$scope)) {
                   8675: 		$perm{$test_perm.'_section'}=$env{'request.course.sec'};
                   8676: 	    } else {
                   8677: 		delete($perm{$test_perm});
                   8678: 	    }
1.285     albertel 8679: 	}
                   8680:     }
                   8681: }
                   8682: 
1.400     www      8683: sub gather_clicker_ids {
1.408     albertel 8684:     my %clicker_ids;
1.400     www      8685: 
                   8686:     my $classlist = &Apache::loncoursedata::get_classlist();
                   8687: 
                   8688:     # Set up a couple variables.
1.407     albertel 8689:     my $username_idx = &Apache::loncoursedata::CL_SNAME();
                   8690:     my $domain_idx   = &Apache::loncoursedata::CL_SDOM();
1.438     www      8691:     my $status_idx   = &Apache::loncoursedata::CL_STATUS();
1.400     www      8692: 
1.407     albertel 8693:     foreach my $student (keys(%$classlist)) {
1.438     www      8694:         if ($classlist->{$student}->[$status_idx] ne 'Active') { next; }
1.407     albertel 8695:         my $username = $classlist->{$student}->[$username_idx];
                   8696:         my $domain   = $classlist->{$student}->[$domain_idx];
1.400     www      8697:         my $clickers =
1.408     albertel 8698: 	    (&Apache::lonnet::userenvironment($domain,$username,'clickers'))[1];
1.400     www      8699:         foreach my $id (split(/\,/,$clickers)) {
1.414     www      8700:             $id=~s/^[\#0]+//;
1.421     www      8701:             $id=~s/[\-\:]//g;
1.407     albertel 8702:             if (exists($clicker_ids{$id})) {
1.408     albertel 8703: 		$clicker_ids{$id}.=','.$username.':'.$domain;
1.400     www      8704:             } else {
1.408     albertel 8705: 		$clicker_ids{$id}=$username.':'.$domain;
1.400     www      8706:             }
                   8707:         }
                   8708:     }
1.407     albertel 8709:     return %clicker_ids;
1.400     www      8710: }
                   8711: 
1.402     www      8712: sub gather_adv_clicker_ids {
1.408     albertel 8713:     my %clicker_ids;
1.402     www      8714:     my $cnum=$env{'course.'.$env{'request.course.id'}.'.num'};
                   8715:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
                   8716:     my %coursepersonnel=&Apache::lonnet::get_course_adv_roles($cdom.'/'.$cnum);
1.409     albertel 8717:     foreach my $element (sort(keys(%coursepersonnel))) {
1.402     www      8718:         foreach my $person (split(/\,/,$coursepersonnel{$element})) {
                   8719:             my ($puname,$pudom)=split(/\:/,$person);
                   8720:             my $clickers =
1.408     albertel 8721: 		(&Apache::lonnet::userenvironment($pudom,$puname,'clickers'))[1];
1.405     www      8722:             foreach my $id (split(/\,/,$clickers)) {
1.414     www      8723: 		$id=~s/^[\#0]+//;
1.421     www      8724:                 $id=~s/[\-\:]//g;
1.408     albertel 8725: 		if (exists($clicker_ids{$id})) {
                   8726: 		    $clicker_ids{$id}.=','.$puname.':'.$pudom;
                   8727: 		} else {
                   8728: 		    $clicker_ids{$id}=$puname.':'.$pudom;
                   8729: 		}
1.405     www      8730:             }
1.402     www      8731:         }
                   8732:     }
1.407     albertel 8733:     return %clicker_ids;
1.402     www      8734: }
                   8735: 
1.413     www      8736: sub clicker_grading_parameters {
                   8737:     return ('gradingmechanism' => 'scalar',
                   8738:             'upfiletype' => 'scalar',
                   8739:             'specificid' => 'scalar',
                   8740:             'pcorrect' => 'scalar',
                   8741:             'pincorrect' => 'scalar');
                   8742: }
                   8743: 
1.400     www      8744: sub process_clicker {
1.608     www      8745:     my ($r,$symb)=@_;
1.400     www      8746:     if (!$symb) {return '';}
                   8747:     my $result=&checkforfile_js();
                   8748:     $result.='<br /><table width="100%" border="0"><tr><td bgcolor="#777777">'."\n";
                   8749:     $result.='<table width="100%" border="0"><tr bgcolor="#e6ffff"><td>'."\n";
1.538     schulted 8750:     $result.='&nbsp;<b>'.&mt('Specify a file containing the clicker information for this resource.').
                   8751:         '</b></td></tr>'."\n";
1.601     www      8752:     $result.='<tr bgcolor="#ffffe6"><td>'."\n";
1.413     www      8753: # Attempt to restore parameters from last session, set defaults if not present
                   8754:     my %Saveable_Parameters=&clicker_grading_parameters();
                   8755:     &Apache::loncommon::restore_course_settings('grades_clicker',
                   8756:                                                  \%Saveable_Parameters);
                   8757:     if (!$env{'form.pcorrect'}) { $env{'form.pcorrect'}=100; }
                   8758:     if (!$env{'form.pincorrect'}) { $env{'form.pincorrect'}=100; }
                   8759:     if (!$env{'form.gradingmechanism'}) { $env{'form.gradingmechanism'}='attendance'; }
                   8760:     if (!$env{'form.upfiletype'}) { $env{'form.upfiletype'}='iclicker'; }
                   8761: 
                   8762:     my %checked;
1.521     www      8763:     foreach my $gradingmechanism ('attendance','personnel','specific','given') {
1.413     www      8764:        if ($env{'form.gradingmechanism'} eq $gradingmechanism) {
1.569     bisitz   8765:           $checked{$gradingmechanism}=' checked="checked"';
1.413     www      8766:        }
                   8767:     }
                   8768: 
1.400     www      8769:     my $upload=&mt("Upload File");
                   8770:     my $type=&mt("Type");
1.402     www      8771:     my $attendance=&mt("Award points just for participation");
                   8772:     my $personnel=&mt("Correctness determined from response by course personnel");
1.414     www      8773:     my $specific=&mt("Correctness determined from response with clicker ID(s)"); 
1.521     www      8774:     my $given=&mt("Correctness determined from given list of answers").' '.
                   8775:               '<font size="-2"><tt>('.&mt("Provide comma-separated list. Use '*' for any answer correct, '-' for skip").')</tt></font>';
1.402     www      8776:     my $pcorrect=&mt("Percentage points for correct solution");
                   8777:     my $pincorrect=&mt("Percentage points for incorrect solution");
1.413     www      8778:     my $selectform=&Apache::loncommon::select_form($env{'form.upfiletype'},'upfiletype',
1.419     www      8779: 						   ('iclicker' => 'i>clicker',
                   8780:                                                     'interwrite' => 'interwrite PRS'));
1.418     albertel 8781:     $symb = &Apache::lonenc::check_encrypt($symb);
1.597     wenzelju 8782:     $result.= &Apache::lonhtmlcommon::scripttag(<<ENDUPFORM);
1.402     www      8783: function sanitycheck() {
                   8784: // Accept only integer percentages
                   8785:    document.forms.gradesupload.pcorrect.value=Math.round(document.forms.gradesupload.pcorrect.value);
                   8786:    document.forms.gradesupload.pincorrect.value=Math.round(document.forms.gradesupload.pincorrect.value);
                   8787: // Find out grading choice
                   8788:    for (i=0; i<document.forms.gradesupload.gradingmechanism.length; i++) {
                   8789:       if (document.forms.gradesupload.gradingmechanism[i].checked) {
                   8790:          gradingchoice=document.forms.gradesupload.gradingmechanism[i].value;
                   8791:       }
                   8792:    }
                   8793: // By default, new choice equals user selection
                   8794:    newgradingchoice=gradingchoice;
                   8795: // Not good to give more points for false answers than correct ones
                   8796:    if (Math.round(document.forms.gradesupload.pcorrect.value)<Math.round(document.forms.gradesupload.pincorrect.value)) {
                   8797:       document.forms.gradesupload.pcorrect.value=document.forms.gradesupload.pincorrect.value;
                   8798:    }
                   8799: // If new choice is attendance only, and old choice was correctness-based, restore defaults
                   8800:    if ((gradingchoice=='attendance') && (document.forms.gradesupload.waschecked.value!='attendance')) {
                   8801:       document.forms.gradesupload.pcorrect.value=100;
                   8802:       document.forms.gradesupload.pincorrect.value=100;
                   8803:    }
                   8804: // If the values are different, cannot be attendance only
                   8805:    if ((Math.round(document.forms.gradesupload.pcorrect.value)!=Math.round(document.forms.gradesupload.pincorrect.value)) &&
                   8806:        (gradingchoice=='attendance')) {
                   8807:        newgradingchoice='personnel';
                   8808:    }
                   8809: // Change grading choice to new one
                   8810:    for (i=0; i<document.forms.gradesupload.gradingmechanism.length; i++) {
                   8811:       if (document.forms.gradesupload.gradingmechanism[i].value==newgradingchoice) {
                   8812:          document.forms.gradesupload.gradingmechanism[i].checked=true;
                   8813:       } else {
                   8814:          document.forms.gradesupload.gradingmechanism[i].checked=false;
                   8815:       }
                   8816:    }
                   8817: // Remember the old state
                   8818:    document.forms.gradesupload.waschecked.value=newgradingchoice;
                   8819: }
1.597     wenzelju 8820: ENDUPFORM
                   8821:     $result.= <<ENDUPFORM;
1.400     www      8822: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="gradesupload">
                   8823: <input type="hidden" name="symb" value="$symb" />
                   8824: <input type="hidden" name="command" value="processclickerfile" />
                   8825: <input type="hidden" name="saveState"  value="$env{'form.saveState'}" />
                   8826: <input type="file" name="upfile" size="50" />
                   8827: <br /><label>$type: $selectform</label>
1.589     bisitz   8828: <br /><label><input type="radio" name="gradingmechanism" value="attendance"$checked{'attendance'} onclick="sanitycheck()" />$attendance </label>
                   8829: <br /><label><input type="radio" name="gradingmechanism" value="personnel"$checked{'personnel'} onclick="sanitycheck()" />$personnel</label>
                   8830: <br /><label><input type="radio" name="gradingmechanism" value="specific"$checked{'specific'} onclick="sanitycheck()" />$specific </label>
1.414     www      8831: <input type="text" name="specificid" value="$env{'form.specificid'}" size="20" />
1.589     bisitz   8832: <br /><label><input type="radio" name="gradingmechanism" value="given"$checked{'given'} onclick="sanitycheck()" />$given </label>
1.521     www      8833: <br />&nbsp;&nbsp;&nbsp;
                   8834: <input type="text" name="givenanswer" size="50" />
1.413     www      8835: <input type="hidden" name="waschecked" value="$env{'form.gradingmechanism'}" />
1.589     bisitz   8836: <br /><label>$pcorrect: <input type="text" name="pcorrect" size="4" value="$env{'form.pcorrect'}" onchange="sanitycheck()" /></label>
                   8837: <br /><label>$pincorrect: <input type="text" name="pincorrect" size="4" value="$env{'form.pincorrect'}" onchange="sanitycheck()" /></label>
                   8838: <br /><input type="button" onclick="javascript:checkUpload(this.form);" value="$upload" />
1.597     wenzelju 8839: </form>'
1.400     www      8840: ENDUPFORM
                   8841:     $result.='</td></tr></table>'."\n".
                   8842:              '</td></tr></table><br /><br />'."\n";
                   8843:     $result.=&show_grading_menu_form($symb);
                   8844:     return $result;
                   8845: }
                   8846: 
                   8847: sub process_clicker_file {
1.608     www      8848:     my ($r,$symb)=@_;
1.400     www      8849:     if (!$symb) {return '';}
1.413     www      8850: 
                   8851:     my %Saveable_Parameters=&clicker_grading_parameters();
                   8852:     &Apache::loncommon::store_course_settings('grades_clicker',
                   8853:                                               \%Saveable_Parameters);
1.598     www      8854:     my $result='';
1.404     www      8855:     if (($env{'form.gradingmechanism'} eq 'specific') && ($env{'form.specificid'}!~/\w/)) {
1.408     albertel 8856: 	$result.='<span class="LC_error">'.&mt('You need to specify a clicker ID for the correct answer').'</span>';
                   8857: 	return $result.&show_grading_menu_form($symb);
1.404     www      8858:     }
1.522     www      8859:     if (($env{'form.gradingmechanism'} eq 'given') && ($env{'form.givenanswer'}!~/\S/)) {
1.521     www      8860:         $result.='<span class="LC_error">'.&mt('You need to specify the correct answer').'</span>';
                   8861:         return $result.&show_grading_menu_form($symb);
                   8862:     }
1.522     www      8863:     my $foundgiven=0;
1.521     www      8864:     if ($env{'form.gradingmechanism'} eq 'given') {
                   8865:         $env{'form.givenanswer'}=~s/^\s*//gs;
                   8866:         $env{'form.givenanswer'}=~s/\s*$//gs;
                   8867:         $env{'form.givenanswer'}=~s/[^a-zA-Z0-9\.\*\-]+/\,/g;
                   8868:         $env{'form.givenanswer'}=uc($env{'form.givenanswer'});
1.522     www      8869:         my @answers=split(/\,/,$env{'form.givenanswer'});
                   8870:         $foundgiven=$#answers+1;
1.521     www      8871:     }
1.407     albertel 8872:     my %clicker_ids=&gather_clicker_ids();
1.408     albertel 8873:     my %correct_ids;
1.404     www      8874:     if ($env{'form.gradingmechanism'} eq 'personnel') {
1.408     albertel 8875: 	%correct_ids=&gather_adv_clicker_ids();
1.404     www      8876:     }
                   8877:     if ($env{'form.gradingmechanism'} eq 'specific') {
1.414     www      8878: 	foreach my $correct_id (split(/[\s\,]/,$env{'form.specificid'})) {;
                   8879: 	   $correct_id=~tr/a-z/A-Z/;
                   8880: 	   $correct_id=~s/\s//gs;
                   8881: 	   $correct_id=~s/^[\#0]+//;
1.421     www      8882:            $correct_id=~s/[\-\:]//g;
1.414     www      8883:            if ($correct_id) {
                   8884: 	      $correct_ids{$correct_id}='specified';
                   8885:            }
                   8886:         }
1.400     www      8887:     }
1.404     www      8888:     if ($env{'form.gradingmechanism'} eq 'attendance') {
1.408     albertel 8889: 	$result.=&mt('Score based on attendance only');
1.521     www      8890:     } elsif ($env{'form.gradingmechanism'} eq 'given') {
1.522     www      8891:         $result.=&mt('Score based on [_1] ([_2] answers)','<tt>'.$env{'form.givenanswer'}.'</tt>',$foundgiven);
1.404     www      8892:     } else {
1.408     albertel 8893: 	my $number=0;
1.411     www      8894: 	$result.='<p><b>'.&mt('Correctness determined by the following IDs').'</b>';
1.408     albertel 8895: 	foreach my $id (sort(keys(%correct_ids))) {
1.411     www      8896: 	    $result.='<br /><tt>'.$id.'</tt> - ';
1.408     albertel 8897: 	    if ($correct_ids{$id} eq 'specified') {
                   8898: 		$result.=&mt('specified');
                   8899: 	    } else {
                   8900: 		my ($uname,$udom)=split(/\:/,$correct_ids{$id});
                   8901: 		$result.=&Apache::loncommon::plainname($uname,$udom);
                   8902: 	    }
                   8903: 	    $number++;
                   8904: 	}
1.411     www      8905:         $result.="</p>\n";
1.408     albertel 8906: 	if ($number==0) {
                   8907: 	    $result.='<span class="LC_error">'.&mt('No IDs found to determine correct answer').'</span>';
                   8908: 	    return $result.&show_grading_menu_form($symb);
                   8909: 	}
1.404     www      8910:     }
1.405     www      8911:     if (length($env{'form.upfile'}) < 2) {
1.407     albertel 8912:         $result.=&mt('[_1] Error: [_2] The file you attempted to upload, [_3] contained no information. Please check that you entered the correct filename.',
                   8913: 		     '<span class="LC_error">',
                   8914: 		     '</span>',
                   8915: 		     '<span class="LC_filename">'.&HTML::Entities::encode($env{'form.upfile.filename'},'<>&"').'</span>');
1.405     www      8916:         return $result.&show_grading_menu_form($symb);
                   8917:     }
1.410     www      8918: 
                   8919: # Were able to get all the info needed, now analyze the file
                   8920: 
1.411     www      8921:     $result.=&Apache::loncommon::studentbrowser_javascript();
1.418     albertel 8922:     $symb = &Apache::lonenc::check_encrypt($symb);
1.410     www      8923:     my $heading=&mt('Scanning clicker file');
                   8924:     $result.=(<<ENDHEADER);
                   8925: <br /><table width="100%" border="0"><tr><td bgcolor="#777777">
                   8926: <table width="100%" border="0"><tr bgcolor="#e6ffff"><td>
                   8927: <b>$heading</b></td></tr><tr bgcolor=#ffffe6><td>
                   8928: <form method="post" action="/adm/grades" name="clickeranalysis">
                   8929: <input type="hidden" name="symb" value="$symb" />
                   8930: <input type="hidden" name="command" value="assignclickergrades" />
                   8931: <input type="hidden" name="saveState"  value="$env{'form.saveState'}" />
1.411     www      8932: <input type="hidden" name="gradingmechanism" value="$env{'form.gradingmechanism'}" />
                   8933: <input type="hidden" name="pcorrect" value="$env{'form.pcorrect'}" />
                   8934: <input type="hidden" name="pincorrect" value="$env{'form.pincorrect'}" />
1.410     www      8935: ENDHEADER
1.522     www      8936:     if ($env{'form.gradingmechanism'} eq 'given') {
                   8937:        $result.='<input type="hidden" name="correct:given" value="'.$env{'form.givenanswer'}.'" />';
                   8938:     } 
1.408     albertel 8939:     my %responses;
                   8940:     my @questiontitles;
1.405     www      8941:     my $errormsg='';
                   8942:     my $number=0;
                   8943:     if ($env{'form.upfiletype'} eq 'iclicker') {
1.408     albertel 8944: 	($errormsg,$number)=&iclicker_eval(\@questiontitles,\%responses);
1.406     www      8945:     }
1.419     www      8946:     if ($env{'form.upfiletype'} eq 'interwrite') {
                   8947:         ($errormsg,$number)=&interwrite_eval(\@questiontitles,\%responses);
                   8948:     }
1.411     www      8949:     $result.='<br />'.&mt('Found [_1] question(s)',$number).'<br />'.
                   8950:              '<input type="hidden" name="number" value="'.$number.'" />'.
                   8951:              &mt('Awarding [_1] percent for correct and [_2] percent for incorrect responses',
                   8952:                  $env{'form.pcorrect'},$env{'form.pincorrect'}).
                   8953:              '<br />';
1.522     www      8954:     if (($env{'form.gradingmechanism'} eq 'given') && ($number!=$foundgiven)) {
                   8955:        $result.='<span class="LC_error">'.&mt('Number of given answers does not agree with number of questions in file.').'</span>';
                   8956:        return $result.&show_grading_menu_form($symb);
                   8957:     } 
1.414     www      8958: # Remember Question Titles
                   8959: # FIXME: Possibly need delimiter other than ":"
                   8960:     for (my $i=0;$i<$number;$i++) {
                   8961:         $result.='<input type="hidden" name="question:'.$i.'" value="'.
                   8962:                  &HTML::Entities::encode($questiontitles[$i],'"&<>').'" />';
                   8963:     }
1.411     www      8964:     my $correct_count=0;
                   8965:     my $student_count=0;
                   8966:     my $unknown_count=0;
1.414     www      8967: # Match answers with usernames
                   8968: # FIXME: Possibly need delimiter other than ":"
1.409     albertel 8969:     foreach my $id (keys(%responses)) {
1.410     www      8970:        if ($correct_ids{$id}) {
1.414     www      8971:           $result.="\n".'<input type="hidden" name="correct:'.$correct_count.':'.$correct_ids{$id}.'" value="'.$responses{$id}.'" />';
1.411     www      8972:           $correct_count++;
1.410     www      8973:        } elsif ($clicker_ids{$id}) {
1.437     www      8974:           if ($clicker_ids{$id}=~/\,/) {
                   8975: # More than one user with the same clicker!
                   8976:              $result.="\n<hr />".&mt('Clicker registered more than once').": <tt>".$id."</tt><br />";
                   8977:              $result.="\n".'<input type="hidden" name="unknown:'.$id.'" value="'.$responses{$id}.'" />'.
                   8978:                            "<select name='multi".$id."'>";
                   8979:              foreach my $reguser (sort(split(/\,/,$clicker_ids{$id}))) {
                   8980:                  $result.="<option value='".$reguser."'>".&Apache::loncommon::plainname(split(/\:/,$reguser)).' ('.$reguser.')</option>';
                   8981:              }
                   8982:              $result.='</select>';
                   8983:              $unknown_count++;
                   8984:           } else {
                   8985: # Good: found one and only one user with the right clicker
                   8986:              $result.="\n".'<input type="hidden" name="student:'.$clicker_ids{$id}.'" value="'.$responses{$id}.'" />';
                   8987:              $student_count++;
                   8988:           }
1.410     www      8989:        } else {
1.411     www      8990:           $result.="\n<hr />".&mt('Unregistered Clicker')." <tt>".$id."</tt><br />";
                   8991:           $result.="\n".'<input type="hidden" name="unknown:'.$id.'" value="'.$responses{$id}.'" />'.
                   8992:                    "\n".&mt("Username").": <input type='text' name='uname".$id."' />&nbsp;".
                   8993:                    "\n".&mt("Domain").": ".
                   8994:                    &Apache::loncommon::select_dom_form($env{'course.'.$env{'request.course.id'}.'.domain'},'udom'.$id).'&nbsp;'.
                   8995:                    &Apache::loncommon::selectstudent_link('clickeranalysis','uname'.$id,'udom'.$id);
                   8996:           $unknown_count++;
1.410     www      8997:        }
1.405     www      8998:     }
1.412     www      8999:     $result.='<hr />'.
                   9000:              &mt('Found [_1] registered and [_2] unregistered clickers.',$student_count,$unknown_count);
1.521     www      9001:     if (($env{'form.gradingmechanism'} ne 'attendance') && ($env{'form.gradingmechanism'} ne 'given')) {
1.412     www      9002:        if ($correct_count==0) {
                   9003:           $errormsg.="Found no correct answers answers for grading!";
                   9004:        } elsif ($correct_count>1) {
1.414     www      9005:           $result.='<br /><span class="LC_warning">'.&mt("Found [_1] entries for grading!",$correct_count).'</span>';
1.412     www      9006:        }
                   9007:     }
1.428     www      9008:     if ($number<1) {
                   9009:        $errormsg.="Found no questions.";
                   9010:     }
1.412     www      9011:     if ($errormsg) {
                   9012:        $result.='<br /><span class="LC_error">'.&mt($errormsg).'</span>';
                   9013:     } else {
                   9014:        $result.='<br /><input type="submit" name="finalize" value="'.&mt('Finalize Grading').'" />';
                   9015:     }
                   9016:     $result.='</form></td></tr></table>'."\n".
1.410     www      9017:              '</td></tr></table><br /><br />'."\n";
1.404     www      9018:     return $result.&show_grading_menu_form($symb);
1.400     www      9019: }
                   9020: 
1.405     www      9021: sub iclicker_eval {
1.406     www      9022:     my ($questiontitles,$responses)=@_;
1.405     www      9023:     my $number=0;
                   9024:     my $errormsg='';
                   9025:     foreach my $line (split(/[\n\r]/,$env{'form.upfile'})) {
1.410     www      9026:         my %components=&Apache::loncommon::record_sep($line);
                   9027:         my @entries=map {$components{$_}} (sort(keys(%components)));
1.408     albertel 9028: 	if ($entries[0] eq 'Question') {
                   9029: 	    for (my $i=3;$i<$#entries;$i+=6) {
                   9030: 		$$questiontitles[$number]=$entries[$i];
                   9031: 		$number++;
                   9032: 	    }
                   9033: 	}
                   9034: 	if ($entries[0]=~/^\#/) {
                   9035: 	    my $id=$entries[0];
                   9036: 	    my @idresponses;
                   9037: 	    $id=~s/^[\#0]+//;
                   9038: 	    for (my $i=0;$i<$number;$i++) {
                   9039: 		my $idx=3+$i*6;
                   9040: 		push(@idresponses,$entries[$idx]);
                   9041: 	    }
                   9042: 	    $$responses{$id}=join(',',@idresponses);
                   9043: 	}
1.405     www      9044:     }
                   9045:     return ($errormsg,$number);
                   9046: }
                   9047: 
1.419     www      9048: sub interwrite_eval {
                   9049:     my ($questiontitles,$responses)=@_;
                   9050:     my $number=0;
                   9051:     my $errormsg='';
1.420     www      9052:     my $skipline=1;
                   9053:     my $questionnumber=0;
                   9054:     my %idresponses=();
1.419     www      9055:     foreach my $line (split(/[\n\r]/,$env{'form.upfile'})) {
                   9056:         my %components=&Apache::loncommon::record_sep($line);
                   9057:         my @entries=map {$components{$_}} (sort(keys(%components)));
1.420     www      9058:         if ($entries[1] eq 'Time') { $skipline=0; next; }
                   9059:         if ($entries[1] eq 'Response') { $skipline=1; }
                   9060:         next if $skipline;
                   9061:         if ($entries[0]!=$questionnumber) {
                   9062:            $questionnumber=$entries[0];
                   9063:            $$questiontitles[$number]=&mt('Question [_1]',$questionnumber);
                   9064:            $number++;
1.419     www      9065:         }
1.420     www      9066:         my $id=$entries[4];
                   9067:         $id=~s/^[\#0]+//;
1.421     www      9068:         $id=~s/^v\d*\://i;
                   9069:         $id=~s/[\-\:]//g;
1.420     www      9070:         $idresponses{$id}[$number]=$entries[6];
                   9071:     }
1.524     raeburn  9072:     foreach my $id (keys(%idresponses)) {
1.420     www      9073:        $$responses{$id}=join(',',@{$idresponses{$id}});
                   9074:        $$responses{$id}=~s/^\s*\,//;
1.419     www      9075:     }
                   9076:     return ($errormsg,$number);
                   9077: }
                   9078: 
1.414     www      9079: sub assign_clicker_grades {
1.608     www      9080:     my ($r,$symb)=@_;
1.414     www      9081:     if (!$symb) {return '';}
1.416     www      9082: # See which part we are saving to
1.582     raeburn  9083:     my $res_error;
                   9084:     my ($partlist,$handgrade,$responseType) = &response_type($symb,\$res_error);
                   9085:     if ($res_error) {
                   9086:         return &navmap_errormsg();
                   9087:     }
1.416     www      9088: # FIXME: This should probably look for the first handgradeable part
                   9089:     my $part=$$partlist[0];
                   9090: # Start screen output
1.598     www      9091:     my $result='';
1.416     www      9092: 
1.414     www      9093:     my $heading=&mt('Assigning grades based on clicker file');
                   9094:     $result.=(<<ENDHEADER);
                   9095: <br /><table width="100%" border="0"><tr><td bgcolor="#777777">
                   9096: <table width="100%" border="0"><tr bgcolor="#e6ffff"><td>
                   9097: <b>$heading</b></td></tr><tr bgcolor=#ffffe6><td>
                   9098: ENDHEADER
                   9099: # Get correct result
                   9100: # FIXME: Possibly need delimiter other than ":"
                   9101:     my @correct=();
1.415     www      9102:     my $gradingmechanism=$env{'form.gradingmechanism'};
                   9103:     my $number=$env{'form.number'};
                   9104:     if ($gradingmechanism ne 'attendance') {
1.414     www      9105:        foreach my $key (keys(%env)) {
                   9106:           if ($key=~/^form\.correct\:/) {
                   9107:              my @input=split(/\,/,$env{$key});
                   9108:              for (my $i=0;$i<=$#input;$i++) {
                   9109:                  if (($correct[$i]) && ($input[$i]) &&
                   9110:                      ($correct[$i] ne $input[$i])) {
                   9111:                     $result.='<br /><span class="LC_warning">'.
                   9112:                              &mt('More than one correct result given for question "[_1]": [_2] versus [_3].',
                   9113:                                  $env{'form.question:'.$i},$correct[$i],$input[$i]).'</span>';
                   9114:                  } elsif ($input[$i]) {
                   9115:                     $correct[$i]=$input[$i];
                   9116:                  }
                   9117:              }
                   9118:           }
                   9119:        }
1.415     www      9120:        for (my $i=0;$i<$number;$i++) {
1.414     www      9121:           if (!$correct[$i]) {
                   9122:              $result.='<br /><span class="LC_error">'.
                   9123:                       &mt('No correct result given for question "[_1]"!',
                   9124:                           $env{'form.question:'.$i}).'</span>';
                   9125:           }
                   9126:        }
                   9127:        $result.='<br />'.&mt("Correct answer: [_1]",join(', ',map { ($_?$_:'-') } @correct));
                   9128:     }
                   9129: # Start grading
1.415     www      9130:     my $pcorrect=$env{'form.pcorrect'};
                   9131:     my $pincorrect=$env{'form.pincorrect'};
1.416     www      9132:     my $storecount=0;
1.415     www      9133:     foreach my $key (keys(%env)) {
1.420     www      9134:        my $user='';
1.415     www      9135:        if ($key=~/^form\.student\:(.*)$/) {
1.420     www      9136:           $user=$1;
                   9137:        }
                   9138:        if ($key=~/^form\.unknown\:(.*)$/) {
                   9139:           my $id=$1;
                   9140:           if (($env{'form.uname'.$id}) && ($env{'form.udom'.$id})) {
                   9141:              $user=$env{'form.uname'.$id}.':'.$env{'form.udom'.$id};
1.437     www      9142:           } elsif ($env{'form.multi'.$id}) {
                   9143:              $user=$env{'form.multi'.$id};
1.420     www      9144:           }
                   9145:        }
                   9146:        if ($user) { 
1.415     www      9147:           my @answer=split(/\,/,$env{$key});
                   9148:           my $sum=0;
1.522     www      9149:           my $realnumber=$number;
1.415     www      9150:           for (my $i=0;$i<$number;$i++) {
1.576     www      9151:              if  ($correct[$i] eq '-') {
                   9152:                 $realnumber--;
                   9153:              } elsif ($answer[$i]) {
1.415     www      9154:                 if ($gradingmechanism eq 'attendance') {
                   9155:                    $sum+=$pcorrect;
1.576     www      9156:                 } elsif ($correct[$i] eq '*') {
1.522     www      9157:                    $sum+=$pcorrect;
1.415     www      9158:                 } else {
                   9159:                    if ($answer[$i] eq $correct[$i]) {
                   9160:                       $sum+=$pcorrect;
                   9161:                    } else {
                   9162:                       $sum+=$pincorrect;
                   9163:                    }
                   9164:                 }
                   9165:              }
                   9166:           }
1.522     www      9167:           my $ave=$sum/(100*$realnumber);
1.416     www      9168: # Store
                   9169:           my ($username,$domain)=split(/\:/,$user);
                   9170:           my %grades=();
                   9171:           $grades{"resource.$part.solved"}='correct_by_override';
                   9172:           $grades{"resource.$part.awarded"}=$ave;
                   9173:           $grades{"resource.regrader"}="$env{'user.name'}:$env{'user.domain'}";
                   9174:           my $returncode=&Apache::lonnet::cstore(\%grades,$symb,
                   9175:                                                  $env{'request.course.id'},
                   9176:                                                  $domain,$username);
                   9177:           if ($returncode ne 'ok') {
                   9178:              $result.="<br /><span class=\"LC_error\">Failed to save student $username:$domain. Message when trying to save was ($returncode)</span>";
                   9179:           } else {
                   9180:              $storecount++;
                   9181:           }
1.415     www      9182:        }
                   9183:     }
                   9184: # We are done
1.549     hauer    9185:     $result.='<br />'.&mt('Successfully stored grades for [quant,_1,student].',$storecount).
1.416     www      9186:              '</td></tr></table>'."\n".
1.414     www      9187:              '</td></tr></table><br /><br />'."\n";
                   9188:     return $result.&show_grading_menu_form($symb);
                   9189: }
                   9190: 
1.582     raeburn  9191: sub navmap_errormsg {
                   9192:     return '<div class="LC_error">'.
                   9193:            &mt('An error occurred retrieving information about resources in the course.').'<br />'.
1.595     raeburn  9194:            &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  9195:            '</div>';
                   9196: }
1.607     droeschl 9197: 
1.609     www      9198: sub startpage {
                   9199:     my ($r,$symb,$crumbs,$onlyfolderflag) = @_;
1.610   ! www      9200:     unshift(@$crumbs,{href=>"/adm/grades?command=gradingmenu&symb=".&HTML::Entities::encode($symb,'<>&"'),text=>"Grading"});
1.607     droeschl 9201:     $r->print(&Apache::loncommon::start_page('Grading',undef,
1.610   ! www      9202:                                           {'bread_crumbs' => $crumbs}));
1.609     www      9203:     $r->print(&Apache::lonhtmlcommon::resource_info_box($symb,$onlyfolderflag));
1.607     droeschl 9204: }
1.582     raeburn  9205: 
1.1       albertel 9206: sub handler {
1.41      ng       9207:     my $request=$_[0];
1.434     albertel 9208:     &reset_caches();
1.257     albertel 9209:     if ($env{'browser.mathml'}) {
1.141     www      9210: 	&Apache::loncommon::content_type($request,'text/xml');
1.41      ng       9211:     } else {
1.141     www      9212: 	&Apache::loncommon::content_type($request,'text/html');
1.41      ng       9213:     }
                   9214:     $request->send_http_header;
1.44      ng       9215:     return '' if $request->header_only;
1.41      ng       9216:     &Apache::loncommon::get_unprocessed_cgi($ENV{'QUERY_STRING'});
1.608     www      9217: 
                   9218: # see what command we need to execute
                   9219: 
1.160     albertel 9220:     my @commands=&Apache::loncommon::get_env_multiple('form.command');
                   9221:     my $command=$commands[0];
1.447     foxr     9222: 
1.160     albertel 9223:     if ($#commands > 0) {
                   9224: 	&Apache::lonnet::logthis("grades got multiple commands ".join(':',@commands));
                   9225:     }
1.608     www      9226: 
                   9227: # see what the symb is
                   9228: 
                   9229:     my $symb=$env{'form.symb'};
                   9230:     unless ($symb) {
                   9231:        (my $url=$env{'form.url'}) =~ s-^https*://($ENV{'SERVER_NAME'}|$ENV{'HTTP_HOST'})--;
                   9232:        $symb=&Apache::lonnet::symbread($url);
                   9233:     }
                   9234:     &Apache::lonenc::check_decrypt(\$symb);                             
                   9235: 
1.513     foxr     9236:     $ssi_error = 0;
1.324     albertel 9237:     if ($symb eq '' && $command eq '') {
1.601     www      9238: #
                   9239: # Not called from a resource
                   9240: #    
                   9241: 
1.41      ng       9242:     } else {
1.285     albertel 9243: 	&init_perm();
1.104     albertel 9244: 	if ($command eq 'submission' && $perm{'vgr'}) {
1.608     www      9245:             &startpage($request,$symb,[{href=>"", text=>"Student Submissions"}]);
1.257     albertel 9246: 	    ($env{'form.student'} eq '' ? &listStudents($request) : &submission($request,0,0));
1.103     albertel 9247: 	} elsif ($command eq 'pickStudentPage' && $perm{'vgr'}) {
1.608     www      9248: 	    &pickStudentPage($request,$symb);
1.103     albertel 9249: 	} elsif ($command eq 'displayPage' && $perm{'vgr'}) {
1.608     www      9250: 	    &displayPage($request,$symb);
1.104     albertel 9251: 	} elsif ($command eq 'gradeByPage' && $perm{'mgr'}) {
1.608     www      9252: 	    &updateGradeByPage($request,$symb);
1.104     albertel 9253: 	} elsif ($command eq 'processGroup' && $perm{'vgr'}) {
1.608     www      9254: 	    &processGroup($request,$symb);
1.104     albertel 9255: 	} elsif ($command eq 'gradingmenu' && $perm{'vgr'}) {
1.608     www      9256:             &startpage($request,$symb);
                   9257: 	    $request->print(&grading_menu($request,$symb));
1.598     www      9258: 	} elsif ($command eq 'individual' && $perm{'vgr'}) {
1.608     www      9259: 	    $request->print(&submit_options($request,$symb));
1.598     www      9260:         } elsif ($command eq 'ungraded' && $perm{'vgr'}) {
1.608     www      9261:             $request->print(&submit_options($request,$symb));
1.598     www      9262:         } elsif ($command eq 'table' && $perm{'vgr'}) {
1.608     www      9263:             $request->print(&submit_options_table($request),$symb);
1.598     www      9264:         } elsif ($command eq 'all_for_one' && $perm{'vgr'}) {
1.608     www      9265:             $request->print(&submit_options_sequence($request,$symb));
1.104     albertel 9266: 	} elsif ($command eq 'viewgrades' && $perm{'vgr'}) {
1.608     www      9267: 	    $request->print(&viewgrades($request,$symb));
1.104     albertel 9268: 	} elsif ($command eq 'handgrade' && $perm{'mgr'}) {
1.608     www      9269: 	    $request->print(&processHandGrade($request,$symb));
1.106     albertel 9270: 	} elsif ($command eq 'editgrades' && $perm{'mgr'}) {
1.608     www      9271: 	    $request->print(&editgrades($request,$symb));
1.602     www      9272:         } elsif ($command eq 'initialverifyreceipt' && $perm{'vgr'}) {
1.608     www      9273:             $request->print(&initialverifyreceipt($request),$symb);
1.106     albertel 9274: 	} elsif ($command eq 'verify' && $perm{'vgr'}) {
1.608     www      9275: 	    $request->print(&verifyreceipt($request,$symb));
1.400     www      9276:         } elsif ($command eq 'processclicker' && $perm{'mgr'}) {
1.608     www      9277:             $request->print(&process_clicker($request,$symb));
1.400     www      9278:         } elsif ($command eq 'processclickerfile' && $perm{'mgr'}) {
1.608     www      9279:             $request->print(&process_clicker_file($request,$symb));
1.414     www      9280:         } elsif ($command eq 'assignclickergrades' && $perm{'mgr'}) {
1.608     www      9281:             $request->print(&assign_clicker_grades($request,$symb));
1.106     albertel 9282: 	} elsif ($command eq 'csvform' && $perm{'mgr'}) {
1.608     www      9283: 	    $request->print(&upcsvScores_form($request,$symb));
1.106     albertel 9284: 	} elsif ($command eq 'csvupload' && $perm{'mgr'}) {
1.608     www      9285: 	    $request->print(&csvupload($request,$symb));
1.106     albertel 9286: 	} elsif ($command eq 'csvuploadmap' && $perm{'mgr'} ) {
1.608     www      9287: 	    $request->print(&csvuploadmap($request,$symb));
1.246     albertel 9288: 	} elsif ($command eq 'csvuploadoptions' && $perm{'mgr'}) {
1.257     albertel 9289: 	    if ($env{'form.associate'} ne 'Reverse Association') {
1.608     www      9290: 		$request->print(&csvuploadoptions($request,$symb));
1.41      ng       9291: 	    } else {
1.257     albertel 9292: 		if ( $env{'form.upfile_associate'} ne 'reverse' ) {
                   9293: 		    $env{'form.upfile_associate'} = 'reverse';
1.41      ng       9294: 		} else {
1.257     albertel 9295: 		    $env{'form.upfile_associate'} = 'forward';
1.41      ng       9296: 		}
1.608     www      9297: 		$request->print(&csvuploadmap($request,$symb));
1.41      ng       9298: 	    }
1.246     albertel 9299: 	} elsif ($command eq 'csvuploadassign' && $perm{'mgr'} ) {
1.608     www      9300: 	    $request->print(&csvuploadassign($request,$symb));
1.106     albertel 9301: 	} elsif ($command eq 'scantron_selectphase' && $perm{'mgr'}) {
1.608     www      9302: 	    $request->print(&scantron_selectphase($request,$symb));
1.203     albertel 9303:  	} elsif ($command eq 'scantron_warning' && $perm{'mgr'}) {
1.608     www      9304:  	    $request->print(&scantron_do_warning($request,$symb));
1.142     albertel 9305: 	} elsif ($command eq 'scantron_validate' && $perm{'mgr'}) {
1.608     www      9306: 	    $request->print(&scantron_validate_file($request,$symb));
1.106     albertel 9307: 	} elsif ($command eq 'scantron_process' && $perm{'mgr'}) {
1.608     www      9308: 	    $request->print(&scantron_process_students($request,$symb));
1.157     albertel 9309:  	} elsif ($command eq 'scantronupload' && 
1.257     albertel 9310:  		 (&Apache::lonnet::allowed('usc',$env{'request.role.domain'})||
                   9311: 		  &Apache::lonnet::allowed('usc',$env{'request.course.id'}))) {
1.608     www      9312:  	    $request->print(&scantron_upload_scantron_data($request,$symb)); 
1.157     albertel 9313:  	} elsif ($command eq 'scantronupload_save' &&
1.257     albertel 9314:  		 (&Apache::lonnet::allowed('usc',$env{'request.role.domain'})||
                   9315: 		  &Apache::lonnet::allowed('usc',$env{'request.course.id'}))) {
1.608     www      9316:  	    $request->print(&scantron_upload_scantron_data_save($request,$symb));
1.202     albertel 9317:  	} elsif ($command eq 'scantron_download' &&
1.257     albertel 9318: 		 &Apache::lonnet::allowed('usc',$env{'request.course.id'})) {
1.608     www      9319:  	    $request->print(&scantron_download_scantron_data($request,$symb));
1.523     raeburn  9320:         } elsif ($command eq 'checksubmissions' && $perm{'vgr'}) {
1.608     www      9321:             $request->print(&checkscantron_results($request,$symb));     
1.106     albertel 9322: 	} elsif ($command) {
1.562     bisitz   9323: 	    $request->print('<p class="LC_error">'.&mt('Access Denied ([_1])',$command).'</p>');
1.26      albertel 9324: 	}
1.2       albertel 9325:     }
1.513     foxr     9326:     if ($ssi_error) {
                   9327: 	&ssi_print_error($request);
                   9328:     }
1.353     albertel 9329:     $request->print(&Apache::loncommon::end_page());
1.434     albertel 9330:     &reset_caches();
1.44      ng       9331:     return '';
                   9332: }
                   9333: 
1.1       albertel 9334: 1;
                   9335: 
1.13      albertel 9336: __END__;
1.531     jms      9337: 
                   9338: 
                   9339: =head1 NAME
                   9340: 
                   9341: Apache::grades
                   9342: 
                   9343: =head1 SYNOPSIS
                   9344: 
                   9345: Handles the viewing of grades.
                   9346: 
                   9347: This is part of the LearningOnline Network with CAPA project
                   9348: described at http://www.lon-capa.org.
                   9349: 
                   9350: =head1 OVERVIEW
                   9351: 
                   9352: Do an ssi with retries:
                   9353: While I'd love to factor out this with the vesrion in lonprintout,
                   9354: 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
                   9355: I'm not quite ready to invent (e.g. an ssi_with_retry object).
                   9356: 
                   9357: At least the logic that drives this has been pulled out into loncommon.
                   9358: 
                   9359: 
                   9360: 
                   9361: ssi_with_retries - Does the server side include of a resource.
                   9362:                      if the ssi call returns an error we'll retry it up to
                   9363:                      the number of times requested by the caller.
                   9364:                      If we still have a proble, no text is appended to the
                   9365:                      output and we set some global variables.
                   9366:                      to indicate to the caller an SSI error occurred.  
                   9367:                      All of this is supposed to deal with the issues described
                   9368:                      in LonCAPA BZ 5631 see:
                   9369:                      http://bugs.lon-capa.org/show_bug.cgi?id=5631
                   9370:                      by informing the user that this happened.
                   9371: 
                   9372: Parameters:
                   9373:   resource   - The resource to include.  This is passed directly, without
                   9374:                interpretation to lonnet::ssi.
                   9375:   form       - The form hash parameters that guide the interpretation of the resource
                   9376:                
                   9377:   retries    - Number of retries allowed before giving up completely.
                   9378: Returns:
                   9379:   On success, returns the rendered resource identified by the resource parameter.
                   9380: Side Effects:
                   9381:   The following global variables can be set:
                   9382:    ssi_error                - If an unrecoverable error occurred this becomes true.
                   9383:                               It is up to the caller to initialize this to false
                   9384:                               if desired.
                   9385:    ssi_error_resource  - If an unrecoverable error occurred, this is the value
                   9386:                               of the resource that could not be rendered by the ssi
                   9387:                               call.
                   9388:    ssi_error_message   - The error string fetched from the ssi response
                   9389:                               in the event of an error.
                   9390: 
                   9391: 
                   9392: =head1 HANDLER SUBROUTINE
                   9393: 
                   9394: ssi_with_retries()
                   9395: 
                   9396: =head1 SUBROUTINES
                   9397: 
                   9398: =over
                   9399: 
                   9400: =item scantron_get_correction() : 
                   9401: 
                   9402:    Builds the interface screen to interact with the operator to fix a
                   9403:    specific error condition in a specific scanline
                   9404: 
                   9405:  Arguments:
                   9406:     $r           - Apache request object
                   9407:     $i           - number of the current scanline
                   9408:     $scan_record - hash ref as returned from &scantron_parse_scanline()
                   9409:     $scan_config - hash ref as returned from &get_scantron_config()
                   9410:     $line        - full contents of the current scanline
                   9411:     $error       - error condition, valid values are
                   9412:                    'incorrectCODE', 'duplicateCODE',
                   9413:                    'doublebubble', 'missingbubble',
                   9414:                    'duplicateID', 'incorrectID'
                   9415:     $arg         - extra information needed
                   9416:        For errors:
                   9417:          - duplicateID   - paper number that this studentID was seen before on
                   9418:          - duplicateCODE - array ref of the paper numbers this CODE was
                   9419:                            seen on before
                   9420:          - incorrectCODE - current incorrect CODE 
                   9421:          - doublebubble  - array ref of the bubble lines that have double
                   9422:                            bubble errors
                   9423:          - missingbubble - array ref of the bubble lines that have missing
                   9424:                            bubble errors
                   9425: 
                   9426: =item  scantron_get_maxbubble() : 
                   9427: 
1.582     raeburn  9428:    Arguments:
                   9429:        $nav_error  - Reference to scalar which is a flag to indicate a
                   9430:                       failure to retrieve a navmap object.
                   9431:        if $nav_error is set to 1 by scantron_get_maxbubble(), the 
                   9432:        calling routine should trap the error condition and display the warning
                   9433:        found in &navmap_errormsg().
                   9434: 
1.531     jms      9435:    Returns the maximum number of bubble lines that are expected to
                   9436:    occur. Does this by walking the selected sequence rendering the
                   9437:    resource and then checking &Apache::lonxml::get_problem_counter()
                   9438:    for what the current value of the problem counter is.
                   9439: 
                   9440:    Caches the results to $env{'form.scantron_maxbubble'},
                   9441:    $env{'form.scantron.bubble_lines.n'}, 
                   9442:    $env{'form.scantron.first_bubble_line.n'} and
                   9443:    $env{"form.scantron.sub_bubblelines.n"}
                   9444:    which are the total number of bubble, lines, the number of bubble
                   9445:    lines for response n and number of the first bubble line for response n,
                   9446:    and a comma separated list of numbers of bubble lines for sub-questions
                   9447:    (for optionresponse, matchresponse, and rankresponse items), for response n.  
                   9448: 
                   9449: 
                   9450: =item  scantron_validate_missingbubbles() : 
                   9451: 
                   9452:    Validates all scanlines in the selected file to not have any
                   9453:     answers that don't have bubbles that have not been verified
                   9454:     to be bubble free.
                   9455: 
                   9456: =item  scantron_process_students() : 
                   9457: 
                   9458:    Routine that does the actual grading of the bubble sheet information.
                   9459: 
                   9460:    The parsed scanline hash is added to %env 
                   9461: 
                   9462:    Then foreach unskipped scanline it does an &Apache::lonnet::ssi()
                   9463:    foreach resource , with the form data of
                   9464: 
                   9465: 	'submitted'     =>'scantron' 
                   9466: 	'grade_target'  =>'grade',
                   9467: 	'grade_username'=> username of student
                   9468: 	'grade_domain'  => domain of student
                   9469: 	'grade_courseid'=> of course
                   9470: 	'grade_symb'    => symb of resource to grade
                   9471: 
                   9472:     This triggers a grading pass. The problem grading code takes care
                   9473:     of converting the bubbled letter information (now in %env) into a
                   9474:     valid submission.
                   9475: 
                   9476: =item  scantron_upload_scantron_data() :
                   9477: 
                   9478:     Creates the screen for adding a new bubble sheet data file to a course.
                   9479: 
                   9480: =item  scantron_upload_scantron_data_save() : 
                   9481: 
                   9482:    Adds a provided bubble information data file to the course if user
                   9483:    has the correct privileges to do so. 
                   9484: 
                   9485: =item  valid_file() :
                   9486: 
                   9487:    Validates that the requested bubble data file exists in the course.
                   9488: 
                   9489: =item  scantron_download_scantron_data() : 
                   9490: 
                   9491:    Shows a list of the three internal files (original, corrected,
                   9492:    skipped) for a specific bubble sheet data file that exists in the
                   9493:    course.
                   9494: 
                   9495: =item  scantron_validate_ID() : 
                   9496: 
                   9497:    Validates all scanlines in the selected file to not have any
1.556     weissno  9498:    invalid or underspecified student/employee IDs
1.531     jms      9499: 
1.582     raeburn  9500: =item navmap_errormsg() :
                   9501: 
                   9502:    Returns HTML mark-up inside a <div></div> with a link to re-initialize the course.
                   9503:    Should be called whenever the request to instantiate a navmap object fails.  
                   9504: 
1.531     jms      9505: =back
                   9506: 
                   9507: =cut

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