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

1.17      albertel    1: # The LearningOnline Network with CAPA
1.13      albertel    2: # The LON-CAPA Grading handler
1.17      albertel    3: #
1.618   ! www         4: # $Id: grades.pm,v 1.617 2010/04/13 16:12:54 www Exp $
1.17      albertel    5: #
                      6: # Copyright Michigan State University Board of Trustees
                      7: #
                      8: # This file is part of the LearningOnline Network with CAPA (LON-CAPA).
                      9: #
                     10: # LON-CAPA is free software; you can redistribute it and/or modify
                     11: # it under the terms of the GNU General Public License as published by
                     12: # the Free Software Foundation; either version 2 of the License, or
                     13: # (at your option) any later version.
                     14: #
                     15: # LON-CAPA is distributed in the hope that it will be useful,
                     16: # but WITHOUT ANY WARRANTY; without even the implied warranty of
                     17: # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
                     18: # GNU General Public License for more details.
                     19: #
                     20: # You should have received a copy of the GNU General Public License
                     21: # along with LON-CAPA; if not, write to the Free Software
                     22: # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
                     23: #
                     24: # /home/httpd/html/adm/gpl.txt
                     25: #
                     26: # http://www.lon-capa.org/
                     27: #
1.1       albertel   28: 
1.529     jms        29: 
                     30: 
1.1       albertel   31: package Apache::grades;
                     32: use strict;
                     33: use Apache::style;
                     34: use Apache::lonxml;
                     35: use Apache::lonnet;
1.3       albertel   36: use Apache::loncommon;
1.112     ng         37: use Apache::lonhtmlcommon;
1.68      ng         38: use Apache::lonnavmaps;
1.1       albertel   39: use Apache::lonhomework;
1.456     banghart   40: use Apache::lonpickcode;
1.55      matthew    41: use Apache::loncoursedata;
1.362     albertel   42: use Apache::lonmsg();
1.1       albertel   43: use Apache::Constants qw(:common);
1.167     sakharuk   44: use Apache::lonlocal;
1.386     raeburn    45: use Apache::lonenc;
1.170     albertel   46: use String::Similarity;
1.359     www        47: use LONCAPA;
                     48: 
1.315     bowersj2   49: use POSIX qw(floor);
1.87      www        50: 
1.435     foxr       51: 
1.513     foxr       52: 
1.435     foxr       53: my %perm=();
1.447     foxr       54: 
1.513     foxr       55: #  These variables are used to recover from ssi errors
                     56: 
                     57: my $ssi_retries = 5;
                     58: my $ssi_error;
                     59: my $ssi_error_resource;
                     60: my $ssi_error_message;
                     61: 
                     62: 
                     63: sub ssi_with_retries {
                     64:     my ($resource, $retries, %form) = @_;
                     65:     my ($content, $response) = &Apache::loncommon::ssi_with_retries($resource, $retries, %form);
                     66:     if ($response->is_error) {
                     67: 	$ssi_error          = 1;
                     68: 	$ssi_error_resource = $resource;
                     69: 	$ssi_error_message  = $response->code . " " . $response->message;
                     70:     }
                     71: 
                     72:     return $content;
                     73: 
                     74: }
                     75: #
                     76: #  Prodcuces an ssi retry failure error message to the user:
                     77: #
                     78: 
                     79: sub ssi_print_error {
                     80:     my ($r) = @_;
1.516     raeburn    81:     my $helpurl = &Apache::loncommon::top_nav_help('Helpdesk');
                     82:     $r->print('
                     83: <br />
                     84: <h2>'.&mt('An unrecoverable network error occurred:').'</h2>
                     85: <p>
                     86: '.&mt('Unable to retrieve a resource from a server:').'<br />
                     87: '.&mt('Resource:').' '.$ssi_error_resource.'<br />
                     88: '.&mt('Error:').' '.$ssi_error_message.'
                     89: </p>
                     90: <p>'.
                     91: &mt('It is recommended that you try again later, as this error may mean the server was just temporarily unavailable, or is down for maintenance.').'<br />'.
                     92: &mt('If the error persists, please contact the [_1] for assistance.',$helpurl).
                     93: '</p>');
                     94:     return;
1.513     foxr       95: }
                     96: 
1.44      ng         97: #
1.146     albertel   98: # --- Retrieve the parts from the metadata file.---
1.598     www        99: # Returns an array of everything that the resources stores away
                    100: #
                    101: 
1.44      ng        102: sub getpartlist {
1.582     raeburn   103:     my ($symb,$errorref) = @_;
1.439     albertel  104: 
                    105:     my $navmap   = Apache::lonnavmaps::navmap->new();
1.582     raeburn   106:     unless (ref($navmap)) {
                    107:         if (ref($errorref)) { 
                    108:             $$errorref = 'navmap';
                    109:             return;
                    110:         }
                    111:     }
1.439     albertel  112:     my $res      = $navmap->getBySymb($symb);
                    113:     my $partlist = $res->parts();
                    114:     my $url      = $res->src();
                    115:     my @metakeys = split(/,/,&Apache::lonnet::metadata($url,'keys'));
                    116: 
1.146     albertel  117:     my @stores;
1.439     albertel  118:     foreach my $part (@{ $partlist }) {
1.146     albertel  119: 	foreach my $key (@metakeys) {
                    120: 	    if ($key =~ m/^stores_\Q$part\E_/) { push(@stores,$key); }
                    121: 	}
                    122:     }
                    123:     return @stores;
1.2       albertel  124: }
                    125: 
1.129     ng        126: #--- Format fullname, username:domain if different for display
                    127: #--- Use anywhere where the student names are listed
                    128: sub nameUserString {
                    129:     my ($type,$fullname,$uname,$udom) = @_;
                    130:     if ($type eq 'header') {
1.485     albertel  131: 	return '<b>&nbsp;'.&mt('Fullname').'&nbsp;</b><span class="LC_internal_info">('.&mt('Username').')</span>';
1.129     ng        132:     } else {
1.398     albertel  133: 	return '&nbsp;'.$fullname.'<span class="LC_internal_info">&nbsp;('.$uname.
                    134: 	    ($env{'user.domain'} eq $udom ? '' : ' ('.$udom.')').')</span>';
1.129     ng        135:     }
                    136: }
                    137: 
1.44      ng        138: #--- Get the partlist and the response type for a given problem. ---
                    139: #--- Indicate if a response type is coded handgraded or not. ---
1.39      ng        140: sub response_type {
1.582     raeburn   141:     my ($symb,$response_error) = @_;
1.377     albertel  142: 
                    143:     my $navmap = Apache::lonnavmaps::navmap->new();
1.582     raeburn   144:     unless (ref($navmap)) {
                    145:         if (ref($response_error)) {
                    146:             $$response_error = 1;
                    147:         }
                    148:         return;
                    149:     }
1.377     albertel  150:     my $res = $navmap->getBySymb($symb);
1.593     raeburn   151:     unless (ref($res)) {
                    152:         $$response_error = 1;
                    153:         return;
                    154:     }
1.377     albertel  155:     my $partlist = $res->parts();
1.392     albertel  156:     my %vPart = 
                    157: 	map { $_ => 1 } (&Apache::loncommon::get_env_multiple('form.vPart'));
1.377     albertel  158:     my (%response_types,%handgrade);
                    159:     foreach my $part (@{ $partlist }) {
1.392     albertel  160: 	next if (%vPart && !exists($vPart{$part}));
                    161: 
1.377     albertel  162: 	my @types = $res->responseType($part);
                    163: 	my @ids = $res->responseIds($part);
                    164: 	for (my $i=0; $i < scalar(@ids); $i++) {
                    165: 	    $response_types{$part}{$ids[$i]} = $types[$i];
                    166: 	    $handgrade{$part.'_'.$ids[$i]} = 
                    167: 		&Apache::lonnet::EXT('resource.'.$part.'_'.$ids[$i].
                    168: 				     '.handgrade',$symb);
1.41      ng        169: 	}
                    170:     }
1.377     albertel  171:     return ($partlist,\%handgrade,\%response_types);
1.39      ng        172: }
                    173: 
1.375     albertel  174: sub flatten_responseType {
                    175:     my ($responseType) = @_;
                    176:     my @part_response_id =
                    177: 	map { 
                    178: 	    my $part = $_;
                    179: 	    map {
                    180: 		[$part,$_]
                    181: 		} sort(keys(%{ $responseType->{$part} }));
                    182: 	} sort(keys(%$responseType));
                    183:     return @part_response_id;
                    184: }
                    185: 
1.207     albertel  186: sub get_display_part {
1.324     albertel  187:     my ($partID,$symb)=@_;
1.207     albertel  188:     my $display=&Apache::lonnet::EXT('resource.'.$partID.'.display',$symb);
                    189:     if (defined($display) and $display ne '') {
1.577     bisitz    190:         $display.= ' (<span class="LC_internal_info">'
                    191:                   .&mt('Part ID: [_1]',$partID).'</span>)';
1.207     albertel  192:     } else {
                    193: 	$display=$partID;
                    194:     }
                    195:     return $display;
                    196: }
1.269     raeburn   197: 
1.434     albertel  198: sub reset_caches {
                    199:     &reset_analyze_cache();
                    200:     &reset_perm();
                    201: }
                    202: 
                    203: {
                    204:     my %analyze_cache;
1.557     raeburn   205:     my %analyze_cache_formkeys;
1.148     albertel  206: 
1.434     albertel  207:     sub reset_analyze_cache {
                    208: 	undef(%analyze_cache);
1.557     raeburn   209:         undef(%analyze_cache_formkeys);
1.434     albertel  210:     }
                    211: 
                    212:     sub get_analyze {
1.557     raeburn   213: 	my ($symb,$uname,$udom,$no_increment,$add_to_hash)=@_;
1.434     albertel  214: 	my $key = "$symb\0$uname\0$udom";
1.557     raeburn   215: 	if (exists($analyze_cache{$key})) {
                    216:             my $getupdate = 0;
                    217:             if (ref($add_to_hash) eq 'HASH') {
                    218:                 foreach my $item (keys(%{$add_to_hash})) {
                    219:                     if (ref($analyze_cache_formkeys{$key}) eq 'HASH') {
                    220:                         if (!exists($analyze_cache_formkeys{$key}{$item})) {
                    221:                             $getupdate = 1;
                    222:                             last;
                    223:                         }
                    224:                     } else {
                    225:                         $getupdate = 1;
                    226:                     }
                    227:                 }
                    228:             }
                    229:             if (!$getupdate) {
                    230:                 return $analyze_cache{$key};
                    231:             }
                    232:         }
1.434     albertel  233: 
                    234: 	my (undef,undef,$url)=&Apache::lonnet::decode_symb($symb);
                    235: 	$url=&Apache::lonnet::clutter($url);
1.557     raeburn   236:         my %form = ('grade_target'      => 'analyze',
                    237:                     'grade_domain'      => $udom,
                    238:                     'grade_symb'        => $symb,
                    239:                     'grade_courseid'    =>  $env{'request.course.id'},
                    240:                     'grade_username'    => $uname,
                    241:                     'grade_noincrement' => $no_increment);
                    242:         if (ref($add_to_hash)) {
                    243:             %form = (%form,%{$add_to_hash});
                    244:         } 
                    245: 	my $subresult=&ssi_with_retries($url, $ssi_retries,%form);
1.434     albertel  246: 	(undef,$subresult)=split(/_HASH_REF__/,$subresult,2);
                    247: 	my %analyze=&Apache::lonnet::str2hash($subresult);
1.557     raeburn   248:         if (ref($add_to_hash) eq 'HASH') {
                    249:             $analyze_cache_formkeys{$key} = $add_to_hash;
                    250:         } else {
                    251:             $analyze_cache_formkeys{$key} = {};
                    252:         }
1.434     albertel  253: 	return $analyze_cache{$key} = \%analyze;
                    254:     }
                    255: 
                    256:     sub get_order {
1.525     raeburn   257: 	my ($partid,$respid,$symb,$uname,$udom,$no_increment)=@_;
                    258: 	my $analyze = &get_analyze($symb,$uname,$udom,$no_increment);
1.434     albertel  259: 	return $analyze->{"$partid.$respid.shown"};
                    260:     }
                    261: 
                    262:     sub get_radiobutton_correct_foil {
                    263: 	my ($partid,$respid,$symb,$uname,$udom)=@_;
                    264: 	my $analyze = &get_analyze($symb,$uname,$udom);
1.555     raeburn   265:         my $foils = &get_order($partid,$respid,$symb,$uname,$udom);
                    266:         if (ref($foils) eq 'ARRAY') {
                    267: 	    foreach my $foil (@{$foils}) {
                    268: 	        if ($analyze->{"$partid.$respid.foil.value.$foil"} eq 'true') {
                    269: 		    return $foil;
                    270: 	        }
1.434     albertel  271: 	    }
                    272: 	}
                    273:     }
1.554     raeburn   274: 
                    275:     sub scantron_partids_tograde {
1.557     raeburn   276:         my ($resource,$cid,$uname,$udom,$check_for_randomlist) = @_;
1.554     raeburn   277:         my (%analysis,@parts);
                    278:         if (ref($resource)) {
                    279:             my $symb = $resource->symb();
1.557     raeburn   280:             my $add_to_form;
                    281:             if ($check_for_randomlist) {
                    282:                 $add_to_form = { 'check_parts_withrandomlist' => 1,};
                    283:             }
                    284:             my $analyze = &get_analyze($symb,$uname,$udom,undef,$add_to_form);
1.554     raeburn   285:             if (ref($analyze) eq 'HASH') {
                    286:                 %analysis = %{$analyze};
                    287:             }
                    288:             if (ref($analysis{'parts'}) eq 'ARRAY') {
                    289:                 foreach my $part (@{$analysis{'parts'}}) {
                    290:                     my ($id,$respid) = split(/\./,$part);
                    291:                     if (!&Apache::loncommon::check_if_partid_hidden($id,$symb,$udom,$uname)) {
                    292:                         push(@parts,$part);
                    293:                     }
                    294:                 }
                    295:             }
                    296:         }
                    297:         return (\%analysis,\@parts);
                    298:     }
                    299: 
1.148     albertel  300: }
1.434     albertel  301: 
1.118     ng        302: #--- Clean response type for display
1.335     albertel  303: #--- Currently filters option/rank/radiobutton/match/essay/Task
                    304: #        response types only.
1.118     ng        305: sub cleanRecord {
1.336     albertel  306:     my ($answer,$response,$symb,$partid,$respid,$record,$order,$version,
                    307: 	$uname,$udom) = @_;
1.398     albertel  308:     my $grayFont = '<span class="LC_internal_info">';
1.148     albertel  309:     if ($response =~ /^(option|rank)$/) {
                    310: 	my %answer=&Apache::lonnet::str2hash($answer);
                    311: 	my %grading=&Apache::lonnet::str2hash($record->{$version."resource.$partid.$respid.submissiongrading"});
                    312: 	my ($toprow,$bottomrow);
                    313: 	foreach my $foil (@$order) {
                    314: 	    if ($grading{$foil} == 1) {
                    315: 		$toprow.='<td><b>'.$answer{$foil}.'&nbsp;</b></td>';
                    316: 	    } else {
                    317: 		$toprow.='<td><i>'.$answer{$foil}.'&nbsp;</i></td>';
                    318: 	    }
1.398     albertel  319: 	    $bottomrow.='<td>'.$grayFont.$foil.'</span>&nbsp;</td>';
1.148     albertel  320: 	}
                    321: 	return '<blockquote><table border="1">'.
1.466     albertel  322: 	    '<tr valign="top"><td>'.&mt('Answer').'</td>'.$toprow.'</tr>'.
                    323: 	    '<tr valign="top"><td>'.$grayFont.&mt('Option ID').'</span></td>'.
1.148     albertel  324: 	    $grayFont.$bottomrow.'</tr>'.'</table></blockquote>';
                    325:     } elsif ($response eq 'match') {
                    326: 	my %answer=&Apache::lonnet::str2hash($answer);
                    327: 	my %grading=&Apache::lonnet::str2hash($record->{$version."resource.$partid.$respid.submissiongrading"});
                    328: 	my @items=&Apache::lonnet::str2array($record->{$version."resource.$partid.$respid.submissionitems"});
                    329: 	my ($toprow,$middlerow,$bottomrow);
                    330: 	foreach my $foil (@$order) {
                    331: 	    my $item=shift(@items);
                    332: 	    if ($grading{$foil} == 1) {
                    333: 		$toprow.='<td><b>'.$item.'&nbsp;</b></td>';
1.398     albertel  334: 		$middlerow.='<td><b>'.$grayFont.$answer{$foil}.'&nbsp;</span></b></td>';
1.148     albertel  335: 	    } else {
                    336: 		$toprow.='<td><i>'.$item.'&nbsp;</i></td>';
1.398     albertel  337: 		$middlerow.='<td><i>'.$grayFont.$answer{$foil}.'&nbsp;</span></i></td>';
1.148     albertel  338: 	    }
1.398     albertel  339: 	    $bottomrow.='<td>'.$grayFont.$foil.'</span>&nbsp;</td>';
1.118     ng        340: 	}
1.126     ng        341: 	return '<blockquote><table border="1">'.
1.466     albertel  342: 	    '<tr valign="top"><td>'.&mt('Answer').'</td>'.$toprow.'</tr>'.
                    343: 	    '<tr valign="top"><td>'.$grayFont.&mt('Item ID').'</span></td>'.
1.148     albertel  344: 	    $middlerow.'</tr>'.
1.466     albertel  345: 	    '<tr valign="top"><td>'.$grayFont.&mt('Option ID').'</span></td>'.
1.148     albertel  346: 	    $bottomrow.'</tr>'.'</table></blockquote>';
                    347:     } elsif ($response eq 'radiobutton') {
                    348: 	my %answer=&Apache::lonnet::str2hash($answer);
                    349: 	my ($toprow,$bottomrow);
1.434     albertel  350: 	my $correct = 
                    351: 	    &get_radiobutton_correct_foil($partid,$respid,$symb,$uname,$udom);
                    352: 	foreach my $foil (@$order) {
1.148     albertel  353: 	    if (exists($answer{$foil})) {
1.434     albertel  354: 		if ($foil eq $correct) {
1.466     albertel  355: 		    $toprow.='<td><b>'.&mt('true').'</b></td>';
1.148     albertel  356: 		} else {
1.466     albertel  357: 		    $toprow.='<td><i>'.&mt('true').'</i></td>';
1.148     albertel  358: 		}
                    359: 	    } else {
1.466     albertel  360: 		$toprow.='<td>'.&mt('false').'</td>';
1.148     albertel  361: 	    }
1.398     albertel  362: 	    $bottomrow.='<td>'.$grayFont.$foil.'</span>&nbsp;</td>';
1.148     albertel  363: 	}
                    364: 	return '<blockquote><table border="1">'.
1.466     albertel  365: 	    '<tr valign="top"><td>'.&mt('Answer').'</td>'.$toprow.'</tr>'.
                    366: 	    '<tr valign="top"><td>'.$grayFont.&mt('Option ID').'</span></td>'.
1.597     wenzelju  367: 	    $bottomrow.'</tr>'.'</table></blockquote>';
1.148     albertel  368:     } elsif ($response eq 'essay') {
1.257     albertel  369: 	if (! exists ($env{'form.'.$symb})) {
1.122     ng        370: 	    my (%keyhash) = &Apache::lonnet::dump('nohist_handgrade',
1.257     albertel  371: 						  $env{'course.'.$env{'request.course.id'}.'.domain'},
                    372: 						  $env{'course.'.$env{'request.course.id'}.'.num'});
1.122     ng        373: 
1.257     albertel  374: 	    my $loginuser = $env{'user.name'}.':'.$env{'user.domain'};
                    375: 	    $env{'form.keywords'} = $keyhash{$symb.'_keywords'} ne '' ? $keyhash{$symb.'_keywords'} : '';
                    376: 	    $env{'form.kwclr'}    = $keyhash{$loginuser.'_kwclr'} ne '' ? $keyhash{$loginuser.'_kwclr'} : 'red';
                    377: 	    $env{'form.kwsize'}   = $keyhash{$loginuser.'_kwsize'} ne '' ? $keyhash{$loginuser.'_kwsize'} : '0';
                    378: 	    $env{'form.kwstyle'}  = $keyhash{$loginuser.'_kwstyle'} ne '' ? $keyhash{$loginuser.'_kwstyle'} : '';
                    379: 	    $env{'form.'.$symb} = 1; # so that we don't have to read it from disk for multiple sub of the same prob.
1.122     ng        380: 	}
1.166     albertel  381: 	$answer =~ s-\n-<br />-g;
                    382: 	return '<br /><br /><blockquote><tt>'.&keywords_highlight($answer).'</tt></blockquote>';
1.268     albertel  383:     } elsif ( $response eq 'organic') {
                    384: 	my $result='Smile representation: "<tt>'.$answer.'</tt>"';
                    385: 	my $jme=$record->{$version."resource.$partid.$respid.molecule"};
                    386: 	$result.=&Apache::chemresponse::jme_img($jme,$answer,400);
                    387: 	return $result;
1.335     albertel  388:     } elsif ( $response eq 'Task') {
                    389: 	if ( $answer eq 'SUBMITTED') {
                    390: 	    my $files = $record->{$version."resource.$respid.$partid.bridgetask.portfiles"};
1.336     albertel  391: 	    my $result = &Apache::bridgetask::file_list($files,$uname,$udom);
1.335     albertel  392: 	    return $result;
                    393: 	} elsif ( grep(/^\Q$version\E.*?\.instance$/, keys(%{$record})) ) {
                    394: 	    my @matches = grep(/^\Q$version\E.*?\.instance$/,
                    395: 			       keys(%{$record}));
                    396: 	    return join('<br />',($version,@matches));
                    397: 			       
                    398: 			       
                    399: 	} else {
                    400: 	    my $result =
                    401: 		'<p>'
                    402: 		.&mt('Overall result: [_1]',
                    403: 		     $record->{$version."resource.$respid.$partid.status"})
                    404: 		.'</p>';
                    405: 	    
                    406: 	    $result .= '<ul>';
                    407: 	    my @grade = grep(/^\Q${version}resource.$respid.$partid.\E[^.]*[.]status$/,
                    408: 			     keys(%{$record}));
                    409: 	    foreach my $grade (sort(@grade)) {
                    410: 		my ($dim) = ($grade =~/[.]([^.]+)[.]status$/);
                    411: 		$result.= '<li>'.&mt("Dimension: [_1], status [_2] ",
                    412: 				     $dim, $record->{$grade}).
                    413: 			  '</li>';
                    414: 	    }
                    415: 	    $result.='</ul>';
                    416: 	    return $result;
                    417: 	}
1.440     albertel  418:     } elsif ( $response =~ m/(?:numerical|formula)/) {
                    419: 	$answer = 
                    420: 	    &Apache::loncommon::format_previous_attempt_value('submission',
                    421: 							      $answer);
1.122     ng        422:     }
1.118     ng        423:     return $answer;
                    424: }
                    425: 
                    426: #-- A couple of common js functions
                    427: sub commonJSfunctions {
                    428:     my $request = shift;
1.597     wenzelju  429:     $request->print(&Apache::lonhtmlcommon::scripttag(<<COMMONJSFUNCTIONS));
1.118     ng        430:     function radioSelection(radioButton) {
                    431: 	var selection=null;
                    432: 	if (radioButton.length > 1) {
                    433: 	    for (var i=0; i<radioButton.length; i++) {
                    434: 		if (radioButton[i].checked) {
                    435: 		    return radioButton[i].value;
                    436: 		}
                    437: 	    }
                    438: 	} else {
                    439: 	    if (radioButton.checked) return radioButton.value;
                    440: 	}
                    441: 	return selection;
                    442:     }
                    443: 
                    444:     function pullDownSelection(selectOne) {
                    445: 	var selection="";
                    446: 	if (selectOne.length > 1) {
                    447: 	    for (var i=0; i<selectOne.length; i++) {
                    448: 		if (selectOne[i].selected) {
                    449: 		    return selectOne[i].value;
                    450: 		}
                    451: 	    }
                    452: 	} else {
1.138     albertel  453:             // only one value it must be the selected one
                    454: 	    return selectOne.value;
1.118     ng        455: 	}
                    456:     }
                    457: COMMONJSFUNCTIONS
                    458: }
                    459: 
1.44      ng        460: #--- Dumps the class list with usernames,list of sections,
                    461: #--- section, ids and fullnames for each user.
                    462: sub getclasslist {
1.449     banghart  463:     my ($getsec,$filterlist,$getgroup) = @_;
1.291     albertel  464:     my @getsec;
1.450     banghart  465:     my @getgroup;
1.442     banghart  466:     my $stu_status = join(':',&Apache::loncommon::get_env_multiple('form.Status'));
1.291     albertel  467:     if (!ref($getsec)) {
                    468: 	if ($getsec ne '' && $getsec ne 'all') {
                    469: 	    @getsec=($getsec);
                    470: 	}
                    471:     } else {
                    472: 	@getsec=@{$getsec};
                    473:     }
                    474:     if (grep(/^all$/,@getsec)) { undef(@getsec); }
1.450     banghart  475:     if (!ref($getgroup)) {
                    476: 	if ($getgroup ne '' && $getgroup ne 'all') {
                    477: 	    @getgroup=($getgroup);
                    478: 	}
                    479:     } else {
                    480: 	@getgroup=@{$getgroup};
                    481:     }
                    482:     if (grep(/^all$/,@getgroup)) { undef(@getgroup); }
1.291     albertel  483: 
1.449     banghart  484:     my ($classlist,$keylist)=&Apache::loncoursedata::get_classlist();
1.49      albertel  485:     # Bail out if we were unable to get the classlist
1.56      matthew   486:     return if (! defined($classlist));
1.449     banghart  487:     &Apache::loncoursedata::get_group_memberships($classlist,$keylist);
1.56      matthew   488:     #
                    489:     my %sections;
                    490:     my %fullnames;
1.205     matthew   491:     foreach my $student (keys(%$classlist)) {
                    492:         my $end      = 
                    493:             $classlist->{$student}->[&Apache::loncoursedata::CL_END()];
                    494:         my $start    = 
                    495:             $classlist->{$student}->[&Apache::loncoursedata::CL_START()];
                    496:         my $id       = 
                    497:             $classlist->{$student}->[&Apache::loncoursedata::CL_ID()];
                    498:         my $section  = 
                    499:             $classlist->{$student}->[&Apache::loncoursedata::CL_SECTION()];
                    500:         my $fullname = 
                    501:             $classlist->{$student}->[&Apache::loncoursedata::CL_FULLNAME()];
                    502:         my $status   = 
                    503:             $classlist->{$student}->[&Apache::loncoursedata::CL_STATUS()];
1.449     banghart  504:         my $group   = 
                    505:             $classlist->{$student}->[&Apache::loncoursedata::CL_GROUP()];
1.76      ng        506: 	# filter students according to status selected
1.442     banghart  507: 	if ($filterlist && (!($stu_status =~ /Any/))) {
                    508: 	    if (!($stu_status =~ $status)) {
1.450     banghart  509: 		delete($classlist->{$student});
1.76      ng        510: 		next;
                    511: 	    }
                    512: 	}
1.450     banghart  513: 	# filter students according to groups selected
1.453     banghart  514: 	my @stu_groups = split(/,/,$group);
1.450     banghart  515: 	if (@getgroup) {
                    516: 	    my $exclude = 1;
1.454     banghart  517: 	    foreach my $grp (@getgroup) {
                    518: 	        foreach my $stu_group (@stu_groups) {
1.453     banghart  519: 	            if ($stu_group eq $grp) {
                    520: 	                $exclude = 0;
                    521:     	            } 
1.450     banghart  522: 	        }
1.453     banghart  523:     	        if (($grp eq 'none') && !$group) {
                    524:         	        $exclude = 0;
                    525:         	}
1.450     banghart  526: 	    }
                    527: 	    if ($exclude) {
                    528: 	        delete($classlist->{$student});
                    529: 	    }
                    530: 	}
1.205     matthew   531: 	$section = ($section ne '' ? $section : 'none');
1.106     albertel  532: 	if (&canview($section)) {
1.291     albertel  533: 	    if (!@getsec || grep(/^\Q$section\E$/,@getsec)) {
1.103     albertel  534: 		$sections{$section}++;
1.450     banghart  535: 		if ($classlist->{$student}) {
                    536: 		    $fullnames{$student}=$fullname;
                    537: 		}
1.103     albertel  538: 	    } else {
1.205     matthew   539: 		delete($classlist->{$student});
1.103     albertel  540: 	    }
                    541: 	} else {
1.205     matthew   542: 	    delete($classlist->{$student});
1.103     albertel  543: 	}
1.44      ng        544:     }
                    545:     my %seen = ();
1.56      matthew   546:     my @sections = sort(keys(%sections));
                    547:     return ($classlist,\@sections,\%fullnames);
1.44      ng        548: }
                    549: 
1.103     albertel  550: sub canmodify {
                    551:     my ($sec)=@_;
                    552:     if ($perm{'mgr'}) {
                    553: 	if (!defined($perm{'mgr_section'})) {
                    554: 	    # can modify whole class
                    555: 	    return 1;
                    556: 	} else {
                    557: 	    if ($sec eq $perm{'mgr_section'}) {
                    558: 		#can modify the requested section
                    559: 		return 1;
                    560: 	    } else {
                    561: 		# can't modify the request section
                    562: 		return 0;
                    563: 	    }
                    564: 	}
                    565:     }
                    566:     #can't modify
                    567:     return 0;
                    568: }
                    569: 
                    570: sub canview {
                    571:     my ($sec)=@_;
                    572:     if ($perm{'vgr'}) {
                    573: 	if (!defined($perm{'vgr_section'})) {
                    574: 	    # can modify whole class
                    575: 	    return 1;
                    576: 	} else {
                    577: 	    if ($sec eq $perm{'vgr_section'}) {
                    578: 		#can modify the requested section
                    579: 		return 1;
                    580: 	    } else {
                    581: 		# can't modify the request section
                    582: 		return 0;
                    583: 	    }
                    584: 	}
                    585:     }
                    586:     #can't modify
                    587:     return 0;
                    588: }
                    589: 
1.44      ng        590: #--- Retrieve the grade status of a student for all the parts
                    591: sub student_gradeStatus {
1.324     albertel  592:     my ($symb,$udom,$uname,$partlist) = @_;
1.257     albertel  593:     my %record     = &Apache::lonnet::restore($symb,$env{'request.course.id'},$udom,$uname);
1.44      ng        594:     my %partstatus = ();
                    595:     foreach (@$partlist) {
1.128     ng        596: 	my ($status,undef)   = split(/_/,$record{"resource.$_.solved"},2);
1.44      ng        597: 	$status              = 'nothing' if ($status eq '');
                    598: 	$partstatus{$_}      = $status;
                    599: 	my $subkey           = "resource.$_.submitted_by";
                    600: 	$partstatus{$subkey} = $record{$subkey} if ($record{$subkey} ne '');
                    601:     }
                    602:     return %partstatus;
                    603: }
                    604: 
1.45      ng        605: # hidden form and javascript that calls the form
                    606: # Use by verifyscript and viewgrades
                    607: # Shows a student's view of problem and submission
                    608: sub jscriptNform {
1.324     albertel  609:     my ($symb) = @_;
1.442     banghart  610:     my $stu_status = join(':',&Apache::loncommon::get_env_multiple('form.Status'));
1.597     wenzelju  611:     my $jscript= &Apache::lonhtmlcommon::scripttag(
1.45      ng        612: 	'    function viewOneStudent(user,domain) {'."\n".
                    613: 	'	document.onestudent.student.value = user;'."\n".
                    614: 	'	document.onestudent.userdom.value = domain;'."\n".
                    615: 	'	document.onestudent.submit();'."\n".
                    616: 	'    }'."\n".
1.597     wenzelju  617: 	"\n");
1.45      ng        618:     $jscript.= '<form action="/adm/grades" method="post" name="onestudent">'."\n".
1.418     albertel  619: 	'<input type="hidden" name="symb"    value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
1.442     banghart  620: 	'<input type="hidden" name="Status"  value="'.$stu_status.'" />'."\n".
1.45      ng        621: 	'<input type="hidden" name="command" value="submission" />'."\n".
                    622: 	'<input type="hidden" name="student" value="" />'."\n".
                    623: 	'<input type="hidden" name="userdom" value="" />'."\n".
                    624: 	'</form>'."\n";
                    625:     return $jscript;
                    626: }
1.39      ng        627: 
1.447     foxr      628: 
                    629: 
1.315     bowersj2  630: # Given the score (as a number [0-1] and the weight) what is the final
                    631: # point value? This function will round to the nearest tenth, third,
                    632: # or quarter if one of those is within the tolerance of .00001.
1.316     albertel  633: sub compute_points {
1.315     bowersj2  634:     my ($score, $weight) = @_;
                    635:     
                    636:     my $tolerance = .00001;
                    637:     my $points = $score * $weight;
                    638: 
                    639:     # Check for nearness to 1/x.
                    640:     my $check_for_nearness = sub {
                    641:         my ($factor) = @_;
                    642:         my $num = ($points * $factor) + $tolerance;
                    643:         my $floored_num = floor($num);
1.316     albertel  644:         if ($num - $floored_num < 2 * $tolerance * $factor) {
1.315     bowersj2  645:             return $floored_num / $factor;
                    646:         }
                    647:         return $points;
                    648:     };
                    649: 
                    650:     $points = $check_for_nearness->(10);
                    651:     $points = $check_for_nearness->(3);
                    652:     $points = $check_for_nearness->(4);
                    653:     
                    654:     return $points;
                    655: }
                    656: 
1.44      ng        657: #------------------ End of general use routines --------------------
1.87      www       658: 
                    659: #
                    660: # Find most similar essay
                    661: #
                    662: 
                    663: sub most_similar {
1.426     albertel  664:     my ($uname,$udom,$uessay,$old_essays)=@_;
1.87      www       665: 
                    666: # ignore spaces and punctuation
                    667: 
                    668:     $uessay=~s/\W+/ /gs;
                    669: 
1.282     www       670: # ignore empty submissions (occuring when only files are sent)
                    671: 
1.598     www       672:     unless ($uessay=~/\w+/s) { return ''; }
1.282     www       673: 
1.87      www       674: # these will be returned. Do not care if not at least 50 percent similar
1.88      www       675:     my $limit=0.6;
1.87      www       676:     my $sname='';
                    677:     my $sdom='';
                    678:     my $scrsid='';
                    679:     my $sessay='';
                    680: # go through all essays ...
1.426     albertel  681:     foreach my $tkey (keys(%$old_essays)) {
                    682: 	my ($tname,$tdom,$tcrsid)=map {&unescape($_)} (split(/\./,$tkey));
1.87      www       683: # ... except the same student
1.426     albertel  684:         next if (($tname eq $uname) && ($tdom eq $udom));
                    685: 	my $tessay=$old_essays->{$tkey};
                    686: 	$tessay=~s/\W+/ /gs;
1.87      www       687: # String similarity gives up if not even limit
1.426     albertel  688: 	my $tsimilar=&String::Similarity::similarity($uessay,$tessay,$limit);
1.87      www       689: # Found one
1.426     albertel  690: 	if ($tsimilar>$limit) {
                    691: 	    $limit=$tsimilar;
                    692: 	    $sname=$tname;
                    693: 	    $sdom=$tdom;
                    694: 	    $scrsid=$tcrsid;
                    695: 	    $sessay=$old_essays->{$tkey};
                    696: 	}
1.87      www       697:     }
1.88      www       698:     if ($limit>0.6) {
1.87      www       699:        return ($sname,$sdom,$scrsid,$sessay,$limit);
                    700:     } else {
                    701:        return ('','','','',0);
                    702:     }
                    703: }
                    704: 
1.44      ng        705: #-------------------------------------------------------------------
                    706: 
                    707: #------------------------------------ Receipt Verification Routines
1.45      ng        708: #
1.602     www       709: 
                    710: sub initialverifyreceipt {
1.608     www       711:    my ($request,$symb) = @_;
1.602     www       712:    &commonJSfunctions($request);
1.605     www       713:    return '<form name="gradingMenu"><input type="submit" value="'.&mt('Verify Receipt Number.').'" />'.
1.602     www       714:         &Apache::lonnet::recprefix($env{'request.course.id'}).
                    715:         '-<input type="text" name="receipt" size="4" />'.
1.603     www       716:         '<input type="hidden" name="symb" value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
                    717:         '<input type="hidden" name="command" value="verify" />'.
                    718:         "</form>\n";
1.602     www       719: }
                    720: 
1.44      ng        721: #--- Check whether a receipt number is valid.---
                    722: sub verifyreceipt {
1.608     www       723:     my ($request,$symb)  = @_;
1.44      ng        724: 
1.257     albertel  725:     my $courseid = $env{'request.course.id'};
1.184     www       726:     my $receipt  = &Apache::lonnet::recprefix($courseid).'-'.
1.257     albertel  727: 	$env{'form.receipt'};
1.44      ng        728:     $receipt     =~ s/[^\-\d]//g;
                    729: 
1.487     albertel  730:     my $title.=
                    731: 	'<h3><span class="LC_info">'.
1.605     www       732: 	&mt('Verifying Receipt Number [_1]',$receipt).
                    733: 	'</span></h3>'."\n";
1.44      ng        734: 
                    735:     my ($string,$contents,$matches) = ('','',0);
1.56      matthew   736:     my (undef,undef,$fullname) = &getclasslist('all','0');
1.177     albertel  737:     
                    738:     my $receiptparts=0;
1.390     albertel  739:     if ($env{"course.$courseid.receiptalg"} eq 'receipt2' ||
                    740: 	$env{"course.$courseid.receiptalg"} eq 'receipt3') { $receiptparts=1; }
1.177     albertel  741:     my $parts=['0'];
1.582     raeburn   742:     if ($receiptparts) {
                    743:         my $res_error; 
                    744:         ($parts)=&response_type($symb,\$res_error);
                    745:         if ($res_error) {
                    746:             return &navmap_errormsg();
                    747:         } 
                    748:     }
1.486     albertel  749:     
                    750:     my $header = 
                    751: 	&Apache::loncommon::start_data_table().
                    752: 	&Apache::loncommon::start_data_table_header_row().
1.487     albertel  753: 	'<th>&nbsp;'.&mt('Fullname').'&nbsp;</th>'."\n".
                    754: 	'<th>&nbsp;'.&mt('Username').'&nbsp;</th>'."\n".
                    755: 	'<th>&nbsp;'.&mt('Domain').'&nbsp;</th>';
1.486     albertel  756:     if ($receiptparts) {
1.487     albertel  757: 	$header.='<th>&nbsp;'.&mt('Problem Part').'&nbsp;</th>';
1.486     albertel  758:     }
                    759:     $header.=
                    760: 	&Apache::loncommon::end_data_table_header_row();
                    761: 
1.294     albertel  762:     foreach (sort 
                    763: 	     {
                    764: 		 if (lc($$fullname{$a}) ne lc($$fullname{$b})) {
                    765: 		     return (lc($$fullname{$a}) cmp lc($$fullname{$b}));
                    766: 		 }
                    767: 		 return $a cmp $b;
                    768: 	     } (keys(%$fullname))) {
1.44      ng        769: 	my ($uname,$udom)=split(/\:/);
1.177     albertel  770: 	foreach my $part (@$parts) {
                    771: 	    if ($receipt eq &Apache::lonnet::ireceipt($uname,$udom,$courseid,$symb,$part)) {
1.486     albertel  772: 		$contents.=
                    773: 		    &Apache::loncommon::start_data_table_row().
                    774: 		    '<td>&nbsp;'."\n".
1.177     albertel  775: 		    '<a href="javascript:viewOneStudent(\''.$uname.'\',\''.$udom.
1.417     albertel  776: 		    '\');" target="_self">'.$$fullname{$_}.'</a>&nbsp;</td>'."\n".
1.177     albertel  777: 		    '<td>&nbsp;'.$uname.'&nbsp;</td>'.
                    778: 		    '<td>&nbsp;'.$udom.'&nbsp;</td>';
                    779: 		if ($receiptparts) {
                    780: 		    $contents.='<td>&nbsp;'.$part.'&nbsp;</td>';
                    781: 		}
1.486     albertel  782: 		$contents.= 
                    783: 		    &Apache::loncommon::end_data_table_row()."\n";
1.177     albertel  784: 		
                    785: 		$matches++;
                    786: 	    }
1.44      ng        787: 	}
                    788:     }
                    789:     if ($matches == 0) {
1.584     bisitz    790:         $string = $title
                    791:                  .'<p class="LC_warning">'
                    792:                  .&mt('No match found for the above receipt number.')
                    793:                  .'</p>';
1.44      ng        794:     } else {
1.324     albertel  795: 	$string = &jscriptNform($symb).$title.
1.487     albertel  796: 	    '<p>'.
1.584     bisitz    797: 	    &mt('The above receipt number matches the following [quant,_1,student].',$matches).
1.487     albertel  798: 	    '</p>'.
1.486     albertel  799: 	    $header.
                    800: 	    $contents.
                    801: 	    &Apache::loncommon::end_data_table()."\n";
1.44      ng        802:     }
1.614     www       803:     return $string;
1.44      ng        804: }
                    805: 
                    806: #--- This is called by a number of programs.
                    807: #--- Called from the Grading Menu - View/Grade an individual student
                    808: #--- Also called directly when one clicks on the subm button 
                    809: #    on the problem page.
1.30      ng        810: sub listStudents {
1.617     www       811:     my ($request,$symb,$submitonly) = @_;
1.49      albertel  812: 
1.257     albertel  813:     my $cdom      = $env{"course.$env{'request.course.id'}.domain"};
                    814:     my $cnum      = $env{"course.$env{'request.course.id'}.num"};
                    815:     my $getsec    = $env{'form.section'} eq '' ? 'all' : $env{'form.section'};
1.449     banghart  816:     my $getgroup  = $env{'form.group'} eq '' ? 'all' : $env{'form.group'};
1.617     www       817:     unless ($submitonly) {
                    818:        $submitonly= $env{'form.submitonly'} eq '' ? 'all' : $env{'form.submitonly'};
                    819:     }
1.49      albertel  820: 
1.548     bisitz    821:     my $result='<h3><span class="LC_info">&nbsp;'
1.618   ! www       822: 	.&mt("View/Grade/Regrade 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".
1.418     albertel  922: 	'<input type="hidden" name="symb" value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
1.110     ng        923: 	'<input type="hidden" name="saveStatusOld" value="'.$saveStatus.'" />'."\n";
                    924: 
1.618   ! www       925:     if (exists($env{'form.Status'})) {
1.561     bisitz    926: 	$gradeTable .= '<input type="hidden" name="Status" value="'.$stu_status.'" />'."\n";
1.124     ng        927:     } else {
1.561     bisitz    928:         $gradeTable .= &Apache::lonhtmlcommon::row_title(&mt('Student Status'))
                    929:                       .&Apache::lonhtmlcommon::StatusOptions(
                    930:                            $saveStatus,undef,1,'javascript:reLoadList(this.form);')
                    931:                       .&Apache::lonhtmlcommon::row_closure();
1.124     ng        932:     }
1.112     ng        933: 
1.561     bisitz    934:     $gradeTable .= &Apache::lonhtmlcommon::row_title(&mt('Check For Plagiarism'))
                    935:                   .'<input type="checkbox" name="checkPlag" checked="checked" />'
                    936:                   .&Apache::lonhtmlcommon::row_closure(1)
                    937:                   .&Apache::lonhtmlcommon::end_pick_box();
                    938: 
                    939:     $gradeTable .= '<p>'
1.618   ! www       940:                   .&mt("To view/grade/regrade 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"
1.561     bisitz    941:                   .'<input type="hidden" name="command" value="processGroup" />'
                    942:                   .'</p>';
1.249     albertel  943: 
                    944: # checkall buttons
                    945:     $gradeTable.=&check_script('gradesub', 'stuinfo');
1.110     ng        946:     $gradeTable.='<input type="button" '."\n".
1.589     bisitz    947:         'onclick="javascript:checkSelect(this.form.stuinfo);" '."\n".
                    948:         'value="'.&mt('Next').' &rarr;" /> <br />'."\n";
1.249     albertel  949:     $gradeTable.=&check_buttons();
1.450     banghart  950:     my ($classlist, undef, $fullname) = &getclasslist($getsec,'1',$getgroup);
1.474     albertel  951:     $gradeTable.= &Apache::loncommon::start_data_table().
                    952: 	&Apache::loncommon::start_data_table_header_row();
1.110     ng        953:     my $loop = 0;
                    954:     while ($loop < 2) {
1.485     albertel  955: 	$gradeTable.='<th>'.&mt('No.').'</th><th>'.&mt('Select').'</th>'.
                    956: 	    '<th>'.&nameUserString('header').'&nbsp;'.&mt('Section/Group').'</th>';
1.618   ! www       957: 	if (($submitonly ne 'queued') && ($submitonly ne 'all')) {
1.485     albertel  958: 	    foreach my $part (sort(@$partlist)) {
                    959: 		my $display_part=
                    960: 		    &get_display_part((split(/_/,$part))[0],$symb);
                    961: 		$gradeTable.=
                    962: 		    '<th>'.&mt('Part: [_1] Status',$display_part).'</th>';
1.110     ng        963: 	    }
1.301     albertel  964: 	} elsif ($submitonly eq 'queued') {
1.474     albertel  965: 	    $gradeTable.='<th>'.&mt('Queue Status').'&nbsp;</th>';
1.110     ng        966: 	}
                    967: 	$loop++;
1.126     ng        968: #	$gradeTable.='<td></td>' if ($loop%2 ==1);
1.41      ng        969:     }
1.474     albertel  970:     $gradeTable.=&Apache::loncommon::end_data_table_header_row()."\n";
1.41      ng        971: 
1.45      ng        972:     my $ctr = 0;
1.294     albertel  973:     foreach my $student (sort 
                    974: 			 {
                    975: 			     if (lc($$fullname{$a}) ne lc($$fullname{$b})) {
                    976: 				 return (lc($$fullname{$a}) cmp lc($$fullname{$b}));
                    977: 			     }
                    978: 			     return $a cmp $b;
                    979: 			 }
                    980: 			 (keys(%$fullname))) {
1.41      ng        981: 	my ($uname,$udom) = split(/:/,$student);
1.301     albertel  982: 
1.110     ng        983: 	my %status = ();
1.301     albertel  984: 
                    985: 	if ($submitonly eq 'queued') {
                    986: 	    my %queue_status = 
                    987: 		&Apache::bridgetask::get_student_status($symb,$cdom,$cnum,
                    988: 							$udom,$uname);
                    989: 	    next if (!defined($queue_status{'gradingqueue'}));
                    990: 	    $status{'gradingqueue'} = $queue_status{'gradingqueue'};
                    991: 	}
                    992: 
1.618   ! www       993: 	if (($submitonly ne 'queued') && ($submitonly ne 'all')) {
1.324     albertel  994: 	    (%status) =&student_gradeStatus($symb,$udom,$uname,$partlist);
1.145     albertel  995: 	    my $submitted = 0;
1.164     albertel  996: 	    my $graded = 0;
1.248     albertel  997: 	    my $incorrect = 0;
1.110     ng        998: 	    foreach (keys(%status)) {
1.145     albertel  999: 		$submitted = 1 if ($status{$_} ne 'nothing');
1.248     albertel 1000: 		$graded = 1 if ($status{$_} =~ /^ungraded/);
                   1001: 		$incorrect = 1 if ($status{$_} =~ /^incorrect/);
                   1002: 		
1.110     ng       1003: 		my ($foo,$partid,$foo1) = split(/\./,$_);
                   1004: 		if ($status{'resource.'.$partid.'.submitted_by'} ne '') {
1.145     albertel 1005: 		    $submitted = 0;
1.150     albertel 1006: 		    my ($part)=split(/\./,$partid);
1.110     ng       1007: 		    $gradeTable.='<input type="hidden" name="'.
1.150     albertel 1008: 			$student.':'.$part.':submitted_by" value="'.
1.110     ng       1009: 			$status{'resource.'.$partid.'.submitted_by'}.'" />';
                   1010: 		}
1.41      ng       1011: 	    }
1.248     albertel 1012: 	    
1.156     albertel 1013: 	    next if (!$submitted && ($submitonly eq 'yes' ||
                   1014: 				     $submitonly eq 'incorrect' ||
                   1015: 				     $submitonly eq 'graded'));
1.248     albertel 1016: 	    next if (!$graded && ($submitonly eq 'graded'));
                   1017: 	    next if (!$incorrect && $submitonly eq 'incorrect');
1.41      ng       1018: 	}
1.34      ng       1019: 
1.45      ng       1020: 	$ctr++;
1.249     albertel 1021: 	my $section = $classlist->{$student}->[&Apache::loncoursedata::CL_SECTION()];
1.452     banghart 1022:         my $group = $classlist->{$student}->[&Apache::loncoursedata::CL_GROUP()];
1.104     albertel 1023: 	if ( $perm{'vgr'} eq 'F' ) {
1.474     albertel 1024: 	    if ($ctr%2 ==1) {
                   1025: 		$gradeTable.= &Apache::loncommon::start_data_table_row();
                   1026: 	    }
1.126     ng       1027: 	    $gradeTable.='<td align="right">'.$ctr.'&nbsp;</td>'.
1.563     bisitz   1028:                '<td align="center"><label><input type="checkbox" name="stuinfo" value="'.
1.249     albertel 1029:                $student.':'.$$fullname{$student}.':::SECTION'.$section.
                   1030: 	       ')&nbsp;" />&nbsp;&nbsp;</label></td>'."\n".'<td>'.
                   1031: 	       &nameUserString(undef,$$fullname{$student},$uname,$udom).
1.474     albertel 1032: 	       '&nbsp;'.$section.($group ne '' ?'/'.$group:'').'</td>'."\n";
1.110     ng       1033: 
1.618   ! www      1034: 	    if ($submitonly ne 'all') {
1.524     raeburn  1035: 		foreach (sort(keys(%status))) {
1.485     albertel 1036: 		    next if ($_ =~ /^resource.*?submitted_by$/);
                   1037: 		    $gradeTable.='<td align="center">&nbsp;'.&mt($status{$_}).'&nbsp;</td>'."\n";
1.110     ng       1038: 		}
1.41      ng       1039: 	    }
1.126     ng       1040: #	    $gradeTable.='<td></td>' if ($ctr%2 ==1);
1.474     albertel 1041: 	    if ($ctr%2 ==0) {
                   1042: 		$gradeTable.=&Apache::loncommon::end_data_table_row()."\n";
                   1043: 	    }
1.41      ng       1044: 	}
                   1045:     }
1.110     ng       1046:     if ($ctr%2 ==1) {
1.126     ng       1047: 	$gradeTable.='<td>&nbsp;</td><td>&nbsp;</td><td>&nbsp;</td>';
1.618   ! www      1048: 	    if (($submitonly ne 'queued') && ($submitonly ne 'all')) {
1.110     ng       1049: 		foreach (@$partlist) {
                   1050: 		    $gradeTable.='<td>&nbsp;</td>';
                   1051: 		}
1.301     albertel 1052: 	    } elsif ($submitonly eq 'queued') {
                   1053: 		$gradeTable.='<td>&nbsp;</td>';
1.110     ng       1054: 	    }
1.474     albertel 1055: 	$gradeTable.=&Apache::loncommon::end_data_table_row();
1.110     ng       1056:     }
                   1057: 
1.474     albertel 1058:     $gradeTable.=&Apache::loncommon::end_data_table()."\n".
1.589     bisitz   1059:         '<input type="button" '.
                   1060:         'onclick="javascript:checkSelect(this.form.stuinfo);" '.
                   1061:         'value="'.&mt('Next').' &rarr;" /></form>'."\n";
1.45      ng       1062:     if ($ctr == 0) {
1.96      albertel 1063: 	my $num_students=(scalar(keys(%$fullname)));
                   1064: 	if ($num_students eq 0) {
1.485     albertel 1065: 	    $gradeTable='<br />&nbsp;<span class="LC_warning">'.&mt('There are no students currently enrolled.').'</span>';
1.96      albertel 1066: 	} else {
1.171     albertel 1067: 	    my $submissions='submissions';
                   1068: 	    if ($submitonly eq 'incorrect') { $submissions = 'incorrect submissions'; }
                   1069: 	    if ($submitonly eq 'graded'   ) { $submissions = 'ungraded submissions'; }
1.301     albertel 1070: 	    if ($submitonly eq 'queued'   ) { $submissions = 'queued submissions'; }
1.398     albertel 1071: 	    $gradeTable='<br />&nbsp;<span class="LC_warning">'.
1.485     albertel 1072: 		&mt('No '.$submissions.' found for this resource for any students. ([_1] students checked for '.$submissions.')',
                   1073: 		    $num_students).
                   1074: 		'</span><br />';
1.96      albertel 1075: 	}
1.46      ng       1076:     } elsif ($ctr == 1) {
1.474     albertel 1077: 	$gradeTable =~ s/type="checkbox"/type="checkbox" checked="checked"/;
1.45      ng       1078:     }
                   1079:     $request->print($gradeTable);
1.44      ng       1080:     return '';
1.10      ng       1081: }
                   1082: 
1.44      ng       1083: #---- Called from the listStudents routine
1.249     albertel 1084: 
                   1085: sub check_script {
                   1086:     my ($form, $type)=@_;
1.597     wenzelju 1087:     my $chkallscript= &Apache::lonhtmlcommon::scripttag('
1.249     albertel 1088:     function checkall() {
                   1089:         for (i=0; i<document.forms.'.$form.'.elements.length; i++) {
                   1090:             ele = document.forms.'.$form.'.elements[i];
                   1091:             if (ele.name == "'.$type.'") {
                   1092:             document.forms.'.$form.'.elements[i].checked=true;
                   1093:                                        }
                   1094:         }
                   1095:     }
                   1096: 
                   1097:     function checksec() {
                   1098:         for (i=0; i<document.forms.'.$form.'.elements.length; i++) {
                   1099:             ele = document.forms.'.$form.'.elements[i];
                   1100:            string = document.forms.'.$form.'.chksec.value;
                   1101:            if
                   1102:           (ele.value.indexOf(":::SECTION"+string)>0) {
                   1103:               document.forms.'.$form.'.elements[i].checked=true;
                   1104:             }
                   1105:         }
                   1106:     }
                   1107: 
                   1108: 
                   1109:     function uncheckall() {
                   1110:         for (i=0; i<document.forms.'.$form.'.elements.length; i++) {
                   1111:             ele = document.forms.'.$form.'.elements[i];
                   1112:             if (ele.name == "'.$type.'") {
                   1113:             document.forms.'.$form.'.elements[i].checked=false;
                   1114:                                        }
                   1115:         }
                   1116:     }
                   1117: 
1.597     wenzelju 1118: '."\n");
1.249     albertel 1119:     return $chkallscript;
                   1120: }
                   1121: 
                   1122: sub check_buttons {
1.485     albertel 1123:     my $buttons.='<input type="button" onclick="checkall()" value="'.&mt('Check All').'" />';
                   1124:     $buttons.='<input type="button" onclick="uncheckall()" value="'.&mt('Uncheck All').'" />&nbsp;';
                   1125:     $buttons.='<input type="button" onclick="checksec()" value="'.&mt('Check Section/Group').'" />';
1.249     albertel 1126:     $buttons.='<input type="text" size="5" name="chksec" />&nbsp;';
                   1127:     return $buttons;
                   1128: }
                   1129: 
1.44      ng       1130: #     Displays the submissions for one student or a group of students
1.34      ng       1131: sub processGroup {
1.41      ng       1132:     my ($request)  = shift;
                   1133:     my $ctr        = 0;
1.155     albertel 1134:     my @stuchecked = &Apache::loncommon::get_env_multiple('form.stuinfo');
1.41      ng       1135:     my $total      = scalar(@stuchecked)-1;
1.45      ng       1136: 
1.396     banghart 1137:     foreach my $student (@stuchecked) {
                   1138: 	my ($uname,$udom,$fullname) = split(/:/,$student);
1.257     albertel 1139: 	$env{'form.student'}        = $uname;
                   1140: 	$env{'form.userdom'}        = $udom;
                   1141: 	$env{'form.fullname'}       = $fullname;
1.41      ng       1142: 	&submission($request,$ctr,$total);
                   1143: 	$ctr++;
                   1144:     }
                   1145:     return '';
1.35      ng       1146: }
1.34      ng       1147: 
1.44      ng       1148: #------------------------------------------------------------------------------------
                   1149: #
                   1150: #-------------------------- Next few routines handles grading by student, essentially
                   1151: #                           handles essay response type problem/part
                   1152: #
                   1153: #--- Javascript to handle the submission page functionality ---
                   1154: sub sub_page_js {
                   1155:     my $request = shift;
1.539     riegler  1156: 	    my $alertmsg = &mt('A number equal or greater than 0 is expected. Entered value = ');
1.597     wenzelju 1157:     $request->print(&Apache::lonhtmlcommon::scripttag(<<SUBJAVASCRIPT));
1.71      ng       1158:     function updateRadio(formname,id,weight) {
1.125     ng       1159: 	var gradeBox = formname["GD_BOX"+id];
                   1160: 	var radioButton = formname["RADVAL"+id];
                   1161: 	var oldpts = formname["oldpts"+id].value;
1.72      ng       1162: 	var pts = checkSolved(formname,id) == 'update' ? gradeBox.value : oldpts;
1.71      ng       1163: 	gradeBox.value = pts;
                   1164: 	var resetbox = false;
                   1165: 	if (isNaN(pts) || pts < 0) {
1.539     riegler  1166: 	    alert("$alertmsg"+pts);
1.71      ng       1167: 	    for (var i=0; i<radioButton.length; i++) {
                   1168: 		if (radioButton[i].checked) {
                   1169: 		    gradeBox.value = i;
                   1170: 		    resetbox = true;
                   1171: 		}
                   1172: 	    }
                   1173: 	    if (!resetbox) {
                   1174: 		formtextbox.value = "";
                   1175: 	    }
                   1176: 	    return;
1.44      ng       1177: 	}
1.71      ng       1178: 
                   1179: 	if (pts > weight) {
                   1180: 	    var resp = confirm("You entered a value ("+pts+
                   1181: 			       ") greater than the weight for the part. Accept?");
                   1182: 	    if (resp == false) {
1.125     ng       1183: 		gradeBox.value = oldpts;
1.71      ng       1184: 		return;
                   1185: 	    }
1.44      ng       1186: 	}
1.13      albertel 1187: 
1.71      ng       1188: 	for (var i=0; i<radioButton.length; i++) {
                   1189: 	    radioButton[i].checked=false;
                   1190: 	    if (pts == i && pts != "") {
                   1191: 		radioButton[i].checked=true;
                   1192: 	    }
                   1193: 	}
                   1194: 	updateSelect(formname,id);
1.125     ng       1195: 	formname["stores"+id].value = "0";
1.41      ng       1196:     }
1.5       albertel 1197: 
1.72      ng       1198:     function writeBox(formname,id,pts) {
1.125     ng       1199: 	var gradeBox = formname["GD_BOX"+id];
1.71      ng       1200: 	if (checkSolved(formname,id) == 'update') {
                   1201: 	    gradeBox.value = pts;
                   1202: 	} else {
1.125     ng       1203: 	    var oldpts = formname["oldpts"+id].value;
1.72      ng       1204: 	    gradeBox.value = oldpts;
1.125     ng       1205: 	    var radioButton = formname["RADVAL"+id];
1.71      ng       1206: 	    for (var i=0; i<radioButton.length; i++) {
                   1207: 		radioButton[i].checked=false;
1.72      ng       1208: 		if (i == oldpts) {
1.71      ng       1209: 		    radioButton[i].checked=true;
                   1210: 		}
                   1211: 	    }
1.41      ng       1212: 	}
1.125     ng       1213: 	formname["stores"+id].value = "0";
1.71      ng       1214: 	updateSelect(formname,id);
                   1215: 	return;
1.41      ng       1216:     }
1.44      ng       1217: 
1.71      ng       1218:     function clearRadBox(formname,id) {
                   1219: 	if (checkSolved(formname,id) == 'noupdate') {
                   1220: 	    updateSelect(formname,id);
                   1221: 	    return;
                   1222: 	}
1.125     ng       1223: 	gradeSelect = formname["GD_SEL"+id];
1.71      ng       1224: 	for (var i=0; i<gradeSelect.length; i++) {
                   1225: 	    if (gradeSelect[i].selected) {
                   1226: 		var selectx=i;
                   1227: 	    }
                   1228: 	}
1.125     ng       1229: 	var stores = formname["stores"+id];
1.71      ng       1230: 	if (selectx == stores.value) { return };
1.125     ng       1231: 	var gradeBox = formname["GD_BOX"+id];
1.71      ng       1232: 	gradeBox.value = "";
1.125     ng       1233: 	var radioButton = formname["RADVAL"+id];
1.71      ng       1234: 	for (var i=0; i<radioButton.length; i++) {
                   1235: 	    radioButton[i].checked=false;
                   1236: 	}
                   1237: 	stores.value = selectx;
                   1238:     }
1.5       albertel 1239: 
1.71      ng       1240:     function checkSolved(formname,id) {
1.125     ng       1241: 	if (formname["solved"+id].value == "correct_by_student" && formname.overRideScore.value == 'no') {
1.118     ng       1242: 	    var reply = confirm("This problem has been graded correct by the computer. Do you want to change the score?");
                   1243: 	    if (!reply) {return "noupdate";}
1.120     ng       1244: 	    formname.overRideScore.value = 'yes';
1.41      ng       1245: 	}
1.71      ng       1246: 	return "update";
1.13      albertel 1247:     }
1.71      ng       1248: 
                   1249:     function updateSelect(formname,id) {
1.125     ng       1250: 	formname["GD_SEL"+id][0].selected = true;
1.71      ng       1251: 	return;
1.41      ng       1252:     }
1.33      ng       1253: 
1.121     ng       1254: //=========== Check that a point is assigned for all the parts  ============
1.71      ng       1255:     function checksubmit(formname,val,total,parttot) {
1.121     ng       1256: 	formname.gradeOpt.value = val;
1.71      ng       1257: 	if (val == "Save & Next") {
                   1258: 	    for (i=0;i<=total;i++) {
                   1259: 		for (j=0;j<parttot;j++) {
1.125     ng       1260: 		    var partid = formname["partid"+i+"_"+j].value;
1.127     ng       1261: 		    if (formname["GD_SEL"+i+"_"+partid][0].selected) {
1.125     ng       1262: 			var points = formname["GD_BOX"+i+"_"+partid].value;
1.71      ng       1263: 			if (points == "") {
1.125     ng       1264: 			    var name = formname["name"+i].value;
1.129     ng       1265: 			    var studentID = (name != '' ? name : formname["unamedom"+i].value);
                   1266: 			    var resp = confirm("You did not assign a score for "+studentID+
                   1267: 					       ", part "+partid+". Continue?");
1.71      ng       1268: 			    if (resp == false) {
1.125     ng       1269: 				formname["GD_BOX"+i+"_"+partid].focus();
1.71      ng       1270: 				return false;
                   1271: 			    }
                   1272: 			}
                   1273: 		    }
                   1274: 		    
                   1275: 		}
                   1276: 	    }
                   1277: 	    
                   1278: 	}
1.121     ng       1279: 	if (val == "Grade Student") {
                   1280: 	    if (formname.Status.value == "") {
                   1281: 		formname.Status.value = "Active";
                   1282: 	    }
                   1283: 	    formname.studentNo.value = total;
                   1284: 	}
1.120     ng       1285: 	formname.submit();
                   1286:     }
                   1287: 
1.71      ng       1288: //======= Check that a score is assigned for all the problems (page/sequence grading only) =========
                   1289:     function checkSubmitPage(formname,total) {
                   1290: 	noscore = new Array(100);
                   1291: 	var ptr = 0;
                   1292: 	for (i=1;i<total;i++) {
1.125     ng       1293: 	    var partid = formname["q_"+i].value;
1.127     ng       1294: 	    if (formname["GD_SEL"+i+"_"+partid][0].selected) {
1.125     ng       1295: 		var points = formname["GD_BOX"+i+"_"+partid].value;
                   1296: 		var status = formname["solved"+i+"_"+partid].value;
1.71      ng       1297: 		if (points == "" && status != "correct_by_student") {
                   1298: 		    noscore[ptr] = i;
                   1299: 		    ptr++;
                   1300: 		}
                   1301: 	    }
                   1302: 	}
                   1303: 	if (ptr != 0) {
                   1304: 	    var sense = ptr == 1 ? ": " : "s: ";
                   1305: 	    var prolist = "";
                   1306: 	    if (ptr == 1) {
                   1307: 		prolist = noscore[0];
                   1308: 	    } else {
                   1309: 		var i = 0;
                   1310: 		while (i < ptr-1) {
                   1311: 		    prolist += noscore[i]+", ";
                   1312: 		    i++;
                   1313: 		}
                   1314: 		prolist += "and "+noscore[i];
                   1315: 	    }
                   1316: 	    var resp = confirm("You did not assign any score for the following problem"+sense+prolist+". Continue?");
                   1317: 	    if (resp == false) {
                   1318: 		return false;
                   1319: 	    }
                   1320: 	}
1.45      ng       1321: 
1.71      ng       1322: 	formname.submit();
                   1323:     }
                   1324: SUBJAVASCRIPT
                   1325: }
1.45      ng       1326: 
1.71      ng       1327: #--- javascript for essay type problem --
                   1328: sub sub_page_kw_js {
                   1329:     my $request = shift;
1.80      ng       1330:     my $iconpath = $request->dir_config('lonIconsURL');
1.118     ng       1331:     &commonJSfunctions($request);
1.350     albertel 1332: 
1.597     wenzelju 1333:     my $inner_js_msg_central= &Apache::lonhtmlcommon::scripttag(<<INNERJS);
1.350     albertel 1334:     function checkInput() {
                   1335:       opener.document.SCORE.msgsub.value = opener.checkEntities(document.msgcenter.msgsub.value);
                   1336:       var nmsg   = opener.document.SCORE.savemsgN.value;
                   1337:       var usrctr = document.msgcenter.usrctr.value;
                   1338:       var newval = opener.document.SCORE["newmsg"+usrctr];
                   1339:       newval.value = opener.checkEntities(document.msgcenter.newmsg.value);
                   1340: 
                   1341:       var msgchk = "";
                   1342:       if (document.msgcenter.subchk.checked) {
                   1343:          msgchk = "msgsub,";
                   1344:       }
                   1345:       var includemsg = 0;
                   1346:       for (var i=1; i<=nmsg; i++) {
                   1347:           var opnmsg = opener.document.SCORE["savemsg"+i];
                   1348:           var frmmsg = document.msgcenter["msg"+i];
                   1349:           opnmsg.value = opener.checkEntities(frmmsg.value);
                   1350:           var showflg = opener.document.SCORE["shownOnce"+i];
                   1351:           showflg.value = "1";
                   1352:           var chkbox = document.msgcenter["msgn"+i];
                   1353:           if (chkbox.checked) {
                   1354:              msgchk += "savemsg"+i+",";
                   1355:              includemsg = 1;
                   1356:           }
                   1357:       }
                   1358:       if (document.msgcenter.newmsgchk.checked) {
                   1359:          msgchk += "newmsg"+usrctr;
                   1360:          includemsg = 1;
                   1361:       }
                   1362:       imgformname = opener.document.SCORE["mailicon"+usrctr];
                   1363:       imgformname.src = "$iconpath/"+((includemsg) ? "mailto.gif" : "mailbkgrd.gif");
                   1364:       var includemsg = opener.document.SCORE["includemsg"+usrctr];
                   1365:       includemsg.value = msgchk;
                   1366: 
                   1367:       self.close()
                   1368: 
                   1369:     }
                   1370: INNERJS
                   1371: 
1.597     wenzelju 1372:     my $inner_js_highlight_central= &Apache::lonhtmlcommon::scripttag(<<INNERJS);
1.351     albertel 1373:     function updateChoice(flag) {
                   1374:       opener.document.SCORE.kwclr.value = opener.radioSelection(document.hlCenter.kwdclr);
                   1375:       opener.document.SCORE.kwsize.value = opener.radioSelection(document.hlCenter.kwdsize);
                   1376:       opener.document.SCORE.kwstyle.value = opener.radioSelection(document.hlCenter.kwdstyle);
                   1377:       opener.document.SCORE.refresh.value = "on";
                   1378:       if (opener.document.SCORE.keywords.value!=""){
                   1379:          opener.document.SCORE.submit();
                   1380:       }
                   1381:       self.close()
                   1382:     }
                   1383: INNERJS
                   1384: 
                   1385:     my $start_page_msg_central = 
                   1386:         &Apache::loncommon::start_page('Message Central',$inner_js_msg_central,
                   1387: 				       {'js_ready'  => 1,
                   1388: 					'only_body' => 1,
                   1389: 					'bgcolor'   =>'#FFFFFF',});
                   1390:     my $end_page_msg_central = 
                   1391: 	&Apache::loncommon::end_page({'js_ready' => 1});
                   1392: 
                   1393: 
                   1394:     my $start_page_highlight_central = 
                   1395:         &Apache::loncommon::start_page('Highlight Central',
                   1396: 				       $inner_js_highlight_central,
1.350     albertel 1397: 				       {'js_ready'  => 1,
                   1398: 					'only_body' => 1,
                   1399: 					'bgcolor'   =>'#FFFFFF',});
1.351     albertel 1400:     my $end_page_highlight_central = 
1.350     albertel 1401: 	&Apache::loncommon::end_page({'js_ready' => 1});
                   1402: 
1.219     www      1403:     my $docopen=&Apache::lonhtmlcommon::javascript_docopen();
1.236     albertel 1404:     $docopen=~s/^document\.//;
1.539     riegler  1405:     my $alertmsg = &mt('Please select a word or group of words from document and then click this link.');
1.597     wenzelju 1406:     $request->print(&Apache::lonhtmlcommon::scripttag(<<SUBJAVASCRIPT));
1.45      ng       1407: 
1.44      ng       1408: //===================== Show list of keywords ====================
1.122     ng       1409:   function keywords(formname) {
                   1410:     var nret = prompt("Keywords list, separated by a space. Add/delete to list if desired.",formname.keywords.value);
1.44      ng       1411:     if (nret==null) return;
1.122     ng       1412:     formname.keywords.value = nret;
1.44      ng       1413: 
1.122     ng       1414:     if (formname.keywords.value != "") {
1.128     ng       1415: 	formname.refresh.value = "on";
1.122     ng       1416: 	formname.submit();
1.44      ng       1417:     }
                   1418:     return;
                   1419:   }
                   1420: 
                   1421: //===================== Script to view submitted by ==================
                   1422:   function viewSubmitter(submitter) {
                   1423:     document.SCORE.refresh.value = "on";
                   1424:     document.SCORE.NCT.value = "1";
                   1425:     document.SCORE.unamedom0.value = submitter;
                   1426:     document.SCORE.submit();
                   1427:     return;
                   1428:   }
                   1429: 
                   1430: //===================== Script to add keyword(s) ==================
                   1431:   function getSel() {
                   1432:     if (document.getSelection) txt = document.getSelection();
                   1433:     else if (document.selection) txt = document.selection.createRange().text;
                   1434:     else return;
                   1435:     var cleantxt = txt.replace(new RegExp('([\\f\\n\\r\\t\\v ])+', 'g')," ");
                   1436:     if (cleantxt=="") {
1.539     riegler  1437: 	alert("$alertmsg");
1.44      ng       1438: 	return;
                   1439:     }
                   1440:     var nret = prompt("Add selection to keyword list? Edit if desired.",cleantxt);
                   1441:     if (nret==null) return;
1.127     ng       1442:     document.SCORE.keywords.value = document.SCORE.keywords.value+" "+nret;
1.44      ng       1443:     if (document.SCORE.keywords.value != "") {
1.127     ng       1444: 	document.SCORE.refresh.value = "on";
1.44      ng       1445: 	document.SCORE.submit();
                   1446:     }
                   1447:     return;
                   1448:   }
                   1449: 
                   1450: //====================== Script for composing message ==============
1.80      ng       1451:    // preload images
                   1452:    img1 = new Image();
                   1453:    img1.src = "$iconpath/mailbkgrd.gif";
                   1454:    img2 = new Image();
                   1455:    img2.src = "$iconpath/mailto.gif";
                   1456: 
1.44      ng       1457:   function msgCenter(msgform,usrctr,fullname) {
                   1458:     var Nmsg  = msgform.savemsgN.value;
                   1459:     savedMsgHeader(Nmsg,usrctr,fullname);
                   1460:     var subject = msgform.msgsub.value;
1.127     ng       1461:     var msgchk = document.SCORE["includemsg"+usrctr].value;
1.44      ng       1462:     re = /msgsub/;
                   1463:     var shwsel = "";
                   1464:     if (re.test(msgchk)) { shwsel = "checked" }
1.123     ng       1465:     subject = (document.SCORE.shownSub.value == 0 ? checkEntities(subject) : subject);
                   1466:     displaySubject(checkEntities(subject),shwsel);
1.44      ng       1467:     for (var i=1; i<=Nmsg; i++) {
1.123     ng       1468: 	var testmsg = "savemsg"+i+",";
                   1469: 	re = new RegExp(testmsg,"g");
1.44      ng       1470: 	shwsel = "";
                   1471: 	if (re.test(msgchk)) { shwsel = "checked" }
1.125     ng       1472: 	var message = document.SCORE["savemsg"+i].value;
1.126     ng       1473: 	message = (document.SCORE["shownOnce"+i].value == 0 ? checkEntities(message) : message);
1.123     ng       1474: 	displaySavedMsg(i,message,shwsel); //I do not get it. w/o checkEntities on saved messages,
                   1475: 	                                   //any &lt; is already converted to <, etc. However, only once!!
1.44      ng       1476:     }
1.125     ng       1477:     newmsg = document.SCORE["newmsg"+usrctr].value;
1.44      ng       1478:     shwsel = "";
                   1479:     re = /newmsg/;
                   1480:     if (re.test(msgchk)) { shwsel = "checked" }
                   1481:     newMsg(newmsg,shwsel);
                   1482:     msgTail(); 
                   1483:     return;
                   1484:   }
                   1485: 
1.123     ng       1486:   function checkEntities(strx) {
                   1487:     if (strx.length == 0) return strx;
                   1488:     var orgStr = ["&", "<", ">", '"']; 
                   1489:     var newStr = ["&amp;", "&lt;", "&gt;", "&quot;"];
                   1490:     var counter = 0;
                   1491:     while (counter < 4) {
                   1492: 	strx = strReplace(strx,orgStr[counter],newStr[counter]);
                   1493: 	counter++;
                   1494:     }
                   1495:     return strx;
                   1496:   }
                   1497: 
                   1498:   function strReplace(strx, orgStr, newStr) {
                   1499:     return strx.split(orgStr).join(newStr);
                   1500:   }
                   1501: 
1.44      ng       1502:   function savedMsgHeader(Nmsg,usrctr,fullname) {
1.76      ng       1503:     var height = 70*Nmsg+250;
1.44      ng       1504:     var scrollbar = "no";
                   1505:     if (height > 600) {
                   1506: 	height = 600;
                   1507: 	scrollbar = "yes";
                   1508:     }
1.118     ng       1509:     var xpos = (screen.width-600)/2;
                   1510:     xpos = (xpos < 0) ? '0' : xpos;
                   1511:     var ypos = (screen.height-height)/2-30;
                   1512:     ypos = (ypos < 0) ? '0' : ypos;
                   1513: 
1.206     albertel 1514:     pWin = window.open('', 'MessageCenter', 'resizable=yes,toolbar=no,location=no,scrollbars='+scrollbar+',screenx='+xpos+',screeny='+ypos+',width=600,height='+height);
1.76      ng       1515:     pWin.focus();
                   1516:     pDoc = pWin.document;
1.219     www      1517:     pDoc.$docopen;
1.351     albertel 1518:     pDoc.write('$start_page_msg_central');
1.76      ng       1519: 
                   1520:     pDoc.write("<form action=\\"inactive\\" name=\\"msgcenter\\">");
                   1521:     pDoc.write("<input value=\\""+usrctr+"\\" name=\\"usrctr\\" type=\\"hidden\\">");
1.465     albertel 1522:     pDoc.write("<h3><span class=\\"LC_info\\">&nbsp;Compose Message for \"+fullname+\"<\\/span><\\/h3><br /><br />");
1.76      ng       1523: 
1.564     bisitz   1524:     pDoc.write('<table border="0" width="100%"><tr><td bgcolor="#777777">');
                   1525:     pDoc.write('<table border="0" width="100%"><tr bgcolor="#DDFFFF">');
1.465     albertel 1526:     pDoc.write("<td><b>Type<\\/b><\\/td><td><b>Include<\\/b><\\/td><td><b>Message<\\/td><\\/tr>");
1.44      ng       1527: }
                   1528:     function displaySubject(msg,shwsel) {
1.76      ng       1529:     pDoc = pWin.document;
                   1530:     pDoc.write("<tr bgcolor=\\"#ffffdd\\">");
1.465     albertel 1531:     pDoc.write("<td>Subject<\\/td>");
                   1532:     pDoc.write("<td align=\\"center\\"><input name=\\"subchk\\" type=\\"checkbox\\"" +shwsel+"><\\/td>");
                   1533:     pDoc.write("<td><input name=\\"msgsub\\" type=\\"text\\" value=\\""+msg+"\\"size=\\"60\\" maxlength=\\"80\\"><\\/td><\\/tr>");
1.44      ng       1534: }
                   1535: 
1.72      ng       1536:   function displaySavedMsg(ctr,msg,shwsel) {
1.76      ng       1537:     pDoc = pWin.document;
                   1538:     pDoc.write("<tr bgcolor=\\"#ffffdd\\">");
1.465     albertel 1539:     pDoc.write("<td align=\\"center\\">"+ctr+"<\\/td>");
                   1540:     pDoc.write("<td align=\\"center\\"><input name=\\"msgn"+ctr+"\\" type=\\"checkbox\\"" +shwsel+"><\\/td>");
                   1541:     pDoc.write("<td><textarea name=\\"msg"+ctr+"\\" cols=\\"60\\" rows=\\"3\\">"+msg+"<\\/textarea><\\/td><\\/tr>");
1.44      ng       1542: }
                   1543: 
                   1544:   function newMsg(newmsg,shwsel) {
1.76      ng       1545:     pDoc = pWin.document;
                   1546:     pDoc.write("<tr bgcolor=\\"#ffffdd\\">");
1.465     albertel 1547:     pDoc.write("<td align=\\"center\\">New<\\/td>");
                   1548:     pDoc.write("<td align=\\"center\\"><input name=\\"newmsgchk\\" type=\\"checkbox\\"" +shwsel+"><\\/td>");
                   1549:     pDoc.write("<td><textarea name=\\"newmsg\\" cols=\\"60\\" rows=\\"3\\" onchange=\\"javascript:this.form.newmsgchk.checked=true\\" >"+newmsg+"<\\/textarea><\\/td><\\/tr>");
1.44      ng       1550: }
                   1551: 
                   1552:   function msgTail() {
1.76      ng       1553:     pDoc = pWin.document;
1.465     albertel 1554:     pDoc.write("<\\/table>");
                   1555:     pDoc.write("<\\/td><\\/tr><\\/table>&nbsp;");
1.589     bisitz   1556:     pDoc.write("<input type=\\"button\\" value=\\"Save\\" onclick=\\"javascript:checkInput()\\">&nbsp;&nbsp;");
                   1557:     pDoc.write("<input type=\\"button\\" value=\\"Cancel\\" onclick=\\"self.close()\\"><br /><br />");
1.465     albertel 1558:     pDoc.write("<\\/form>");
1.351     albertel 1559:     pDoc.write('$end_page_msg_central');
1.128     ng       1560:     pDoc.close();
1.44      ng       1561: }
                   1562: 
                   1563: //====================== Script for keyword highlight options ==============
                   1564:   function kwhighlight() {
                   1565:     var kwclr    = document.SCORE.kwclr.value;
                   1566:     var kwsize   = document.SCORE.kwsize.value;
                   1567:     var kwstyle  = document.SCORE.kwstyle.value;
                   1568:     var redsel = "";
                   1569:     var grnsel = "";
                   1570:     var blusel = "";
                   1571:     if (kwclr=="red")   {var redsel="checked"};
                   1572:     if (kwclr=="green") {var grnsel="checked"};
                   1573:     if (kwclr=="blue")  {var blusel="checked"};
                   1574:     var sznsel = "";
                   1575:     var sz1sel = "";
                   1576:     var sz2sel = "";
                   1577:     if (kwsize=="0")  {var sznsel="checked"};
                   1578:     if (kwsize=="+1") {var sz1sel="checked"};
                   1579:     if (kwsize=="+2") {var sz2sel="checked"};
                   1580:     var synsel = "";
                   1581:     var syisel = "";
                   1582:     var sybsel = "";
                   1583:     if (kwstyle=="")    {var synsel="checked"};
                   1584:     if (kwstyle=="<i>") {var syisel="checked"};
                   1585:     if (kwstyle=="<b>") {var sybsel="checked"};
                   1586:     highlightCentral();
                   1587:     highlightbody('red','red',redsel,'0','normal',sznsel,'','normal',synsel);
                   1588:     highlightbody('green','green',grnsel,'+1','+1',sz1sel,'<i>','italic',syisel);
                   1589:     highlightbody('blue','blue',blusel,'+2','+2',sz2sel,'<b>','bold',sybsel);
                   1590:     highlightend();
                   1591:     return;
                   1592:   }
                   1593: 
                   1594:   function highlightCentral() {
1.76      ng       1595: //    if (window.hwdWin) window.hwdWin.close();
1.118     ng       1596:     var xpos = (screen.width-400)/2;
                   1597:     xpos = (xpos < 0) ? '0' : xpos;
                   1598:     var ypos = (screen.height-330)/2-30;
                   1599:     ypos = (ypos < 0) ? '0' : ypos;
                   1600: 
1.206     albertel 1601:     hwdWin = window.open('', 'KeywordHighlightCentral', 'resizeable=yes,toolbar=no,location=no,scrollbars=no,width=400,height=300,screenx='+xpos+',screeny='+ypos);
1.76      ng       1602:     hwdWin.focus();
                   1603:     var hDoc = hwdWin.document;
1.219     www      1604:     hDoc.$docopen;
1.351     albertel 1605:     hDoc.write('$start_page_highlight_central');
1.76      ng       1606:     hDoc.write("<form action=\\"inactive\\" name=\\"hlCenter\\">");
1.465     albertel 1607:     hDoc.write("<h3><span class=\\"LC_info\\">&nbsp;Keyword Highlight Options<\\/span><\\/h3><br /><br />");
1.76      ng       1608: 
1.564     bisitz   1609:     hDoc.write('<table border="0" width="100%"><tr><td bgcolor="#777777">');
                   1610:     hDoc.write('<table border="0" width="100%"><tr bgcolor="#DDFFFF">');
1.465     albertel 1611:     hDoc.write("<td><b>Text Color<\\/b><\\/td><td><b>Font Size<\\/b><\\/td><td><b>Font Style<\\/td><\\/tr>");
1.44      ng       1612:   }
                   1613: 
                   1614:   function highlightbody(clrval,clrtxt,clrsel,szval,sztxt,szsel,syval,sytxt,sysel) { 
1.76      ng       1615:     var hDoc = hwdWin.document;
                   1616:     hDoc.write("<tr bgcolor=\\"#ffffdd\\">");
                   1617:     hDoc.write("<td align=\\"left\\">");
1.465     albertel 1618:     hDoc.write("<input name=\\"kwdclr\\" type=\\"radio\\" value=\\""+clrval+"\\" "+clrsel+">&nbsp;"+clrtxt+"<\\/td>");
1.76      ng       1619:     hDoc.write("<td align=\\"left\\">");
1.465     albertel 1620:     hDoc.write("<input name=\\"kwdsize\\" type=\\"radio\\" value=\\""+szval+"\\" "+szsel+">&nbsp;"+sztxt+"<\\/td>");
1.76      ng       1621:     hDoc.write("<td align=\\"left\\">");
1.465     albertel 1622:     hDoc.write("<input name=\\"kwdstyle\\" type=\\"radio\\" value=\\""+syval+"\\" "+sysel+">&nbsp;"+sytxt+"<\\/td>");
                   1623:     hDoc.write("<\\/tr>");
1.44      ng       1624:   }
                   1625: 
                   1626:   function highlightend() { 
1.76      ng       1627:     var hDoc = hwdWin.document;
1.465     albertel 1628:     hDoc.write("<\\/table>");
                   1629:     hDoc.write("<\\/td><\\/tr><\\/table>&nbsp;");
1.589     bisitz   1630:     hDoc.write("<input type=\\"button\\" value=\\"Save\\" onclick=\\"javascript:updateChoice(1)\\">&nbsp;&nbsp;");
                   1631:     hDoc.write("<input type=\\"button\\" value=\\"Cancel\\" onclick=\\"self.close()\\"><br /><br />");
1.465     albertel 1632:     hDoc.write("<\\/form>");
1.351     albertel 1633:     hDoc.write('$end_page_highlight_central');
1.128     ng       1634:     hDoc.close();
1.44      ng       1635:   }
                   1636: 
                   1637: SUBJAVASCRIPT
                   1638: }
                   1639: 
1.349     albertel 1640: sub get_increment {
1.348     bowersj2 1641:     my $increment = $env{'form.increment'};
                   1642:     if ($increment != 1 && $increment != .5 && $increment != .25 &&
                   1643:         $increment != .1) {
                   1644:         $increment = 1;
                   1645:     }
                   1646:     return $increment;
                   1647: }
                   1648: 
1.585     bisitz   1649: sub gradeBox_start {
                   1650:     return (
                   1651:         &Apache::loncommon::start_data_table()
                   1652:        .&Apache::loncommon::start_data_table_header_row()
                   1653:        .'<th>'.&mt('Part').'</th>'
                   1654:        .'<th>'.&mt('Points').'</th>'
                   1655:        .'<th>&nbsp;</th>'
                   1656:        .'<th>'.&mt('Assign Grade').'</th>'
                   1657:        .'<th>'.&mt('Weight').'</th>'
                   1658:        .'<th>'.&mt('Grade Status').'</th>'
                   1659:        .&Apache::loncommon::end_data_table_header_row()
                   1660:     );
                   1661: }
                   1662: 
                   1663: sub gradeBox_end {
                   1664:     return (
                   1665:         &Apache::loncommon::end_data_table()
                   1666:     );
                   1667: }
1.71      ng       1668: #--- displays the grading box, used in essay type problem and grading by page/sequence
                   1669: sub gradeBox {
1.322     albertel 1670:     my ($request,$symb,$uname,$udom,$counter,$partid,$record) = @_;
1.381     albertel 1671:     my $checkIcon = '<img alt="'.&mt('Check Mark').
1.485     albertel 1672: 	'" src="'.&Apache::loncommon::lonhttpdurl($request->dir_config('lonIconsURL').'/check.gif').'" height="16" border="0" />';
1.71      ng       1673:     my $wgt    = &Apache::lonnet::EXT('resource.'.$partid.'.weight',$symb,$udom,$uname);
1.466     albertel 1674:     my $wgtmsg = ($wgt > 0) ? &mt('(problem weight)') 
                   1675:                            : '<span class="LC_info">'.&mt('problem weight assigned by computer').'</span>';
1.71      ng       1676:     $wgt       = ($wgt > 0 ? $wgt : '1');
                   1677:     my $score  = ($$record{'resource.'.$partid.'.awarded'} eq '' ?
1.320     albertel 1678: 		  '' : &compute_points($$record{'resource.'.$partid.'.awarded'},$wgt));
1.71      ng       1679:     my $result='<input type="hidden" name="WGT'.$counter.'_'.$partid.'" value="'.$wgt.'" />'."\n";
1.466     albertel 1680:     my $display_part= &get_display_part($partid,$symb);
1.270     albertel 1681:     my %last_resets = &get_last_resets($symb,$env{'request.course.id'},
                   1682: 				       [$partid]);
                   1683:     my $aggtries = $$record{'resource.'.$partid.'.tries'};
1.269     raeburn  1684:     if ($last_resets{$partid}) {
                   1685:         $aggtries = &get_num_tries($record,$last_resets{$partid},$partid);
                   1686:     }
1.585     bisitz   1687:     $result.=&Apache::loncommon::start_data_table_row();
1.71      ng       1688:     my $ctr = 0;
1.348     bowersj2 1689:     my $thisweight = 0;
1.349     albertel 1690:     my $increment = &get_increment();
1.485     albertel 1691: 
                   1692:     my $radio.='<table border="0"><tr>'."\n";  # display radio buttons in a nice table 10 across
1.348     bowersj2 1693:     while ($thisweight<=$wgt) {
1.532     bisitz   1694: 	$radio.= '<td><span class="LC_nobreak"><label><input type="radio" name="RADVAL'.$counter.'_'.$partid.'" '.
1.589     bisitz   1695:         'onclick="javascript:writeBox(this.form,\''.$counter.'_'.$partid.'\','.
1.348     bowersj2 1696: 	    $thisweight.')" value="'.$thisweight.'" '.
1.401     albertel 1697: 	    ($score eq $thisweight ? 'checked="checked"':'').' /> '.$thisweight."</label></span></td>\n";
1.485     albertel 1698: 	$radio.=(($ctr+1)%10 == 0 ? '</tr><tr>' : '');
1.348     bowersj2 1699:         $thisweight += $increment;
1.71      ng       1700: 	$ctr++;
                   1701:     }
1.485     albertel 1702:     $radio.='</tr></table>';
                   1703: 
                   1704:     my $line.='<input type="text" name="GD_BOX'.$counter.'_'.$partid.'"'.
1.71      ng       1705: 	($score ne ''? ' value = "'.$score.'"':'').' size="4" '.
1.589     bisitz   1706: 	'onchange="javascript:updateRadio(this.form,\''.$counter.'_'.$partid.'\','.
1.71      ng       1707: 	$wgt.')" /></td>'."\n";
1.485     albertel 1708:     $line.='<td>/'.$wgt.' '.$wgtmsg.
1.71      ng       1709: 	($$record{'resource.'.$partid.'.solved'} eq 'correct_by_student' ? '&nbsp;'.$checkIcon : '').
1.585     bisitz   1710: 	' </td>'."\n";
                   1711:     $line.='<td><select name="GD_SEL'.$counter.'_'.$partid.'" '.
1.589     bisitz   1712: 	'onchange="javascript:clearRadBox(this.form,\''.$counter.'_'.$partid.'\')" >'."\n";
1.71      ng       1713:     if ($$record{'resource.'.$partid.'.solved'} eq 'excused') {
1.485     albertel 1714: 	$line.='<option></option>'.
                   1715: 	    '<option value="excused" selected="selected">'.&mt('excused').'</option>';
1.71      ng       1716:     } else {
1.485     albertel 1717: 	$line.='<option selected="selected"></option>'.
                   1718: 	    '<option value="excused" >'.&mt('excused').'</option>';
1.71      ng       1719:     }
1.485     albertel 1720:     $line.='<option value="reset status">'.&mt('reset status').'</option></select>'."\n";
                   1721: 
                   1722: 
                   1723:     $result .= 
1.585     bisitz   1724: 	    '<td>'.$display_part.'</td><td>'.$radio.'</td><td>'.&mt('or').'</td><td>'.$line.'</td>';
                   1725:     $result.=&Apache::loncommon::end_data_table_row();
1.71      ng       1726:     $result.='<input type="hidden" name="stores'.$counter.'_'.$partid.'" value="" />'."\n".
                   1727: 	'<input type="hidden" name="oldpts'.$counter.'_'.$partid.'" value="'.$score.'" />'."\n".
                   1728: 	'<input type="hidden" name="solved'.$counter.'_'.$partid.'" value="'.
1.269     raeburn  1729: 	$$record{'resource.'.$partid.'.solved'}.'" />'."\n".
                   1730:         '<input type="hidden" name="totaltries'.$counter.'_'.$partid.'" value="'.
                   1731:         $$record{'resource.'.$partid.'.tries'}.'" />'."\n".
                   1732:         '<input type="hidden" name="aggtries'.$counter.'_'.$partid.'" value="'.
                   1733:         $aggtries.'" />'."\n";
1.582     raeburn  1734:     my $res_error;
                   1735:     $result.=&handback_box($symb,$uname,$udom,$counter,$partid,$record,\$res_error);
                   1736:     if ($res_error) {
                   1737:         return &navmap_errormsg();
                   1738:     }
1.318     banghart 1739:     return $result;
                   1740: }
1.322     albertel 1741: 
                   1742: sub handback_box {
1.582     raeburn  1743:     my ($symb,$uname,$udom,$counter,$partid,$record,$res_error) = @_;
                   1744:     my ($partlist,$handgrade,$responseType) = &response_type($symb,$res_error);
1.323     banghart 1745:     my (@respids);
1.375     albertel 1746:      my @part_response_id = &flatten_responseType($responseType);
                   1747:     foreach my $part_response_id (@part_response_id) {
                   1748:     	my ($part,$resp) = @{ $part_response_id };
1.323     banghart 1749:         if ($part eq $partid) {
1.375     albertel 1750:             push(@respids,$resp);
1.323     banghart 1751:         }
                   1752:     }
1.318     banghart 1753:     my $result;
1.323     banghart 1754:     foreach my $respid (@respids) {
1.322     albertel 1755: 	my $prefix = $counter.'_'.$partid.'_'.$respid.'_';
                   1756: 	my $files=&get_submitted_files($udom,$uname,$partid,$respid,$record);
                   1757: 	next if (!@$files);
                   1758: 	my $file_counter = 1;
1.313     banghart 1759: 	foreach my $file (@$files) {
1.368     banghart 1760: 	    if ($file =~ /\/portfolio\//) {
                   1761:     	        my ($file_path, $file_disp) = ($file =~ m|(.+/)(.+)$|);
                   1762:     	        my ($name,$version,$ext) = &file_name_version_ext($file_disp);
                   1763:     	        $file_disp = "$name.$ext";
                   1764:     	        $file = $file_path.$file_disp;
                   1765:     	        $result.=&mt('Return commented version of [_1] to student.',
                   1766:     			 '<span class="LC_filename">'.$file_disp.'</span>');
                   1767:     	        $result.='<input type="file"   name="'.$prefix.'returndoc'.$file_counter.'" />'."\n";
                   1768:     	        $result.='<input type="hidden" name="'.$prefix.'origdoc'.$file_counter.'" value="'.$file.'" /><br />';
1.485     albertel 1769:     	        $result.='('.&mt('File will be uploaded when you click on Save &amp; Next below.').')<br />';
1.368     banghart 1770:     	        $file_counter++;
                   1771: 	    }
1.322     albertel 1772: 	}
1.313     banghart 1773:     }
1.318     banghart 1774:     return $result;    
1.71      ng       1775: }
1.44      ng       1776: 
1.58      albertel 1777: sub show_problem {
1.382     albertel 1778:     my ($request,$symb,$uname,$udom,$removeform,$viewon,$mode,$form) = @_;
1.144     albertel 1779:     my $rendered;
1.382     albertel 1780:     my %form = ((ref($form) eq 'HASH')? %{$form} : ());
1.329     albertel 1781:     &Apache::lonxml::remember_problem_counter();
1.144     albertel 1782:     if ($mode eq 'both' or $mode eq 'text') {
                   1783: 	$rendered=&Apache::loncommon::get_student_view($symb,$uname,$udom,
1.382     albertel 1784: 						       $env{'request.course.id'},
                   1785: 						       undef,\%form);
1.144     albertel 1786:     }
1.58      albertel 1787:     if ($removeform) {
                   1788: 	$rendered=~s|<form(.*?)>||g;
                   1789: 	$rendered=~s|</form>||g;
1.374     albertel 1790: 	$rendered=~s|(<input[^>]*name\s*=\s*"?)(\w+)("?)|$1would_have_been_$2$3|g;
1.58      albertel 1791:     }
1.144     albertel 1792:     my $companswer;
                   1793:     if ($mode eq 'both' or $mode eq 'answer') {
1.329     albertel 1794: 	&Apache::lonxml::restore_problem_counter();
1.382     albertel 1795: 	$companswer=
                   1796: 	    &Apache::loncommon::get_student_answers($symb,$uname,$udom,
                   1797: 						    $env{'request.course.id'},
                   1798: 						    %form);
1.144     albertel 1799:     }
1.58      albertel 1800:     if ($removeform) {
                   1801: 	$companswer=~s|<form(.*?)>||g;
                   1802: 	$companswer=~s|</form>||g;
1.144     albertel 1803: 	$companswer=~s|name="submit"|name="would_have_been_submit"|g;
1.58      albertel 1804:     }
1.468     albertel 1805:     $rendered=
1.588     bisitz   1806:         '<div class="LC_Box">'
                   1807:        .'<h3 class="LC_hcell">'.&mt('View of the problem').'</h3>'
                   1808:        .$rendered
                   1809:        .'</div>';
1.468     albertel 1810:     $companswer=
1.588     bisitz   1811:         '<div class="LC_Box">'
                   1812:        .'<h3 class="LC_hcell">'.&mt('Correct answer').'</h3>'
                   1813:        .$companswer
                   1814:        .'</div>';
1.468     albertel 1815:     my $result;
1.144     albertel 1816:     if ($mode eq 'both') {
1.588     bisitz   1817:         $result=$rendered.$companswer;
1.144     albertel 1818:     } elsif ($mode eq 'text') {
1.588     bisitz   1819:         $result=$rendered;
1.144     albertel 1820:     } elsif ($mode eq 'answer') {
1.588     bisitz   1821:         $result=$companswer;
1.144     albertel 1822:     }
1.71      ng       1823:     return $result;
1.58      albertel 1824: }
1.397     albertel 1825: 
1.396     banghart 1826: sub files_exist {
                   1827:     my ($r, $symb) = @_;
                   1828:     my @students = &Apache::loncommon::get_env_multiple('form.stuinfo');
1.397     albertel 1829: 
1.396     banghart 1830:     foreach my $student (@students) {
                   1831:         my ($uname,$udom,$fullname) = split(/:/,$student);
1.397     albertel 1832:         my %record = &Apache::lonnet::restore($symb,$env{'request.course.id'},
                   1833: 					      $udom,$uname);
1.396     banghart 1834:         my ($string,$timestamp)= &get_last_submission(\%record);
1.397     albertel 1835:         foreach my $submission (@$string) {
                   1836:             my ($partid,$respid) =
                   1837: 		($submission =~ /^resource\.([^\.]*)\.([^\.]*)\.submission/);
                   1838:             my $files=&get_submitted_files($udom,$uname,$partid,$respid,
                   1839: 					   \%record);
                   1840:             return 1 if (@$files);
1.396     banghart 1841:         }
                   1842:     }
1.397     albertel 1843:     return 0;
1.396     banghart 1844: }
1.397     albertel 1845: 
1.394     banghart 1846: sub download_all_link {
                   1847:     my ($r,$symb) = @_;
1.395     albertel 1848:     my $all_students = 
                   1849: 	join("\n", &Apache::loncommon::get_env_multiple('form.stuinfo'));
                   1850: 
                   1851:     my $parts =
                   1852: 	join("\n",&Apache::loncommon::get_env_multiple('form.vPart'));
                   1853: 
1.394     banghart 1854:     my $identifier = &Apache::loncommon::get_cgi_id();
1.514     raeburn  1855:     &Apache::lonnet::appenv({'cgi.'.$identifier.'.students' => $all_students,
                   1856:                              'cgi.'.$identifier.'.symb' => $symb,
                   1857:                              'cgi.'.$identifier.'.parts' => $parts,});
1.395     albertel 1858:     $r->print('<a href="/cgi-bin/multidownload.pl?'.$identifier.'">'.
                   1859: 	      &mt('Download All Submitted Documents').'</a>');
1.394     banghart 1860:     return
                   1861: }
1.395     albertel 1862: 
1.432     banghart 1863: sub build_section_inputs {
                   1864:     my $section_inputs;
                   1865:     if ($env{'form.section'} eq '') {
                   1866:         $section_inputs .= '<input type="hidden" name="section" value="all" />'."\n";
                   1867:     } else {
                   1868:         my @sections = &Apache::loncommon::get_env_multiple('form.section');
1.434     albertel 1869:         foreach my $section (@sections) {
1.432     banghart 1870:             $section_inputs .= '<input type="hidden" name="section" value="'.$section.'" />'."\n";
                   1871:         }
                   1872:     }
                   1873:     return $section_inputs;
                   1874: }
                   1875: 
1.44      ng       1876: # --------------------------- show submissions of a student, option to grade 
                   1877: sub submission {
1.608     www      1878:     my ($request,$counter,$total,$symb) = @_;
1.257     albertel 1879:     my ($uname,$udom)     = ($env{'form.student'},$env{'form.userdom'});
                   1880:     $udom = ($udom eq '' ? $env{'user.domain'} : $udom); #has form.userdom changed for a student?
                   1881:     my $usec = &Apache::lonnet::getsection($udom,$uname,$env{'request.course.id'});
                   1882:     $env{'form.fullname'} = &Apache::loncommon::plainname($uname,$udom,'lastname') if $env{'form.fullname'} eq '';
1.608     www      1883: 
1.605     www      1884:     my $probtitle=&Apache::lonnet::gettitle($symb); 
1.324     albertel 1885:     if ($symb eq '') { $request->print("Unable to handle ambiguous references:."); return ''; }
1.104     albertel 1886: 
                   1887:     if (!&canview($usec)) {
1.398     albertel 1888: 	$request->print('<span class="LC_warning">Unable to view requested student.('.
                   1889: 			$uname.':'.$udom.' in section '.$usec.' in course id '.
                   1890: 			$env{'request.course.id'}.')</span>');
1.104     albertel 1891: 	return;
                   1892:     }
                   1893: 
1.257     albertel 1894:     if (!$env{'form.lastSub'}) { $env{'form.lastSub'} = 'datesub'; }
                   1895:     if (!$env{'form.vProb'}) { $env{'form.vProb'} = 'yes'; }
                   1896:     if (!$env{'form.vAns'}) { $env{'form.vAns'} = 'yes'; }
                   1897:     my $last = ($env{'form.lastSub'} eq 'last' ? 'last' : '');
1.381     albertel 1898:     my $checkIcon = '<img alt="'.&mt('Check Mark').
                   1899: 	'" src="'.$request->dir_config('lonIconsURL').
1.122     ng       1900: 	'/check.gif" height="16" border="0" />';
1.41      ng       1901: 
1.426     albertel 1902:     my %old_essays;
1.41      ng       1903:     # header info
                   1904:     if ($counter == 0) {
                   1905: 	&sub_page_js($request);
1.257     albertel 1906: 	&sub_page_kw_js($request) if ($env{'form.handgrade'} eq 'yes');
1.397     albertel 1907: 	if ($env{'form.handgrade'} eq 'yes' && &files_exist($request, $symb)) {
1.396     banghart 1908: 	    &download_all_link($request, $symb);
                   1909: 	}
1.605     www      1910: 	$request->print('<h3>&nbsp;<span class="LC_info">'.&mt('Submission Record').'</span></h3>');
1.118     ng       1911: 
1.44      ng       1912: 	# option to display problem, only once else it cause problems 
                   1913:         # with the form later since the problem has a form.
1.257     albertel 1914: 	if ($env{'form.vProb'} eq 'yes' or $env{'form.vAns'} eq 'yes') {
1.144     albertel 1915: 	    my $mode;
1.257     albertel 1916: 	    if ($env{'form.vProb'} eq 'yes' && $env{'form.vAns'} eq 'yes') {
1.144     albertel 1917: 		$mode='both';
1.257     albertel 1918: 	    } elsif ($env{'form.vProb'} eq 'yes') {
1.144     albertel 1919: 		$mode='text';
1.257     albertel 1920: 	    } elsif ($env{'form.vAns'} eq 'yes') {
1.144     albertel 1921: 		$mode='answer';
                   1922: 	    }
1.329     albertel 1923: 	    &Apache::lonxml::clear_problem_counter();
1.144     albertel 1924: 	    $request->print(&show_problem($request,$symb,$uname,$udom,0,1,$mode));
1.41      ng       1925: 	}
1.441     www      1926: 
1.44      ng       1927: 	# kwclr is the only variable that is guaranteed to be non blank 
                   1928:         # if this subroutine has been called once.
1.41      ng       1929: 	my %keyhash = ();
1.257     albertel 1930: 	if ($env{'form.kwclr'} eq '' && $env{'form.handgrade'} eq 'yes') {
1.41      ng       1931: 	    %keyhash = &Apache::lonnet::dump('nohist_handgrade',
1.257     albertel 1932: 					     $env{'course.'.$env{'request.course.id'}.'.domain'},
                   1933: 					     $env{'course.'.$env{'request.course.id'}.'.num'});
1.41      ng       1934: 
1.257     albertel 1935: 	    my $loginuser = $env{'user.name'}.':'.$env{'user.domain'};
                   1936: 	    $env{'form.keywords'} = $keyhash{$symb.'_keywords'} ne '' ? $keyhash{$symb.'_keywords'} : '';
                   1937: 	    $env{'form.kwclr'}    = $keyhash{$loginuser.'_kwclr'} ne '' ? $keyhash{$loginuser.'_kwclr'} : 'red';
                   1938: 	    $env{'form.kwsize'}   = $keyhash{$loginuser.'_kwsize'} ne '' ? $keyhash{$loginuser.'_kwsize'} : '0';
                   1939: 	    $env{'form.kwstyle'}  = $keyhash{$loginuser.'_kwstyle'} ne '' ? $keyhash{$loginuser.'_kwstyle'} : '';
                   1940: 	    $env{'form.msgsub'}   = $keyhash{$symb.'_subject'} ne '' ? 
1.605     www      1941: 		$keyhash{$symb.'_subject'} : $probtitle;
1.257     albertel 1942: 	    $env{'form.savemsgN'} = $keyhash{$symb.'_savemsgN'} ne '' ? $keyhash{$symb.'_savemsgN'} : '0';
1.41      ng       1943: 	}
1.257     albertel 1944: 	my $overRideScore = $env{'form.overRideScore'} eq '' ? 'no' : $env{'form.overRideScore'};
1.442     banghart 1945: 	my $stu_status = join(':',&Apache::loncommon::get_env_multiple('form.Status'));
1.303     banghart 1946: 	$request->print('<form action="/adm/grades" method="post" name="SCORE" enctype="multipart/form-data">'."\n".
1.41      ng       1947: 			'<input type="hidden" name="command"    value="handgrade" />'."\n".
1.442     banghart 1948: 			'<input type="hidden" name="Status"     value="'.$stu_status.'" />'."\n".
1.120     ng       1949: 			'<input type="hidden" name="overRideScore" value="'.$overRideScore.'" />'."\n".
1.41      ng       1950: 			'<input type="hidden" name="refresh"    value="off" />'."\n".
1.120     ng       1951: 			'<input type="hidden" name="studentNo"  value="" />'."\n".
                   1952: 			'<input type="hidden" name="gradeOpt"   value="" />'."\n".
1.418     albertel 1953: 			'<input type="hidden" name="symb"       value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
1.257     albertel 1954: 			'<input type="hidden" name="vProb"      value="'.$env{'form.vProb'}.'" />'."\n".
                   1955: 			'<input type="hidden" name="vAns"       value="'.$env{'form.vAns'}.'" />'."\n".
                   1956: 			'<input type="hidden" name="lastSub"    value="'.$env{'form.lastSub'}.'" />'."\n".
1.432     banghart 1957: 			&build_section_inputs().
1.326     albertel 1958: 			'<input type="hidden" name="submitonly" value="'.$env{'form.submitonly'}.'" />'."\n".
                   1959: 			'<input type="hidden" name="handgrade"  value="'.$env{'form.handgrade'}.'" />'."\n".
1.41      ng       1960: 			'<input type="hidden" name="NCT"'.
1.257     albertel 1961: 			' value="'.($env{'form.NTSTU'} ne '' ? $env{'form.NTSTU'} : $total+1).'" />'."\n");
                   1962: 	if ($env{'form.handgrade'} eq 'yes') {
                   1963: 	    $request->print('<input type="hidden" name="keywords" value="'.$env{'form.keywords'}.'" />'."\n".
                   1964: 			    '<input type="hidden" name="kwclr"    value="'.$env{'form.kwclr'}.'" />'."\n".
                   1965: 			    '<input type="hidden" name="kwsize"   value="'.$env{'form.kwsize'}.'" />'."\n".
                   1966: 			    '<input type="hidden" name="kwstyle"  value="'.$env{'form.kwstyle'}.'" />'."\n".
                   1967: 			    '<input type="hidden" name="msgsub"   value="'.$env{'form.msgsub'}.'" />'."\n".
1.123     ng       1968: 			    '<input type="hidden" name="shownSub" value="0" />'."\n".
1.257     albertel 1969: 			    '<input type="hidden" name="savemsgN" value="'.$env{'form.savemsgN'}.'" />'."\n");
1.154     albertel 1970: 	    foreach my $partid (&Apache::loncommon::get_env_multiple('form.vPart')) {
                   1971: 		$request->print('<input type="hidden" name="vPart" value="'.$partid.'" />'."\n");
                   1972: 	    }
1.123     ng       1973: 	}
1.41      ng       1974: 	
                   1975: 	my ($cts,$prnmsg) = (1,'');
1.257     albertel 1976: 	while ($cts <= $env{'form.savemsgN'}) {
1.41      ng       1977: 	    $prnmsg.='<input type="hidden" name="savemsg'.$cts.'" value="'.
1.123     ng       1978: 		(!exists($keyhash{$symb.'_savemsg'.$cts}) ? 
1.257     albertel 1979: 		 &Apache::lonfeedback::clear_out_html($env{'form.savemsg'.$cts}) :
1.80      ng       1980: 		 &Apache::lonfeedback::clear_out_html($keyhash{$symb.'_savemsg'.$cts})).
1.123     ng       1981: 		'" />'."\n".
                   1982: 		'<input type="hidden" name="shownOnce'.$cts.'" value="0" />'."\n";
1.41      ng       1983: 	    $cts++;
                   1984: 	}
                   1985: 	$request->print($prnmsg);
1.32      ng       1986: 
1.618   ! www      1987: 	if ($env{'form.handgrade'} eq 'yes') {
1.88      www      1988: #
                   1989: # Print out the keyword options line
                   1990: #
1.41      ng       1991: 	    $request->print(<<KEYWORDS);
1.38      ng       1992: &nbsp;<b>Keyword Options:</b>&nbsp;
1.417     albertel 1993: <a href="javascript:keywords(document.SCORE);" target="_self">List</a>&nbsp; &nbsp;
1.589     bisitz   1994: <a href="#" onmousedown="javascript:getSel(); return false"
1.38      ng       1995:  CLASS="page">Paste Selection to List</a>&nbsp; &nbsp;
1.417     albertel 1996: <a href="javascript:kwhighlight();" target="_self">Highlight Attribute</a><br /><br />
1.38      ng       1997: KEYWORDS
1.88      www      1998: #
                   1999: # Load the other essays for similarity check
                   2000: #
1.324     albertel 2001:             my (undef,undef,$essayurl) = &Apache::lonnet::decode_symb($symb);
1.384     albertel 2002: 	    my ($adom,$aname,$apath)=($essayurl=~/^($LONCAPA::domain_re)\/($LONCAPA::username_re)\/(.*)$/);
1.359     www      2003: 	    $apath=&escape($apath);
1.88      www      2004: 	    $apath=~s/\W/\_/gs;
1.426     albertel 2005: 	    %old_essays=&Apache::lonnet::dump('nohist_essay_'.$apath,$adom,$aname);
1.41      ng       2006:         }
                   2007:     }
1.44      ng       2008: 
1.441     www      2009: # This is where output for one specific student would start
1.592     bisitz   2010:     my $add_class = ($counter%2) ? ' LC_grade_show_user_odd_row' : '';
                   2011:     $request->print(
                   2012:         "\n\n"
                   2013:        .'<div class="LC_grade_show_user'.$add_class.'">'
                   2014:        .'<h2>'.&nameUserString(undef,$env{'form.fullname'},$uname,$udom).'</h2>'
                   2015:        ."\n"
                   2016:     );
1.441     www      2017: 
1.592     bisitz   2018:     # Show additional functions if allowed
                   2019:     if ($perm{'vgr'}) {
                   2020:         $request->print(
                   2021:             &Apache::loncommon::track_student_link(
                   2022:                 &mt('View recent activity'),
                   2023:                 $uname,$udom,'check')
                   2024:            .' '
                   2025:         );
                   2026:     }
                   2027:     if ($perm{'opa'}) {
                   2028:         $request->print(
                   2029:             &Apache::loncommon::pprmlink(
                   2030:                 &mt('Set/Change parameters'),
                   2031:                 $uname,$udom,$symb,'check'));
                   2032:     }
                   2033: 
                   2034:     # Show Problem
1.257     albertel 2035:     if ($env{'form.vProb'} eq 'all' or $env{'form.vAns'} eq 'all') {
1.144     albertel 2036: 	my $mode;
1.257     albertel 2037: 	if ($env{'form.vProb'} eq 'all' && $env{'form.vAns'} eq 'all') {
1.144     albertel 2038: 	    $mode='both';
1.257     albertel 2039: 	} elsif ($env{'form.vProb'} eq 'all' ) {
1.144     albertel 2040: 	    $mode='text';
1.257     albertel 2041: 	} elsif ($env{'form.vAns'} eq 'all') {
1.144     albertel 2042: 	    $mode='answer';
                   2043: 	}
1.329     albertel 2044: 	&Apache::lonxml::clear_problem_counter();
1.475     albertel 2045: 	$request->print(&show_problem($request,$symb,$uname,$udom,1,1,$mode,{'request.prefix' => 'ctr'.$counter}));
1.58      albertel 2046:     }
1.144     albertel 2047: 
1.257     albertel 2048:     my %record = &Apache::lonnet::restore($symb,$env{'request.course.id'},$udom,$uname);
1.582     raeburn  2049:     my $res_error;
                   2050:     my ($partlist,$handgrade,$responseType) = &response_type($symb,\$res_error);
                   2051:     if ($res_error) {
                   2052:         $request->print(&navmap_errormsg());
                   2053:         return;
                   2054:     }
1.41      ng       2055: 
1.44      ng       2056:     # Display student info
1.41      ng       2057:     $request->print(($counter == 0 ? '' : '<br />'));
1.590     bisitz   2058: 
                   2059:     my $result='<div class="LC_Box">'
                   2060:               .'<h3 class="LC_hcell">'.&mt('Submissions').'</h3>';
1.45      ng       2061:     $result.='<input type="hidden" name="name'.$counter.
1.588     bisitz   2062:              '" value="'.$env{'form.fullname'}.'" />'."\n";
1.469     albertel 2063:     if ($env{'form.handgrade'} eq 'no') {
1.588     bisitz   2064:         $result.='<p class="LC_info">'
                   2065:                 .&mt('Part(s) graded correct by the computer is marked with a [_1] symbol.',$checkIcon)
                   2066:                 ."</p>\n";
1.469     albertel 2067:     }
                   2068: 
1.118     ng       2069:     # If any part of the problem is an essay-response (handgraded), then check for collaborators
1.464     albertel 2070:     my $fullname;
                   2071:     my $col_fullnames = [];
1.257     albertel 2072:     if ($env{'form.handgrade'} eq 'yes') {
1.464     albertel 2073: 	(my $sub_result,$fullname,$col_fullnames)=
                   2074: 	    &check_collaborators($symb,$uname,$udom,\%record,$handgrade,
                   2075: 				 $counter);
                   2076: 	$result.=$sub_result;
1.41      ng       2077:     }
1.44      ng       2078:     $request->print($result."\n");
1.588     bisitz   2079: 
1.44      ng       2080:     # print student answer/submission
1.588     bisitz   2081:     # Options are (1) Handgraded submission only
1.44      ng       2082:     #             (2) Last submission, includes submission that is not handgraded 
                   2083:     #                  (for multi-response type part)
                   2084:     #             (3) Last submission plus the parts info
                   2085:     #             (4) The whole record for this student
1.257     albertel 2086:     if ($env{'form.lastSub'} =~ /^(lastonly|hdgrade)$/) {
1.151     albertel 2087: 	my ($string,$timestamp)= &get_last_submission(\%record);
1.468     albertel 2088: 	
                   2089: 	my $lastsubonly;
                   2090: 
1.588     bisitz   2091:         if ($$timestamp eq '') {
                   2092:             $lastsubonly.='<div class="LC_grade_submissions_body">'.$$string[0].'</div>'; 
                   2093:         } else {
1.592     bisitz   2094:             $lastsubonly =
                   2095:                 '<div class="LC_grade_submissions_body">'
                   2096:                .'<b>'.&mt('Date Submitted:').'</b> '.$$timestamp."\n";
1.468     albertel 2097: 
1.151     albertel 2098: 	    my %seenparts;
1.375     albertel 2099: 	    my @part_response_id = &flatten_responseType($responseType);
                   2100: 	    foreach my $part (@part_response_id) {
1.393     albertel 2101: 		next if ($env{'form.lastSub'} eq 'hdgrade' 
                   2102: 			 && $$handgrade{$$part[0].'_'.$$part[1]} ne 'yes');
                   2103: 
1.375     albertel 2104: 		my ($partid,$respid) = @{ $part };
1.324     albertel 2105: 		my $display_part=&get_display_part($partid,$symb);
1.257     albertel 2106: 		if ($env{"form.$uname:$udom:$partid:submitted_by"}) {
1.151     albertel 2107: 		    if (exists($seenparts{$partid})) { next; }
                   2108: 		    $seenparts{$partid}=1;
1.207     albertel 2109: 		    my $submitby='<b>Part:</b> '.$display_part.
                   2110: 			' <b>Collaborative submission by:</b> '.
1.151     albertel 2111: 			'<a href="javascript:viewSubmitter(\''.
1.257     albertel 2112: 			$env{"form.$uname:$udom:$partid:submitted_by"}.
1.417     albertel 2113: 			'\');" target="_self">'.
1.257     albertel 2114: 			$$fullname{$env{"form.$uname:$udom:$partid:submitted_by"}}.'</a><br />';
1.151     albertel 2115: 		    $request->print($submitby);
                   2116: 		    next;
                   2117: 		}
                   2118: 		my $responsetype = $responseType->{$partid}->{$respid};
                   2119: 		if (!exists($record{"resource.$partid.$respid.submission"})) {
1.577     bisitz   2120:                     $lastsubonly.="\n".'<div class="LC_grade_submission_part">'.
                   2121:                         '<b>'.&mt('Part: [_1]',$display_part).'</b>'.
                   2122:                         ' <span class="LC_internal_info">'.
1.597     wenzelju 2123:                         '('.&mt('Part ID: [_1]',$respid).')'.
1.577     bisitz   2124:                         '</span>&nbsp; &nbsp;'.
1.539     riegler  2125: 			'<span class="LC_warning">'.&mt('Nothing submitted - no attempts.').'</span><br /><br /></div>';
1.151     albertel 2126: 		    next;
                   2127: 		}
1.468     albertel 2128: 		foreach my $submission (@$string) {
                   2129: 		    my ($partid,$respid) = ($submission =~ /^resource\.([^\.]*)\.([^\.]*)\.submission/);
1.375     albertel 2130: 		    if (join('_',@{$part}) ne ($partid.'_'.$respid)) { next; }
1.596     raeburn  2131: 		    my ($ressub,$hide,$subval) = split(/:/,$submission,3);
1.151     albertel 2132: 		    # Similarity check
                   2133: 		    my $similar='';
1.257     albertel 2134: 		    if($env{'form.checkPlag'}){
1.151     albertel 2135: 			my ($oname,$odom,$ocrsid,$oessay,$osim)=
1.426     albertel 2136: 			    &most_similar($uname,$udom,$subval,\%old_essays);
1.151     albertel 2137: 			if ($osim) {
                   2138: 			    $osim=int($osim*100.0);
1.426     albertel 2139: 			    my %old_course_desc = 
                   2140: 				&Apache::lonnet::coursedescription($ocrsid,
                   2141: 								   {'one_time' => 1});
                   2142: 
1.596     raeburn  2143:                             if ($hide) {
                   2144:                                 $similar='<hr /><span class="LC_warning">'.&mt("Essay was found to be similar to another essay submitted for this assignment.").'<br />'.
                   2145:                                          &mt('As the current submission is for an anonymous survey, no other details are available.').'</span><hr />';
                   2146:                             } else {
                   2147: 			        $similar="<hr /><h3><span class=\"LC_warning\">".
                   2148: 				    &mt('Essay is [_1]% similar to an essay by [_2] in course [_3] (course id [_4]:[_5])',
                   2149: 				        $osim,
                   2150: 				        &Apache::loncommon::plainname($oname,$odom).' ('.$oname.':'.$odom.')',
                   2151: 				        $old_course_desc{'description'},
                   2152: 				        $old_course_desc{'num'},
                   2153: 				        $old_course_desc{'domain'}).
                   2154: 				    '</span></h3><blockquote><i>'.
                   2155: 				    &keywords_highlight($oessay).
                   2156: 				    '</i></blockquote><hr />';
                   2157:                             }
1.151     albertel 2158: 			}
1.150     albertel 2159: 		    }
1.151     albertel 2160: 		    my $order=&get_order($partid,$respid,$symb,$uname,$udom);
1.257     albertel 2161: 		    if ($env{'form.lastSub'} eq 'lastonly' || 
                   2162: 			($env{'form.lastSub'} eq 'hdgrade' && 
1.377     albertel 2163: 			 $$handgrade{$$part[0].'_'.$$part[1]} eq 'yes')) {
1.324     albertel 2164: 			my $display_part=&get_display_part($partid,$symb);
1.577     bisitz   2165:                         $lastsubonly.='<div class="LC_grade_submission_part">'.
                   2166:                             '<b>'.&mt('Part: [_1]',$display_part).'</b>'.
                   2167:                             ' <span class="LC_internal_info">'.
                   2168:                             '('.&mt('Part ID: [_1]',$respid).')'.
1.597     wenzelju 2169:                             '</span>&nbsp; &nbsp;';
1.313     banghart 2170: 			my $files=&get_submitted_files($udom,$uname,$partid,$respid,\%record);
                   2171: 			if (@$files) {
1.596     raeburn  2172:                             if ($hide) {
                   2173:                                 $lastsubonly.='<br />'.&mt('[quant,_1,file] uploaded to this anonymous survey',scalar(@{$files}));
                   2174:                             } else {
                   2175:                                 $lastsubonly.='<br /><span class="LC_warning">'.&mt('Like all files provided by users, this file may contain viruses').'</span><br />';
                   2176:                                 foreach my $file (@$files) {
                   2177:                                     &Apache::lonnet::allowuploaded('/adm/grades',$file);
                   2178:                                     $lastsubonly.='<br /><a href="'.$file.'?rawmode=1" target="lonGRDs"><img src="'.&Apache::loncommon::icon($file).'" border="0" /> '.$file.'</a>';
                   2179:                                 }
                   2180:                             }
1.236     albertel 2181: 			    $lastsubonly.='<br />';
1.41      ng       2182: 			}
1.596     raeburn  2183:                         if ($hide) {
                   2184:                             $lastsubonly.='<b>'.&mt('Anonymous Survey').'</b>'; 
                   2185:                         } else {
                   2186: 			    $lastsubonly.='<b>'.&mt('Submitted Answer:').' </b>'.
                   2187: 			        &cleanRecord($subval,$responsetype,$symb,$partid,
                   2188: 					     $respid,\%record,$order,undef,$uname,$udom);
                   2189:                         }
1.151     albertel 2190: 			if ($similar) {$lastsubonly.="<br /><br />$similar\n";}
1.468     albertel 2191: 			$lastsubonly.='</div>';
1.41      ng       2192: 		    }
                   2193: 		}
                   2194: 	    }
1.588     bisitz   2195: 	    $lastsubonly.='</div>'."\n"; # End: LC_grade_submissions_body
1.151     albertel 2196: 	}
                   2197: 	$request->print($lastsubonly);
1.468     albertel 2198:    } elsif ($env{'form.lastSub'} eq 'datesub') {
1.618   ! www      2199:         my ($parts,$handgrade,$responseType) = &response_type($symb);
1.148     albertel 2200: 	$request->print(&displaySubByDates($symb,\%record,$parts,$responseType,$checkIcon,$uname,$udom));
1.257     albertel 2201:     } elsif ($env{'form.lastSub'} =~ /^(last|all)$/) {
1.41      ng       2202: 	$request->print(&Apache::loncommon::get_previous_attempt($symb,$uname,$udom,
1.257     albertel 2203: 								 $env{'request.course.id'},
1.44      ng       2204: 								 $last,'.submission',
                   2205: 								 'Apache::grades::keywords_highlight'));
1.41      ng       2206:     }
1.120     ng       2207: 
1.121     ng       2208:     $request->print('<input type="hidden" name="unamedom'.$counter.'" value="'.$uname.':'
                   2209: 	.$udom.'" />'."\n");
1.44      ng       2210:     # return if view submission with no grading option
1.618   ! www      2211:     if (!&canmodify($usec)) {
1.120     ng       2212: 	my $toGrade.='<input type="button" value="Grade Student" '.
1.589     bisitz   2213: 	    'onclick="javascript:checksubmit(this.form,\'Grade Student\',\''
1.417     albertel 2214: 	    .$counter.'\');" target="_self" /> &nbsp;'."\n" if (&canmodify($usec));
1.468     albertel 2215: 	$toGrade.='</div>'."\n";
1.180     albertel 2216: 	$request->print($toGrade);
1.41      ng       2217: 	return;
1.180     albertel 2218:     } else {
1.468     albertel 2219: 	$request->print('</div>'."\n");
1.41      ng       2220:     }
1.33      ng       2221: 
1.121     ng       2222:     # essay grading message center
1.257     albertel 2223:     if ($env{'form.handgrade'} eq 'yes') {
1.468     albertel 2224: 	my $result='<div class="LC_grade_message_center">';
                   2225:     
                   2226: 	$result.='<div class="LC_grade_message_center_header">'.
                   2227: 	    &mt('Send Message').'</div><div class="LC_grade_message_center_body">';
1.257     albertel 2228: 	my ($lastname,$givenn) = split(/,/,$env{'form.fullname'});
1.118     ng       2229: 	my $msgfor = $givenn.' '.$lastname;
1.464     albertel 2230: 	if (scalar(@$col_fullnames) > 0) {
                   2231: 	    my $lastone = pop(@$col_fullnames);
                   2232: 	    $msgfor .= ', '.(join ', ',@$col_fullnames).' and '.$lastone.'.';
1.118     ng       2233: 	}
                   2234: 	$msgfor =~ s/\'/\\'/g; #' stupid emacs - no! javascript
1.468     albertel 2235: 	$result.='<input type="hidden" name="includemsg'.$counter.'" value="" />'."\n".
1.121     ng       2236: 	    '<input type="hidden" name="newmsg'.$counter.'" value="" />'."\n";
                   2237: 	$result.='&nbsp;<a href="javascript:msgCenter(document.SCORE,'.$counter.
1.417     albertel 2238: 	    ',\''.$msgfor.'\');" target="_self">'.
1.464     albertel 2239: 	    &mt('Compose message to student').(scalar(@$col_fullnames) >= 1 ? 's' : '').'</a><label> ('.
1.350     albertel 2240: 	    &mt('incl. grades').' <input type="checkbox" name="withgrades'.$counter.'" /></label>)'.
1.118     ng       2241: 	    '<img src="'.$request->dir_config('lonIconsURL').
                   2242: 	    '/mailbkgrd.gif" width="14" height="10" name="mailicon'.$counter.'" />'."\n".
1.298     www      2243: 	    '<br />&nbsp;('.
1.468     albertel 2244: 	    &mt('Message will be sent when you click on Save &amp; Next below.').")\n";
                   2245: 	$result.='</div></div>';
1.121     ng       2246: 	$request->print($result);
1.118     ng       2247:     }
1.41      ng       2248: 
                   2249:     my %seen = ();
                   2250:     my @partlist;
1.129     ng       2251:     my @gradePartRespid;
1.375     albertel 2252:     my @part_response_id = &flatten_responseType($responseType);
1.585     bisitz   2253:     $request->print(
1.588     bisitz   2254:         '<div class="LC_Box">'
                   2255:        .'<h3 class="LC_hcell">'.&mt('Assign Grades').'</h3>'
1.585     bisitz   2256:     );
1.592     bisitz   2257:     $request->print(&gradeBox_start());
1.375     albertel 2258:     foreach my $part_response_id (@part_response_id) {
                   2259:     	my ($partid,$respid) = @{ $part_response_id };
                   2260: 	my $part_resp = join('_',@{ $part_response_id });
1.322     albertel 2261: 	next if ($seen{$partid} > 0);
1.41      ng       2262: 	$seen{$partid}++;
1.393     albertel 2263: 	next if ($$handgrade{$part_resp} ne 'yes' 
                   2264: 		 && $env{'form.lastSub'} eq 'hdgrade');
1.524     raeburn  2265: 	push(@partlist,$partid);
                   2266: 	push(@gradePartRespid,$partid.'.'.$respid);
1.322     albertel 2267: 	$request->print(&gradeBox($request,$symb,$uname,$udom,$counter,$partid,\%record));
1.41      ng       2268:     }
1.585     bisitz   2269:     $request->print(&gradeBox_end()); # </div>
                   2270:     $request->print('</div>');
1.468     albertel 2271: 
                   2272:     $request->print('<div class="LC_grade_info_links">');
                   2273:     $request->print('</div>');
                   2274: 
1.45      ng       2275:     $result='<input type="hidden" name="partlist'.$counter.
                   2276: 	'" value="'.(join ":",@partlist).'" />'."\n";
1.129     ng       2277:     $result.='<input type="hidden" name="gradePartRespid'.
                   2278: 	'" value="'.(join ":",@gradePartRespid).'" />'."\n" if ($counter == 0);
1.45      ng       2279:     my $ctr = 0;
                   2280:     while ($ctr < scalar(@partlist)) {
                   2281: 	$result.='<input type="hidden" name="partid'.$counter.'_'.$ctr.'" value="'.
                   2282: 	    $partlist[$ctr].'" />'."\n";
                   2283: 	$ctr++;
                   2284:     }
1.468     albertel 2285:     $request->print($result.''."\n");
1.41      ng       2286: 
1.441     www      2287: # Done with printing info for one student
                   2288: 
1.468     albertel 2289:     $request->print('</div>');#LC_grade_show_user
1.441     www      2290: 
                   2291: 
1.41      ng       2292:     # print end of form
                   2293:     if ($counter == $total) {
1.592     bisitz   2294:         my $endform='<br /><hr /><table border="0"><tr><td>'."\n";
1.485     albertel 2295: 	$endform.='<input type="button" value="'.&mt('Save &amp; Next').'" '.
1.589     bisitz   2296: 	    'onclick="javascript:checksubmit(this.form,\'Save & Next\','.
1.417     albertel 2297: 	    $total.','.scalar(@partlist).');" target="_self" /> &nbsp;'."\n";
1.119     ng       2298: 	my $ntstu ='<select name="NTSTU">'.
                   2299: 	    '<option>1</option><option>2</option>'.
                   2300: 	    '<option>3</option><option>5</option>'.
                   2301: 	    '<option>7</option><option>10</option></select>'."\n";
1.257     albertel 2302: 	my $nsel = ($env{'form.NTSTU'} ne '' ? $env{'form.NTSTU'} : '1');
1.401     albertel 2303: 	$ntstu =~ s/<option>$nsel</<option selected="selected">$nsel</;
1.578     raeburn  2304:         $endform.=&mt('[_1]student(s)',$ntstu);
1.485     albertel 2305: 	$endform.='&nbsp;&nbsp;<input type="button" value="'.&mt('Previous').'" '.
1.589     bisitz   2306: 	    'onclick="javascript:checksubmit(this.form,\'Previous\');" target="_self" /> &nbsp;'."\n".
1.485     albertel 2307: 	    '<input type="button" value="'.&mt('Next').'" '.
1.589     bisitz   2308: 	    'onclick="javascript:checksubmit(this.form,\'Next\');" target="_self" /> &nbsp;';
1.592     bisitz   2309:         $endform.='<span class="LC_warning">'.
                   2310:                   &mt('(Next and Previous (student) do not save the scores.)').
                   2311:                   '</span>'."\n" ;
1.349     albertel 2312:         $endform.="<input type='hidden' value='".&get_increment().
1.348     bowersj2 2313:             "' name='increment' />";
1.485     albertel 2314: 	$endform.='</td></tr></table></form>';
1.41      ng       2315: 	$request->print($endform);
                   2316:     }
                   2317:     return '';
1.38      ng       2318: }
                   2319: 
1.464     albertel 2320: sub check_collaborators {
                   2321:     my ($symb,$uname,$udom,$record,$handgrade,$counter) = @_;
                   2322:     my ($result,@col_fullnames);
                   2323:     my ($classlist,undef,$fullname) = &getclasslist('all','0');
                   2324:     foreach my $part (keys(%$handgrade)) {
                   2325: 	my $ncol = &Apache::lonnet::EXT('resource.'.$part.
                   2326: 					'.maxcollaborators',
                   2327: 					$symb,$udom,$uname);
                   2328: 	next if ($ncol <= 0);
                   2329: 	$part =~ s/\_/\./g;
                   2330: 	next if ($record->{'resource.'.$part.'.collaborators'} eq '');
                   2331: 	my (@good_collaborators, @bad_collaborators);
                   2332: 	foreach my $possible_collaborator
                   2333: 	    (split(/,?\s+/,$record->{'resource.'.$part.'.collaborators'})) { 
                   2334: 	    $possible_collaborator =~ s/[\$\^\(\)]//g;
                   2335: 	    next if ($possible_collaborator eq '');
                   2336: 	    my ($co_name,$co_dom) = split(/\@|:/,$possible_collaborator);
                   2337: 	    $co_dom = $udom if (! defined($co_dom) || $co_dom =~ /^domain$/i);
                   2338: 	    next if ($co_name eq $uname && $co_dom eq $udom);
                   2339: 	    # Doing this grep allows 'fuzzy' specification
                   2340: 	    my @matches = grep(/^\Q$co_name\E:\Q$co_dom\E$/i, 
                   2341: 			       keys(%$classlist));
                   2342: 	    if (! scalar(@matches)) {
                   2343: 		push(@bad_collaborators, $possible_collaborator);
                   2344: 	    } else {
                   2345: 		push(@good_collaborators, @matches);
                   2346: 	    }
                   2347: 	}
                   2348: 	if (scalar(@good_collaborators) != 0) {
1.466     albertel 2349: 	    $result.='<br />'.&mt('Collaborators: ');
1.464     albertel 2350: 	    foreach my $name (@good_collaborators) {
                   2351: 		my ($lastname,$givenn) = split(/,/,$$fullname{$name});
                   2352: 		push(@col_fullnames, $givenn.' '.$lastname);
                   2353: 		$result.=$fullname->{$name}.'&nbsp; &nbsp; &nbsp;';
                   2354: 	    }
                   2355: 	    $result.='<br />'."\n";
1.466     albertel 2356: 	    my ($part)=split(/\./,$part);
1.464     albertel 2357: 	    $result.='<input type="hidden" name="collaborator'.$counter.
                   2358: 		'" value="'.$part.':'.(join ':',@good_collaborators).'" />'.
                   2359: 		"\n";
                   2360: 	}
                   2361: 	if (scalar(@bad_collaborators) > 0) {
1.466     albertel 2362: 	    $result.='<div class="LC_warning">';
1.464     albertel 2363: 	    $result.=&mt('This student has submitted [quant,_1,invalid collaborator]: [_2]',scalar(@bad_collaborators),join(', ',@bad_collaborators));
                   2364: 	    $result .= '</div>';
                   2365: 	}         
                   2366: 	if (scalar(@bad_collaborators > $ncol)) {
1.466     albertel 2367: 	    $result .= '<div class="LC_warning">';
1.464     albertel 2368: 	    $result .= &mt('This student has submitted too many '.
                   2369: 		'collaborators.  Maximum is [_1].',$ncol);
                   2370: 	    $result .= '</div>';
                   2371: 	}
                   2372:     }
                   2373:     return ($result,$fullname,\@col_fullnames);
                   2374: }
                   2375: 
1.44      ng       2376: #--- Retrieve the last submission for all the parts
1.38      ng       2377: sub get_last_submission {
1.119     ng       2378:     my ($returnhash)=@_;
1.596     raeburn  2379:     my (@string,$timestamp,%lasthidden);
1.119     ng       2380:     if ($$returnhash{'version'}) {
1.46      ng       2381: 	my %lasthash=();
                   2382: 	my ($version);
1.119     ng       2383: 	for ($version=1;$version<=$$returnhash{'version'};$version++) {
1.397     albertel 2384: 	    foreach my $key (sort(split(/\:/,
                   2385: 					$$returnhash{$version.':keys'}))) {
                   2386: 		$lasthash{$key}=$$returnhash{$version.':'.$key};
                   2387: 		$timestamp = 
1.545     raeburn  2388: 		    &Apache::lonlocal::locallocaltime($$returnhash{$version.':timestamp'});
1.46      ng       2389: 	    }
                   2390: 	}
1.596     raeburn  2391:         my %typeparts;
                   2392:         my $showsurv = 
                   2393:             &Apache::lonnet::allowed('vas',$env{'request.course.id'});
                   2394:         foreach my $key (sort(keys(%lasthash))) {
                   2395:             if ($key =~ /\.type$/) {
                   2396:                 if (($lasthash{$key} eq 'anonsurvey') || 
                   2397:                     ($lasthash{$key} eq 'anonsurveycred')) {
                   2398:                     my ($ign,@parts) = split(/\./,$key);
                   2399:                     pop(@parts);
                   2400:                     unless ($showsurv) {
                   2401:                         my $id = join(',',@parts);
                   2402:                         $typeparts{$ign.'.'.$id} = $lasthash{$key};
                   2403:                     }
                   2404:                     delete($lasthash{$key});
                   2405:                 }
                   2406:             }
                   2407:         }
                   2408:         my @hidden = keys(%typeparts);
1.397     albertel 2409: 	foreach my $key (keys(%lasthash)) {
                   2410: 	    next if ($key !~ /\.submission$/);
1.596     raeburn  2411:             my $hide;
                   2412:             if (@hidden) {
                   2413:                 foreach my $id (@hidden) {
                   2414:                     if ($key =~ /^\Q$id\E/) {
                   2415:                         $hide = 1;
                   2416:                         last;
                   2417:                     }
                   2418:                 }
                   2419:             }
1.397     albertel 2420: 	    my ($partid,$foo) = split(/submission$/,$key);
                   2421: 	    my $draft  = $lasthash{$partid.'awarddetail'} eq 'DRAFT' ?
1.398     albertel 2422: 		'<span class="LC_warning">Draft Copy</span> ' : '';
1.596     raeburn  2423: 	    push(@string, join(':', $key, $hide, $draft.$lasthash{$key}));
1.41      ng       2424: 	}
                   2425:     }
1.397     albertel 2426:     if (!@string) {
                   2427: 	$string[0] =
1.539     riegler  2428: 	    '<span class="LC_warning">'.&mt('Nothing submitted - no attempts.').'</span>';
1.397     albertel 2429:     }
                   2430:     return (\@string,\$timestamp);
1.38      ng       2431: }
1.35      ng       2432: 
1.44      ng       2433: #--- High light keywords, with style choosen by user.
1.38      ng       2434: sub keywords_highlight {
1.44      ng       2435:     my $string    = shift;
1.257     albertel 2436:     my $size      = $env{'form.kwsize'} eq '0' ? '' : 'size='.$env{'form.kwsize'};
                   2437:     my $styleon   = $env{'form.kwstyle'} eq ''  ? '' : $env{'form.kwstyle'};
1.41      ng       2438:     (my $styleoff = $styleon) =~ s/\</\<\//;
1.257     albertel 2439:     my @keylist   = split(/[,\s+]/,$env{'form.keywords'});
1.398     albertel 2440:     foreach my $keyword (@keylist) {
                   2441: 	$string =~ s/\b\Q$keyword\E(\b|\.)/<font color\=$env{'form.kwclr'} $size\>$styleon$keyword$styleoff<\/font>/gi;
1.41      ng       2442:     }
                   2443:     return $string;
1.38      ng       2444: }
1.36      ng       2445: 
1.44      ng       2446: #--- Called from submission routine
1.38      ng       2447: sub processHandGrade {
1.608     www      2448:     my ($request,$symb) = @_;
1.324     albertel 2449:     my (undef,undef,$url) = &Apache::lonnet::decode_symb($symb);
1.257     albertel 2450:     my $button = $env{'form.gradeOpt'};
                   2451:     my $ngrade = $env{'form.NCT'};
                   2452:     my $ntstu  = $env{'form.NTSTU'};
1.301     albertel 2453:     my $cdom   = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   2454:     my $cnum   = $env{'course.'.$env{'request.course.id'}.'.num'};
                   2455: 
1.44      ng       2456:     if ($button eq 'Save & Next') {
                   2457: 	my $ctr = 0;
                   2458: 	while ($ctr < $ngrade) {
1.257     albertel 2459: 	    my ($uname,$udom) = split(/:/,$env{'form.unamedom'.$ctr});
1.324     albertel 2460: 	    my ($errorflag,$pts,$wgt) = &saveHandGrade($request,$symb,$uname,$udom,$ctr);
1.71      ng       2461: 	    if ($errorflag eq 'no_score') {
                   2462: 		$ctr++;
                   2463: 		next;
                   2464: 	    }
1.104     albertel 2465: 	    if ($errorflag eq 'not_allowed') {
1.398     albertel 2466: 		$request->print("<span class=\"LC_warning\">Not allowed to modify grades for $uname:$udom</span>");
1.104     albertel 2467: 		$ctr++;
                   2468: 		next;
                   2469: 	    }
1.257     albertel 2470: 	    my $includemsg = $env{'form.includemsg'.$ctr};
1.44      ng       2471: 	    my ($subject,$message,$msgstatus) = ('','','');
1.418     albertel 2472: 	    my $restitle = &Apache::lonnet::gettitle($symb);
                   2473:             my ($feedurl,$showsymb) =
                   2474: 		&get_feedurl_and_symb($symb,$uname,$udom);
                   2475: 	    my $messagetail;
1.62      albertel 2476: 	    if ($includemsg =~ /savemsg|newmsg\Q$ctr\E/) {
1.298     www      2477: 		$subject = $env{'form.msgsub'} if ($includemsg =~ /msgsub/);
1.295     www      2478: 		unless ($subject=~/\w/) { $subject=&mt('Grading Feedback'); }
1.386     raeburn  2479: 		$subject.=' ['.$restitle.']';
1.44      ng       2480: 		my (@msgnum) = split(/,/,$includemsg);
                   2481: 		foreach (@msgnum) {
1.257     albertel 2482: 		    $message.=$env{'form.'.$_} if ($_ =~ /savemsg|newmsg/ && $_ ne '');
1.44      ng       2483: 		}
1.80      ng       2484: 		$message =&Apache::lonfeedback::clear_out_html($message);
1.298     www      2485: 		if ($env{'form.withgrades'.$ctr}) {
                   2486: 		    $message.="\n\nPoint".($pts > 1 ? 's':'').' awarded = '.$pts.' out of '.$wgt;
1.386     raeburn  2487: 		    $messagetail = " for <a href=\"".
1.605     www      2488: 		                   $feedurl."?symb=$showsymb\">$restitle</a>";
1.386     raeburn  2489: 		}
                   2490: 		$msgstatus = 
                   2491:                     &Apache::lonmsg::user_normal_msg($uname,$udom,$subject,
                   2492: 						     $message.$messagetail,
1.418     albertel 2493:                                                      undef,$feedurl,undef,
1.386     raeburn  2494:                                                      undef,undef,$showsymb,
                   2495:                                                      $restitle);
1.574     bisitz   2496: 		$request->print('<br />'.&mt('Sending message to [_1]',$uname.':'.$udom).': '.
1.296     www      2497: 				$msgstatus);
1.44      ng       2498: 	    }
1.257     albertel 2499: 	    if ($env{'form.collaborator'.$ctr}) {
1.155     albertel 2500: 		my @collabstrs=&Apache::loncommon::get_env_multiple("form.collaborator$ctr");
1.150     albertel 2501: 		foreach my $collabstr (@collabstrs) {
                   2502: 		    my ($part,@collaborators) = split(/:/,$collabstr);
1.310     banghart 2503: 		    foreach my $collaborator (@collaborators) {
1.150     albertel 2504: 			my ($errorflag,$pts,$wgt) = 
1.324     albertel 2505: 			    &saveHandGrade($request,$symb,$collaborator,$udom,$ctr,
1.257     albertel 2506: 					   $env{'form.unamedom'.$ctr},$part);
1.150     albertel 2507: 			if ($errorflag eq 'not_allowed') {
1.362     albertel 2508: 			    $request->print("<span class=\"LC_error\">".&mt('Not allowed to modify grades for [_1]',"$collaborator:$udom")."</span>");
1.150     albertel 2509: 			    next;
1.418     albertel 2510: 			} elsif ($message ne '') {
                   2511: 			    my ($baseurl,$showsymb) = 
                   2512: 				&get_feedurl_and_symb($symb,$collaborator,
                   2513: 						      $udom);
                   2514: 			    if ($env{'form.withgrades'.$ctr}) {
                   2515: 				$messagetail = " for <a href=\"".
1.605     www      2516:                                     $baseurl."?symb=$showsymb\">$restitle</a>";
1.150     albertel 2517: 			    }
1.418     albertel 2518: 			    $msgstatus = 
                   2519: 				&Apache::lonmsg::user_normal_msg($collaborator,$udom,$subject,$message.$messagetail,undef,$baseurl,undef,undef,undef,$showsymb,$restitle);
1.104     albertel 2520: 			}
1.44      ng       2521: 		    }
                   2522: 		}
                   2523: 	    }
                   2524: 	    $ctr++;
                   2525: 	}
                   2526:     }
                   2527: 
1.257     albertel 2528:     if ($env{'form.handgrade'} eq 'yes') {
1.119     ng       2529: 	# Keywords sorted in alphabatical order
1.257     albertel 2530: 	my $loginuser = $env{'user.name'}.':'.$env{'user.domain'};
1.119     ng       2531: 	my %keyhash = ();
1.257     albertel 2532: 	$env{'form.keywords'}           =~ s/,\s{0,}|\s+/ /g;
                   2533: 	$env{'form.keywords'}           =~ s/^\s+|\s+$//;
                   2534: 	my (@keywords) = sort(split(/\s+/,$env{'form.keywords'}));
                   2535: 	$env{'form.keywords'} = join(' ',@keywords);
                   2536: 	$keyhash{$symb.'_keywords'}     = $env{'form.keywords'};
                   2537: 	$keyhash{$symb.'_subject'}      = $env{'form.msgsub'};
                   2538: 	$keyhash{$loginuser.'_kwclr'}   = $env{'form.kwclr'};
                   2539: 	$keyhash{$loginuser.'_kwsize'}  = $env{'form.kwsize'};
                   2540: 	$keyhash{$loginuser.'_kwstyle'} = $env{'form.kwstyle'};
1.119     ng       2541: 
                   2542: 	# message center - Order of message gets changed. Blank line is eliminated.
1.257     albertel 2543: 	# New messages are saved in env for the next student.
1.119     ng       2544: 	# All messages are saved in nohist_handgrade.db
                   2545: 	my ($ctr,$idx) = (1,1);
1.257     albertel 2546: 	while ($ctr <= $env{'form.savemsgN'}) {
                   2547: 	    if ($env{'form.savemsg'.$ctr} ne '') {
                   2548: 		$keyhash{$symb.'_savemsg'.$idx} = $env{'form.savemsg'.$ctr};
1.119     ng       2549: 		$idx++;
                   2550: 	    }
                   2551: 	    $ctr++;
1.41      ng       2552: 	}
1.119     ng       2553: 	$ctr = 0;
                   2554: 	while ($ctr < $ngrade) {
1.257     albertel 2555: 	    if ($env{'form.newmsg'.$ctr} ne '') {
                   2556: 		$keyhash{$symb.'_savemsg'.$idx} = $env{'form.newmsg'.$ctr};
                   2557: 		$env{'form.savemsg'.$idx} = $env{'form.newmsg'.$ctr};
1.119     ng       2558: 		$idx++;
                   2559: 	    }
                   2560: 	    $ctr++;
1.41      ng       2561: 	}
1.257     albertel 2562: 	$env{'form.savemsgN'} = --$idx;
                   2563: 	$keyhash{$symb.'_savemsgN'} = $env{'form.savemsgN'};
1.119     ng       2564: 	my $putresult = &Apache::lonnet::put
1.301     albertel 2565: 	    ('nohist_handgrade',\%keyhash,$cdom,$cnum);
1.41      ng       2566:     }
1.44      ng       2567:     # Called by Save & Refresh from Highlight Attribute Window
1.257     albertel 2568:     my (undef,undef,$fullname) = &getclasslist($env{'form.section'},'1');
                   2569:     if ($env{'form.refresh'} eq 'on') {
1.86      ng       2570: 	my ($ctr,$total) = (0,0);
                   2571: 	while ($ctr < $ngrade) {
1.257     albertel 2572: 	    $total++ if  $env{'form.unamedom'.$ctr} ne '';
1.86      ng       2573: 	    $ctr++;
                   2574: 	}
1.257     albertel 2575: 	$env{'form.NTSTU'}=$ngrade;
1.86      ng       2576: 	$ctr = 0;
                   2577: 	while ($ctr < $total) {
1.257     albertel 2578: 	    my $processUser = $env{'form.unamedom'.$ctr};
                   2579: 	    ($env{'form.student'},$env{'form.userdom'}) = split(/:/,$processUser);
                   2580: 	    $env{'form.fullname'} = $$fullname{$processUser};
1.86      ng       2581: 	    &submission($request,$ctr,$total-1);
1.41      ng       2582: 	    $ctr++;
                   2583: 	}
                   2584: 	return '';
                   2585:     }
1.36      ng       2586: 
1.121     ng       2587: # Go directly to grade student - from submission or link from chart page
1.120     ng       2588:     if ($button eq 'Grade Student') {
1.598     www      2589: #	(undef,undef,$env{'form.handgrade'},undef,undef) = &showResourceInfo($symb);
1.257     albertel 2590: 	my $processUser = $env{'form.unamedom'.$env{'form.studentNo'}};
                   2591: 	($env{'form.student'},$env{'form.userdom'}) = split(/:/,$processUser);
                   2592: 	$env{'form.fullname'} = $$fullname{$processUser};
1.120     ng       2593: 	&submission($request,0,0);
                   2594: 	return '';
                   2595:     }
                   2596: 
1.44      ng       2597:     # Get the next/previous one or group of students
1.257     albertel 2598:     my $firststu = $env{'form.unamedom0'};
                   2599:     my $laststu = $env{'form.unamedom'.($ngrade-1)};
1.119     ng       2600:     my $ctr = 2;
1.41      ng       2601:     while ($laststu eq '') {
1.257     albertel 2602: 	$laststu  = $env{'form.unamedom'.($ngrade-$ctr)};
1.41      ng       2603: 	$ctr++;
                   2604: 	$laststu = $firststu if ($ctr > $ngrade);
                   2605:     }
1.44      ng       2606: 
1.41      ng       2607:     my (@parsedlist,@nextlist);
                   2608:     my ($nextflg) = 0;
1.524     raeburn  2609:     foreach my $item (sort 
1.294     albertel 2610: 	     {
                   2611: 		 if (lc($$fullname{$a}) ne lc($$fullname{$b})) {
                   2612: 		     return (lc($$fullname{$a}) cmp lc($$fullname{$b}));
                   2613: 		 }
                   2614: 		 return $a cmp $b;
                   2615: 	     } (keys(%$fullname))) {
1.605     www      2616: # FIXME: this is fishy, looks like the button label
1.41      ng       2617: 	if ($nextflg == 1 && $button =~ /Next$/) {
1.524     raeburn  2618: 	    push(@parsedlist,$item);
1.41      ng       2619: 	}
1.524     raeburn  2620: 	$nextflg = 1 if ($item eq $laststu);
1.41      ng       2621: 	if ($button eq 'Previous') {
1.524     raeburn  2622: 	    last if ($item eq $firststu);
                   2623: 	    push(@parsedlist,$item);
1.41      ng       2624: 	}
                   2625:     }
                   2626:     $ctr = 0;
1.605     www      2627: # FIXME: this is fishy, looks like the button label
1.41      ng       2628:     @parsedlist = reverse @parsedlist if ($button eq 'Previous');
1.582     raeburn  2629:     my $res_error;
                   2630:     my ($partlist) = &response_type($symb,\$res_error);
                   2631:     if ($res_error) {
                   2632:         $request->print(&navmap_errormsg());
                   2633:         return;
                   2634:     }
1.41      ng       2635:     foreach my $student (@parsedlist) {
1.257     albertel 2636: 	my $submitonly=$env{'form.submitonly'};
1.41      ng       2637: 	my ($uname,$udom) = split(/:/,$student);
1.301     albertel 2638: 	
                   2639: 	if ($submitonly eq 'queued') {
                   2640: 	    my %queue_status = 
                   2641: 		&Apache::bridgetask::get_student_status($symb,$cdom,$cnum,
                   2642: 							$udom,$uname);
                   2643: 	    next if (!defined($queue_status{'gradingqueue'}));
                   2644: 	}
                   2645: 
1.156     albertel 2646: 	if ($submitonly =~ /^(yes|graded|incorrect)$/) {
1.257     albertel 2647: #	    my %record = &Apache::lonnet::restore($symb,$env{'request.course.id'},$udom,$uname);
1.324     albertel 2648: 	    my %status=&student_gradeStatus($symb,$udom,$uname,$partlist);
1.145     albertel 2649: 	    my $submitted = 0;
1.248     albertel 2650: 	    my $ungraded = 0;
                   2651: 	    my $incorrect = 0;
1.524     raeburn  2652: 	    foreach my $item (keys(%status)) {
                   2653: 		$submitted = 1 if ($status{$item} ne 'nothing');
                   2654: 		$ungraded = 1 if ($status{$item} =~ /^ungraded/);
                   2655: 		$incorrect = 1 if ($status{$item} =~ /^incorrect/);
                   2656: 		my ($foo,$partid,$foo1) = split(/\./,$item);
1.145     albertel 2657: 		if ($status{'resource.'.$partid.'.submitted_by'} ne '') {
                   2658: 		    $submitted = 0;
                   2659: 		}
1.41      ng       2660: 	    }
1.156     albertel 2661: 	    next if (!$submitted && ($submitonly eq 'yes' ||
                   2662: 				     $submitonly eq 'incorrect' ||
                   2663: 				     $submitonly eq 'graded'));
1.248     albertel 2664: 	    next if (!$ungraded && ($submitonly eq 'graded'));
                   2665: 	    next if (!$incorrect && $submitonly eq 'incorrect');
1.41      ng       2666: 	}
1.524     raeburn  2667: 	push(@nextlist,$student) if ($ctr < $ntstu);
1.129     ng       2668: 	last if ($ctr == $ntstu);
1.41      ng       2669: 	$ctr++;
                   2670:     }
1.36      ng       2671: 
1.41      ng       2672:     $ctr = 0;
                   2673:     my $total = scalar(@nextlist)-1;
1.39      ng       2674: 
1.524     raeburn  2675:     foreach (sort(@nextlist)) {
1.41      ng       2676: 	my ($uname,$udom,$submitter) = split(/:/);
1.257     albertel 2677: 	$env{'form.student'}  = $uname;
                   2678: 	$env{'form.userdom'}  = $udom;
                   2679: 	$env{'form.fullname'} = $$fullname{$_};
1.41      ng       2680: 	&submission($request,$ctr,$total);
                   2681: 	$ctr++;
                   2682:     }
                   2683:     if ($total < 0) {
1.485     albertel 2684: 	my $the_end = '<h3><span class="LC_info">'.&mt('LON-CAPA User Message').'</span></h3><br />'."\n";
                   2685: 	$the_end.=&mt('<b>Message: </b> No more students for this section or class.').'<br /><br />'."\n";
                   2686: 	$the_end.=&mt('Click on the button below to return to the grading menu.').'<br /><br />'."\n";
1.41      ng       2687: 	$request->print($the_end);
                   2688:     }
                   2689:     return '';
1.38      ng       2690: }
1.36      ng       2691: 
1.44      ng       2692: #---- Save the score and award for each student, if changed
1.38      ng       2693: sub saveHandGrade {
1.324     albertel 2694:     my ($request,$symb,$stuname,$domain,$newflg,$submitter,$part) = @_;
1.342     banghart 2695:     my @version_parts;
1.104     albertel 2696:     my $usec = &Apache::lonnet::getsection($domain,$stuname,
1.257     albertel 2697: 					   $env{'request.course.id'});
1.104     albertel 2698:     if (!&canmodify($usec)) { return('not_allowed'); }
1.337     banghart 2699:     my %record = &Apache::lonnet::restore($symb,$env{'request.course.id'},$domain,$stuname);
1.251     banghart 2700:     my @parts_graded;
1.77      ng       2701:     my %newrecord  = ();
                   2702:     my ($pts,$wgt) = ('','');
1.269     raeburn  2703:     my %aggregate = ();
                   2704:     my $aggregateflag = 0;
1.301     albertel 2705:     my @parts = split(/:/,$env{'form.partlist'.$newflg});
                   2706:     foreach my $new_part (@parts) {
1.337     banghart 2707: 	#collaborator ($submi may vary for different parts
1.259     banghart 2708: 	if ($submitter && $new_part ne $part) { next; }
                   2709: 	my $dropMenu = $env{'form.GD_SEL'.$newflg.'_'.$new_part};
1.125     ng       2710: 	if ($dropMenu eq 'excused') {
1.259     banghart 2711: 	    if ($record{'resource.'.$new_part.'.solved'} ne 'excused') {
                   2712: 		$newrecord{'resource.'.$new_part.'.solved'} = 'excused';
                   2713: 		if (exists($record{'resource.'.$new_part.'.awarded'})) {
                   2714: 		    $newrecord{'resource.'.$new_part.'.awarded'} = '';
1.58      albertel 2715: 		}
1.364     banghart 2716: 	        $newrecord{'resource.'.$new_part.'.regrader'}="$env{'user.name'}:$env{'user.domain'}";
1.58      albertel 2717: 	    }
1.125     ng       2718: 	} elsif ($dropMenu eq 'reset status'
1.259     banghart 2719: 		 && exists($record{'resource.'.$new_part.'.solved'})) { #don't bother if no old records -> no attempts
1.524     raeburn  2720: 	    foreach my $key (keys(%record)) {
1.259     banghart 2721: 		if ($key=~/^resource\.\Q$new_part\E\./) { $newrecord{$key} = ''; }
1.197     albertel 2722: 	    }
1.259     banghart 2723: 	    $newrecord{'resource.'.$new_part.'.regrader'}=
1.257     albertel 2724: 		"$env{'user.name'}:$env{'user.domain'}";
1.270     albertel 2725:             my $totaltries = $record{'resource.'.$part.'.tries'};
                   2726: 
                   2727:             my %last_resets = &get_last_resets($symb,$env{'request.course.id'},
                   2728: 					       [$new_part]);
                   2729:             my $aggtries =$totaltries;
1.269     raeburn  2730:             if ($last_resets{$new_part}) {
1.270     albertel 2731:                 $aggtries = &get_num_tries(\%record,$last_resets{$new_part},
                   2732: 					   $new_part);
1.269     raeburn  2733:             }
1.270     albertel 2734: 
                   2735:             my $solvedstatus = $record{'resource.'.$new_part.'.solved'};
1.269     raeburn  2736:             if ($aggtries > 0) {
1.327     albertel 2737:                 &decrement_aggs($symb,$new_part,\%aggregate,$aggtries,$totaltries,$solvedstatus);
1.269     raeburn  2738:                 $aggregateflag = 1;
                   2739:             }
1.125     ng       2740: 	} elsif ($dropMenu eq '') {
1.259     banghart 2741: 	    $pts = ($env{'form.GD_BOX'.$newflg.'_'.$new_part} ne '' ? 
                   2742: 		    $env{'form.GD_BOX'.$newflg.'_'.$new_part} : 
                   2743: 		    $env{'form.RADVAL'.$newflg.'_'.$new_part});
                   2744: 	    if ($pts eq '' && $env{'form.GD_SEL'.$newflg.'_'.$new_part} eq '') {
1.153     albertel 2745: 		next;
                   2746: 	    }
1.259     banghart 2747: 	    $wgt = $env{'form.WGT'.$newflg.'_'.$new_part} eq '' ? 1 : 
                   2748: 		$env{'form.WGT'.$newflg.'_'.$new_part};
1.41      ng       2749: 	    my $partial= $pts/$wgt;
1.259     banghart 2750: 	    if ($partial eq $record{'resource.'.$new_part.'.awarded'}) {
1.153     albertel 2751: 		#do not update score for part if not changed.
1.346     banghart 2752:                 &handback_files($request,$symb,$stuname,$domain,$newflg,$new_part,\%newrecord);
1.153     albertel 2753: 		next;
1.251     banghart 2754: 	    } else {
1.524     raeburn  2755: 	        push(@parts_graded,$new_part);
1.153     albertel 2756: 	    }
1.259     banghart 2757: 	    if ($record{'resource.'.$new_part.'.awarded'} ne $partial) {
                   2758: 		$newrecord{'resource.'.$new_part.'.awarded'}  = $partial;
1.153     albertel 2759: 	    }
1.259     banghart 2760: 	    my $reckey = 'resource.'.$new_part.'.solved';
1.41      ng       2761: 	    if ($partial == 0) {
1.153     albertel 2762: 		if ($record{$reckey} ne 'incorrect_by_override') {
                   2763: 		    $newrecord{$reckey} = 'incorrect_by_override';
                   2764: 		}
1.41      ng       2765: 	    } else {
1.153     albertel 2766: 		if ($record{$reckey} ne 'correct_by_override') {
                   2767: 		    $newrecord{$reckey} = 'correct_by_override';
                   2768: 		}
                   2769: 	    }	    
                   2770: 	    if ($submitter && 
1.259     banghart 2771: 		($record{'resource.'.$new_part.'.submitted_by'} ne $submitter)) {
                   2772: 		$newrecord{'resource.'.$new_part.'.submitted_by'} = $submitter;
1.41      ng       2773: 	    }
1.259     banghart 2774: 	    $newrecord{'resource.'.$new_part.'.regrader'}=
1.257     albertel 2775: 		"$env{'user.name'}:$env{'user.domain'}";
1.41      ng       2776: 	}
1.259     banghart 2777: 	# unless problem has been graded, set flag to version the submitted files
1.305     banghart 2778: 	unless ($record{'resource.'.$new_part.'.solved'} =~ /^correct_/  || 
                   2779: 	        $record{'resource.'.$new_part.'.solved'} eq 'incorrect_by_override' ||
                   2780: 	        $dropMenu eq 'reset status')
                   2781: 	   {
1.524     raeburn  2782: 	    push(@version_parts,$new_part);
1.259     banghart 2783: 	}
1.41      ng       2784:     }
1.301     albertel 2785:     my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   2786:     my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   2787: 
1.344     albertel 2788:     if (%newrecord) {
                   2789:         if (@version_parts) {
1.364     banghart 2790:             my @changed_keys = &version_portfiles(\%record, \@parts_graded, 
                   2791:                                 $env{'request.course.id'}, $symb, $domain, $stuname, \@version_parts);
1.344     albertel 2792: 	    @newrecord{@changed_keys} = @record{@changed_keys};
1.367     albertel 2793: 	    foreach my $new_part (@version_parts) {
                   2794: 		&handback_files($request,$symb,$stuname,$domain,$newflg,
                   2795: 				$new_part,\%newrecord);
                   2796: 	    }
1.259     banghart 2797:         }
1.44      ng       2798: 	&Apache::lonnet::cstore(\%newrecord,$symb,
1.257     albertel 2799: 				$env{'request.course.id'},$domain,$stuname);
1.380     albertel 2800: 	&check_and_remove_from_queue(\@parts,\%record,\%newrecord,$symb,
                   2801: 				     $cdom,$cnum,$domain,$stuname);
1.41      ng       2802:     }
1.269     raeburn  2803:     if ($aggregateflag) {
                   2804:         &Apache::lonnet::cinc('nohist_resourcetracker',\%aggregate,
1.301     albertel 2805: 			      $cdom,$cnum);
1.269     raeburn  2806:     }
1.301     albertel 2807:     return ('',$pts,$wgt);
1.36      ng       2808: }
1.322     albertel 2809: 
1.380     albertel 2810: sub check_and_remove_from_queue {
                   2811:     my ($parts,$record,$newrecord,$symb,$cdom,$cnum,$domain,$stuname) = @_;
                   2812:     my @ungraded_parts;
                   2813:     foreach my $part (@{$parts}) {
                   2814: 	if (    $record->{   'resource.'.$part.'.awarded'} eq ''
                   2815: 	     && $record->{   'resource.'.$part.'.solved' } ne 'excused'
                   2816: 	     && $newrecord->{'resource.'.$part.'.awarded'} eq ''
                   2817: 	     && $newrecord->{'resource.'.$part.'.solved' } ne 'excused'
                   2818: 		) {
                   2819: 	    push(@ungraded_parts, $part);
                   2820: 	}
                   2821:     }
                   2822:     if ( !@ungraded_parts ) {
                   2823: 	&Apache::bridgetask::remove_from_queue('gradingqueue',$symb,$cdom,
                   2824: 					       $cnum,$domain,$stuname);
                   2825:     }
                   2826: }
                   2827: 
1.337     banghart 2828: sub handback_files {
                   2829:     my ($request,$symb,$stuname,$domain,$newflg,$new_part,$newrecord) = @_;
1.517     raeburn  2830:     my $portfolio_root = '/userfiles/portfolio';
1.582     raeburn  2831:     my $res_error;
                   2832:     my ($partlist,$handgrade,$responseType) = &response_type($symb,\$res_error);
                   2833:     if ($res_error) {
                   2834:         $request->print('<br />'.&navmap_errormsg().'<br />');
                   2835:         return;
                   2836:     }
1.375     albertel 2837:     my @part_response_id = &flatten_responseType($responseType);
                   2838:     foreach my $part_response_id (@part_response_id) {
                   2839:     	my ($part_id,$resp_id) = @{ $part_response_id };
                   2840: 	my $part_resp = join('_',@{ $part_response_id });
1.337     banghart 2841:             if (($env{'form.'.$newflg.'_'.$part_resp.'_returndoc1'}) && ($new_part == $part_id)) {
                   2842:                 # if multiple files are uploaded names will be 'returndoc2','returndoc3'
                   2843:                 my $file_counter = 1;
1.367     albertel 2844: 		my $file_msg;
1.337     banghart 2845:                 while ($env{'form.'.$newflg.'_'.$part_resp.'_returndoc'.$file_counter}) {
                   2846:                     my $fname=$env{'form.'.$newflg.'_'.$part_resp.'_returndoc'.$file_counter.'.filename'};
1.338     banghart 2847:                     my ($directory,$answer_file) = 
                   2848:                         ($env{'form.'.$newflg.'_'.$part_resp.'_origdoc'.$file_counter} =~ /^(.*?)([^\/]*)$/);
                   2849:                     my ($answer_name,$answer_ver,$answer_ext) =
                   2850: 		        &file_name_version_ext($answer_file);
1.355     banghart 2851: 		    my ($portfolio_path) = ($directory =~ /^.+$stuname\/portfolio(.*)/);
1.517     raeburn  2852:                     my $getpropath = 1;
                   2853: 		    my @dir_list = &Apache::lonnet::dirlist($portfolio_root.$portfolio_path,$domain,$stuname,$getpropath);
1.338     banghart 2854: 		    my $version = &get_next_version($answer_name, $answer_ext, \@dir_list);
1.355     banghart 2855:                     # fix file name
                   2856:                     my ($save_file_name) = (($directory.$answer_name.".$version.".$answer_ext) =~ /^.+\/${stuname}\/(.*)/);
                   2857:                     my $result=&Apache::lonnet::finishuserfileupload($stuname,$domain,
                   2858:             	                                $newflg.'_'.$part_resp.'_returndoc'.$file_counter,
                   2859:             	                                $save_file_name);
1.337     banghart 2860:                     if ($result !~ m|^/uploaded/|) {
1.536     raeburn  2861:                         $request->print('<br /><span class="LC_error">'.
                   2862:                             &mt('An error occurred ([_1]) while trying to upload [_2].',
                   2863:                                 $result,$newflg.'_'.$part_resp.'_returndoc'.$file_counter).
                   2864:                                         '</span>');
1.356     banghart 2865:                     } else {
1.360     banghart 2866:                         # mark the file as read only
                   2867:                         my @files = ($save_file_name);
1.372     albertel 2868:                         my @what = ($symb,$env{'request.course.id'},'handback');
1.360     banghart 2869:                         &Apache::lonnet::mark_as_readonly($domain,$stuname,\@files,\@what);
1.367     albertel 2870: 			if (exists($$newrecord{"resource.$new_part.$resp_id.handback"})) {
                   2871: 			    $$newrecord{"resource.$new_part.$resp_id.handback"}.=',';
                   2872: 			}
                   2873:                         $$newrecord{"resource.$new_part.$resp_id.handback"} .= $save_file_name;
                   2874: 			$file_msg.= "\n".'<br /><span class="LC_filename"><a href="/uploaded/'."$domain/$stuname/".$save_file_name.'">'.$save_file_name."</a></span><br />";
                   2875: 
1.337     banghart 2876:                     }
                   2877:                     $request->print("<br />".$fname." will be the uploaded file name");
1.354     albertel 2878:                     $request->print(" ".$env{'form.'.$newflg.'_'.$part_resp.'_origdoc'.$file_counter});
1.337     banghart 2879:                     $file_counter++;
                   2880:                 }
1.367     albertel 2881: 		my $subject = "File Handed Back by Instructor ";
                   2882: 		my $message = "A file has been returned that was originally submitted in reponse to: <br />";
                   2883: 		$message .= "<strong>".&Apache::lonnet::gettitle($symb)."</strong><br />";
                   2884: 		$message .= ' The returned file(s) are named: '. $file_msg;
                   2885: 		$message .= " and can be found in your portfolio space.";
1.418     albertel 2886: 		my ($feedurl,$showsymb) = 
                   2887: 		    &get_feedurl_and_symb($symb,$domain,$stuname);
1.386     raeburn  2888:                 my $restitle = &Apache::lonnet::gettitle($symb);
                   2889: 		my $msgstatus = 
                   2890:                    &Apache::lonmsg::user_normal_msg($stuname,$domain,$subject.
                   2891: 			 ' (File Returned) ['.$restitle.']',$message,undef,
1.418     albertel 2892:                          $feedurl,undef,undef,undef,$showsymb,$restitle);
1.337     banghart 2893:             }
                   2894:         }
1.338     banghart 2895:     return;
1.337     banghart 2896: }
                   2897: 
1.418     albertel 2898: sub get_feedurl_and_symb {
                   2899:     my ($symb,$uname,$udom) = @_;
                   2900:     my (undef,undef,$url) = &Apache::lonnet::decode_symb($symb);
                   2901:     $url = &Apache::lonnet::clutter($url);
                   2902:     my $encrypturl=&Apache::lonnet::EXT('resource.0.encrypturl',
                   2903: 					$symb,$udom,$uname);
                   2904:     if ($encrypturl =~ /^yes$/i) {
                   2905: 	&Apache::lonenc::encrypted(\$url,1);
                   2906: 	&Apache::lonenc::encrypted(\$symb,1);
                   2907:     }
                   2908:     return ($url,$symb);
                   2909: }
                   2910: 
1.313     banghart 2911: sub get_submitted_files {
                   2912:     my ($udom,$uname,$partid,$respid,$record) = @_;
                   2913:     my @files;
                   2914:     if ($$record{"resource.$partid.$respid.portfiles"}) {
                   2915:         my $file_url = '/uploaded/'.$udom.'/'.$uname.'/portfolio';
                   2916:         foreach my $file (split(',',$$record{"resource.$partid.$respid.portfiles"})) {
                   2917:     	    push(@files,$file_url.$file);
                   2918:         }
                   2919:     }
                   2920:     if ($$record{"resource.$partid.$respid.uploadedurl"}) {
                   2921:         push(@files,$$record{"resource.$partid.$respid.uploadedurl"});
                   2922:     }
                   2923:     return (\@files);
                   2924: }
1.322     albertel 2925: 
1.269     raeburn  2926: # ----------- Provides number of tries since last reset.
                   2927: sub get_num_tries {
                   2928:     my ($record,$last_reset,$part) = @_;
                   2929:     my $timestamp = '';
                   2930:     my $num_tries = 0;
                   2931:     if ($$record{'version'}) {
                   2932:         for (my $version=$$record{'version'};$version>=1;$version--) {
                   2933:             if (exists($$record{$version.':resource.'.$part.'.solved'})) {
                   2934:                 $timestamp = $$record{$version.':timestamp'};
                   2935:                 if ($timestamp > $last_reset) {
                   2936:                     $num_tries ++;
                   2937:                 } else {
                   2938:                     last;
                   2939:                 }
                   2940:             }
                   2941:         }
                   2942:     }
                   2943:     return $num_tries;
                   2944: }
                   2945: 
                   2946: # ----------- Determine decrements required in aggregate totals 
                   2947: sub decrement_aggs {
                   2948:     my ($symb,$part,$aggregate,$aggtries,$totaltries,$solvedstatus) = @_;
                   2949:     my %decrement = (
                   2950:                         attempts => 0,
                   2951:                         users => 0,
                   2952:                         correct => 0
                   2953:                     );
                   2954:     $decrement{'attempts'} = $aggtries;
                   2955:     if ($solvedstatus =~ /^correct/) {
                   2956:         $decrement{'correct'} = 1;
                   2957:     }
                   2958:     if ($aggtries == $totaltries) {
                   2959:         $decrement{'users'} = 1;
                   2960:     }
1.524     raeburn  2961:     foreach my $type (keys(%decrement)) {
1.269     raeburn  2962:         $$aggregate{$symb."\0".$part."\0".$type} = -$decrement{$type};
                   2963:     }
                   2964:     return;
                   2965: }
                   2966: 
                   2967: # ----------- Determine timestamps for last reset of aggregate totals for parts  
                   2968: sub get_last_resets {
1.270     albertel 2969:     my ($symb,$courseid,$partids) =@_;
                   2970:     my %last_resets;
1.269     raeburn  2971:     my $cdom = $env{'course.'.$courseid.'.domain'};
                   2972:     my $cname = $env{'course.'.$courseid.'.num'};
1.271     albertel 2973:     my @keys;
                   2974:     foreach my $part (@{$partids}) {
                   2975: 	push(@keys,"$symb\0$part\0resettime");
                   2976:     }
                   2977:     my %results=&Apache::lonnet::get('nohist_resourcetracker',\@keys,
                   2978: 				     $cdom,$cname);
                   2979:     foreach my $part (@{$partids}) {
                   2980: 	$last_resets{$part}=$results{"$symb\0$part\0resettime"};
1.269     raeburn  2981:     }
1.270     albertel 2982:     return %last_resets;
1.269     raeburn  2983: }
                   2984: 
1.251     banghart 2985: # ----------- Handles creating versions for portfolio files as answers
                   2986: sub version_portfiles {
1.343     banghart 2987:     my ($record, $parts_graded, $courseid, $symb, $domain, $stu_name, $v_flag) = @_;
1.263     banghart 2988:     my $version_parts = join('|',@$v_flag);
1.343     banghart 2989:     my @returned_keys;
1.255     banghart 2990:     my $parts = join('|', @$parts_graded);
1.517     raeburn  2991:     my $portfolio_root = '/userfiles/portfolio';
1.277     albertel 2992:     foreach my $key (keys(%$record)) {
1.259     banghart 2993:         my $new_portfiles;
1.263     banghart 2994:         if ($key =~ /^resource\.($version_parts)\./ && $key =~ /\.portfiles$/ ) {
1.342     banghart 2995:             my @versioned_portfiles;
1.367     albertel 2996:             my @portfiles = split(/\s*,\s*/,$$record{$key});
1.252     banghart 2997:             foreach my $file (@portfiles) {
1.306     banghart 2998:                 &Apache::lonnet::unmark_as_readonly($domain,$stu_name,[$symb,$env{'request.course.id'}],$file);
1.304     albertel 2999:                 my ($directory,$answer_file) =($file =~ /^(.*?)([^\/]*)$/);
                   3000: 		my ($answer_name,$answer_ver,$answer_ext) =
                   3001: 		    &file_name_version_ext($answer_file);
1.517     raeburn  3002:                 my $getpropath = 1;    
                   3003:                 my @dir_list = &Apache::lonnet::dirlist($portfolio_root.$directory,$domain,$stu_name,$getpropath);
1.342     banghart 3004:                 my $version = &get_next_version($answer_name, $answer_ext, \@dir_list);
1.306     banghart 3005:                 my $new_answer = &version_selected_portfile($domain, $stu_name, $directory, $answer_file, $version);
                   3006:                 if ($new_answer ne 'problem getting file') {
1.342     banghart 3007:                     push(@versioned_portfiles, $directory.$new_answer);
1.306     banghart 3008:                     &Apache::lonnet::mark_as_readonly($domain,$stu_name,
1.367     albertel 3009:                         [$directory.$new_answer],
1.306     banghart 3010:                         [$symb,$env{'request.course.id'},'graded']);
1.259     banghart 3011:                 }
1.252     banghart 3012:             }
1.343     banghart 3013:             $$record{$key} = join(',',@versioned_portfiles);
                   3014:             push(@returned_keys,$key);
1.251     banghart 3015:         }
                   3016:     } 
1.343     banghart 3017:     return (@returned_keys);   
1.305     banghart 3018: }
                   3019: 
1.307     banghart 3020: sub get_next_version {
1.341     banghart 3021:     my ($answer_name, $answer_ext, $dir_list) = @_;
1.307     banghart 3022:     my $version;
                   3023:     foreach my $row (@$dir_list) {
                   3024:         my ($file) = split(/\&/,$row,2);
                   3025:         my ($file_name,$file_version,$file_ext) =
                   3026: 	    &file_name_version_ext($file);
                   3027:         if (($file_name eq $answer_name) && 
                   3028: 	    ($file_ext eq $answer_ext)) {
                   3029:                 # gets here if filename and extension match, regardless of version
                   3030:                 if ($file_version ne '') {
                   3031:                 # a versioned file is found  so save it for later
                   3032:                 if ($file_version > $version) {
                   3033: 		    $version = $file_version;
                   3034: 	        }
                   3035:             }
                   3036:         }
                   3037:     } 
                   3038:     $version ++;
                   3039:     return($version);
                   3040: }
                   3041: 
1.305     banghart 3042: sub version_selected_portfile {
1.306     banghart 3043:     my ($domain,$stu_name,$directory,$file_name,$version) = @_;
                   3044:     my ($answer_name,$answer_ver,$answer_ext) =
                   3045:         &file_name_version_ext($file_name);
                   3046:     my $new_answer;
                   3047:     $env{'form.copy'} = &Apache::lonnet::getfile("/uploaded/$domain/$stu_name/portfolio$directory$file_name");
                   3048:     if($env{'form.copy'} eq '-1') {
                   3049:         $new_answer = 'problem getting file';
                   3050:     } else {
                   3051:         $new_answer = $answer_name.'.'.$version.'.'.$answer_ext;
                   3052:         my $copy_result = &Apache::lonnet::finishuserfileupload(
                   3053:                             $stu_name,$domain,'copy',
                   3054: 		        '/portfolio'.$directory.$new_answer);
                   3055:     }    
                   3056:     return ($new_answer);
1.251     banghart 3057: }
                   3058: 
1.304     albertel 3059: sub file_name_version_ext {
                   3060:     my ($file)=@_;
                   3061:     my @file_parts = split(/\./, $file);
                   3062:     my ($name,$version,$ext);
                   3063:     if (@file_parts > 1) {
                   3064: 	$ext=pop(@file_parts);
                   3065: 	if (@file_parts > 1 && $file_parts[-1] =~ /^\d+$/) {
                   3066: 	    $version=pop(@file_parts);
                   3067: 	}
                   3068: 	$name=join('.',@file_parts);
                   3069:     } else {
                   3070: 	$name=join('.',@file_parts);
                   3071:     }
                   3072:     return($name,$version,$ext);
                   3073: }
                   3074: 
1.44      ng       3075: #--------------------------------------------------------------------------------------
                   3076: #
                   3077: #-------------------------- Next few routines handles grading by section or whole class
                   3078: #
                   3079: #--- Javascript to handle grading by section or whole class
1.42      ng       3080: sub viewgrades_js {
                   3081:     my ($request) = shift;
                   3082: 
1.539     riegler  3083:     my $alertmsg = &mt('A number equal or greater than 0 is expected. Entered value = ');
1.597     wenzelju 3084:     $request->print(&Apache::lonhtmlcommon::scripttag(<<VIEWJAVASCRIPT));
1.45      ng       3085:    function writePoint(partid,weight,point) {
1.125     ng       3086: 	var radioButton = document.classgrade["RADVAL_"+partid];
                   3087: 	var textbox = document.classgrade["TEXTVAL_"+partid];
1.42      ng       3088: 	if (point == "textval") {
1.125     ng       3089: 	    point = document.classgrade["TEXTVAL_"+partid].value;
1.109     matthew  3090: 	    if (isNaN(point) || parseFloat(point) < 0) {
1.539     riegler  3091: 		alert("$alertmsg"+parseFloat(point));
1.42      ng       3092: 		var resetbox = false;
                   3093: 		for (var i=0; i<radioButton.length; i++) {
                   3094: 		    if (radioButton[i].checked) {
                   3095: 			textbox.value = i;
                   3096: 			resetbox = true;
                   3097: 		    }
                   3098: 		}
                   3099: 		if (!resetbox) {
                   3100: 		    textbox.value = "";
                   3101: 		}
                   3102: 		return;
                   3103: 	    }
1.109     matthew  3104: 	    if (parseFloat(point) > parseFloat(weight)) {
                   3105: 		var resp = confirm("You entered a value ("+parseFloat(point)+
1.44      ng       3106: 				   ") greater than the weight for the part. Accept?");
                   3107: 		if (resp == false) {
                   3108: 		    textbox.value = "";
                   3109: 		    return;
                   3110: 		}
                   3111: 	    }
1.42      ng       3112: 	    for (var i=0; i<radioButton.length; i++) {
                   3113: 		radioButton[i].checked=false;
1.109     matthew  3114: 		if (parseFloat(point) == i) {
1.42      ng       3115: 		    radioButton[i].checked=true;
                   3116: 		}
                   3117: 	    }
1.41      ng       3118: 
1.42      ng       3119: 	} else {
1.125     ng       3120: 	    textbox.value = parseFloat(point);
1.42      ng       3121: 	}
1.41      ng       3122: 	for (i=0;i<document.classgrade.total.value;i++) {
1.125     ng       3123: 	    var user = document.classgrade["ctr"+i].value;
1.289     albertel 3124: 	    user = user.replace(new RegExp(':', 'g'),"_");
1.125     ng       3125: 	    var scorename = document.classgrade["GD_"+user+"_"+partid+"_awarded"];
                   3126: 	    var saveval   = document.classgrade["GD_"+user+"_"+partid+"_solved_s"].value;
                   3127: 	    var selname   = document.classgrade["GD_"+user+"_"+partid+"_solved"];
1.42      ng       3128: 	    if (saveval != "correct") {
                   3129: 		scorename.value = point;
1.43      ng       3130: 		if (selname[0].selected != true) {
                   3131: 		    selname[0].selected = true;
                   3132: 		}
1.42      ng       3133: 	    }
                   3134: 	}
1.125     ng       3135: 	document.classgrade["SELVAL_"+partid][0].selected = true;
1.42      ng       3136:     }
                   3137: 
                   3138:     function writeRadText(partid,weight) {
1.125     ng       3139: 	var selval   = document.classgrade["SELVAL_"+partid];
                   3140: 	var radioButton = document.classgrade["RADVAL_"+partid];
1.265     www      3141:         var override = document.classgrade["FORCE_"+partid].checked;
1.125     ng       3142: 	var textbox = document.classgrade["TEXTVAL_"+partid];
                   3143: 	if (selval[1].selected || selval[2].selected) {
1.42      ng       3144: 	    for (var i=0; i<radioButton.length; i++) {
                   3145: 		radioButton[i].checked=false;
                   3146: 
                   3147: 	    }
                   3148: 	    textbox.value = "";
                   3149: 
                   3150: 	    for (i=0;i<document.classgrade.total.value;i++) {
1.125     ng       3151: 		var user = document.classgrade["ctr"+i].value;
1.289     albertel 3152: 		user = user.replace(new RegExp(':', 'g'),"_");
1.125     ng       3153: 		var scorename = document.classgrade["GD_"+user+"_"+partid+"_awarded"];
                   3154: 		var saveval   = document.classgrade["GD_"+user+"_"+partid+"_solved_s"].value;
                   3155: 		var selname   = document.classgrade["GD_"+user+"_"+partid+"_solved"];
1.265     www      3156: 		if ((saveval != "correct") || override) {
1.42      ng       3157: 		    scorename.value = "";
1.125     ng       3158: 		    if (selval[1].selected) {
                   3159: 			selname[1].selected = true;
                   3160: 		    } else {
                   3161: 			selname[2].selected = true;
                   3162: 			if (Number(document.classgrade["GD_"+user+"_"+partid+"_tries"].value)) 
                   3163: 			{document.classgrade["GD_"+user+"_"+partid+"_tries"].value = '0';}
                   3164: 		    }
1.42      ng       3165: 		}
                   3166: 	    }
1.43      ng       3167: 	} else {
                   3168: 	    for (i=0;i<document.classgrade.total.value;i++) {
1.125     ng       3169: 		var user = document.classgrade["ctr"+i].value;
1.289     albertel 3170: 		user = user.replace(new RegExp(':', 'g'),"_");
1.125     ng       3171: 		var scorename = document.classgrade["GD_"+user+"_"+partid+"_awarded"];
                   3172: 		var saveval   = document.classgrade["GD_"+user+"_"+partid+"_solved_s"].value;
                   3173: 		var selname   = document.classgrade["GD_"+user+"_"+partid+"_solved"];
1.265     www      3174: 		if ((saveval != "correct") || override) {
1.125     ng       3175: 		    scorename.value = document.classgrade["GD_"+user+"_"+partid+"_awarded_s"].value;
1.43      ng       3176: 		    selname[0].selected = true;
                   3177: 		}
                   3178: 	    }
                   3179: 	}	    
1.42      ng       3180:     }
                   3181: 
                   3182:     function changeSelect(partid,user) {
1.125     ng       3183: 	var selval = document.classgrade["GD_"+user+'_'+partid+"_solved"];
                   3184: 	var textbox = document.classgrade["GD_"+user+'_'+partid+"_awarded"];
1.44      ng       3185: 	var point  = textbox.value;
1.125     ng       3186: 	var weight = document.classgrade["weight_"+partid].value;
1.44      ng       3187: 
1.109     matthew  3188: 	if (isNaN(point) || parseFloat(point) < 0) {
1.539     riegler  3189: 	    alert("$alertmsg"+parseFloat(point));
1.44      ng       3190: 	    textbox.value = "";
                   3191: 	    return;
                   3192: 	}
1.109     matthew  3193: 	if (parseFloat(point) > parseFloat(weight)) {
                   3194: 	    var resp = confirm("You entered a value ("+parseFloat(point)+
1.44      ng       3195: 			       ") greater than the weight of the part. Accept?");
                   3196: 	    if (resp == false) {
                   3197: 		textbox.value = "";
                   3198: 		return;
                   3199: 	    }
                   3200: 	}
1.42      ng       3201: 	selval[0].selected = true;
                   3202:     }
                   3203: 
                   3204:     function changeOneScore(partid,user) {
1.125     ng       3205: 	var selval = document.classgrade["GD_"+user+'_'+partid+"_solved"];
                   3206: 	if (selval[1].selected || selval[2].selected) {
                   3207: 	    document.classgrade["GD_"+user+'_'+partid+"_awarded"].value = "";
                   3208: 	    if (selval[2].selected) {
                   3209: 		document.classgrade["GD_"+user+'_'+partid+"_tries"].value = "0";
                   3210: 	    }
1.269     raeburn  3211:         }
1.42      ng       3212:     }
                   3213: 
                   3214:     function resetEntry(numpart) {
                   3215: 	for (ctpart=0;ctpart<numpart;ctpart++) {
1.125     ng       3216: 	    var partid = document.classgrade["partid_"+ctpart].value;
                   3217: 	    var radioButton = document.classgrade["RADVAL_"+partid];
                   3218: 	    var textbox = document.classgrade["TEXTVAL_"+partid];
                   3219: 	    var selval  = document.classgrade["SELVAL_"+partid];
1.42      ng       3220: 	    for (var i=0; i<radioButton.length; i++) {
                   3221: 		radioButton[i].checked=false;
                   3222: 
                   3223: 	    }
                   3224: 	    textbox.value = "";
                   3225: 	    selval[0].selected = true;
                   3226: 
                   3227: 	    for (i=0;i<document.classgrade.total.value;i++) {
1.125     ng       3228: 		var user = document.classgrade["ctr"+i].value;
1.289     albertel 3229: 		user = user.replace(new RegExp(':', 'g'),"_");
1.125     ng       3230: 		var resetscore = document.classgrade["GD_"+user+"_"+partid+"_awarded"];
                   3231: 		resetscore.value = document.classgrade["GD_"+user+"_"+partid+"_awarded_s"].value;
                   3232: 		var resettries = document.classgrade["GD_"+user+"_"+partid+"_tries"];
                   3233: 		resettries.value = document.classgrade["GD_"+user+"_"+partid+"_tries_s"].value;
                   3234: 		var saveselval   = document.classgrade["GD_"+user+"_"+partid+"_solved_s"].value;
                   3235: 		var selname   = document.classgrade["GD_"+user+"_"+partid+"_solved"];
1.42      ng       3236: 		if (saveselval == "excused") {
1.43      ng       3237: 		    if (selname[1].selected == false) { selname[1].selected = true;}
1.42      ng       3238: 		} else {
1.43      ng       3239: 		    if (selname[0].selected == false) {selname[0].selected = true};
1.42      ng       3240: 		}
                   3241: 	    }
1.41      ng       3242: 	}
1.42      ng       3243:     }
                   3244: 
1.41      ng       3245: VIEWJAVASCRIPT
1.42      ng       3246: }
                   3247: 
1.44      ng       3248: #--- show scores for a section or whole class w/ option to change/update a score
1.42      ng       3249: sub viewgrades {
1.608     www      3250:     my ($request,$symb) = @_;
1.42      ng       3251:     &viewgrades_js($request);
1.41      ng       3252: 
1.168     albertel 3253:     #need to make sure we have the correct data for later EXT calls, 
                   3254:     #thus invalidate the cache
                   3255:     &Apache::lonnet::devalidatecourseresdata(
1.257     albertel 3256:                  $env{'course.'.$env{'request.course.id'}.'.num'},
                   3257:                  $env{'course.'.$env{'request.course.id'}.'.domain'});
1.168     albertel 3258:     &Apache::lonnet::clear_EXT_cache_status();
                   3259: 
1.398     albertel 3260:     my $result='<h3><span class="LC_info">'.&mt('Manual Grading').'</span></h3>';
1.41      ng       3261: 
                   3262:     #view individual student submission form - called using Javascript viewOneStudent
1.324     albertel 3263:     $result.=&jscriptNform($symb);
1.41      ng       3264: 
1.44      ng       3265:     #beginning of class grading form
1.442     banghart 3266:     my $stu_status = join(':',&Apache::loncommon::get_env_multiple('form.Status'));
1.41      ng       3267:     $result.= '<form action="/adm/grades" method="post" name="classgrade">'."\n".
1.418     albertel 3268: 	'<input type="hidden" name="symb"    value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
1.38      ng       3269: 	'<input type="hidden" name="command" value="editgrades" />'."\n".
1.432     banghart 3270: 	&build_section_inputs().
1.442     banghart 3271: 	'<input type="hidden" name="Status" value="'.$env{'stu_status'}.'" />'."\n".
1.72      ng       3272: 
1.560     raeburn  3273:     my ($common_header,$specific_header);
1.257     albertel 3274:     if ($env{'form.section'} eq 'all') {
1.560     raeburn  3275: 	$common_header = &mt('Assign Common Grade to Class');
                   3276:         $specific_header = &mt('Assign Grade to Specific Students in Class');
1.257     albertel 3277:     } elsif ($env{'form.section'} eq 'none') {
1.560     raeburn  3278:         $common_header = &mt('Assign Common Grade to Students in no Section');
                   3279: 	$specific_header = &mt('Assign Grade to Specific Students in no Section');
1.52      albertel 3280:     } else {
1.560     raeburn  3281:         my $section_display = join (", ",&Apache::loncommon::get_env_multiple('form.section'));
                   3282:         $common_header = &mt('Assign Common Grade to Students in Section(s) [_1]',$section_display);
                   3283: 	$specific_header = &mt('Assign Grade to Specific Students in Section(s) [_1]',$section_display);
1.52      albertel 3284:     }
1.560     raeburn  3285:     $result.= '<h3>'.$common_header.'</h3>'.&Apache::loncommon::start_data_table();
1.44      ng       3286:     #radio buttons/text box for assigning points for a section or class.
                   3287:     #handles different parts of a problem
1.582     raeburn  3288:     my $res_error;
                   3289:     my ($partlist,$handgrade,$responseType) = &response_type($symb,\$res_error);
                   3290:     if ($res_error) {
                   3291:         return &navmap_errormsg();
                   3292:     }
1.42      ng       3293:     my %weight = ();
                   3294:     my $ctsparts = 0;
1.45      ng       3295:     my %seen = ();
1.375     albertel 3296:     my @part_response_id = &flatten_responseType($responseType);
                   3297:     foreach my $part_response_id (@part_response_id) {
                   3298:     	my ($partid,$respid) = @{ $part_response_id };
                   3299: 	my $part_resp = join('_',@{ $part_response_id });
1.45      ng       3300: 	next if $seen{$partid};
                   3301: 	$seen{$partid}++;
1.375     albertel 3302: 	my $handgrade=$$handgrade{$part_resp};
1.42      ng       3303: 	my $wgt = &Apache::lonnet::EXT('resource.'.$partid.'.weight',$symb);
                   3304: 	$weight{$partid} = $wgt eq '' ? '1' : $wgt;
                   3305: 
1.324     albertel 3306: 	my $display_part=&get_display_part($partid,$symb);
1.485     albertel 3307: 	my $radio.='<table border="0"><tr>';  
1.41      ng       3308: 	my $ctr = 0;
1.42      ng       3309: 	while ($ctr<=$weight{$partid}) { # display radio buttons in a nice table 10 across
1.485     albertel 3310: 	    $radio.= '<td><label><input type="radio" name="RADVAL_'.$partid.'" '.
1.54      albertel 3311: 		'onclick="javascript:writePoint(\''.$partid.'\','.$weight{$partid}.
1.288     albertel 3312: 		','.$ctr.')" />'.$ctr."</label></td>\n";
1.41      ng       3313: 	    $result.=(($ctr+1)%10 == 0 ? '</tr><tr>' : '');
                   3314: 	    $ctr++;
                   3315: 	}
1.485     albertel 3316: 	$radio.='</tr></table>';
                   3317: 	my $line = '<input type="text" name="TEXTVAL_'.
1.589     bisitz   3318: 	    $partid.'" size="4" '.'onchange="javascript:writePoint(\''.
1.54      albertel 3319: 		$partid.'\','.$weight{$partid}.',\'textval\')" /> /'.
1.539     riegler  3320: 	    $weight{$partid}.' '.&mt('(problem weight)').'</td>'."\n";
                   3321: 	$line.= '<td><b>'.&mt('Grade Status').':</b><select name="SELVAL_'.$partid.'"'.
1.589     bisitz   3322: 	    'onchange="javascript:writeRadText(\''.$partid.'\','.
1.59      albertel 3323: 		$weight{$partid}.')"> '.
1.401     albertel 3324: 	    '<option selected="selected"> </option>'.
1.485     albertel 3325: 	    '<option value="excused">'.&mt('excused').'</option>'.
                   3326: 	    '<option value="reset status">'.&mt('reset status').'</option>'.
                   3327: 	    '</select></td>'.
                   3328:             '<td><label><input type="checkbox" name="FORCE_'.$partid.'" />'.&mt('Override "Correct"').'</label>';
                   3329: 	$line.='<input type="hidden" name="partid_'.
                   3330: 	    $ctsparts.'" value="'.$partid.'" />'."\n";
                   3331: 	$line.='<input type="hidden" name="weight_'.
                   3332: 	    $partid.'" value="'.$weight{$partid}.'" />'."\n";
                   3333: 
                   3334: 	$result.=
                   3335: 	    &Apache::loncommon::start_data_table_row()."\n".
1.577     bisitz   3336: 	    '<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 3337: 	    &Apache::loncommon::end_data_table_row()."\n";
1.42      ng       3338: 	$ctsparts++;
1.41      ng       3339:     }
1.474     albertel 3340:     $result.=&Apache::loncommon::end_data_table()."\n".
1.52      albertel 3341: 	'<input type="hidden" name="totalparts" value="'.$ctsparts.'" />';
1.485     albertel 3342:     $result.='<input type="button" value="'.&mt('Revert to Default').'" '.
1.589     bisitz   3343: 	'onclick="javascript:resetEntry('.$ctsparts.');" />';
1.41      ng       3344: 
1.44      ng       3345:     #table listing all the students in a section/class
                   3346:     #header of table
1.560     raeburn  3347:     $result.= '<h3>'.$specific_header.'</h3>'.
                   3348:               &Apache::loncommon::start_data_table().
                   3349: 	      &Apache::loncommon::start_data_table_header_row().
                   3350: 	      '<th>'.&mt('No.').'</th>'.
                   3351: 	      '<th>'.&nameUserString('header')."</th>\n";
1.582     raeburn  3352:     my $partserror;
                   3353:     my (@parts) = sort(&getpartlist($symb,\$partserror));
                   3354:     if ($partserror) {
                   3355:         return &navmap_errormsg();
                   3356:     }
1.324     albertel 3357:     my (undef,undef,$url)=&Apache::lonnet::decode_symb($symb);
1.269     raeburn  3358:     my @partids = ();
1.41      ng       3359:     foreach my $part (@parts) {
                   3360: 	my $display=&Apache::lonnet::metadata($url,$part.'.display');
1.539     riegler  3361:         my $narrowtext = &mt('Tries');
                   3362: 	$display =~ s|^Number of Attempts|$narrowtext <br />|; # makes the column narrower
1.41      ng       3363: 	if  (!$display) { $display = &Apache::lonnet::metadata($url,$part.'.name'); }
1.207     albertel 3364: 	my ($partid) = &split_part_type($part);
1.524     raeburn  3365:         push(@partids,$partid);
1.324     albertel 3366: 	my $display_part=&get_display_part($partid,$symb);
1.41      ng       3367: 	if ($display =~ /^Partial Credit Factor/) {
1.485     albertel 3368: 	    $result.='<th>'.
                   3369: 		&mt('Score Part: [_1]<br /> (weight = [_2])',
                   3370: 		    $display_part,$weight{$partid}).'</th>'."\n";
1.41      ng       3371: 	    next;
1.485     albertel 3372: 	    
1.207     albertel 3373: 	} else {
1.485     albertel 3374: 	    if ($display =~ /Problem Status/) {
                   3375: 		my $grade_status_mt = &mt('Grade Status');
                   3376: 		$display =~ s{Problem Status}{$grade_status_mt<br />};
                   3377: 	    }
                   3378: 	    my $part_mt = &mt('Part:');
                   3379: 	    $display =~s{\[Part: \Q$partid\E\]}{$part_mt $display_part};
1.41      ng       3380: 	}
1.485     albertel 3381: 
1.474     albertel 3382: 	$result.='<th>'.$display.'</th>'."\n";
1.41      ng       3383:     }
1.474     albertel 3384:     $result.=&Apache::loncommon::end_data_table_header_row();
1.44      ng       3385: 
1.270     albertel 3386:     my %last_resets = 
                   3387: 	&get_last_resets($symb,$env{'request.course.id'},\@partids);
1.269     raeburn  3388: 
1.41      ng       3389:     #get info for each student
1.44      ng       3390:     #list all the students - with points and grade status
1.257     albertel 3391:     my (undef,undef,$fullname) = &getclasslist($env{'form.section'},'1');
1.41      ng       3392:     my $ctr = 0;
1.294     albertel 3393:     foreach (sort 
                   3394: 	     {
                   3395: 		 if (lc($$fullname{$a}) ne lc($$fullname{$b})) {
                   3396: 		     return (lc($$fullname{$a}) cmp lc($$fullname{$b}));
                   3397: 		 }
                   3398: 		 return $a cmp $b;
                   3399: 	     } (keys(%$fullname))) {
1.126     ng       3400: 	$ctr++;
1.324     albertel 3401: 	$result.=&viewstudentgrade($symb,$env{'request.course.id'},
1.269     raeburn  3402: 				   $_,$$fullname{$_},\@parts,\%weight,$ctr,\%last_resets);
1.41      ng       3403:     }
1.474     albertel 3404:     $result.=&Apache::loncommon::end_data_table();
1.41      ng       3405:     $result.='<input type="hidden" name="total" value="'.$ctr.'" />'."\n";
1.485     albertel 3406:     $result.='<input type="button" value="'.&mt('Save').'" '.
1.589     bisitz   3407: 	'onclick="javascript:submit();" target="_self" /></form>'."\n";
1.96      albertel 3408:     if (scalar(%$fullname) eq 0) {
                   3409: 	my $colspan=3+scalar(@parts);
1.433     banghart 3410: 	my $section_display = join (", ",&Apache::loncommon::get_env_multiple('form.section'));
1.442     banghart 3411:         my $stu_status = join(' or ',&Apache::loncommon::get_env_multiple('form.Status'));
1.433     banghart 3412: 	$result='<span class="LC_warning">'.
1.485     albertel 3413: 	    &mt('There are no students in section(s) [_1] with enrollment status [_2] to modify or grade.',
1.442     banghart 3414: 	        $section_display, $stu_status).
1.433     banghart 3415: 	    '</span>';
1.96      albertel 3416:     }
1.41      ng       3417:     return $result;
                   3418: }
                   3419: 
1.44      ng       3420: #--- call by previous routine to display each student
1.41      ng       3421: sub viewstudentgrade {
1.324     albertel 3422:     my ($symb,$courseid,$student,$fullname,$parts,$weight,$ctr,$last_resets) = @_;
1.44      ng       3423:     my ($uname,$udom) = split(/:/,$student);
                   3424:     my %record=&Apache::lonnet::restore($symb,$courseid,$udom,$uname);
1.269     raeburn  3425:     my %aggregates = (); 
1.474     albertel 3426:     my $result=&Apache::loncommon::start_data_table_row().'<td align="right">'.
1.233     albertel 3427: 	'<input type="hidden" name="ctr'.($ctr-1).'" value="'.$student.'" />'.
                   3428: 	"\n".$ctr.'&nbsp;</td><td>&nbsp;'.
1.44      ng       3429: 	'<a href="javascript:viewOneStudent(\''.$uname.'\',\''.$udom.
1.417     albertel 3430: 	'\');" target="_self">'.$fullname.'</a> '.
1.398     albertel 3431: 	'<span class="LC_internal_info">('.$uname.($env{'user.domain'} eq $udom ? '' : ':'.$udom).')</span></td>'."\n";
1.281     albertel 3432:     $student=~s/:/_/; # colon doen't work in javascript for names
1.63      albertel 3433:     foreach my $apart (@$parts) {
                   3434: 	my ($part,$type) = &split_part_type($apart);
1.41      ng       3435: 	my $score=$record{"resource.$part.$type"};
1.276     albertel 3436:         $result.='<td align="center">';
1.269     raeburn  3437:         my ($aggtries,$totaltries);
                   3438:         unless (exists($aggregates{$part})) {
1.270     albertel 3439: 	    $totaltries = $record{'resource.'.$part.'.tries'};
                   3440: 
                   3441: 	    $aggtries = $totaltries;
1.269     raeburn  3442:             if ($$last_resets{$part}) {  
1.270     albertel 3443:                 $aggtries = &get_num_tries(\%record,$$last_resets{$part},
                   3444: 					   $part);
                   3445:             }
1.269     raeburn  3446:             $result.='<input type="hidden" name="'.
                   3447:                 'GD_'.$student.'_'.$part.'_aggtries" value="'.$aggtries.'" />'."\n";
                   3448:             $result.='<input type="hidden" name="'.
                   3449:                 'GD_'.$student.'_'.$part.'_totaltries" value="'.$totaltries.'" />'."\n";
                   3450:             $aggregates{$part} = 1;
                   3451:         }
1.41      ng       3452: 	if ($type eq 'awarded') {
1.320     albertel 3453: 	    my $pts = $score eq '' ? '' : &compute_points($score,$$weight{$part});
1.42      ng       3454: 	    $result.='<input type="hidden" name="'.
1.89      albertel 3455: 		'GD_'.$student.'_'.$part.'_awarded_s" value="'.$pts.'" />'."\n";
1.233     albertel 3456: 	    $result.='<input type="text" name="'.
1.89      albertel 3457: 		'GD_'.$student.'_'.$part.'_awarded" '.
1.589     bisitz   3458:                 'onchange="javascript:changeSelect(\''.$part.'\',\''.$student.
1.44      ng       3459: 		'\')" value="'.$pts.'" size="4" /></td>'."\n";
1.41      ng       3460: 	} elsif ($type eq 'solved') {
                   3461: 	    my ($status,$foo)=split(/_/,$score,2);
                   3462: 	    $status = 'nothing' if ($status eq '');
1.89      albertel 3463: 	    $result.='<input type="hidden" name="'.'GD_'.$student.'_'.
1.54      albertel 3464: 		$part.'_solved_s" value="'.$status.'" />'."\n";
1.233     albertel 3465: 	    $result.='&nbsp;<select name="'.
1.89      albertel 3466: 		'GD_'.$student.'_'.$part.'_solved" '.
1.589     bisitz   3467:                 'onchange="javascript:changeOneScore(\''.$part.'\',\''.$student.'\')" >'."\n";
1.485     albertel 3468: 	    $result.= (($status eq 'excused') ? '<option> </option><option selected="selected" value="excused">'.&mt('excused').'</option>' 
                   3469: 		: '<option selected="selected"> </option><option value="excused">'.&mt('excused').'</option>')."\n";
                   3470: 	    $result.='<option value="reset status">'.&mt('reset status').'</option>';
1.126     ng       3471: 	    $result.="</select>&nbsp;</td>\n";
1.122     ng       3472: 	} else {
                   3473: 	    $result.='<input type="hidden" name="'.
                   3474: 		'GD_'.$student.'_'.$part.'_'.$type.'_s" value="'.$score.'" />'.
                   3475: 		    "\n";
1.233     albertel 3476: 	    $result.='<input type="text" name="'.
1.122     ng       3477: 		'GD_'.$student.'_'.$part.'_'.$type.'" '.
                   3478: 		'value="'.$score.'" size="4" /></td>'."\n";
1.41      ng       3479: 	}
                   3480:     }
1.474     albertel 3481:     $result.=&Apache::loncommon::end_data_table_row();
1.41      ng       3482:     return $result;
1.38      ng       3483: }
                   3484: 
1.44      ng       3485: #--- change scores for all the students in a section/class
                   3486: #    record does not get update if unchanged
1.38      ng       3487: sub editgrades {
1.608     www      3488:     my ($request,$symb) = @_;
1.41      ng       3489: 
1.433     banghart 3490:     my $section_display = join (", ",&Apache::loncommon::get_env_multiple('form.section'));
1.477     albertel 3491:     my $title='<h2>'.&mt('Current Grade Status').'</h2>';
1.433     banghart 3492:     $title.='<h4>'.&mt('<b>Section: </b>[_1]',$section_display).'</h4>'."\n";
1.126     ng       3493: 
1.477     albertel 3494:     my $result= &Apache::loncommon::start_data_table().
                   3495: 	&Apache::loncommon::start_data_table_header_row().
                   3496: 	'<th rowspan="2" valign="middle">'.&mt('No.').'</th>'.
                   3497: 	'<th rowspan="2" valign="middle">'.&nameUserString('header')."</th>\n";
1.43      ng       3498:     my %scoreptr = (
                   3499: 		    'correct'  =>'correct_by_override',
                   3500: 		    'incorrect'=>'incorrect_by_override',
                   3501: 		    'excused'  =>'excused',
                   3502: 		    'ungraded' =>'ungraded_attempted',
1.596     raeburn  3503:                     'credited' =>'credit_attempted',
1.43      ng       3504: 		    'nothing'  => '',
                   3505: 		    );
1.257     albertel 3506:     my ($classlist,undef,$fullname) = &getclasslist($env{'form.section'},'0');
1.34      ng       3507: 
1.44      ng       3508:     my (@partid);
                   3509:     my %weight = ();
1.54      albertel 3510:     my %columns = ();
1.44      ng       3511:     my ($i,$ctr,$count,$rec_update) = (0,0,0,0);
1.54      albertel 3512: 
1.582     raeburn  3513:     my $partserror;
                   3514:     my (@parts) = sort(&getpartlist($symb,\$partserror));
                   3515:     if ($partserror) {
                   3516:         return &navmap_errormsg();
                   3517:     }
1.54      albertel 3518:     my $header;
1.257     albertel 3519:     while ($ctr < $env{'form.totalparts'}) {
                   3520: 	my $partid = $env{'form.partid_'.$ctr};
1.524     raeburn  3521: 	push(@partid,$partid);
1.257     albertel 3522: 	$weight{$partid} = $env{'form.weight_'.$partid};
1.44      ng       3523: 	$ctr++;
1.54      albertel 3524:     }
1.324     albertel 3525:     my (undef,undef,$url) = &Apache::lonnet::decode_symb($symb);
1.54      albertel 3526:     foreach my $partid (@partid) {
1.478     albertel 3527: 	$header .= '<th align="center">'.&mt('Old Score').'</th>'.
                   3528: 	    '<th align="center">'.&mt('New Score').'</th>';
1.54      albertel 3529: 	$columns{$partid}=2;
                   3530: 	foreach my $stores (@parts) {
                   3531: 	    my ($part,$type) = &split_part_type($stores);
                   3532: 	    if ($part !~ m/^\Q$partid\E/) { next;}
                   3533: 	    if ($type eq 'awarded' || $type eq 'solved') { next; }
                   3534: 	    my $display=&Apache::lonnet::metadata($url,$stores.'.display');
1.551     raeburn  3535: 	    $display =~ s/\[Part: \Q$part\E\]//;
1.539     riegler  3536:             my $narrowtext = &mt('Tries');
                   3537: 	    $display =~ s/Number of Attempts/$narrowtext/;
                   3538: 	    $header .= '<th align="center">'.&mt('Old').' '.$display.'</th>'.
                   3539: 		'<th align="center">'.&mt('New').' '.$display.'</th>';
1.54      albertel 3540: 	    $columns{$partid}+=2;
                   3541: 	}
                   3542:     }
                   3543:     foreach my $partid (@partid) {
1.324     albertel 3544: 	my $display_part=&get_display_part($partid,$symb);
1.478     albertel 3545: 	$result .= '<th colspan="'.$columns{$partid}.'" align="center">'.
                   3546: 	    &mt('Part: [_1] (Weight = [_2])',$display_part,$weight{$partid}).
                   3547: 	    '</th>';
1.54      albertel 3548: 
1.44      ng       3549:     }
1.477     albertel 3550:     $result .= &Apache::loncommon::end_data_table_header_row().
                   3551: 	&Apache::loncommon::start_data_table_header_row().
                   3552: 	$header.
                   3553: 	&Apache::loncommon::end_data_table_header_row();
                   3554:     my @noupdate;
1.126     ng       3555:     my ($updateCtr,$noupdateCtr) = (1,1);
1.257     albertel 3556:     for ($i=0; $i<$env{'form.total'}; $i++) {
1.93      albertel 3557: 	my $line;
1.257     albertel 3558: 	my $user = $env{'form.ctr'.$i};
1.281     albertel 3559: 	my ($uname,$udom)=split(/:/,$user);
1.44      ng       3560: 	my %newrecord;
                   3561: 	my $updateflag = 0;
1.281     albertel 3562: 	$line .= '<td>'.&nameUserString(undef,$$fullname{$user},$uname,$udom).'</td>';
1.108     albertel 3563: 	my $usec=$classlist->{"$uname:$udom"}[5];
1.105     albertel 3564: 	if (!&canmodify($usec)) {
1.126     ng       3565: 	    my $numcols=scalar(@partid)*4+2;
1.477     albertel 3566: 	    push(@noupdate,
1.478     albertel 3567: 		 $line."<td colspan=\"$numcols\"><span class=\"LC_warning\">".
                   3568: 		 &mt('Not allowed to modify student')."</span></td></tr>");
1.105     albertel 3569: 	    next;
                   3570: 	}
1.269     raeburn  3571:         my %aggregate = ();
                   3572:         my $aggregateflag = 0;
1.281     albertel 3573: 	$user=~s/:/_/; # colon doen't work in javascript for names
1.44      ng       3574: 	foreach (@partid) {
1.257     albertel 3575: 	    my $old_aw    = $env{'form.GD_'.$user.'_'.$_.'_awarded_s'};
1.54      albertel 3576: 	    my $old_part_pcr = $old_aw/($weight{$_} ne '0' ? $weight{$_}:1);
                   3577: 	    my $old_part  = $old_aw eq '' ? '' : $old_part_pcr;
1.257     albertel 3578: 	    my $old_score = $scoreptr{$env{'form.GD_'.$user.'_'.$_.'_solved_s'}};
                   3579: 	    my $awarded   = $env{'form.GD_'.$user.'_'.$_.'_awarded'};
1.54      albertel 3580: 	    my $pcr       = $awarded/($weight{$_} ne '0' ? $weight{$_} : 1);
                   3581: 	    my $partial   = $awarded eq '' ? '' : $pcr;
1.44      ng       3582: 	    my $score;
                   3583: 	    if ($partial eq '') {
1.257     albertel 3584: 		$score = $scoreptr{$env{'form.GD_'.$user.'_'.$_.'_solved_s'}};
1.44      ng       3585: 	    } elsif ($partial > 0) {
                   3586: 		$score = 'correct_by_override';
                   3587: 	    } elsif ($partial == 0) {
                   3588: 		$score = 'incorrect_by_override';
                   3589: 	    }
1.257     albertel 3590: 	    my $dropMenu = $env{'form.GD_'.$user.'_'.$_.'_solved'};
1.125     ng       3591: 	    $score = 'excused' if (($dropMenu eq 'excused') && ($score ne 'excused'));
                   3592: 
1.292     albertel 3593: 	    $newrecord{'resource.'.$_.'.regrader'}=
                   3594: 		"$env{'user.name'}:$env{'user.domain'}";
1.125     ng       3595: 	    if ($dropMenu eq 'reset status' &&
                   3596: 		$old_score ne '') { # ignore if no previous attempts => nothing to reset
1.299     albertel 3597: 		$newrecord{'resource.'.$_.'.tries'} = '';
1.125     ng       3598: 		$newrecord{'resource.'.$_.'.solved'} = '';
                   3599: 		$newrecord{'resource.'.$_.'.award'} = '';
1.299     albertel 3600: 		$newrecord{'resource.'.$_.'.awarded'} = '';
1.125     ng       3601: 		$updateflag = 1;
1.269     raeburn  3602:                 if ($env{'form.GD_'.$user.'_'.$_.'_aggtries'} > 0) {
                   3603:                     my $aggtries = $env{'form.GD_'.$user.'_'.$_.'_aggtries'};
                   3604:                     my $totaltries = $env{'form.GD_'.$user.'_'.$_.'_totaltries'};
                   3605:                     my $solvedstatus = $env{'form.GD_'.$user.'_'.$_.'_solved_s'};
                   3606:                     &decrement_aggs($symb,$_,\%aggregate,$aggtries,$totaltries,$solvedstatus);
                   3607:                     $aggregateflag = 1;
                   3608:                 }
1.139     albertel 3609: 	    } elsif (!($old_part eq $partial && $old_score eq $score)) {
                   3610: 		$updateflag = 1;
                   3611: 		$newrecord{'resource.'.$_.'.awarded'}  = $partial if $partial ne '';
                   3612: 		$newrecord{'resource.'.$_.'.solved'}   = $score;
                   3613: 		$rec_update++;
1.125     ng       3614: 	    }
                   3615: 
1.93      albertel 3616: 	    $line .= '<td align="center">'.$old_aw.'&nbsp;</td>'.
1.44      ng       3617: 		'<td align="center">'.$awarded.
                   3618: 		($score eq 'excused' ? $score : '').'&nbsp;</td>';
1.5       albertel 3619: 
1.54      albertel 3620: 
                   3621: 	    my $partid=$_;
                   3622: 	    foreach my $stores (@parts) {
                   3623: 		my ($part,$type) = &split_part_type($stores);
                   3624: 		if ($part !~ m/^\Q$partid\E/) { next;}
                   3625: 		if ($type eq 'awarded' || $type eq 'solved') { next; }
1.257     albertel 3626: 		my $old_aw    = $env{'form.GD_'.$user.'_'.$part.'_'.$type.'_s'};
                   3627: 		my $awarded   = $env{'form.GD_'.$user.'_'.$part.'_'.$type};
1.54      albertel 3628: 		if ($awarded ne '' && $awarded ne $old_aw) {
                   3629: 		    $newrecord{'resource.'.$part.'.'.$type}= $awarded;
1.257     albertel 3630: 		    $newrecord{'resource.'.$part.'.regrader'}="$env{'user.name'}:$env{'user.domain'}";
1.54      albertel 3631: 		    $updateflag=1;
                   3632: 		}
1.93      albertel 3633: 		$line .= '<td align="center">'.$old_aw.'&nbsp;</td>'.
1.54      albertel 3634: 		    '<td align="center">'.$awarded.'&nbsp;</td>';
                   3635: 	    }
1.44      ng       3636: 	}
1.477     albertel 3637: 	$line.="\n";
1.301     albertel 3638: 
                   3639: 	my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   3640: 	my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   3641: 
1.44      ng       3642: 	if ($updateflag) {
                   3643: 	    $count++;
1.257     albertel 3644: 	    &Apache::lonnet::cstore(\%newrecord,$symb,$env{'request.course.id'},
1.89      albertel 3645: 				    $udom,$uname);
1.301     albertel 3646: 
                   3647: 	    if (&Apache::bridgetask::in_queue('gradingqueue',$symb,$cdom,
                   3648: 					      $cnum,$udom,$uname)) {
                   3649: 		# need to figure out if should be in queue.
                   3650: 		my %record =  
                   3651: 		    &Apache::lonnet::restore($symb,$env{'request.course.id'},
                   3652: 					     $udom,$uname);
                   3653: 		my $all_graded = 1;
                   3654: 		my $none_graded = 1;
                   3655: 		foreach my $part (@parts) {
                   3656: 		    if ( $record{'resource.'.$part.'.awarded'} eq '' ) {
                   3657: 			$all_graded = 0;
                   3658: 		    } else {
                   3659: 			$none_graded = 0;
                   3660: 		    }
                   3661: 		}
                   3662: 
                   3663: 		if ($all_graded || $none_graded) {
                   3664: 		    &Apache::bridgetask::remove_from_queue('gradingqueue',
                   3665: 							   $symb,$cdom,$cnum,
                   3666: 							   $udom,$uname);
                   3667: 		}
                   3668: 	    }
                   3669: 
1.477     albertel 3670: 	    $result.=&Apache::loncommon::start_data_table_row().
                   3671: 		'<td align="right">&nbsp;'.$updateCtr.'&nbsp;</td>'.$line.
                   3672: 		&Apache::loncommon::end_data_table_row();
1.126     ng       3673: 	    $updateCtr++;
1.93      albertel 3674: 	} else {
1.477     albertel 3675: 	    push(@noupdate,
                   3676: 		 '<td align="right">&nbsp;'.$noupdateCtr.'&nbsp;</td>'.$line);
1.126     ng       3677: 	    $noupdateCtr++;
1.44      ng       3678: 	}
1.269     raeburn  3679:         if ($aggregateflag) {
                   3680:             &Apache::lonnet::cinc('nohist_resourcetracker',\%aggregate,
1.301     albertel 3681: 				  $cdom,$cnum);
1.269     raeburn  3682:         }
1.93      albertel 3683:     }
1.477     albertel 3684:     if (@noupdate) {
1.126     ng       3685: #	my $numcols=(scalar(@partid)*(scalar(@parts)-1)*2)+3;
                   3686: 	my $numcols=scalar(@partid)*4+2;
1.477     albertel 3687: 	$result .= &Apache::loncommon::start_data_table_row('LC_empty_row').
1.478     albertel 3688: 	    '<td align="center" colspan="'.$numcols.'">'.
                   3689: 	    &mt('No Changes Occurred For the Students Below').
                   3690: 	    '</td>'.
1.477     albertel 3691: 	    &Apache::loncommon::end_data_table_row();
                   3692: 	foreach my $line (@noupdate) {
                   3693: 	    $result.=
                   3694: 		&Apache::loncommon::start_data_table_row().
                   3695: 		$line.
                   3696: 		&Apache::loncommon::end_data_table_row();
                   3697: 	}
1.44      ng       3698:     }
1.614     www      3699:     $result .= &Apache::loncommon::end_data_table();
1.478     albertel 3700:     my $msg = '<p><b>'.
                   3701: 	&mt('Number of records updated = [_1] for [quant,_2,student].',
                   3702: 	    $rec_update,$count).'</b><br />'.
                   3703: 	'<b>'.&mt('Total number of students = [_1]',$env{'form.total'}).
                   3704: 	'</b></p>';
1.44      ng       3705:     return $title.$msg.$result;
1.5       albertel 3706: }
1.54      albertel 3707: 
                   3708: sub split_part_type {
                   3709:     my ($partstr) = @_;
                   3710:     my ($temp,@allparts)=split(/_/,$partstr);
                   3711:     my $type=pop(@allparts);
1.439     albertel 3712:     my $part=join('_',@allparts);
1.54      albertel 3713:     return ($part,$type);
                   3714: }
                   3715: 
1.44      ng       3716: #------------- end of section for handling grading by section/class ---------
                   3717: #
                   3718: #----------------------------------------------------------------------------
                   3719: 
1.5       albertel 3720: 
1.44      ng       3721: #----------------------------------------------------------------------------
                   3722: #
                   3723: #-------------------------- Next few routines handles grading by csv upload
                   3724: #
                   3725: #--- Javascript to handle csv upload
1.27      albertel 3726: sub csvupload_javascript_reverse_associate {
1.573     bisitz   3727:     my $error1=&mt('You need to specify the username or the student/employee ID');
1.246     albertel 3728:     my $error2=&mt('You need to specify at least one grading field');
1.27      albertel 3729:   return(<<ENDPICK);
                   3730:   function verify(vf) {
                   3731:     var foundsomething=0;
                   3732:     var founduname=0;
1.243     albertel 3733:     var foundID=0;
1.27      albertel 3734:     for (i=0;i<=vf.nfields.value;i++) {
                   3735:       tw=eval('vf.f'+i+'.selectedIndex');
1.243     albertel 3736:       if (i==0 && tw!=0) { foundID=1; }
                   3737:       if (i==1 && tw!=0) { founduname=1; }
                   3738:       if (i!=0 && i!=1 && i!=2 && tw!=0) { foundsomething=1; }
1.27      albertel 3739:     }
1.246     albertel 3740:     if (founduname==0 && foundID==0) {
                   3741: 	alert('$error1');
                   3742: 	return;
1.27      albertel 3743:     }
                   3744:     if (foundsomething==0) {
1.246     albertel 3745: 	alert('$error2');
                   3746: 	return;
1.27      albertel 3747:     }
                   3748:     vf.submit();
                   3749:   }
                   3750:   function flip(vf,tf) {
                   3751:     var nw=eval('vf.f'+tf+'.selectedIndex');
                   3752:     var i;
                   3753:     for (i=0;i<=vf.nfields.value;i++) {
                   3754:       //can not pick the same destination field for both name and domain
                   3755:       if (((i ==0)||(i ==1)) && 
                   3756:           ((tf==0)||(tf==1)) && 
                   3757:           (i!=tf) &&
                   3758:           (eval('vf.f'+i+'.selectedIndex')==nw)) {
                   3759:         eval('vf.f'+i+'.selectedIndex=0;')
                   3760:       }
                   3761:     }
                   3762:   }
                   3763: ENDPICK
                   3764: }
                   3765: 
                   3766: sub csvupload_javascript_forward_associate {
1.573     bisitz   3767:     my $error1=&mt('You need to specify the username or the student/employee ID');
1.246     albertel 3768:     my $error2=&mt('You need to specify at least one grading field');
1.27      albertel 3769:   return(<<ENDPICK);
                   3770:   function verify(vf) {
                   3771:     var foundsomething=0;
                   3772:     var founduname=0;
1.243     albertel 3773:     var foundID=0;
1.27      albertel 3774:     for (i=0;i<=vf.nfields.value;i++) {
                   3775:       tw=eval('vf.f'+i+'.selectedIndex');
1.243     albertel 3776:       if (tw==1) { foundID=1; }
                   3777:       if (tw==2) { founduname=1; }
                   3778:       if (tw>3) { foundsomething=1; }
1.27      albertel 3779:     }
1.246     albertel 3780:     if (founduname==0 && foundID==0) {
                   3781: 	alert('$error1');
                   3782: 	return;
1.27      albertel 3783:     }
                   3784:     if (foundsomething==0) {
1.246     albertel 3785: 	alert('$error2');
                   3786: 	return;
1.27      albertel 3787:     }
                   3788:     vf.submit();
                   3789:   }
                   3790:   function flip(vf,tf) {
                   3791:     var nw=eval('vf.f'+tf+'.selectedIndex');
                   3792:     var i;
                   3793:     //can not pick the same destination field twice
                   3794:     for (i=0;i<=vf.nfields.value;i++) {
                   3795:       if ((i!=tf) && (eval('vf.f'+i+'.selectedIndex')==nw)) {
                   3796:         eval('vf.f'+i+'.selectedIndex=0;')
                   3797:       }
                   3798:     }
                   3799:   }
                   3800: ENDPICK
                   3801: }
                   3802: 
1.26      albertel 3803: sub csvuploadmap_header {
1.324     albertel 3804:     my ($request,$symb,$datatoken,$distotal)= @_;
1.41      ng       3805:     my $javascript;
1.257     albertel 3806:     if ($env{'form.upfile_associate'} eq 'reverse') {
1.41      ng       3807: 	$javascript=&csvupload_javascript_reverse_associate();
                   3808:     } else {
                   3809: 	$javascript=&csvupload_javascript_forward_associate();
                   3810:     }
1.45      ng       3811: 
1.598     www      3812:     my $result='';
1.257     albertel 3813:     my $checked=(($env{'form.noFirstLine'})?' checked="checked"':'');
1.245     albertel 3814:     my $ignore=&mt('Ignore First Line');
1.418     albertel 3815:     $symb = &Apache::lonenc::check_encrypt($symb);
1.41      ng       3816:     $request->print(<<ENDPICK);
1.26      albertel 3817: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="gradesupload">
1.398     albertel 3818: <h3><span class="LC_info">Uploading Class Grades</span></h3>
1.45      ng       3819: $result
1.326     albertel 3820: <hr />
1.26      albertel 3821: <h3>Identify fields</h3>
                   3822: Total number of records found in file: $distotal <hr />
                   3823: Enter as many fields as you can. The system will inform you and bring you back
                   3824: to this page if the data selected is insufficient to run your class.<hr />
1.589     bisitz   3825: <input type="button" value="Reverse Association" onclick="javascript:this.form.associate.value='Reverse Association';submit(this.form);" />
1.245     albertel 3826: <label><input type="checkbox" name="noFirstLine" $checked />$ignore</label>
1.26      albertel 3827: <input type="hidden" name="associate"  value="" />
                   3828: <input type="hidden" name="phase"      value="three" />
                   3829: <input type="hidden" name="datatoken"  value="$datatoken" />
1.257     albertel 3830: <input type="hidden" name="fileupload" value="$env{'form.fileupload'}" />
                   3831: <input type="hidden" name="upfiletype" value="$env{'form.upfiletype'}" />
1.26      albertel 3832: <input type="hidden" name="upfile_associate" 
1.257     albertel 3833:                                        value="$env{'form.upfile_associate'}" />
1.26      albertel 3834: <input type="hidden" name="symb"       value="$symb" />
1.246     albertel 3835: <input type="hidden" name="command"    value="csvuploadoptions" />
1.26      albertel 3836: <hr />
                   3837: ENDPICK
1.597     wenzelju 3838:     $request->print(&Apache::lonhtmlcommon::scripttag($javascript));
1.118     ng       3839:     return '';
1.26      albertel 3840: 
                   3841: }
                   3842: 
                   3843: sub csvupload_fields {
1.582     raeburn  3844:     my ($symb,$errorref) = @_;
                   3845:     my (@parts) = &getpartlist($symb,$errorref);
                   3846:     if (ref($errorref)) {
                   3847:         if ($$errorref) {
                   3848:             return;
                   3849:         }
                   3850:     }
                   3851: 
1.556     weissno  3852:     my @fields=(['ID','Student/Employee ID'],
1.243     albertel 3853: 		['username','Student Username'],
                   3854: 		['domain','Student Domain']);
1.324     albertel 3855:     my (undef,undef,$url) = &Apache::lonnet::decode_symb($symb);
1.41      ng       3856:     foreach my $part (sort(@parts)) {
                   3857: 	my @datum;
                   3858: 	my $display=&Apache::lonnet::metadata($url,$part.'.display');
                   3859: 	my $name=$part;
                   3860: 	if  (!$display) { $display = $name; }
                   3861: 	@datum=($name,$display);
1.244     albertel 3862: 	if ($name=~/^stores_(.*)_awarded/) {
                   3863: 	    push(@fields,['stores_'.$1.'_points',"Points [Part: $1]"]);
                   3864: 	}
1.41      ng       3865: 	push(@fields,\@datum);
                   3866:     }
                   3867:     return (@fields);
1.26      albertel 3868: }
                   3869: 
                   3870: sub csvuploadmap_footer {
1.41      ng       3871:     my ($request,$i,$keyfields) =@_;
                   3872:     $request->print(<<ENDPICK);
1.26      albertel 3873: </table>
                   3874: <input type="hidden" name="nfields" value="$i" />
                   3875: <input type="hidden" name="keyfields" value="$keyfields" />
1.589     bisitz   3876: <input type="button" onclick="javascript:verify(this.form)" value="Assign Grades" /><br />
1.26      albertel 3877: </form>
                   3878: ENDPICK
                   3879: }
                   3880: 
1.283     albertel 3881: sub checkforfile_js {
1.539     riegler  3882:     my $alertmsg = &mt('Please use the browse button to select a file from your local directory.');
1.597     wenzelju 3883:     my $result = &Apache::lonhtmlcommon::scripttag(<<CSVFORMJS);
1.86      ng       3884:     function checkUpload(formname) {
                   3885: 	if (formname.upfile.value == "") {
1.539     riegler  3886: 	    alert("$alertmsg");
1.86      ng       3887: 	    return false;
                   3888: 	}
                   3889: 	formname.submit();
                   3890:     }
                   3891: CSVFORMJS
1.283     albertel 3892:     return $result;
                   3893: }
                   3894: 
                   3895: sub upcsvScores_form {
1.608     www      3896:     my ($request,$symb) = @_;
1.283     albertel 3897:     if (!$symb) {return '';}
                   3898:     my $result=&checkforfile_js();
1.326     albertel 3899:     $result.='<br /><table width="100%" border="0"><tr><td bgcolor="#777777">'."\n";
                   3900:     $result.='<table width="100%" border="0"><tr bgcolor="#e6ffff"><td>'."\n";
1.538     schulted 3901:     $result.='&nbsp;<b>'.&mt('Specify a file containing the class scores for current resource.').
                   3902: 	'</b></td></tr>'."\n";
1.86      ng       3903:     $result.='<tr bgcolor=#ffffe6><td>'."\n";
1.370     www      3904:     my $upload=&mt("Upload Scores");
1.86      ng       3905:     my $upfile_select=&Apache::loncommon::upfile_select_html();
1.245     albertel 3906:     my $ignore=&mt('Ignore First Line');
1.418     albertel 3907:     $symb = &Apache::lonenc::check_encrypt($symb);
1.86      ng       3908:     $result.=<<ENDUPFORM;
1.106     albertel 3909: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="gradesupload">
1.86      ng       3910: <input type="hidden" name="symb" value="$symb" />
                   3911: <input type="hidden" name="command" value="csvuploadmap" />
                   3912: $upfile_select
1.589     bisitz   3913: <br /><input type="button" onclick="javascript:checkUpload(this.form);" value="$upload" />
1.283     albertel 3914: <label><input type="checkbox" name="noFirstLine" />$ignore</label>
1.86      ng       3915: </form>
                   3916: ENDUPFORM
1.370     www      3917:     $result.=&Apache::loncommon::help_open_topic("Course_Convert_To_CSV",
                   3918:                            &mt("How do I create a CSV file from a spreadsheet"))
                   3919:     .'</td></tr></table>'."\n";
1.86      ng       3920:     $result.='</td></tr></table><br /><br />'."\n";
                   3921:     return $result;
                   3922: }
                   3923: 
                   3924: 
1.26      albertel 3925: sub csvuploadmap {
1.608     www      3926:     my ($request,$symb)= @_;
1.41      ng       3927:     if (!$symb) {return '';}
1.72      ng       3928: 
1.41      ng       3929:     my $datatoken;
1.257     albertel 3930:     if (!$env{'form.datatoken'}) {
1.41      ng       3931: 	$datatoken=&Apache::loncommon::upfile_store($request);
1.26      albertel 3932:     } else {
1.257     albertel 3933: 	$datatoken=$env{'form.datatoken'};
1.41      ng       3934: 	&Apache::loncommon::load_tmp_file($request);
1.26      albertel 3935:     }
1.41      ng       3936:     my @records=&Apache::loncommon::upfile_record_sep();
1.257     albertel 3937:     if ($env{'form.noFirstLine'}) { shift(@records); }
1.324     albertel 3938:     &csvuploadmap_header($request,$symb,$datatoken,$#records+1);
1.41      ng       3939:     my ($i,$keyfields);
                   3940:     if (@records) {
1.582     raeburn  3941:         my $fieldserror;
                   3942: 	my @fields=&csvupload_fields($symb,\$fieldserror);
                   3943:         if ($fieldserror) {
                   3944:             $request->print(&navmap_errormsg());
                   3945:             return;
                   3946:         }
1.257     albertel 3947: 	if ($env{'form.upfile_associate'} eq 'reverse') {	
1.41      ng       3948: 	    &Apache::loncommon::csv_print_samples($request,\@records);
                   3949: 	    $i=&Apache::loncommon::csv_print_select_table($request,\@records,
                   3950: 							  \@fields);
                   3951: 	    foreach (@fields) { $keyfields.=$_->[0].','; }
                   3952: 	    chop($keyfields);
                   3953: 	} else {
                   3954: 	    unshift(@fields,['none','']);
                   3955: 	    $i=&Apache::loncommon::csv_samples_select_table($request,\@records,
                   3956: 							    \@fields);
1.311     banghart 3957:             foreach my $rec (@records) {
                   3958:                 my %temp = &Apache::loncommon::record_sep($rec);
                   3959:                 if (%temp) {
                   3960:                     $keyfields=join(',',sort(keys(%temp)));
                   3961:                     last;
                   3962:                 }
                   3963:             }
1.41      ng       3964: 	}
                   3965:     }
                   3966:     &csvuploadmap_footer($request,$i,$keyfields);
1.72      ng       3967: 
1.41      ng       3968:     return '';
1.27      albertel 3969: }
                   3970: 
1.246     albertel 3971: sub csvuploadoptions {
1.608     www      3972:     my ($request,$symb)= @_;
1.257     albertel 3973:     my $checked=(($env{'form.noFirstLine'})?'1':'0');
1.246     albertel 3974:     my $ignore=&mt('Ignore First Line');
                   3975:     $request->print(<<ENDPICK);
                   3976: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="gradesupload">
1.398     albertel 3977: <h3><span class="LC_info">Uploading Class Grade Options</span></h3>
1.246     albertel 3978: <input type="hidden" name="command"    value="csvuploadassign" />
1.302     albertel 3979: <!--
1.246     albertel 3980: <p>
                   3981: <label>
                   3982:    <input type="checkbox" name="show_full_results" />
                   3983:    Show a table of all changes
                   3984: </label>
                   3985: </p>
1.302     albertel 3986: -->
1.246     albertel 3987: <p>
                   3988: <label>
                   3989:    <input type="checkbox" name="overwite_scores" checked="checked" />
                   3990:    Overwrite any existing score
                   3991: </label>
                   3992: </p>
                   3993: ENDPICK
                   3994:     my %fields=&get_fields();
                   3995:     if (!defined($fields{'domain'})) {
1.257     albertel 3996: 	my $domform = &Apache::loncommon::select_dom_form($env{'request.role.domain'},'default_domain');
1.246     albertel 3997: 	$request->print("\n<p> Users are in domain: ".$domform."</p>\n");
                   3998:     }
1.257     albertel 3999:     foreach my $key (sort(keys(%env))) {
1.246     albertel 4000: 	if ($key !~ /^form\.(.*)$/) { next; }
                   4001: 	my $cleankey=$1;
                   4002: 	if ($cleankey eq 'command') { next; }
                   4003: 	$request->print('<input type="hidden" name="'.$cleankey.
1.257     albertel 4004: 			'"  value="'.$env{$key}.'" />'."\n");
1.246     albertel 4005:     }
                   4006:     # FIXME do a check for any duplicated user ids...
                   4007:     # FIXME do a check for any invalid user ids?...
1.290     albertel 4008:     $request->print('<input type="submit" value="Assign Grades" /><br />
                   4009: <hr /></form>'."\n");
1.246     albertel 4010:     return '';
                   4011: }
                   4012: 
                   4013: sub get_fields {
                   4014:     my %fields;
1.257     albertel 4015:     my @keyfields = split(/\,/,$env{'form.keyfields'});
                   4016:     for (my $i=0; $i<=$env{'form.nfields'}; $i++) {
                   4017: 	if ($env{'form.upfile_associate'} eq 'reverse') {
                   4018: 	    if ($env{'form.f'.$i} ne 'none') {
                   4019: 		$fields{$keyfields[$i]}=$env{'form.f'.$i};
1.41      ng       4020: 	    }
                   4021: 	} else {
1.257     albertel 4022: 	    if ($env{'form.f'.$i} ne 'none') {
                   4023: 		$fields{$env{'form.f'.$i}}=$keyfields[$i];
1.41      ng       4024: 	    }
                   4025: 	}
1.27      albertel 4026:     }
1.246     albertel 4027:     return %fields;
                   4028: }
                   4029: 
                   4030: sub csvuploadassign {
1.608     www      4031:     my ($request,$symb)= @_;
1.246     albertel 4032:     if (!$symb) {return '';}
1.345     bowersj2 4033:     my $error_msg = '';
1.246     albertel 4034:     &Apache::loncommon::load_tmp_file($request);
                   4035:     my @gradedata = &Apache::loncommon::upfile_record_sep();
1.257     albertel 4036:     if ($env{'form.noFirstLine'}) { shift(@gradedata); }
1.246     albertel 4037:     my %fields=&get_fields();
1.41      ng       4038:     $request->print('<h3>Assigning Grades</h3>');
1.257     albertel 4039:     my $courseid=$env{'request.course.id'};
1.97      albertel 4040:     my ($classlist) = &getclasslist('all',0);
1.106     albertel 4041:     my @notallowed;
1.41      ng       4042:     my @skipped;
                   4043:     my $countdone=0;
                   4044:     foreach my $grade (@gradedata) {
                   4045: 	my %entries=&Apache::loncommon::record_sep($grade);
1.246     albertel 4046: 	my $domain;
                   4047: 	if ($entries{$fields{'domain'}}) {
                   4048: 	    $domain=$entries{$fields{'domain'}};
                   4049: 	} else {
1.257     albertel 4050: 	    $domain=$env{'form.default_domain'};
1.246     albertel 4051: 	}
1.243     albertel 4052: 	$domain=~s/\s//g;
1.41      ng       4053: 	my $username=$entries{$fields{'username'}};
1.160     albertel 4054: 	$username=~s/\s//g;
1.243     albertel 4055: 	if (!$username) {
                   4056: 	    my $id=$entries{$fields{'ID'}};
1.247     albertel 4057: 	    $id=~s/\s//g;
1.243     albertel 4058: 	    my %ids=&Apache::lonnet::idget($domain,$id);
                   4059: 	    $username=$ids{$id};
                   4060: 	}
1.41      ng       4061: 	if (!exists($$classlist{"$username:$domain"})) {
1.247     albertel 4062: 	    my $id=$entries{$fields{'ID'}};
                   4063: 	    $id=~s/\s//g;
                   4064: 	    if ($id) {
                   4065: 		push(@skipped,"$id:$domain");
                   4066: 	    } else {
                   4067: 		push(@skipped,"$username:$domain");
                   4068: 	    }
1.41      ng       4069: 	    next;
                   4070: 	}
1.108     albertel 4071: 	my $usec=$classlist->{"$username:$domain"}[5];
1.106     albertel 4072: 	if (!&canmodify($usec)) {
                   4073: 	    push(@notallowed,"$username:$domain");
                   4074: 	    next;
                   4075: 	}
1.244     albertel 4076: 	my %points;
1.41      ng       4077: 	my %grades;
                   4078: 	foreach my $dest (keys(%fields)) {
1.244     albertel 4079: 	    if ($dest eq 'ID' || $dest eq 'username' ||
                   4080: 		$dest eq 'domain') { next; }
                   4081: 	    if ($entries{$fields{$dest}} =~ /^\s*$/) { next; }
                   4082: 	    if ($dest=~/stores_(.*)_points/) {
                   4083: 		my $part=$1;
                   4084: 		my $wgt =&Apache::lonnet::EXT('resource.'.$part.'.weight',
                   4085: 					      $symb,$domain,$username);
1.345     bowersj2 4086:                 if ($wgt) {
                   4087:                     $entries{$fields{$dest}}=~s/\s//g;
                   4088:                     my $pcr=$entries{$fields{$dest}} / $wgt;
1.463     albertel 4089:                     my $award=($pcr == 0) ? 'incorrect_by_override'
                   4090:                                           : 'correct_by_override';
1.345     bowersj2 4091:                     $grades{"resource.$part.awarded"}=$pcr;
                   4092:                     $grades{"resource.$part.solved"}=$award;
                   4093:                     $points{$part}=1;
                   4094:                 } else {
                   4095:                     $error_msg = "<br />" .
                   4096:                         &mt("Some point values were assigned"
                   4097:                             ." for problems with a weight "
                   4098:                             ."of zero. These values were "
                   4099:                             ."ignored.");
                   4100:                 }
1.244     albertel 4101: 	    } else {
                   4102: 		if ($dest=~/stores_(.*)_awarded/) { if ($points{$1}) {next;} }
                   4103: 		if ($dest=~/stores_(.*)_solved/)  { if ($points{$1}) {next;} }
                   4104: 		my $store_key=$dest;
                   4105: 		$store_key=~s/^stores/resource/;
                   4106: 		$store_key=~s/_/\./g;
                   4107: 		$grades{$store_key}=$entries{$fields{$dest}};
                   4108: 	    }
1.41      ng       4109: 	}
1.508     www      4110: 	if (! %grades) { 
                   4111:            push(@skipped,&mt("[_1]: no data to save","$username:$domain")); 
                   4112:         } else {
                   4113: 	   $grades{"resource.regrader"}="$env{'user.name'}:$env{'user.domain'}";
                   4114: 	   my $result=&Apache::lonnet::cstore(\%grades,$symb,
1.302     albertel 4115: 					   $env{'request.course.id'},
                   4116: 					   $domain,$username);
1.508     www      4117: 	   if ($result eq 'ok') {
                   4118: 	      $request->print('.');
                   4119: 	   } else {
                   4120: 	      $request->print("<p><span class=\"LC_error\">".
                   4121:                               &mt("Failed to save data for student [_1]. Message when trying to save was: [_2]",
                   4122:                                   "$username:$domain",$result)."</span></p>");
                   4123: 	   }
                   4124: 	   $request->rflush();
                   4125: 	   $countdone++;
                   4126:         }
1.41      ng       4127:     }
1.570     www      4128:     $request->print('<br />'.&Apache::lonhtmlcommon::confirm_success(&mt("Saved scores for [quant,_1,student]",$countdone),$countdone==0));
1.41      ng       4129:     if (@skipped) {
1.571     www      4130: 	$request->print('<br />'.&Apache::lonhtmlcommon::confirm_success(&mt('No scores stored for the following username(s):'),1).'<br />');
                   4131:         $request->print(join(', ',@skipped));
1.106     albertel 4132:     }
                   4133:     if (@notallowed) {
1.571     www      4134: 	$request->print('<br />'.&Apache::lonhtmlcommon::confirm_success(&mt('Modification of scores not allowed for the following username(s):'),1).'<br />');
                   4135: 	$request->print(join(', ',@notallowed));
1.41      ng       4136:     }
1.106     albertel 4137:     $request->print("<br />\n");
1.345     bowersj2 4138:     return $error_msg;
1.26      albertel 4139: }
1.44      ng       4140: #------------- end of section for handling csv file upload ---------
                   4141: #
                   4142: #-------------------------------------------------------------------
                   4143: #
1.122     ng       4144: #-------------- Next few routines handle grading by page/sequence
1.72      ng       4145: #
                   4146: #--- Select a page/sequence and a student to grade
1.68      ng       4147: sub pickStudentPage {
1.608     www      4148:     my ($request,$symb) = @_;
1.68      ng       4149: 
1.539     riegler  4150:     my $alertmsg = &mt('Please select the student you wish to grade.');
1.597     wenzelju 4151:     $request->print(&Apache::lonhtmlcommon::scripttag(<<LISTJAVASCRIPT));
1.68      ng       4152: 
                   4153: function checkPickOne(formname) {
1.76      ng       4154:     if (radioSelection(formname.student) == null) {
1.539     riegler  4155: 	alert("$alertmsg");
1.68      ng       4156: 	return;
                   4157:     }
1.125     ng       4158:     ptr = pullDownSelection(formname.selectpage);
                   4159:     formname.page.value = formname["page"+ptr].value;
                   4160:     formname.title.value = formname["title"+ptr].value;
1.68      ng       4161:     formname.submit();
                   4162: }
                   4163: 
                   4164: LISTJAVASCRIPT
1.118     ng       4165:     &commonJSfunctions($request);
1.608     www      4166: 
1.257     albertel 4167:     my $cdom      = $env{"course.$env{'request.course.id'}.domain"};
                   4168:     my $cnum      = $env{"course.$env{'request.course.id'}.num"};
                   4169:     my $getsec    = $env{'form.section'} eq '' ? 'all' : $env{'form.section'};
1.68      ng       4170: 
1.398     albertel 4171:     my $result='<h3><span class="LC_info">&nbsp;'.
1.485     albertel 4172: 	&mt('Manual Grading by Page or Sequence').'</span></h3>';
1.68      ng       4173: 
1.80      ng       4174:     $result.='<form action="/adm/grades" method="post" name="displayPage">'."\n";
1.582     raeburn  4175:     my $map_error;
                   4176:     my ($titles,$symbx) = &getSymbMap($map_error);
                   4177:     if ($map_error) {
                   4178:         $request->print(&navmap_errormsg());
                   4179:         return; 
                   4180:     }
1.137     albertel 4181:     my ($curpage) =&Apache::lonnet::decode_symb($symb); 
                   4182: #    my ($curpage,$mapId) =&Apache::lonnet::decode_symb($symb); 
                   4183: #    my $type=($curpage =~ /\.(page|sequence)/);
1.485     albertel 4184:     my $select = '<select name="selectpage">'."\n";
1.70      ng       4185:     my $ctr=0;
1.68      ng       4186:     foreach (@$titles) {
                   4187: 	my ($minder,$showtitle) = ($_ =~ /(\d+)\.(.*)/);
1.485     albertel 4188: 	$select.='<option value="'.$ctr.'" '.
1.401     albertel 4189: 	    ($$symbx{$_} =~ /$curpage$/ ? 'selected="selected"' : '').
1.71      ng       4190: 	    '>'.$showtitle.'</option>'."\n";
1.70      ng       4191: 	$ctr++;
1.68      ng       4192:     }
1.485     albertel 4193:     $select.= '</select>';
1.539     riegler  4194:     $result.='&nbsp;<b>'.&mt('Problems from').':</b> '.$select."<br />\n";
1.485     albertel 4195: 
1.70      ng       4196:     $ctr=0;
                   4197:     foreach (@$titles) {
                   4198: 	my ($minder,$showtitle) = ($_ =~ /(\d+)\.(.*)/);
                   4199: 	$result.='<input type="hidden" name="page'.$ctr.'" value="'.$$symbx{$_}.'" />'."\n";
                   4200: 	$result.='<input type="hidden" name="title'.$ctr.'" value="'.$showtitle.'" />'."\n";
                   4201: 	$ctr++;
                   4202:     }
1.72      ng       4203:     $result.='<input type="hidden" name="page" />'."\n".
                   4204: 	'<input type="hidden" name="title" />'."\n";
1.68      ng       4205: 
1.485     albertel 4206:     my $options =
                   4207: 	'<label><input type="radio" name="vProb" value="no" checked="checked" /> '.&mt('no').' </label>'."\n".
                   4208: 	'<label><input type="radio" name="vProb" value="yes" /> '.&mt('yes').' </label>'."<br />\n";
1.539     riegler  4209:     $result.='&nbsp;<b>'.&mt('View Problem Text').': </b>'.$options;
1.485     albertel 4210: 
                   4211:     $options =
                   4212: 	'<label><input type="radio" name="lastSub" value="none" /> '.&mt('none').' </label>'."\n".
                   4213: 	'<label><input type="radio" name="lastSub" value="datesub" checked="checked" /> '.&mt('by dates and submissions').'</label>'."\n".
                   4214: 	'<label><input type="radio" name="lastSub" value="all" /> '.&mt('all details').' </label>'."\n";
1.539     riegler  4215:     $result.='&nbsp;<b>'.&mt('Submissions').': </b>'.$options;
1.432     banghart 4216:     
                   4217:     $result.=&build_section_inputs();
1.442     banghart 4218:     my $stu_status = join(':',&Apache::loncommon::get_env_multiple('form.Status'));
                   4219:     $result.='<input type="hidden" name="Status"  value="'.$stu_status.'" />'."\n".
1.72      ng       4220: 	'<input type="hidden" name="command" value="displayPage" />'."\n".
1.613     www      4221: 	'<input type="hidden" name="symb"    value="'.&Apache::lonenc::check_encrypt($symb).'" />'."<br />\n";
1.72      ng       4222: 
1.539     riegler  4223:     $result.='&nbsp;<b>'.&mt('Use CODE').': </b> <input type="text" name="CODE" value="" /> <br />'."\n";
1.382     albertel 4224: 
1.80      ng       4225:     $result.='&nbsp;<input type="button" '.
1.589     bisitz   4226:              'onclick="javascript:checkPickOne(this.form);" value="'.&mt('Next').' &rarr;" /><br />'."\n";
1.72      ng       4227: 
1.68      ng       4228:     $request->print($result);
                   4229: 
1.485     albertel 4230:     my $studentTable.='&nbsp;<b>'.&mt('Select a student you wish to grade and then click on the Next button.').'</b><br />'.
1.484     albertel 4231: 	&Apache::loncommon::start_data_table().
                   4232: 	&Apache::loncommon::start_data_table_header_row().
1.485     albertel 4233: 	'<th align="right">&nbsp;'.&mt('No.').'</th>'.
1.484     albertel 4234: 	'<th>'.&nameUserString('header').'</th>'.
1.485     albertel 4235: 	'<th align="right">&nbsp;'.&mt('No.').'</th>'.
1.484     albertel 4236: 	'<th>'.&nameUserString('header').'</th>'.
                   4237: 	&Apache::loncommon::end_data_table_header_row();
1.68      ng       4238:  
1.76      ng       4239:     my (undef,undef,$fullname) = &getclasslist($getsec,'1');
1.68      ng       4240:     my $ptr = 1;
1.294     albertel 4241:     foreach my $student (sort 
                   4242: 			 {
                   4243: 			     if (lc($$fullname{$a}) ne lc($$fullname{$b})) {
                   4244: 				 return (lc($$fullname{$a}) cmp lc($$fullname{$b}));
                   4245: 			     }
                   4246: 			     return $a cmp $b;
                   4247: 			 } (keys(%$fullname))) {
1.68      ng       4248: 	my ($uname,$udom) = split(/:/,$student);
1.484     albertel 4249: 	$studentTable.=($ptr%2==1 ? &Apache::loncommon::start_data_table_row()
                   4250:                                   : '</td>');
1.126     ng       4251: 	$studentTable.='<td align="right">'.$ptr.'&nbsp;</td>';
1.288     albertel 4252: 	$studentTable.='<td>&nbsp;<label><input type="radio" name="student" value="'.$student.'" /> '
                   4253: 	    .&nameUserString(undef,$$fullname{$student},$uname,$udom)."</label>\n";
1.484     albertel 4254: 	$studentTable.=
                   4255: 	    ($ptr%2 == 0 ? '</td>'.&Apache::loncommon::end_data_table_row() 
                   4256:                          : '');
1.68      ng       4257: 	$ptr++;
                   4258:     }
1.484     albertel 4259:     if ($ptr%2 == 0) {
                   4260: 	$studentTable.='</td><td>&nbsp;</td><td>&nbsp;</td>'.
                   4261: 	    &Apache::loncommon::end_data_table_row();
                   4262:     }
                   4263:     $studentTable.=&Apache::loncommon::end_data_table()."\n";
1.126     ng       4264:     $studentTable.='<input type="button" '.
1.589     bisitz   4265:                    'onclick="javascript:checkPickOne(this.form);" value="'.&mt('Next').' &rarr;" /></form>'."\n";
1.68      ng       4266: 
                   4267:     $request->print($studentTable);
                   4268: 
                   4269:     return '';
                   4270: }
                   4271: 
                   4272: sub getSymbMap {
1.582     raeburn  4273:     my ($map_error) = @_;
1.132     bowersj2 4274:     my $navmap = Apache::lonnavmaps::navmap->new();
1.582     raeburn  4275:     unless (ref($navmap)) {
                   4276:         if (ref($map_error)) {
                   4277:             $$map_error = 'navmap';
                   4278:         }
                   4279:         return;
                   4280:     }
1.68      ng       4281:     my %symbx = ();
                   4282:     my @titles = ();
1.117     bowersj2 4283:     my $minder = 0;
                   4284: 
                   4285:     # Gather every sequence that has problems.
1.240     albertel 4286:     my @sequences = $navmap->retrieveResources(undef, sub { shift->is_map(); },
                   4287: 					       1,0,1);
1.117     bowersj2 4288:     for my $sequence ($navmap->getById('0.0'), @sequences) {
1.241     albertel 4289: 	if ($navmap->hasResource($sequence, sub { shift->is_problem(); }, 0) ) {
1.381     albertel 4290: 	    my $title = $minder.'.'.
                   4291: 		&HTML::Entities::encode($sequence->compTitle(),'"\'&');
                   4292: 	    push(@titles, $title); # minder in case two titles are identical
                   4293: 	    $symbx{$title} = &HTML::Entities::encode($sequence->symb(),'"\'&');
1.117     bowersj2 4294: 	    $minder++;
1.241     albertel 4295: 	}
1.68      ng       4296:     }
                   4297:     return \@titles,\%symbx;
                   4298: }
                   4299: 
1.72      ng       4300: #
                   4301: #--- Displays a page/sequence w/wo problems, w/wo submissions
1.68      ng       4302: sub displayPage {
1.608     www      4303:     my ($request,$symb) = @_;
1.257     albertel 4304:     my $cdom      = $env{"course.$env{'request.course.id'}.domain"};
                   4305:     my $cnum      = $env{"course.$env{'request.course.id'}.num"};
                   4306:     my $getsec    = $env{'form.section'} eq '' ? 'all' : $env{'form.section'};
                   4307:     my $pageTitle = $env{'form.page'};
1.103     albertel 4308:     my ($classlist,undef,$fullname) = &getclasslist($getsec,'1');
1.257     albertel 4309:     my ($uname,$udom) = split(/:/,$env{'form.student'});
                   4310:     my $usec=$classlist->{$env{'form.student'}}[5];
1.168     albertel 4311: 
                   4312:     #need to make sure we have the correct data for later EXT calls, 
                   4313:     #thus invalidate the cache
                   4314:     &Apache::lonnet::devalidatecourseresdata(
1.257     albertel 4315:                  $env{'course.'.$env{'request.course.id'}.'.num'},
                   4316:                  $env{'course.'.$env{'request.course.id'}.'.domain'});
1.168     albertel 4317:     &Apache::lonnet::clear_EXT_cache_status();
                   4318: 
1.103     albertel 4319:     if (!&canview($usec)) {
1.485     albertel 4320: 	$request->print('<span class="LC_warning">'.&mt('Unable to view requested student. ([_1])',$env{'form.student'}).'</span>');
1.103     albertel 4321: 	return;
                   4322:     }
1.398     albertel 4323:     my $result='<h3><span class="LC_info">&nbsp;'.$env{'form.title'}.'</span></h3>';
1.485     albertel 4324:     $result.='<h3>&nbsp;'.&mt('Student: [_1]',&nameUserString(undef,$$fullname{$env{'form.student'}},$uname,$udom)).
1.129     ng       4325: 	'</h3>'."\n";
1.500     albertel 4326:     $env{'form.CODE'} = uc($env{'form.CODE'});
1.501     foxr     4327:     if (&Apache::lonnet::validCODE(uc($env{'form.CODE'}))) {
1.485     albertel 4328: 	$result.='<h3>&nbsp;'.&mt('CODE: [_1]',$env{'form.CODE'}).'</h3>'."\n";
1.382     albertel 4329:     } else {
                   4330: 	delete($env{'form.CODE'});
                   4331:     }
1.71      ng       4332:     &sub_page_js($request);
                   4333:     $request->print($result);
                   4334: 
1.132     bowersj2 4335:     my $navmap = Apache::lonnavmaps::navmap->new();
1.582     raeburn  4336:     unless (ref($navmap)) {
                   4337:         $request->print(&navmap_errormsg());
                   4338:         return;
                   4339:     }
1.257     albertel 4340:     my ($mapUrl, $id, $resUrl)=&Apache::lonnet::decode_symb($env{'form.page'});
1.68      ng       4341:     my $map = $navmap->getResourceByUrl($resUrl); # add to navmaps
1.288     albertel 4342:     if (!$map) {
1.485     albertel 4343: 	$request->print('<span class="LC_warning">'.&mt('Unable to view requested sequence. ([_1])',$resUrl).'</span>');
1.288     albertel 4344: 	return; 
                   4345:     }
1.68      ng       4346:     my $iterator = $navmap->getIterator($map->map_start(),
                   4347: 					$map->map_finish());
                   4348: 
1.71      ng       4349:     my $studentTable='<form action="/adm/grades" method="post" name="gradePage">'."\n".
1.72      ng       4350: 	'<input type="hidden" name="command" value="gradeByPage" />'."\n".
1.257     albertel 4351: 	'<input type="hidden" name="fullname" value="'.$$fullname{$env{'form.student'}}.'" />'."\n".
                   4352: 	'<input type="hidden" name="student" value="'.$env{'form.student'}.'" />'."\n".
1.72      ng       4353: 	'<input type="hidden" name="page"    value="'.$pageTitle.'" />'."\n".
1.257     albertel 4354: 	'<input type="hidden" name="title"   value="'.$env{'form.title'}.'" />'."\n".
1.418     albertel 4355: 	'<input type="hidden" name="symb"    value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
1.613     www      4356: 	'<input type="hidden" name="overRideScore" value="no" />'."\n";
1.71      ng       4357: 
1.382     albertel 4358:     if (defined($env{'form.CODE'})) {
                   4359: 	$studentTable.=
                   4360: 	    '<input type="hidden" name="CODE" value="'.$env{'form.CODE'}.'" />'."\n";
                   4361:     }
1.381     albertel 4362:     my $checkIcon = '<img alt="'.&mt('Check Mark').
1.485     albertel 4363: 	'" src="'.&Apache::loncommon::lonhttpdurl($request->dir_config('lonIconsURL').'/check.gif').'" height="16" border="0" />';
1.71      ng       4364: 
1.594     bisitz   4365:     $studentTable.='&nbsp;<span class="LC_info">'.
                   4366:         &mt('Problems graded correct by the computer are marked with a [_1] symbol.',$checkIcon).
                   4367:         '</span>'."\n".
1.484     albertel 4368: 	&Apache::loncommon::start_data_table().
                   4369: 	&Apache::loncommon::start_data_table_header_row().
                   4370: 	'<th align="center">&nbsp;Prob.&nbsp;</th>'.
1.485     albertel 4371: 	'<th>&nbsp;'.($env{'form.vProb'} eq 'no' ? &mt('Title') : &mt('Problem Text')).'/'.&mt('Grade').'</th>'.
1.484     albertel 4372: 	&Apache::loncommon::end_data_table_header_row();
1.71      ng       4373: 
1.329     albertel 4374:     &Apache::lonxml::clear_problem_counter();
1.196     albertel 4375:     my ($depth,$question,$prob) = (1,1,1);
1.68      ng       4376:     $iterator->next(); # skip the first BEGIN_MAP
                   4377:     my $curRes = $iterator->next(); # for "current resource"
1.101     albertel 4378:     while ($depth > 0) {
1.68      ng       4379:         if($curRes == $iterator->BEGIN_MAP) { $depth++; }
1.100     bowersj2 4380:         if($curRes == $iterator->END_MAP) { $depth--; }
1.68      ng       4381: 
1.385     albertel 4382:         if (ref($curRes) && $curRes->is_problem()) {
1.91      albertel 4383: 	    my $parts = $curRes->parts();
1.68      ng       4384:             my $title = $curRes->compTitle();
1.71      ng       4385: 	    my $symbx = $curRes->symb();
1.484     albertel 4386: 	    $studentTable.=
                   4387: 		&Apache::loncommon::start_data_table_row().
                   4388: 		'<td align="center" valign="top" >'.$prob.
1.485     albertel 4389: 		(scalar(@{$parts}) == 1 ? '' 
                   4390: 		                        : '<br />('.&mt('[_1]&nbsp;parts)',
                   4391: 							scalar(@{$parts}))
                   4392: 		 ).
                   4393: 		 '</td>';
1.71      ng       4394: 	    $studentTable.='<td valign="top">';
1.382     albertel 4395: 	    my %form = ('CODE' => $env{'form.CODE'},);
1.257     albertel 4396: 	    if ($env{'form.vProb'} eq 'yes' ) {
1.144     albertel 4397: 		$studentTable.=&show_problem($request,$symbx,$uname,$udom,1,
1.383     albertel 4398: 					     undef,'both',\%form);
1.71      ng       4399: 	    } else {
1.382     albertel 4400: 		my $companswer = &Apache::loncommon::get_student_answers($symbx,$uname,$udom,$env{'request.course.id'},%form);
1.80      ng       4401: 		$companswer =~ s|<form(.*?)>||g;
                   4402: 		$companswer =~ s|</form>||g;
1.71      ng       4403: #		while ($companswer =~ /(<a href\=\"javascript:newWindow.*?Script Vars<\/a>)/s) { #<a href="javascript:newWindow</a>
1.116     ng       4404: #		    $companswer =~ s/$1/ /ms;
1.326     albertel 4405: #		    $request->print('match='.$1."<br />\n");
1.71      ng       4406: #		}
1.116     ng       4407: #		$companswer =~ s|<table border=\"1\">|<table border=\"0\">|g;
1.539     riegler  4408: 		$studentTable.='&nbsp;<b>'.$title.'</b>&nbsp;<br />&nbsp;<b>'.&mt('Correct answer').':</b><br />'.$companswer;
1.71      ng       4409: 	    }
                   4410: 
1.257     albertel 4411: 	    my %record = &Apache::lonnet::restore($symbx,$env{'request.course.id'},$udom,$uname);
1.125     ng       4412: 
1.257     albertel 4413: 	    if ($env{'form.lastSub'} eq 'datesub') {
1.71      ng       4414: 		if ($record{'version'} eq '') {
1.485     albertel 4415: 		    $studentTable.='<br />&nbsp;<span class="LC_warning">'.&mt('No recorded submission for this problem.').'</span><br />';
1.71      ng       4416: 		} else {
1.116     ng       4417: 		    my %responseType = ();
                   4418: 		    foreach my $partid (@{$parts}) {
1.147     albertel 4419: 			my @responseIds =$curRes->responseIds($partid);
                   4420: 			my @responseType =$curRes->responseType($partid);
                   4421: 			my %responseIds;
                   4422: 			for (my $i=0;$i<=$#responseIds;$i++) {
                   4423: 			    $responseIds{$responseIds[$i]}=$responseType[$i];
                   4424: 			}
                   4425: 			$responseType{$partid} = \%responseIds;
1.116     ng       4426: 		    }
1.148     albertel 4427: 		    $studentTable.= &displaySubByDates($symbx,\%record,$parts,\%responseType,$checkIcon,$uname,$udom);
1.147     albertel 4428: 
1.71      ng       4429: 		}
1.257     albertel 4430: 	    } elsif ($env{'form.lastSub'} eq 'all') {
                   4431: 		my $last = ($env{'form.lastSub'} eq 'last' ? 'last' : '');
1.71      ng       4432: 		$studentTable.=&Apache::loncommon::get_previous_attempt($symbx,$uname,$udom,
1.257     albertel 4433: 									$env{'request.course.id'},
1.71      ng       4434: 									'','.submission');
                   4435:  
                   4436: 	    }
1.103     albertel 4437: 	    if (&canmodify($usec)) {
1.585     bisitz   4438:             $studentTable.=&gradeBox_start();
1.103     albertel 4439: 		foreach my $partid (@{$parts}) {
                   4440: 		    $studentTable.=&gradeBox($request,$symbx,$uname,$udom,$question,$partid,\%record);
                   4441: 		    $studentTable.='<input type="hidden" name="q_'.$question.'" value="'.$partid.'" />'."\n";
                   4442: 		    $question++;
                   4443: 		}
1.585     bisitz   4444:             $studentTable.=&gradeBox_end();
1.196     albertel 4445: 		$prob++;
1.71      ng       4446: 	    }
                   4447: 	    $studentTable.='</td></tr>';
1.68      ng       4448: 
1.103     albertel 4449: 	}
1.68      ng       4450:         $curRes = $iterator->next();
                   4451:     }
                   4452: 
1.589     bisitz   4453:     $studentTable.=
                   4454:         '</table>'."\n".
                   4455:         '<input type="button" value="'.&mt('Save').'" '.
                   4456:         'onclick="javascript:checkSubmitPage(this.form,'.$question.');" />'.
                   4457:         '</form>'."\n";
1.71      ng       4458:     $request->print($studentTable);
                   4459: 
                   4460:     return '';
1.119     ng       4461: }
                   4462: 
                   4463: sub displaySubByDates {
1.148     albertel 4464:     my ($symb,$record,$parts,$responseType,$checkIcon,$uname,$udom) = @_;
1.224     albertel 4465:     my $isCODE=0;
1.335     albertel 4466:     my $isTask = ($symb =~/\.task$/);
1.224     albertel 4467:     if (exists($record->{'resource.CODE'})) { $isCODE=1; }
1.467     albertel 4468:     my $studentTable=&Apache::loncommon::start_data_table().
                   4469: 	&Apache::loncommon::start_data_table_header_row().
                   4470: 	'<th>'.&mt('Date/Time').'</th>'.
                   4471: 	($isCODE?'<th>'.&mt('CODE').'</th>':'').
                   4472: 	'<th>'.&mt('Submission').'</th>'.
                   4473: 	'<th>'.&mt('Status').'</th>'.
                   4474: 	&Apache::loncommon::end_data_table_header_row();
1.119     ng       4475:     my ($version);
                   4476:     my %mark;
1.148     albertel 4477:     my %orders;
1.119     ng       4478:     $mark{'correct_by_student'} = $checkIcon;
1.147     albertel 4479:     if (!exists($$record{'1:timestamp'})) {
1.539     riegler  4480: 	return '<br />&nbsp;<span class="LC_warning">'.&mt('Nothing submitted - no attempts.').'</span><br />';
1.147     albertel 4481:     }
1.335     albertel 4482: 
                   4483:     my $interaction;
1.525     raeburn  4484:     my $no_increment = 1;
1.119     ng       4485:     for ($version=1;$version<=$$record{'version'};$version++) {
1.467     albertel 4486: 	my $timestamp = 
                   4487: 	    &Apache::lonlocal::locallocaltime($$record{$version.':timestamp'});
1.335     albertel 4488: 	if (exists($$record{$version.':resource.0.version'})) {
                   4489: 	    $interaction = $$record{$version.':resource.0.version'};
                   4490: 	}
                   4491: 
                   4492: 	my $where = ($isTask ? "$version:resource.$interaction"
                   4493: 		             : "$version:resource");
1.467     albertel 4494: 	$studentTable.=&Apache::loncommon::start_data_table_row().
                   4495: 	    '<td>'.$timestamp.'</td>';
1.224     albertel 4496: 	if ($isCODE) {
                   4497: 	    $studentTable.='<td>'.$record->{$version.':resource.CODE'}.'</td>';
                   4498: 	}
1.119     ng       4499: 	my @versionKeys = split(/\:/,$$record{$version.':keys'});
                   4500: 	my @displaySub = ();
                   4501: 	foreach my $partid (@{$parts}) {
1.596     raeburn  4502:             my $hidden;
                   4503:             if (($$record{$version.':resource.'.$partid.'.type'} eq 'anonsurvey') ||
                   4504:                 ($$record{$version.':resource.'.$partid.'.type'} eq 'anonsurveycred')) {
                   4505:                 $hidden = 1;
                   4506:             }
1.335     albertel 4507: 	    my @matchKey = ($isTask ? sort(grep /^resource\.\d+\.\Q$partid\E\.award$/,@versionKeys)
                   4508: 			            : sort(grep /^resource\.\Q$partid\E\..*?\.submission$/,@versionKeys));
                   4509: 	    
1.122     ng       4510: #	    next if ($$record{"$version:resource.$partid.solved"} eq '');
1.324     albertel 4511: 	    my $display_part=&get_display_part($partid,$symb);
1.147     albertel 4512: 	    foreach my $matchKey (@matchKey) {
1.198     albertel 4513: 		if (exists($$record{$version.':'.$matchKey}) &&
                   4514: 		    $$record{$version.':'.$matchKey} ne '') {
1.596     raeburn  4515:                     
1.335     albertel 4516: 		    my ($responseId)= ($isTask ? ($matchKey=~ /^resource\.(.*?)\.\Q$partid\E\.award$/)
                   4517: 				               : ($matchKey=~ /^resource\.\Q$partid\E\.(.*?)\.submission$/));
1.577     bisitz   4518:                     $displaySub[0].='<span class="LC_nobreak"';
                   4519:                     $displaySub[0].='<b>'.&mt('Part: [_1]',$display_part).'</b>'
                   4520:                                    .' <span class="LC_internal_info">'
                   4521:                                    .'('.&mt('Part ID: [_1]',$responseId).')'
                   4522:                                    .'</span>'
                   4523:                                    .' <b>';
1.596     raeburn  4524:                     if ($hidden) {
                   4525:                         $displaySub[0].= &mt('Anonymous Survey').'</b>';
                   4526:                     } else {
                   4527: 		        if ($$record{"$where.$partid.tries"} eq '') {
                   4528: 			    $displaySub[0].=&mt('Trial not counted');
                   4529: 		        } else {
                   4530: 			    $displaySub[0].=&mt('Trial: [_1]',
1.467     albertel 4531: 					    $$record{"$where.$partid.tries"});
1.596     raeburn  4532: 		        }
                   4533: 		        my $responseType=($isTask ? 'Task'
1.335     albertel 4534:                                               : $responseType->{$partid}->{$responseId});
1.596     raeburn  4535: 		        if (!exists($orders{$partid})) { $orders{$partid}={}; }
                   4536: 		        if (!exists($orders{$partid}->{$responseId})) {
                   4537: 			    $orders{$partid}->{$responseId}=
                   4538: 			        &get_order($partid,$responseId,$symb,$uname,$udom,
                   4539:                                            $no_increment);
                   4540: 		        }
                   4541: 		        $displaySub[0].='</b></span>'; # /nobreak
                   4542: 		        $displaySub[0].='&nbsp; '.
                   4543: 			    &cleanRecord($$record{$version.':'.$matchKey},$responseType,$symb,$partid,$responseId,$record,$orders{$partid}->{$responseId},"$version:",$uname,$udom).'<br />';
                   4544:                     }
1.147     albertel 4545: 		}
                   4546: 	    }
1.335     albertel 4547: 	    if (exists($$record{"$where.$partid.checkedin"})) {
1.485     albertel 4548: 		$displaySub[1].=&mt('Checked in by [_1] into slot [_2]',
                   4549: 				    $$record{"$where.$partid.checkedin"},
                   4550: 				    $$record{"$where.$partid.checkedin.slot"}).
                   4551: 					'<br />';
1.335     albertel 4552: 	    }
                   4553: 	    if (exists $$record{"$where.$partid.award"}) {
1.485     albertel 4554: 		$displaySub[1].='<b>'.&mt('Part:').'</b>&nbsp;'.$display_part.' &nbsp;'.
1.335     albertel 4555: 		    lc($$record{"$where.$partid.award"}).' '.
                   4556: 		    $mark{$$record{"$where.$partid.solved"}}.
1.147     albertel 4557: 		    '<br />';
                   4558: 	    }
1.335     albertel 4559: 	    if (exists $$record{"$where.$partid.regrader"}) {
                   4560: 		$displaySub[2].=$$record{"$where.$partid.regrader"}.
                   4561: 		    ' (<b>'.&mt('Part').':</b> '.$display_part.')';
                   4562: 	    } elsif ($$record{"$version:resource.$partid.regrader"} =~ /\S/) {
                   4563: 		$displaySub[2].=
                   4564: 		    $$record{"$version:resource.$partid.regrader"}.
1.207     albertel 4565: 		    ' (<b>'.&mt('Part').':</b> '.$display_part.')';
1.147     albertel 4566: 	    }
                   4567: 	}
                   4568: 	# needed because old essay regrader has not parts info
                   4569: 	if (exists $$record{"$version:resource.regrader"}) {
                   4570: 	    $displaySub[2].=$$record{"$version:resource.regrader"};
                   4571: 	}
                   4572: 	$studentTable.='<td>'.$displaySub[0].'&nbsp;</td><td>'.$displaySub[1];
                   4573: 	if ($displaySub[2]) {
1.467     albertel 4574: 	    $studentTable.=&mt('Manually graded by [_1]',$displaySub[2]);
1.147     albertel 4575: 	}
1.467     albertel 4576: 	$studentTable.='&nbsp;</td>'.
                   4577: 	    &Apache::loncommon::end_data_table_row();
1.119     ng       4578:     }
1.467     albertel 4579:     $studentTable.=&Apache::loncommon::end_data_table();
1.119     ng       4580:     return $studentTable;
1.71      ng       4581: }
                   4582: 
                   4583: sub updateGradeByPage {
1.608     www      4584:     my ($request,$symb) = @_;
1.71      ng       4585: 
1.257     albertel 4586:     my $cdom      = $env{"course.$env{'request.course.id'}.domain"};
                   4587:     my $cnum      = $env{"course.$env{'request.course.id'}.num"};
                   4588:     my $getsec    = $env{'form.section'} eq '' ? 'all' : $env{'form.section'};
                   4589:     my $pageTitle = $env{'form.page'};
1.103     albertel 4590:     my ($classlist,undef,$fullname) = &getclasslist($getsec,'1');
1.257     albertel 4591:     my ($uname,$udom) = split(/:/,$env{'form.student'});
                   4592:     my $usec=$classlist->{$env{'form.student'}}[5];
1.103     albertel 4593:     if (!&canmodify($usec)) {
1.526     raeburn  4594: 	$request->print('<span class="LC_warning">'.&mt('Unable to modify requested student ([_1])',$env{'form.student'}).'</span>');
1.103     albertel 4595: 	return;
                   4596:     }
1.398     albertel 4597:     my $result='<h3><span class="LC_info">&nbsp;'.$env{'form.title'}.'</span></h3>';
1.526     raeburn  4598:     $result.='<h3>&nbsp;'.&mt('Student: ').&nameUserString(undef,$env{'form.fullname'},$uname,$udom).
1.129     ng       4599: 	'</h3>'."\n";
1.70      ng       4600: 
1.68      ng       4601:     $request->print($result);
                   4602: 
1.582     raeburn  4603: 
1.132     bowersj2 4604:     my $navmap = Apache::lonnavmaps::navmap->new();
1.582     raeburn  4605:     unless (ref($navmap)) {
                   4606:         $request->print(&navmap_errormsg());
                   4607:         return;
                   4608:     }
1.257     albertel 4609:     my ($mapUrl, $id, $resUrl) = &Apache::lonnet::decode_symb( $env{'form.page'});
1.71      ng       4610:     my $map = $navmap->getResourceByUrl($resUrl); # add to navmaps
1.288     albertel 4611:     if (!$map) {
1.527     raeburn  4612: 	$request->print('<span class="LC_warning">'.&mt('Unable to grade requested sequence ([_1]).',$resUrl).'</span>');
1.288     albertel 4613: 	return; 
                   4614:     }
1.71      ng       4615:     my $iterator = $navmap->getIterator($map->map_start(),
                   4616: 					$map->map_finish());
1.70      ng       4617: 
1.484     albertel 4618:     my $studentTable=
                   4619: 	&Apache::loncommon::start_data_table().
                   4620: 	&Apache::loncommon::start_data_table_header_row().
1.485     albertel 4621: 	'<th align="center">&nbsp;'.&mt('Prob.').'&nbsp;</th>'.
                   4622: 	'<th>&nbsp;'.&mt('Title').'&nbsp;</th>'.
                   4623: 	'<th>&nbsp;'.&mt('Previous Score').'&nbsp;</th>'.
                   4624: 	'<th>&nbsp;'.&mt('New Score').'&nbsp;</th>'.
1.484     albertel 4625: 	&Apache::loncommon::end_data_table_header_row();
1.71      ng       4626: 
                   4627:     $iterator->next(); # skip the first BEGIN_MAP
                   4628:     my $curRes = $iterator->next(); # for "current resource"
1.196     albertel 4629:     my ($depth,$question,$prob,$changeflag)= (1,1,1,0);
1.101     albertel 4630:     while ($depth > 0) {
1.71      ng       4631:         if($curRes == $iterator->BEGIN_MAP) { $depth++; }
1.100     bowersj2 4632:         if($curRes == $iterator->END_MAP) { $depth--; }
1.71      ng       4633: 
1.385     albertel 4634:         if (ref($curRes) && $curRes->is_problem()) {
1.91      albertel 4635: 	    my $parts = $curRes->parts();
1.71      ng       4636:             my $title = $curRes->compTitle();
                   4637: 	    my $symbx = $curRes->symb();
1.484     albertel 4638: 	    $studentTable.=
                   4639: 		&Apache::loncommon::start_data_table_row().
                   4640: 		'<td align="center" valign="top" >'.$prob.
1.485     albertel 4641: 		(scalar(@{$parts}) == 1 ? '' 
1.526     raeburn  4642:                                         : '<br />('.&mt('[quant,_1,&nbsp;part]',scalar(@{$parts}))
                   4643: 		.')').'</td>';
1.71      ng       4644: 	    $studentTable.='<td valign="top">&nbsp;<b>'.$title.'</b>&nbsp;</td>';
                   4645: 
                   4646: 	    my %newrecord=();
                   4647: 	    my @displayPts=();
1.269     raeburn  4648:             my %aggregate = ();
                   4649:             my $aggregateflag = 0;
1.71      ng       4650: 	    foreach my $partid (@{$parts}) {
1.257     albertel 4651: 		my $newpts = $env{'form.GD_BOX'.$question.'_'.$partid};
                   4652: 		my $oldpts = $env{'form.oldpts'.$question.'_'.$partid};
1.71      ng       4653: 
1.257     albertel 4654: 		my $wgt = $env{'form.WGT'.$question.'_'.$partid} != 0 ? 
                   4655: 		    $env{'form.WGT'.$question.'_'.$partid} : 1;
1.71      ng       4656: 		my $partial = $newpts/$wgt;
                   4657: 		my $score;
                   4658: 		if ($partial > 0) {
                   4659: 		    $score = 'correct_by_override';
1.125     ng       4660: 		} elsif ($newpts ne '') { #empty is taken as 0
1.71      ng       4661: 		    $score = 'incorrect_by_override';
                   4662: 		}
1.257     albertel 4663: 		my $dropMenu = $env{'form.GD_SEL'.$question.'_'.$partid};
1.125     ng       4664: 		if ($dropMenu eq 'excused') {
1.71      ng       4665: 		    $partial = '';
                   4666: 		    $score = 'excused';
1.125     ng       4667: 		} elsif ($dropMenu eq 'reset status'
1.257     albertel 4668: 			 && $env{'form.solved'.$question.'_'.$partid} ne '') { #update only if previous record exists
1.125     ng       4669: 		    $newrecord{'resource.'.$partid.'.tries'} = 0;
                   4670: 		    $newrecord{'resource.'.$partid.'.solved'} = '';
                   4671: 		    $newrecord{'resource.'.$partid.'.award'} = '';
                   4672: 		    $newrecord{'resource.'.$partid.'.awarded'} = 0;
1.257     albertel 4673: 		    $newrecord{'resource.'.$partid.'.regrader'} = "$env{'user.name'}:$env{'user.domain'}";
1.125     ng       4674: 		    $changeflag++;
                   4675: 		    $newpts = '';
1.269     raeburn  4676:                     
                   4677:                     my $aggtries =  $env{'form.aggtries'.$question.'_'.$partid};
                   4678:                     my $totaltries = $env{'form.totaltries'.$question.'_'.$partid};
                   4679:                     my $solvedstatus = $env{'form.solved'.$question.'_'.$partid};
                   4680:                     if ($aggtries > 0) {
                   4681:                         &decrement_aggs($symbx,$partid,\%aggregate,$aggtries,$totaltries,$solvedstatus);
                   4682:                         $aggregateflag = 1;
                   4683:                     }
1.71      ng       4684: 		}
1.324     albertel 4685: 		my $display_part=&get_display_part($partid,$curRes->symb());
1.257     albertel 4686: 		my $oldstatus = $env{'form.solved'.$question.'_'.$partid};
1.526     raeburn  4687: 		$displayPts[0].='&nbsp;<b>'.&mt('Part').':</b> '.$display_part.' = '.
1.71      ng       4688: 		    (($oldstatus eq 'excused') ? 'excused' : $oldpts).
1.326     albertel 4689: 		    '&nbsp;<br />';
1.526     raeburn  4690: 		$displayPts[1].='&nbsp;<b>'.&mt('Part').':</b> '.$display_part.' = '.
1.125     ng       4691: 		     (($score eq 'excused') ? 'excused' : $newpts).
1.326     albertel 4692: 		    '&nbsp;<br />';
1.71      ng       4693: 		$question++;
1.380     albertel 4694: 		next if ($dropMenu eq 'reset status' || ($newpts eq $oldpts && $score ne 'excused'));
1.125     ng       4695: 
1.71      ng       4696: 		$newrecord{'resource.'.$partid.'.awarded'}  = $partial if $partial ne '';
1.125     ng       4697: 		$newrecord{'resource.'.$partid.'.solved'}   = $score if $score ne '';
1.257     albertel 4698: 		$newrecord{'resource.'.$partid.'.regrader'} = "$env{'user.name'}:$env{'user.domain'}"
1.125     ng       4699: 		    if (scalar(keys(%newrecord)) > 0);
1.71      ng       4700: 
                   4701: 		$changeflag++;
                   4702: 	    }
                   4703: 	    if (scalar(keys(%newrecord)) > 0) {
1.382     albertel 4704: 		my %record = 
                   4705: 		    &Apache::lonnet::restore($symbx,$env{'request.course.id'},
                   4706: 					     $udom,$uname);
                   4707: 
                   4708: 		if (&Apache::lonnet::validCODE($env{'form.CODE'})) {
                   4709: 		    $newrecord{'resource.CODE'} = $env{'form.CODE'};
                   4710: 		} elsif (&Apache::lonnet::validCODE($record{'resource.CODE'})) {
                   4711: 		    $newrecord{'resource.CODE'} = '';
                   4712: 		}
1.257     albertel 4713: 		&Apache::lonnet::cstore(\%newrecord,$symbx,$env{'request.course.id'},
1.71      ng       4714: 					$udom,$uname);
1.382     albertel 4715: 		%record = &Apache::lonnet::restore($symbx,
                   4716: 						   $env{'request.course.id'},
                   4717: 						   $udom,$uname);
1.380     albertel 4718: 		&check_and_remove_from_queue($parts,\%record,undef,$symbx,
                   4719: 					     $cdom,$cnum,$udom,$uname);
1.71      ng       4720: 	    }
1.380     albertel 4721: 	    
1.269     raeburn  4722:             if ($aggregateflag) {
                   4723:                 &Apache::lonnet::cinc('nohist_resourcetracker',\%aggregate,
                   4724:                       $env{'course.'.$env{'request.course.id'}.'.domain'},
                   4725:                       $env{'course.'.$env{'request.course.id'}.'.num'});
                   4726:             }
1.125     ng       4727: 
1.71      ng       4728: 	    $studentTable.='<td valign="top">'.$displayPts[0].'</td>'.
                   4729: 		'<td valign="top">'.$displayPts[1].'</td>'.
1.484     albertel 4730: 		&Apache::loncommon::end_data_table_row();
1.68      ng       4731: 
1.196     albertel 4732: 	    $prob++;
1.68      ng       4733: 	}
1.71      ng       4734:         $curRes = $iterator->next();
1.68      ng       4735:     }
1.98      albertel 4736: 
1.484     albertel 4737:     $studentTable.=&Apache::loncommon::end_data_table();
1.526     raeburn  4738:     my $grademsg=($changeflag == 0 ? &mt('No score was changed or updated.') :
                   4739: 		  &mt('The scores were changed for [quant,_1,problem].',
                   4740: 		  $changeflag));
1.76      ng       4741:     $request->print($grademsg.$studentTable);
1.68      ng       4742: 
1.70      ng       4743:     return '';
                   4744: }
                   4745: 
1.72      ng       4746: #-------- end of section for handling grading by page/sequence ---------
                   4747: #
                   4748: #-------------------------------------------------------------------
                   4749: 
1.581     www      4750: #-------------------- Bubblesheet (Scantron) Grading -------------------
1.75      albertel 4751: #
                   4752: #------ start of section for handling grading by page/sequence ---------
                   4753: 
1.423     albertel 4754: =pod
                   4755: 
                   4756: =head1 Bubble sheet grading routines
                   4757: 
1.424     albertel 4758:   For this documentation:
                   4759: 
                   4760:    'scanline' refers to the full line of characters
                   4761:    from the file that we are parsing that represents one entire sheet
                   4762: 
                   4763:    'bubble line' refers to the data
                   4764:    representing the line of bubbles that are on the physical bubble sheet
                   4765: 
                   4766: 
                   4767: The overall process is that a scanned in bubble sheet data is uploaded
                   4768: into a course. When a user wants to grade, they select a
                   4769: sequence/folder of resources, a file of bubble sheet info, and pick
                   4770: one of the predefined configurations for what each scanline looks
                   4771: like.
                   4772: 
                   4773: Next each scanline is checked for any errors of either 'missing
1.435     foxr     4774: bubbles' (it's an error because it may have been mis-scanned
1.424     albertel 4775: because too light bubbling), 'double bubble' (each bubble line should
                   4776: have no more that one letter picked), invalid or duplicated CODE,
1.556     weissno  4777: invalid student/employee ID
1.424     albertel 4778: 
                   4779: If the CODE option is used that determines the randomization of the
1.556     weissno  4780: homework problems, either way the student/employee ID is looked up into a
1.424     albertel 4781: username:domain.
                   4782: 
                   4783: During the validation phase the instructor can choose to skip scanlines. 
                   4784: 
1.435     foxr     4785: After the validation phase, there are now 3 bubble sheet files
1.424     albertel 4786: 
                   4787:   scantron_original_filename (unmodified original file)
                   4788:   scantron_corrected_filename (file where the corrected information has replaced the original information)
                   4789:   scantron_skipped_filename (contains the exact text of scanlines that where skipped)
                   4790: 
                   4791: Also there is a separate hash nohist_scantrondata that contains extra
                   4792: correction information that isn't representable in the bubble sheet
                   4793: file (see &scantron_getfile() for more information)
                   4794: 
                   4795: After all scanlines are either valid, marked as valid or skipped, then
                   4796: foreach line foreach problem in the picked sequence, an ssi request is
                   4797: made that simulates a user submitting their selected letter(s) against
                   4798: the homework problem.
1.423     albertel 4799: 
                   4800: =over 4
                   4801: 
                   4802: 
                   4803: 
                   4804: =item defaultFormData
                   4805: 
                   4806:   Returns html hidden inputs used to hold context/default values.
                   4807: 
                   4808:  Arguments:
                   4809:   $symb - $symb of the current resource 
                   4810: 
                   4811: =cut
1.422     foxr     4812: 
1.81      albertel 4813: sub defaultFormData {
1.324     albertel 4814:     my ($symb)=@_;
1.613     www      4815:     return '<input type="hidden" name="symb"    value="'.&Apache::lonenc::check_encrypt($symb).'" />';
1.81      albertel 4816: }
                   4817: 
1.447     foxr     4818: 
1.423     albertel 4819: =pod 
                   4820: 
                   4821: =item getSequenceDropDown
                   4822: 
                   4823:    Return html dropdown of possible sequences to grade
                   4824:  
                   4825:  Arguments:
1.582     raeburn  4826:    $symb - $symb of the current resource
                   4827:    $map_error - ref to scalar which will container error if
                   4828:                 $navmap object is unavailable in &getSymbMap().
1.423     albertel 4829: 
                   4830: =cut
1.422     foxr     4831: 
1.75      albertel 4832: sub getSequenceDropDown {
1.582     raeburn  4833:     my ($symb,$map_error)=@_;
1.75      albertel 4834:     my $result='<select name="selectpage">'."\n";
1.582     raeburn  4835:     my ($titles,$symbx) = &getSymbMap($map_error);
                   4836:     if (ref($map_error)) {
                   4837:         return if ($$map_error);
                   4838:     }
1.137     albertel 4839:     my ($curpage)=&Apache::lonnet::decode_symb($symb); 
1.75      albertel 4840:     my $ctr=0;
                   4841:     foreach (@$titles) {
                   4842: 	my ($minder,$showtitle) = ($_ =~ /(\d+)\.(.*)/);
                   4843: 	$result.='<option value="'.$$symbx{$_}.'" '.
1.401     albertel 4844: 	    ($$symbx{$_} =~ /$curpage$/ ? 'selected="selected"' : '').
1.75      albertel 4845: 	    '>'.$showtitle.'</option>'."\n";
                   4846: 	$ctr++;
                   4847:     }
                   4848:     $result.= '</select>';
                   4849:     return $result;
                   4850: }
                   4851: 
1.495     albertel 4852: my %bubble_lines_per_response;     # no. bubble lines for each response.
1.554     raeburn  4853:                                    # key is zero-based index - 0, 1, 2 ...
1.495     albertel 4854: 
                   4855: my %first_bubble_line;             # First bubble line no. for each bubble.
                   4856: 
1.509     raeburn  4857: my %subdivided_bubble_lines;       # no. bubble lines for optionresponse, 
                   4858:                                    # matchresponse or rankresponse, where 
                   4859:                                    # an individual response can have multiple 
                   4860:                                    # lines
1.503     raeburn  4861: 
                   4862: my %responsetype_per_response;     # responsetype for each response
                   4863: 
1.495     albertel 4864: # Save and restore the bubble lines array to the form env.
                   4865: 
                   4866: 
                   4867: sub save_bubble_lines {
                   4868:     foreach my $line (keys(%bubble_lines_per_response)) {
                   4869: 	$env{"form.scantron.bubblelines.$line"}  = $bubble_lines_per_response{$line};
                   4870: 	$env{"form.scantron.first_bubble_line.$line"} =
                   4871: 	    $first_bubble_line{$line};
1.503     raeburn  4872:         $env{"form.scantron.sub_bubblelines.$line"} = 
                   4873:             $subdivided_bubble_lines{$line};
                   4874:         $env{"form.scantron.responsetype.$line"} =
                   4875:             $responsetype_per_response{$line};
1.495     albertel 4876:     }
                   4877: }
                   4878: 
                   4879: 
                   4880: sub restore_bubble_lines {
                   4881:     my $line = 0;
                   4882:     %bubble_lines_per_response = ();
                   4883:     while ($env{"form.scantron.bubblelines.$line"}) {
                   4884: 	my $value = $env{"form.scantron.bubblelines.$line"};
                   4885: 	$bubble_lines_per_response{$line} = $value;
                   4886: 	$first_bubble_line{$line}  =
                   4887: 	    $env{"form.scantron.first_bubble_line.$line"};
1.503     raeburn  4888:         $subdivided_bubble_lines{$line} =
                   4889:             $env{"form.scantron.sub_bubblelines.$line"};
                   4890:         $responsetype_per_response{$line} =
                   4891:             $env{"form.scantron.responsetype.$line"};
1.495     albertel 4892: 	$line++;
                   4893:     }
                   4894: }
                   4895: 
                   4896: #  Given the parsed scanline, get the response for 
                   4897: #  'answer' number n:
                   4898: 
                   4899: sub get_response_bubbles {
                   4900:     my ($parsed_line, $response)  = @_;
                   4901: 
                   4902:     my $bubble_line = $first_bubble_line{$response-1} +1;
                   4903:     my $bubble_lines= $bubble_lines_per_response{$response-1};
                   4904:     
                   4905:     my $selected = "";
                   4906: 
                   4907:     for (my $bline = 0; $bline < $bubble_lines; $bline++) {
                   4908: 	$selected .= $$parsed_line{"scantron.$bubble_line.answer"}.":";
                   4909: 	$bubble_line++;
                   4910:     }
                   4911:     return $selected;
                   4912: }
1.423     albertel 4913: 
                   4914: =pod 
                   4915: 
                   4916: =item scantron_filenames
                   4917: 
                   4918:    Returns a list of the scantron files in the current course 
                   4919: 
                   4920: =cut
1.422     foxr     4921: 
1.202     albertel 4922: sub scantron_filenames {
1.257     albertel 4923:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
                   4924:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
1.517     raeburn  4925:     my $getpropath = 1;
1.157     albertel 4926:     my @files=&Apache::lonnet::dirlist('userfiles',$cdom,$cname,
1.517     raeburn  4927:                                        $getpropath);
1.202     albertel 4928:     my @possiblenames;
1.201     albertel 4929:     foreach my $filename (sort(@files)) {
1.157     albertel 4930: 	($filename)=split(/&/,$filename);
                   4931: 	if ($filename!~/^scantron_orig_/) { next ; }
                   4932: 	$filename=~s/^scantron_orig_//;
1.202     albertel 4933: 	push(@possiblenames,$filename);
                   4934:     }
                   4935:     return @possiblenames;
                   4936: }
                   4937: 
1.423     albertel 4938: =pod 
                   4939: 
                   4940: =item scantron_uploads
                   4941: 
                   4942:    Returns  html drop-down list of scantron files in current course.
                   4943: 
                   4944:  Arguments:
                   4945:    $file2grade - filename to set as selected in the dropdown
                   4946: 
                   4947: =cut
1.422     foxr     4948: 
1.202     albertel 4949: sub scantron_uploads {
1.209     ng       4950:     my ($file2grade) = @_;
1.202     albertel 4951:     my $result=	'<select name="scantron_selectfile">';
                   4952:     $result.="<option></option>";
                   4953:     foreach my $filename (sort(&scantron_filenames())) {
1.401     albertel 4954: 	$result.="<option".($filename eq $file2grade ? ' selected="selected"':'').">$filename</option>\n";
1.81      albertel 4955:     }
                   4956:     $result.="</select>";
                   4957:     return $result;
                   4958: }
                   4959: 
1.423     albertel 4960: =pod 
                   4961: 
                   4962: =item scantron_scantab
                   4963: 
                   4964:   Returns html drop down of the scantron formats in the scantronformat.tab
                   4965:   file.
                   4966: 
                   4967: =cut
1.422     foxr     4968: 
1.82      albertel 4969: sub scantron_scantab {
                   4970:     my $result='<select name="scantron_format">'."\n";
1.191     albertel 4971:     $result.='<option></option>'."\n";
1.518     raeburn  4972:     my @lines = &get_scantronformat_file();
                   4973:     if (@lines > 0) {
                   4974:         foreach my $line (@lines) {
                   4975:             next if (($line =~ /^\#/) || ($line eq ''));
                   4976: 	    my ($name,$descrip)=split(/:/,$line);
                   4977: 	    $result.='<option value="'.$name.'">'.$descrip.'</option>'."\n";
                   4978:         }
1.82      albertel 4979:     }
                   4980:     $result.='</select>'."\n";
1.518     raeburn  4981:     return $result;
                   4982: }
                   4983: 
                   4984: =pod
                   4985: 
                   4986: =item get_scantronformat_file
                   4987: 
                   4988:   Returns an array containing lines from the scantron format file for
                   4989:   the domain of the course.
                   4990: 
                   4991:   If a url for a custom.tab file is listed in domain's configuration.db, 
                   4992:   lines are from this file.
                   4993: 
                   4994:   Otherwise, if a default.tab has been published in RES space by the 
                   4995:   domainconfig user, lines are from this file.
                   4996: 
                   4997:   Otherwise, fall back to getting lines from the legacy file on the
1.519     raeburn  4998:   local server:  /home/httpd/lonTabs/default_scantronformat.tab    
1.82      albertel 4999: 
1.518     raeburn  5000: =cut
                   5001: 
                   5002: sub get_scantronformat_file {
                   5003:     my $cdom= $env{'course.'.$env{'request.course.id'}.'.domain'};
                   5004:     my %domconfig = &Apache::lonnet::get_dom('configuration',['scantron'],$cdom);
                   5005:     my $gottab = 0;
                   5006:     my @lines;
                   5007:     if (ref($domconfig{'scantron'}) eq 'HASH') {
                   5008:         if ($domconfig{'scantron'}{'scantronformat'} ne '') {
                   5009:             my $formatfile = &Apache::lonnet::getfile($Apache::lonnet::perlvar{'lonDocRoot'}.$domconfig{'scantron'}{'scantronformat'});
                   5010:             if ($formatfile ne '-1') {
                   5011:                 @lines = split("\n",$formatfile,-1);
                   5012:                 $gottab = 1;
                   5013:             }
                   5014:         }
                   5015:     }
                   5016:     if (!$gottab) {
                   5017:         my $confname = $cdom.'-domainconfig';
                   5018:         my $default = $Apache::lonnet::perlvar{'lonDocRoot'}.'/res/'.$cdom.'/'.$confname.'/default.tab';
                   5019:         my $formatfile =  &Apache::lonnet::getfile($default);
                   5020:         if ($formatfile ne '-1') {
                   5021:             @lines = split("\n",$formatfile,-1);
                   5022:             $gottab = 1;
                   5023:         }
                   5024:     }
                   5025:     if (!$gottab) {
1.519     raeburn  5026:         my @domains = &Apache::lonnet::current_machine_domains();
                   5027:         if (grep(/^\Q$cdom\E$/,@domains)) {
                   5028:             my $fh=Apache::File->new($Apache::lonnet::perlvar{'lonTabDir'}.'/scantronformat.tab');
                   5029:             @lines = <$fh>;
                   5030:             close($fh);
                   5031:         } else {
                   5032:             my $fh=Apache::File->new($Apache::lonnet::perlvar{'lonTabDir'}.'/default_scantronformat.tab');
                   5033:             @lines = <$fh>;
                   5034:             close($fh);
                   5035:         }
1.518     raeburn  5036:     }
                   5037:     return @lines;
1.82      albertel 5038: }
                   5039: 
1.423     albertel 5040: =pod 
                   5041: 
                   5042: =item scantron_CODElist
                   5043: 
                   5044:   Returns html drop down of the saved CODE lists from current course,
                   5045:   generated from earlier printings.
                   5046: 
                   5047: =cut
1.422     foxr     5048: 
1.186     albertel 5049: sub scantron_CODElist {
1.257     albertel 5050:     my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   5051:     my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
1.186     albertel 5052:     my @names=&Apache::lonnet::getkeys('CODEs',$cdom,$cnum);
                   5053:     my $namechoice='<option></option>';
1.225     albertel 5054:     foreach my $name (sort {uc($a) cmp uc($b)} @names) {
1.191     albertel 5055: 	if ($name =~ /^error: 2 /) { next; }
1.278     albertel 5056: 	if ($name =~ /^type\0/) { next; }
1.186     albertel 5057: 	$namechoice.='<option value="'.$name.'">'.$name.'</option>';
                   5058:     }
                   5059:     $namechoice='<select name="scantron_CODElist">'.$namechoice.'</select>';
                   5060:     return $namechoice;
                   5061: }
                   5062: 
1.423     albertel 5063: =pod 
                   5064: 
                   5065: =item scantron_CODEunique
                   5066: 
                   5067:   Returns the html for "Each CODE to be used once" radio.
                   5068: 
                   5069: =cut
1.422     foxr     5070: 
1.186     albertel 5071: sub scantron_CODEunique {
1.532     bisitz   5072:     my $result='<span class="LC_nobreak">
1.272     albertel 5073:                  <label><input type="radio" name="scantron_CODEunique"
1.423     albertel 5074:                         value="yes" checked="checked" />'.&mt('Yes').' </label>
1.381     albertel 5075:                 </span>
1.532     bisitz   5076:                 <span class="LC_nobreak">
1.272     albertel 5077:                  <label><input type="radio" name="scantron_CODEunique"
1.423     albertel 5078:                         value="no" />'.&mt('No').' </label>
1.381     albertel 5079:                 </span>';
1.186     albertel 5080:     return $result;
                   5081: }
1.423     albertel 5082: 
                   5083: =pod 
                   5084: 
                   5085: =item scantron_selectphase
                   5086: 
                   5087:   Generates the initial screen to start the bubble sheet process.
                   5088:   Allows for - starting a grading run.
1.424     albertel 5089:              - downloading existing scan data (original, corrected
1.423     albertel 5090:                                                 or skipped info)
                   5091: 
                   5092:              - uploading new scan data
                   5093: 
                   5094:  Arguments:
                   5095:   $r          - The Apache request object
                   5096:   $file2grade - name of the file that contain the scanned data to score
                   5097: 
                   5098: =cut
1.186     albertel 5099: 
1.75      albertel 5100: sub scantron_selectphase {
1.608     www      5101:     my ($r,$file2grade,$symb) = @_;
1.75      albertel 5102:     if (!$symb) {return '';}
1.582     raeburn  5103:     my $map_error;
                   5104:     my $sequence_selector=&getSequenceDropDown($symb,\$map_error);
                   5105:     if ($map_error) {
                   5106:         $r->print('<br />'.&navmap_errormsg().'<br />');
                   5107:         return;
                   5108:     }
1.324     albertel 5109:     my $default_form_data=&defaultFormData($symb);
1.209     ng       5110:     my $file_selector=&scantron_uploads($file2grade);
1.82      albertel 5111:     my $format_selector=&scantron_scantab();
1.186     albertel 5112:     my $CODE_selector=&scantron_CODElist();
                   5113:     my $CODE_unique=&scantron_CODEunique();
1.75      albertel 5114:     my $result;
1.422     foxr     5115: 
1.513     foxr     5116:     $ssi_error = 0;
                   5117: 
1.606     wenzelju 5118:     if (&Apache::lonnet::allowed('usc',$env{'request.role.domain'}) ||
                   5119:         &Apache::lonnet::allowed('usc',$env{'request.course.id'})) {
                   5120: 
                   5121: 	# Chunk of form to prompt for a scantron file upload.
                   5122: 
                   5123:         $r->print('
                   5124:     <br />
                   5125:     '.&Apache::loncommon::start_data_table('LC_scantron_action').'
                   5126:        '.&Apache::loncommon::start_data_table_header_row().'
                   5127:             <th>
                   5128:               &nbsp;'.&mt('Specify a bubblesheet data file to upload.').'
                   5129:             </th>
                   5130:        '.&Apache::loncommon::end_data_table_header_row().'
                   5131:        '.&Apache::loncommon::start_data_table_row().'
                   5132:             <td>
                   5133: ');
1.608     www      5134:     my $default_form_data=&defaultFormData($symb);
1.606     wenzelju 5135:     my $cdom= $env{'course.'.$env{'request.course.id'}.'.domain'};
                   5136:     my $cnum= $env{'course.'.$env{'request.course.id'}.'.num'};
                   5137:     $r->print(&Apache::lonhtmlcommon::scripttag('
                   5138:     function checkUpload(formname) {
                   5139: 	if (formname.upfile.value == "") {
                   5140: 	    alert("'.&mt('Please use the browse button to select a file from your local directory.').'");
                   5141: 	    return false;
                   5142: 	}
                   5143: 	formname.submit();
                   5144:     }'));
                   5145:     $r->print('
                   5146:               <form enctype="multipart/form-data" action="/adm/grades" name="rules" method="post">
                   5147:                 '.$default_form_data.'
                   5148:                 <input name="courseid" type="hidden" value="'.$cnum.'" />
                   5149:                 <input name="domainid" type="hidden" value="'.$cdom.'" />
                   5150:                 <input name="command" value="scantronupload_save" type="hidden" />
                   5151:                 '.&mt('File to upload: [_1]','<input type="file" name="upfile" size="50" />').'
                   5152:                 <br />
                   5153:                 <input type="button" onclick="javascript:checkUpload(this.form);" value="'.&mt('Upload Bubblesheet Data').'" />
                   5154:               </form>
                   5155: ');
                   5156: 
                   5157:         $r->print('
                   5158:             </td>
                   5159:        '.&Apache::loncommon::end_data_table_row().'
                   5160:        '.&Apache::loncommon::end_data_table().'
                   5161: ');
                   5162:     }
                   5163: 
1.422     foxr     5164:     # Chunk of form to prompt for a file to grade and how:
                   5165: 
1.489     albertel 5166:     $result.= '
                   5167:     <br />
                   5168:     <form method="post" enctype="multipart/form-data" action="/adm/grades" name="scantron_process">
                   5169:     <input type="hidden" name="command" value="scantron_warning" />
                   5170:     '.$default_form_data.'
                   5171:     '.&Apache::loncommon::start_data_table('LC_scantron_action').'
                   5172:        '.&Apache::loncommon::start_data_table_header_row().'
                   5173:             <th colspan="2">
1.492     albertel 5174:               &nbsp;'.&mt('Specify file and which Folder/Sequence to grade').'
1.489     albertel 5175:             </th>
                   5176:        '.&Apache::loncommon::end_data_table_header_row().'
                   5177:        '.&Apache::loncommon::start_data_table_row().'
1.492     albertel 5178:             <td> '.&mt('Sequence to grade:').' </td><td> '.$sequence_selector.' </td>
1.489     albertel 5179:        '.&Apache::loncommon::end_data_table_row().'
                   5180:        '.&Apache::loncommon::start_data_table_row().'
1.572     www      5181:             <td> '.&mt('Filename of bubblesheet data file:').' </td><td> '.$file_selector.' </td>
1.489     albertel 5182:        '.&Apache::loncommon::end_data_table_row().'
                   5183:        '.&Apache::loncommon::start_data_table_row().'
1.572     www      5184:             <td> '.&mt('Format of bubblesheet data file:').' </td><td> '.$format_selector.' </td>
1.489     albertel 5185:        '.&Apache::loncommon::end_data_table_row().'
                   5186:        '.&Apache::loncommon::start_data_table_row().'
1.492     albertel 5187:             <td> '.&mt('Saved CODEs to validate against:').' </td><td> '.$CODE_selector.' </td>
1.489     albertel 5188:        '.&Apache::loncommon::end_data_table_row().'
                   5189:        '.&Apache::loncommon::start_data_table_row().'
1.492     albertel 5190:             <td> '.&mt('Each CODE is only to be used once:').'</td><td> '.$CODE_unique.' </td>
1.489     albertel 5191:        '.&Apache::loncommon::end_data_table_row().'
                   5192:        '.&Apache::loncommon::start_data_table_row().'
1.492     albertel 5193: 	    <td> '.&mt('Options:').' </td>
1.187     albertel 5194:             <td>
1.492     albertel 5195: 	       <label><input type="checkbox" name="scantron_options_redo" value="redo_skipped"/> '.&mt('Do only previously skipped records').'</label> <br />
                   5196:                <label><input type="checkbox" name="scantron_options_ignore" value="ignore_corrections"/> '.&mt('Remove all existing corrections').'</label> <br />
                   5197:                <label><input type="checkbox" name="scantron_options_hidden" value="ignore_hidden"/> '.&mt('Skip hidden resources when grading').'</label>
1.187     albertel 5198: 	    </td>
1.489     albertel 5199:        '.&Apache::loncommon::end_data_table_row().'
                   5200:        '.&Apache::loncommon::start_data_table_row().'
1.174     albertel 5201:             <td colspan="2">
1.572     www      5202:               <input type="submit" value="'.&mt('Grading: Validate Bubblesheet Records').'" />
1.162     albertel 5203:             </td>
1.489     albertel 5204:        '.&Apache::loncommon::end_data_table_row().'
                   5205:     '.&Apache::loncommon::end_data_table().'
                   5206:     </form>
                   5207: ';
1.162     albertel 5208:    
                   5209:     $r->print($result);
                   5210: 
1.422     foxr     5211: 
                   5212: 
                   5213:     # Chunk of the form that prompts to view a scoring office file,
                   5214:     # corrected file, skipped records in a file.
                   5215: 
1.489     albertel 5216:     $r->print('
                   5217:    <br />
                   5218:    <form action="/adm/grades" name="scantron_download">
                   5219:      '.$default_form_data.'
                   5220:      <input type="hidden" name="command" value="scantron_download" />
                   5221:      '.&Apache::loncommon::start_data_table('LC_scantron_action').'
                   5222:        '.&Apache::loncommon::start_data_table_header_row().'
                   5223:               <th>
1.492     albertel 5224:                 &nbsp;'.&mt('Download a scoring office file').'
1.489     albertel 5225:               </th>
                   5226:        '.&Apache::loncommon::end_data_table_header_row().'
                   5227:        '.&Apache::loncommon::start_data_table_row().'
1.492     albertel 5228:               <td> '.&mt('Filename of scoring office file: [_1]',$file_selector).' 
1.489     albertel 5229:                 <br />
1.492     albertel 5230:                 <input type="submit" value="'.&mt('Download: Show List of Associated Files').'" />
1.489     albertel 5231:        '.&Apache::loncommon::end_data_table_row().'
                   5232:      '.&Apache::loncommon::end_data_table().'
                   5233:    </form>
                   5234:    <br />
                   5235: ');
1.162     albertel 5236: 
1.457     banghart 5237:     &Apache::lonpickcode::code_list($r,2);
1.523     raeburn  5238: 
1.528     raeburn  5239:     $r->print('<br /><form method="post" name="checkscantron">'.
1.523     raeburn  5240:              $default_form_data."\n".
                   5241:              &Apache::loncommon::start_data_table('LC_scantron_action')."\n".
                   5242:              &Apache::loncommon::start_data_table_header_row()."\n".
                   5243:              '<th colspan="2">
1.572     www      5244:               &nbsp;'.&mt('Review bubblesheet data and submissions for a previously graded folder/sequence')."\n".
1.523     raeburn  5245:              '</th>'."\n".
                   5246:               &Apache::loncommon::end_data_table_header_row()."\n".
                   5247:               &Apache::loncommon::start_data_table_row()."\n".
                   5248:               '<td> '.&mt('Graded folder/sequence:').' </td>'."\n".
                   5249:               '<td> '.$sequence_selector.' </td>'.
                   5250:               &Apache::loncommon::end_data_table_row()."\n".
                   5251:               &Apache::loncommon::start_data_table_row()."\n".
                   5252:               '<td> '.&mt('Filename of scoring office file:').' </td>'."\n".
                   5253:               '<td> '.$file_selector.' </td>'."\n".
                   5254:               &Apache::loncommon::end_data_table_row()."\n".
                   5255:               &Apache::loncommon::start_data_table_row()."\n".
                   5256:               '<td> '.&mt('Format of data file:').' </td>'."\n".
                   5257:               '<td> '.$format_selector.' </td>'."\n".
                   5258:               &Apache::loncommon::end_data_table_row()."\n".
                   5259:               &Apache::loncommon::start_data_table_row()."\n".
1.557     raeburn  5260:               '<td> '.&mt('Options').' </td>'."\n".
                   5261:               '<td> <label><input type="checkbox" name="scantron_options_hidden" value="ignore_hidden"/> '.&mt('Skip hidden resources').'</label></td>'.
                   5262:               &Apache::loncommon::end_data_table_row()."\n".
                   5263:               &Apache::loncommon::start_data_table_row()."\n".
1.523     raeburn  5264:               '<td colspan="2">'."\n".
                   5265:               '<input type="hidden" name="command" value="checksubmissions" />'."\n".
1.575     www      5266:               '<input type="submit" value="'.&mt('Review Bubblesheet Data and Submission Records').'" />'."\n".
1.523     raeburn  5267:               '</td>'."\n".
                   5268:               &Apache::loncommon::end_data_table_row()."\n".
                   5269:               &Apache::loncommon::end_data_table()."\n".
                   5270:               '</form><br />');
                   5271:     return;
1.75      albertel 5272: }
                   5273: 
1.423     albertel 5274: =pod
                   5275: 
                   5276: =item get_scantron_config
                   5277: 
                   5278:    Parse and return the scantron configuration line selected as a
                   5279:    hash of configuration file fields.
                   5280: 
                   5281:  Arguments:
                   5282:     which - the name of the configuration to parse from the file.
                   5283: 
                   5284: 
                   5285:  Returns:
                   5286:             If the named configuration is not in the file, an empty
                   5287:             hash is returned.
                   5288:     a hash with the fields
                   5289:       name         - internal name for the this configuration setup
                   5290:       description  - text to display to operator that describes this config
                   5291:       CODElocation - if 0 or the string 'none'
                   5292:                           - no CODE exists for this config
                   5293:                      if -1 || the string 'letter'
                   5294:                           - a CODE exists for this config and is
                   5295:                             a string of letters
                   5296:                      Unsupported value (but planned for future support)
                   5297:                           if a positive integer
                   5298:                                - The CODE exists as the first n items from
                   5299:                                  the question section of the form
                   5300:                           if the string 'number'
                   5301:                                - The CODE exists for this config and is
                   5302:                                  a string of numbers
                   5303:       CODEstart   - (only matter if a CODE exists) column in the line where
                   5304:                      the CODE starts
                   5305:       CODElength  - length of the CODE
1.573     bisitz   5306:       IDstart     - column where the student/employee ID starts
1.556     weissno  5307:       IDlength    - length of the student/employee ID info
1.423     albertel 5308:       Qstart      - column where the information from the bubbled
                   5309:                     'questions' start
                   5310:       Qlength     - number of columns comprising a single bubble line from
                   5311:                     the sheet. (usually either 1 or 10)
1.424     albertel 5312:       Qon         - either a single character representing the character used
1.423     albertel 5313:                     to signal a bubble was chosen in the positional setup, or
                   5314:                     the string 'letter' if the letter of the chosen bubble is
                   5315:                     in the final, or 'number' if a number representing the
                   5316:                     chosen bubble is in the file (1->A 0->J)
1.424     albertel 5317:       Qoff        - the character used to represent that a bubble was
                   5318:                     left blank
1.423     albertel 5319:       PaperID     - if the scanning process generates a unique number for each
                   5320:                     sheet scanned the column that this ID number starts in
                   5321:       PaperIDlength - number of columns that comprise the unique ID number
                   5322:                       for the sheet of paper
1.424     albertel 5323:       FirstName   - column that the first name starts in
1.423     albertel 5324:       FirstNameLength - number of columns that the first name spans
                   5325:  
                   5326:       LastName    - column that the last name starts in
                   5327:       LastNameLength - number of columns that the last name spans
                   5328: 
                   5329: =cut
1.422     foxr     5330: 
1.82      albertel 5331: sub get_scantron_config {
                   5332:     my ($which) = @_;
1.518     raeburn  5333:     my @lines = &get_scantronformat_file();
1.82      albertel 5334:     my %config;
1.157     albertel 5335:     #FIXME probably should move to XML it has already gotten a bit much now
1.518     raeburn  5336:     foreach my $line (@lines) {
1.82      albertel 5337: 	my ($name,$descrip)=split(/:/,$line);
                   5338: 	if ($name ne $which ) { next; }
                   5339: 	chomp($line);
                   5340: 	my @config=split(/:/,$line);
                   5341: 	$config{'name'}=$config[0];
                   5342: 	$config{'description'}=$config[1];
                   5343: 	$config{'CODElocation'}=$config[2];
                   5344: 	$config{'CODEstart'}=$config[3];
                   5345: 	$config{'CODElength'}=$config[4];
                   5346: 	$config{'IDstart'}=$config[5];
                   5347: 	$config{'IDlength'}=$config[6];
                   5348: 	$config{'Qstart'}=$config[7];
1.497     foxr     5349:  	$config{'Qlength'}=$config[8];
1.82      albertel 5350: 	$config{'Qoff'}=$config[9];
                   5351: 	$config{'Qon'}=$config[10];
1.157     albertel 5352: 	$config{'PaperID'}=$config[11];
                   5353: 	$config{'PaperIDlength'}=$config[12];
                   5354: 	$config{'FirstName'}=$config[13];
                   5355: 	$config{'FirstNamelength'}=$config[14];
                   5356: 	$config{'LastName'}=$config[15];
                   5357: 	$config{'LastNamelength'}=$config[16];
1.82      albertel 5358: 	last;
                   5359:     }
                   5360:     return %config;
                   5361: }
                   5362: 
1.423     albertel 5363: =pod 
                   5364: 
                   5365: =item username_to_idmap
                   5366: 
1.556     weissno  5367:     creates a hash keyed by student/employee ID with values of the corresponding
1.423     albertel 5368:     student username:domain.
                   5369: 
                   5370:   Arguments:
                   5371: 
                   5372:     $classlist - reference to the class list hash. This is a hash
                   5373:                  keyed by student name:domain  whose elements are references
1.424     albertel 5374:                  to arrays containing various chunks of information
1.423     albertel 5375:                  about the student. (See loncoursedata for more info).
                   5376: 
                   5377:   Returns
                   5378:     %idmap - the constructed hash
                   5379: 
                   5380: =cut
                   5381: 
1.82      albertel 5382: sub username_to_idmap {
                   5383:     my ($classlist)= @_;
                   5384:     my %idmap;
                   5385:     foreach my $student (keys(%$classlist)) {
                   5386: 	$idmap{$classlist->{$student}->[&Apache::loncoursedata::CL_ID]}=
                   5387: 	    $student;
                   5388:     }
                   5389:     return %idmap;
                   5390: }
1.423     albertel 5391: 
                   5392: =pod
                   5393: 
1.424     albertel 5394: =item scantron_fixup_scanline
1.423     albertel 5395: 
                   5396:    Process a requested correction to a scanline.
                   5397: 
                   5398:   Arguments:
                   5399:     $scantron_config   - hash from &get_scantron_config()
                   5400:     $scan_data         - hash of correction information 
                   5401:                           (see &scantron_getfile())
                   5402:     $line              - existing scanline
                   5403:     $whichline         - line number of the passed in scanline
                   5404:     $field             - type of change to process 
                   5405:                          (either 
1.573     bisitz   5406:                           'ID'     -> correct the student/employee ID
1.423     albertel 5407:                           'CODE'   -> correct the CODE
                   5408:                           'answer' -> fixup the submitted answers)
                   5409:     
                   5410:    $args               - hash of additional info,
                   5411:                           - 'ID' 
                   5412:                                'newid' -> studentID to use in replacement
1.424     albertel 5413:                                           of existing one
1.423     albertel 5414:                           - 'CODE' 
                   5415:                                'CODE_ignore_dup' - set to true if duplicates
                   5416:                                                    should be ignored.
                   5417: 	                       'CODE' - is new code or 'use_unfound'
1.424     albertel 5418:                                         if the existing unfound code should
1.423     albertel 5419:                                         be used as is
                   5420:                           - 'answer'
                   5421:                                'response' - new answer or 'none' if blank
                   5422:                                'question' - the bubble line to change
1.503     raeburn  5423:                                'questionnum' - the question identifier,
                   5424:                                                may include subquestion. 
1.423     albertel 5425: 
                   5426:   Returns:
                   5427:     $line - the modified scanline
                   5428: 
                   5429:   Side effects: 
                   5430:     $scan_data - may be updated
                   5431: 
                   5432: =cut
                   5433: 
1.82      albertel 5434: 
1.157     albertel 5435: sub scantron_fixup_scanline {
                   5436:     my ($scantron_config,$scan_data,$line,$whichline,$field,$args)=@_;
                   5437:     if ($field eq 'ID') {
                   5438: 	if (length($args->{'newid'}) > $$scantron_config{'IDlength'}) {
1.186     albertel 5439: 	    return ($line,1,'New value too large');
1.157     albertel 5440: 	}
                   5441: 	if (length($args->{'newid'}) < $$scantron_config{'IDlength'}) {
                   5442: 	    $args->{'newid'}=sprintf('%-'.$$scantron_config{'IDlength'}.'s',
                   5443: 				     $args->{'newid'});
                   5444: 	}
                   5445: 	substr($line,$$scantron_config{'IDstart'}-1,
                   5446: 	       $$scantron_config{'IDlength'})=$args->{'newid'};
                   5447: 	if ($args->{'newid'}=~/^\s*$/) {
                   5448: 	    &scan_data($scan_data,"$whichline.user",
                   5449: 		       $args->{'username'}.':'.$args->{'domain'});
                   5450: 	}
1.186     albertel 5451:     } elsif ($field eq 'CODE') {
1.192     albertel 5452: 	if ($args->{'CODE_ignore_dup'}) {
                   5453: 	    &scan_data($scan_data,"$whichline.CODE_ignore_dup",'1');
                   5454: 	}
                   5455: 	&scan_data($scan_data,"$whichline.useCODE",'1');
                   5456: 	if ($args->{'CODE'} ne 'use_unfound') {
1.191     albertel 5457: 	    if (length($args->{'CODE'}) > $$scantron_config{'CODElength'}) {
                   5458: 		return ($line,1,'New CODE value too large');
                   5459: 	    }
                   5460: 	    if (length($args->{'CODE'}) < $$scantron_config{'CODElength'}) {
                   5461: 		$args->{'CODE'}=sprintf('%-'.$$scantron_config{'CODElength'}.'s',$args->{'CODE'});
                   5462: 	    }
                   5463: 	    substr($line,$$scantron_config{'CODEstart'}-1,
                   5464: 		   $$scantron_config{'CODElength'})=$args->{'CODE'};
1.186     albertel 5465: 	}
1.157     albertel 5466:     } elsif ($field eq 'answer') {
1.497     foxr     5467: 	my $length=$scantron_config->{'Qlength'};
1.157     albertel 5468: 	my $off=$scantron_config->{'Qoff'};
                   5469: 	my $on=$scantron_config->{'Qon'};
1.497     foxr     5470: 	my $answer=${off}x$length;
                   5471: 	if ($args->{'response'} eq 'none') {
                   5472: 	    &scan_data($scan_data,
1.503     raeburn  5473: 		       "$whichline.no_bubble.".$args->{'questionnum'},'1');
1.497     foxr     5474: 	} else {
                   5475: 	    if ($on eq 'letter') {
                   5476: 		my @alphabet=('A'..'Z');
                   5477: 		$answer=$alphabet[$args->{'response'}];
                   5478: 	    } elsif ($on eq 'number') {
                   5479: 		$answer=$args->{'response'}+1;
                   5480: 		if ($answer == 10) { $answer = '0'; }
1.274     albertel 5481: 	    } else {
1.497     foxr     5482: 		substr($answer,$args->{'response'},1)=$on;
1.274     albertel 5483: 	    }
1.497     foxr     5484: 	    &scan_data($scan_data,
1.503     raeburn  5485: 		       "$whichline.no_bubble.".$args->{'questionnum'},undef,'1');
1.157     albertel 5486: 	}
1.497     foxr     5487: 	my $where=$length*($args->{'question'}-1)+$scantron_config->{'Qstart'};
                   5488: 	substr($line,$where-1,$length)=$answer;
1.157     albertel 5489:     }
                   5490:     return $line;
                   5491: }
1.423     albertel 5492: 
                   5493: =pod
                   5494: 
                   5495: =item scan_data
                   5496: 
                   5497:     Edit or look up  an item in the scan_data hash.
                   5498: 
                   5499:   Arguments:
                   5500:     $scan_data  - The hash (see scantron_getfile)
                   5501:     $key        - shorthand of the key to edit (actual key is
1.424     albertel 5502:                   scantronfilename_key).
1.423     albertel 5503:     $data        - New value of the hash entry.
                   5504:     $delete      - If true, the entry is removed from the hash.
                   5505: 
                   5506:   Returns:
                   5507:     The new value of the hash table field (undefined if deleted).
                   5508: 
                   5509: =cut
                   5510: 
                   5511: 
1.157     albertel 5512: sub scan_data {
                   5513:     my ($scan_data,$key,$value,$delete)=@_;
1.257     albertel 5514:     my $filename=$env{'form.scantron_selectfile'};
1.157     albertel 5515:     if (defined($value)) {
                   5516: 	$scan_data->{$filename.'_'.$key} = $value;
                   5517:     }
                   5518:     if ($delete) { delete($scan_data->{$filename.'_'.$key}); }
                   5519:     return $scan_data->{$filename.'_'.$key};
                   5520: }
1.423     albertel 5521: 
1.495     albertel 5522: # ----- These first few routines are general use routines.----
                   5523: 
                   5524: # Return the number of occurences of a pattern in a string.
                   5525: 
                   5526: sub occurence_count {
                   5527:     my ($string, $pattern) = @_;
                   5528: 
                   5529:     my @matches = ($string =~ /$pattern/g);
                   5530: 
                   5531:     return scalar(@matches);
                   5532: }
                   5533: 
                   5534: 
                   5535: # Take a string known to have digits and convert all the
                   5536: # digits into letters in the range J,A..I.
                   5537: 
                   5538: sub digits_to_letters {
                   5539:     my ($input) = @_;
                   5540: 
                   5541:     my @alphabet = ('J', 'A'..'I');
                   5542: 
                   5543:     my @input    = split(//, $input);
                   5544:     my $output ='';
                   5545:     for (my $i = 0; $i < scalar(@input); $i++) {
                   5546: 	if ($input[$i] =~ /\d/) {
                   5547: 	    $output .= $alphabet[$input[$i]];
                   5548: 	} else {
                   5549: 	    $output .= $input[$i];
                   5550: 	}
                   5551:     }
                   5552:     return $output;
                   5553: }
                   5554: 
1.423     albertel 5555: =pod 
                   5556: 
                   5557: =item scantron_parse_scanline
                   5558: 
                   5559:   Decodes a scanline from the selected scantron file
                   5560: 
                   5561:  Arguments:
                   5562:     line             - The text of the scantron file line to process
                   5563:     whichline        - Line number
                   5564:     scantron_config  - Hash describing the format of the scantron lines.
                   5565:     scan_data        - Hash of extra information about the scanline
                   5566:                        (see scantron_getfile for more information)
                   5567:     just_header      - True if should not process question answers but only
                   5568:                        the stuff to the left of the answers.
                   5569:  Returns:
                   5570:    Hash containing the result of parsing the scanline
                   5571: 
                   5572:    Keys are all proceeded by the string 'scantron.'
                   5573: 
                   5574:        CODE    - the CODE in use for this scanline
                   5575:        useCODE - 1 if the CODE is invalid but it usage has been forced
                   5576:                  by the operator
                   5577:        CODE_ignore_dup - 1 if the CODE is a duplicated use when unique
                   5578:                             CODEs were selected, but the usage has been
                   5579:                             forced by the operator
1.556     weissno  5580:        ID  - student/employee ID
1.423     albertel 5581:        PaperID - if used, the ID number printed on the sheet when the 
                   5582:                  paper was scanned
                   5583:        FirstName - first name from the sheet
                   5584:        LastName  - last name from the sheet
                   5585: 
                   5586:      if just_header was not true these key may also exist
                   5587: 
1.447     foxr     5588:        missingerror - a list of bubble ranges that are considered to be answers
                   5589:                       to a single question that don't have any bubbles filled in.
                   5590:                       Of the form questionnumber:firstbubblenumber:count.
                   5591:        doubleerror  - a list of bubble ranges that are considered to be answers
                   5592:                       to a single question that have more than one bubble filled in.
                   5593:                       Of the form questionnumber::firstbubblenumber:count
                   5594:    
                   5595:                 In the above, count is the number of bubble responses in the
                   5596:                 input line needed to represent the possible answers to the question.
                   5597:                 e.g. a radioresponse with 15 choices in an answer sheet with 10 choices
                   5598:                 per line would have count = 2.
                   5599: 
1.423     albertel 5600:        maxquest     - the number of the last bubble line that was parsed
                   5601: 
                   5602:        (<number> starts at 1)
                   5603:        <number>.answer - zero or more letters representing the selected
                   5604:                          letters from the scanline for the bubble line 
                   5605:                          <number>.
                   5606:                          if blank there was either no bubble or there where
                   5607:                          multiple bubbles, (consult the keys missingerror and
                   5608:                          doubleerror if this is an error condition)
                   5609: 
                   5610: =cut
                   5611: 
1.82      albertel 5612: sub scantron_parse_scanline {
1.423     albertel 5613:     my ($line,$whichline,$scantron_config,$scan_data,$just_header)=@_;
1.470     foxr     5614: 
1.82      albertel 5615:     my %record;
1.550     raeburn  5616:     my $lastpos = $env{'form.scantron_maxbubble'}*$$scantron_config{'Qlength'};
                   5617:     my $questions=substr($line,$$scantron_config{'Qstart'}-1,$lastpos);  # Answers
1.422     foxr     5618:     my $data=substr($line,0,$$scantron_config{'Qstart'}-1);     # earlier stuff
1.278     albertel 5619:     if (!($$scantron_config{'CODElocation'} eq 0 ||
                   5620: 	  $$scantron_config{'CODElocation'} eq 'none')) {
                   5621: 	if ($$scantron_config{'CODElocation'} < 0 ||
                   5622: 	    $$scantron_config{'CODElocation'} eq 'letter' ||
                   5623: 	    $$scantron_config{'CODElocation'} eq 'number') {
1.191     albertel 5624: 	    $record{'scantron.CODE'}=substr($data,
                   5625: 					    $$scantron_config{'CODEstart'}-1,
1.83      albertel 5626: 					    $$scantron_config{'CODElength'});
1.191     albertel 5627: 	    if (&scan_data($scan_data,"$whichline.useCODE")) {
                   5628: 		$record{'scantron.useCODE'}=1;
                   5629: 	    }
1.192     albertel 5630: 	    if (&scan_data($scan_data,"$whichline.CODE_ignore_dup")) {
                   5631: 		$record{'scantron.CODE_ignore_dup'}=1;
                   5632: 	    }
1.82      albertel 5633: 	} else {
                   5634: 	    #FIXME interpret first N questions
                   5635: 	}
                   5636:     }
1.83      albertel 5637:     $record{'scantron.ID'}=substr($data,$$scantron_config{'IDstart'}-1,
                   5638: 				  $$scantron_config{'IDlength'});
1.157     albertel 5639:     $record{'scantron.PaperID'}=
                   5640: 	substr($data,$$scantron_config{'PaperID'}-1,
                   5641: 	       $$scantron_config{'PaperIDlength'});
                   5642:     $record{'scantron.FirstName'}=
                   5643: 	substr($data,$$scantron_config{'FirstName'}-1,
                   5644: 	       $$scantron_config{'FirstNamelength'});
                   5645:     $record{'scantron.LastName'}=
                   5646: 	substr($data,$$scantron_config{'LastName'}-1,
                   5647: 	       $$scantron_config{'LastNamelength'});
1.423     albertel 5648:     if ($just_header) { return \%record; }
1.194     albertel 5649: 
1.82      albertel 5650:     my @alphabet=('A'..'Z');
                   5651:     my $questnum=0;
1.447     foxr     5652:     my $ansnum  =1;		# Multiple 'answer lines'/question.
                   5653: 
1.470     foxr     5654:     chomp($questions);		# Get rid of any trailing \n.
                   5655:     $questions =~ s/\r$//;      # Get rid of trailing \r too (MAC or Win uploads).
                   5656:     while (length($questions)) {
1.447     foxr     5657: 	my $answers_needed = $bubble_lines_per_response{$questnum};
1.503     raeburn  5658:         my $answer_length  = ($$scantron_config{'Qlength'} * $answers_needed)
                   5659:                              || 1;
                   5660:         $questnum++;
                   5661:         my $quest_id = $questnum;
                   5662:         my $currentquest = substr($questions,0,$answer_length);
                   5663:         $questions       = substr($questions,$answer_length);
                   5664:         if (length($currentquest) < $answer_length) { next; }
                   5665: 
                   5666:         if ($subdivided_bubble_lines{$questnum-1} =~ /,/) {
                   5667:             my $subquestnum = 1;
                   5668:             my $subquestions = $currentquest;
                   5669:             my @subanswers_needed = 
                   5670:                 split(/,/,$subdivided_bubble_lines{$questnum-1});  
                   5671:             foreach my $subans (@subanswers_needed) {
                   5672:                 my $subans_length =
                   5673:                     ($$scantron_config{'Qlength'} * $subans)  || 1;
                   5674:                 my $currsubquest = substr($subquestions,0,$subans_length);
                   5675:                 $subquestions   = substr($subquestions,$subans_length);
                   5676:                 $quest_id = "$questnum.$subquestnum";
                   5677:                 if (($$scantron_config{'Qon'} eq 'letter') ||
                   5678:                     ($$scantron_config{'Qon'} eq 'number')) {
                   5679:                     $ansnum = &scantron_validator_lettnum($ansnum, 
                   5680:                         $questnum,$quest_id,$subans,$currsubquest,$whichline,
                   5681:                         \@alphabet,\%record,$scantron_config,$scan_data);
                   5682:                 } else {
                   5683:                     $ansnum = &scantron_validator_positional($ansnum,
                   5684:                         $questnum,$quest_id,$subans,$currsubquest,$whichline,                        \@alphabet,\%record,$scantron_config,$scan_data);
                   5685:                 }
                   5686:                 $subquestnum ++;
                   5687:             }
                   5688:         } else {
                   5689:             if (($$scantron_config{'Qon'} eq 'letter') ||
                   5690:                 ($$scantron_config{'Qon'} eq 'number')) {
                   5691:                 $ansnum = &scantron_validator_lettnum($ansnum,$questnum,
                   5692:                     $quest_id,$answers_needed,$currentquest,$whichline,
                   5693:                     \@alphabet,\%record,$scantron_config,$scan_data);
                   5694:             } else {
                   5695:                 $ansnum = &scantron_validator_positional($ansnum,$questnum,
                   5696:                     $quest_id,$answers_needed,$currentquest,$whichline,
                   5697:                     \@alphabet,\%record,$scantron_config,$scan_data);
                   5698:             }
                   5699:         }
                   5700:     }
                   5701:     $record{'scantron.maxquest'}=$questnum;
                   5702:     return \%record;
                   5703: }
1.447     foxr     5704: 
1.503     raeburn  5705: sub scantron_validator_lettnum {
                   5706:     my ($ansnum,$questnum,$quest_id,$answers_needed,$currquest,$whichline,
                   5707:         $alphabet,$record,$scantron_config,$scan_data) = @_;
                   5708: 
                   5709:     # Qon 'letter' implies for each slot in currquest we have:
                   5710:     #    ? or * for doubles, a letter in A-Z for a bubble, and
                   5711:     #    about anything else (esp. a value of Qoff) for missing
                   5712:     #    bubbles.
                   5713:     #
                   5714:     # Qon 'number' implies each slot gives a digit that indexes the
                   5715:     #    bubbles filled, or Qoff, or a non-number for unbubbled lines,
                   5716:     #    and * or ? for double bubbles on a single line.
                   5717:     #
1.447     foxr     5718: 
1.503     raeburn  5719:     my $matchon;
                   5720:     if ($$scantron_config{'Qon'} eq 'letter') {
                   5721:         $matchon = '[A-Z]';
                   5722:     } elsif ($$scantron_config{'Qon'} eq 'number') {
                   5723:         $matchon = '\d';
                   5724:     }
                   5725:     my $occurrences = 0;
                   5726:     if (($responsetype_per_response{$questnum-1} eq 'essayresponse') ||
                   5727:         ($responsetype_per_response{$questnum-1} eq 'formularesponse') ||
1.510     raeburn  5728:         ($responsetype_per_response{$questnum-1} eq 'stringresponse') ||
                   5729:         ($responsetype_per_response{$questnum-1} eq 'imageresponse') ||
                   5730:         ($responsetype_per_response{$questnum-1} eq 'reactionresponse') ||
                   5731:         ($responsetype_per_response{$questnum-1} eq 'organicresponse')) {
1.503     raeburn  5732:         my @singlelines = split('',$currquest);
                   5733:         foreach my $entry (@singlelines) {
                   5734:             $occurrences = &occurence_count($entry,$matchon);
                   5735:             if ($occurrences > 1) {
                   5736:                 last;
                   5737:             }
                   5738:         } 
                   5739:     } else {
                   5740:         $occurrences = &occurence_count($currquest,$matchon); 
                   5741:     }
                   5742:     if (($currquest =~ /\?/ || $currquest =~ /\*/) || ($occurrences > 1)) {
                   5743:         push(@{$record->{'scantron.doubleerror'}},$quest_id);
                   5744:         for (my $ans=0; $ans<$answers_needed; $ans++) {
                   5745:             my $bubble = substr($currquest,$ans,1);
                   5746:             if ($bubble =~ /$matchon/ ) {
                   5747:                 if ($$scantron_config{'Qon'} eq 'number') {
                   5748:                     if ($bubble == 0) {
                   5749:                         $bubble = 10; 
                   5750:                     }
                   5751:                     $record->{"scantron.$ansnum.answer"} = 
                   5752:                         $alphabet->[$bubble-1];
                   5753:                 } else {
                   5754:                     $record->{"scantron.$ansnum.answer"} = $bubble;
                   5755:                 }
                   5756:             } else {
                   5757:                 $record->{"scantron.$ansnum.answer"}='';
                   5758:             }
                   5759:             $ansnum++;
                   5760:         }
                   5761:     } elsif (!defined($currquest)
                   5762:             || (&occurence_count($currquest, $$scantron_config{'Qoff'}) == length($currquest))
                   5763:             || (&occurence_count($currquest,$matchon) == 0)) {
                   5764:         for (my $ans=0; $ans<$answers_needed; $ans++ ) {
                   5765:             $record->{"scantron.$ansnum.answer"}='';
                   5766:             $ansnum++;
                   5767:         }
                   5768:         if (!&scan_data($scan_data,"$whichline.no_bubble.$quest_id")) {
                   5769:             push(@{$record->{'scantron.missingerror'}},$quest_id);
                   5770:         }
                   5771:     } else {
                   5772:         if ($$scantron_config{'Qon'} eq 'number') {
                   5773:             $currquest = &digits_to_letters($currquest);            
                   5774:         }
                   5775:         for (my $ans=0; $ans<$answers_needed; $ans++) {
                   5776:             my $bubble = substr($currquest,$ans,1);
                   5777:             $record->{"scantron.$ansnum.answer"} = $bubble;
                   5778:             $ansnum++;
                   5779:         }
                   5780:     }
                   5781:     return $ansnum;
                   5782: }
1.447     foxr     5783: 
1.503     raeburn  5784: sub scantron_validator_positional {
                   5785:     my ($ansnum,$questnum,$quest_id,$answers_needed,$currquest,
                   5786:         $whichline,$alphabet,$record,$scantron_config,$scan_data) = @_;
1.447     foxr     5787: 
1.503     raeburn  5788:     # Otherwise there's a positional notation;
                   5789:     # each bubble line requires Qlength items, and there are filled in
                   5790:     # bubbles for each case where there 'Qon' characters.
                   5791:     #
1.447     foxr     5792: 
1.503     raeburn  5793:     my @array=split($$scantron_config{'Qon'},$currquest,-1);
1.447     foxr     5794: 
1.503     raeburn  5795:     # If the split only gives us one element.. the full length of the
                   5796:     # answer string, no bubbles are filled in:
1.447     foxr     5797: 
1.507     raeburn  5798:     if ($answers_needed eq '') {
                   5799:         return;
                   5800:     }
                   5801: 
1.503     raeburn  5802:     if (length($array[0]) eq $$scantron_config{'Qlength'}*$answers_needed) {
                   5803:         for (my $ans=0; $ans<$answers_needed; $ans++ ) {
                   5804:             $record->{"scantron.$ansnum.answer"}='';
                   5805:             $ansnum++;
                   5806:         }
                   5807:         if (!&scan_data($scan_data,"$whichline.no_bubble.$quest_id")) {
                   5808:             push(@{$record->{"scantron.missingerror"}},$quest_id);
                   5809:         }
                   5810:     } elsif (scalar(@array) == 2) {
                   5811:         my $location = length($array[0]);
                   5812:         my $line_num = int($location / $$scantron_config{'Qlength'});
                   5813:         my $bubble   = $alphabet->[$location % $$scantron_config{'Qlength'}];
                   5814:         for (my $ans=0; $ans<$answers_needed; $ans++) {
                   5815:             if ($ans eq $line_num) {
                   5816:                 $record->{"scantron.$ansnum.answer"} = $bubble;
                   5817:             } else {
                   5818:                 $record->{"scantron.$ansnum.answer"} = ' ';
                   5819:             }
                   5820:             $ansnum++;
                   5821:          }
                   5822:     } else {
                   5823:         #  If there's more than one instance of a bubble character
                   5824:         #  That's a double bubble; with positional notation we can
                   5825:         #  record all the bubbles filled in as well as the
                   5826:         #  fact this response consists of multiple bubbles.
                   5827:         #
                   5828:         if (($responsetype_per_response{$questnum-1} eq 'essayresponse') ||
                   5829:             ($responsetype_per_response{$questnum-1} eq 'formularesponse') ||
1.510     raeburn  5830:             ($responsetype_per_response{$questnum-1} eq 'stringresponse') ||
                   5831:             ($responsetype_per_response{$questnum-1} eq 'imageresponse') ||
                   5832:             ($responsetype_per_response{$questnum-1} eq 'reactionresponse') ||
                   5833:             ($responsetype_per_response{$questnum-1} eq 'organicresponse')) {
1.503     raeburn  5834:             my $doubleerror = 0;
                   5835:             while (($currquest >= $$scantron_config{'Qlength'}) && 
                   5836:                    (!$doubleerror)) {
                   5837:                my $currline = substr($currquest,0,$$scantron_config{'Qlength'});
                   5838:                $currquest = substr($currquest,$$scantron_config{'Qlength'});
                   5839:                my @currarray = split($$scantron_config{'Qon'},$currline,-1);
                   5840:                if (length(@currarray) > 2) {
                   5841:                    $doubleerror = 1;
                   5842:                } 
                   5843:             }
                   5844:             if ($doubleerror) {
                   5845:                 push(@{$record->{'scantron.doubleerror'}},$quest_id);
                   5846:             }
                   5847:         } else {
                   5848:             push(@{$record->{'scantron.doubleerror'}},$quest_id);
                   5849:         }
                   5850:         my $item = $ansnum;
                   5851:         for (my $ans=0; $ans<$answers_needed; $ans++) {
                   5852:             $record->{"scantron.$item.answer"} = '';
                   5853:             $item ++;
                   5854:         }
1.447     foxr     5855: 
1.503     raeburn  5856:         my @ans=@array;
                   5857:         my $i=0;
                   5858:         my $increment = 0;
                   5859:         while ($#ans) {
                   5860:             $i+=length($ans[0]) + $increment;
                   5861:             my $line   = int($i/$$scantron_config{'Qlength'} + $ansnum);
                   5862:             my $bubble = $i%$$scantron_config{'Qlength'};
                   5863:             $record->{"scantron.$line.answer"}.=$alphabet->[$bubble];
                   5864:             shift(@ans);
                   5865:             $increment = 1;
                   5866:         }
                   5867:         $ansnum += $answers_needed;
1.82      albertel 5868:     }
1.503     raeburn  5869:     return $ansnum;
1.82      albertel 5870: }
                   5871: 
1.423     albertel 5872: =pod
                   5873: 
                   5874: =item scantron_add_delay
                   5875: 
                   5876:    Adds an error message that occurred during the grading phase to a
                   5877:    queue of messages to be shown after grading pass is complete
                   5878: 
                   5879:  Arguments:
1.424     albertel 5880:    $delayqueue  - arrary ref of hash ref of error messages
1.423     albertel 5881:    $scanline    - the scanline that caused the error
                   5882:    $errormesage - the error message
                   5883:    $errorcode   - a numeric code for the error
                   5884: 
                   5885:  Side Effects:
1.424     albertel 5886:    updates the $delayqueue to have a new hash ref of the error
1.423     albertel 5887: 
                   5888: =cut
                   5889: 
1.82      albertel 5890: sub scantron_add_delay {
1.140     albertel 5891:     my ($delayqueue,$scanline,$errormessage,$errorcode)=@_;
                   5892:     push(@$delayqueue,
                   5893: 	 {'line' => $scanline, 'emsg' => $errormessage,
                   5894: 	  'ecode' => $errorcode }
                   5895: 	 );
1.82      albertel 5896: }
                   5897: 
1.423     albertel 5898: =pod
                   5899: 
                   5900: =item scantron_find_student
                   5901: 
1.424     albertel 5902:    Finds the username for the current scanline
                   5903: 
                   5904:   Arguments:
                   5905:    $scantron_record - hash result from scantron_parse_scanline
                   5906:    $scan_data       - hash of correction information 
                   5907:                       (see &scantron_getfile() form more information)
                   5908:    $idmap           - hash from &username_to_idmap()
                   5909:    $line            - number of current scanline
                   5910:  
                   5911:   Returns:
                   5912:    Either 'username:domain' or undef if unknown
                   5913: 
1.423     albertel 5914: =cut
                   5915: 
1.82      albertel 5916: sub scantron_find_student {
1.157     albertel 5917:     my ($scantron_record,$scan_data,$idmap,$line)=@_;
1.83      albertel 5918:     my $scanID=$$scantron_record{'scantron.ID'};
1.157     albertel 5919:     if ($scanID =~ /^\s*$/) {
                   5920:  	return &scan_data($scan_data,"$line.user");
                   5921:     }
1.83      albertel 5922:     foreach my $id (keys(%$idmap)) {
1.157     albertel 5923:  	if (lc($id) eq lc($scanID)) {
                   5924:  	    return $$idmap{$id};
                   5925:  	}
1.83      albertel 5926:     }
                   5927:     return undef;
                   5928: }
                   5929: 
1.423     albertel 5930: =pod
                   5931: 
                   5932: =item scantron_filter
                   5933: 
1.424     albertel 5934:    Filter sub for lonnavmaps, filters out hidden resources if ignore
                   5935:    hidden resources was selected
                   5936: 
1.423     albertel 5937: =cut
                   5938: 
1.83      albertel 5939: sub scantron_filter {
                   5940:     my ($curres)=@_;
1.331     albertel 5941: 
                   5942:     if (ref($curres) && $curres->is_problem()) {
                   5943: 	# if the user has asked to not have either hidden
                   5944: 	# or 'randomout' controlled resources to be graded
                   5945: 	# don't include them
                   5946: 	if ($env{'form.scantron_options_hidden'} eq 'ignore_hidden'
                   5947: 	    && $curres->randomout) {
                   5948: 	    return 0;
                   5949: 	}
1.83      albertel 5950: 	return 1;
                   5951:     }
                   5952:     return 0;
1.82      albertel 5953: }
                   5954: 
1.423     albertel 5955: =pod
                   5956: 
                   5957: =item scantron_process_corrections
                   5958: 
1.424     albertel 5959:    Gets correction information out of submitted form data and corrects
                   5960:    the scanline
                   5961: 
1.423     albertel 5962: =cut
                   5963: 
1.157     albertel 5964: sub scantron_process_corrections {
                   5965:     my ($r) = @_;
1.257     albertel 5966:     my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
1.157     albertel 5967:     my ($scanlines,$scan_data)=&scantron_getfile();
                   5968:     my $classlist=&Apache::loncoursedata::get_classlist();
1.257     albertel 5969:     my $which=$env{'form.scantron_line'};
1.200     albertel 5970:     my $line=&scantron_get_line($scanlines,$scan_data,$which);
1.157     albertel 5971:     my ($skip,$err,$errmsg);
1.257     albertel 5972:     if ($env{'form.scantron_skip_record'}) {
1.157     albertel 5973: 	$skip=1;
1.257     albertel 5974:     } elsif ($env{'form.scantron_corrections'} =~ /^(duplicate|incorrect)ID$/) {
                   5975: 	my $newstudent=$env{'form.scantron_username'}.':'.
                   5976: 	    $env{'form.scantron_domain'};
1.157     albertel 5977: 	my $newid=$classlist->{$newstudent}->[&Apache::loncoursedata::CL_ID];
                   5978: 	($line,$err,$errmsg)=
                   5979: 	    &scantron_fixup_scanline(\%scantron_config,$scan_data,$line,$which,
                   5980: 				     'ID',{'newid'=>$newid,
1.257     albertel 5981: 				    'username'=>$env{'form.scantron_username'},
                   5982: 				    'domain'=>$env{'form.scantron_domain'}});
                   5983:     } elsif ($env{'form.scantron_corrections'} =~ /^(duplicate|incorrect)CODE$/) {
                   5984: 	my $resolution=$env{'form.scantron_CODE_resolution'};
1.190     albertel 5985: 	my $newCODE;
1.192     albertel 5986: 	my %args;
1.190     albertel 5987: 	if      ($resolution eq 'use_unfound') {
1.191     albertel 5988: 	    $newCODE='use_unfound';
1.190     albertel 5989: 	} elsif ($resolution eq 'use_found') {
1.257     albertel 5990: 	    $newCODE=$env{'form.scantron_CODE_selectedvalue'};
1.190     albertel 5991: 	} elsif ($resolution eq 'use_typed') {
1.257     albertel 5992: 	    $newCODE=$env{'form.scantron_CODE_newvalue'};
1.194     albertel 5993: 	} elsif ($resolution =~ /^use_closest_(\d+)/) {
1.257     albertel 5994: 	    $newCODE=$env{"form.scantron_CODE_closest_$1"};
1.190     albertel 5995: 	}
1.257     albertel 5996: 	if ($env{'form.scantron_corrections'} eq 'duplicateCODE') {
1.192     albertel 5997: 	    $args{'CODE_ignore_dup'}=1;
                   5998: 	}
                   5999: 	$args{'CODE'}=$newCODE;
1.186     albertel 6000: 	($line,$err,$errmsg)=
                   6001: 	    &scantron_fixup_scanline(\%scantron_config,$scan_data,$line,$which,
1.192     albertel 6002: 				     'CODE',\%args);
1.257     albertel 6003:     } elsif ($env{'form.scantron_corrections'} =~ /^(missing|double)bubble$/) {
                   6004: 	foreach my $question (split(',',$env{'form.scantron_questions'})) {
1.157     albertel 6005: 	    ($line,$err,$errmsg)=
                   6006: 		&scantron_fixup_scanline(\%scantron_config,$scan_data,$line,
                   6007: 					 $which,'answer',
                   6008: 					 { 'question'=>$question,
1.503     raeburn  6009: 		      		   'response'=>$env{"form.scantron_correct_Q_$question"},
                   6010:                                    'questionnum'=>$env{"form.scantron_questionnum_Q_$question"}});
1.157     albertel 6011: 	    if ($err) { last; }
                   6012: 	}
                   6013:     }
                   6014:     if ($err) {
1.398     albertel 6015: 	$r->print("<span class=\"LC_warning\">Unable to accept last correction, an error occurred :$errmsg:</span>");
1.157     albertel 6016:     } else {
1.200     albertel 6017: 	&scantron_put_line($scanlines,$scan_data,$which,$line,$skip);
1.157     albertel 6018: 	&scantron_putfile($scanlines,$scan_data);
                   6019:     }
                   6020: }
                   6021: 
1.423     albertel 6022: =pod
                   6023: 
                   6024: =item reset_skipping_status
                   6025: 
1.424     albertel 6026:    Forgets the current set of remember skipped scanlines (and thus
                   6027:    reverts back to considering all lines in the
                   6028:    scantron_skipped_<filename> file)
                   6029: 
1.423     albertel 6030: =cut
                   6031: 
1.200     albertel 6032: sub reset_skipping_status {
                   6033:     my ($scanlines,$scan_data)=&scantron_getfile();
                   6034:     &scan_data($scan_data,'remember_skipping',undef,1);
                   6035:     &scantron_putfile(undef,$scan_data);
                   6036: }
                   6037: 
1.423     albertel 6038: =pod
                   6039: 
                   6040: =item start_skipping
                   6041: 
1.424     albertel 6042:    Marks a scanline to be skipped. 
                   6043: 
1.423     albertel 6044: =cut
                   6045: 
1.376     albertel 6046: sub start_skipping {
1.200     albertel 6047:     my ($scan_data,$i)=@_;
                   6048:     my %remembered=split(':',&scan_data($scan_data,'remember_skipping'));
1.376     albertel 6049:     if ($env{'form.scantron_options_redo'} =~ /^redo_/) {
                   6050: 	$remembered{$i}=2;
                   6051:     } else {
                   6052: 	$remembered{$i}=1;
                   6053:     }
1.200     albertel 6054:     &scan_data($scan_data,'remember_skipping',join(':',%remembered));
                   6055: }
                   6056: 
1.423     albertel 6057: =pod
                   6058: 
                   6059: =item should_be_skipped
                   6060: 
1.424     albertel 6061:    Checks whether a scanline should be skipped.
                   6062: 
1.423     albertel 6063: =cut
                   6064: 
1.200     albertel 6065: sub should_be_skipped {
1.376     albertel 6066:     my ($scanlines,$scan_data,$i)=@_;
1.257     albertel 6067:     if ($env{'form.scantron_options_redo'} !~ /^redo_/) {
1.200     albertel 6068: 	# not redoing old skips
1.376     albertel 6069: 	if ($scanlines->{'skipped'}[$i]) { return 1; }
1.200     albertel 6070: 	return 0;
                   6071:     }
                   6072:     my %remembered=split(':',&scan_data($scan_data,'remember_skipping'));
1.376     albertel 6073: 
                   6074:     if (exists($remembered{$i}) && $remembered{$i} != 2 ) {
                   6075: 	return 0;
                   6076:     }
1.200     albertel 6077:     return 1;
                   6078: }
                   6079: 
1.423     albertel 6080: =pod
                   6081: 
                   6082: =item remember_current_skipped
                   6083: 
1.424     albertel 6084:    Discovers what scanlines are in the scantron_skipped_<filename>
                   6085:    file and remembers them into scan_data for later use.
                   6086: 
1.423     albertel 6087: =cut
                   6088: 
1.200     albertel 6089: sub remember_current_skipped {
                   6090:     my ($scanlines,$scan_data)=&scantron_getfile();
                   6091:     my %to_remember;
                   6092:     for (my $i=0;$i<=$scanlines->{'count'};$i++) {
                   6093: 	if ($scanlines->{'skipped'}[$i]) {
                   6094: 	    $to_remember{$i}=1;
                   6095: 	}
                   6096:     }
1.376     albertel 6097: 
1.200     albertel 6098:     &scan_data($scan_data,'remember_skipping',join(':',%to_remember));
                   6099:     &scantron_putfile(undef,$scan_data);
                   6100: }
                   6101: 
1.423     albertel 6102: =pod
                   6103: 
                   6104: =item check_for_error
                   6105: 
1.424     albertel 6106:     Checks if there was an error when attempting to remove a specific
                   6107:     scantron_.. bubble sheet data file. Prints out an error if
                   6108:     something went wrong.
                   6109: 
1.423     albertel 6110: =cut
                   6111: 
1.200     albertel 6112: sub check_for_error {
                   6113:     my ($r,$result)=@_;
                   6114:     if ($result ne 'ok' && $result ne 'not_found' ) {
1.492     albertel 6115: 	$r->print(&mt("An error occurred ([_1]) when trying to remove the existing corrections.",$result));
1.200     albertel 6116:     }
                   6117: }
1.157     albertel 6118: 
1.423     albertel 6119: =pod
                   6120: 
                   6121: =item scantron_warning_screen
                   6122: 
1.424     albertel 6123:    Interstitial screen to make sure the operator has selected the
                   6124:    correct options before we start the validation phase.
                   6125: 
1.423     albertel 6126: =cut
                   6127: 
1.203     albertel 6128: sub scantron_warning_screen {
                   6129:     my ($button_text)=@_;
1.257     albertel 6130:     my $title=&Apache::lonnet::gettitle($env{'form.selectpage'});
1.284     albertel 6131:     my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
1.373     albertel 6132:     my $CODElist;
1.284     albertel 6133:     if ($scantron_config{'CODElocation'} &&
                   6134: 	$scantron_config{'CODEstart'} &&
                   6135: 	$scantron_config{'CODElength'}) {
                   6136: 	$CODElist=$env{'form.scantron_CODElist'};
1.398     albertel 6137: 	if ($env{'form.scantron_CODElist'} eq '') { $CODElist='<span class="LC_warning">None</span>'; }
1.284     albertel 6138: 	$CODElist=
1.492     albertel 6139: 	    '<tr><td><b>'.&mt('List of CODES to validate against:').'</b></td><td><tt>'.
1.373     albertel 6140: 	    $env{'form.scantron_CODElist'}.'</tt></td></tr>';
1.284     albertel 6141:     }
1.492     albertel 6142:     return ('
1.203     albertel 6143: <p>
1.492     albertel 6144: <span class="LC_warning">
                   6145: '.&mt('Please double check the information below before clicking on \'[_1]\'',&mt($button_text)).'</span>
1.203     albertel 6146: </p>
                   6147: <table>
1.492     albertel 6148: <tr><td><b>'.&mt('Sequence to be Graded:').'</b></td><td>'.$title.'</td></tr>
                   6149: <tr><td><b>'.&mt('Data File that will be used:').'</b></td><td><tt>'.$env{'form.scantron_selectfile'}.'</tt></td></tr>
                   6150: '.$CODElist.'
1.203     albertel 6151: </table>
                   6152: <br />
1.492     albertel 6153: <p> '.&mt('If this information is correct, please click on \'[_1]\'.',&mt($button_text)).'</p>
                   6154: <p> '.&mt('If something is incorrect, please click the \'Grading Menu\' button to start over.').'</p>
1.203     albertel 6155: 
                   6156: <br />
1.492     albertel 6157: ');
1.203     albertel 6158: }
                   6159: 
1.423     albertel 6160: =pod
                   6161: 
                   6162: =item scantron_do_warning
                   6163: 
1.424     albertel 6164:    Check if the operator has picked something for all required
                   6165:    fields. Error out if something is missing.
                   6166: 
1.423     albertel 6167: =cut
                   6168: 
1.203     albertel 6169: sub scantron_do_warning {
1.608     www      6170:     my ($r,$symb)=@_;
1.203     albertel 6171:     if (!$symb) {return '';}
1.324     albertel 6172:     my $default_form_data=&defaultFormData($symb);
1.203     albertel 6173:     $r->print(&scantron_form_start().$default_form_data);
1.257     albertel 6174:     if ( $env{'form.selectpage'} eq '' ||
                   6175: 	 $env{'form.scantron_selectfile'} eq '' ||
                   6176: 	 $env{'form.scantron_format'} eq '' ) {
1.492     albertel 6177: 	$r->print("<p>".&mt('You have forgetten to specify some information. Please go Back and try again.')."</p>");
1.257     albertel 6178: 	if ( $env{'form.selectpage'} eq '') {
1.492     albertel 6179: 	    $r->print('<p><span class="LC_error">'.&mt('You have not selected a Sequence to grade').'</span></p>');
1.237     albertel 6180: 	} 
1.257     albertel 6181: 	if ( $env{'form.scantron_selectfile'} eq '') {
1.492     albertel 6182: 	    $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 6183: 	} 
1.257     albertel 6184: 	if ( $env{'form.scantron_format'} eq '') {
1.492     albertel 6185: 	    $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 6186: 	} 
                   6187:     } else {
1.265     www      6188: 	my $warning=&scantron_warning_screen('Grading: Validate Records');
1.492     albertel 6189: 	$r->print('
                   6190: '.$warning.'
                   6191: <input type="submit" name="submit" value="'.&mt('Grading: Validate Records').'" />
1.203     albertel 6192: <input type="hidden" name="command" value="scantron_validate" />
1.492     albertel 6193: ');
1.237     albertel 6194:     }
1.614     www      6195:     $r->print("</form><br />");
1.203     albertel 6196:     return '';
                   6197: }
                   6198: 
1.423     albertel 6199: =pod
                   6200: 
                   6201: =item scantron_form_start
                   6202: 
1.424     albertel 6203:     html hidden input for remembering all selected grading options
                   6204: 
1.423     albertel 6205: =cut
                   6206: 
1.203     albertel 6207: sub scantron_form_start {
                   6208:     my ($max_bubble)=@_;
                   6209:     my $result= <<SCANTRONFORM;
                   6210: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="scantronupload">
1.257     albertel 6211:   <input type="hidden" name="selectpage" value="$env{'form.selectpage'}" />
                   6212:   <input type="hidden" name="scantron_format" value="$env{'form.scantron_format'}" />
                   6213:   <input type="hidden" name="scantron_selectfile" value="$env{'form.scantron_selectfile'}" />
1.218     albertel 6214:   <input type="hidden" name="scantron_maxbubble" value="$max_bubble" />
1.257     albertel 6215:   <input type="hidden" name="scantron_CODElist" value="$env{'form.scantron_CODElist'}" />
                   6216:   <input type="hidden" name="scantron_CODEunique" value="$env{'form.scantron_CODEunique'}" />
                   6217:   <input type="hidden" name="scantron_options_redo" value="$env{'form.scantron_options_redo'}" />
                   6218:   <input type="hidden" name="scantron_options_ignore" value="$env{'form.scantron_options_ignore'}" />
1.331     albertel 6219:   <input type="hidden" name="scantron_options_hidden" value="$env{'form.scantron_options_hidden'}" />
1.203     albertel 6220: SCANTRONFORM
1.447     foxr     6221: 
                   6222:   my $line = 0;
                   6223:     while (defined($env{"form.scantron.bubblelines.$line"})) {
                   6224:        my $chunk =
                   6225: 	   '<input type="hidden" name="scantron.bubblelines.'.$line.'" value="'.$env{"form.scantron.bubblelines.$line"}.'" />'."\n";
1.448     foxr     6226:        $chunk .=
                   6227: 	   '<input type="hidden" name="scantron.first_bubble_line.'.$line.'" value="'.$env{"form.scantron.first_bubble_line.$line"}.'" />'."\n";
1.503     raeburn  6228:        $chunk .= 
                   6229:            '<input type="hidden" name="scantron.sub_bubblelines.'.$line.'" value="'.$env{"form.scantron.sub_bubblelines.$line"}.'" />'."\n";
1.504     raeburn  6230:        $chunk .=
                   6231:            '<input type="hidden" name="scantron.responsetype.'.$line.'" value="'.$env{"form.scantron.responsetype.$line"}.'" />'."\n";
1.447     foxr     6232:        $result .= $chunk;
                   6233:        $line++;
                   6234:    }
1.203     albertel 6235:     return $result;
                   6236: }
                   6237: 
1.423     albertel 6238: =pod
                   6239: 
                   6240: =item scantron_validate_file
                   6241: 
1.424     albertel 6242:     Dispatch routine for doing validation of a bubble sheet data file.
                   6243: 
                   6244:     Also processes any necessary information resets that need to
                   6245:     occur before validation begins (ignore previous corrections,
                   6246:     restarting the skipped records processing)
                   6247: 
1.423     albertel 6248: =cut
                   6249: 
1.157     albertel 6250: sub scantron_validate_file {
1.608     www      6251:     my ($r,$symb) = @_;
1.157     albertel 6252:     if (!$symb) {return '';}
1.324     albertel 6253:     my $default_form_data=&defaultFormData($symb);
1.200     albertel 6254:     
                   6255:     # do the detection of only doing skipped records first befroe we delete
1.424     albertel 6256:     # them when doing the corrections reset
1.257     albertel 6257:     if ($env{'form.scantron_options_redo'} ne 'redo_skipped_ready') {
1.200     albertel 6258: 	&reset_skipping_status();
                   6259:     }
1.257     albertel 6260:     if ($env{'form.scantron_options_redo'} eq 'redo_skipped') {
1.200     albertel 6261: 	&remember_current_skipped();
1.257     albertel 6262: 	$env{'form.scantron_options_redo'}='redo_skipped_ready';
1.200     albertel 6263:     }
                   6264: 
1.257     albertel 6265:     if ($env{'form.scantron_options_ignore'} eq 'ignore_corrections') {
1.200     albertel 6266: 	&check_for_error($r,&scantron_remove_file('corrected'));
                   6267: 	&check_for_error($r,&scantron_remove_file('skipped'));
                   6268: 	&check_for_error($r,&scantron_remove_scan_data());
1.257     albertel 6269: 	$env{'form.scantron_options_ignore'}='done';
1.192     albertel 6270:     }
1.200     albertel 6271: 
1.257     albertel 6272:     if ($env{'form.scantron_corrections'}) {
1.157     albertel 6273: 	&scantron_process_corrections($r);
                   6274:     }
1.503     raeburn  6275:     $r->print('<p>'.&mt('Gathering necessary information.').'</p>');$r->rflush();
1.157     albertel 6276:     #get the student pick code ready
                   6277:     $r->print(&Apache::loncommon::studentbrowser_javascript());
1.582     raeburn  6278:     my $nav_error;
                   6279:     my $max_bubble=&scantron_get_maxbubble(\$nav_error);
                   6280:     if ($nav_error) {
                   6281:         $r->print(&navmap_errormsg());
                   6282:         return '';
                   6283:     }
1.203     albertel 6284:     my $result=&scantron_form_start($max_bubble).$default_form_data;
1.157     albertel 6285:     $r->print($result);
                   6286:     
1.334     albertel 6287:     my @validate_phases=( 'sequence',
                   6288: 			  'ID',
1.157     albertel 6289: 			  'CODE',
                   6290: 			  'doublebubble',
                   6291: 			  'missingbubbles');
1.257     albertel 6292:     if (!$env{'form.validatepass'}) {
                   6293: 	$env{'form.validatepass'} = 0;
1.157     albertel 6294:     }
1.257     albertel 6295:     my $currentphase=$env{'form.validatepass'};
1.157     albertel 6296: 
1.448     foxr     6297: 
1.157     albertel 6298:     my $stop=0;
                   6299:     while (!$stop && $currentphase < scalar(@validate_phases)) {
1.503     raeburn  6300: 	$r->print(&mt('Validating '.$validate_phases[$currentphase]).'<br />');
1.157     albertel 6301: 	$r->rflush();
                   6302: 	my $which="scantron_validate_".$validate_phases[$currentphase];
                   6303: 	{
                   6304: 	    no strict 'refs';
                   6305: 	    ($stop,$currentphase)=&$which($r,$currentphase);
                   6306: 	}
                   6307:     }
                   6308:     if (!$stop) {
1.203     albertel 6309: 	my $warning=&scantron_warning_screen('Start Grading');
1.542     raeburn  6310: 	$r->print(&mt('Validation process complete.').'<br />'.
                   6311:                   $warning.
                   6312:                   &mt('Perform verification for each student after storage of submissions?').
                   6313:                   '&nbsp;<span class="LC_nobreak"><label>'.
                   6314:                   '<input type="radio" name="verifyrecord" value="1" />'.&mt('Yes').'</label>'.
                   6315:                   ('&nbsp;'x3).'<label>'.
                   6316:                   '<input type="radio" name="verifyrecord" value="0" checked="checked" />'.&mt('No').
                   6317:                   '</label></span><br />'.
                   6318:                   &mt('Grading will take longer if you use verification.').'<br />'.
1.572     www      6319:                   &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  6320:                   '<input type="submit" name="submit" value="'.&mt('Start Grading').'" />'.
                   6321:                   '<input type="hidden" name="command" value="scantron_process" />'."\n");
1.157     albertel 6322:     } else {
                   6323: 	$r->print('<input type="hidden" name="command" value="scantron_validate" />');
                   6324: 	$r->print("<input type='hidden' name='validatepass' value='".$currentphase."' />");
                   6325:     }
                   6326:     if ($stop) {
1.334     albertel 6327: 	if ($validate_phases[$currentphase] eq 'sequence') {
1.539     riegler  6328: 	    $r->print('<input type="submit" name="submit" value="'.&mt('Ignore').' &rarr; " />');
1.492     albertel 6329: 	    $r->print(' '.&mt('this error').' <br />');
1.334     albertel 6330: 
1.492     albertel 6331: 	    $r->print(" <p>".&mt("Or click the 'Grading Menu' button to start over.")."</p>");
1.334     albertel 6332: 	} else {
1.503     raeburn  6333:             if ($validate_phases[$currentphase] eq 'doublebubble' || $validate_phases[$currentphase] eq 'missingbubbles') {
1.539     riegler  6334: 	        $r->print('<input type="button" name="submitbutton" value="'.&mt('Continue').' &rarr;" onclick="javascript:verify_bubble_radio(this.form)" />');
1.503     raeburn  6335:             } else {
1.539     riegler  6336:                 $r->print('<input type="submit" name="submit" value="'.&mt('Continue').' &rarr;" />');
1.503     raeburn  6337:             }
1.492     albertel 6338: 	    $r->print(' '.&mt('using corrected info').' <br />');
                   6339: 	    $r->print("<input type='submit' value='".&mt("Skip")."' name='scantron_skip_record' />");
                   6340: 	    $r->print(" ".&mt("this scanline saving it for later."));
1.334     albertel 6341: 	}
1.157     albertel 6342:     }
1.614     www      6343:     $r->print(" </form><br />");
1.157     albertel 6344:     return '';
                   6345: }
                   6346: 
1.423     albertel 6347: 
                   6348: =pod
                   6349: 
                   6350: =item scantron_remove_file
                   6351: 
1.424     albertel 6352:    Removes the requested bubble sheet data file, makes sure that
                   6353:    scantron_original_<filename> is never removed
                   6354: 
                   6355: 
1.423     albertel 6356: =cut
                   6357: 
1.200     albertel 6358: sub scantron_remove_file {
1.192     albertel 6359:     my ($which)=@_;
1.257     albertel 6360:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   6361:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1.192     albertel 6362:     my $file='scantron_';
1.200     albertel 6363:     if ($which eq 'corrected' || $which eq 'skipped') {
                   6364: 	$file.=$which.'_';
1.192     albertel 6365:     } else {
                   6366: 	return 'refused';
                   6367:     }
1.257     albertel 6368:     $file.=$env{'form.scantron_selectfile'};
1.200     albertel 6369:     return &Apache::lonnet::removeuserfile($cname,$cdom,$file);
                   6370: }
                   6371: 
1.423     albertel 6372: 
                   6373: =pod
                   6374: 
                   6375: =item scantron_remove_scan_data
                   6376: 
1.424     albertel 6377:    Removes all scan_data correction for the requested bubble sheet
                   6378:    data file.  (In the case that both the are doing skipped records we need
                   6379:    to remember the old skipped lines for the time being so that element
                   6380:    persists for a while.)
                   6381: 
1.423     albertel 6382: =cut
                   6383: 
1.200     albertel 6384: sub scantron_remove_scan_data {
1.257     albertel 6385:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   6386:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1.192     albertel 6387:     my @keys=&Apache::lonnet::getkeys('nohist_scantrondata',$cdom,$cname);
                   6388:     my @todelete;
1.257     albertel 6389:     my $filename=$env{'form.scantron_selectfile'};
1.192     albertel 6390:     foreach my $key (@keys) {
                   6391: 	if ($key=~/^\Q$filename\E_/) {
1.257     albertel 6392: 	    if ($env{'form.scantron_options_redo'} eq 'redo_skipped_ready' &&
1.200     albertel 6393: 		$key=~/remember_skipping/) {
                   6394: 		next;
                   6395: 	    }
1.192     albertel 6396: 	    push(@todelete,$key);
                   6397: 	}
                   6398:     }
1.200     albertel 6399:     my $result;
1.192     albertel 6400:     if (@todelete) {
1.491     albertel 6401: 	$result = &Apache::lonnet::del('nohist_scantrondata',
                   6402: 				       \@todelete,$cdom,$cname);
                   6403:     } else {
                   6404: 	$result = 'ok';
1.192     albertel 6405:     }
                   6406:     return $result;
                   6407: }
                   6408: 
1.423     albertel 6409: 
                   6410: =pod
                   6411: 
                   6412: =item scantron_getfile
                   6413: 
1.424     albertel 6414:     Fetches the requested bubble sheet data file (all 3 versions), and
                   6415:     the scan_data hash
                   6416:   
                   6417:   Arguments:
                   6418:     None
                   6419: 
                   6420:   Returns:
                   6421:     2 hash references
                   6422: 
                   6423:      - first one has 
                   6424:          orig      -
                   6425:          corrected -
                   6426:          skipped   -  each of which points to an array ref of the specified
                   6427:                       file broken up into individual lines
                   6428:          count     - number of scanlines
                   6429:  
                   6430:      - second is the scan_data hash possible keys are
1.425     albertel 6431:        ($number refers to scanline numbered $number and thus the key affects
                   6432:         only that scanline
                   6433:         $bubline refers to the specific bubble line element and the aspects
                   6434:         refers to that specific bubble line element)
                   6435: 
                   6436:        $number.user - username:domain to use
                   6437:        $number.CODE_ignore_dup 
                   6438:                     - ignore the duplicate CODE error 
                   6439:        $number.useCODE
                   6440:                     - use the CODE in the scanline as is
                   6441:        $number.no_bubble.$bubline
                   6442:                     - it is valid that there is no bubbled in bubble
                   6443:                       at $number $bubline
                   6444:        remember_skipping
                   6445:                     - a frozen hash containing keys of $number and values
                   6446:                       of either 
                   6447:                         1 - we are on a 'do skipped records pass' and plan
                   6448:                             on processing this line
                   6449:                         2 - we are on a 'do skipped records pass' and this
                   6450:                             scanline has been marked to skip yet again
1.424     albertel 6451: 
1.423     albertel 6452: =cut
                   6453: 
1.157     albertel 6454: sub scantron_getfile {
1.200     albertel 6455:     #FIXME really would prefer a scantron directory
1.257     albertel 6456:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   6457:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1.157     albertel 6458:     my $lines;
                   6459:     $lines=&Apache::lonnet::getfile('/uploaded/'.$cdom.'/'.$cname.'/'.
1.257     albertel 6460: 		       'scantron_orig_'.$env{'form.scantron_selectfile'});
1.157     albertel 6461:     my %scanlines;
                   6462:     $scanlines{'orig'}=[(split("\n",$lines,-1))];
                   6463:     my $temp=$scanlines{'orig'};
                   6464:     $scanlines{'count'}=$#$temp;
                   6465: 
                   6466:     $lines=&Apache::lonnet::getfile('/uploaded/'.$cdom.'/'.$cname.'/'.
1.257     albertel 6467: 		       'scantron_corrected_'.$env{'form.scantron_selectfile'});
1.157     albertel 6468:     if ($lines eq '-1') {
                   6469: 	$scanlines{'corrected'}=[];
                   6470:     } else {
                   6471: 	$scanlines{'corrected'}=[(split("\n",$lines,-1))];
                   6472:     }
                   6473:     $lines=&Apache::lonnet::getfile('/uploaded/'.$cdom.'/'.$cname.'/'.
1.257     albertel 6474: 		       'scantron_skipped_'.$env{'form.scantron_selectfile'});
1.157     albertel 6475:     if ($lines eq '-1') {
                   6476: 	$scanlines{'skipped'}=[];
                   6477:     } else {
                   6478: 	$scanlines{'skipped'}=[(split("\n",$lines,-1))];
                   6479:     }
1.175     albertel 6480:     my @tmp=&Apache::lonnet::dump('nohist_scantrondata',$cdom,$cname);
1.157     albertel 6481:     if ($tmp[0] =~ /^(error:|no_such_host)/) { @tmp=(); }
                   6482:     my %scan_data = @tmp;
                   6483:     return (\%scanlines,\%scan_data);
                   6484: }
                   6485: 
1.423     albertel 6486: =pod
                   6487: 
                   6488: =item lonnet_putfile
                   6489: 
1.424     albertel 6490:    Wrapper routine to call &Apache::lonnet::finishuserfileupload
                   6491: 
                   6492:  Arguments:
                   6493:    $contents - data to store
                   6494:    $filename - filename to store $contents into
                   6495: 
                   6496:  Returns:
                   6497:    result value from &Apache::lonnet::finishuserfileupload
                   6498: 
1.423     albertel 6499: =cut
                   6500: 
1.157     albertel 6501: sub lonnet_putfile {
                   6502:     my ($contents,$filename)=@_;
1.257     albertel 6503:     my $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   6504:     my $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
                   6505:     $env{'form.sillywaytopassafilearound'}=$contents;
1.275     albertel 6506:     &Apache::lonnet::finishuserfileupload($docuname,$docudom,'sillywaytopassafilearound',$filename);
1.157     albertel 6507: 
                   6508: }
                   6509: 
1.423     albertel 6510: =pod
                   6511: 
                   6512: =item scantron_putfile
                   6513: 
1.424     albertel 6514:     Stores the current version of the bubble sheet data files, and the
                   6515:     scan_data hash. (Does not modify the original version only the
                   6516:     corrected and skipped versions.
                   6517: 
                   6518:  Arguments:
                   6519:     $scanlines - hash ref that looks like the first return value from
                   6520:                  &scantron_getfile()
                   6521:     $scan_data - hash ref that looks like the second return value from
                   6522:                  &scantron_getfile()
                   6523: 
1.423     albertel 6524: =cut
                   6525: 
1.157     albertel 6526: sub scantron_putfile {
                   6527:     my ($scanlines,$scan_data) = @_;
1.200     albertel 6528:     #FIXME really would prefer a scantron directory
1.257     albertel 6529:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   6530:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1.200     albertel 6531:     if ($scanlines) {
                   6532: 	my $prefix='scantron_';
1.157     albertel 6533: # no need to update orig, shouldn't change
                   6534: #   &lonnet_putfile(join("\n",@{$scanlines->{'orig'}}),$prefix.'orig_'.
1.257     albertel 6535: #		    $env{'form.scantron_selectfile'});
1.200     albertel 6536: 	&lonnet_putfile(join("\n",@{$scanlines->{'corrected'}}),
                   6537: 			$prefix.'corrected_'.
1.257     albertel 6538: 			$env{'form.scantron_selectfile'});
1.200     albertel 6539: 	&lonnet_putfile(join("\n",@{$scanlines->{'skipped'}}),
                   6540: 			$prefix.'skipped_'.
1.257     albertel 6541: 			$env{'form.scantron_selectfile'});
1.200     albertel 6542:     }
1.175     albertel 6543:     &Apache::lonnet::put('nohist_scantrondata',$scan_data,$cdom,$cname);
1.157     albertel 6544: }
                   6545: 
1.423     albertel 6546: =pod
                   6547: 
                   6548: =item scantron_get_line
                   6549: 
1.424     albertel 6550:    Returns the correct version of the scanline
                   6551: 
                   6552:  Arguments:
                   6553:     $scanlines - hash ref that looks like the first return value from
                   6554:                  &scantron_getfile()
                   6555:     $scan_data - hash ref that looks like the second return value from
                   6556:                  &scantron_getfile()
                   6557:     $i         - number of the requested line (starts at 0)
                   6558: 
                   6559:  Returns:
                   6560:    A scanline, (either the original or the corrected one if it
                   6561:    exists), or undef if the requested scanline should be
                   6562:    skipped. (Either because it's an skipped scanline, or it's an
                   6563:    unskipped scanline and we are not doing a 'do skipped scanlines'
                   6564:    pass.
                   6565: 
1.423     albertel 6566: =cut
                   6567: 
1.157     albertel 6568: sub scantron_get_line {
1.200     albertel 6569:     my ($scanlines,$scan_data,$i)=@_;
1.376     albertel 6570:     if (&should_be_skipped($scanlines,$scan_data,$i)) { return undef; }
                   6571:     #if ($scanlines->{'skipped'}[$i]) { return undef; }
1.157     albertel 6572:     if ($scanlines->{'corrected'}[$i]) {return $scanlines->{'corrected'}[$i];}
                   6573:     return $scanlines->{'orig'}[$i]; 
                   6574: }
                   6575: 
1.423     albertel 6576: =pod
                   6577: 
                   6578: =item scantron_todo_count
                   6579: 
1.424     albertel 6580:     Counts the number of scanlines that need processing.
                   6581: 
                   6582:  Arguments:
                   6583:     $scanlines - hash ref that looks like the first return value from
                   6584:                  &scantron_getfile()
                   6585:     $scan_data - hash ref that looks like the second return value from
                   6586:                  &scantron_getfile()
                   6587: 
                   6588:  Returns:
                   6589:     $count - number of scanlines to process
                   6590: 
1.423     albertel 6591: =cut
                   6592: 
1.200     albertel 6593: sub get_todo_count {
                   6594:     my ($scanlines,$scan_data)=@_;
                   6595:     my $count=0;
                   6596:     for (my $i=0;$i<=$scanlines->{'count'};$i++) {
                   6597: 	my $line=&scantron_get_line($scanlines,$scan_data,$i);
                   6598: 	if ($line=~/^[\s\cz]*$/) { next; }
                   6599: 	$count++;
                   6600:     }
                   6601:     return $count;
                   6602: }
                   6603: 
1.423     albertel 6604: =pod
                   6605: 
                   6606: =item scantron_put_line
                   6607: 
1.424     albertel 6608:     Updates the 'corrected' or 'skipped' versions of the bubble sheet
                   6609:     data file.
                   6610: 
                   6611:  Arguments:
                   6612:     $scanlines - hash ref that looks like the first return value from
                   6613:                  &scantron_getfile()
                   6614:     $scan_data - hash ref that looks like the second return value from
                   6615:                  &scantron_getfile()
                   6616:     $i         - line number to update
                   6617:     $newline   - contents of the updated scanline
                   6618:     $skip      - if true make the line for skipping and update the
                   6619:                  'skipped' file
                   6620: 
1.423     albertel 6621: =cut
                   6622: 
1.157     albertel 6623: sub scantron_put_line {
1.200     albertel 6624:     my ($scanlines,$scan_data,$i,$newline,$skip)=@_;
1.157     albertel 6625:     if ($skip) {
                   6626: 	$scanlines->{'skipped'}[$i]=$newline;
1.376     albertel 6627: 	&start_skipping($scan_data,$i);
1.157     albertel 6628: 	return;
                   6629:     }
                   6630:     $scanlines->{'corrected'}[$i]=$newline;
                   6631: }
                   6632: 
1.423     albertel 6633: =pod
                   6634: 
                   6635: =item scantron_clear_skip
                   6636: 
1.424     albertel 6637:    Remove a line from the 'skipped' file
                   6638: 
                   6639:  Arguments:
                   6640:     $scanlines - hash ref that looks like the first return value from
                   6641:                  &scantron_getfile()
                   6642:     $scan_data - hash ref that looks like the second return value from
                   6643:                  &scantron_getfile()
                   6644:     $i         - line number to update
                   6645: 
1.423     albertel 6646: =cut
                   6647: 
1.376     albertel 6648: sub scantron_clear_skip {
                   6649:     my ($scanlines,$scan_data,$i)=@_;
                   6650:     if (exists($scanlines->{'skipped'}[$i])) {
                   6651: 	undef($scanlines->{'skipped'}[$i]);
                   6652: 	return 1;
                   6653:     }
                   6654:     return 0;
                   6655: }
                   6656: 
1.423     albertel 6657: =pod
                   6658: 
                   6659: =item scantron_filter_not_exam
                   6660: 
1.424     albertel 6661:    Filter routine used by &Apache::lonnavmaps::retrieveResources(), to
                   6662:    filter out resources that are not marked as 'exam' mode
                   6663: 
1.423     albertel 6664: =cut
                   6665: 
1.334     albertel 6666: sub scantron_filter_not_exam {
                   6667:     my ($curres)=@_;
                   6668:     
                   6669:     if (ref($curres) && $curres->is_problem() && !$curres->is_exam()) {
                   6670: 	# if the user has asked to not have either hidden
                   6671: 	# or 'randomout' controlled resources to be graded
                   6672: 	# don't include them
                   6673: 	if ($env{'form.scantron_options_hidden'} eq 'ignore_hidden'
                   6674: 	    && $curres->randomout) {
                   6675: 	    return 0;
                   6676: 	}
                   6677: 	return 1;
                   6678:     }
                   6679:     return 0;
                   6680: }
                   6681: 
1.423     albertel 6682: =pod
                   6683: 
                   6684: =item scantron_validate_sequence
                   6685: 
1.424     albertel 6686:     Validates the selected sequence, checking for resource that are
                   6687:     not set to exam mode.
                   6688: 
1.423     albertel 6689: =cut
                   6690: 
1.334     albertel 6691: sub scantron_validate_sequence {
                   6692:     my ($r,$currentphase) = @_;
                   6693: 
                   6694:     my $navmap=Apache::lonnavmaps::navmap->new();
1.582     raeburn  6695:     unless (ref($navmap)) {
                   6696:         $r->print(&navmap_errormsg());
                   6697:         return (1,$currentphase);
                   6698:     }
1.334     albertel 6699:     my (undef,undef,$sequence)=
                   6700: 	&Apache::lonnet::decode_symb($env{'form.selectpage'});
                   6701: 
                   6702:     my $map=$navmap->getResourceByUrl($sequence);
                   6703: 
                   6704:     $r->print('<input type="hidden" name="validate_sequence_exam"
                   6705:                                     value="ignore" />');
                   6706:     if ($env{'form.validate_sequence_exam'} ne 'ignore') {
                   6707: 	my @resources=
                   6708: 	    $navmap->retrieveResources($map,\&scantron_filter_not_exam,1,0);
                   6709: 	if (@resources) {
1.357     banghart 6710: 	    $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 6711: 	    return (1,$currentphase);
                   6712: 	}
                   6713:     }
                   6714: 
                   6715:     return (0,$currentphase+1);
                   6716: }
                   6717: 
1.423     albertel 6718: 
                   6719: 
1.157     albertel 6720: sub scantron_validate_ID {
                   6721:     my ($r,$currentphase) = @_;
                   6722:     
                   6723:     #get student info
                   6724:     my $classlist=&Apache::loncoursedata::get_classlist();
                   6725:     my %idmap=&username_to_idmap($classlist);
                   6726: 
                   6727:     #get scantron line setup
1.257     albertel 6728:     my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
1.157     albertel 6729:     my ($scanlines,$scan_data)=&scantron_getfile();
1.582     raeburn  6730: 
                   6731:     my $nav_error;
                   6732:     &scantron_get_maxbubble(\$nav_error); # parse needs the bubble_lines.. array.
                   6733:     if ($nav_error) {
                   6734:         $r->print(&navmap_errormsg());
                   6735:         return(1,$currentphase);
                   6736:     }
1.157     albertel 6737: 
                   6738:     my %found=('ids'=>{},'usernames'=>{});
                   6739:     for (my $i=0;$i<=$scanlines->{'count'};$i++) {
1.200     albertel 6740: 	my $line=&scantron_get_line($scanlines,$scan_data,$i);
1.157     albertel 6741: 	if ($line=~/^[\s\cz]*$/) { next; }
                   6742: 	my $scan_record=&scantron_parse_scanline($line,$i,\%scantron_config,
                   6743: 						 $scan_data);
                   6744: 	my $id=$$scan_record{'scantron.ID'};
                   6745: 	my $found;
                   6746: 	foreach my $checkid (keys(%idmap)) {
                   6747: 	    if (lc($checkid) eq lc($id)) { $found=$checkid;last; }
                   6748: 	}
                   6749: 	if ($found) {
                   6750: 	    my $username=$idmap{$found};
                   6751: 	    if ($found{'ids'}{$found}) {
                   6752: 		&scantron_get_correction($r,$i,$scan_record,\%scantron_config,
                   6753: 					 $line,'duplicateID',$found);
1.194     albertel 6754: 		return(1,$currentphase);
1.157     albertel 6755: 	    } elsif ($found{'usernames'}{$username}) {
                   6756: 		&scantron_get_correction($r,$i,$scan_record,\%scantron_config,
                   6757: 					 $line,'duplicateID',$username);
1.194     albertel 6758: 		return(1,$currentphase);
1.157     albertel 6759: 	    }
1.186     albertel 6760: 	    #FIXME store away line we previously saw the ID on to use above
1.157     albertel 6761: 	    $found{'ids'}{$found}++;
                   6762: 	    $found{'usernames'}{$username}++;
                   6763: 	} else {
                   6764: 	    if ($id =~ /^\s*$/) {
1.158     albertel 6765: 		my $username=&scan_data($scan_data,"$i.user");
1.157     albertel 6766: 		if (defined($username) && $found{'usernames'}{$username}) {
                   6767: 		    &scantron_get_correction($r,$i,$scan_record,
                   6768: 					     \%scantron_config,
                   6769: 					     $line,'duplicateID',$username);
1.194     albertel 6770: 		    return(1,$currentphase);
1.157     albertel 6771: 		} elsif (!defined($username)) {
                   6772: 		    &scantron_get_correction($r,$i,$scan_record,
                   6773: 					     \%scantron_config,
                   6774: 					     $line,'incorrectID');
1.194     albertel 6775: 		    return(1,$currentphase);
1.157     albertel 6776: 		}
                   6777: 		$found{'usernames'}{$username}++;
                   6778: 	    } else {
                   6779: 		&scantron_get_correction($r,$i,$scan_record,\%scantron_config,
                   6780: 					 $line,'incorrectID');
1.194     albertel 6781: 		return(1,$currentphase);
1.157     albertel 6782: 	    }
                   6783: 	}
                   6784:     }
                   6785: 
                   6786:     return (0,$currentphase+1);
                   6787: }
                   6788: 
1.423     albertel 6789: 
1.157     albertel 6790: sub scantron_get_correction {
                   6791:     my ($r,$i,$scan_record,$scan_config,$line,$error,$arg)=@_;
1.454     banghart 6792: #FIXME in the case of a duplicated ID the previous line, probably need
1.157     albertel 6793: #to show both the current line and the previous one and allow skipping
                   6794: #the previous one or the current one
                   6795: 
1.333     albertel 6796:     if ( $$scan_record{'scantron.PaperID'} =~ /\S/) {
1.492     albertel 6797: 	$r->print("<p>".&mt("<b>An error was detected ($error)</b>".
                   6798: 			    " for PaperID <tt>[_1]</tt>",
                   6799: 			    $$scan_record{'scantron.PaperID'})."</p> \n");
1.157     albertel 6800:     } else {
1.492     albertel 6801: 	$r->print("<p>".&mt("<b>An error was detected ($error)</b>".
                   6802: 			    " in scanline [_1] <pre>[_2]</pre>",
                   6803: 			    $i,$line)."</p> \n");
                   6804:     }
                   6805:     my $message="<p>".&mt("The ID on the form is  <tt>[_1]</tt><br />".
                   6806: 			  "The name on the paper is [_2],[_3]",
                   6807: 			  $$scan_record{'scantron.ID'},
                   6808: 			  $$scan_record{'scantron.LastName'},
                   6809: 			  $$scan_record{'scantron.FirstName'})."</p>";
1.242     albertel 6810: 
1.157     albertel 6811:     $r->print('<input type="hidden" name="scantron_corrections" value="'.$error.'" />'."\n");
                   6812:     $r->print('<input type="hidden" name="scantron_line" value="'.$i.'" />'."\n");
1.503     raeburn  6813:                            # Array populated for doublebubble or
                   6814:     my @lines_to_correct;  # missingbubble errors to build javascript
                   6815:                            # to validate radio button checking   
                   6816: 
1.157     albertel 6817:     if ($error =~ /ID$/) {
1.186     albertel 6818: 	if ($error eq 'incorrectID') {
1.492     albertel 6819: 	    $r->print("<p>".&mt("The encoded ID is not in the classlist").
                   6820: 		      "</p>\n");
1.157     albertel 6821: 	} elsif ($error eq 'duplicateID') {
1.492     albertel 6822: 	    $r->print("<p>".&mt("The encoded ID has also been used by a previous paper [_1]",$arg)."</p>\n");
1.157     albertel 6823: 	}
1.242     albertel 6824: 	$r->print($message);
1.492     albertel 6825: 	$r->print("<p>".&mt("How should I handle this?")." <br /> \n");
1.157     albertel 6826: 	$r->print("\n<ul><li> ");
                   6827: 	#FIXME it would be nice if this sent back the user ID and
                   6828: 	#could do partial userID matches
                   6829: 	$r->print(&Apache::loncommon::selectstudent_link('scantronupload',
                   6830: 				       'scantron_username','scantron_domain'));
                   6831: 	$r->print(": <input type='text' name='scantron_username' value='' />");
                   6832: 	$r->print("\n@".
1.257     albertel 6833: 		 &Apache::loncommon::select_dom_form($env{'request.role.domain'},'scantron_domain'));
1.157     albertel 6834: 
                   6835: 	$r->print('</li>');
1.186     albertel 6836:     } elsif ($error =~ /CODE$/) {
                   6837: 	if ($error eq 'incorrectCODE') {
1.492     albertel 6838: 	    $r->print("<p>".&mt("The encoded CODE is not in the list of possible CODEs.")."</p>\n");
1.186     albertel 6839: 	} elsif ($error eq 'duplicateCODE') {
1.492     albertel 6840: 	    $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 6841: 	}
1.492     albertel 6842: 	$r->print("<p>".&mt("The CODE on the form is  <tt>'[_1]'</tt>",
                   6843: 			    $$scan_record{'scantron.CODE'})."<br />\n");
1.242     albertel 6844: 	$r->print($message);
1.492     albertel 6845: 	$r->print("<p>".&mt("How should I handle this?")." <br /> \n");
1.187     albertel 6846: 	$r->print("\n<br /> ");
1.194     albertel 6847: 	my $i=0;
1.273     albertel 6848: 	if ($error eq 'incorrectCODE' 
                   6849: 	    && $$scan_record{'scantron.CODE'}=~/\S/ ) {
1.194     albertel 6850: 	    my ($max,$closest)=&scantron_get_closely_matching_CODEs($arg,$$scan_record{'scantron.CODE'});
1.278     albertel 6851: 	    if ($closest > 0) {
                   6852: 		foreach my $testcode (@{$closest}) {
                   6853: 		    my $checked='';
1.569     bisitz   6854: 		    if (!$i) { $checked=' checked="checked"'; }
1.492     albertel 6855: 		    $r->print("
                   6856:    <label>
1.569     bisitz   6857:        <input type='radio' name='scantron_CODE_resolution' value='use_closest_$i'$checked />
1.492     albertel 6858:        ".&mt("Use the similar CODE [_1] instead.",
                   6859: 	    "<b><tt>".$testcode."</tt></b>")."
                   6860:     </label>
                   6861:     <input type='hidden' name='scantron_CODE_closest_$i' value='$testcode' />");
1.278     albertel 6862: 		    $r->print("\n<br />");
                   6863: 		    $i++;
                   6864: 		}
1.194     albertel 6865: 	    }
                   6866: 	}
1.273     albertel 6867: 	if ($$scan_record{'scantron.CODE'}=~/\S/ ) {
1.569     bisitz   6868: 	    my $checked; if (!$i) { $checked=' checked="checked"'; }
1.492     albertel 6869: 	    $r->print("
                   6870:     <label>
1.569     bisitz   6871:         <input type='radio' name='scantron_CODE_resolution' value='use_unfound'$checked />
1.492     albertel 6872:        ".&mt("Use the CODE [_1] that is was on the paper, ignoring the error.",
                   6873: 	     "<b><tt>".$$scan_record{'scantron.CODE'}."</tt></b>")."
                   6874:     </label>");
1.273     albertel 6875: 	    $r->print("\n<br />");
                   6876: 	}
1.194     albertel 6877: 
1.597     wenzelju 6878: 	$r->print(&Apache::lonhtmlcommon::scripttag(<<ENDSCRIPT));
1.188     albertel 6879: function change_radio(field) {
1.190     albertel 6880:     var slct=document.scantronupload.scantron_CODE_resolution;
1.188     albertel 6881:     var i;
                   6882:     for (i=0;i<slct.length;i++) {
                   6883:         if (slct[i].value==field) { slct[i].checked=true; }
                   6884:     }
                   6885: }
                   6886: ENDSCRIPT
1.187     albertel 6887: 	my $href="/adm/pickcode?".
1.359     www      6888: 	   "form=".&escape("scantronupload").
                   6889: 	   "&scantron_format=".&escape($env{'form.scantron_format'}).
                   6890: 	   "&scantron_CODElist=".&escape($env{'form.scantron_CODElist'}).
                   6891: 	   "&curCODE=".&escape($$scan_record{'scantron.CODE'}).
                   6892: 	   "&scantron_selectfile=".&escape($env{'form.scantron_selectfile'});
1.332     albertel 6893: 	if ($env{'form.scantron_CODElist'} =~ /\S/) { 
1.492     albertel 6894: 	    $r->print("
                   6895:     <label>
                   6896:        <input type='radio' name='scantron_CODE_resolution' value='use_found' />
                   6897:        ".&mt("[_1]Select[_2] a CODE from the list of all CODEs and use it.",
                   6898: 	     "<a target='_blank' href='$href'>","</a>")."
                   6899:     </label> 
1.558     bisitz   6900:     ".&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 6901: 	    $r->print("\n<br />");
                   6902: 	}
1.492     albertel 6903: 	$r->print("
                   6904:     <label>
                   6905:        <input type='radio' name='scantron_CODE_resolution' value='use_typed' />
                   6906:        ".&mt("Use [_1] as the CODE.",
                   6907: 	     "</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 6908: 	$r->print("\n<br /><br />");
1.157     albertel 6909:     } elsif ($error eq 'doublebubble') {
1.503     raeburn  6910: 	$r->print("<p>".&mt("There have been multiple bubbles scanned for some question(s)")."</p>\n");
1.497     foxr     6911: 
                   6912: 	# The form field scantron_questions is acutally a list of line numbers.
                   6913: 	# represented by this form so:
                   6914: 
                   6915: 	my $line_list = &questions_to_line_list($arg);
                   6916: 
1.157     albertel 6917: 	$r->print('<input type="hidden" name="scantron_questions" value="'.
1.497     foxr     6918: 		  $line_list.'" />');
1.242     albertel 6919: 	$r->print($message);
1.492     albertel 6920: 	$r->print("<p>".&mt("Please indicate which bubble should be used for grading")."</p>");
1.157     albertel 6921: 	foreach my $question (@{$arg}) {
1.503     raeburn  6922: 	    my @linenums = &prompt_for_corrections($r,$question,$scan_config,
                   6923:                                                    $scan_record, $error);
1.524     raeburn  6924:             push(@lines_to_correct,@linenums);
1.157     albertel 6925: 	}
1.503     raeburn  6926:         $r->print(&verify_bubbles_checked(@lines_to_correct));
1.157     albertel 6927:     } elsif ($error eq 'missingbubble') {
1.492     albertel 6928: 	$r->print("<p>".&mt("There have been <b>no</b> bubbles scanned for some question(s)")."</p>\n");
1.242     albertel 6929: 	$r->print($message);
1.492     albertel 6930: 	$r->print("<p>".&mt("Please indicate which bubble should be used for grading.")."</p>");
1.503     raeburn  6931: 	$r->print(&mt("Some questions have no scanned bubbles.")."\n");
1.497     foxr     6932: 
1.503     raeburn  6933: 	# The form field scantron_questions is actually a list of line numbers not
1.497     foxr     6934: 	# a list of question numbers. Therefore:
                   6935: 	#
                   6936: 	
                   6937: 	my $line_list = &questions_to_line_list($arg);
                   6938: 
1.157     albertel 6939: 	$r->print('<input type="hidden" name="scantron_questions" value="'.
1.497     foxr     6940: 		  $line_list.'" />');
1.157     albertel 6941: 	foreach my $question (@{$arg}) {
1.503     raeburn  6942: 	    my @linenums = &prompt_for_corrections($r,$question,$scan_config,
                   6943:                                                    $scan_record, $error);
1.524     raeburn  6944:             push(@lines_to_correct,@linenums);
1.157     albertel 6945: 	}
1.503     raeburn  6946:         $r->print(&verify_bubbles_checked(@lines_to_correct));
1.157     albertel 6947:     } else {
                   6948: 	$r->print("\n<ul>");
                   6949:     }
                   6950:     $r->print("\n</li></ul>");
1.497     foxr     6951: }
                   6952: 
1.503     raeburn  6953: sub verify_bubbles_checked {
                   6954:     my (@ansnums) = @_;
                   6955:     my $ansnumstr = join('","',@ansnums);
                   6956:     my $warning = &mt("A bubble or 'No bubble' selection has not been made for one or more lines.");
1.597     wenzelju 6957:     my $output = &Apache::lonhtmlcommon::scripttag((<<ENDSCRIPT));
1.503     raeburn  6958: function verify_bubble_radio(form) {
                   6959:     var ansnumArray = new Array ("$ansnumstr");
                   6960:     var need_bubble_count = 0;
                   6961:     for (var i=0; i<ansnumArray.length; i++) {
                   6962:         if (form.elements["scantron_correct_Q_"+ansnumArray[i]].length > 1) {
                   6963:             var bubble_picked = 0; 
                   6964:             for (var j=0; j<form.elements["scantron_correct_Q_"+ansnumArray[i]].length; j++) {
                   6965:                 if (form.elements["scantron_correct_Q_"+ansnumArray[i]][j].checked == true) {
                   6966:                     bubble_picked = 1;
                   6967:                 }
                   6968:             }
                   6969:             if (bubble_picked == 0) {
                   6970:                 need_bubble_count ++;
                   6971:             }
                   6972:         }
                   6973:     }
                   6974:     if (need_bubble_count) {
                   6975:         alert("$warning");
                   6976:         return;
                   6977:     }
                   6978:     form.submit(); 
                   6979: }
                   6980: ENDSCRIPT
                   6981:     return $output;
                   6982: }
                   6983: 
1.497     foxr     6984: =pod
                   6985: 
                   6986: =item  questions_to_line_list
1.157     albertel 6987: 
1.497     foxr     6988: Converts a list of questions into a string of comma separated
                   6989: line numbers in the answer sheet used by the questions.  This is
                   6990: used to fill in the scantron_questions form field.
                   6991: 
                   6992:   Arguments:
                   6993:      questions    - Reference to an array of questions.
                   6994: 
                   6995: =cut
                   6996: 
                   6997: 
                   6998: sub questions_to_line_list {
                   6999:     my ($questions) = @_;
                   7000:     my @lines;
                   7001: 
1.503     raeburn  7002:     foreach my $item (@{$questions}) {
                   7003:         my $question = $item;
                   7004:         my ($first,$count,$last);
                   7005:         if ($item =~ /^(\d+)\.(\d+)$/) {
                   7006:             $question = $1;
                   7007:             my $subquestion = $2;
                   7008:             $first = $first_bubble_line{$question-1} + 1;
                   7009:             my @subans = split(/,/,$subdivided_bubble_lines{$question-1});
                   7010:             my $subcount = 1;
                   7011:             while ($subcount<$subquestion) {
                   7012:                 $first += $subans[$subcount-1];
                   7013:                 $subcount ++;
                   7014:             }
                   7015:             $count = $subans[$subquestion-1];
                   7016:         } else {
                   7017: 	    $first   = $first_bubble_line{$question-1} + 1;
                   7018: 	    $count   = $bubble_lines_per_response{$question-1};
                   7019:         }
1.506     raeburn  7020:         $last = $first+$count-1;
1.503     raeburn  7021:         push(@lines, ($first..$last));
1.497     foxr     7022:     }
                   7023:     return join(',', @lines);
                   7024: }
                   7025: 
                   7026: =pod 
                   7027: 
                   7028: =item prompt_for_corrections
                   7029: 
                   7030: Prompts for a potentially multiline correction to the
                   7031: user's bubbling (factors out common code from scantron_get_correction
                   7032: for multi and missing bubble cases).
                   7033: 
                   7034:  Arguments:
                   7035:    $r           - Apache request object.
                   7036:    $question    - The question number to prompt for.
                   7037:    $scan_config - The scantron file configuration hash.
                   7038:    $scan_record - Reference to the hash that has the the parsed scanlines.
1.503     raeburn  7039:    $error       - Type of error
1.497     foxr     7040: 
                   7041:  Implicit inputs:
                   7042:    %bubble_lines_per_response   - Starting line numbers for each question.
                   7043:                                   Numbered from 0 (but question numbers are from
                   7044:                                   1.
                   7045:    %first_bubble_line           - Starting bubble line for each question.
1.509     raeburn  7046:    %subdivided_bubble_lines     - optionresponse, matchresponse and rankresponse 
                   7047:                                   type problems render as separate sub-questions, 
1.503     raeburn  7048:                                   in exam mode. This hash contains a 
                   7049:                                   comma-separated list of the lines per 
                   7050:                                   sub-question.
1.510     raeburn  7051:    %responsetype_per_response   - essayresponse, formularesponse,
                   7052:                                   stringresponse, imageresponse, reactionresponse,
                   7053:                                   and organicresponse type problem parts can have
1.503     raeburn  7054:                                   multiple lines per response if the weight
                   7055:                                   assigned exceeds 10.  In this case, only
                   7056:                                   one bubble per line is permitted, but more 
                   7057:                                   than one line might contain bubbles, e.g.
                   7058:                                   bubbling of: line 1 - J, line 2 - J, 
                   7059:                                   line 3 - B would assign 22 points.  
1.497     foxr     7060: 
                   7061: =cut
                   7062: 
                   7063: sub prompt_for_corrections {
1.503     raeburn  7064:     my ($r, $question, $scan_config, $scan_record, $error) = @_;
                   7065:     my ($current_line,$lines);
                   7066:     my @linenums;
                   7067:     my $questionnum = $question;
                   7068:     if ($question =~ /^(\d+)\.(\d+)$/) {
                   7069:         $question = $1;
                   7070:         $current_line = $first_bubble_line{$question-1} + 1 ;
                   7071:         my $subquestion = $2;
                   7072:         my @subans = split(/,/,$subdivided_bubble_lines{$question-1});
                   7073:         my $subcount = 1;
                   7074:         while ($subcount<$subquestion) {
                   7075:             $current_line += $subans[$subcount-1];
                   7076:             $subcount ++;
                   7077:         }
                   7078:         $lines = $subans[$subquestion-1];
                   7079:     } else {
                   7080:         $current_line = $first_bubble_line{$question-1} + 1 ;
                   7081:         $lines        = $bubble_lines_per_response{$question-1};
                   7082:     }
1.497     foxr     7083:     if ($lines > 1) {
1.503     raeburn  7084:         $r->print(&mt('The group of bubble lines below responds to a single question.').'<br />');
                   7085:         if (($responsetype_per_response{$question-1} eq 'essayresponse') ||
                   7086:             ($responsetype_per_response{$question-1} eq 'formularesponse') ||
1.510     raeburn  7087:             ($responsetype_per_response{$question-1} eq 'stringresponse') ||
                   7088:             ($responsetype_per_response{$question-1} eq 'imageresponse') ||
                   7089:             ($responsetype_per_response{$question-1} eq 'reactionresponse') ||
                   7090:             ($responsetype_per_response{$question-1} eq 'organicresponse')) {
1.572     www      7091:             $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  7092:         } else {
                   7093:             $r->print(&mt("Select at most one bubble in a single line and select 'No Bubble' in all the other lines. ")."<br />");
                   7094:         }
1.497     foxr     7095:     }
                   7096:     for (my $i =0; $i < $lines; $i++) {
1.503     raeburn  7097:         my $selected = $$scan_record{"scantron.$current_line.answer"};
                   7098: 	&scantron_bubble_selector($r,$scan_config,$current_line, 
                   7099: 	        		  $questionnum,$error,split('', $selected));
1.524     raeburn  7100:         push(@linenums,$current_line);
1.497     foxr     7101: 	$current_line++;
                   7102:     }
                   7103:     if ($lines > 1) {
                   7104: 	$r->print("<hr /><br />");
                   7105:     }
1.503     raeburn  7106:     return @linenums;
1.157     albertel 7107: }
1.423     albertel 7108: 
                   7109: =pod
                   7110: 
                   7111: =item scantron_bubble_selector
                   7112:   
                   7113:    Generates the html radiobuttons to correct a single bubble line
1.424     albertel 7114:    possibly showing the existing the selected bubbles if known
1.423     albertel 7115: 
                   7116:  Arguments:
                   7117:     $r           - Apache request object
                   7118:     $scan_config - hash from &get_scantron_config()
1.497     foxr     7119:     $line        - Number of the line being displayed.
1.503     raeburn  7120:     $questionnum - Question number (may include subquestion)
                   7121:     $error       - Type of error.
1.497     foxr     7122:     @selected    - Array of bubbles picked on this line.
1.423     albertel 7123: 
                   7124: =cut
                   7125: 
1.157     albertel 7126: sub scantron_bubble_selector {
1.503     raeburn  7127:     my ($r,$scan_config,$line,$questionnum,$error,@selected)=@_;
1.157     albertel 7128:     my $max=$$scan_config{'Qlength'};
1.274     albertel 7129: 
                   7130:     my $scmode=$$scan_config{'Qon'};
                   7131:     if ($scmode eq 'number' || $scmode eq 'letter') { $max=10; }	     
                   7132: 
1.157     albertel 7133:     my @alphabet=('A'..'Z');
1.503     raeburn  7134:     $r->print(&Apache::loncommon::start_data_table().
                   7135:               &Apache::loncommon::start_data_table_row());
                   7136:     $r->print('<td rowspan="2" class="LC_leftcol_header">'.$line.'</td>');
1.497     foxr     7137:     for (my $i=0;$i<$max+1;$i++) {
                   7138: 	$r->print("\n".'<td align="center">');
                   7139: 	if ($selected[0] eq $alphabet[$i]) { $r->print('X'); shift(@selected) }
                   7140: 	else { $r->print('&nbsp;'); }
                   7141: 	$r->print('</td>');
                   7142:     }
1.503     raeburn  7143:     $r->print(&Apache::loncommon::end_data_table_row().
                   7144:               &Apache::loncommon::start_data_table_row());
1.497     foxr     7145:     for (my $i=0;$i<$max;$i++) {
                   7146: 	$r->print("\n".
                   7147: 		  '<td><label><input type="radio" name="scantron_correct_Q_'.
                   7148: 		  $line.'" value="'.$i.'" />'.$alphabet[$i]."</label></td>");
                   7149:     }
1.503     raeburn  7150:     my $nobub_checked = ' ';
                   7151:     if ($error eq 'missingbubble') {
                   7152:         $nobub_checked = ' checked = "checked" ';
                   7153:     }
                   7154:     $r->print("\n".'<td><label><input type="radio" name="scantron_correct_Q_'.
                   7155: 	      $line.'" value="none"'.$nobub_checked.'/>'.&mt('No bubble').
                   7156:               '</label>'."\n".'<input type="hidden" name="scantron_questionnum_Q_'.
                   7157:               $line.'" value="'.$questionnum.'" /></td>');
                   7158:     $r->print(&Apache::loncommon::end_data_table_row().
                   7159:               &Apache::loncommon::end_data_table());
1.157     albertel 7160: }
                   7161: 
1.423     albertel 7162: =pod
                   7163: 
                   7164: =item num_matches
                   7165: 
1.424     albertel 7166:    Counts the number of characters that are the same between the two arguments.
                   7167: 
                   7168:  Arguments:
                   7169:    $orig - CODE from the scanline
                   7170:    $code - CODE to match against
                   7171: 
                   7172:  Returns:
                   7173:    $count - integer count of the number of same characters between the
                   7174:             two arguments
                   7175: 
1.423     albertel 7176: =cut
                   7177: 
1.194     albertel 7178: sub num_matches {
                   7179:     my ($orig,$code) = @_;
                   7180:     my @code=split(//,$code);
                   7181:     my @orig=split(//,$orig);
                   7182:     my $same=0;
                   7183:     for (my $i=0;$i<scalar(@code);$i++) {
                   7184: 	if ($code[$i] eq $orig[$i]) { $same++; }
                   7185:     }
                   7186:     return $same;
                   7187: }
                   7188: 
1.423     albertel 7189: =pod
                   7190: 
                   7191: =item scantron_get_closely_matching_CODEs
                   7192: 
1.424     albertel 7193:    Cycles through all CODEs and finds the set that has the greatest
                   7194:    number of same characters as the provided CODE
                   7195: 
                   7196:  Arguments:
                   7197:    $allcodes - hash ref returned by &get_codes()
                   7198:    $CODE     - CODE from the current scanline
                   7199: 
                   7200:  Returns:
                   7201:    2 element list
                   7202:     - first elements is number of how closely matching the best fit is 
                   7203:       (5 means best set has 5 matching characters)
                   7204:     - second element is an arrary ref containing the set of valid CODEs
                   7205:       that best fit the passed in CODE
                   7206: 
1.423     albertel 7207: =cut
                   7208: 
1.194     albertel 7209: sub scantron_get_closely_matching_CODEs {
                   7210:     my ($allcodes,$CODE)=@_;
                   7211:     my @CODEs;
                   7212:     foreach my $testcode (sort(keys(%{$allcodes}))) {
                   7213: 	push(@{$CODEs[&num_matches($CODE,$testcode)]},$testcode);
                   7214:     }
                   7215: 
                   7216:     return ($#CODEs,$CODEs[-1]);
                   7217: }
                   7218: 
1.423     albertel 7219: =pod
                   7220: 
                   7221: =item get_codes
                   7222: 
1.424     albertel 7223:    Builds a hash which has keys of all of the valid CODEs from the selected
                   7224:    set of remembered CODEs.
                   7225: 
                   7226:  Arguments:
                   7227:   $old_name - name of the set of remembered CODEs
                   7228:   $cdom     - domain of the course
                   7229:   $cnum     - internal course name
                   7230: 
                   7231:  Returns:
                   7232:   %allcodes - keys are the valid CODEs, values are all 1
                   7233: 
1.423     albertel 7234: =cut
                   7235: 
1.194     albertel 7236: sub get_codes {
1.280     foxr     7237:     my ($old_name, $cdom, $cnum) = @_;
                   7238:     if (!$old_name) {
                   7239: 	$old_name=$env{'form.scantron_CODElist'};
                   7240:     }
                   7241:     if (!$cdom) {
                   7242: 	$cdom =$env{'course.'.$env{'request.course.id'}.'.domain'};
                   7243:     }
                   7244:     if (!$cnum) {
                   7245: 	$cnum =$env{'course.'.$env{'request.course.id'}.'.num'};
                   7246:     }
1.278     albertel 7247:     my %result=&Apache::lonnet::get('CODEs',[$old_name,"type\0$old_name"],
                   7248: 				    $cdom,$cnum);
                   7249:     my %allcodes;
                   7250:     if ($result{"type\0$old_name"} eq 'number') {
                   7251: 	%allcodes=map {($_,1)} split(',',$result{$old_name});
                   7252:     } else {
                   7253: 	%allcodes=map {(&Apache::lonprintout::num_to_letters($_),1)} split(',',$result{$old_name});
                   7254:     }
1.194     albertel 7255:     return %allcodes;
                   7256: }
                   7257: 
1.423     albertel 7258: =pod
                   7259: 
                   7260: =item scantron_validate_CODE
                   7261: 
1.424     albertel 7262:    Validates all scanlines in the selected file to not have any
                   7263:    invalid or underspecified CODEs and that none of the codes are
                   7264:    duplicated if this was requested.
                   7265: 
1.423     albertel 7266: =cut
                   7267: 
1.157     albertel 7268: sub scantron_validate_CODE {
                   7269:     my ($r,$currentphase) = @_;
1.257     albertel 7270:     my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
1.186     albertel 7271:     if ($scantron_config{'CODElocation'} &&
                   7272: 	$scantron_config{'CODEstart'} &&
                   7273: 	$scantron_config{'CODElength'}) {
1.257     albertel 7274: 	if (!defined($env{'form.scantron_CODElist'})) {
1.186     albertel 7275: 	    &FIXME_blow_up()
                   7276: 	}
                   7277:     } else {
                   7278: 	return (0,$currentphase+1);
                   7279:     }
                   7280:     
                   7281:     my %usedCODEs;
                   7282: 
1.194     albertel 7283:     my %allcodes=&get_codes();
1.186     albertel 7284: 
1.582     raeburn  7285:     my $nav_error;
                   7286:     &scantron_get_maxbubble(\$nav_error); # parse needs the lines per response array.
                   7287:     if ($nav_error) {
                   7288:         $r->print(&navmap_errormsg());
                   7289:         return(1,$currentphase);
                   7290:     }
1.447     foxr     7291: 
1.186     albertel 7292:     my ($scanlines,$scan_data)=&scantron_getfile();
                   7293:     for (my $i=0;$i<=$scanlines->{'count'};$i++) {
1.200     albertel 7294: 	my $line=&scantron_get_line($scanlines,$scan_data,$i);
1.186     albertel 7295: 	if ($line=~/^[\s\cz]*$/) { next; }
                   7296: 	my $scan_record=&scantron_parse_scanline($line,$i,\%scantron_config,
                   7297: 						 $scan_data);
                   7298: 	my $CODE=$$scan_record{'scantron.CODE'};
                   7299: 	my $error=0;
1.224     albertel 7300: 	if (!&Apache::lonnet::validCODE($CODE)) {
                   7301: 	    &scantron_get_correction($r,$i,$scan_record,
                   7302: 				     \%scantron_config,
                   7303: 				     $line,'incorrectCODE',\%allcodes);
                   7304: 	    return(1,$currentphase);
                   7305: 	}
1.221     albertel 7306: 	if (%allcodes && !exists($allcodes{$CODE}) 
                   7307: 	    && !$$scan_record{'scantron.useCODE'}) {
1.186     albertel 7308: 	    &scantron_get_correction($r,$i,$scan_record,
                   7309: 				     \%scantron_config,
1.194     albertel 7310: 				     $line,'incorrectCODE',\%allcodes);
                   7311: 	    return(1,$currentphase);
1.186     albertel 7312: 	}
1.214     albertel 7313: 	if (exists($usedCODEs{$CODE}) 
1.257     albertel 7314: 	    && $env{'form.scantron_CODEunique'} eq 'yes'
1.192     albertel 7315: 	    && !$$scan_record{'scantron.CODE_ignore_dup'}) {
1.186     albertel 7316: 	    &scantron_get_correction($r,$i,$scan_record,
                   7317: 				     \%scantron_config,
1.194     albertel 7318: 				     $line,'duplicateCODE',$usedCODEs{$CODE});
                   7319: 	    return(1,$currentphase);
1.186     albertel 7320: 	}
1.524     raeburn  7321: 	push(@{$usedCODEs{$CODE}},$$scan_record{'scantron.PaperID'});
1.186     albertel 7322:     }
1.157     albertel 7323:     return (0,$currentphase+1);
                   7324: }
                   7325: 
1.423     albertel 7326: =pod
                   7327: 
                   7328: =item scantron_validate_doublebubble
                   7329: 
1.424     albertel 7330:    Validates all scanlines in the selected file to not have any
                   7331:    bubble lines with multiple bubbles marked.
                   7332: 
1.423     albertel 7333: =cut
                   7334: 
1.157     albertel 7335: sub scantron_validate_doublebubble {
                   7336:     my ($r,$currentphase) = @_;
                   7337:     #get student info
                   7338:     my $classlist=&Apache::loncoursedata::get_classlist();
                   7339:     my %idmap=&username_to_idmap($classlist);
                   7340: 
                   7341:     #get scantron line setup
1.257     albertel 7342:     my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
1.157     albertel 7343:     my ($scanlines,$scan_data)=&scantron_getfile();
1.583     raeburn  7344:     my $nav_error;
                   7345:     &scantron_get_maxbubble(\$nav_error); # parse needs the bubble line array.
                   7346:     if ($nav_error) {
                   7347:         $r->print(&navmap_errormsg());
                   7348:         return(1,$currentphase);
                   7349:     }
1.447     foxr     7350: 
1.157     albertel 7351:     for (my $i=0;$i<=$scanlines->{'count'};$i++) {
1.200     albertel 7352: 	my $line=&scantron_get_line($scanlines,$scan_data,$i);
1.157     albertel 7353: 	if ($line=~/^[\s\cz]*$/) { next; }
                   7354: 	my $scan_record=&scantron_parse_scanline($line,$i,\%scantron_config,
                   7355: 						 $scan_data);
                   7356: 	if (!defined($$scan_record{'scantron.doubleerror'})) { next; }
                   7357: 	&scantron_get_correction($r,$i,$scan_record,\%scantron_config,$line,
                   7358: 				 'doublebubble',
                   7359: 				 $$scan_record{'scantron.doubleerror'});
                   7360:     	return (1,$currentphase);
                   7361:     }
                   7362:     return (0,$currentphase+1);
                   7363: }
                   7364: 
1.423     albertel 7365: 
1.503     raeburn  7366: sub scantron_get_maxbubble {
1.582     raeburn  7367:     my ($nav_error) = @_;
1.257     albertel 7368:     if (defined($env{'form.scantron_maxbubble'}) &&
                   7369: 	$env{'form.scantron_maxbubble'}) {
1.447     foxr     7370: 	&restore_bubble_lines();
1.257     albertel 7371: 	return $env{'form.scantron_maxbubble'};
1.191     albertel 7372:     }
1.330     albertel 7373: 
1.447     foxr     7374:     my (undef, undef, $sequence) =
1.257     albertel 7375: 	&Apache::lonnet::decode_symb($env{'form.selectpage'});
1.330     albertel 7376: 
1.447     foxr     7377:     my $navmap=Apache::lonnavmaps::navmap->new();
1.582     raeburn  7378:     unless (ref($navmap)) {
                   7379:         if (ref($nav_error)) {
                   7380:             $$nav_error = 1;
                   7381:         }
1.591     raeburn  7382:         return;
1.582     raeburn  7383:     }
1.191     albertel 7384:     my $map=$navmap->getResourceByUrl($sequence);
                   7385:     my @resources=$navmap->retrieveResources($map,\&scantron_filter,1,0);
1.330     albertel 7386: 
                   7387:     &Apache::lonxml::clear_problem_counter();
                   7388: 
1.557     raeburn  7389:     my $uname       = $env{'user.name'};
                   7390:     my $udom        = $env{'user.domain'};
1.435     foxr     7391:     my $cid         = $env{'request.course.id'};
                   7392:     my $total_lines = 0;
                   7393:     %bubble_lines_per_response = ();
1.447     foxr     7394:     %first_bubble_line         = ();
1.503     raeburn  7395:     %subdivided_bubble_lines   = ();
                   7396:     %responsetype_per_response = ();
1.554     raeburn  7397: 
1.447     foxr     7398:     my $response_number = 0;
                   7399:     my $bubble_line     = 0;
1.191     albertel 7400:     foreach my $resource (@resources) {
1.542     raeburn  7401:         my ($analysis,$parts) = &scantron_partids_tograde($resource,$cid,$uname,$udom);
                   7402:         if ((ref($analysis) eq 'HASH') && (ref($parts) eq 'ARRAY')) {
                   7403: 	    foreach my $part_id (@{$parts}) {
                   7404:                 my $lines;
                   7405: 
                   7406: 	        # TODO - make this a persistent hash not an array.
                   7407: 
                   7408:                 # optionresponse, matchresponse and rankresponse type items 
                   7409:                 # render as separate sub-questions in exam mode.
                   7410:                 if (($analysis->{$part_id.'.type'} eq 'optionresponse') ||
                   7411:                     ($analysis->{$part_id.'.type'} eq 'matchresponse') ||
                   7412:                     ($analysis->{$part_id.'.type'} eq 'rankresponse')) {
                   7413:                     my ($numbub,$numshown);
                   7414:                     if ($analysis->{$part_id.'.type'} eq 'optionresponse') {
                   7415:                         if (ref($analysis->{$part_id.'.options'}) eq 'ARRAY') {
                   7416:                             $numbub = scalar(@{$analysis->{$part_id.'.options'}});
                   7417:                         }
                   7418:                     } elsif ($analysis->{$part_id.'.type'} eq 'matchresponse') {
                   7419:                         if (ref($analysis->{$part_id.'.items'}) eq 'ARRAY') {
                   7420:                             $numbub = scalar(@{$analysis->{$part_id.'.items'}});
                   7421:                         }
                   7422:                     } elsif ($analysis->{$part_id.'.type'} eq 'rankresponse') {
                   7423:                         if (ref($analysis->{$part_id.'.foils'}) eq 'ARRAY') {
                   7424:                             $numbub = scalar(@{$analysis->{$part_id.'.foils'}});
                   7425:                         }
                   7426:                     }
                   7427:                     if (ref($analysis->{$part_id.'.shown'}) eq 'ARRAY') {
                   7428:                         $numshown = scalar(@{$analysis->{$part_id.'.shown'}});
                   7429:                     }
                   7430:                     my $bubbles_per_line = 10;
                   7431:                     my $inner_bubble_lines = int($numbub/$bubbles_per_line);
                   7432:                     if (($numbub % $bubbles_per_line) != 0) {
                   7433:                         $inner_bubble_lines++;
                   7434:                     }
                   7435:                     for (my $i=0; $i<$numshown; $i++) {
                   7436:                         $subdivided_bubble_lines{$response_number} .= 
                   7437:                             $inner_bubble_lines.',';
                   7438:                     }
                   7439:                     $subdivided_bubble_lines{$response_number} =~ s/,$//;
                   7440:                     $lines = $numshown * $inner_bubble_lines;
                   7441:                 } else {
                   7442:                     $lines = $analysis->{"$part_id.bubble_lines"};
                   7443:                 } 
                   7444: 
                   7445:                 $first_bubble_line{$response_number} = $bubble_line;
                   7446: 	        $bubble_lines_per_response{$response_number} = $lines;
                   7447:                 $responsetype_per_response{$response_number} = 
                   7448:                     $analysis->{$part_id.'.type'};
                   7449: 	        $response_number++;
                   7450: 
                   7451: 	        $bubble_line +=  $lines;
                   7452: 	        $total_lines +=  $lines;
                   7453: 	    }
                   7454:         }
                   7455:     }
1.552     raeburn  7456:     &Apache::lonnet::delenv('scantron.');
1.542     raeburn  7457: 
                   7458:     &save_bubble_lines();
                   7459:     $env{'form.scantron_maxbubble'} =
                   7460: 	$total_lines;
                   7461:     return $env{'form.scantron_maxbubble'};
                   7462: }
1.523     raeburn  7463: 
1.157     albertel 7464: sub scantron_validate_missingbubbles {
                   7465:     my ($r,$currentphase) = @_;
                   7466:     #get student info
                   7467:     my $classlist=&Apache::loncoursedata::get_classlist();
                   7468:     my %idmap=&username_to_idmap($classlist);
                   7469: 
                   7470:     #get scantron line setup
1.257     albertel 7471:     my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
1.157     albertel 7472:     my ($scanlines,$scan_data)=&scantron_getfile();
1.582     raeburn  7473:     my $nav_error;
                   7474:     my $max_bubble=&scantron_get_maxbubble(\$nav_error);
                   7475:     if ($nav_error) {
                   7476:         return(1,$currentphase);
                   7477:     }
1.157     albertel 7478:     if (!$max_bubble) { $max_bubble=2**31; }
                   7479:     for (my $i=0;$i<=$scanlines->{'count'};$i++) {
1.200     albertel 7480: 	my $line=&scantron_get_line($scanlines,$scan_data,$i);
1.157     albertel 7481: 	if ($line=~/^[\s\cz]*$/) { next; }
                   7482: 	my $scan_record=&scantron_parse_scanline($line,$i,\%scantron_config,
                   7483: 						 $scan_data);
                   7484: 	if (!defined($$scan_record{'scantron.missingerror'})) { next; }
                   7485: 	my @to_correct;
1.470     foxr     7486: 	
                   7487: 	# Probably here's where the error is...
                   7488: 
1.157     albertel 7489: 	foreach my $missing (@{$$scan_record{'scantron.missingerror'}}) {
1.505     raeburn  7490:             my $lastbubble;
                   7491:             if ($missing =~ /^(\d+)\.(\d+)$/) {
                   7492:                my $question = $1;
                   7493:                my $subquestion = $2;
                   7494:                if (!defined($first_bubble_line{$question -1})) { next; }
                   7495:                my $first = $first_bubble_line{$question-1};
                   7496:                my @subans = split(/,/,$subdivided_bubble_lines{$question-1});
                   7497:                my $subcount = 1;
                   7498:                while ($subcount<$subquestion) {
                   7499:                    $first += $subans[$subcount-1];
                   7500:                    $subcount ++;
                   7501:                }
                   7502:                my $count = $subans[$subquestion-1];
                   7503:                $lastbubble = $first + $count;
                   7504:             } else {
                   7505:                 if (!defined($first_bubble_line{$missing - 1})) { next; }
                   7506:                 $lastbubble = $first_bubble_line{$missing - 1} + $bubble_lines_per_response{$missing - 1};
                   7507:             }
                   7508:             if ($lastbubble > $max_bubble) { next; }
1.157     albertel 7509: 	    push(@to_correct,$missing);
                   7510: 	}
                   7511: 	if (@to_correct) {
                   7512: 	    &scantron_get_correction($r,$i,$scan_record,\%scantron_config,
                   7513: 				     $line,'missingbubble',\@to_correct);
                   7514: 	    return (1,$currentphase);
                   7515: 	}
                   7516: 
                   7517:     }
                   7518:     return (0,$currentphase+1);
                   7519: }
                   7520: 
1.423     albertel 7521: 
1.82      albertel 7522: sub scantron_process_students {
1.608     www      7523:     my ($r,$symb) = @_;
1.513     foxr     7524: 
1.257     albertel 7525:     my (undef,undef,$sequence)=&Apache::lonnet::decode_symb($env{'form.selectpage'});
1.513     foxr     7526:     if (!$symb) {
                   7527: 	return '';
                   7528:     }
1.324     albertel 7529:     my $default_form_data=&defaultFormData($symb);
1.82      albertel 7530: 
1.257     albertel 7531:     my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
1.157     albertel 7532:     my ($scanlines,$scan_data)=&scantron_getfile();
1.82      albertel 7533:     my $classlist=&Apache::loncoursedata::get_classlist();
                   7534:     my %idmap=&username_to_idmap($classlist);
1.132     bowersj2 7535:     my $navmap=Apache::lonnavmaps::navmap->new();
1.582     raeburn  7536:     unless (ref($navmap)) {
                   7537:         $r->print(&navmap_errormsg());
                   7538:         return '';
                   7539:     }  
1.83      albertel 7540:     my $map=$navmap->getResourceByUrl($sequence);
                   7541:     my @resources=$navmap->retrieveResources($map,\&scantron_filter,1,0);
1.557     raeburn  7542:     my (%grader_partids_by_symb,%grader_randomlists_by_symb);
                   7543:     &graders_resources_pass(\@resources,\%grader_partids_by_symb,
                   7544:                             \%grader_randomlists_by_symb);
1.586     raeburn  7545:     my $resource_error;
1.557     raeburn  7546:     foreach my $resource (@resources) {
1.586     raeburn  7547:         my $ressymb;
                   7548:         if (ref($resource)) {
                   7549:             $ressymb = $resource->symb();
                   7550:         } else {
                   7551:             $resource_error = 1;
                   7552:             last;
                   7553:         }
1.557     raeburn  7554:         my ($analysis,$parts) =
                   7555:             &scantron_partids_tograde($resource,$env{'request.course.id'},
                   7556:                                       $env{'user.name'},$env{'user.domain'},1);
                   7557:         $grader_partids_by_symb{$ressymb} = $parts;
                   7558:         if (ref($analysis) eq 'HASH') {
                   7559:             if (ref($analysis->{'parts_withrandomlist'}) eq 'ARRAY') {
                   7560:                 $grader_randomlists_by_symb{$ressymb} = 
                   7561:                     $analysis->{'parts_withrandomlist'};
                   7562:             }
                   7563:         }
                   7564:     }
1.586     raeburn  7565:     if ($resource_error) {
                   7566:         $r->print(&navmap_errormsg());
                   7567:         return '';
                   7568:     }
1.557     raeburn  7569: 
1.554     raeburn  7570:     my ($uname,$udom);
1.82      albertel 7571:     my $result= <<SCANTRONFORM;
1.81      albertel 7572: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="scantronupload">
                   7573:   <input type="hidden" name="command" value="scantron_configphase" />
                   7574:   $default_form_data
                   7575: SCANTRONFORM
1.82      albertel 7576:     $r->print($result);
                   7577: 
                   7578:     my @delayqueue;
1.542     raeburn  7579:     my (%completedstudents,%scandata);
1.140     albertel 7580:     
1.520     www      7581:     my $lock=&Apache::lonnet::set_lock(&mt('Grading bubblesheet exam'));
1.200     albertel 7582:     my $count=&get_todo_count($scanlines,$scan_data);
1.575     www      7583:     my %prog_state=&Apache::lonhtmlcommon::Create_PrgWin($r,'Bubblesheet Status',
                   7584:  				    'Bubblesheet Progress',$count,
1.195     albertel 7585: 				    'inline',undef,'scantronupload');
1.140     albertel 7586:     &Apache::lonhtmlcommon::Update_PrgWin($r,\%prog_state,
                   7587: 					  'Processing first student');
1.542     raeburn  7588:     $r->print('<br />');
1.140     albertel 7589:     my $start=&Time::HiRes::time();
1.158     albertel 7590:     my $i=-1;
1.542     raeburn  7591:     my $started;
1.447     foxr     7592: 
1.582     raeburn  7593:     my $nav_error;
                   7594:     &scantron_get_maxbubble(\$nav_error); # Need the bubble lines array to parse.
                   7595:     if ($nav_error) {
                   7596:         $r->print(&navmap_errormsg());
                   7597:         return '';
                   7598:     }
                   7599: 
1.513     foxr     7600:     # If an ssi failed in scantron_get_maxbubble, put an error message out to
                   7601:     # the user and return.
                   7602: 
                   7603:     if ($ssi_error) {
                   7604: 	$r->print("</form>");
                   7605: 	&ssi_print_error($r);
1.520     www      7606:         &Apache::lonnet::remove_lock($lock);
1.513     foxr     7607: 	return '';		# Dunno why the other returns return '' rather than just returning.
                   7608:     }
1.447     foxr     7609: 
1.542     raeburn  7610:     my %lettdig = &letter_to_digits();
                   7611:     my $numletts = scalar(keys(%lettdig));
                   7612: 
1.157     albertel 7613:     while ($i<$scanlines->{'count'}) {
                   7614:  	($uname,$udom)=('','');
                   7615:  	$i++;
1.200     albertel 7616:  	my $line=&scantron_get_line($scanlines,$scan_data,$i);
1.157     albertel 7617:  	if ($line=~/^[\s\cz]*$/) { next; }
1.200     albertel 7618: 	if ($started) {
                   7619: 	    &Apache::lonhtmlcommon::Increment_PrgWin($r,\%prog_state,
                   7620: 						     'last student');
                   7621: 	}
                   7622: 	$started=1;
1.157     albertel 7623:  	my $scan_record=&scantron_parse_scanline($line,$i,\%scantron_config,
                   7624:  						 $scan_data);
                   7625:  	unless ($uname=&scantron_find_student($scan_record,$scan_data,
                   7626:  					      \%idmap,$i)) {
                   7627:   	    &scantron_add_delay(\@delayqueue,$line,
                   7628:  				'Unable to find a student that matches',1);
                   7629:  	    next;
                   7630:   	}
                   7631:  	if (exists $completedstudents{$uname}) {
                   7632:  	    &scantron_add_delay(\@delayqueue,$line,
                   7633:  				'Student '.$uname.' has multiple sheets',2);
                   7634:  	    next;
                   7635:  	}
                   7636:   	($uname,$udom)=split(/:/,$uname);
1.330     albertel 7637: 
1.586     raeburn  7638:         my (%partids_by_symb,$res_error);
1.554     raeburn  7639:         foreach my $resource (@resources) {
1.586     raeburn  7640:             my $ressymb;
                   7641:             if (ref($resource)) {
                   7642:                 $ressymb = $resource->symb();
                   7643:             } else {
                   7644:                 $res_error = 1;
                   7645:                 last;
                   7646:             }
1.557     raeburn  7647:             if ((exists($grader_randomlists_by_symb{$ressymb})) ||
                   7648:                 (ref($grader_partids_by_symb{$ressymb}) ne 'ARRAY')) {
                   7649:                 my ($analysis,$parts) =
                   7650:                     &scantron_partids_tograde($resource,$env{'request.course.id'},$uname,$udom);
                   7651:                 $partids_by_symb{$ressymb} = $parts;
                   7652:             } else {
                   7653:                 $partids_by_symb{$ressymb} = $grader_partids_by_symb{$ressymb};
                   7654:             }
1.554     raeburn  7655:         }
                   7656: 
1.586     raeburn  7657:         if ($res_error) {
                   7658:             &scantron_add_delay(\@delayqueue,$line,
                   7659:                                 'An error occurred while grading student '.$uname,2);
                   7660:             next;
                   7661:         }
                   7662: 
1.330     albertel 7663: 	&Apache::lonxml::clear_problem_counter();
1.514     raeburn  7664:   	&Apache::lonnet::appenv($scan_record);
1.376     albertel 7665: 
                   7666: 	if (&scantron_clear_skip($scanlines,$scan_data,$i)) {
                   7667: 	    &scantron_putfile($scanlines,$scan_data);
                   7668: 	}
1.161     albertel 7669: 	
1.542     raeburn  7670:         my $scancode;
                   7671:         if ((exists($scan_record->{'scantron.CODE'})) &&
                   7672:             (&Apache::lonnet::validCODE($scan_record->{'scantron.CODE'}))) {
                   7673:             $scancode = $scan_record->{'scantron.CODE'};
                   7674:         } else {
                   7675:             $scancode = '';
                   7676:         }
                   7677: 
                   7678:         if (&grade_student_bubbles($r,$uname,$udom,$scan_record,$scancode,
1.554     raeburn  7679:                                    \@resources,\%partids_by_symb) eq 'ssi_error') {
1.542     raeburn  7680:             $ssi_error = 0; # So end of handler error message does not trigger.
                   7681:             $r->print("</form>");
                   7682:             &ssi_print_error($r);
                   7683:             &Apache::lonnet::remove_lock($lock);
                   7684:             return '';      # Why return ''?  Beats me.
                   7685:         }
1.513     foxr     7686: 
1.140     albertel 7687: 	$completedstudents{$uname}={'line'=>$line};
1.542     raeburn  7688:         if ($env{'form.verifyrecord'}) {
                   7689:             my $lastpos = $env{'form.scantron_maxbubble'}*$scantron_config{'Qlength'};
                   7690:             my $studentdata = substr($line,$scantron_config{'Qstart'}-1,$lastpos);
                   7691:             chomp($studentdata);
                   7692:             $studentdata =~ s/\r$//;
                   7693:             my $studentrecord = '';
                   7694:             my $counter = -1;
                   7695:             foreach my $resource (@resources) {
1.554     raeburn  7696:                 my $ressymb = $resource->symb();
1.542     raeburn  7697:                 ($counter,my $recording) =
                   7698:                     &verify_scantron_grading($resource,$udom,$uname,$env{'request.course.id'},
1.554     raeburn  7699:                                              $counter,$studentdata,$partids_by_symb{$ressymb},
1.542     raeburn  7700:                                              \%scantron_config,\%lettdig,$numletts);
                   7701:                 $studentrecord .= $recording;
                   7702:             }
                   7703:             if ($studentrecord ne $studentdata) {
1.554     raeburn  7704:                 &Apache::lonxml::clear_problem_counter();
                   7705:                 if (&grade_student_bubbles($r,$uname,$udom,$scan_record,$scancode,
                   7706:                                            \@resources,\%partids_by_symb) eq 'ssi_error') {
                   7707:                     $ssi_error = 0; # So end of handler error message does not trigger.
                   7708:                     $r->print("</form>");
                   7709:                     &ssi_print_error($r);
                   7710:                     &Apache::lonnet::remove_lock($lock);
                   7711:                     delete($completedstudents{$uname});
                   7712:                     return '';
                   7713:                 }
1.542     raeburn  7714:                 $counter = -1;
                   7715:                 $studentrecord = '';
                   7716:                 foreach my $resource (@resources) {
1.554     raeburn  7717:                     my $ressymb = $resource->symb();
1.542     raeburn  7718:                     ($counter,my $recording) =
                   7719:                         &verify_scantron_grading($resource,$udom,$uname,$env{'request.course.id'},
1.554     raeburn  7720:                                                  $counter,$studentdata,$partids_by_symb{$ressymb},
1.542     raeburn  7721:                                                  \%scantron_config,\%lettdig,$numletts);
                   7722:                     $studentrecord .= $recording;
                   7723:                 }
                   7724:                 if ($studentrecord ne $studentdata) {
                   7725:                     $r->print('<p><span class="LC_error">');
                   7726:                     if ($scancode eq '') {
                   7727:                         $r->print(&mt('Mismatch grading bubble sheet for user: [_1] with ID: [_2].',
                   7728:                                   $uname.':'.$udom,$scan_record->{'scantron.ID'}));
                   7729:                     } else {
                   7730:                         $r->print(&mt('Mismatch grading bubble sheet for user: [_1] with ID: [_2] and CODE: [_3].',
                   7731:                                   $uname.':'.$udom,$scan_record->{'scantron.ID'},$scancode));
                   7732:                     }
                   7733:                     $r->print('</span><br />'.&Apache::loncommon::start_data_table()."\n".
                   7734:                               &Apache::loncommon::start_data_table_header_row()."\n".
                   7735:                               '<th>'.&mt('Source').'</th><th>'.&mt('Bubbled responses').'</th>'.
                   7736:                               &Apache::loncommon::end_data_table_header_row()."\n".
                   7737:                               &Apache::loncommon::start_data_table_row().
                   7738:                               '<td>'.&mt('Bubble Sheet').'</td>'.
                   7739:                               '<td><span class="LC_nobreak">'.$studentdata.'</span></td>'.
                   7740:                               &Apache::loncommon::end_data_table_row().
                   7741:                               &Apache::loncommon::start_data_table_row().
                   7742:                               '<td>Stored submissions</td>'.
                   7743:                               '<td><span class="LC_nobreak">'.$studentrecord.'</span></td>'."\n".
                   7744:                               &Apache::loncommon::end_data_table_row().
                   7745:                               &Apache::loncommon::end_data_table().'</p>');
                   7746:                 } else {
                   7747:                     $r->print('<br /><span class="LC_warning">'.
                   7748:                              &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 />'.
                   7749:                              &mt("As a consequence, this user's submission history records two tries.").
                   7750:                                  '</span><br />');
                   7751:                 }
                   7752:             }
                   7753:         }
1.543     raeburn  7754:         if (&Apache::loncommon::connection_aborted($r)) { last; }
1.140     albertel 7755:     } continue {
1.330     albertel 7756: 	&Apache::lonxml::clear_problem_counter();
1.552     raeburn  7757: 	&Apache::lonnet::delenv('scantron.');
1.82      albertel 7758:     }
1.140     albertel 7759:     &Apache::lonhtmlcommon::Close_PrgWin($r,\%prog_state);
1.520     www      7760:     &Apache::lonnet::remove_lock($lock);
1.172     albertel 7761: #    my $lasttime = &Time::HiRes::time()-$start;
                   7762: #    $r->print("<p>took $lasttime</p>");
1.140     albertel 7763: 
1.200     albertel 7764:     $r->print("</form>");
1.157     albertel 7765:     return '';
1.75      albertel 7766: }
1.157     albertel 7767: 
1.557     raeburn  7768: sub graders_resources_pass {
                   7769:     my ($resources,$grader_partids_by_symb,$grader_randomlists_by_symb) = @_;
                   7770:     if ((ref($resources) eq 'ARRAY') && (ref($grader_partids_by_symb)) && 
                   7771:         (ref($grader_randomlists_by_symb) eq 'HASH')) {
                   7772:         foreach my $resource (@{$resources}) {
                   7773:             my $ressymb = $resource->symb();
                   7774:             my ($analysis,$parts) =
                   7775:                 &scantron_partids_tograde($resource,$env{'request.course.id'},
                   7776:                                           $env{'user.name'},$env{'user.domain'},1);
                   7777:             $grader_partids_by_symb->{$ressymb} = $parts;
                   7778:             if (ref($analysis) eq 'HASH') {
                   7779:                 if (ref($analysis->{'parts_withrandomlist'}) eq 'ARRAY') {
                   7780:                     $grader_randomlists_by_symb->{$ressymb} =
                   7781:                         $analysis->{'parts_withrandomlist'};
                   7782:                 }
                   7783:             }
                   7784:         }
                   7785:     }
                   7786:     return;
                   7787: }
                   7788: 
1.542     raeburn  7789: sub grade_student_bubbles {
1.554     raeburn  7790:     my ($r,$uname,$udom,$scan_record,$scancode,$resources,$parts) = @_;
                   7791:     if (ref($resources) eq 'ARRAY') {
                   7792:         my $count = 0;
                   7793:         foreach my $resource (@{$resources}) {
                   7794:             my $ressymb = $resource->symb();
                   7795:             my %form = ('submitted'      => 'scantron',
                   7796:                         'grade_target'   => 'grade',
                   7797:                         'grade_username' => $uname,
                   7798:                         'grade_domain'   => $udom,
                   7799:                         'grade_courseid' => $env{'request.course.id'},
                   7800:                         'grade_symb'     => $ressymb,
                   7801:                         'CODE'           => $scancode
                   7802:                        );
                   7803:             if (ref($parts) eq 'HASH') {
                   7804:                 if (ref($parts->{$ressymb}) eq 'ARRAY') {
                   7805:                     foreach my $part (@{$parts->{$ressymb}}) {
                   7806:                         $form{'scantron_questnum_start.'.$part} =
                   7807:                             1+$env{'form.scantron.first_bubble_line.'.$count};
                   7808:                         $count++;
                   7809:                     }
                   7810:                 }
                   7811:             }
                   7812:             my $result=&ssi_with_retries($resource->src(),$ssi_retries,%form);
                   7813:             return 'ssi_error' if ($ssi_error);
                   7814:             last if (&Apache::loncommon::connection_aborted($r));
                   7815:         }
1.542     raeburn  7816:     }
                   7817:     return;
                   7818: }
                   7819: 
1.157     albertel 7820: sub scantron_upload_scantron_data {
1.608     www      7821:     my ($r,$symb)=@_;
1.565     raeburn  7822:     my $dom = $env{'request.role.domain'};
                   7823:     my $domdesc = &Apache::lonnet::domain($dom,'description');
                   7824:     $r->print(&Apache::loncommon::coursebrowser_javascript($dom));
1.157     albertel 7825:     my $select_link=&Apache::loncommon::selectcourse_link('rules','courseid',
1.181     albertel 7826: 							  'domainid',
1.565     raeburn  7827: 							  'coursename',$dom);
                   7828:     my $syllabuslink = '<a href="javascript:ToSyllabus();">'.&mt('Syllabus').'</a>'.
                   7829:                        ('&nbsp'x2).&mt('(shows course personnel)'); 
1.608     www      7830:     my $default_form_data=&defaultFormData($symb);
1.579     raeburn  7831:     my $nofile_alert = &mt('Please use the browse button to select a file from your local directory.');
                   7832:     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 7833:     $r->print(&Apache::lonhtmlcommon::scripttag('
1.157     albertel 7834:     function checkUpload(formname) {
                   7835: 	if (formname.upfile.value == "") {
1.579     raeburn  7836: 	    alert("'.$nofile_alert.'");
1.157     albertel 7837: 	    return false;
                   7838: 	}
1.565     raeburn  7839:         if (formname.courseid.value == "") {
1.579     raeburn  7840:             alert("'.$nocourseid_alert.'");
1.565     raeburn  7841:             return false;
                   7842:         }
1.157     albertel 7843: 	formname.submit();
                   7844:     }
1.565     raeburn  7845: 
                   7846:     function ToSyllabus() {
                   7847:         var cdom = '."'$dom'".';
                   7848:         var cnum = document.rules.courseid.value;
                   7849:         if (cdom == "" || cdom == null) {
                   7850:             return;
                   7851:         }
                   7852:         if (cnum == "" || cnum == null) {
                   7853:            return;
                   7854:         }
                   7855:         syllwin=window.open("/public/"+cdom+"/"+cnum+"/syllabus","LONCAPASyllabus",
                   7856:                             "height=350,width=350,scrollbars=yes,menubar=no");
                   7857:         return;
                   7858:     }
                   7859: 
1.597     wenzelju 7860: '));
                   7861:     $r->print('
1.566     raeburn  7862: <h3>'.&mt('Send scanned bubblesheet data to a course').'</h3>
                   7863: 
1.492     albertel 7864: <form enctype="multipart/form-data" action="/adm/grades" name="rules" method="post">
1.565     raeburn  7865: '.$default_form_data.
                   7866:   &Apache::lonhtmlcommon::start_pick_box().
                   7867:   &Apache::lonhtmlcommon::row_title(&mt('Course ID')).
                   7868:   '<input name="courseid" type="text" size="30" />'.$select_link.
                   7869:   &Apache::lonhtmlcommon::row_closure().
                   7870:   &Apache::lonhtmlcommon::row_title(&mt('Course Name')).
                   7871:   '<input name="coursename" type="text" size="30" />'.$syllabuslink.
                   7872:   &Apache::lonhtmlcommon::row_closure().
                   7873:   &Apache::lonhtmlcommon::row_title(&mt('Domain')).
                   7874:   '<input name="domainid" type="hidden" />'.$domdesc.
                   7875:   &Apache::lonhtmlcommon::row_closure().
                   7876:   &Apache::lonhtmlcommon::row_title(&mt('File to upload')).
                   7877:   '<input type="file" name="upfile" size="50" />'.
                   7878:   &Apache::lonhtmlcommon::row_closure(1).
                   7879:   &Apache::lonhtmlcommon::end_pick_box().'<br />
                   7880: 
1.492     albertel 7881: <input name="command" value="scantronupload_save" type="hidden" />
1.589     bisitz   7882: <input type="button" onclick="javascript:checkUpload(this.form);" value="'.&mt('Upload Bubblesheet Data').'" />
1.157     albertel 7883: </form>
1.492     albertel 7884: ');
1.157     albertel 7885:     return '';
                   7886: }
                   7887: 
1.423     albertel 7888: 
1.157     albertel 7889: sub scantron_upload_scantron_data_save {
1.608     www      7890:     my($r,$symb)=@_;
1.182     albertel 7891:     my $doanotherupload=
                   7892: 	'<br /><form action="/adm/grades" method="post">'."\n".
                   7893: 	'<input type="hidden" name="command" value="scantronupload" />'."\n".
1.492     albertel 7894: 	'<input type="submit" name="submit" value="'.&mt('Do Another Upload').'" />'."\n".
1.182     albertel 7895: 	'</form>'."\n";
1.257     albertel 7896:     if (!&Apache::lonnet::allowed('usc',$env{'form.domainid'}) &&
1.162     albertel 7897: 	!&Apache::lonnet::allowed('usc',
1.257     albertel 7898: 			    $env{'form.domainid'}.'_'.$env{'form.courseid'})) {
1.575     www      7899: 	$r->print(&mt("You are not allowed to upload bubblesheet data to the requested course.")."<br />");
1.614     www      7900: 	unless ($symb) {
1.182     albertel 7901: 	    $r->print($doanotherupload);
                   7902: 	}
1.162     albertel 7903: 	return '';
                   7904:     }
1.257     albertel 7905:     my %coursedata=&Apache::lonnet::coursedescription($env{'form.domainid'}.'_'.$env{'form.courseid'});
1.568     raeburn  7906:     my $uploadedfile;
1.567     raeburn  7907:     $r->print('<h3>'.&mt("Uploading file to [_1]",$coursedata{'description'}).'</h3>');
1.257     albertel 7908:     if (length($env{'form.upfile'}) < 2) {
1.568     raeburn  7909:         $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 7910:     } else {
1.568     raeburn  7911:         my $result = 
                   7912:             &Apache::lonnet::userfileupload('upfile','','scantron','','','',
                   7913:                                             $env{'form.courseid'},$env{'form.domainid'});
                   7914: 	if ($result =~ m{^/uploaded/}) {
1.567     raeburn  7915: 	    $r->print(&mt('[_1]Success:[_2] Successfully uploaded [_3] bytes of data into location: [_4]',
                   7916:                           '<span class="LC_success">','</span>',(length($env{'form.upfile'})-1),
                   7917: 			  '<span class="LC_filename">'.$result.'</span>'));
1.568     raeburn  7918:             ($uploadedfile) = ($result =~ m{/([^/]+)$});
1.567     raeburn  7919:             $r->print(&validate_uploaded_scantron_file($env{'form.domainid'},
1.568     raeburn  7920:                                                        $env{'form.courseid'},$uploadedfile));
1.210     albertel 7921: 	} else {
1.567     raeburn  7922: 	    $r->print(&mt('[_1]Error:[_2] An error ([_3]) occurred when attempting to upload the file, [_4]',
                   7923:                           '<span class="LC_error">','</span>',$result,
1.568     raeburn  7924: 			  '<span class="LC_filename">'.&HTML::Entities::encode($env{'form.upfile.filename'},'<>&"').'</span>'));
1.183     albertel 7925: 	}
                   7926:     }
1.174     albertel 7927:     if ($symb) {
1.612     www      7928: 	$r->print(&scantron_selectphase($r,$uploadedfile,$symb));
1.174     albertel 7929:     } else {
1.182     albertel 7930: 	$r->print($doanotherupload);
1.174     albertel 7931:     }
1.157     albertel 7932:     return '';
                   7933: }
                   7934: 
1.567     raeburn  7935: sub validate_uploaded_scantron_file {
                   7936:     my ($cdom,$cname,$fname) = @_;
                   7937:     my $scanlines=&Apache::lonnet::getfile('/uploaded/'.$cdom.'/'.$cname.'/'.$fname);
                   7938:     my @lines;
                   7939:     if ($scanlines ne '-1') {
                   7940:         @lines=split("\n",$scanlines,-1);
                   7941:     }
                   7942:     my $output;
                   7943:     if (@lines) {
                   7944:         my (%counts,$max_match_format);
                   7945:         my ($max_match_count,$max_match_pct) = (0,0);
                   7946:         my $classlist = &Apache::loncoursedata::get_classlist($cdom,$cname);
                   7947:         my %idmap = &username_to_idmap($classlist);
                   7948:         foreach my $key (keys(%idmap)) {
                   7949:             my $lckey = lc($key);
                   7950:             $idmap{$lckey} = $idmap{$key};
                   7951:         }
                   7952:         my %unique_formats;
                   7953:         my @formatlines = &get_scantronformat_file();
                   7954:         foreach my $line (@formatlines) {
                   7955:             chomp($line);
                   7956:             my @config = split(/:/,$line);
                   7957:             my $idstart = $config[5];
                   7958:             my $idlength = $config[6];
                   7959:             if (($idstart ne '') && ($idlength > 0)) {
                   7960:                 if (ref($unique_formats{$idstart.':'.$idlength}) eq 'ARRAY') {
                   7961:                     push(@{$unique_formats{$idstart.':'.$idlength}},$config[0].':'.$config[1]); 
                   7962:                 } else {
                   7963:                     $unique_formats{$idstart.':'.$idlength} = [$config[0].':'.$config[1]];
                   7964:                 }
                   7965:             }
                   7966:         }
                   7967:         foreach my $key (keys(%unique_formats)) {
                   7968:             my ($idstart,$idlength) = split(':',$key);
                   7969:             %{$counts{$key}} = (
                   7970:                                'found'   => 0,
                   7971:                                'total'   => 0,
                   7972:                               );
                   7973:             foreach my $line (@lines) {
                   7974:                 next if ($line =~ /^#/);
                   7975:                 next if ($line =~ /^[\s\cz]*$/);
                   7976:                 my $id = substr($line,$idstart-1,$idlength);
                   7977:                 $id = lc($id);
                   7978:                 if (exists($idmap{$id})) {
                   7979:                     $counts{$key}{'found'} ++;
                   7980:                 }
                   7981:                 $counts{$key}{'total'} ++;
                   7982:             }
                   7983:             if ($counts{$key}{'total'}) {
                   7984:                 my $percent_match = (100*$counts{$key}{'found'})/($counts{$key}{'total'});
                   7985:                 if (($max_match_format eq '') || ($percent_match > $max_match_pct)) {
                   7986:                     $max_match_pct = $percent_match;
                   7987:                     $max_match_format = $key;
                   7988:                     $max_match_count = $counts{$key}{'total'};
                   7989:                 }
                   7990:             }
                   7991:         }
                   7992:         if (ref($unique_formats{$max_match_format}) eq 'ARRAY') {
                   7993:             my $format_descs;
                   7994:             my $numwithformat = @{$unique_formats{$max_match_format}};
                   7995:             for (my $i=0; $i<$numwithformat; $i++) {
                   7996:                 my ($name,$desc) = split(':',$unique_formats{$max_match_format}[$i]);
                   7997:                 if ($i<$numwithformat-2) {
                   7998:                     $format_descs .= '"<i>'.$desc.'</i>", ';
                   7999:                 } elsif ($i==$numwithformat-2) {
                   8000:                     $format_descs .= '"<i>'.$desc.'</i>" '.&mt('and').' ';
                   8001:                 } elsif ($i==$numwithformat-1) {
                   8002:                     $format_descs .= '"<i>'.$desc.'</i>"';
                   8003:                 }
                   8004:             }
                   8005:             my $showpct = sprintf("%.0f",$max_match_pct).'%';
                   8006:             $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).
                   8007:                        '<br />'.&mt('A low percentage of matches results from one of the following:').'<ul>'.
                   8008:                        '<li>'.&mt('The file was uploaded to the wrong course').'</li>'.
                   8009:                        '<li>'.&mt('The data are not in the format expected for the domain: [_1]',
                   8010:                                   '<i>'.$cdom.'</i>').'</li>'.
                   8011:                        '<li>'.&mt('Students did not bubble their IDs, or mis-bubbled them').'</li>'.
                   8012:                        '<li>'.&mt('The course roster is not up to date').'</li>'.
                   8013:                        '</ul>';
                   8014:         }
                   8015:     } else {
                   8016:         $output = '<span class="LC_warning">'.&mt('Uploaded file contained no data').'</span>';
                   8017:     }
                   8018:     return $output;
                   8019: }
                   8020: 
1.202     albertel 8021: sub valid_file {
                   8022:     my ($requested_file)=@_;
                   8023:     foreach my $filename (sort(&scantron_filenames())) {
                   8024: 	if ($requested_file eq $filename) { return 1; }
                   8025:     }
                   8026:     return 0;
                   8027: }
                   8028: 
                   8029: sub scantron_download_scantron_data {
1.608     www      8030:     my ($r,$symb)=@_;
                   8031:     my $default_form_data=&defaultFormData($symb);
1.257     albertel 8032:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   8033:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
                   8034:     my $file=$env{'form.scantron_selectfile'};
1.202     albertel 8035:     if (! &valid_file($file)) {
1.492     albertel 8036: 	$r->print('
1.202     albertel 8037: 	<p>
1.492     albertel 8038: 	    '.&mt('The requested file name was invalid.').'
1.202     albertel 8039:         </p>
1.492     albertel 8040: ');
1.202     albertel 8041: 	return;
                   8042:     }
                   8043:     my $orig='/uploaded/'.$cdom.'/'.$cname.'/scantron_orig_'.$file;
                   8044:     my $corrected='/uploaded/'.$cdom.'/'.$cname.'/scantron_corrected_'.$file;
                   8045:     my $skipped='/uploaded/'.$cdom.'/'.$cname.'/scantron_skipped_'.$file;
                   8046:     &Apache::lonnet::allowuploaded('/adm/grades',$orig);
                   8047:     &Apache::lonnet::allowuploaded('/adm/grades',$corrected);
                   8048:     &Apache::lonnet::allowuploaded('/adm/grades',$skipped);
1.492     albertel 8049:     $r->print('
1.202     albertel 8050:     <p>
1.492     albertel 8051: 	'.&mt('[_1]Original[_2] file as uploaded by the scantron office.',
                   8052: 	      '<a href="'.$orig.'">','</a>').'
1.202     albertel 8053:     </p>
                   8054:     <p>
1.492     albertel 8055: 	'.&mt('[_1]Corrections[_2], a file of corrected records that were used in grading.',
                   8056: 	      '<a href="'.$corrected.'">','</a>').'
1.202     albertel 8057:     </p>
                   8058:     <p>
1.492     albertel 8059: 	'.&mt('[_1]Skipped[_2], a file of records that were skipped.',
                   8060: 	      '<a href="'.$skipped.'">','</a>').'
1.202     albertel 8061:     </p>
1.492     albertel 8062: ');
1.202     albertel 8063:     return '';
                   8064: }
1.157     albertel 8065: 
1.523     raeburn  8066: sub checkscantron_results {
1.608     www      8067:     my ($r,$symb) = @_;
1.523     raeburn  8068:     if (!$symb) {return '';}
                   8069:     my $cid = $env{'request.course.id'};
1.542     raeburn  8070:     my %lettdig = &letter_to_digits();
1.523     raeburn  8071:     my $numletts = scalar(keys(%lettdig));
                   8072:     my $cnum = $env{'course.'.$cid.'.num'};
                   8073:     my $cdom = $env{'course.'.$cid.'.domain'};
                   8074:     my (undef, undef, $sequence) = &Apache::lonnet::decode_symb($env{'form.selectpage'});
                   8075:     my %record;
                   8076:     my %scantron_config =
                   8077:         &Apache::grades::get_scantron_config($env{'form.scantron_format'});
                   8078:     my ($scanlines,$scan_data)=&Apache::grades::scantron_getfile();
                   8079:     my $classlist=&Apache::loncoursedata::get_classlist();
                   8080:     my %idmap=&Apache::grades::username_to_idmap($classlist);
                   8081:     my $navmap=Apache::lonnavmaps::navmap->new();
1.582     raeburn  8082:     unless (ref($navmap)) {
                   8083:         $r->print(&navmap_errormsg());
                   8084:         return '';
                   8085:     }
1.523     raeburn  8086:     my $map=$navmap->getResourceByUrl($sequence);
1.557     raeburn  8087:     my @resources=$navmap->retrieveResources($map,\&scantron_filter,1,0);
                   8088:     my (%grader_partids_by_symb,%grader_randomlists_by_symb);
                   8089:     &graders_resources_pass(\@resources,\%grader_partids_by_symb,                             \%grader_randomlists_by_symb);
                   8090: 
1.554     raeburn  8091:     my ($uname,$udom);
1.523     raeburn  8092:     my (%scandata,%lastname,%bylast);
                   8093:     $r->print('
                   8094: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="checkscantron">'."\n");
                   8095: 
                   8096:     my @delayqueue;
                   8097:     my %completedstudents;
                   8098: 
                   8099:     my $count=&Apache::grades::get_todo_count($scanlines,$scan_data);
1.581     www      8100:     my %prog_state=&Apache::lonhtmlcommon::Create_PrgWin($r,'Bubblesheet/Submissions Comparison Status',
                   8101:                                     'Progress of Bubblesheet Data/Submission Records Comparison',$count,
1.523     raeburn  8102:                                     'inline',undef,'checkscantron');
1.546     raeburn  8103:     my ($username,$domain,$started);
1.582     raeburn  8104:     my $nav_error;
                   8105:     &scantron_get_maxbubble(\$nav_error); # Need the bubble lines array to parse.
                   8106:     if ($nav_error) {
                   8107:         $r->print(&navmap_errormsg());
                   8108:         return '';
                   8109:     }
1.523     raeburn  8110: 
                   8111:     &Apache::lonhtmlcommon::Update_PrgWin($r,\%prog_state,
                   8112:                                           'Processing first student');
                   8113:     my $start=&Time::HiRes::time();
                   8114:     my $i=-1;
                   8115: 
                   8116:     while ($i<$scanlines->{'count'}) {
                   8117:         ($username,$domain,$uname)=('','','');
                   8118:         $i++;
                   8119:         my $line=&Apache::grades::scantron_get_line($scanlines,$scan_data,$i);
                   8120:         if ($line=~/^[\s\cz]*$/) { next; }
                   8121:         if ($started) {
                   8122:             &Apache::lonhtmlcommon::Increment_PrgWin($r,\%prog_state,
                   8123:                                                      'last student');
                   8124:         }
                   8125:         $started=1;
                   8126:         my $scan_record=
                   8127:             &Apache::grades::scantron_parse_scanline($line,$i,\%scantron_config,
                   8128:                                                      $scan_data);
                   8129:         unless ($uname=&Apache::grades::scantron_find_student($scan_record,$scan_data,
                   8130:                                                               \%idmap,$i)) {
                   8131:             &Apache::grades::scantron_add_delay(\@delayqueue,$line,
                   8132:                                 'Unable to find a student that matches',1);
                   8133:             next;
                   8134:         }
                   8135:         if (exists $completedstudents{$uname}) {
                   8136:             &Apache::grades::scantron_add_delay(\@delayqueue,$line,
                   8137:                                 'Student '.$uname.' has multiple sheets',2);
                   8138:             next;
                   8139:         }
                   8140:         my $pid = $scan_record->{'scantron.ID'};
                   8141:         $lastname{$pid} = $scan_record->{'scantron.LastName'};
                   8142:         push(@{$bylast{$lastname{$pid}}},$pid);
                   8143:         my $lastpos = $env{'form.scantron_maxbubble'}*$scantron_config{'Qlength'};
                   8144:         $scandata{$pid} = substr($line,$scantron_config{'Qstart'}-1,$lastpos);
                   8145:         chomp($scandata{$pid});
                   8146:         $scandata{$pid} =~ s/\r$//;
                   8147:         ($username,$domain)=split(/:/,$uname);
                   8148:         my $counter = -1;
                   8149:         foreach my $resource (@resources) {
1.557     raeburn  8150:             my $parts;
1.554     raeburn  8151:             my $ressymb = $resource->symb();
1.557     raeburn  8152:             if ((exists($grader_randomlists_by_symb{$ressymb})) ||
                   8153:                 (ref($grader_partids_by_symb{$ressymb}) ne 'ARRAY')) {
                   8154:                 (my $analysis,$parts) =
                   8155:                     &scantron_partids_tograde($resource,$env{'request.course.id'},$username,$domain);
                   8156:             } else {
                   8157:                 $parts = $grader_partids_by_symb{$ressymb};
                   8158:             }
1.542     raeburn  8159:             ($counter,my $recording) =
                   8160:                 &verify_scantron_grading($resource,$domain,$username,$cid,$counter,
1.554     raeburn  8161:                                          $scandata{$pid},$parts,
1.542     raeburn  8162:                                          \%scantron_config,\%lettdig,$numletts);
                   8163:             $record{$pid} .= $recording;
1.523     raeburn  8164:         }
                   8165:     }
                   8166:     &Apache::lonhtmlcommon::Close_PrgWin($r,\%prog_state);
                   8167:     $r->print('<br />');
                   8168:     my ($okstudents,$badstudents,$numstudents,$passed,$failed);
                   8169:     $passed = 0;
                   8170:     $failed = 0;
                   8171:     $numstudents = 0;
                   8172:     foreach my $last (sort(keys(%bylast))) {
                   8173:         if (ref($bylast{$last}) eq 'ARRAY') {
                   8174:             foreach my $pid (sort(@{$bylast{$last}})) {
                   8175:                 my $showscandata = $scandata{$pid};
                   8176:                 my $showrecord = $record{$pid};
                   8177:                 $showscandata =~ s/\s/&nbsp;/g;
                   8178:                 $showrecord =~ s/\s/&nbsp;/g;
                   8179:                 if ($scandata{$pid} eq $record{$pid}) {
                   8180:                     my $css_class = ($passed % 2)?'LC_odd_row':'LC_even_row';
                   8181:                     $okstudents .= '<tr class="'.$css_class.'">'.
1.581     www      8182: '<td>'.&mt('Bubblesheet').'</td><td>'.$showscandata.'</td><td rowspan="2">'.$last.'</td><td rowspan="2">'.$pid.'</td>'."\n".
1.523     raeburn  8183: '</tr>'."\n".
                   8184: '<tr class="'.$css_class.'">'."\n".
                   8185: '<td>Submissions</td><td>'.$showrecord.'</td></tr>'."\n";
                   8186:                     $passed ++;
                   8187:                 } else {
                   8188:                     my $css_class = ($failed % 2)?'LC_odd_row':'LC_even_row';
1.581     www      8189:                     $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  8190: '</tr>'."\n".
                   8191: '<tr class="'.$css_class.'">'."\n".
                   8192: '<td>Submissions</td><td><span class="LC_nobreak">'.$record{$pid}.'</span></td>'."\n".
                   8193: '</tr>'."\n";
                   8194:                     $failed ++;
                   8195:                 }
                   8196:                 $numstudents ++;
                   8197:             }
                   8198:         }
                   8199:     }
1.572     www      8200:     $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  8201:     $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>');
                   8202:     if ($passed) {
1.572     www      8203:         $r->print(&mt('Students with exact correspondence between bubblesheet data and submissions are as follows:').'<br /><br />');
1.523     raeburn  8204:         $r->print(&Apache::loncommon::start_data_table()."\n".
                   8205:                  &Apache::loncommon::start_data_table_header_row()."\n".
                   8206:                  '<th>'.&mt('Source').'</th><th>'.&mt('Bubble records').'</th><th>'.&mt('Name').'</th><th>'.&mt('ID').'</th>'.
                   8207:                  &Apache::loncommon::end_data_table_header_row()."\n".
                   8208:                  $okstudents."\n".
                   8209:                  &Apache::loncommon::end_data_table().'<br />');
                   8210:     }
                   8211:     if ($failed) {
1.572     www      8212:         $r->print(&mt('Students with differences between bubblesheet data and submissions are as follows:').'<br /><br />');
1.523     raeburn  8213:         $r->print(&Apache::loncommon::start_data_table()."\n".
                   8214:                  &Apache::loncommon::start_data_table_header_row()."\n".
                   8215:                  '<th>'.&mt('Source').'</th><th>'.&mt('Bubble records').'</th><th>'.&mt('Name').'</th><th>'.&mt('ID').'</th>'.
                   8216:                  &Apache::loncommon::end_data_table_header_row()."\n".
                   8217:                  $badstudents."\n".
                   8218:                  &Apache::loncommon::end_data_table()).'<br />'.
1.572     www      8219:                  &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  8220:     }
1.614     www      8221:     $r->print('</form><br />');
1.523     raeburn  8222:     return;
                   8223: }
                   8224: 
1.542     raeburn  8225: sub verify_scantron_grading {
1.554     raeburn  8226:     my ($resource,$domain,$username,$cid,$counter,$scandata,$partids,
1.542     raeburn  8227:         $scantron_config,$lettdig,$numletts) = @_;
                   8228:     my ($record,%expected,%startpos);
                   8229:     return ($counter,$record) if (!ref($resource));
                   8230:     return ($counter,$record) if (!$resource->is_problem());
                   8231:     my $symb = $resource->symb();
1.554     raeburn  8232:     return ($counter,$record) if (ref($partids) ne 'ARRAY');
                   8233:     foreach my $part_id (@{$partids}) {
1.542     raeburn  8234:         $counter ++;
                   8235:         $expected{$part_id} = 0;
                   8236:         if ($env{"form.scantron.sub_bubblelines.$counter"}) {
                   8237:             my @sub_lines = split(/,/,$env{"form.scantron.sub_bubblelines.$counter"});
                   8238:             foreach my $item (@sub_lines) {
                   8239:                 $expected{$part_id} += $item;
                   8240:             }
                   8241:         } else {
                   8242:             $expected{$part_id} = $env{"form.scantron.bubblelines.$counter"};
                   8243:         }
                   8244:         $startpos{$part_id} = $env{"form.scantron.first_bubble_line.$counter"};
                   8245:     }
                   8246:     if ($symb) {
                   8247:         my %recorded;
                   8248:         my (%returnhash) = &Apache::lonnet::restore($symb,$cid,$domain,$username);
                   8249:         if ($returnhash{'version'}) {
                   8250:             my %lasthash=();
                   8251:             my $version;
                   8252:             for ($version=1;$version<=$returnhash{'version'};$version++) {
                   8253:                 foreach my $key (sort(split(/\:/,$returnhash{$version.':keys'}))) {
                   8254:                     $lasthash{$key}=$returnhash{$version.':'.$key};
                   8255:                 }
                   8256:             }
                   8257:             foreach my $key (keys(%lasthash)) {
                   8258:                 if ($key =~ /\.scantron$/) {
                   8259:                     my $value = &unescape($lasthash{$key});
                   8260:                     my ($part_id) = ($key =~ /^resource\.(.+)\.scantron$/);
                   8261:                     if ($value eq '') {
                   8262:                         for (my $i=0; $i<$expected{$part_id}; $i++) {
                   8263:                             for (my $j=0; $j<$scantron_config->{'length'}; $j++) {
                   8264:                                 $recorded{$part_id} .= $scantron_config->{'Qoff'};
                   8265:                             }
                   8266:                         }
                   8267:                     } else {
                   8268:                         my @tocheck;
                   8269:                         my @items = split(//,$value);
                   8270:                         if (($scantron_config->{'Qon'} eq 'letter') ||
                   8271:                             ($scantron_config->{'Qon'} eq 'number')) {
                   8272:                             if (@items < $expected{$part_id}) {
                   8273:                                 my $fragment = substr($scandata,$startpos{$part_id},$expected{$part_id});
                   8274:                                 my @singles = split(//,$fragment);
                   8275:                                 foreach my $pos (@singles) {
                   8276:                                     if ($pos eq ' ') {
                   8277:                                         push(@tocheck,$pos);
                   8278:                                     } else {
                   8279:                                         my $next = shift(@items);
                   8280:                                         push(@tocheck,$next);
                   8281:                                     }
                   8282:                                 }
                   8283:                             } else {
                   8284:                                 @tocheck = @items;
                   8285:                             }
                   8286:                             foreach my $letter (@tocheck) {
                   8287:                                 if ($scantron_config->{'Qon'} eq 'letter') {
                   8288:                                     if ($letter !~ /^[A-J]$/) {
                   8289:                                         $letter = $scantron_config->{'Qoff'};
                   8290:                                     }
                   8291:                                     $recorded{$part_id} .= $letter;
                   8292:                                 } elsif ($scantron_config->{'Qon'} eq 'number') {
                   8293:                                     my $digit;
                   8294:                                     if ($letter !~ /^[A-J]$/) {
                   8295:                                         $digit = $scantron_config->{'Qoff'};
                   8296:                                     } else {
                   8297:                                         $digit = $lettdig->{$letter};
                   8298:                                     }
                   8299:                                     $recorded{$part_id} .= $digit;
                   8300:                                 }
                   8301:                             }
                   8302:                         } else {
                   8303:                             @tocheck = @items;
                   8304:                             for (my $i=0; $i<$expected{$part_id}; $i++) {
                   8305:                                 my $curr_sub = shift(@tocheck);
                   8306:                                 my $digit;
                   8307:                                 if ($curr_sub =~ /^[A-J]$/) {
                   8308:                                     $digit = $lettdig->{$curr_sub}-1;
                   8309:                                 }
                   8310:                                 if ($curr_sub eq 'J') {
                   8311:                                     $digit += scalar($numletts);
                   8312:                                 }
                   8313:                                 for (my $j=0; $j<$scantron_config->{'Qlength'}; $j++) {
                   8314:                                     if ($j == $digit) {
                   8315:                                         $recorded{$part_id} .= $scantron_config->{'Qon'};
                   8316:                                     } else {
                   8317:                                         $recorded{$part_id} .= $scantron_config->{'Qoff'};
                   8318:                                     }
                   8319:                                 }
                   8320:                             }
                   8321:                         }
                   8322:                     }
                   8323:                 }
                   8324:             }
                   8325:         }
1.554     raeburn  8326:         foreach my $part_id (@{$partids}) {
1.542     raeburn  8327:             if ($recorded{$part_id} eq '') {
                   8328:                 for (my $i=0; $i<$expected{$part_id}; $i++) {
                   8329:                     for (my $j=0; $j<$scantron_config->{'Qlength'}; $j++) {
                   8330:                         $recorded{$part_id} .= $scantron_config->{'Qoff'};
                   8331:                     }
                   8332:                 }
                   8333:             }
                   8334:             $record .= $recorded{$part_id};
                   8335:         }
                   8336:     }
                   8337:     return ($counter,$record);
                   8338: }
                   8339: 
                   8340: sub letter_to_digits { 
                   8341:     my %lettdig = (
                   8342:                     A => 1,
                   8343:                     B => 2,
                   8344:                     C => 3,
                   8345:                     D => 4,
                   8346:                     E => 5,
                   8347:                     F => 6,
                   8348:                     G => 7,
                   8349:                     H => 8,
                   8350:                     I => 9,
                   8351:                     J => 0,
                   8352:                   );
                   8353:     return %lettdig;
                   8354: }
                   8355: 
1.423     albertel 8356: 
1.75      albertel 8357: #-------- end of section for handling grading scantron forms -------
                   8358: #
                   8359: #-------------------------------------------------------------------
                   8360: 
1.72      ng       8361: #-------------------------- Menu interface -------------------------
                   8362: #
1.614     www      8363: #--- Href with symb and command ---
                   8364: 
                   8365: sub href_symb_cmd {
                   8366:     my ($symb,$cmd)=@_;
                   8367:     return '/adm/grades?symb='.&HTML::Entities::encode(&Apache::lonenc::check_encrypt($symb),'<>&"').'&command='.$cmd;
1.72      ng       8368: }
                   8369: 
1.443     banghart 8370: sub grading_menu {
1.608     www      8371:     my ($request,$symb) = @_;
1.443     banghart 8372:     if (!$symb) {return '';}
                   8373: 
                   8374:     my %fields = ('symb'=>&Apache::lonenc::check_encrypt($symb),
1.618   ! www      8375:                   'command'=>'individual');
1.538     schulted 8376:     
1.598     www      8377:     my $url1a = &Apache::lonhtmlcommon::build_url('grades/',\%fields);
                   8378: 
                   8379:     $fields{'command'}='ungraded';
                   8380:     my $url1b=&Apache::lonhtmlcommon::build_url('grades/',\%fields);
                   8381: 
                   8382:     $fields{'command'}='table';
                   8383:     my $url1c=&Apache::lonhtmlcommon::build_url('grades/',\%fields);
                   8384: 
                   8385:     $fields{'command'}='all_for_one';
                   8386:     my $url1d=&Apache::lonhtmlcommon::build_url('grades/',\%fields);
                   8387: 
1.443     banghart 8388:     $fields{'command'} = 'csvform';
1.538     schulted 8389:     my $url2 = &Apache::lonhtmlcommon::build_url('grades/',\%fields);
                   8390:     
1.443     banghart 8391:     $fields{'command'} = 'processclicker';
1.538     schulted 8392:     my $url3 = &Apache::lonhtmlcommon::build_url('grades/',\%fields);
                   8393:     
1.443     banghart 8394:     $fields{'command'} = 'scantron_selectphase';
1.538     schulted 8395:     my $url4 = &Apache::lonhtmlcommon::build_url('grades/',\%fields);
1.602     www      8396: 
                   8397:     $fields{'command'} = 'initialverifyreceipt';
                   8398:     my $url5 = &Apache::lonhtmlcommon::build_url('grades/',\%fields);
1.538     schulted 8399:     
1.598     www      8400:     my @menu = ({	categorytitle=>'Hand Grading',
1.538     schulted 8401:             items =>[
1.598     www      8402:                         {	linktext => 'Select individual students to grade',
                   8403:                     		url => $url1a,
1.538     schulted 8404:                     		permission => 'F',
                   8405:                     		icon => 'edit-find-replace.png',
1.598     www      8406:                     		linktitle => 'Grade current resource for a selection of students.'
                   8407:                         }, 
                   8408:                         {       linktext => 'Grade ungraded submissions.',
                   8409:                                 url => $url1b,
                   8410:                                 permission => 'F',
                   8411:                                 icon => 'edit-find-replace.png',
                   8412:                                 linktitle => 'Grade all submissions that have not been graded yet.'
1.538     schulted 8413:                         },
1.598     www      8414: 
                   8415:                         {       linktext => 'Grading table',
                   8416:                                 url => $url1c,
                   8417:                                 permission => 'F',
                   8418:                                 icon => 'edit-find-replace.png',
                   8419:                                 linktitle => 'Grade current resource for all students.'
                   8420:                         },
1.615     www      8421:                         {       linktext => 'Grade page/folder for one student',
1.598     www      8422:                                 url => $url1d,
                   8423:                                 permission => 'F',
                   8424:                                 icon => 'edit-find-replace.png',
                   8425:                                 linktitle => 'Grade all resources in current page/sequence/folder for one student.'
                   8426:                         }]},
                   8427:                          { categorytitle=>'Automated Grading',
                   8428:                items =>[
                   8429: 
1.538     schulted 8430:                 	    {	linktext => 'Upload Scores',
                   8431:                     		url => $url2,
                   8432:                     		permission => 'F',
                   8433:                     		icon => 'uploadscores.png',
                   8434:                     		linktitle => 'Specify a file containing the class scores for current resource.'
                   8435:                 	    },
                   8436:                 	    {	linktext => 'Process Clicker',
                   8437:                     		url => $url3,
                   8438:                     		permission => 'F',
                   8439:                     		icon => 'addClickerInfoFile.png',
                   8440:                     		linktitle => 'Specify a file containing the clicker information for this resource.'
                   8441:                 	    },
1.587     raeburn  8442:                 	    {	linktext => 'Grade/Manage/Review Bubblesheets',
1.538     schulted 8443:                     		url => $url4,
                   8444:                     		permission => 'F',
                   8445:                     		icon => 'stat.png',
                   8446:                     		linktitle => 'Grade scantron exams, upload/download scantron data files, and review previously graded scantron exams.'
1.602     www      8447:                 	    },
1.616     www      8448:                             {   linktext => 'Verify Receipt Number',
1.602     www      8449:                                 url => $url5,
                   8450:                                 permission => 'F',
                   8451:                                 icon => 'edit-find-replace.png',
                   8452:                                 linktitle => 'Verify a system-generated receipt number for correct problem solution.'
                   8453:                             }
                   8454: 
1.538     schulted 8455:                     ]
                   8456:             });
                   8457: 
1.443     banghart 8458:     # Create the menu
                   8459:     my $Str;
1.445     banghart 8460:     $Str .= '<form method="post" action="" name="gradingMenu">';
                   8461:     $Str .= '<input type="hidden" name="command" value="" />'.
1.618   ! www      8462:     	'<input type="hidden" name="symb"        value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n";
1.445     banghart 8463: 
1.602     www      8464:     $Str .= &Apache::lonhtmlcommon::generate_menu(@menu);
1.443     banghart 8465:     return $Str;    
                   8466: }
                   8467: 
1.598     www      8468: 
                   8469: sub ungraded {
                   8470:     my ($request)=@_;
                   8471:     &submit_options($request);
                   8472: }
                   8473: 
1.599     www      8474: sub submit_options_sequence {
1.608     www      8475:     my ($request,$symb) = @_;
1.599     www      8476:     if (!$symb) {return '';}
1.600     www      8477:     &commonJSfunctions($request);
                   8478:     my $result;
1.599     www      8479: 
1.600     www      8480:     $result.='<form action="/adm/grades" method="post" name="gradingMenu">'."\n".
1.618   ! www      8481:         '<input type="hidden" name="symb"        value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n";
1.600     www      8482:     $result.='
                   8483: <h2>
1.615     www      8484:   '.&mt('Grade page/folder for one student').'
1.601     www      8485: </h2>'.
                   8486:             &selectfield(0).
                   8487:             '<input type="hidden" name="command" value="pickStudentPage" />
1.600     www      8488:             <div>
                   8489:               <input type="submit" value="'.&mt('Next').' &rarr;" />
                   8490:             </div>
                   8491:         </div>
                   8492:   </form>';
                   8493:     return $result;
                   8494: }
                   8495: 
                   8496: sub submit_options_table {
1.608     www      8497:     my ($request,$symb) = @_;
1.600     www      8498:     if (!$symb) {return '';}
1.599     www      8499:     &commonJSfunctions($request);
                   8500:     my $result;
                   8501: 
                   8502:     $result.='<form action="/adm/grades" method="post" name="gradingMenu">'."\n".
1.618   ! www      8503:         '<input type="hidden" name="symb"        value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n";
1.599     www      8504: 
                   8505:     $result.='
                   8506: <h2>
1.600     www      8507:   '.&mt('Grading table').'
1.601     www      8508: </h2>'.
                   8509:             &selectfield(0).
                   8510:             '<input type="hidden" name="command" value="viewgrades" />
1.599     www      8511:             <div>
                   8512:               <input type="submit" value="'.&mt('Next').' &rarr;" />
                   8513:             </div>
                   8514:         </div>
                   8515:   </form>';
                   8516:     return $result;
                   8517: }
1.443     banghart 8518: 
1.600     www      8519: 
                   8520: 
1.443     banghart 8521: #--- Displays the submissions first page -------
                   8522: sub submit_options {
1.608     www      8523:     my ($request,$symb) = @_;
1.72      ng       8524:     if (!$symb) {return '';}
                   8525: 
1.118     ng       8526:     &commonJSfunctions($request);
1.473     albertel 8527:     my $result;
1.533     bisitz   8528: 
1.72      ng       8529:     $result.='<form action="/adm/grades" method="post" name="gradingMenu">'."\n".
1.618   ! www      8530: 	'<input type="hidden" name="symb"        value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n";
1.472     albertel 8531:     $result.='
1.533     bisitz   8532: <h2>
1.600     www      8533:   '.&mt('Select individual students to grade').'
1.601     www      8534: </h2>'.&selectfield(1).'
                   8535:                 <input type="hidden" name="command" value="submission" /> 
                   8536: 	      <input type="submit" value="'.&mt('Next').' &rarr;" />
                   8537:             </div>
                   8538:           </div>
                   8539: 
                   8540: 
                   8541:   </form>';
                   8542:     return $result;
                   8543: }
1.533     bisitz   8544: 
1.601     www      8545: sub selectfield {
                   8546:    my ($full)=@_;
                   8547:    my $result='<div class="LC_columnSection">
1.537     harmsja  8548:   
1.533     bisitz   8549:     <fieldset>
                   8550:       <legend>
                   8551:        '.&mt('Sections').'
                   8552:       </legend>
1.601     www      8553:       '.&Apache::lonstatistics::SectionSelect('section','multiple',5).'
1.533     bisitz   8554:     </fieldset>
1.537     harmsja  8555:   
1.533     bisitz   8556:     <fieldset>
                   8557:       <legend>
                   8558:         '.&mt('Groups').'
                   8559:       </legend>
                   8560:       '.&Apache::lonstatistics::GroupSelect('group','multiple',5).'
                   8561:     </fieldset>
1.537     harmsja  8562:   
1.533     bisitz   8563:     <fieldset>
                   8564:       <legend>
                   8565:         '.&mt('Access Status').'
                   8566:       </legend>
1.601     www      8567:       '.&Apache::lonhtmlcommon::StatusOptions(undef,undef,5,undef,'mult').'
                   8568:     </fieldset>';
                   8569:     if ($full) {
                   8570:        $result.='
1.533     bisitz   8571:     <fieldset>
                   8572:       <legend>
                   8573:         '.&mt('Submission Status').'
1.601     www      8574:       </legend>'.
                   8575:        &Apache::loncommon::select_form('all','submitonly',
                   8576:           (&Apache::lonlocal::texthash(
                   8577:              'yes'       => 'with submissions',
                   8578:              'queued'    => 'in grading queue',
                   8579:              'graded'    => 'with ungraded submissions',
                   8580:              'incorrect' => 'with incorrect submissions',
                   8581:              'all'       => 'with any status'),
                   8582:              'select_form_order' => ['yes','queued','graded','incorrect','all'])).
                   8583:    '</fieldset>';
                   8584:     }
                   8585:     $result.='</div><br />';
1.44      ng       8586:     return $result;
1.2       albertel 8587: }
                   8588: 
1.285     albertel 8589: sub reset_perm {
                   8590:     undef(%perm);
                   8591: }
                   8592: 
                   8593: sub init_perm {
                   8594:     &reset_perm();
1.300     albertel 8595:     foreach my $test_perm ('vgr','mgr','opa') {
                   8596: 
                   8597: 	my $scope = $env{'request.course.id'};
                   8598: 	if (!($perm{$test_perm}=&Apache::lonnet::allowed($test_perm,$scope))) {
                   8599: 
                   8600: 	    $scope .= '/'.$env{'request.course.sec'};
                   8601: 	    if ( $perm{$test_perm}=
                   8602: 		 &Apache::lonnet::allowed($test_perm,$scope)) {
                   8603: 		$perm{$test_perm.'_section'}=$env{'request.course.sec'};
                   8604: 	    } else {
                   8605: 		delete($perm{$test_perm});
                   8606: 	    }
1.285     albertel 8607: 	}
                   8608:     }
                   8609: }
                   8610: 
1.400     www      8611: sub gather_clicker_ids {
1.408     albertel 8612:     my %clicker_ids;
1.400     www      8613: 
                   8614:     my $classlist = &Apache::loncoursedata::get_classlist();
                   8615: 
                   8616:     # Set up a couple variables.
1.407     albertel 8617:     my $username_idx = &Apache::loncoursedata::CL_SNAME();
                   8618:     my $domain_idx   = &Apache::loncoursedata::CL_SDOM();
1.438     www      8619:     my $status_idx   = &Apache::loncoursedata::CL_STATUS();
1.400     www      8620: 
1.407     albertel 8621:     foreach my $student (keys(%$classlist)) {
1.438     www      8622:         if ($classlist->{$student}->[$status_idx] ne 'Active') { next; }
1.407     albertel 8623:         my $username = $classlist->{$student}->[$username_idx];
                   8624:         my $domain   = $classlist->{$student}->[$domain_idx];
1.400     www      8625:         my $clickers =
1.408     albertel 8626: 	    (&Apache::lonnet::userenvironment($domain,$username,'clickers'))[1];
1.400     www      8627:         foreach my $id (split(/\,/,$clickers)) {
1.414     www      8628:             $id=~s/^[\#0]+//;
1.421     www      8629:             $id=~s/[\-\:]//g;
1.407     albertel 8630:             if (exists($clicker_ids{$id})) {
1.408     albertel 8631: 		$clicker_ids{$id}.=','.$username.':'.$domain;
1.400     www      8632:             } else {
1.408     albertel 8633: 		$clicker_ids{$id}=$username.':'.$domain;
1.400     www      8634:             }
                   8635:         }
                   8636:     }
1.407     albertel 8637:     return %clicker_ids;
1.400     www      8638: }
                   8639: 
1.402     www      8640: sub gather_adv_clicker_ids {
1.408     albertel 8641:     my %clicker_ids;
1.402     www      8642:     my $cnum=$env{'course.'.$env{'request.course.id'}.'.num'};
                   8643:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
                   8644:     my %coursepersonnel=&Apache::lonnet::get_course_adv_roles($cdom.'/'.$cnum);
1.409     albertel 8645:     foreach my $element (sort(keys(%coursepersonnel))) {
1.402     www      8646:         foreach my $person (split(/\,/,$coursepersonnel{$element})) {
                   8647:             my ($puname,$pudom)=split(/\:/,$person);
                   8648:             my $clickers =
1.408     albertel 8649: 		(&Apache::lonnet::userenvironment($pudom,$puname,'clickers'))[1];
1.405     www      8650:             foreach my $id (split(/\,/,$clickers)) {
1.414     www      8651: 		$id=~s/^[\#0]+//;
1.421     www      8652:                 $id=~s/[\-\:]//g;
1.408     albertel 8653: 		if (exists($clicker_ids{$id})) {
                   8654: 		    $clicker_ids{$id}.=','.$puname.':'.$pudom;
                   8655: 		} else {
                   8656: 		    $clicker_ids{$id}=$puname.':'.$pudom;
                   8657: 		}
1.405     www      8658:             }
1.402     www      8659:         }
                   8660:     }
1.407     albertel 8661:     return %clicker_ids;
1.402     www      8662: }
                   8663: 
1.413     www      8664: sub clicker_grading_parameters {
                   8665:     return ('gradingmechanism' => 'scalar',
                   8666:             'upfiletype' => 'scalar',
                   8667:             'specificid' => 'scalar',
                   8668:             'pcorrect' => 'scalar',
                   8669:             'pincorrect' => 'scalar');
                   8670: }
                   8671: 
1.400     www      8672: sub process_clicker {
1.608     www      8673:     my ($r,$symb)=@_;
1.400     www      8674:     if (!$symb) {return '';}
                   8675:     my $result=&checkforfile_js();
                   8676:     $result.='<br /><table width="100%" border="0"><tr><td bgcolor="#777777">'."\n";
                   8677:     $result.='<table width="100%" border="0"><tr bgcolor="#e6ffff"><td>'."\n";
1.538     schulted 8678:     $result.='&nbsp;<b>'.&mt('Specify a file containing the clicker information for this resource.').
                   8679:         '</b></td></tr>'."\n";
1.601     www      8680:     $result.='<tr bgcolor="#ffffe6"><td>'."\n";
1.413     www      8681: # Attempt to restore parameters from last session, set defaults if not present
                   8682:     my %Saveable_Parameters=&clicker_grading_parameters();
                   8683:     &Apache::loncommon::restore_course_settings('grades_clicker',
                   8684:                                                  \%Saveable_Parameters);
                   8685:     if (!$env{'form.pcorrect'}) { $env{'form.pcorrect'}=100; }
                   8686:     if (!$env{'form.pincorrect'}) { $env{'form.pincorrect'}=100; }
                   8687:     if (!$env{'form.gradingmechanism'}) { $env{'form.gradingmechanism'}='attendance'; }
                   8688:     if (!$env{'form.upfiletype'}) { $env{'form.upfiletype'}='iclicker'; }
                   8689: 
                   8690:     my %checked;
1.521     www      8691:     foreach my $gradingmechanism ('attendance','personnel','specific','given') {
1.413     www      8692:        if ($env{'form.gradingmechanism'} eq $gradingmechanism) {
1.569     bisitz   8693:           $checked{$gradingmechanism}=' checked="checked"';
1.413     www      8694:        }
                   8695:     }
                   8696: 
1.400     www      8697:     my $upload=&mt("Upload File");
                   8698:     my $type=&mt("Type");
1.402     www      8699:     my $attendance=&mt("Award points just for participation");
                   8700:     my $personnel=&mt("Correctness determined from response by course personnel");
1.414     www      8701:     my $specific=&mt("Correctness determined from response with clicker ID(s)"); 
1.521     www      8702:     my $given=&mt("Correctness determined from given list of answers").' '.
                   8703:               '<font size="-2"><tt>('.&mt("Provide comma-separated list. Use '*' for any answer correct, '-' for skip").')</tt></font>';
1.402     www      8704:     my $pcorrect=&mt("Percentage points for correct solution");
                   8705:     my $pincorrect=&mt("Percentage points for incorrect solution");
1.413     www      8706:     my $selectform=&Apache::loncommon::select_form($env{'form.upfiletype'},'upfiletype',
1.419     www      8707: 						   ('iclicker' => 'i>clicker',
                   8708:                                                     'interwrite' => 'interwrite PRS'));
1.418     albertel 8709:     $symb = &Apache::lonenc::check_encrypt($symb);
1.597     wenzelju 8710:     $result.= &Apache::lonhtmlcommon::scripttag(<<ENDUPFORM);
1.402     www      8711: function sanitycheck() {
                   8712: // Accept only integer percentages
                   8713:    document.forms.gradesupload.pcorrect.value=Math.round(document.forms.gradesupload.pcorrect.value);
                   8714:    document.forms.gradesupload.pincorrect.value=Math.round(document.forms.gradesupload.pincorrect.value);
                   8715: // Find out grading choice
                   8716:    for (i=0; i<document.forms.gradesupload.gradingmechanism.length; i++) {
                   8717:       if (document.forms.gradesupload.gradingmechanism[i].checked) {
                   8718:          gradingchoice=document.forms.gradesupload.gradingmechanism[i].value;
                   8719:       }
                   8720:    }
                   8721: // By default, new choice equals user selection
                   8722:    newgradingchoice=gradingchoice;
                   8723: // Not good to give more points for false answers than correct ones
                   8724:    if (Math.round(document.forms.gradesupload.pcorrect.value)<Math.round(document.forms.gradesupload.pincorrect.value)) {
                   8725:       document.forms.gradesupload.pcorrect.value=document.forms.gradesupload.pincorrect.value;
                   8726:    }
                   8727: // If new choice is attendance only, and old choice was correctness-based, restore defaults
                   8728:    if ((gradingchoice=='attendance') && (document.forms.gradesupload.waschecked.value!='attendance')) {
                   8729:       document.forms.gradesupload.pcorrect.value=100;
                   8730:       document.forms.gradesupload.pincorrect.value=100;
                   8731:    }
                   8732: // If the values are different, cannot be attendance only
                   8733:    if ((Math.round(document.forms.gradesupload.pcorrect.value)!=Math.round(document.forms.gradesupload.pincorrect.value)) &&
                   8734:        (gradingchoice=='attendance')) {
                   8735:        newgradingchoice='personnel';
                   8736:    }
                   8737: // Change grading choice to new one
                   8738:    for (i=0; i<document.forms.gradesupload.gradingmechanism.length; i++) {
                   8739:       if (document.forms.gradesupload.gradingmechanism[i].value==newgradingchoice) {
                   8740:          document.forms.gradesupload.gradingmechanism[i].checked=true;
                   8741:       } else {
                   8742:          document.forms.gradesupload.gradingmechanism[i].checked=false;
                   8743:       }
                   8744:    }
                   8745: // Remember the old state
                   8746:    document.forms.gradesupload.waschecked.value=newgradingchoice;
                   8747: }
1.597     wenzelju 8748: ENDUPFORM
                   8749:     $result.= <<ENDUPFORM;
1.400     www      8750: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="gradesupload">
                   8751: <input type="hidden" name="symb" value="$symb" />
                   8752: <input type="hidden" name="command" value="processclickerfile" />
                   8753: <input type="file" name="upfile" size="50" />
                   8754: <br /><label>$type: $selectform</label>
1.589     bisitz   8755: <br /><label><input type="radio" name="gradingmechanism" value="attendance"$checked{'attendance'} onclick="sanitycheck()" />$attendance </label>
                   8756: <br /><label><input type="radio" name="gradingmechanism" value="personnel"$checked{'personnel'} onclick="sanitycheck()" />$personnel</label>
                   8757: <br /><label><input type="radio" name="gradingmechanism" value="specific"$checked{'specific'} onclick="sanitycheck()" />$specific </label>
1.414     www      8758: <input type="text" name="specificid" value="$env{'form.specificid'}" size="20" />
1.589     bisitz   8759: <br /><label><input type="radio" name="gradingmechanism" value="given"$checked{'given'} onclick="sanitycheck()" />$given </label>
1.521     www      8760: <br />&nbsp;&nbsp;&nbsp;
                   8761: <input type="text" name="givenanswer" size="50" />
1.413     www      8762: <input type="hidden" name="waschecked" value="$env{'form.gradingmechanism'}" />
1.589     bisitz   8763: <br /><label>$pcorrect: <input type="text" name="pcorrect" size="4" value="$env{'form.pcorrect'}" onchange="sanitycheck()" /></label>
                   8764: <br /><label>$pincorrect: <input type="text" name="pincorrect" size="4" value="$env{'form.pincorrect'}" onchange="sanitycheck()" /></label>
                   8765: <br /><input type="button" onclick="javascript:checkUpload(this.form);" value="$upload" />
1.597     wenzelju 8766: </form>'
1.400     www      8767: ENDUPFORM
                   8768:     $result.='</td></tr></table>'."\n".
                   8769:              '</td></tr></table><br /><br />'."\n";
                   8770:     return $result;
                   8771: }
                   8772: 
                   8773: sub process_clicker_file {
1.608     www      8774:     my ($r,$symb)=@_;
1.400     www      8775:     if (!$symb) {return '';}
1.413     www      8776: 
                   8777:     my %Saveable_Parameters=&clicker_grading_parameters();
                   8778:     &Apache::loncommon::store_course_settings('grades_clicker',
                   8779:                                               \%Saveable_Parameters);
1.598     www      8780:     my $result='';
1.404     www      8781:     if (($env{'form.gradingmechanism'} eq 'specific') && ($env{'form.specificid'}!~/\w/)) {
1.408     albertel 8782: 	$result.='<span class="LC_error">'.&mt('You need to specify a clicker ID for the correct answer').'</span>';
1.614     www      8783: 	return $result;
1.404     www      8784:     }
1.522     www      8785:     if (($env{'form.gradingmechanism'} eq 'given') && ($env{'form.givenanswer'}!~/\S/)) {
1.521     www      8786:         $result.='<span class="LC_error">'.&mt('You need to specify the correct answer').'</span>';
1.614     www      8787:         return $result;
1.521     www      8788:     }
1.522     www      8789:     my $foundgiven=0;
1.521     www      8790:     if ($env{'form.gradingmechanism'} eq 'given') {
                   8791:         $env{'form.givenanswer'}=~s/^\s*//gs;
                   8792:         $env{'form.givenanswer'}=~s/\s*$//gs;
                   8793:         $env{'form.givenanswer'}=~s/[^a-zA-Z0-9\.\*\-]+/\,/g;
                   8794:         $env{'form.givenanswer'}=uc($env{'form.givenanswer'});
1.522     www      8795:         my @answers=split(/\,/,$env{'form.givenanswer'});
                   8796:         $foundgiven=$#answers+1;
1.521     www      8797:     }
1.407     albertel 8798:     my %clicker_ids=&gather_clicker_ids();
1.408     albertel 8799:     my %correct_ids;
1.404     www      8800:     if ($env{'form.gradingmechanism'} eq 'personnel') {
1.408     albertel 8801: 	%correct_ids=&gather_adv_clicker_ids();
1.404     www      8802:     }
                   8803:     if ($env{'form.gradingmechanism'} eq 'specific') {
1.414     www      8804: 	foreach my $correct_id (split(/[\s\,]/,$env{'form.specificid'})) {;
                   8805: 	   $correct_id=~tr/a-z/A-Z/;
                   8806: 	   $correct_id=~s/\s//gs;
                   8807: 	   $correct_id=~s/^[\#0]+//;
1.421     www      8808:            $correct_id=~s/[\-\:]//g;
1.414     www      8809:            if ($correct_id) {
                   8810: 	      $correct_ids{$correct_id}='specified';
                   8811:            }
                   8812:         }
1.400     www      8813:     }
1.404     www      8814:     if ($env{'form.gradingmechanism'} eq 'attendance') {
1.408     albertel 8815: 	$result.=&mt('Score based on attendance only');
1.521     www      8816:     } elsif ($env{'form.gradingmechanism'} eq 'given') {
1.522     www      8817:         $result.=&mt('Score based on [_1] ([_2] answers)','<tt>'.$env{'form.givenanswer'}.'</tt>',$foundgiven);
1.404     www      8818:     } else {
1.408     albertel 8819: 	my $number=0;
1.411     www      8820: 	$result.='<p><b>'.&mt('Correctness determined by the following IDs').'</b>';
1.408     albertel 8821: 	foreach my $id (sort(keys(%correct_ids))) {
1.411     www      8822: 	    $result.='<br /><tt>'.$id.'</tt> - ';
1.408     albertel 8823: 	    if ($correct_ids{$id} eq 'specified') {
                   8824: 		$result.=&mt('specified');
                   8825: 	    } else {
                   8826: 		my ($uname,$udom)=split(/\:/,$correct_ids{$id});
                   8827: 		$result.=&Apache::loncommon::plainname($uname,$udom);
                   8828: 	    }
                   8829: 	    $number++;
                   8830: 	}
1.411     www      8831:         $result.="</p>\n";
1.408     albertel 8832: 	if ($number==0) {
                   8833: 	    $result.='<span class="LC_error">'.&mt('No IDs found to determine correct answer').'</span>';
1.614     www      8834: 	    return $result;
1.408     albertel 8835: 	}
1.404     www      8836:     }
1.405     www      8837:     if (length($env{'form.upfile'}) < 2) {
1.407     albertel 8838:         $result.=&mt('[_1] Error: [_2] The file you attempted to upload, [_3] contained no information. Please check that you entered the correct filename.',
                   8839: 		     '<span class="LC_error">',
                   8840: 		     '</span>',
                   8841: 		     '<span class="LC_filename">'.&HTML::Entities::encode($env{'form.upfile.filename'},'<>&"').'</span>');
1.614     www      8842:         return $result;
1.405     www      8843:     }
1.410     www      8844: 
                   8845: # Were able to get all the info needed, now analyze the file
                   8846: 
1.411     www      8847:     $result.=&Apache::loncommon::studentbrowser_javascript();
1.418     albertel 8848:     $symb = &Apache::lonenc::check_encrypt($symb);
1.410     www      8849:     my $heading=&mt('Scanning clicker file');
                   8850:     $result.=(<<ENDHEADER);
                   8851: <br /><table width="100%" border="0"><tr><td bgcolor="#777777">
                   8852: <table width="100%" border="0"><tr bgcolor="#e6ffff"><td>
                   8853: <b>$heading</b></td></tr><tr bgcolor=#ffffe6><td>
                   8854: <form method="post" action="/adm/grades" name="clickeranalysis">
                   8855: <input type="hidden" name="symb" value="$symb" />
                   8856: <input type="hidden" name="command" value="assignclickergrades" />
1.411     www      8857: <input type="hidden" name="gradingmechanism" value="$env{'form.gradingmechanism'}" />
                   8858: <input type="hidden" name="pcorrect" value="$env{'form.pcorrect'}" />
                   8859: <input type="hidden" name="pincorrect" value="$env{'form.pincorrect'}" />
1.410     www      8860: ENDHEADER
1.522     www      8861:     if ($env{'form.gradingmechanism'} eq 'given') {
                   8862:        $result.='<input type="hidden" name="correct:given" value="'.$env{'form.givenanswer'}.'" />';
                   8863:     } 
1.408     albertel 8864:     my %responses;
                   8865:     my @questiontitles;
1.405     www      8866:     my $errormsg='';
                   8867:     my $number=0;
                   8868:     if ($env{'form.upfiletype'} eq 'iclicker') {
1.408     albertel 8869: 	($errormsg,$number)=&iclicker_eval(\@questiontitles,\%responses);
1.406     www      8870:     }
1.419     www      8871:     if ($env{'form.upfiletype'} eq 'interwrite') {
                   8872:         ($errormsg,$number)=&interwrite_eval(\@questiontitles,\%responses);
                   8873:     }
1.411     www      8874:     $result.='<br />'.&mt('Found [_1] question(s)',$number).'<br />'.
                   8875:              '<input type="hidden" name="number" value="'.$number.'" />'.
                   8876:              &mt('Awarding [_1] percent for correct and [_2] percent for incorrect responses',
                   8877:                  $env{'form.pcorrect'},$env{'form.pincorrect'}).
                   8878:              '<br />';
1.522     www      8879:     if (($env{'form.gradingmechanism'} eq 'given') && ($number!=$foundgiven)) {
                   8880:        $result.='<span class="LC_error">'.&mt('Number of given answers does not agree with number of questions in file.').'</span>';
1.614     www      8881:        return $result;
1.522     www      8882:     } 
1.414     www      8883: # Remember Question Titles
                   8884: # FIXME: Possibly need delimiter other than ":"
                   8885:     for (my $i=0;$i<$number;$i++) {
                   8886:         $result.='<input type="hidden" name="question:'.$i.'" value="'.
                   8887:                  &HTML::Entities::encode($questiontitles[$i],'"&<>').'" />';
                   8888:     }
1.411     www      8889:     my $correct_count=0;
                   8890:     my $student_count=0;
                   8891:     my $unknown_count=0;
1.414     www      8892: # Match answers with usernames
                   8893: # FIXME: Possibly need delimiter other than ":"
1.409     albertel 8894:     foreach my $id (keys(%responses)) {
1.410     www      8895:        if ($correct_ids{$id}) {
1.414     www      8896:           $result.="\n".'<input type="hidden" name="correct:'.$correct_count.':'.$correct_ids{$id}.'" value="'.$responses{$id}.'" />';
1.411     www      8897:           $correct_count++;
1.410     www      8898:        } elsif ($clicker_ids{$id}) {
1.437     www      8899:           if ($clicker_ids{$id}=~/\,/) {
                   8900: # More than one user with the same clicker!
                   8901:              $result.="\n<hr />".&mt('Clicker registered more than once').": <tt>".$id."</tt><br />";
                   8902:              $result.="\n".'<input type="hidden" name="unknown:'.$id.'" value="'.$responses{$id}.'" />'.
                   8903:                            "<select name='multi".$id."'>";
                   8904:              foreach my $reguser (sort(split(/\,/,$clicker_ids{$id}))) {
                   8905:                  $result.="<option value='".$reguser."'>".&Apache::loncommon::plainname(split(/\:/,$reguser)).' ('.$reguser.')</option>';
                   8906:              }
                   8907:              $result.='</select>';
                   8908:              $unknown_count++;
                   8909:           } else {
                   8910: # Good: found one and only one user with the right clicker
                   8911:              $result.="\n".'<input type="hidden" name="student:'.$clicker_ids{$id}.'" value="'.$responses{$id}.'" />';
                   8912:              $student_count++;
                   8913:           }
1.410     www      8914:        } else {
1.411     www      8915:           $result.="\n<hr />".&mt('Unregistered Clicker')." <tt>".$id."</tt><br />";
                   8916:           $result.="\n".'<input type="hidden" name="unknown:'.$id.'" value="'.$responses{$id}.'" />'.
                   8917:                    "\n".&mt("Username").": <input type='text' name='uname".$id."' />&nbsp;".
                   8918:                    "\n".&mt("Domain").": ".
                   8919:                    &Apache::loncommon::select_dom_form($env{'course.'.$env{'request.course.id'}.'.domain'},'udom'.$id).'&nbsp;'.
                   8920:                    &Apache::loncommon::selectstudent_link('clickeranalysis','uname'.$id,'udom'.$id);
                   8921:           $unknown_count++;
1.410     www      8922:        }
1.405     www      8923:     }
1.412     www      8924:     $result.='<hr />'.
                   8925:              &mt('Found [_1] registered and [_2] unregistered clickers.',$student_count,$unknown_count);
1.521     www      8926:     if (($env{'form.gradingmechanism'} ne 'attendance') && ($env{'form.gradingmechanism'} ne 'given')) {
1.412     www      8927:        if ($correct_count==0) {
                   8928:           $errormsg.="Found no correct answers answers for grading!";
                   8929:        } elsif ($correct_count>1) {
1.414     www      8930:           $result.='<br /><span class="LC_warning">'.&mt("Found [_1] entries for grading!",$correct_count).'</span>';
1.412     www      8931:        }
                   8932:     }
1.428     www      8933:     if ($number<1) {
                   8934:        $errormsg.="Found no questions.";
                   8935:     }
1.412     www      8936:     if ($errormsg) {
                   8937:        $result.='<br /><span class="LC_error">'.&mt($errormsg).'</span>';
                   8938:     } else {
                   8939:        $result.='<br /><input type="submit" name="finalize" value="'.&mt('Finalize Grading').'" />';
                   8940:     }
                   8941:     $result.='</form></td></tr></table>'."\n".
1.410     www      8942:              '</td></tr></table><br /><br />'."\n";
1.614     www      8943:     return $result;
1.400     www      8944: }
                   8945: 
1.405     www      8946: sub iclicker_eval {
1.406     www      8947:     my ($questiontitles,$responses)=@_;
1.405     www      8948:     my $number=0;
                   8949:     my $errormsg='';
                   8950:     foreach my $line (split(/[\n\r]/,$env{'form.upfile'})) {
1.410     www      8951:         my %components=&Apache::loncommon::record_sep($line);
                   8952:         my @entries=map {$components{$_}} (sort(keys(%components)));
1.408     albertel 8953: 	if ($entries[0] eq 'Question') {
                   8954: 	    for (my $i=3;$i<$#entries;$i+=6) {
                   8955: 		$$questiontitles[$number]=$entries[$i];
                   8956: 		$number++;
                   8957: 	    }
                   8958: 	}
                   8959: 	if ($entries[0]=~/^\#/) {
                   8960: 	    my $id=$entries[0];
                   8961: 	    my @idresponses;
                   8962: 	    $id=~s/^[\#0]+//;
                   8963: 	    for (my $i=0;$i<$number;$i++) {
                   8964: 		my $idx=3+$i*6;
                   8965: 		push(@idresponses,$entries[$idx]);
                   8966: 	    }
                   8967: 	    $$responses{$id}=join(',',@idresponses);
                   8968: 	}
1.405     www      8969:     }
                   8970:     return ($errormsg,$number);
                   8971: }
                   8972: 
1.419     www      8973: sub interwrite_eval {
                   8974:     my ($questiontitles,$responses)=@_;
                   8975:     my $number=0;
                   8976:     my $errormsg='';
1.420     www      8977:     my $skipline=1;
                   8978:     my $questionnumber=0;
                   8979:     my %idresponses=();
1.419     www      8980:     foreach my $line (split(/[\n\r]/,$env{'form.upfile'})) {
                   8981:         my %components=&Apache::loncommon::record_sep($line);
                   8982:         my @entries=map {$components{$_}} (sort(keys(%components)));
1.420     www      8983:         if ($entries[1] eq 'Time') { $skipline=0; next; }
                   8984:         if ($entries[1] eq 'Response') { $skipline=1; }
                   8985:         next if $skipline;
                   8986:         if ($entries[0]!=$questionnumber) {
                   8987:            $questionnumber=$entries[0];
                   8988:            $$questiontitles[$number]=&mt('Question [_1]',$questionnumber);
                   8989:            $number++;
1.419     www      8990:         }
1.420     www      8991:         my $id=$entries[4];
                   8992:         $id=~s/^[\#0]+//;
1.421     www      8993:         $id=~s/^v\d*\://i;
                   8994:         $id=~s/[\-\:]//g;
1.420     www      8995:         $idresponses{$id}[$number]=$entries[6];
                   8996:     }
1.524     raeburn  8997:     foreach my $id (keys(%idresponses)) {
1.420     www      8998:        $$responses{$id}=join(',',@{$idresponses{$id}});
                   8999:        $$responses{$id}=~s/^\s*\,//;
1.419     www      9000:     }
                   9001:     return ($errormsg,$number);
                   9002: }
                   9003: 
1.414     www      9004: sub assign_clicker_grades {
1.608     www      9005:     my ($r,$symb)=@_;
1.414     www      9006:     if (!$symb) {return '';}
1.416     www      9007: # See which part we are saving to
1.582     raeburn  9008:     my $res_error;
                   9009:     my ($partlist,$handgrade,$responseType) = &response_type($symb,\$res_error);
                   9010:     if ($res_error) {
                   9011:         return &navmap_errormsg();
                   9012:     }
1.416     www      9013: # FIXME: This should probably look for the first handgradeable part
                   9014:     my $part=$$partlist[0];
                   9015: # Start screen output
1.598     www      9016:     my $result='';
1.416     www      9017: 
1.414     www      9018:     my $heading=&mt('Assigning grades based on clicker file');
                   9019:     $result.=(<<ENDHEADER);
                   9020: <br /><table width="100%" border="0"><tr><td bgcolor="#777777">
                   9021: <table width="100%" border="0"><tr bgcolor="#e6ffff"><td>
                   9022: <b>$heading</b></td></tr><tr bgcolor=#ffffe6><td>
                   9023: ENDHEADER
                   9024: # Get correct result
                   9025: # FIXME: Possibly need delimiter other than ":"
                   9026:     my @correct=();
1.415     www      9027:     my $gradingmechanism=$env{'form.gradingmechanism'};
                   9028:     my $number=$env{'form.number'};
                   9029:     if ($gradingmechanism ne 'attendance') {
1.414     www      9030:        foreach my $key (keys(%env)) {
                   9031:           if ($key=~/^form\.correct\:/) {
                   9032:              my @input=split(/\,/,$env{$key});
                   9033:              for (my $i=0;$i<=$#input;$i++) {
                   9034:                  if (($correct[$i]) && ($input[$i]) &&
                   9035:                      ($correct[$i] ne $input[$i])) {
                   9036:                     $result.='<br /><span class="LC_warning">'.
                   9037:                              &mt('More than one correct result given for question "[_1]": [_2] versus [_3].',
                   9038:                                  $env{'form.question:'.$i},$correct[$i],$input[$i]).'</span>';
                   9039:                  } elsif ($input[$i]) {
                   9040:                     $correct[$i]=$input[$i];
                   9041:                  }
                   9042:              }
                   9043:           }
                   9044:        }
1.415     www      9045:        for (my $i=0;$i<$number;$i++) {
1.414     www      9046:           if (!$correct[$i]) {
                   9047:              $result.='<br /><span class="LC_error">'.
                   9048:                       &mt('No correct result given for question "[_1]"!',
                   9049:                           $env{'form.question:'.$i}).'</span>';
                   9050:           }
                   9051:        }
                   9052:        $result.='<br />'.&mt("Correct answer: [_1]",join(', ',map { ($_?$_:'-') } @correct));
                   9053:     }
                   9054: # Start grading
1.415     www      9055:     my $pcorrect=$env{'form.pcorrect'};
                   9056:     my $pincorrect=$env{'form.pincorrect'};
1.416     www      9057:     my $storecount=0;
1.415     www      9058:     foreach my $key (keys(%env)) {
1.420     www      9059:        my $user='';
1.415     www      9060:        if ($key=~/^form\.student\:(.*)$/) {
1.420     www      9061:           $user=$1;
                   9062:        }
                   9063:        if ($key=~/^form\.unknown\:(.*)$/) {
                   9064:           my $id=$1;
                   9065:           if (($env{'form.uname'.$id}) && ($env{'form.udom'.$id})) {
                   9066:              $user=$env{'form.uname'.$id}.':'.$env{'form.udom'.$id};
1.437     www      9067:           } elsif ($env{'form.multi'.$id}) {
                   9068:              $user=$env{'form.multi'.$id};
1.420     www      9069:           }
                   9070:        }
                   9071:        if ($user) { 
1.415     www      9072:           my @answer=split(/\,/,$env{$key});
                   9073:           my $sum=0;
1.522     www      9074:           my $realnumber=$number;
1.415     www      9075:           for (my $i=0;$i<$number;$i++) {
1.576     www      9076:              if  ($correct[$i] eq '-') {
                   9077:                 $realnumber--;
                   9078:              } elsif ($answer[$i]) {
1.415     www      9079:                 if ($gradingmechanism eq 'attendance') {
                   9080:                    $sum+=$pcorrect;
1.576     www      9081:                 } elsif ($correct[$i] eq '*') {
1.522     www      9082:                    $sum+=$pcorrect;
1.415     www      9083:                 } else {
                   9084:                    if ($answer[$i] eq $correct[$i]) {
                   9085:                       $sum+=$pcorrect;
                   9086:                    } else {
                   9087:                       $sum+=$pincorrect;
                   9088:                    }
                   9089:                 }
                   9090:              }
                   9091:           }
1.522     www      9092:           my $ave=$sum/(100*$realnumber);
1.416     www      9093: # Store
                   9094:           my ($username,$domain)=split(/\:/,$user);
                   9095:           my %grades=();
                   9096:           $grades{"resource.$part.solved"}='correct_by_override';
                   9097:           $grades{"resource.$part.awarded"}=$ave;
                   9098:           $grades{"resource.regrader"}="$env{'user.name'}:$env{'user.domain'}";
                   9099:           my $returncode=&Apache::lonnet::cstore(\%grades,$symb,
                   9100:                                                  $env{'request.course.id'},
                   9101:                                                  $domain,$username);
                   9102:           if ($returncode ne 'ok') {
                   9103:              $result.="<br /><span class=\"LC_error\">Failed to save student $username:$domain. Message when trying to save was ($returncode)</span>";
                   9104:           } else {
                   9105:              $storecount++;
                   9106:           }
1.415     www      9107:        }
                   9108:     }
                   9109: # We are done
1.549     hauer    9110:     $result.='<br />'.&mt('Successfully stored grades for [quant,_1,student].',$storecount).
1.416     www      9111:              '</td></tr></table>'."\n".
1.414     www      9112:              '</td></tr></table><br /><br />'."\n";
1.614     www      9113:     return $result;
1.414     www      9114: }
                   9115: 
1.582     raeburn  9116: sub navmap_errormsg {
                   9117:     return '<div class="LC_error">'.
                   9118:            &mt('An error occurred retrieving information about resources in the course.').'<br />'.
1.595     raeburn  9119:            &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  9120:            '</div>';
                   9121: }
1.607     droeschl 9122: 
1.609     www      9123: sub startpage {
1.613     www      9124:     my ($r,$symb,$crumbs,$onlyfolderflag,$nodisplayflag) = @_;
1.614     www      9125:     unshift(@$crumbs,{href=>&href_symb_cmd($symb,'gradingmenu'),text=>"Grading"});
1.607     droeschl 9126:     $r->print(&Apache::loncommon::start_page('Grading',undef,
1.610     www      9127:                                           {'bread_crumbs' => $crumbs}));
1.613     www      9128:     unless ($nodisplayflag) {
                   9129:        $r->print(&Apache::lonhtmlcommon::resource_info_box($symb,$onlyfolderflag));
                   9130:     }
1.607     droeschl 9131: }
1.582     raeburn  9132: 
1.1       albertel 9133: sub handler {
1.41      ng       9134:     my $request=$_[0];
1.434     albertel 9135:     &reset_caches();
1.257     albertel 9136:     if ($env{'browser.mathml'}) {
1.141     www      9137: 	&Apache::loncommon::content_type($request,'text/xml');
1.41      ng       9138:     } else {
1.141     www      9139: 	&Apache::loncommon::content_type($request,'text/html');
1.41      ng       9140:     }
                   9141:     $request->send_http_header;
1.44      ng       9142:     return '' if $request->header_only;
1.41      ng       9143:     &Apache::loncommon::get_unprocessed_cgi($ENV{'QUERY_STRING'});
1.608     www      9144: 
                   9145: # see what command we need to execute
                   9146: 
1.160     albertel 9147:     my @commands=&Apache::loncommon::get_env_multiple('form.command');
                   9148:     my $command=$commands[0];
1.447     foxr     9149: 
1.160     albertel 9150:     if ($#commands > 0) {
                   9151: 	&Apache::lonnet::logthis("grades got multiple commands ".join(':',@commands));
                   9152:     }
1.608     www      9153: 
                   9154: # see what the symb is
                   9155: 
                   9156:     my $symb=$env{'form.symb'};
                   9157:     unless ($symb) {
                   9158:        (my $url=$env{'form.url'}) =~ s-^https*://($ENV{'SERVER_NAME'}|$ENV{'HTTP_HOST'})--;
                   9159:        $symb=&Apache::lonnet::symbread($url);
                   9160:     }
                   9161:     &Apache::lonenc::check_decrypt(\$symb);                             
                   9162: 
1.513     foxr     9163:     $ssi_error = 0;
1.324     albertel 9164:     if ($symb eq '' && $command eq '') {
1.601     www      9165: #
                   9166: # Not called from a resource
                   9167: #    
                   9168: 
1.41      ng       9169:     } else {
1.285     albertel 9170: 	&init_perm();
1.104     albertel 9171: 	if ($command eq 'submission' && $perm{'vgr'}) {
1.608     www      9172:             &startpage($request,$symb,[{href=>"", text=>"Student Submissions"}]);
1.611     www      9173: 	    ($env{'form.student'} eq '' ? &listStudents($request,$symb) : &submission($request,0,0,$symb));
1.103     albertel 9174: 	} elsif ($command eq 'pickStudentPage' && $perm{'vgr'}) {
1.615     www      9175:             &startpage($request,$symb,[{href=>&href_symb_cmd($symb,'all_for_one'),text=>'Grade page/folder for one student'},
                   9176:                                        {href=>'',text=>'Select student'}],1,1);
1.608     www      9177: 	    &pickStudentPage($request,$symb);
1.103     albertel 9178: 	} elsif ($command eq 'displayPage' && $perm{'vgr'}) {
1.615     www      9179:             &startpage($request,$symb,
                   9180:                                       [{href=>&href_symb_cmd($symb,'all_for_one'),text=>'Grade page/folder for one student'},
                   9181:                                        {href=>'',text=>'Select student'},
                   9182:                                        {href=>'',text=>'Grade student'}],1,1);
1.608     www      9183: 	    &displayPage($request,$symb);
1.104     albertel 9184: 	} elsif ($command eq 'gradeByPage' && $perm{'mgr'}) {
1.616     www      9185:             &startpage($request,$symb,[{href=>&href_symb_cmd($symb,'all_for_one'),text=>'Grade page/folder for one student'},
                   9186:                                        {href=>'',text=>'Select student'},
                   9187:                                        {href=>'',text=>'Grade student'},
                   9188:                                        {href=>'',text=>'Store grades'}],1,1);
1.608     www      9189: 	    &updateGradeByPage($request,$symb);
1.104     albertel 9190: 	} elsif ($command eq 'processGroup' && $perm{'vgr'}) {
1.611     www      9191:             &startpage($request,$symb);
1.608     www      9192: 	    &processGroup($request,$symb);
1.104     albertel 9193: 	} elsif ($command eq 'gradingmenu' && $perm{'vgr'}) {
1.608     www      9194:             &startpage($request,$symb);
                   9195: 	    $request->print(&grading_menu($request,$symb));
1.598     www      9196: 	} elsif ($command eq 'individual' && $perm{'vgr'}) {
1.617     www      9197:             &startpage($request,$symb,[{href=>'',text=>'Select individual students to grade'}]);
1.608     www      9198: 	    $request->print(&submit_options($request,$symb));
1.598     www      9199:         } elsif ($command eq 'ungraded' && $perm{'vgr'}) {
1.617     www      9200:             &startpage($request,$symb,[{href=>'',text=>'Grade ungraded submissions'}]);
                   9201:             $request->print(&listStudents($request,$symb,'graded'));
1.598     www      9202:         } elsif ($command eq 'table' && $perm{'vgr'}) {
1.614     www      9203:             &startpage($request,$symb,[{href=>"", text=>"Grading table"}]);
1.611     www      9204:             $request->print(&submit_options_table($request,$symb));
1.598     www      9205:         } elsif ($command eq 'all_for_one' && $perm{'vgr'}) {
1.615     www      9206:             &startpage($request,$symb,[{href=>'',text=>'Grade page/folder for one student'}],1,1);
1.608     www      9207:             $request->print(&submit_options_sequence($request,$symb));
1.104     albertel 9208: 	} elsif ($command eq 'viewgrades' && $perm{'vgr'}) {
1.614     www      9209:             &startpage($request,$symb,[{href=>&href_symb_cmd($symb,"table"), text=>"Grading table"},{href=>'', text=>"Modify grades"}]);
1.608     www      9210: 	    $request->print(&viewgrades($request,$symb));
1.104     albertel 9211: 	} elsif ($command eq 'handgrade' && $perm{'mgr'}) {
1.611     www      9212:             &startpage($request,$symb);
1.608     www      9213: 	    $request->print(&processHandGrade($request,$symb));
1.106     albertel 9214: 	} elsif ($command eq 'editgrades' && $perm{'mgr'}) {
1.614     www      9215:             &startpage($request,$symb,[{href=>&href_symb_cmd($symb,"table"), text=>"Grading table"},
                   9216:                                        {href=>&href_symb_cmd($symb,'viewgrades').'&group=all&section=all&Status=Active',
                   9217:                                                                              text=>"Modify grades"},
                   9218:                                        {href=>'', text=>"Store grades"}]);
1.608     www      9219: 	    $request->print(&editgrades($request,$symb));
1.602     www      9220:         } elsif ($command eq 'initialverifyreceipt' && $perm{'vgr'}) {
1.616     www      9221:             &startpage($request,$symb,[{href=>'',text=>'Verify Receipt Number'}]);
1.611     www      9222:             $request->print(&initialverifyreceipt($request,$symb));
1.106     albertel 9223: 	} elsif ($command eq 'verify' && $perm{'vgr'}) {
1.616     www      9224:             &startpage($request,$symb,[{href=>&href_symb_cmd($symb,"initialverifyreceipt"),text=>'Verify Receipt Number'},
                   9225:                                        {href=>'',text=>'Verification Result'}]);
1.608     www      9226: 	    $request->print(&verifyreceipt($request,$symb));
1.400     www      9227:         } elsif ($command eq 'processclicker' && $perm{'mgr'}) {
1.615     www      9228:             &startpage($request,$symb,[{href=>'', text=>'Process clicker'}]);
1.608     www      9229:             $request->print(&process_clicker($request,$symb));
1.400     www      9230:         } elsif ($command eq 'processclickerfile' && $perm{'mgr'}) {
1.615     www      9231:             &startpage($request,$symb,[{href=>&href_symb_cmd($symb,'processclicker'), text=>'Process clicker'},
                   9232:                                        {href=>'', text=>'Process clicker file'}]);
1.608     www      9233:             $request->print(&process_clicker_file($request,$symb));
1.414     www      9234:         } elsif ($command eq 'assignclickergrades' && $perm{'mgr'}) {
1.615     www      9235:             &startpage($request,$symb,[{href=>&href_symb_cmd($symb,'processclicker'), text=>'Process clicker'},
                   9236:                                        {href=>'', text=>'Process clicker file'},
                   9237:                                        {href=>'', text=>'Store grades'}]);
1.608     www      9238:             $request->print(&assign_clicker_grades($request,$symb));
1.106     albertel 9239: 	} elsif ($command eq 'csvform' && $perm{'mgr'}) {
1.616     www      9240:             &startpage($request,$symb,[{href=>'', text=>'Grade/Manage/Review Bubblesheets'}],1,1);
1.608     www      9241: 	    $request->print(&upcsvScores_form($request,$symb));
1.106     albertel 9242: 	} elsif ($command eq 'csvupload' && $perm{'mgr'}) {
1.616     www      9243:             &startpage($request,$symb,[{href=>'', text=>'Grade/Manage/Review Bubblesheets'}],1,1);
1.608     www      9244: 	    $request->print(&csvupload($request,$symb));
1.106     albertel 9245: 	} elsif ($command eq 'csvuploadmap' && $perm{'mgr'} ) {
1.616     www      9246:             &startpage($request,$symb,[{href=>'', text=>'Grade/Manage/Review Bubblesheets'}],1,1);
1.608     www      9247: 	    $request->print(&csvuploadmap($request,$symb));
1.246     albertel 9248: 	} elsif ($command eq 'csvuploadoptions' && $perm{'mgr'}) {
1.257     albertel 9249: 	    if ($env{'form.associate'} ne 'Reverse Association') {
1.616     www      9250:                 &startpage($request,$symb,[{href=>'', text=>'Grade/Manage/Review Bubblesheets'}],1,1);
1.608     www      9251: 		$request->print(&csvuploadoptions($request,$symb));
1.41      ng       9252: 	    } else {
1.257     albertel 9253: 		if ( $env{'form.upfile_associate'} ne 'reverse' ) {
                   9254: 		    $env{'form.upfile_associate'} = 'reverse';
1.41      ng       9255: 		} else {
1.257     albertel 9256: 		    $env{'form.upfile_associate'} = 'forward';
1.41      ng       9257: 		}
1.616     www      9258:                 &startpage($request,$symb,[{href=>'', text=>'Grade/Manage/Review Bubblesheets'}],1,1);
1.608     www      9259: 		$request->print(&csvuploadmap($request,$symb));
1.41      ng       9260: 	    }
1.246     albertel 9261: 	} elsif ($command eq 'csvuploadassign' && $perm{'mgr'} ) {
1.616     www      9262:             &startpage($request,$symb,[{href=>'', text=>'Grade/Manage/Review Bubblesheets'}],1,1);
1.608     www      9263: 	    $request->print(&csvuploadassign($request,$symb));
1.106     albertel 9264: 	} elsif ($command eq 'scantron_selectphase' && $perm{'mgr'}) {
1.616     www      9265:             &startpage($request,$symb,[{href=>'', text=>'Grade/Manage/Review Bubblesheets'}],1,1);
1.612     www      9266: 	    $request->print(&scantron_selectphase($request,undef,$symb));
1.203     albertel 9267:  	} elsif ($command eq 'scantron_warning' && $perm{'mgr'}) {
1.616     www      9268:             &startpage($request,$symb,[{href=>'', text=>'Grade/Manage/Review Bubblesheets'}],1,1);
1.608     www      9269:  	    $request->print(&scantron_do_warning($request,$symb));
1.142     albertel 9270: 	} elsif ($command eq 'scantron_validate' && $perm{'mgr'}) {
1.616     www      9271:             &startpage($request,$symb,[{href=>'', text=>'Grade/Manage/Review Bubblesheets'}],1,1);
1.608     www      9272: 	    $request->print(&scantron_validate_file($request,$symb));
1.106     albertel 9273: 	} elsif ($command eq 'scantron_process' && $perm{'mgr'}) {
1.616     www      9274:             &startpage($request,$symb,[{href=>'', text=>'Grade/Manage/Review Bubblesheets'}],1,1);
1.608     www      9275: 	    $request->print(&scantron_process_students($request,$symb));
1.157     albertel 9276:  	} elsif ($command eq 'scantronupload' && 
1.257     albertel 9277:  		 (&Apache::lonnet::allowed('usc',$env{'request.role.domain'})||
                   9278: 		  &Apache::lonnet::allowed('usc',$env{'request.course.id'}))) {
1.616     www      9279:             &startpage($request,$symb,[{href=>'', text=>'Grade/Manage/Review Bubblesheets'}],1,1);
1.608     www      9280:  	    $request->print(&scantron_upload_scantron_data($request,$symb)); 
1.157     albertel 9281:  	} elsif ($command eq 'scantronupload_save' &&
1.257     albertel 9282:  		 (&Apache::lonnet::allowed('usc',$env{'request.role.domain'})||
                   9283: 		  &Apache::lonnet::allowed('usc',$env{'request.course.id'}))) {
1.616     www      9284:             &startpage($request,$symb,[{href=>'', text=>'Grade/Manage/Review Bubblesheets'}],1,1);
1.608     www      9285:  	    $request->print(&scantron_upload_scantron_data_save($request,$symb));
1.202     albertel 9286:  	} elsif ($command eq 'scantron_download' &&
1.257     albertel 9287: 		 &Apache::lonnet::allowed('usc',$env{'request.course.id'})) {
1.616     www      9288:             &startpage($request,$symb,[{href=>'', text=>'Grade/Manage/Review Bubblesheets'}],1,1);
1.608     www      9289:  	    $request->print(&scantron_download_scantron_data($request,$symb));
1.523     raeburn  9290:         } elsif ($command eq 'checksubmissions' && $perm{'vgr'}) {
1.616     www      9291:             &startpage($request,$symb,[{href=>'', text=>'Grade/Manage/Review Bubblesheets'}],1,1);
1.608     www      9292:             $request->print(&checkscantron_results($request,$symb));     
1.106     albertel 9293: 	} elsif ($command) {
1.611     www      9294:             &startpage($request,$symb);
1.562     bisitz   9295: 	    $request->print('<p class="LC_error">'.&mt('Access Denied ([_1])',$command).'</p>');
1.26      albertel 9296: 	}
1.2       albertel 9297:     }
1.513     foxr     9298:     if ($ssi_error) {
                   9299: 	&ssi_print_error($request);
                   9300:     }
1.353     albertel 9301:     $request->print(&Apache::loncommon::end_page());
1.434     albertel 9302:     &reset_caches();
1.44      ng       9303:     return '';
                   9304: }
                   9305: 
1.1       albertel 9306: 1;
                   9307: 
1.13      albertel 9308: __END__;
1.531     jms      9309: 
                   9310: 
                   9311: =head1 NAME
                   9312: 
                   9313: Apache::grades
                   9314: 
                   9315: =head1 SYNOPSIS
                   9316: 
                   9317: Handles the viewing of grades.
                   9318: 
                   9319: This is part of the LearningOnline Network with CAPA project
                   9320: described at http://www.lon-capa.org.
                   9321: 
                   9322: =head1 OVERVIEW
                   9323: 
                   9324: Do an ssi with retries:
                   9325: While I'd love to factor out this with the vesrion in lonprintout,
                   9326: 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
                   9327: I'm not quite ready to invent (e.g. an ssi_with_retry object).
                   9328: 
                   9329: At least the logic that drives this has been pulled out into loncommon.
                   9330: 
                   9331: 
                   9332: 
                   9333: ssi_with_retries - Does the server side include of a resource.
                   9334:                      if the ssi call returns an error we'll retry it up to
                   9335:                      the number of times requested by the caller.
                   9336:                      If we still have a proble, no text is appended to the
                   9337:                      output and we set some global variables.
                   9338:                      to indicate to the caller an SSI error occurred.  
                   9339:                      All of this is supposed to deal with the issues described
                   9340:                      in LonCAPA BZ 5631 see:
                   9341:                      http://bugs.lon-capa.org/show_bug.cgi?id=5631
                   9342:                      by informing the user that this happened.
                   9343: 
                   9344: Parameters:
                   9345:   resource   - The resource to include.  This is passed directly, without
                   9346:                interpretation to lonnet::ssi.
                   9347:   form       - The form hash parameters that guide the interpretation of the resource
                   9348:                
                   9349:   retries    - Number of retries allowed before giving up completely.
                   9350: Returns:
                   9351:   On success, returns the rendered resource identified by the resource parameter.
                   9352: Side Effects:
                   9353:   The following global variables can be set:
                   9354:    ssi_error                - If an unrecoverable error occurred this becomes true.
                   9355:                               It is up to the caller to initialize this to false
                   9356:                               if desired.
                   9357:    ssi_error_resource  - If an unrecoverable error occurred, this is the value
                   9358:                               of the resource that could not be rendered by the ssi
                   9359:                               call.
                   9360:    ssi_error_message   - The error string fetched from the ssi response
                   9361:                               in the event of an error.
                   9362: 
                   9363: 
                   9364: =head1 HANDLER SUBROUTINE
                   9365: 
                   9366: ssi_with_retries()
                   9367: 
                   9368: =head1 SUBROUTINES
                   9369: 
                   9370: =over
                   9371: 
                   9372: =item scantron_get_correction() : 
                   9373: 
                   9374:    Builds the interface screen to interact with the operator to fix a
                   9375:    specific error condition in a specific scanline
                   9376: 
                   9377:  Arguments:
                   9378:     $r           - Apache request object
                   9379:     $i           - number of the current scanline
                   9380:     $scan_record - hash ref as returned from &scantron_parse_scanline()
                   9381:     $scan_config - hash ref as returned from &get_scantron_config()
                   9382:     $line        - full contents of the current scanline
                   9383:     $error       - error condition, valid values are
                   9384:                    'incorrectCODE', 'duplicateCODE',
                   9385:                    'doublebubble', 'missingbubble',
                   9386:                    'duplicateID', 'incorrectID'
                   9387:     $arg         - extra information needed
                   9388:        For errors:
                   9389:          - duplicateID   - paper number that this studentID was seen before on
                   9390:          - duplicateCODE - array ref of the paper numbers this CODE was
                   9391:                            seen on before
                   9392:          - incorrectCODE - current incorrect CODE 
                   9393:          - doublebubble  - array ref of the bubble lines that have double
                   9394:                            bubble errors
                   9395:          - missingbubble - array ref of the bubble lines that have missing
                   9396:                            bubble errors
                   9397: 
                   9398: =item  scantron_get_maxbubble() : 
                   9399: 
1.582     raeburn  9400:    Arguments:
                   9401:        $nav_error  - Reference to scalar which is a flag to indicate a
                   9402:                       failure to retrieve a navmap object.
                   9403:        if $nav_error is set to 1 by scantron_get_maxbubble(), the 
                   9404:        calling routine should trap the error condition and display the warning
                   9405:        found in &navmap_errormsg().
                   9406: 
1.531     jms      9407:    Returns the maximum number of bubble lines that are expected to
                   9408:    occur. Does this by walking the selected sequence rendering the
                   9409:    resource and then checking &Apache::lonxml::get_problem_counter()
                   9410:    for what the current value of the problem counter is.
                   9411: 
                   9412:    Caches the results to $env{'form.scantron_maxbubble'},
                   9413:    $env{'form.scantron.bubble_lines.n'}, 
                   9414:    $env{'form.scantron.first_bubble_line.n'} and
                   9415:    $env{"form.scantron.sub_bubblelines.n"}
                   9416:    which are the total number of bubble, lines, the number of bubble
                   9417:    lines for response n and number of the first bubble line for response n,
                   9418:    and a comma separated list of numbers of bubble lines for sub-questions
                   9419:    (for optionresponse, matchresponse, and rankresponse items), for response n.  
                   9420: 
                   9421: 
                   9422: =item  scantron_validate_missingbubbles() : 
                   9423: 
                   9424:    Validates all scanlines in the selected file to not have any
                   9425:     answers that don't have bubbles that have not been verified
                   9426:     to be bubble free.
                   9427: 
                   9428: =item  scantron_process_students() : 
                   9429: 
                   9430:    Routine that does the actual grading of the bubble sheet information.
                   9431: 
                   9432:    The parsed scanline hash is added to %env 
                   9433: 
                   9434:    Then foreach unskipped scanline it does an &Apache::lonnet::ssi()
                   9435:    foreach resource , with the form data of
                   9436: 
                   9437: 	'submitted'     =>'scantron' 
                   9438: 	'grade_target'  =>'grade',
                   9439: 	'grade_username'=> username of student
                   9440: 	'grade_domain'  => domain of student
                   9441: 	'grade_courseid'=> of course
                   9442: 	'grade_symb'    => symb of resource to grade
                   9443: 
                   9444:     This triggers a grading pass. The problem grading code takes care
                   9445:     of converting the bubbled letter information (now in %env) into a
                   9446:     valid submission.
                   9447: 
                   9448: =item  scantron_upload_scantron_data() :
                   9449: 
                   9450:     Creates the screen for adding a new bubble sheet data file to a course.
                   9451: 
                   9452: =item  scantron_upload_scantron_data_save() : 
                   9453: 
                   9454:    Adds a provided bubble information data file to the course if user
                   9455:    has the correct privileges to do so. 
                   9456: 
                   9457: =item  valid_file() :
                   9458: 
                   9459:    Validates that the requested bubble data file exists in the course.
                   9460: 
                   9461: =item  scantron_download_scantron_data() : 
                   9462: 
                   9463:    Shows a list of the three internal files (original, corrected,
                   9464:    skipped) for a specific bubble sheet data file that exists in the
                   9465:    course.
                   9466: 
                   9467: =item  scantron_validate_ID() : 
                   9468: 
                   9469:    Validates all scanlines in the selected file to not have any
1.556     weissno  9470:    invalid or underspecified student/employee IDs
1.531     jms      9471: 
1.582     raeburn  9472: =item navmap_errormsg() :
                   9473: 
                   9474:    Returns HTML mark-up inside a <div></div> with a link to re-initialize the course.
                   9475:    Should be called whenever the request to instantiate a navmap object fails.  
                   9476: 
1.531     jms      9477: =back
                   9478: 
                   9479: =cut

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