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

1.17      albertel    1: # The LearningOnline Network with CAPA
1.13      albertel    2: # The LON-CAPA Grading handler
1.17      albertel    3: #
1.619   ! www         4: # $Id: grades.pm,v 1.618 2010/04/14 00:38:09 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.619   ! www      1132:     my ($request,$symb)  = @_;
1.41      ng       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.619   ! www      1142: 	&submission($request,$ctr,$total,$symb);
1.41      ng       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.619   ! www      2211: # FIXME: the logic seems off here. Why show the grade button if you cannot grade?
1.618     www      2212:     if (!&canmodify($usec)) {
1.120     ng       2213: 	my $toGrade.='<input type="button" value="Grade Student" '.
1.589     bisitz   2214: 	    'onclick="javascript:checksubmit(this.form,\'Grade Student\',\''
1.417     albertel 2215: 	    .$counter.'\');" target="_self" /> &nbsp;'."\n" if (&canmodify($usec));
1.468     albertel 2216: 	$toGrade.='</div>'."\n";
1.180     albertel 2217: 	$request->print($toGrade);
1.41      ng       2218: 	return;
1.180     albertel 2219:     } else {
1.468     albertel 2220: 	$request->print('</div>'."\n");
1.41      ng       2221:     }
1.33      ng       2222: 
1.121     ng       2223:     # essay grading message center
1.257     albertel 2224:     if ($env{'form.handgrade'} eq 'yes') {
1.468     albertel 2225: 	my $result='<div class="LC_grade_message_center">';
                   2226:     
                   2227: 	$result.='<div class="LC_grade_message_center_header">'.
                   2228: 	    &mt('Send Message').'</div><div class="LC_grade_message_center_body">';
1.257     albertel 2229: 	my ($lastname,$givenn) = split(/,/,$env{'form.fullname'});
1.118     ng       2230: 	my $msgfor = $givenn.' '.$lastname;
1.464     albertel 2231: 	if (scalar(@$col_fullnames) > 0) {
                   2232: 	    my $lastone = pop(@$col_fullnames);
                   2233: 	    $msgfor .= ', '.(join ', ',@$col_fullnames).' and '.$lastone.'.';
1.118     ng       2234: 	}
                   2235: 	$msgfor =~ s/\'/\\'/g; #' stupid emacs - no! javascript
1.468     albertel 2236: 	$result.='<input type="hidden" name="includemsg'.$counter.'" value="" />'."\n".
1.121     ng       2237: 	    '<input type="hidden" name="newmsg'.$counter.'" value="" />'."\n";
                   2238: 	$result.='&nbsp;<a href="javascript:msgCenter(document.SCORE,'.$counter.
1.417     albertel 2239: 	    ',\''.$msgfor.'\');" target="_self">'.
1.464     albertel 2240: 	    &mt('Compose message to student').(scalar(@$col_fullnames) >= 1 ? 's' : '').'</a><label> ('.
1.350     albertel 2241: 	    &mt('incl. grades').' <input type="checkbox" name="withgrades'.$counter.'" /></label>)'.
1.118     ng       2242: 	    '<img src="'.$request->dir_config('lonIconsURL').
                   2243: 	    '/mailbkgrd.gif" width="14" height="10" name="mailicon'.$counter.'" />'."\n".
1.298     www      2244: 	    '<br />&nbsp;('.
1.468     albertel 2245: 	    &mt('Message will be sent when you click on Save &amp; Next below.').")\n";
                   2246: 	$result.='</div></div>';
1.121     ng       2247: 	$request->print($result);
1.118     ng       2248:     }
1.41      ng       2249: 
                   2250:     my %seen = ();
                   2251:     my @partlist;
1.129     ng       2252:     my @gradePartRespid;
1.375     albertel 2253:     my @part_response_id = &flatten_responseType($responseType);
1.585     bisitz   2254:     $request->print(
1.588     bisitz   2255:         '<div class="LC_Box">'
                   2256:        .'<h3 class="LC_hcell">'.&mt('Assign Grades').'</h3>'
1.585     bisitz   2257:     );
1.592     bisitz   2258:     $request->print(&gradeBox_start());
1.375     albertel 2259:     foreach my $part_response_id (@part_response_id) {
                   2260:     	my ($partid,$respid) = @{ $part_response_id };
                   2261: 	my $part_resp = join('_',@{ $part_response_id });
1.322     albertel 2262: 	next if ($seen{$partid} > 0);
1.41      ng       2263: 	$seen{$partid}++;
1.393     albertel 2264: 	next if ($$handgrade{$part_resp} ne 'yes' 
                   2265: 		 && $env{'form.lastSub'} eq 'hdgrade');
1.524     raeburn  2266: 	push(@partlist,$partid);
                   2267: 	push(@gradePartRespid,$partid.'.'.$respid);
1.322     albertel 2268: 	$request->print(&gradeBox($request,$symb,$uname,$udom,$counter,$partid,\%record));
1.41      ng       2269:     }
1.585     bisitz   2270:     $request->print(&gradeBox_end()); # </div>
                   2271:     $request->print('</div>');
1.468     albertel 2272: 
                   2273:     $request->print('<div class="LC_grade_info_links">');
                   2274:     $request->print('</div>');
                   2275: 
1.45      ng       2276:     $result='<input type="hidden" name="partlist'.$counter.
                   2277: 	'" value="'.(join ":",@partlist).'" />'."\n";
1.129     ng       2278:     $result.='<input type="hidden" name="gradePartRespid'.
                   2279: 	'" value="'.(join ":",@gradePartRespid).'" />'."\n" if ($counter == 0);
1.45      ng       2280:     my $ctr = 0;
                   2281:     while ($ctr < scalar(@partlist)) {
                   2282: 	$result.='<input type="hidden" name="partid'.$counter.'_'.$ctr.'" value="'.
                   2283: 	    $partlist[$ctr].'" />'."\n";
                   2284: 	$ctr++;
                   2285:     }
1.468     albertel 2286:     $request->print($result.''."\n");
1.41      ng       2287: 
1.441     www      2288: # Done with printing info for one student
                   2289: 
1.468     albertel 2290:     $request->print('</div>');#LC_grade_show_user
1.441     www      2291: 
                   2292: 
1.41      ng       2293:     # print end of form
                   2294:     if ($counter == $total) {
1.592     bisitz   2295:         my $endform='<br /><hr /><table border="0"><tr><td>'."\n";
1.485     albertel 2296: 	$endform.='<input type="button" value="'.&mt('Save &amp; Next').'" '.
1.589     bisitz   2297: 	    'onclick="javascript:checksubmit(this.form,\'Save & Next\','.
1.417     albertel 2298: 	    $total.','.scalar(@partlist).');" target="_self" /> &nbsp;'."\n";
1.119     ng       2299: 	my $ntstu ='<select name="NTSTU">'.
                   2300: 	    '<option>1</option><option>2</option>'.
                   2301: 	    '<option>3</option><option>5</option>'.
                   2302: 	    '<option>7</option><option>10</option></select>'."\n";
1.257     albertel 2303: 	my $nsel = ($env{'form.NTSTU'} ne '' ? $env{'form.NTSTU'} : '1');
1.401     albertel 2304: 	$ntstu =~ s/<option>$nsel</<option selected="selected">$nsel</;
1.578     raeburn  2305:         $endform.=&mt('[_1]student(s)',$ntstu);
1.485     albertel 2306: 	$endform.='&nbsp;&nbsp;<input type="button" value="'.&mt('Previous').'" '.
1.589     bisitz   2307: 	    'onclick="javascript:checksubmit(this.form,\'Previous\');" target="_self" /> &nbsp;'."\n".
1.485     albertel 2308: 	    '<input type="button" value="'.&mt('Next').'" '.
1.589     bisitz   2309: 	    'onclick="javascript:checksubmit(this.form,\'Next\');" target="_self" /> &nbsp;';
1.592     bisitz   2310:         $endform.='<span class="LC_warning">'.
                   2311:                   &mt('(Next and Previous (student) do not save the scores.)').
                   2312:                   '</span>'."\n" ;
1.349     albertel 2313:         $endform.="<input type='hidden' value='".&get_increment().
1.348     bowersj2 2314:             "' name='increment' />";
1.485     albertel 2315: 	$endform.='</td></tr></table></form>';
1.41      ng       2316: 	$request->print($endform);
                   2317:     }
                   2318:     return '';
1.38      ng       2319: }
                   2320: 
1.464     albertel 2321: sub check_collaborators {
                   2322:     my ($symb,$uname,$udom,$record,$handgrade,$counter) = @_;
                   2323:     my ($result,@col_fullnames);
                   2324:     my ($classlist,undef,$fullname) = &getclasslist('all','0');
                   2325:     foreach my $part (keys(%$handgrade)) {
                   2326: 	my $ncol = &Apache::lonnet::EXT('resource.'.$part.
                   2327: 					'.maxcollaborators',
                   2328: 					$symb,$udom,$uname);
                   2329: 	next if ($ncol <= 0);
                   2330: 	$part =~ s/\_/\./g;
                   2331: 	next if ($record->{'resource.'.$part.'.collaborators'} eq '');
                   2332: 	my (@good_collaborators, @bad_collaborators);
                   2333: 	foreach my $possible_collaborator
                   2334: 	    (split(/,?\s+/,$record->{'resource.'.$part.'.collaborators'})) { 
                   2335: 	    $possible_collaborator =~ s/[\$\^\(\)]//g;
                   2336: 	    next if ($possible_collaborator eq '');
                   2337: 	    my ($co_name,$co_dom) = split(/\@|:/,$possible_collaborator);
                   2338: 	    $co_dom = $udom if (! defined($co_dom) || $co_dom =~ /^domain$/i);
                   2339: 	    next if ($co_name eq $uname && $co_dom eq $udom);
                   2340: 	    # Doing this grep allows 'fuzzy' specification
                   2341: 	    my @matches = grep(/^\Q$co_name\E:\Q$co_dom\E$/i, 
                   2342: 			       keys(%$classlist));
                   2343: 	    if (! scalar(@matches)) {
                   2344: 		push(@bad_collaborators, $possible_collaborator);
                   2345: 	    } else {
                   2346: 		push(@good_collaborators, @matches);
                   2347: 	    }
                   2348: 	}
                   2349: 	if (scalar(@good_collaborators) != 0) {
1.466     albertel 2350: 	    $result.='<br />'.&mt('Collaborators: ');
1.464     albertel 2351: 	    foreach my $name (@good_collaborators) {
                   2352: 		my ($lastname,$givenn) = split(/,/,$$fullname{$name});
                   2353: 		push(@col_fullnames, $givenn.' '.$lastname);
                   2354: 		$result.=$fullname->{$name}.'&nbsp; &nbsp; &nbsp;';
                   2355: 	    }
                   2356: 	    $result.='<br />'."\n";
1.466     albertel 2357: 	    my ($part)=split(/\./,$part);
1.464     albertel 2358: 	    $result.='<input type="hidden" name="collaborator'.$counter.
                   2359: 		'" value="'.$part.':'.(join ':',@good_collaborators).'" />'.
                   2360: 		"\n";
                   2361: 	}
                   2362: 	if (scalar(@bad_collaborators) > 0) {
1.466     albertel 2363: 	    $result.='<div class="LC_warning">';
1.464     albertel 2364: 	    $result.=&mt('This student has submitted [quant,_1,invalid collaborator]: [_2]',scalar(@bad_collaborators),join(', ',@bad_collaborators));
                   2365: 	    $result .= '</div>';
                   2366: 	}         
                   2367: 	if (scalar(@bad_collaborators > $ncol)) {
1.466     albertel 2368: 	    $result .= '<div class="LC_warning">';
1.464     albertel 2369: 	    $result .= &mt('This student has submitted too many '.
                   2370: 		'collaborators.  Maximum is [_1].',$ncol);
                   2371: 	    $result .= '</div>';
                   2372: 	}
                   2373:     }
                   2374:     return ($result,$fullname,\@col_fullnames);
                   2375: }
                   2376: 
1.44      ng       2377: #--- Retrieve the last submission for all the parts
1.38      ng       2378: sub get_last_submission {
1.119     ng       2379:     my ($returnhash)=@_;
1.596     raeburn  2380:     my (@string,$timestamp,%lasthidden);
1.119     ng       2381:     if ($$returnhash{'version'}) {
1.46      ng       2382: 	my %lasthash=();
                   2383: 	my ($version);
1.119     ng       2384: 	for ($version=1;$version<=$$returnhash{'version'};$version++) {
1.397     albertel 2385: 	    foreach my $key (sort(split(/\:/,
                   2386: 					$$returnhash{$version.':keys'}))) {
                   2387: 		$lasthash{$key}=$$returnhash{$version.':'.$key};
                   2388: 		$timestamp = 
1.545     raeburn  2389: 		    &Apache::lonlocal::locallocaltime($$returnhash{$version.':timestamp'});
1.46      ng       2390: 	    }
                   2391: 	}
1.596     raeburn  2392:         my %typeparts;
                   2393:         my $showsurv = 
                   2394:             &Apache::lonnet::allowed('vas',$env{'request.course.id'});
                   2395:         foreach my $key (sort(keys(%lasthash))) {
                   2396:             if ($key =~ /\.type$/) {
                   2397:                 if (($lasthash{$key} eq 'anonsurvey') || 
                   2398:                     ($lasthash{$key} eq 'anonsurveycred')) {
                   2399:                     my ($ign,@parts) = split(/\./,$key);
                   2400:                     pop(@parts);
                   2401:                     unless ($showsurv) {
                   2402:                         my $id = join(',',@parts);
                   2403:                         $typeparts{$ign.'.'.$id} = $lasthash{$key};
                   2404:                     }
                   2405:                     delete($lasthash{$key});
                   2406:                 }
                   2407:             }
                   2408:         }
                   2409:         my @hidden = keys(%typeparts);
1.397     albertel 2410: 	foreach my $key (keys(%lasthash)) {
                   2411: 	    next if ($key !~ /\.submission$/);
1.596     raeburn  2412:             my $hide;
                   2413:             if (@hidden) {
                   2414:                 foreach my $id (@hidden) {
                   2415:                     if ($key =~ /^\Q$id\E/) {
                   2416:                         $hide = 1;
                   2417:                         last;
                   2418:                     }
                   2419:                 }
                   2420:             }
1.397     albertel 2421: 	    my ($partid,$foo) = split(/submission$/,$key);
                   2422: 	    my $draft  = $lasthash{$partid.'awarddetail'} eq 'DRAFT' ?
1.398     albertel 2423: 		'<span class="LC_warning">Draft Copy</span> ' : '';
1.596     raeburn  2424: 	    push(@string, join(':', $key, $hide, $draft.$lasthash{$key}));
1.41      ng       2425: 	}
                   2426:     }
1.397     albertel 2427:     if (!@string) {
                   2428: 	$string[0] =
1.539     riegler  2429: 	    '<span class="LC_warning">'.&mt('Nothing submitted - no attempts.').'</span>';
1.397     albertel 2430:     }
                   2431:     return (\@string,\$timestamp);
1.38      ng       2432: }
1.35      ng       2433: 
1.44      ng       2434: #--- High light keywords, with style choosen by user.
1.38      ng       2435: sub keywords_highlight {
1.44      ng       2436:     my $string    = shift;
1.257     albertel 2437:     my $size      = $env{'form.kwsize'} eq '0' ? '' : 'size='.$env{'form.kwsize'};
                   2438:     my $styleon   = $env{'form.kwstyle'} eq ''  ? '' : $env{'form.kwstyle'};
1.41      ng       2439:     (my $styleoff = $styleon) =~ s/\</\<\//;
1.257     albertel 2440:     my @keylist   = split(/[,\s+]/,$env{'form.keywords'});
1.398     albertel 2441:     foreach my $keyword (@keylist) {
                   2442: 	$string =~ s/\b\Q$keyword\E(\b|\.)/<font color\=$env{'form.kwclr'} $size\>$styleon$keyword$styleoff<\/font>/gi;
1.41      ng       2443:     }
                   2444:     return $string;
1.38      ng       2445: }
1.36      ng       2446: 
1.44      ng       2447: #--- Called from submission routine
1.38      ng       2448: sub processHandGrade {
1.608     www      2449:     my ($request,$symb) = @_;
1.324     albertel 2450:     my (undef,undef,$url) = &Apache::lonnet::decode_symb($symb);
1.257     albertel 2451:     my $button = $env{'form.gradeOpt'};
                   2452:     my $ngrade = $env{'form.NCT'};
                   2453:     my $ntstu  = $env{'form.NTSTU'};
1.301     albertel 2454:     my $cdom   = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   2455:     my $cnum   = $env{'course.'.$env{'request.course.id'}.'.num'};
                   2456: 
1.44      ng       2457:     if ($button eq 'Save & Next') {
                   2458: 	my $ctr = 0;
                   2459: 	while ($ctr < $ngrade) {
1.257     albertel 2460: 	    my ($uname,$udom) = split(/:/,$env{'form.unamedom'.$ctr});
1.324     albertel 2461: 	    my ($errorflag,$pts,$wgt) = &saveHandGrade($request,$symb,$uname,$udom,$ctr);
1.71      ng       2462: 	    if ($errorflag eq 'no_score') {
                   2463: 		$ctr++;
                   2464: 		next;
                   2465: 	    }
1.104     albertel 2466: 	    if ($errorflag eq 'not_allowed') {
1.398     albertel 2467: 		$request->print("<span class=\"LC_warning\">Not allowed to modify grades for $uname:$udom</span>");
1.104     albertel 2468: 		$ctr++;
                   2469: 		next;
                   2470: 	    }
1.257     albertel 2471: 	    my $includemsg = $env{'form.includemsg'.$ctr};
1.44      ng       2472: 	    my ($subject,$message,$msgstatus) = ('','','');
1.418     albertel 2473: 	    my $restitle = &Apache::lonnet::gettitle($symb);
                   2474:             my ($feedurl,$showsymb) =
                   2475: 		&get_feedurl_and_symb($symb,$uname,$udom);
                   2476: 	    my $messagetail;
1.62      albertel 2477: 	    if ($includemsg =~ /savemsg|newmsg\Q$ctr\E/) {
1.298     www      2478: 		$subject = $env{'form.msgsub'} if ($includemsg =~ /msgsub/);
1.295     www      2479: 		unless ($subject=~/\w/) { $subject=&mt('Grading Feedback'); }
1.386     raeburn  2480: 		$subject.=' ['.$restitle.']';
1.44      ng       2481: 		my (@msgnum) = split(/,/,$includemsg);
                   2482: 		foreach (@msgnum) {
1.257     albertel 2483: 		    $message.=$env{'form.'.$_} if ($_ =~ /savemsg|newmsg/ && $_ ne '');
1.44      ng       2484: 		}
1.80      ng       2485: 		$message =&Apache::lonfeedback::clear_out_html($message);
1.298     www      2486: 		if ($env{'form.withgrades'.$ctr}) {
                   2487: 		    $message.="\n\nPoint".($pts > 1 ? 's':'').' awarded = '.$pts.' out of '.$wgt;
1.386     raeburn  2488: 		    $messagetail = " for <a href=\"".
1.605     www      2489: 		                   $feedurl."?symb=$showsymb\">$restitle</a>";
1.386     raeburn  2490: 		}
                   2491: 		$msgstatus = 
                   2492:                     &Apache::lonmsg::user_normal_msg($uname,$udom,$subject,
                   2493: 						     $message.$messagetail,
1.418     albertel 2494:                                                      undef,$feedurl,undef,
1.386     raeburn  2495:                                                      undef,undef,$showsymb,
                   2496:                                                      $restitle);
1.574     bisitz   2497: 		$request->print('<br />'.&mt('Sending message to [_1]',$uname.':'.$udom).': '.
1.296     www      2498: 				$msgstatus);
1.44      ng       2499: 	    }
1.257     albertel 2500: 	    if ($env{'form.collaborator'.$ctr}) {
1.155     albertel 2501: 		my @collabstrs=&Apache::loncommon::get_env_multiple("form.collaborator$ctr");
1.150     albertel 2502: 		foreach my $collabstr (@collabstrs) {
                   2503: 		    my ($part,@collaborators) = split(/:/,$collabstr);
1.310     banghart 2504: 		    foreach my $collaborator (@collaborators) {
1.150     albertel 2505: 			my ($errorflag,$pts,$wgt) = 
1.324     albertel 2506: 			    &saveHandGrade($request,$symb,$collaborator,$udom,$ctr,
1.257     albertel 2507: 					   $env{'form.unamedom'.$ctr},$part);
1.150     albertel 2508: 			if ($errorflag eq 'not_allowed') {
1.362     albertel 2509: 			    $request->print("<span class=\"LC_error\">".&mt('Not allowed to modify grades for [_1]',"$collaborator:$udom")."</span>");
1.150     albertel 2510: 			    next;
1.418     albertel 2511: 			} elsif ($message ne '') {
                   2512: 			    my ($baseurl,$showsymb) = 
                   2513: 				&get_feedurl_and_symb($symb,$collaborator,
                   2514: 						      $udom);
                   2515: 			    if ($env{'form.withgrades'.$ctr}) {
                   2516: 				$messagetail = " for <a href=\"".
1.605     www      2517:                                     $baseurl."?symb=$showsymb\">$restitle</a>";
1.150     albertel 2518: 			    }
1.418     albertel 2519: 			    $msgstatus = 
                   2520: 				&Apache::lonmsg::user_normal_msg($collaborator,$udom,$subject,$message.$messagetail,undef,$baseurl,undef,undef,undef,$showsymb,$restitle);
1.104     albertel 2521: 			}
1.44      ng       2522: 		    }
                   2523: 		}
                   2524: 	    }
                   2525: 	    $ctr++;
                   2526: 	}
                   2527:     }
                   2528: 
1.257     albertel 2529:     if ($env{'form.handgrade'} eq 'yes') {
1.119     ng       2530: 	# Keywords sorted in alphabatical order
1.257     albertel 2531: 	my $loginuser = $env{'user.name'}.':'.$env{'user.domain'};
1.119     ng       2532: 	my %keyhash = ();
1.257     albertel 2533: 	$env{'form.keywords'}           =~ s/,\s{0,}|\s+/ /g;
                   2534: 	$env{'form.keywords'}           =~ s/^\s+|\s+$//;
                   2535: 	my (@keywords) = sort(split(/\s+/,$env{'form.keywords'}));
                   2536: 	$env{'form.keywords'} = join(' ',@keywords);
                   2537: 	$keyhash{$symb.'_keywords'}     = $env{'form.keywords'};
                   2538: 	$keyhash{$symb.'_subject'}      = $env{'form.msgsub'};
                   2539: 	$keyhash{$loginuser.'_kwclr'}   = $env{'form.kwclr'};
                   2540: 	$keyhash{$loginuser.'_kwsize'}  = $env{'form.kwsize'};
                   2541: 	$keyhash{$loginuser.'_kwstyle'} = $env{'form.kwstyle'};
1.119     ng       2542: 
                   2543: 	# message center - Order of message gets changed. Blank line is eliminated.
1.257     albertel 2544: 	# New messages are saved in env for the next student.
1.119     ng       2545: 	# All messages are saved in nohist_handgrade.db
                   2546: 	my ($ctr,$idx) = (1,1);
1.257     albertel 2547: 	while ($ctr <= $env{'form.savemsgN'}) {
                   2548: 	    if ($env{'form.savemsg'.$ctr} ne '') {
                   2549: 		$keyhash{$symb.'_savemsg'.$idx} = $env{'form.savemsg'.$ctr};
1.119     ng       2550: 		$idx++;
                   2551: 	    }
                   2552: 	    $ctr++;
1.41      ng       2553: 	}
1.119     ng       2554: 	$ctr = 0;
                   2555: 	while ($ctr < $ngrade) {
1.257     albertel 2556: 	    if ($env{'form.newmsg'.$ctr} ne '') {
                   2557: 		$keyhash{$symb.'_savemsg'.$idx} = $env{'form.newmsg'.$ctr};
                   2558: 		$env{'form.savemsg'.$idx} = $env{'form.newmsg'.$ctr};
1.119     ng       2559: 		$idx++;
                   2560: 	    }
                   2561: 	    $ctr++;
1.41      ng       2562: 	}
1.257     albertel 2563: 	$env{'form.savemsgN'} = --$idx;
                   2564: 	$keyhash{$symb.'_savemsgN'} = $env{'form.savemsgN'};
1.119     ng       2565: 	my $putresult = &Apache::lonnet::put
1.301     albertel 2566: 	    ('nohist_handgrade',\%keyhash,$cdom,$cnum);
1.41      ng       2567:     }
1.44      ng       2568:     # Called by Save & Refresh from Highlight Attribute Window
1.257     albertel 2569:     my (undef,undef,$fullname) = &getclasslist($env{'form.section'},'1');
                   2570:     if ($env{'form.refresh'} eq 'on') {
1.86      ng       2571: 	my ($ctr,$total) = (0,0);
                   2572: 	while ($ctr < $ngrade) {
1.257     albertel 2573: 	    $total++ if  $env{'form.unamedom'.$ctr} ne '';
1.86      ng       2574: 	    $ctr++;
                   2575: 	}
1.257     albertel 2576: 	$env{'form.NTSTU'}=$ngrade;
1.86      ng       2577: 	$ctr = 0;
                   2578: 	while ($ctr < $total) {
1.257     albertel 2579: 	    my $processUser = $env{'form.unamedom'.$ctr};
                   2580: 	    ($env{'form.student'},$env{'form.userdom'}) = split(/:/,$processUser);
                   2581: 	    $env{'form.fullname'} = $$fullname{$processUser};
1.86      ng       2582: 	    &submission($request,$ctr,$total-1);
1.41      ng       2583: 	    $ctr++;
                   2584: 	}
                   2585: 	return '';
                   2586:     }
1.36      ng       2587: 
1.121     ng       2588: # Go directly to grade student - from submission or link from chart page
1.120     ng       2589:     if ($button eq 'Grade Student') {
1.598     www      2590: #	(undef,undef,$env{'form.handgrade'},undef,undef) = &showResourceInfo($symb);
1.257     albertel 2591: 	my $processUser = $env{'form.unamedom'.$env{'form.studentNo'}};
                   2592: 	($env{'form.student'},$env{'form.userdom'}) = split(/:/,$processUser);
                   2593: 	$env{'form.fullname'} = $$fullname{$processUser};
1.120     ng       2594: 	&submission($request,0,0);
                   2595: 	return '';
                   2596:     }
                   2597: 
1.44      ng       2598:     # Get the next/previous one or group of students
1.257     albertel 2599:     my $firststu = $env{'form.unamedom0'};
                   2600:     my $laststu = $env{'form.unamedom'.($ngrade-1)};
1.119     ng       2601:     my $ctr = 2;
1.41      ng       2602:     while ($laststu eq '') {
1.257     albertel 2603: 	$laststu  = $env{'form.unamedom'.($ngrade-$ctr)};
1.41      ng       2604: 	$ctr++;
                   2605: 	$laststu = $firststu if ($ctr > $ngrade);
                   2606:     }
1.44      ng       2607: 
1.41      ng       2608:     my (@parsedlist,@nextlist);
                   2609:     my ($nextflg) = 0;
1.524     raeburn  2610:     foreach my $item (sort 
1.294     albertel 2611: 	     {
                   2612: 		 if (lc($$fullname{$a}) ne lc($$fullname{$b})) {
                   2613: 		     return (lc($$fullname{$a}) cmp lc($$fullname{$b}));
                   2614: 		 }
                   2615: 		 return $a cmp $b;
                   2616: 	     } (keys(%$fullname))) {
1.605     www      2617: # FIXME: this is fishy, looks like the button label
1.41      ng       2618: 	if ($nextflg == 1 && $button =~ /Next$/) {
1.524     raeburn  2619: 	    push(@parsedlist,$item);
1.41      ng       2620: 	}
1.524     raeburn  2621: 	$nextflg = 1 if ($item eq $laststu);
1.41      ng       2622: 	if ($button eq 'Previous') {
1.524     raeburn  2623: 	    last if ($item eq $firststu);
                   2624: 	    push(@parsedlist,$item);
1.41      ng       2625: 	}
                   2626:     }
                   2627:     $ctr = 0;
1.605     www      2628: # FIXME: this is fishy, looks like the button label
1.41      ng       2629:     @parsedlist = reverse @parsedlist if ($button eq 'Previous');
1.582     raeburn  2630:     my $res_error;
                   2631:     my ($partlist) = &response_type($symb,\$res_error);
                   2632:     if ($res_error) {
                   2633:         $request->print(&navmap_errormsg());
                   2634:         return;
                   2635:     }
1.41      ng       2636:     foreach my $student (@parsedlist) {
1.257     albertel 2637: 	my $submitonly=$env{'form.submitonly'};
1.41      ng       2638: 	my ($uname,$udom) = split(/:/,$student);
1.301     albertel 2639: 	
                   2640: 	if ($submitonly eq 'queued') {
                   2641: 	    my %queue_status = 
                   2642: 		&Apache::bridgetask::get_student_status($symb,$cdom,$cnum,
                   2643: 							$udom,$uname);
                   2644: 	    next if (!defined($queue_status{'gradingqueue'}));
                   2645: 	}
                   2646: 
1.156     albertel 2647: 	if ($submitonly =~ /^(yes|graded|incorrect)$/) {
1.257     albertel 2648: #	    my %record = &Apache::lonnet::restore($symb,$env{'request.course.id'},$udom,$uname);
1.324     albertel 2649: 	    my %status=&student_gradeStatus($symb,$udom,$uname,$partlist);
1.145     albertel 2650: 	    my $submitted = 0;
1.248     albertel 2651: 	    my $ungraded = 0;
                   2652: 	    my $incorrect = 0;
1.524     raeburn  2653: 	    foreach my $item (keys(%status)) {
                   2654: 		$submitted = 1 if ($status{$item} ne 'nothing');
                   2655: 		$ungraded = 1 if ($status{$item} =~ /^ungraded/);
                   2656: 		$incorrect = 1 if ($status{$item} =~ /^incorrect/);
                   2657: 		my ($foo,$partid,$foo1) = split(/\./,$item);
1.145     albertel 2658: 		if ($status{'resource.'.$partid.'.submitted_by'} ne '') {
                   2659: 		    $submitted = 0;
                   2660: 		}
1.41      ng       2661: 	    }
1.156     albertel 2662: 	    next if (!$submitted && ($submitonly eq 'yes' ||
                   2663: 				     $submitonly eq 'incorrect' ||
                   2664: 				     $submitonly eq 'graded'));
1.248     albertel 2665: 	    next if (!$ungraded && ($submitonly eq 'graded'));
                   2666: 	    next if (!$incorrect && $submitonly eq 'incorrect');
1.41      ng       2667: 	}
1.524     raeburn  2668: 	push(@nextlist,$student) if ($ctr < $ntstu);
1.129     ng       2669: 	last if ($ctr == $ntstu);
1.41      ng       2670: 	$ctr++;
                   2671:     }
1.36      ng       2672: 
1.41      ng       2673:     $ctr = 0;
                   2674:     my $total = scalar(@nextlist)-1;
1.39      ng       2675: 
1.524     raeburn  2676:     foreach (sort(@nextlist)) {
1.41      ng       2677: 	my ($uname,$udom,$submitter) = split(/:/);
1.257     albertel 2678: 	$env{'form.student'}  = $uname;
                   2679: 	$env{'form.userdom'}  = $udom;
                   2680: 	$env{'form.fullname'} = $$fullname{$_};
1.41      ng       2681: 	&submission($request,$ctr,$total);
                   2682: 	$ctr++;
                   2683:     }
                   2684:     if ($total < 0) {
1.485     albertel 2685: 	my $the_end = '<h3><span class="LC_info">'.&mt('LON-CAPA User Message').'</span></h3><br />'."\n";
                   2686: 	$the_end.=&mt('<b>Message: </b> No more students for this section or class.').'<br /><br />'."\n";
                   2687: 	$the_end.=&mt('Click on the button below to return to the grading menu.').'<br /><br />'."\n";
1.41      ng       2688: 	$request->print($the_end);
                   2689:     }
                   2690:     return '';
1.38      ng       2691: }
1.36      ng       2692: 
1.44      ng       2693: #---- Save the score and award for each student, if changed
1.38      ng       2694: sub saveHandGrade {
1.324     albertel 2695:     my ($request,$symb,$stuname,$domain,$newflg,$submitter,$part) = @_;
1.342     banghart 2696:     my @version_parts;
1.104     albertel 2697:     my $usec = &Apache::lonnet::getsection($domain,$stuname,
1.257     albertel 2698: 					   $env{'request.course.id'});
1.104     albertel 2699:     if (!&canmodify($usec)) { return('not_allowed'); }
1.337     banghart 2700:     my %record = &Apache::lonnet::restore($symb,$env{'request.course.id'},$domain,$stuname);
1.251     banghart 2701:     my @parts_graded;
1.77      ng       2702:     my %newrecord  = ();
                   2703:     my ($pts,$wgt) = ('','');
1.269     raeburn  2704:     my %aggregate = ();
                   2705:     my $aggregateflag = 0;
1.301     albertel 2706:     my @parts = split(/:/,$env{'form.partlist'.$newflg});
                   2707:     foreach my $new_part (@parts) {
1.337     banghart 2708: 	#collaborator ($submi may vary for different parts
1.259     banghart 2709: 	if ($submitter && $new_part ne $part) { next; }
                   2710: 	my $dropMenu = $env{'form.GD_SEL'.$newflg.'_'.$new_part};
1.125     ng       2711: 	if ($dropMenu eq 'excused') {
1.259     banghart 2712: 	    if ($record{'resource.'.$new_part.'.solved'} ne 'excused') {
                   2713: 		$newrecord{'resource.'.$new_part.'.solved'} = 'excused';
                   2714: 		if (exists($record{'resource.'.$new_part.'.awarded'})) {
                   2715: 		    $newrecord{'resource.'.$new_part.'.awarded'} = '';
1.58      albertel 2716: 		}
1.364     banghart 2717: 	        $newrecord{'resource.'.$new_part.'.regrader'}="$env{'user.name'}:$env{'user.domain'}";
1.58      albertel 2718: 	    }
1.125     ng       2719: 	} elsif ($dropMenu eq 'reset status'
1.259     banghart 2720: 		 && exists($record{'resource.'.$new_part.'.solved'})) { #don't bother if no old records -> no attempts
1.524     raeburn  2721: 	    foreach my $key (keys(%record)) {
1.259     banghart 2722: 		if ($key=~/^resource\.\Q$new_part\E\./) { $newrecord{$key} = ''; }
1.197     albertel 2723: 	    }
1.259     banghart 2724: 	    $newrecord{'resource.'.$new_part.'.regrader'}=
1.257     albertel 2725: 		"$env{'user.name'}:$env{'user.domain'}";
1.270     albertel 2726:             my $totaltries = $record{'resource.'.$part.'.tries'};
                   2727: 
                   2728:             my %last_resets = &get_last_resets($symb,$env{'request.course.id'},
                   2729: 					       [$new_part]);
                   2730:             my $aggtries =$totaltries;
1.269     raeburn  2731:             if ($last_resets{$new_part}) {
1.270     albertel 2732:                 $aggtries = &get_num_tries(\%record,$last_resets{$new_part},
                   2733: 					   $new_part);
1.269     raeburn  2734:             }
1.270     albertel 2735: 
                   2736:             my $solvedstatus = $record{'resource.'.$new_part.'.solved'};
1.269     raeburn  2737:             if ($aggtries > 0) {
1.327     albertel 2738:                 &decrement_aggs($symb,$new_part,\%aggregate,$aggtries,$totaltries,$solvedstatus);
1.269     raeburn  2739:                 $aggregateflag = 1;
                   2740:             }
1.125     ng       2741: 	} elsif ($dropMenu eq '') {
1.259     banghart 2742: 	    $pts = ($env{'form.GD_BOX'.$newflg.'_'.$new_part} ne '' ? 
                   2743: 		    $env{'form.GD_BOX'.$newflg.'_'.$new_part} : 
                   2744: 		    $env{'form.RADVAL'.$newflg.'_'.$new_part});
                   2745: 	    if ($pts eq '' && $env{'form.GD_SEL'.$newflg.'_'.$new_part} eq '') {
1.153     albertel 2746: 		next;
                   2747: 	    }
1.259     banghart 2748: 	    $wgt = $env{'form.WGT'.$newflg.'_'.$new_part} eq '' ? 1 : 
                   2749: 		$env{'form.WGT'.$newflg.'_'.$new_part};
1.41      ng       2750: 	    my $partial= $pts/$wgt;
1.259     banghart 2751: 	    if ($partial eq $record{'resource.'.$new_part.'.awarded'}) {
1.153     albertel 2752: 		#do not update score for part if not changed.
1.346     banghart 2753:                 &handback_files($request,$symb,$stuname,$domain,$newflg,$new_part,\%newrecord);
1.153     albertel 2754: 		next;
1.251     banghart 2755: 	    } else {
1.524     raeburn  2756: 	        push(@parts_graded,$new_part);
1.153     albertel 2757: 	    }
1.259     banghart 2758: 	    if ($record{'resource.'.$new_part.'.awarded'} ne $partial) {
                   2759: 		$newrecord{'resource.'.$new_part.'.awarded'}  = $partial;
1.153     albertel 2760: 	    }
1.259     banghart 2761: 	    my $reckey = 'resource.'.$new_part.'.solved';
1.41      ng       2762: 	    if ($partial == 0) {
1.153     albertel 2763: 		if ($record{$reckey} ne 'incorrect_by_override') {
                   2764: 		    $newrecord{$reckey} = 'incorrect_by_override';
                   2765: 		}
1.41      ng       2766: 	    } else {
1.153     albertel 2767: 		if ($record{$reckey} ne 'correct_by_override') {
                   2768: 		    $newrecord{$reckey} = 'correct_by_override';
                   2769: 		}
                   2770: 	    }	    
                   2771: 	    if ($submitter && 
1.259     banghart 2772: 		($record{'resource.'.$new_part.'.submitted_by'} ne $submitter)) {
                   2773: 		$newrecord{'resource.'.$new_part.'.submitted_by'} = $submitter;
1.41      ng       2774: 	    }
1.259     banghart 2775: 	    $newrecord{'resource.'.$new_part.'.regrader'}=
1.257     albertel 2776: 		"$env{'user.name'}:$env{'user.domain'}";
1.41      ng       2777: 	}
1.259     banghart 2778: 	# unless problem has been graded, set flag to version the submitted files
1.305     banghart 2779: 	unless ($record{'resource.'.$new_part.'.solved'} =~ /^correct_/  || 
                   2780: 	        $record{'resource.'.$new_part.'.solved'} eq 'incorrect_by_override' ||
                   2781: 	        $dropMenu eq 'reset status')
                   2782: 	   {
1.524     raeburn  2783: 	    push(@version_parts,$new_part);
1.259     banghart 2784: 	}
1.41      ng       2785:     }
1.301     albertel 2786:     my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   2787:     my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   2788: 
1.344     albertel 2789:     if (%newrecord) {
                   2790:         if (@version_parts) {
1.364     banghart 2791:             my @changed_keys = &version_portfiles(\%record, \@parts_graded, 
                   2792:                                 $env{'request.course.id'}, $symb, $domain, $stuname, \@version_parts);
1.344     albertel 2793: 	    @newrecord{@changed_keys} = @record{@changed_keys};
1.367     albertel 2794: 	    foreach my $new_part (@version_parts) {
                   2795: 		&handback_files($request,$symb,$stuname,$domain,$newflg,
                   2796: 				$new_part,\%newrecord);
                   2797: 	    }
1.259     banghart 2798:         }
1.44      ng       2799: 	&Apache::lonnet::cstore(\%newrecord,$symb,
1.257     albertel 2800: 				$env{'request.course.id'},$domain,$stuname);
1.380     albertel 2801: 	&check_and_remove_from_queue(\@parts,\%record,\%newrecord,$symb,
                   2802: 				     $cdom,$cnum,$domain,$stuname);
1.41      ng       2803:     }
1.269     raeburn  2804:     if ($aggregateflag) {
                   2805:         &Apache::lonnet::cinc('nohist_resourcetracker',\%aggregate,
1.301     albertel 2806: 			      $cdom,$cnum);
1.269     raeburn  2807:     }
1.301     albertel 2808:     return ('',$pts,$wgt);
1.36      ng       2809: }
1.322     albertel 2810: 
1.380     albertel 2811: sub check_and_remove_from_queue {
                   2812:     my ($parts,$record,$newrecord,$symb,$cdom,$cnum,$domain,$stuname) = @_;
                   2813:     my @ungraded_parts;
                   2814:     foreach my $part (@{$parts}) {
                   2815: 	if (    $record->{   'resource.'.$part.'.awarded'} eq ''
                   2816: 	     && $record->{   'resource.'.$part.'.solved' } ne 'excused'
                   2817: 	     && $newrecord->{'resource.'.$part.'.awarded'} eq ''
                   2818: 	     && $newrecord->{'resource.'.$part.'.solved' } ne 'excused'
                   2819: 		) {
                   2820: 	    push(@ungraded_parts, $part);
                   2821: 	}
                   2822:     }
                   2823:     if ( !@ungraded_parts ) {
                   2824: 	&Apache::bridgetask::remove_from_queue('gradingqueue',$symb,$cdom,
                   2825: 					       $cnum,$domain,$stuname);
                   2826:     }
                   2827: }
                   2828: 
1.337     banghart 2829: sub handback_files {
                   2830:     my ($request,$symb,$stuname,$domain,$newflg,$new_part,$newrecord) = @_;
1.517     raeburn  2831:     my $portfolio_root = '/userfiles/portfolio';
1.582     raeburn  2832:     my $res_error;
                   2833:     my ($partlist,$handgrade,$responseType) = &response_type($symb,\$res_error);
                   2834:     if ($res_error) {
                   2835:         $request->print('<br />'.&navmap_errormsg().'<br />');
                   2836:         return;
                   2837:     }
1.375     albertel 2838:     my @part_response_id = &flatten_responseType($responseType);
                   2839:     foreach my $part_response_id (@part_response_id) {
                   2840:     	my ($part_id,$resp_id) = @{ $part_response_id };
                   2841: 	my $part_resp = join('_',@{ $part_response_id });
1.337     banghart 2842:             if (($env{'form.'.$newflg.'_'.$part_resp.'_returndoc1'}) && ($new_part == $part_id)) {
                   2843:                 # if multiple files are uploaded names will be 'returndoc2','returndoc3'
                   2844:                 my $file_counter = 1;
1.367     albertel 2845: 		my $file_msg;
1.337     banghart 2846:                 while ($env{'form.'.$newflg.'_'.$part_resp.'_returndoc'.$file_counter}) {
                   2847:                     my $fname=$env{'form.'.$newflg.'_'.$part_resp.'_returndoc'.$file_counter.'.filename'};
1.338     banghart 2848:                     my ($directory,$answer_file) = 
                   2849:                         ($env{'form.'.$newflg.'_'.$part_resp.'_origdoc'.$file_counter} =~ /^(.*?)([^\/]*)$/);
                   2850:                     my ($answer_name,$answer_ver,$answer_ext) =
                   2851: 		        &file_name_version_ext($answer_file);
1.355     banghart 2852: 		    my ($portfolio_path) = ($directory =~ /^.+$stuname\/portfolio(.*)/);
1.517     raeburn  2853:                     my $getpropath = 1;
                   2854: 		    my @dir_list = &Apache::lonnet::dirlist($portfolio_root.$portfolio_path,$domain,$stuname,$getpropath);
1.338     banghart 2855: 		    my $version = &get_next_version($answer_name, $answer_ext, \@dir_list);
1.355     banghart 2856:                     # fix file name
                   2857:                     my ($save_file_name) = (($directory.$answer_name.".$version.".$answer_ext) =~ /^.+\/${stuname}\/(.*)/);
                   2858:                     my $result=&Apache::lonnet::finishuserfileupload($stuname,$domain,
                   2859:             	                                $newflg.'_'.$part_resp.'_returndoc'.$file_counter,
                   2860:             	                                $save_file_name);
1.337     banghart 2861:                     if ($result !~ m|^/uploaded/|) {
1.536     raeburn  2862:                         $request->print('<br /><span class="LC_error">'.
                   2863:                             &mt('An error occurred ([_1]) while trying to upload [_2].',
                   2864:                                 $result,$newflg.'_'.$part_resp.'_returndoc'.$file_counter).
                   2865:                                         '</span>');
1.356     banghart 2866:                     } else {
1.360     banghart 2867:                         # mark the file as read only
                   2868:                         my @files = ($save_file_name);
1.372     albertel 2869:                         my @what = ($symb,$env{'request.course.id'},'handback');
1.360     banghart 2870:                         &Apache::lonnet::mark_as_readonly($domain,$stuname,\@files,\@what);
1.367     albertel 2871: 			if (exists($$newrecord{"resource.$new_part.$resp_id.handback"})) {
                   2872: 			    $$newrecord{"resource.$new_part.$resp_id.handback"}.=',';
                   2873: 			}
                   2874:                         $$newrecord{"resource.$new_part.$resp_id.handback"} .= $save_file_name;
                   2875: 			$file_msg.= "\n".'<br /><span class="LC_filename"><a href="/uploaded/'."$domain/$stuname/".$save_file_name.'">'.$save_file_name."</a></span><br />";
                   2876: 
1.337     banghart 2877:                     }
                   2878:                     $request->print("<br />".$fname." will be the uploaded file name");
1.354     albertel 2879:                     $request->print(" ".$env{'form.'.$newflg.'_'.$part_resp.'_origdoc'.$file_counter});
1.337     banghart 2880:                     $file_counter++;
                   2881:                 }
1.367     albertel 2882: 		my $subject = "File Handed Back by Instructor ";
                   2883: 		my $message = "A file has been returned that was originally submitted in reponse to: <br />";
                   2884: 		$message .= "<strong>".&Apache::lonnet::gettitle($symb)."</strong><br />";
                   2885: 		$message .= ' The returned file(s) are named: '. $file_msg;
                   2886: 		$message .= " and can be found in your portfolio space.";
1.418     albertel 2887: 		my ($feedurl,$showsymb) = 
                   2888: 		    &get_feedurl_and_symb($symb,$domain,$stuname);
1.386     raeburn  2889:                 my $restitle = &Apache::lonnet::gettitle($symb);
                   2890: 		my $msgstatus = 
                   2891:                    &Apache::lonmsg::user_normal_msg($stuname,$domain,$subject.
                   2892: 			 ' (File Returned) ['.$restitle.']',$message,undef,
1.418     albertel 2893:                          $feedurl,undef,undef,undef,$showsymb,$restitle);
1.337     banghart 2894:             }
                   2895:         }
1.338     banghart 2896:     return;
1.337     banghart 2897: }
                   2898: 
1.418     albertel 2899: sub get_feedurl_and_symb {
                   2900:     my ($symb,$uname,$udom) = @_;
                   2901:     my (undef,undef,$url) = &Apache::lonnet::decode_symb($symb);
                   2902:     $url = &Apache::lonnet::clutter($url);
                   2903:     my $encrypturl=&Apache::lonnet::EXT('resource.0.encrypturl',
                   2904: 					$symb,$udom,$uname);
                   2905:     if ($encrypturl =~ /^yes$/i) {
                   2906: 	&Apache::lonenc::encrypted(\$url,1);
                   2907: 	&Apache::lonenc::encrypted(\$symb,1);
                   2908:     }
                   2909:     return ($url,$symb);
                   2910: }
                   2911: 
1.313     banghart 2912: sub get_submitted_files {
                   2913:     my ($udom,$uname,$partid,$respid,$record) = @_;
                   2914:     my @files;
                   2915:     if ($$record{"resource.$partid.$respid.portfiles"}) {
                   2916:         my $file_url = '/uploaded/'.$udom.'/'.$uname.'/portfolio';
                   2917:         foreach my $file (split(',',$$record{"resource.$partid.$respid.portfiles"})) {
                   2918:     	    push(@files,$file_url.$file);
                   2919:         }
                   2920:     }
                   2921:     if ($$record{"resource.$partid.$respid.uploadedurl"}) {
                   2922:         push(@files,$$record{"resource.$partid.$respid.uploadedurl"});
                   2923:     }
                   2924:     return (\@files);
                   2925: }
1.322     albertel 2926: 
1.269     raeburn  2927: # ----------- Provides number of tries since last reset.
                   2928: sub get_num_tries {
                   2929:     my ($record,$last_reset,$part) = @_;
                   2930:     my $timestamp = '';
                   2931:     my $num_tries = 0;
                   2932:     if ($$record{'version'}) {
                   2933:         for (my $version=$$record{'version'};$version>=1;$version--) {
                   2934:             if (exists($$record{$version.':resource.'.$part.'.solved'})) {
                   2935:                 $timestamp = $$record{$version.':timestamp'};
                   2936:                 if ($timestamp > $last_reset) {
                   2937:                     $num_tries ++;
                   2938:                 } else {
                   2939:                     last;
                   2940:                 }
                   2941:             }
                   2942:         }
                   2943:     }
                   2944:     return $num_tries;
                   2945: }
                   2946: 
                   2947: # ----------- Determine decrements required in aggregate totals 
                   2948: sub decrement_aggs {
                   2949:     my ($symb,$part,$aggregate,$aggtries,$totaltries,$solvedstatus) = @_;
                   2950:     my %decrement = (
                   2951:                         attempts => 0,
                   2952:                         users => 0,
                   2953:                         correct => 0
                   2954:                     );
                   2955:     $decrement{'attempts'} = $aggtries;
                   2956:     if ($solvedstatus =~ /^correct/) {
                   2957:         $decrement{'correct'} = 1;
                   2958:     }
                   2959:     if ($aggtries == $totaltries) {
                   2960:         $decrement{'users'} = 1;
                   2961:     }
1.524     raeburn  2962:     foreach my $type (keys(%decrement)) {
1.269     raeburn  2963:         $$aggregate{$symb."\0".$part."\0".$type} = -$decrement{$type};
                   2964:     }
                   2965:     return;
                   2966: }
                   2967: 
                   2968: # ----------- Determine timestamps for last reset of aggregate totals for parts  
                   2969: sub get_last_resets {
1.270     albertel 2970:     my ($symb,$courseid,$partids) =@_;
                   2971:     my %last_resets;
1.269     raeburn  2972:     my $cdom = $env{'course.'.$courseid.'.domain'};
                   2973:     my $cname = $env{'course.'.$courseid.'.num'};
1.271     albertel 2974:     my @keys;
                   2975:     foreach my $part (@{$partids}) {
                   2976: 	push(@keys,"$symb\0$part\0resettime");
                   2977:     }
                   2978:     my %results=&Apache::lonnet::get('nohist_resourcetracker',\@keys,
                   2979: 				     $cdom,$cname);
                   2980:     foreach my $part (@{$partids}) {
                   2981: 	$last_resets{$part}=$results{"$symb\0$part\0resettime"};
1.269     raeburn  2982:     }
1.270     albertel 2983:     return %last_resets;
1.269     raeburn  2984: }
                   2985: 
1.251     banghart 2986: # ----------- Handles creating versions for portfolio files as answers
                   2987: sub version_portfiles {
1.343     banghart 2988:     my ($record, $parts_graded, $courseid, $symb, $domain, $stu_name, $v_flag) = @_;
1.263     banghart 2989:     my $version_parts = join('|',@$v_flag);
1.343     banghart 2990:     my @returned_keys;
1.255     banghart 2991:     my $parts = join('|', @$parts_graded);
1.517     raeburn  2992:     my $portfolio_root = '/userfiles/portfolio';
1.277     albertel 2993:     foreach my $key (keys(%$record)) {
1.259     banghart 2994:         my $new_portfiles;
1.263     banghart 2995:         if ($key =~ /^resource\.($version_parts)\./ && $key =~ /\.portfiles$/ ) {
1.342     banghart 2996:             my @versioned_portfiles;
1.367     albertel 2997:             my @portfiles = split(/\s*,\s*/,$$record{$key});
1.252     banghart 2998:             foreach my $file (@portfiles) {
1.306     banghart 2999:                 &Apache::lonnet::unmark_as_readonly($domain,$stu_name,[$symb,$env{'request.course.id'}],$file);
1.304     albertel 3000:                 my ($directory,$answer_file) =($file =~ /^(.*?)([^\/]*)$/);
                   3001: 		my ($answer_name,$answer_ver,$answer_ext) =
                   3002: 		    &file_name_version_ext($answer_file);
1.517     raeburn  3003:                 my $getpropath = 1;    
                   3004:                 my @dir_list = &Apache::lonnet::dirlist($portfolio_root.$directory,$domain,$stu_name,$getpropath);
1.342     banghart 3005:                 my $version = &get_next_version($answer_name, $answer_ext, \@dir_list);
1.306     banghart 3006:                 my $new_answer = &version_selected_portfile($domain, $stu_name, $directory, $answer_file, $version);
                   3007:                 if ($new_answer ne 'problem getting file') {
1.342     banghart 3008:                     push(@versioned_portfiles, $directory.$new_answer);
1.306     banghart 3009:                     &Apache::lonnet::mark_as_readonly($domain,$stu_name,
1.367     albertel 3010:                         [$directory.$new_answer],
1.306     banghart 3011:                         [$symb,$env{'request.course.id'},'graded']);
1.259     banghart 3012:                 }
1.252     banghart 3013:             }
1.343     banghart 3014:             $$record{$key} = join(',',@versioned_portfiles);
                   3015:             push(@returned_keys,$key);
1.251     banghart 3016:         }
                   3017:     } 
1.343     banghart 3018:     return (@returned_keys);   
1.305     banghart 3019: }
                   3020: 
1.307     banghart 3021: sub get_next_version {
1.341     banghart 3022:     my ($answer_name, $answer_ext, $dir_list) = @_;
1.307     banghart 3023:     my $version;
                   3024:     foreach my $row (@$dir_list) {
                   3025:         my ($file) = split(/\&/,$row,2);
                   3026:         my ($file_name,$file_version,$file_ext) =
                   3027: 	    &file_name_version_ext($file);
                   3028:         if (($file_name eq $answer_name) && 
                   3029: 	    ($file_ext eq $answer_ext)) {
                   3030:                 # gets here if filename and extension match, regardless of version
                   3031:                 if ($file_version ne '') {
                   3032:                 # a versioned file is found  so save it for later
                   3033:                 if ($file_version > $version) {
                   3034: 		    $version = $file_version;
                   3035: 	        }
                   3036:             }
                   3037:         }
                   3038:     } 
                   3039:     $version ++;
                   3040:     return($version);
                   3041: }
                   3042: 
1.305     banghart 3043: sub version_selected_portfile {
1.306     banghart 3044:     my ($domain,$stu_name,$directory,$file_name,$version) = @_;
                   3045:     my ($answer_name,$answer_ver,$answer_ext) =
                   3046:         &file_name_version_ext($file_name);
                   3047:     my $new_answer;
                   3048:     $env{'form.copy'} = &Apache::lonnet::getfile("/uploaded/$domain/$stu_name/portfolio$directory$file_name");
                   3049:     if($env{'form.copy'} eq '-1') {
                   3050:         $new_answer = 'problem getting file';
                   3051:     } else {
                   3052:         $new_answer = $answer_name.'.'.$version.'.'.$answer_ext;
                   3053:         my $copy_result = &Apache::lonnet::finishuserfileupload(
                   3054:                             $stu_name,$domain,'copy',
                   3055: 		        '/portfolio'.$directory.$new_answer);
                   3056:     }    
                   3057:     return ($new_answer);
1.251     banghart 3058: }
                   3059: 
1.304     albertel 3060: sub file_name_version_ext {
                   3061:     my ($file)=@_;
                   3062:     my @file_parts = split(/\./, $file);
                   3063:     my ($name,$version,$ext);
                   3064:     if (@file_parts > 1) {
                   3065: 	$ext=pop(@file_parts);
                   3066: 	if (@file_parts > 1 && $file_parts[-1] =~ /^\d+$/) {
                   3067: 	    $version=pop(@file_parts);
                   3068: 	}
                   3069: 	$name=join('.',@file_parts);
                   3070:     } else {
                   3071: 	$name=join('.',@file_parts);
                   3072:     }
                   3073:     return($name,$version,$ext);
                   3074: }
                   3075: 
1.44      ng       3076: #--------------------------------------------------------------------------------------
                   3077: #
                   3078: #-------------------------- Next few routines handles grading by section or whole class
                   3079: #
                   3080: #--- Javascript to handle grading by section or whole class
1.42      ng       3081: sub viewgrades_js {
                   3082:     my ($request) = shift;
                   3083: 
1.539     riegler  3084:     my $alertmsg = &mt('A number equal or greater than 0 is expected. Entered value = ');
1.597     wenzelju 3085:     $request->print(&Apache::lonhtmlcommon::scripttag(<<VIEWJAVASCRIPT));
1.45      ng       3086:    function writePoint(partid,weight,point) {
1.125     ng       3087: 	var radioButton = document.classgrade["RADVAL_"+partid];
                   3088: 	var textbox = document.classgrade["TEXTVAL_"+partid];
1.42      ng       3089: 	if (point == "textval") {
1.125     ng       3090: 	    point = document.classgrade["TEXTVAL_"+partid].value;
1.109     matthew  3091: 	    if (isNaN(point) || parseFloat(point) < 0) {
1.539     riegler  3092: 		alert("$alertmsg"+parseFloat(point));
1.42      ng       3093: 		var resetbox = false;
                   3094: 		for (var i=0; i<radioButton.length; i++) {
                   3095: 		    if (radioButton[i].checked) {
                   3096: 			textbox.value = i;
                   3097: 			resetbox = true;
                   3098: 		    }
                   3099: 		}
                   3100: 		if (!resetbox) {
                   3101: 		    textbox.value = "";
                   3102: 		}
                   3103: 		return;
                   3104: 	    }
1.109     matthew  3105: 	    if (parseFloat(point) > parseFloat(weight)) {
                   3106: 		var resp = confirm("You entered a value ("+parseFloat(point)+
1.44      ng       3107: 				   ") greater than the weight for the part. Accept?");
                   3108: 		if (resp == false) {
                   3109: 		    textbox.value = "";
                   3110: 		    return;
                   3111: 		}
                   3112: 	    }
1.42      ng       3113: 	    for (var i=0; i<radioButton.length; i++) {
                   3114: 		radioButton[i].checked=false;
1.109     matthew  3115: 		if (parseFloat(point) == i) {
1.42      ng       3116: 		    radioButton[i].checked=true;
                   3117: 		}
                   3118: 	    }
1.41      ng       3119: 
1.42      ng       3120: 	} else {
1.125     ng       3121: 	    textbox.value = parseFloat(point);
1.42      ng       3122: 	}
1.41      ng       3123: 	for (i=0;i<document.classgrade.total.value;i++) {
1.125     ng       3124: 	    var user = document.classgrade["ctr"+i].value;
1.289     albertel 3125: 	    user = user.replace(new RegExp(':', 'g'),"_");
1.125     ng       3126: 	    var scorename = document.classgrade["GD_"+user+"_"+partid+"_awarded"];
                   3127: 	    var saveval   = document.classgrade["GD_"+user+"_"+partid+"_solved_s"].value;
                   3128: 	    var selname   = document.classgrade["GD_"+user+"_"+partid+"_solved"];
1.42      ng       3129: 	    if (saveval != "correct") {
                   3130: 		scorename.value = point;
1.43      ng       3131: 		if (selname[0].selected != true) {
                   3132: 		    selname[0].selected = true;
                   3133: 		}
1.42      ng       3134: 	    }
                   3135: 	}
1.125     ng       3136: 	document.classgrade["SELVAL_"+partid][0].selected = true;
1.42      ng       3137:     }
                   3138: 
                   3139:     function writeRadText(partid,weight) {
1.125     ng       3140: 	var selval   = document.classgrade["SELVAL_"+partid];
                   3141: 	var radioButton = document.classgrade["RADVAL_"+partid];
1.265     www      3142:         var override = document.classgrade["FORCE_"+partid].checked;
1.125     ng       3143: 	var textbox = document.classgrade["TEXTVAL_"+partid];
                   3144: 	if (selval[1].selected || selval[2].selected) {
1.42      ng       3145: 	    for (var i=0; i<radioButton.length; i++) {
                   3146: 		radioButton[i].checked=false;
                   3147: 
                   3148: 	    }
                   3149: 	    textbox.value = "";
                   3150: 
                   3151: 	    for (i=0;i<document.classgrade.total.value;i++) {
1.125     ng       3152: 		var user = document.classgrade["ctr"+i].value;
1.289     albertel 3153: 		user = user.replace(new RegExp(':', 'g'),"_");
1.125     ng       3154: 		var scorename = document.classgrade["GD_"+user+"_"+partid+"_awarded"];
                   3155: 		var saveval   = document.classgrade["GD_"+user+"_"+partid+"_solved_s"].value;
                   3156: 		var selname   = document.classgrade["GD_"+user+"_"+partid+"_solved"];
1.265     www      3157: 		if ((saveval != "correct") || override) {
1.42      ng       3158: 		    scorename.value = "";
1.125     ng       3159: 		    if (selval[1].selected) {
                   3160: 			selname[1].selected = true;
                   3161: 		    } else {
                   3162: 			selname[2].selected = true;
                   3163: 			if (Number(document.classgrade["GD_"+user+"_"+partid+"_tries"].value)) 
                   3164: 			{document.classgrade["GD_"+user+"_"+partid+"_tries"].value = '0';}
                   3165: 		    }
1.42      ng       3166: 		}
                   3167: 	    }
1.43      ng       3168: 	} else {
                   3169: 	    for (i=0;i<document.classgrade.total.value;i++) {
1.125     ng       3170: 		var user = document.classgrade["ctr"+i].value;
1.289     albertel 3171: 		user = user.replace(new RegExp(':', 'g'),"_");
1.125     ng       3172: 		var scorename = document.classgrade["GD_"+user+"_"+partid+"_awarded"];
                   3173: 		var saveval   = document.classgrade["GD_"+user+"_"+partid+"_solved_s"].value;
                   3174: 		var selname   = document.classgrade["GD_"+user+"_"+partid+"_solved"];
1.265     www      3175: 		if ((saveval != "correct") || override) {
1.125     ng       3176: 		    scorename.value = document.classgrade["GD_"+user+"_"+partid+"_awarded_s"].value;
1.43      ng       3177: 		    selname[0].selected = true;
                   3178: 		}
                   3179: 	    }
                   3180: 	}	    
1.42      ng       3181:     }
                   3182: 
                   3183:     function changeSelect(partid,user) {
1.125     ng       3184: 	var selval = document.classgrade["GD_"+user+'_'+partid+"_solved"];
                   3185: 	var textbox = document.classgrade["GD_"+user+'_'+partid+"_awarded"];
1.44      ng       3186: 	var point  = textbox.value;
1.125     ng       3187: 	var weight = document.classgrade["weight_"+partid].value;
1.44      ng       3188: 
1.109     matthew  3189: 	if (isNaN(point) || parseFloat(point) < 0) {
1.539     riegler  3190: 	    alert("$alertmsg"+parseFloat(point));
1.44      ng       3191: 	    textbox.value = "";
                   3192: 	    return;
                   3193: 	}
1.109     matthew  3194: 	if (parseFloat(point) > parseFloat(weight)) {
                   3195: 	    var resp = confirm("You entered a value ("+parseFloat(point)+
1.44      ng       3196: 			       ") greater than the weight of the part. Accept?");
                   3197: 	    if (resp == false) {
                   3198: 		textbox.value = "";
                   3199: 		return;
                   3200: 	    }
                   3201: 	}
1.42      ng       3202: 	selval[0].selected = true;
                   3203:     }
                   3204: 
                   3205:     function changeOneScore(partid,user) {
1.125     ng       3206: 	var selval = document.classgrade["GD_"+user+'_'+partid+"_solved"];
                   3207: 	if (selval[1].selected || selval[2].selected) {
                   3208: 	    document.classgrade["GD_"+user+'_'+partid+"_awarded"].value = "";
                   3209: 	    if (selval[2].selected) {
                   3210: 		document.classgrade["GD_"+user+'_'+partid+"_tries"].value = "0";
                   3211: 	    }
1.269     raeburn  3212:         }
1.42      ng       3213:     }
                   3214: 
                   3215:     function resetEntry(numpart) {
                   3216: 	for (ctpart=0;ctpart<numpart;ctpart++) {
1.125     ng       3217: 	    var partid = document.classgrade["partid_"+ctpart].value;
                   3218: 	    var radioButton = document.classgrade["RADVAL_"+partid];
                   3219: 	    var textbox = document.classgrade["TEXTVAL_"+partid];
                   3220: 	    var selval  = document.classgrade["SELVAL_"+partid];
1.42      ng       3221: 	    for (var i=0; i<radioButton.length; i++) {
                   3222: 		radioButton[i].checked=false;
                   3223: 
                   3224: 	    }
                   3225: 	    textbox.value = "";
                   3226: 	    selval[0].selected = true;
                   3227: 
                   3228: 	    for (i=0;i<document.classgrade.total.value;i++) {
1.125     ng       3229: 		var user = document.classgrade["ctr"+i].value;
1.289     albertel 3230: 		user = user.replace(new RegExp(':', 'g'),"_");
1.125     ng       3231: 		var resetscore = document.classgrade["GD_"+user+"_"+partid+"_awarded"];
                   3232: 		resetscore.value = document.classgrade["GD_"+user+"_"+partid+"_awarded_s"].value;
                   3233: 		var resettries = document.classgrade["GD_"+user+"_"+partid+"_tries"];
                   3234: 		resettries.value = document.classgrade["GD_"+user+"_"+partid+"_tries_s"].value;
                   3235: 		var saveselval   = document.classgrade["GD_"+user+"_"+partid+"_solved_s"].value;
                   3236: 		var selname   = document.classgrade["GD_"+user+"_"+partid+"_solved"];
1.42      ng       3237: 		if (saveselval == "excused") {
1.43      ng       3238: 		    if (selname[1].selected == false) { selname[1].selected = true;}
1.42      ng       3239: 		} else {
1.43      ng       3240: 		    if (selname[0].selected == false) {selname[0].selected = true};
1.42      ng       3241: 		}
                   3242: 	    }
1.41      ng       3243: 	}
1.42      ng       3244:     }
                   3245: 
1.41      ng       3246: VIEWJAVASCRIPT
1.42      ng       3247: }
                   3248: 
1.44      ng       3249: #--- show scores for a section or whole class w/ option to change/update a score
1.42      ng       3250: sub viewgrades {
1.608     www      3251:     my ($request,$symb) = @_;
1.42      ng       3252:     &viewgrades_js($request);
1.41      ng       3253: 
1.168     albertel 3254:     #need to make sure we have the correct data for later EXT calls, 
                   3255:     #thus invalidate the cache
                   3256:     &Apache::lonnet::devalidatecourseresdata(
1.257     albertel 3257:                  $env{'course.'.$env{'request.course.id'}.'.num'},
                   3258:                  $env{'course.'.$env{'request.course.id'}.'.domain'});
1.168     albertel 3259:     &Apache::lonnet::clear_EXT_cache_status();
                   3260: 
1.398     albertel 3261:     my $result='<h3><span class="LC_info">'.&mt('Manual Grading').'</span></h3>';
1.41      ng       3262: 
                   3263:     #view individual student submission form - called using Javascript viewOneStudent
1.324     albertel 3264:     $result.=&jscriptNform($symb);
1.41      ng       3265: 
1.44      ng       3266:     #beginning of class grading form
1.442     banghart 3267:     my $stu_status = join(':',&Apache::loncommon::get_env_multiple('form.Status'));
1.41      ng       3268:     $result.= '<form action="/adm/grades" method="post" name="classgrade">'."\n".
1.418     albertel 3269: 	'<input type="hidden" name="symb"    value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
1.38      ng       3270: 	'<input type="hidden" name="command" value="editgrades" />'."\n".
1.432     banghart 3271: 	&build_section_inputs().
1.442     banghart 3272: 	'<input type="hidden" name="Status" value="'.$env{'stu_status'}.'" />'."\n".
1.72      ng       3273: 
1.560     raeburn  3274:     my ($common_header,$specific_header);
1.257     albertel 3275:     if ($env{'form.section'} eq 'all') {
1.560     raeburn  3276: 	$common_header = &mt('Assign Common Grade to Class');
                   3277:         $specific_header = &mt('Assign Grade to Specific Students in Class');
1.257     albertel 3278:     } elsif ($env{'form.section'} eq 'none') {
1.560     raeburn  3279:         $common_header = &mt('Assign Common Grade to Students in no Section');
                   3280: 	$specific_header = &mt('Assign Grade to Specific Students in no Section');
1.52      albertel 3281:     } else {
1.560     raeburn  3282:         my $section_display = join (", ",&Apache::loncommon::get_env_multiple('form.section'));
                   3283:         $common_header = &mt('Assign Common Grade to Students in Section(s) [_1]',$section_display);
                   3284: 	$specific_header = &mt('Assign Grade to Specific Students in Section(s) [_1]',$section_display);
1.52      albertel 3285:     }
1.560     raeburn  3286:     $result.= '<h3>'.$common_header.'</h3>'.&Apache::loncommon::start_data_table();
1.44      ng       3287:     #radio buttons/text box for assigning points for a section or class.
                   3288:     #handles different parts of a problem
1.582     raeburn  3289:     my $res_error;
                   3290:     my ($partlist,$handgrade,$responseType) = &response_type($symb,\$res_error);
                   3291:     if ($res_error) {
                   3292:         return &navmap_errormsg();
                   3293:     }
1.42      ng       3294:     my %weight = ();
                   3295:     my $ctsparts = 0;
1.45      ng       3296:     my %seen = ();
1.375     albertel 3297:     my @part_response_id = &flatten_responseType($responseType);
                   3298:     foreach my $part_response_id (@part_response_id) {
                   3299:     	my ($partid,$respid) = @{ $part_response_id };
                   3300: 	my $part_resp = join('_',@{ $part_response_id });
1.45      ng       3301: 	next if $seen{$partid};
                   3302: 	$seen{$partid}++;
1.375     albertel 3303: 	my $handgrade=$$handgrade{$part_resp};
1.42      ng       3304: 	my $wgt = &Apache::lonnet::EXT('resource.'.$partid.'.weight',$symb);
                   3305: 	$weight{$partid} = $wgt eq '' ? '1' : $wgt;
                   3306: 
1.324     albertel 3307: 	my $display_part=&get_display_part($partid,$symb);
1.485     albertel 3308: 	my $radio.='<table border="0"><tr>';  
1.41      ng       3309: 	my $ctr = 0;
1.42      ng       3310: 	while ($ctr<=$weight{$partid}) { # display radio buttons in a nice table 10 across
1.485     albertel 3311: 	    $radio.= '<td><label><input type="radio" name="RADVAL_'.$partid.'" '.
1.54      albertel 3312: 		'onclick="javascript:writePoint(\''.$partid.'\','.$weight{$partid}.
1.288     albertel 3313: 		','.$ctr.')" />'.$ctr."</label></td>\n";
1.41      ng       3314: 	    $result.=(($ctr+1)%10 == 0 ? '</tr><tr>' : '');
                   3315: 	    $ctr++;
                   3316: 	}
1.485     albertel 3317: 	$radio.='</tr></table>';
                   3318: 	my $line = '<input type="text" name="TEXTVAL_'.
1.589     bisitz   3319: 	    $partid.'" size="4" '.'onchange="javascript:writePoint(\''.
1.54      albertel 3320: 		$partid.'\','.$weight{$partid}.',\'textval\')" /> /'.
1.539     riegler  3321: 	    $weight{$partid}.' '.&mt('(problem weight)').'</td>'."\n";
                   3322: 	$line.= '<td><b>'.&mt('Grade Status').':</b><select name="SELVAL_'.$partid.'"'.
1.589     bisitz   3323: 	    'onchange="javascript:writeRadText(\''.$partid.'\','.
1.59      albertel 3324: 		$weight{$partid}.')"> '.
1.401     albertel 3325: 	    '<option selected="selected"> </option>'.
1.485     albertel 3326: 	    '<option value="excused">'.&mt('excused').'</option>'.
                   3327: 	    '<option value="reset status">'.&mt('reset status').'</option>'.
                   3328: 	    '</select></td>'.
                   3329:             '<td><label><input type="checkbox" name="FORCE_'.$partid.'" />'.&mt('Override "Correct"').'</label>';
                   3330: 	$line.='<input type="hidden" name="partid_'.
                   3331: 	    $ctsparts.'" value="'.$partid.'" />'."\n";
                   3332: 	$line.='<input type="hidden" name="weight_'.
                   3333: 	    $partid.'" value="'.$weight{$partid}.'" />'."\n";
                   3334: 
                   3335: 	$result.=
                   3336: 	    &Apache::loncommon::start_data_table_row()."\n".
1.577     bisitz   3337: 	    '<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 3338: 	    &Apache::loncommon::end_data_table_row()."\n";
1.42      ng       3339: 	$ctsparts++;
1.41      ng       3340:     }
1.474     albertel 3341:     $result.=&Apache::loncommon::end_data_table()."\n".
1.52      albertel 3342: 	'<input type="hidden" name="totalparts" value="'.$ctsparts.'" />';
1.485     albertel 3343:     $result.='<input type="button" value="'.&mt('Revert to Default').'" '.
1.589     bisitz   3344: 	'onclick="javascript:resetEntry('.$ctsparts.');" />';
1.41      ng       3345: 
1.44      ng       3346:     #table listing all the students in a section/class
                   3347:     #header of table
1.560     raeburn  3348:     $result.= '<h3>'.$specific_header.'</h3>'.
                   3349:               &Apache::loncommon::start_data_table().
                   3350: 	      &Apache::loncommon::start_data_table_header_row().
                   3351: 	      '<th>'.&mt('No.').'</th>'.
                   3352: 	      '<th>'.&nameUserString('header')."</th>\n";
1.582     raeburn  3353:     my $partserror;
                   3354:     my (@parts) = sort(&getpartlist($symb,\$partserror));
                   3355:     if ($partserror) {
                   3356:         return &navmap_errormsg();
                   3357:     }
1.324     albertel 3358:     my (undef,undef,$url)=&Apache::lonnet::decode_symb($symb);
1.269     raeburn  3359:     my @partids = ();
1.41      ng       3360:     foreach my $part (@parts) {
                   3361: 	my $display=&Apache::lonnet::metadata($url,$part.'.display');
1.539     riegler  3362:         my $narrowtext = &mt('Tries');
                   3363: 	$display =~ s|^Number of Attempts|$narrowtext <br />|; # makes the column narrower
1.41      ng       3364: 	if  (!$display) { $display = &Apache::lonnet::metadata($url,$part.'.name'); }
1.207     albertel 3365: 	my ($partid) = &split_part_type($part);
1.524     raeburn  3366:         push(@partids,$partid);
1.324     albertel 3367: 	my $display_part=&get_display_part($partid,$symb);
1.41      ng       3368: 	if ($display =~ /^Partial Credit Factor/) {
1.485     albertel 3369: 	    $result.='<th>'.
                   3370: 		&mt('Score Part: [_1]<br /> (weight = [_2])',
                   3371: 		    $display_part,$weight{$partid}).'</th>'."\n";
1.41      ng       3372: 	    next;
1.485     albertel 3373: 	    
1.207     albertel 3374: 	} else {
1.485     albertel 3375: 	    if ($display =~ /Problem Status/) {
                   3376: 		my $grade_status_mt = &mt('Grade Status');
                   3377: 		$display =~ s{Problem Status}{$grade_status_mt<br />};
                   3378: 	    }
                   3379: 	    my $part_mt = &mt('Part:');
                   3380: 	    $display =~s{\[Part: \Q$partid\E\]}{$part_mt $display_part};
1.41      ng       3381: 	}
1.485     albertel 3382: 
1.474     albertel 3383: 	$result.='<th>'.$display.'</th>'."\n";
1.41      ng       3384:     }
1.474     albertel 3385:     $result.=&Apache::loncommon::end_data_table_header_row();
1.44      ng       3386: 
1.270     albertel 3387:     my %last_resets = 
                   3388: 	&get_last_resets($symb,$env{'request.course.id'},\@partids);
1.269     raeburn  3389: 
1.41      ng       3390:     #get info for each student
1.44      ng       3391:     #list all the students - with points and grade status
1.257     albertel 3392:     my (undef,undef,$fullname) = &getclasslist($env{'form.section'},'1');
1.41      ng       3393:     my $ctr = 0;
1.294     albertel 3394:     foreach (sort 
                   3395: 	     {
                   3396: 		 if (lc($$fullname{$a}) ne lc($$fullname{$b})) {
                   3397: 		     return (lc($$fullname{$a}) cmp lc($$fullname{$b}));
                   3398: 		 }
                   3399: 		 return $a cmp $b;
                   3400: 	     } (keys(%$fullname))) {
1.126     ng       3401: 	$ctr++;
1.324     albertel 3402: 	$result.=&viewstudentgrade($symb,$env{'request.course.id'},
1.269     raeburn  3403: 				   $_,$$fullname{$_},\@parts,\%weight,$ctr,\%last_resets);
1.41      ng       3404:     }
1.474     albertel 3405:     $result.=&Apache::loncommon::end_data_table();
1.41      ng       3406:     $result.='<input type="hidden" name="total" value="'.$ctr.'" />'."\n";
1.485     albertel 3407:     $result.='<input type="button" value="'.&mt('Save').'" '.
1.589     bisitz   3408: 	'onclick="javascript:submit();" target="_self" /></form>'."\n";
1.96      albertel 3409:     if (scalar(%$fullname) eq 0) {
                   3410: 	my $colspan=3+scalar(@parts);
1.433     banghart 3411: 	my $section_display = join (", ",&Apache::loncommon::get_env_multiple('form.section'));
1.442     banghart 3412:         my $stu_status = join(' or ',&Apache::loncommon::get_env_multiple('form.Status'));
1.433     banghart 3413: 	$result='<span class="LC_warning">'.
1.485     albertel 3414: 	    &mt('There are no students in section(s) [_1] with enrollment status [_2] to modify or grade.',
1.442     banghart 3415: 	        $section_display, $stu_status).
1.433     banghart 3416: 	    '</span>';
1.96      albertel 3417:     }
1.41      ng       3418:     return $result;
                   3419: }
                   3420: 
1.44      ng       3421: #--- call by previous routine to display each student
1.41      ng       3422: sub viewstudentgrade {
1.324     albertel 3423:     my ($symb,$courseid,$student,$fullname,$parts,$weight,$ctr,$last_resets) = @_;
1.44      ng       3424:     my ($uname,$udom) = split(/:/,$student);
                   3425:     my %record=&Apache::lonnet::restore($symb,$courseid,$udom,$uname);
1.269     raeburn  3426:     my %aggregates = (); 
1.474     albertel 3427:     my $result=&Apache::loncommon::start_data_table_row().'<td align="right">'.
1.233     albertel 3428: 	'<input type="hidden" name="ctr'.($ctr-1).'" value="'.$student.'" />'.
                   3429: 	"\n".$ctr.'&nbsp;</td><td>&nbsp;'.
1.44      ng       3430: 	'<a href="javascript:viewOneStudent(\''.$uname.'\',\''.$udom.
1.417     albertel 3431: 	'\');" target="_self">'.$fullname.'</a> '.
1.398     albertel 3432: 	'<span class="LC_internal_info">('.$uname.($env{'user.domain'} eq $udom ? '' : ':'.$udom).')</span></td>'."\n";
1.281     albertel 3433:     $student=~s/:/_/; # colon doen't work in javascript for names
1.63      albertel 3434:     foreach my $apart (@$parts) {
                   3435: 	my ($part,$type) = &split_part_type($apart);
1.41      ng       3436: 	my $score=$record{"resource.$part.$type"};
1.276     albertel 3437:         $result.='<td align="center">';
1.269     raeburn  3438:         my ($aggtries,$totaltries);
                   3439:         unless (exists($aggregates{$part})) {
1.270     albertel 3440: 	    $totaltries = $record{'resource.'.$part.'.tries'};
                   3441: 
                   3442: 	    $aggtries = $totaltries;
1.269     raeburn  3443:             if ($$last_resets{$part}) {  
1.270     albertel 3444:                 $aggtries = &get_num_tries(\%record,$$last_resets{$part},
                   3445: 					   $part);
                   3446:             }
1.269     raeburn  3447:             $result.='<input type="hidden" name="'.
                   3448:                 'GD_'.$student.'_'.$part.'_aggtries" value="'.$aggtries.'" />'."\n";
                   3449:             $result.='<input type="hidden" name="'.
                   3450:                 'GD_'.$student.'_'.$part.'_totaltries" value="'.$totaltries.'" />'."\n";
                   3451:             $aggregates{$part} = 1;
                   3452:         }
1.41      ng       3453: 	if ($type eq 'awarded') {
1.320     albertel 3454: 	    my $pts = $score eq '' ? '' : &compute_points($score,$$weight{$part});
1.42      ng       3455: 	    $result.='<input type="hidden" name="'.
1.89      albertel 3456: 		'GD_'.$student.'_'.$part.'_awarded_s" value="'.$pts.'" />'."\n";
1.233     albertel 3457: 	    $result.='<input type="text" name="'.
1.89      albertel 3458: 		'GD_'.$student.'_'.$part.'_awarded" '.
1.589     bisitz   3459:                 'onchange="javascript:changeSelect(\''.$part.'\',\''.$student.
1.44      ng       3460: 		'\')" value="'.$pts.'" size="4" /></td>'."\n";
1.41      ng       3461: 	} elsif ($type eq 'solved') {
                   3462: 	    my ($status,$foo)=split(/_/,$score,2);
                   3463: 	    $status = 'nothing' if ($status eq '');
1.89      albertel 3464: 	    $result.='<input type="hidden" name="'.'GD_'.$student.'_'.
1.54      albertel 3465: 		$part.'_solved_s" value="'.$status.'" />'."\n";
1.233     albertel 3466: 	    $result.='&nbsp;<select name="'.
1.89      albertel 3467: 		'GD_'.$student.'_'.$part.'_solved" '.
1.589     bisitz   3468:                 'onchange="javascript:changeOneScore(\''.$part.'\',\''.$student.'\')" >'."\n";
1.485     albertel 3469: 	    $result.= (($status eq 'excused') ? '<option> </option><option selected="selected" value="excused">'.&mt('excused').'</option>' 
                   3470: 		: '<option selected="selected"> </option><option value="excused">'.&mt('excused').'</option>')."\n";
                   3471: 	    $result.='<option value="reset status">'.&mt('reset status').'</option>';
1.126     ng       3472: 	    $result.="</select>&nbsp;</td>\n";
1.122     ng       3473: 	} else {
                   3474: 	    $result.='<input type="hidden" name="'.
                   3475: 		'GD_'.$student.'_'.$part.'_'.$type.'_s" value="'.$score.'" />'.
                   3476: 		    "\n";
1.233     albertel 3477: 	    $result.='<input type="text" name="'.
1.122     ng       3478: 		'GD_'.$student.'_'.$part.'_'.$type.'" '.
                   3479: 		'value="'.$score.'" size="4" /></td>'."\n";
1.41      ng       3480: 	}
                   3481:     }
1.474     albertel 3482:     $result.=&Apache::loncommon::end_data_table_row();
1.41      ng       3483:     return $result;
1.38      ng       3484: }
                   3485: 
1.44      ng       3486: #--- change scores for all the students in a section/class
                   3487: #    record does not get update if unchanged
1.38      ng       3488: sub editgrades {
1.608     www      3489:     my ($request,$symb) = @_;
1.41      ng       3490: 
1.433     banghart 3491:     my $section_display = join (", ",&Apache::loncommon::get_env_multiple('form.section'));
1.477     albertel 3492:     my $title='<h2>'.&mt('Current Grade Status').'</h2>';
1.433     banghart 3493:     $title.='<h4>'.&mt('<b>Section: </b>[_1]',$section_display).'</h4>'."\n";
1.126     ng       3494: 
1.477     albertel 3495:     my $result= &Apache::loncommon::start_data_table().
                   3496: 	&Apache::loncommon::start_data_table_header_row().
                   3497: 	'<th rowspan="2" valign="middle">'.&mt('No.').'</th>'.
                   3498: 	'<th rowspan="2" valign="middle">'.&nameUserString('header')."</th>\n";
1.43      ng       3499:     my %scoreptr = (
                   3500: 		    'correct'  =>'correct_by_override',
                   3501: 		    'incorrect'=>'incorrect_by_override',
                   3502: 		    'excused'  =>'excused',
                   3503: 		    'ungraded' =>'ungraded_attempted',
1.596     raeburn  3504:                     'credited' =>'credit_attempted',
1.43      ng       3505: 		    'nothing'  => '',
                   3506: 		    );
1.257     albertel 3507:     my ($classlist,undef,$fullname) = &getclasslist($env{'form.section'},'0');
1.34      ng       3508: 
1.44      ng       3509:     my (@partid);
                   3510:     my %weight = ();
1.54      albertel 3511:     my %columns = ();
1.44      ng       3512:     my ($i,$ctr,$count,$rec_update) = (0,0,0,0);
1.54      albertel 3513: 
1.582     raeburn  3514:     my $partserror;
                   3515:     my (@parts) = sort(&getpartlist($symb,\$partserror));
                   3516:     if ($partserror) {
                   3517:         return &navmap_errormsg();
                   3518:     }
1.54      albertel 3519:     my $header;
1.257     albertel 3520:     while ($ctr < $env{'form.totalparts'}) {
                   3521: 	my $partid = $env{'form.partid_'.$ctr};
1.524     raeburn  3522: 	push(@partid,$partid);
1.257     albertel 3523: 	$weight{$partid} = $env{'form.weight_'.$partid};
1.44      ng       3524: 	$ctr++;
1.54      albertel 3525:     }
1.324     albertel 3526:     my (undef,undef,$url) = &Apache::lonnet::decode_symb($symb);
1.54      albertel 3527:     foreach my $partid (@partid) {
1.478     albertel 3528: 	$header .= '<th align="center">'.&mt('Old Score').'</th>'.
                   3529: 	    '<th align="center">'.&mt('New Score').'</th>';
1.54      albertel 3530: 	$columns{$partid}=2;
                   3531: 	foreach my $stores (@parts) {
                   3532: 	    my ($part,$type) = &split_part_type($stores);
                   3533: 	    if ($part !~ m/^\Q$partid\E/) { next;}
                   3534: 	    if ($type eq 'awarded' || $type eq 'solved') { next; }
                   3535: 	    my $display=&Apache::lonnet::metadata($url,$stores.'.display');
1.551     raeburn  3536: 	    $display =~ s/\[Part: \Q$part\E\]//;
1.539     riegler  3537:             my $narrowtext = &mt('Tries');
                   3538: 	    $display =~ s/Number of Attempts/$narrowtext/;
                   3539: 	    $header .= '<th align="center">'.&mt('Old').' '.$display.'</th>'.
                   3540: 		'<th align="center">'.&mt('New').' '.$display.'</th>';
1.54      albertel 3541: 	    $columns{$partid}+=2;
                   3542: 	}
                   3543:     }
                   3544:     foreach my $partid (@partid) {
1.324     albertel 3545: 	my $display_part=&get_display_part($partid,$symb);
1.478     albertel 3546: 	$result .= '<th colspan="'.$columns{$partid}.'" align="center">'.
                   3547: 	    &mt('Part: [_1] (Weight = [_2])',$display_part,$weight{$partid}).
                   3548: 	    '</th>';
1.54      albertel 3549: 
1.44      ng       3550:     }
1.477     albertel 3551:     $result .= &Apache::loncommon::end_data_table_header_row().
                   3552: 	&Apache::loncommon::start_data_table_header_row().
                   3553: 	$header.
                   3554: 	&Apache::loncommon::end_data_table_header_row();
                   3555:     my @noupdate;
1.126     ng       3556:     my ($updateCtr,$noupdateCtr) = (1,1);
1.257     albertel 3557:     for ($i=0; $i<$env{'form.total'}; $i++) {
1.93      albertel 3558: 	my $line;
1.257     albertel 3559: 	my $user = $env{'form.ctr'.$i};
1.281     albertel 3560: 	my ($uname,$udom)=split(/:/,$user);
1.44      ng       3561: 	my %newrecord;
                   3562: 	my $updateflag = 0;
1.281     albertel 3563: 	$line .= '<td>'.&nameUserString(undef,$$fullname{$user},$uname,$udom).'</td>';
1.108     albertel 3564: 	my $usec=$classlist->{"$uname:$udom"}[5];
1.105     albertel 3565: 	if (!&canmodify($usec)) {
1.126     ng       3566: 	    my $numcols=scalar(@partid)*4+2;
1.477     albertel 3567: 	    push(@noupdate,
1.478     albertel 3568: 		 $line."<td colspan=\"$numcols\"><span class=\"LC_warning\">".
                   3569: 		 &mt('Not allowed to modify student')."</span></td></tr>");
1.105     albertel 3570: 	    next;
                   3571: 	}
1.269     raeburn  3572:         my %aggregate = ();
                   3573:         my $aggregateflag = 0;
1.281     albertel 3574: 	$user=~s/:/_/; # colon doen't work in javascript for names
1.44      ng       3575: 	foreach (@partid) {
1.257     albertel 3576: 	    my $old_aw    = $env{'form.GD_'.$user.'_'.$_.'_awarded_s'};
1.54      albertel 3577: 	    my $old_part_pcr = $old_aw/($weight{$_} ne '0' ? $weight{$_}:1);
                   3578: 	    my $old_part  = $old_aw eq '' ? '' : $old_part_pcr;
1.257     albertel 3579: 	    my $old_score = $scoreptr{$env{'form.GD_'.$user.'_'.$_.'_solved_s'}};
                   3580: 	    my $awarded   = $env{'form.GD_'.$user.'_'.$_.'_awarded'};
1.54      albertel 3581: 	    my $pcr       = $awarded/($weight{$_} ne '0' ? $weight{$_} : 1);
                   3582: 	    my $partial   = $awarded eq '' ? '' : $pcr;
1.44      ng       3583: 	    my $score;
                   3584: 	    if ($partial eq '') {
1.257     albertel 3585: 		$score = $scoreptr{$env{'form.GD_'.$user.'_'.$_.'_solved_s'}};
1.44      ng       3586: 	    } elsif ($partial > 0) {
                   3587: 		$score = 'correct_by_override';
                   3588: 	    } elsif ($partial == 0) {
                   3589: 		$score = 'incorrect_by_override';
                   3590: 	    }
1.257     albertel 3591: 	    my $dropMenu = $env{'form.GD_'.$user.'_'.$_.'_solved'};
1.125     ng       3592: 	    $score = 'excused' if (($dropMenu eq 'excused') && ($score ne 'excused'));
                   3593: 
1.292     albertel 3594: 	    $newrecord{'resource.'.$_.'.regrader'}=
                   3595: 		"$env{'user.name'}:$env{'user.domain'}";
1.125     ng       3596: 	    if ($dropMenu eq 'reset status' &&
                   3597: 		$old_score ne '') { # ignore if no previous attempts => nothing to reset
1.299     albertel 3598: 		$newrecord{'resource.'.$_.'.tries'} = '';
1.125     ng       3599: 		$newrecord{'resource.'.$_.'.solved'} = '';
                   3600: 		$newrecord{'resource.'.$_.'.award'} = '';
1.299     albertel 3601: 		$newrecord{'resource.'.$_.'.awarded'} = '';
1.125     ng       3602: 		$updateflag = 1;
1.269     raeburn  3603:                 if ($env{'form.GD_'.$user.'_'.$_.'_aggtries'} > 0) {
                   3604:                     my $aggtries = $env{'form.GD_'.$user.'_'.$_.'_aggtries'};
                   3605:                     my $totaltries = $env{'form.GD_'.$user.'_'.$_.'_totaltries'};
                   3606:                     my $solvedstatus = $env{'form.GD_'.$user.'_'.$_.'_solved_s'};
                   3607:                     &decrement_aggs($symb,$_,\%aggregate,$aggtries,$totaltries,$solvedstatus);
                   3608:                     $aggregateflag = 1;
                   3609:                 }
1.139     albertel 3610: 	    } elsif (!($old_part eq $partial && $old_score eq $score)) {
                   3611: 		$updateflag = 1;
                   3612: 		$newrecord{'resource.'.$_.'.awarded'}  = $partial if $partial ne '';
                   3613: 		$newrecord{'resource.'.$_.'.solved'}   = $score;
                   3614: 		$rec_update++;
1.125     ng       3615: 	    }
                   3616: 
1.93      albertel 3617: 	    $line .= '<td align="center">'.$old_aw.'&nbsp;</td>'.
1.44      ng       3618: 		'<td align="center">'.$awarded.
                   3619: 		($score eq 'excused' ? $score : '').'&nbsp;</td>';
1.5       albertel 3620: 
1.54      albertel 3621: 
                   3622: 	    my $partid=$_;
                   3623: 	    foreach my $stores (@parts) {
                   3624: 		my ($part,$type) = &split_part_type($stores);
                   3625: 		if ($part !~ m/^\Q$partid\E/) { next;}
                   3626: 		if ($type eq 'awarded' || $type eq 'solved') { next; }
1.257     albertel 3627: 		my $old_aw    = $env{'form.GD_'.$user.'_'.$part.'_'.$type.'_s'};
                   3628: 		my $awarded   = $env{'form.GD_'.$user.'_'.$part.'_'.$type};
1.54      albertel 3629: 		if ($awarded ne '' && $awarded ne $old_aw) {
                   3630: 		    $newrecord{'resource.'.$part.'.'.$type}= $awarded;
1.257     albertel 3631: 		    $newrecord{'resource.'.$part.'.regrader'}="$env{'user.name'}:$env{'user.domain'}";
1.54      albertel 3632: 		    $updateflag=1;
                   3633: 		}
1.93      albertel 3634: 		$line .= '<td align="center">'.$old_aw.'&nbsp;</td>'.
1.54      albertel 3635: 		    '<td align="center">'.$awarded.'&nbsp;</td>';
                   3636: 	    }
1.44      ng       3637: 	}
1.477     albertel 3638: 	$line.="\n";
1.301     albertel 3639: 
                   3640: 	my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   3641: 	my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   3642: 
1.44      ng       3643: 	if ($updateflag) {
                   3644: 	    $count++;
1.257     albertel 3645: 	    &Apache::lonnet::cstore(\%newrecord,$symb,$env{'request.course.id'},
1.89      albertel 3646: 				    $udom,$uname);
1.301     albertel 3647: 
                   3648: 	    if (&Apache::bridgetask::in_queue('gradingqueue',$symb,$cdom,
                   3649: 					      $cnum,$udom,$uname)) {
                   3650: 		# need to figure out if should be in queue.
                   3651: 		my %record =  
                   3652: 		    &Apache::lonnet::restore($symb,$env{'request.course.id'},
                   3653: 					     $udom,$uname);
                   3654: 		my $all_graded = 1;
                   3655: 		my $none_graded = 1;
                   3656: 		foreach my $part (@parts) {
                   3657: 		    if ( $record{'resource.'.$part.'.awarded'} eq '' ) {
                   3658: 			$all_graded = 0;
                   3659: 		    } else {
                   3660: 			$none_graded = 0;
                   3661: 		    }
                   3662: 		}
                   3663: 
                   3664: 		if ($all_graded || $none_graded) {
                   3665: 		    &Apache::bridgetask::remove_from_queue('gradingqueue',
                   3666: 							   $symb,$cdom,$cnum,
                   3667: 							   $udom,$uname);
                   3668: 		}
                   3669: 	    }
                   3670: 
1.477     albertel 3671: 	    $result.=&Apache::loncommon::start_data_table_row().
                   3672: 		'<td align="right">&nbsp;'.$updateCtr.'&nbsp;</td>'.$line.
                   3673: 		&Apache::loncommon::end_data_table_row();
1.126     ng       3674: 	    $updateCtr++;
1.93      albertel 3675: 	} else {
1.477     albertel 3676: 	    push(@noupdate,
                   3677: 		 '<td align="right">&nbsp;'.$noupdateCtr.'&nbsp;</td>'.$line);
1.126     ng       3678: 	    $noupdateCtr++;
1.44      ng       3679: 	}
1.269     raeburn  3680:         if ($aggregateflag) {
                   3681:             &Apache::lonnet::cinc('nohist_resourcetracker',\%aggregate,
1.301     albertel 3682: 				  $cdom,$cnum);
1.269     raeburn  3683:         }
1.93      albertel 3684:     }
1.477     albertel 3685:     if (@noupdate) {
1.126     ng       3686: #	my $numcols=(scalar(@partid)*(scalar(@parts)-1)*2)+3;
                   3687: 	my $numcols=scalar(@partid)*4+2;
1.477     albertel 3688: 	$result .= &Apache::loncommon::start_data_table_row('LC_empty_row').
1.478     albertel 3689: 	    '<td align="center" colspan="'.$numcols.'">'.
                   3690: 	    &mt('No Changes Occurred For the Students Below').
                   3691: 	    '</td>'.
1.477     albertel 3692: 	    &Apache::loncommon::end_data_table_row();
                   3693: 	foreach my $line (@noupdate) {
                   3694: 	    $result.=
                   3695: 		&Apache::loncommon::start_data_table_row().
                   3696: 		$line.
                   3697: 		&Apache::loncommon::end_data_table_row();
                   3698: 	}
1.44      ng       3699:     }
1.614     www      3700:     $result .= &Apache::loncommon::end_data_table();
1.478     albertel 3701:     my $msg = '<p><b>'.
                   3702: 	&mt('Number of records updated = [_1] for [quant,_2,student].',
                   3703: 	    $rec_update,$count).'</b><br />'.
                   3704: 	'<b>'.&mt('Total number of students = [_1]',$env{'form.total'}).
                   3705: 	'</b></p>';
1.44      ng       3706:     return $title.$msg.$result;
1.5       albertel 3707: }
1.54      albertel 3708: 
                   3709: sub split_part_type {
                   3710:     my ($partstr) = @_;
                   3711:     my ($temp,@allparts)=split(/_/,$partstr);
                   3712:     my $type=pop(@allparts);
1.439     albertel 3713:     my $part=join('_',@allparts);
1.54      albertel 3714:     return ($part,$type);
                   3715: }
                   3716: 
1.44      ng       3717: #------------- end of section for handling grading by section/class ---------
                   3718: #
                   3719: #----------------------------------------------------------------------------
                   3720: 
1.5       albertel 3721: 
1.44      ng       3722: #----------------------------------------------------------------------------
                   3723: #
                   3724: #-------------------------- Next few routines handles grading by csv upload
                   3725: #
                   3726: #--- Javascript to handle csv upload
1.27      albertel 3727: sub csvupload_javascript_reverse_associate {
1.573     bisitz   3728:     my $error1=&mt('You need to specify the username or the student/employee ID');
1.246     albertel 3729:     my $error2=&mt('You need to specify at least one grading field');
1.27      albertel 3730:   return(<<ENDPICK);
                   3731:   function verify(vf) {
                   3732:     var foundsomething=0;
                   3733:     var founduname=0;
1.243     albertel 3734:     var foundID=0;
1.27      albertel 3735:     for (i=0;i<=vf.nfields.value;i++) {
                   3736:       tw=eval('vf.f'+i+'.selectedIndex');
1.243     albertel 3737:       if (i==0 && tw!=0) { foundID=1; }
                   3738:       if (i==1 && tw!=0) { founduname=1; }
                   3739:       if (i!=0 && i!=1 && i!=2 && tw!=0) { foundsomething=1; }
1.27      albertel 3740:     }
1.246     albertel 3741:     if (founduname==0 && foundID==0) {
                   3742: 	alert('$error1');
                   3743: 	return;
1.27      albertel 3744:     }
                   3745:     if (foundsomething==0) {
1.246     albertel 3746: 	alert('$error2');
                   3747: 	return;
1.27      albertel 3748:     }
                   3749:     vf.submit();
                   3750:   }
                   3751:   function flip(vf,tf) {
                   3752:     var nw=eval('vf.f'+tf+'.selectedIndex');
                   3753:     var i;
                   3754:     for (i=0;i<=vf.nfields.value;i++) {
                   3755:       //can not pick the same destination field for both name and domain
                   3756:       if (((i ==0)||(i ==1)) && 
                   3757:           ((tf==0)||(tf==1)) && 
                   3758:           (i!=tf) &&
                   3759:           (eval('vf.f'+i+'.selectedIndex')==nw)) {
                   3760:         eval('vf.f'+i+'.selectedIndex=0;')
                   3761:       }
                   3762:     }
                   3763:   }
                   3764: ENDPICK
                   3765: }
                   3766: 
                   3767: sub csvupload_javascript_forward_associate {
1.573     bisitz   3768:     my $error1=&mt('You need to specify the username or the student/employee ID');
1.246     albertel 3769:     my $error2=&mt('You need to specify at least one grading field');
1.27      albertel 3770:   return(<<ENDPICK);
                   3771:   function verify(vf) {
                   3772:     var foundsomething=0;
                   3773:     var founduname=0;
1.243     albertel 3774:     var foundID=0;
1.27      albertel 3775:     for (i=0;i<=vf.nfields.value;i++) {
                   3776:       tw=eval('vf.f'+i+'.selectedIndex');
1.243     albertel 3777:       if (tw==1) { foundID=1; }
                   3778:       if (tw==2) { founduname=1; }
                   3779:       if (tw>3) { foundsomething=1; }
1.27      albertel 3780:     }
1.246     albertel 3781:     if (founduname==0 && foundID==0) {
                   3782: 	alert('$error1');
                   3783: 	return;
1.27      albertel 3784:     }
                   3785:     if (foundsomething==0) {
1.246     albertel 3786: 	alert('$error2');
                   3787: 	return;
1.27      albertel 3788:     }
                   3789:     vf.submit();
                   3790:   }
                   3791:   function flip(vf,tf) {
                   3792:     var nw=eval('vf.f'+tf+'.selectedIndex');
                   3793:     var i;
                   3794:     //can not pick the same destination field twice
                   3795:     for (i=0;i<=vf.nfields.value;i++) {
                   3796:       if ((i!=tf) && (eval('vf.f'+i+'.selectedIndex')==nw)) {
                   3797:         eval('vf.f'+i+'.selectedIndex=0;')
                   3798:       }
                   3799:     }
                   3800:   }
                   3801: ENDPICK
                   3802: }
                   3803: 
1.26      albertel 3804: sub csvuploadmap_header {
1.324     albertel 3805:     my ($request,$symb,$datatoken,$distotal)= @_;
1.41      ng       3806:     my $javascript;
1.257     albertel 3807:     if ($env{'form.upfile_associate'} eq 'reverse') {
1.41      ng       3808: 	$javascript=&csvupload_javascript_reverse_associate();
                   3809:     } else {
                   3810: 	$javascript=&csvupload_javascript_forward_associate();
                   3811:     }
1.45      ng       3812: 
1.598     www      3813:     my $result='';
1.257     albertel 3814:     my $checked=(($env{'form.noFirstLine'})?' checked="checked"':'');
1.245     albertel 3815:     my $ignore=&mt('Ignore First Line');
1.418     albertel 3816:     $symb = &Apache::lonenc::check_encrypt($symb);
1.41      ng       3817:     $request->print(<<ENDPICK);
1.26      albertel 3818: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="gradesupload">
1.398     albertel 3819: <h3><span class="LC_info">Uploading Class Grades</span></h3>
1.45      ng       3820: $result
1.326     albertel 3821: <hr />
1.26      albertel 3822: <h3>Identify fields</h3>
                   3823: Total number of records found in file: $distotal <hr />
                   3824: Enter as many fields as you can. The system will inform you and bring you back
                   3825: to this page if the data selected is insufficient to run your class.<hr />
1.589     bisitz   3826: <input type="button" value="Reverse Association" onclick="javascript:this.form.associate.value='Reverse Association';submit(this.form);" />
1.245     albertel 3827: <label><input type="checkbox" name="noFirstLine" $checked />$ignore</label>
1.26      albertel 3828: <input type="hidden" name="associate"  value="" />
                   3829: <input type="hidden" name="phase"      value="three" />
                   3830: <input type="hidden" name="datatoken"  value="$datatoken" />
1.257     albertel 3831: <input type="hidden" name="fileupload" value="$env{'form.fileupload'}" />
                   3832: <input type="hidden" name="upfiletype" value="$env{'form.upfiletype'}" />
1.26      albertel 3833: <input type="hidden" name="upfile_associate" 
1.257     albertel 3834:                                        value="$env{'form.upfile_associate'}" />
1.26      albertel 3835: <input type="hidden" name="symb"       value="$symb" />
1.246     albertel 3836: <input type="hidden" name="command"    value="csvuploadoptions" />
1.26      albertel 3837: <hr />
                   3838: ENDPICK
1.597     wenzelju 3839:     $request->print(&Apache::lonhtmlcommon::scripttag($javascript));
1.118     ng       3840:     return '';
1.26      albertel 3841: 
                   3842: }
                   3843: 
                   3844: sub csvupload_fields {
1.582     raeburn  3845:     my ($symb,$errorref) = @_;
                   3846:     my (@parts) = &getpartlist($symb,$errorref);
                   3847:     if (ref($errorref)) {
                   3848:         if ($$errorref) {
                   3849:             return;
                   3850:         }
                   3851:     }
                   3852: 
1.556     weissno  3853:     my @fields=(['ID','Student/Employee ID'],
1.243     albertel 3854: 		['username','Student Username'],
                   3855: 		['domain','Student Domain']);
1.324     albertel 3856:     my (undef,undef,$url) = &Apache::lonnet::decode_symb($symb);
1.41      ng       3857:     foreach my $part (sort(@parts)) {
                   3858: 	my @datum;
                   3859: 	my $display=&Apache::lonnet::metadata($url,$part.'.display');
                   3860: 	my $name=$part;
                   3861: 	if  (!$display) { $display = $name; }
                   3862: 	@datum=($name,$display);
1.244     albertel 3863: 	if ($name=~/^stores_(.*)_awarded/) {
                   3864: 	    push(@fields,['stores_'.$1.'_points',"Points [Part: $1]"]);
                   3865: 	}
1.41      ng       3866: 	push(@fields,\@datum);
                   3867:     }
                   3868:     return (@fields);
1.26      albertel 3869: }
                   3870: 
                   3871: sub csvuploadmap_footer {
1.41      ng       3872:     my ($request,$i,$keyfields) =@_;
                   3873:     $request->print(<<ENDPICK);
1.26      albertel 3874: </table>
                   3875: <input type="hidden" name="nfields" value="$i" />
                   3876: <input type="hidden" name="keyfields" value="$keyfields" />
1.589     bisitz   3877: <input type="button" onclick="javascript:verify(this.form)" value="Assign Grades" /><br />
1.26      albertel 3878: </form>
                   3879: ENDPICK
                   3880: }
                   3881: 
1.283     albertel 3882: sub checkforfile_js {
1.539     riegler  3883:     my $alertmsg = &mt('Please use the browse button to select a file from your local directory.');
1.597     wenzelju 3884:     my $result = &Apache::lonhtmlcommon::scripttag(<<CSVFORMJS);
1.86      ng       3885:     function checkUpload(formname) {
                   3886: 	if (formname.upfile.value == "") {
1.539     riegler  3887: 	    alert("$alertmsg");
1.86      ng       3888: 	    return false;
                   3889: 	}
                   3890: 	formname.submit();
                   3891:     }
                   3892: CSVFORMJS
1.283     albertel 3893:     return $result;
                   3894: }
                   3895: 
                   3896: sub upcsvScores_form {
1.608     www      3897:     my ($request,$symb) = @_;
1.283     albertel 3898:     if (!$symb) {return '';}
                   3899:     my $result=&checkforfile_js();
1.326     albertel 3900:     $result.='<br /><table width="100%" border="0"><tr><td bgcolor="#777777">'."\n";
                   3901:     $result.='<table width="100%" border="0"><tr bgcolor="#e6ffff"><td>'."\n";
1.538     schulted 3902:     $result.='&nbsp;<b>'.&mt('Specify a file containing the class scores for current resource.').
                   3903: 	'</b></td></tr>'."\n";
1.86      ng       3904:     $result.='<tr bgcolor=#ffffe6><td>'."\n";
1.370     www      3905:     my $upload=&mt("Upload Scores");
1.86      ng       3906:     my $upfile_select=&Apache::loncommon::upfile_select_html();
1.245     albertel 3907:     my $ignore=&mt('Ignore First Line');
1.418     albertel 3908:     $symb = &Apache::lonenc::check_encrypt($symb);
1.86      ng       3909:     $result.=<<ENDUPFORM;
1.106     albertel 3910: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="gradesupload">
1.86      ng       3911: <input type="hidden" name="symb" value="$symb" />
                   3912: <input type="hidden" name="command" value="csvuploadmap" />
                   3913: $upfile_select
1.589     bisitz   3914: <br /><input type="button" onclick="javascript:checkUpload(this.form);" value="$upload" />
1.283     albertel 3915: <label><input type="checkbox" name="noFirstLine" />$ignore</label>
1.86      ng       3916: </form>
                   3917: ENDUPFORM
1.370     www      3918:     $result.=&Apache::loncommon::help_open_topic("Course_Convert_To_CSV",
                   3919:                            &mt("How do I create a CSV file from a spreadsheet"))
                   3920:     .'</td></tr></table>'."\n";
1.86      ng       3921:     $result.='</td></tr></table><br /><br />'."\n";
                   3922:     return $result;
                   3923: }
                   3924: 
                   3925: 
1.26      albertel 3926: sub csvuploadmap {
1.608     www      3927:     my ($request,$symb)= @_;
1.41      ng       3928:     if (!$symb) {return '';}
1.72      ng       3929: 
1.41      ng       3930:     my $datatoken;
1.257     albertel 3931:     if (!$env{'form.datatoken'}) {
1.41      ng       3932: 	$datatoken=&Apache::loncommon::upfile_store($request);
1.26      albertel 3933:     } else {
1.257     albertel 3934: 	$datatoken=$env{'form.datatoken'};
1.41      ng       3935: 	&Apache::loncommon::load_tmp_file($request);
1.26      albertel 3936:     }
1.41      ng       3937:     my @records=&Apache::loncommon::upfile_record_sep();
1.257     albertel 3938:     if ($env{'form.noFirstLine'}) { shift(@records); }
1.324     albertel 3939:     &csvuploadmap_header($request,$symb,$datatoken,$#records+1);
1.41      ng       3940:     my ($i,$keyfields);
                   3941:     if (@records) {
1.582     raeburn  3942:         my $fieldserror;
                   3943: 	my @fields=&csvupload_fields($symb,\$fieldserror);
                   3944:         if ($fieldserror) {
                   3945:             $request->print(&navmap_errormsg());
                   3946:             return;
                   3947:         }
1.257     albertel 3948: 	if ($env{'form.upfile_associate'} eq 'reverse') {	
1.41      ng       3949: 	    &Apache::loncommon::csv_print_samples($request,\@records);
                   3950: 	    $i=&Apache::loncommon::csv_print_select_table($request,\@records,
                   3951: 							  \@fields);
                   3952: 	    foreach (@fields) { $keyfields.=$_->[0].','; }
                   3953: 	    chop($keyfields);
                   3954: 	} else {
                   3955: 	    unshift(@fields,['none','']);
                   3956: 	    $i=&Apache::loncommon::csv_samples_select_table($request,\@records,
                   3957: 							    \@fields);
1.311     banghart 3958:             foreach my $rec (@records) {
                   3959:                 my %temp = &Apache::loncommon::record_sep($rec);
                   3960:                 if (%temp) {
                   3961:                     $keyfields=join(',',sort(keys(%temp)));
                   3962:                     last;
                   3963:                 }
                   3964:             }
1.41      ng       3965: 	}
                   3966:     }
                   3967:     &csvuploadmap_footer($request,$i,$keyfields);
1.72      ng       3968: 
1.41      ng       3969:     return '';
1.27      albertel 3970: }
                   3971: 
1.246     albertel 3972: sub csvuploadoptions {
1.608     www      3973:     my ($request,$symb)= @_;
1.257     albertel 3974:     my $checked=(($env{'form.noFirstLine'})?'1':'0');
1.246     albertel 3975:     my $ignore=&mt('Ignore First Line');
                   3976:     $request->print(<<ENDPICK);
                   3977: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="gradesupload">
1.398     albertel 3978: <h3><span class="LC_info">Uploading Class Grade Options</span></h3>
1.246     albertel 3979: <input type="hidden" name="command"    value="csvuploadassign" />
1.302     albertel 3980: <!--
1.246     albertel 3981: <p>
                   3982: <label>
                   3983:    <input type="checkbox" name="show_full_results" />
                   3984:    Show a table of all changes
                   3985: </label>
                   3986: </p>
1.302     albertel 3987: -->
1.246     albertel 3988: <p>
                   3989: <label>
                   3990:    <input type="checkbox" name="overwite_scores" checked="checked" />
                   3991:    Overwrite any existing score
                   3992: </label>
                   3993: </p>
                   3994: ENDPICK
                   3995:     my %fields=&get_fields();
                   3996:     if (!defined($fields{'domain'})) {
1.257     albertel 3997: 	my $domform = &Apache::loncommon::select_dom_form($env{'request.role.domain'},'default_domain');
1.246     albertel 3998: 	$request->print("\n<p> Users are in domain: ".$domform."</p>\n");
                   3999:     }
1.257     albertel 4000:     foreach my $key (sort(keys(%env))) {
1.246     albertel 4001: 	if ($key !~ /^form\.(.*)$/) { next; }
                   4002: 	my $cleankey=$1;
                   4003: 	if ($cleankey eq 'command') { next; }
                   4004: 	$request->print('<input type="hidden" name="'.$cleankey.
1.257     albertel 4005: 			'"  value="'.$env{$key}.'" />'."\n");
1.246     albertel 4006:     }
                   4007:     # FIXME do a check for any duplicated user ids...
                   4008:     # FIXME do a check for any invalid user ids?...
1.290     albertel 4009:     $request->print('<input type="submit" value="Assign Grades" /><br />
                   4010: <hr /></form>'."\n");
1.246     albertel 4011:     return '';
                   4012: }
                   4013: 
                   4014: sub get_fields {
                   4015:     my %fields;
1.257     albertel 4016:     my @keyfields = split(/\,/,$env{'form.keyfields'});
                   4017:     for (my $i=0; $i<=$env{'form.nfields'}; $i++) {
                   4018: 	if ($env{'form.upfile_associate'} eq 'reverse') {
                   4019: 	    if ($env{'form.f'.$i} ne 'none') {
                   4020: 		$fields{$keyfields[$i]}=$env{'form.f'.$i};
1.41      ng       4021: 	    }
                   4022: 	} else {
1.257     albertel 4023: 	    if ($env{'form.f'.$i} ne 'none') {
                   4024: 		$fields{$env{'form.f'.$i}}=$keyfields[$i];
1.41      ng       4025: 	    }
                   4026: 	}
1.27      albertel 4027:     }
1.246     albertel 4028:     return %fields;
                   4029: }
                   4030: 
                   4031: sub csvuploadassign {
1.608     www      4032:     my ($request,$symb)= @_;
1.246     albertel 4033:     if (!$symb) {return '';}
1.345     bowersj2 4034:     my $error_msg = '';
1.246     albertel 4035:     &Apache::loncommon::load_tmp_file($request);
                   4036:     my @gradedata = &Apache::loncommon::upfile_record_sep();
1.257     albertel 4037:     if ($env{'form.noFirstLine'}) { shift(@gradedata); }
1.246     albertel 4038:     my %fields=&get_fields();
1.41      ng       4039:     $request->print('<h3>Assigning Grades</h3>');
1.257     albertel 4040:     my $courseid=$env{'request.course.id'};
1.97      albertel 4041:     my ($classlist) = &getclasslist('all',0);
1.106     albertel 4042:     my @notallowed;
1.41      ng       4043:     my @skipped;
                   4044:     my $countdone=0;
                   4045:     foreach my $grade (@gradedata) {
                   4046: 	my %entries=&Apache::loncommon::record_sep($grade);
1.246     albertel 4047: 	my $domain;
                   4048: 	if ($entries{$fields{'domain'}}) {
                   4049: 	    $domain=$entries{$fields{'domain'}};
                   4050: 	} else {
1.257     albertel 4051: 	    $domain=$env{'form.default_domain'};
1.246     albertel 4052: 	}
1.243     albertel 4053: 	$domain=~s/\s//g;
1.41      ng       4054: 	my $username=$entries{$fields{'username'}};
1.160     albertel 4055: 	$username=~s/\s//g;
1.243     albertel 4056: 	if (!$username) {
                   4057: 	    my $id=$entries{$fields{'ID'}};
1.247     albertel 4058: 	    $id=~s/\s//g;
1.243     albertel 4059: 	    my %ids=&Apache::lonnet::idget($domain,$id);
                   4060: 	    $username=$ids{$id};
                   4061: 	}
1.41      ng       4062: 	if (!exists($$classlist{"$username:$domain"})) {
1.247     albertel 4063: 	    my $id=$entries{$fields{'ID'}};
                   4064: 	    $id=~s/\s//g;
                   4065: 	    if ($id) {
                   4066: 		push(@skipped,"$id:$domain");
                   4067: 	    } else {
                   4068: 		push(@skipped,"$username:$domain");
                   4069: 	    }
1.41      ng       4070: 	    next;
                   4071: 	}
1.108     albertel 4072: 	my $usec=$classlist->{"$username:$domain"}[5];
1.106     albertel 4073: 	if (!&canmodify($usec)) {
                   4074: 	    push(@notallowed,"$username:$domain");
                   4075: 	    next;
                   4076: 	}
1.244     albertel 4077: 	my %points;
1.41      ng       4078: 	my %grades;
                   4079: 	foreach my $dest (keys(%fields)) {
1.244     albertel 4080: 	    if ($dest eq 'ID' || $dest eq 'username' ||
                   4081: 		$dest eq 'domain') { next; }
                   4082: 	    if ($entries{$fields{$dest}} =~ /^\s*$/) { next; }
                   4083: 	    if ($dest=~/stores_(.*)_points/) {
                   4084: 		my $part=$1;
                   4085: 		my $wgt =&Apache::lonnet::EXT('resource.'.$part.'.weight',
                   4086: 					      $symb,$domain,$username);
1.345     bowersj2 4087:                 if ($wgt) {
                   4088:                     $entries{$fields{$dest}}=~s/\s//g;
                   4089:                     my $pcr=$entries{$fields{$dest}} / $wgt;
1.463     albertel 4090:                     my $award=($pcr == 0) ? 'incorrect_by_override'
                   4091:                                           : 'correct_by_override';
1.345     bowersj2 4092:                     $grades{"resource.$part.awarded"}=$pcr;
                   4093:                     $grades{"resource.$part.solved"}=$award;
                   4094:                     $points{$part}=1;
                   4095:                 } else {
                   4096:                     $error_msg = "<br />" .
                   4097:                         &mt("Some point values were assigned"
                   4098:                             ." for problems with a weight "
                   4099:                             ."of zero. These values were "
                   4100:                             ."ignored.");
                   4101:                 }
1.244     albertel 4102: 	    } else {
                   4103: 		if ($dest=~/stores_(.*)_awarded/) { if ($points{$1}) {next;} }
                   4104: 		if ($dest=~/stores_(.*)_solved/)  { if ($points{$1}) {next;} }
                   4105: 		my $store_key=$dest;
                   4106: 		$store_key=~s/^stores/resource/;
                   4107: 		$store_key=~s/_/\./g;
                   4108: 		$grades{$store_key}=$entries{$fields{$dest}};
                   4109: 	    }
1.41      ng       4110: 	}
1.508     www      4111: 	if (! %grades) { 
                   4112:            push(@skipped,&mt("[_1]: no data to save","$username:$domain")); 
                   4113:         } else {
                   4114: 	   $grades{"resource.regrader"}="$env{'user.name'}:$env{'user.domain'}";
                   4115: 	   my $result=&Apache::lonnet::cstore(\%grades,$symb,
1.302     albertel 4116: 					   $env{'request.course.id'},
                   4117: 					   $domain,$username);
1.508     www      4118: 	   if ($result eq 'ok') {
                   4119: 	      $request->print('.');
                   4120: 	   } else {
                   4121: 	      $request->print("<p><span class=\"LC_error\">".
                   4122:                               &mt("Failed to save data for student [_1]. Message when trying to save was: [_2]",
                   4123:                                   "$username:$domain",$result)."</span></p>");
                   4124: 	   }
                   4125: 	   $request->rflush();
                   4126: 	   $countdone++;
                   4127:         }
1.41      ng       4128:     }
1.570     www      4129:     $request->print('<br />'.&Apache::lonhtmlcommon::confirm_success(&mt("Saved scores for [quant,_1,student]",$countdone),$countdone==0));
1.41      ng       4130:     if (@skipped) {
1.571     www      4131: 	$request->print('<br />'.&Apache::lonhtmlcommon::confirm_success(&mt('No scores stored for the following username(s):'),1).'<br />');
                   4132:         $request->print(join(', ',@skipped));
1.106     albertel 4133:     }
                   4134:     if (@notallowed) {
1.571     www      4135: 	$request->print('<br />'.&Apache::lonhtmlcommon::confirm_success(&mt('Modification of scores not allowed for the following username(s):'),1).'<br />');
                   4136: 	$request->print(join(', ',@notallowed));
1.41      ng       4137:     }
1.106     albertel 4138:     $request->print("<br />\n");
1.345     bowersj2 4139:     return $error_msg;
1.26      albertel 4140: }
1.44      ng       4141: #------------- end of section for handling csv file upload ---------
                   4142: #
                   4143: #-------------------------------------------------------------------
                   4144: #
1.122     ng       4145: #-------------- Next few routines handle grading by page/sequence
1.72      ng       4146: #
                   4147: #--- Select a page/sequence and a student to grade
1.68      ng       4148: sub pickStudentPage {
1.608     www      4149:     my ($request,$symb) = @_;
1.68      ng       4150: 
1.539     riegler  4151:     my $alertmsg = &mt('Please select the student you wish to grade.');
1.597     wenzelju 4152:     $request->print(&Apache::lonhtmlcommon::scripttag(<<LISTJAVASCRIPT));
1.68      ng       4153: 
                   4154: function checkPickOne(formname) {
1.76      ng       4155:     if (radioSelection(formname.student) == null) {
1.539     riegler  4156: 	alert("$alertmsg");
1.68      ng       4157: 	return;
                   4158:     }
1.125     ng       4159:     ptr = pullDownSelection(formname.selectpage);
                   4160:     formname.page.value = formname["page"+ptr].value;
                   4161:     formname.title.value = formname["title"+ptr].value;
1.68      ng       4162:     formname.submit();
                   4163: }
                   4164: 
                   4165: LISTJAVASCRIPT
1.118     ng       4166:     &commonJSfunctions($request);
1.608     www      4167: 
1.257     albertel 4168:     my $cdom      = $env{"course.$env{'request.course.id'}.domain"};
                   4169:     my $cnum      = $env{"course.$env{'request.course.id'}.num"};
                   4170:     my $getsec    = $env{'form.section'} eq '' ? 'all' : $env{'form.section'};
1.68      ng       4171: 
1.398     albertel 4172:     my $result='<h3><span class="LC_info">&nbsp;'.
1.485     albertel 4173: 	&mt('Manual Grading by Page or Sequence').'</span></h3>';
1.68      ng       4174: 
1.80      ng       4175:     $result.='<form action="/adm/grades" method="post" name="displayPage">'."\n";
1.582     raeburn  4176:     my $map_error;
                   4177:     my ($titles,$symbx) = &getSymbMap($map_error);
                   4178:     if ($map_error) {
                   4179:         $request->print(&navmap_errormsg());
                   4180:         return; 
                   4181:     }
1.137     albertel 4182:     my ($curpage) =&Apache::lonnet::decode_symb($symb); 
                   4183: #    my ($curpage,$mapId) =&Apache::lonnet::decode_symb($symb); 
                   4184: #    my $type=($curpage =~ /\.(page|sequence)/);
1.485     albertel 4185:     my $select = '<select name="selectpage">'."\n";
1.70      ng       4186:     my $ctr=0;
1.68      ng       4187:     foreach (@$titles) {
                   4188: 	my ($minder,$showtitle) = ($_ =~ /(\d+)\.(.*)/);
1.485     albertel 4189: 	$select.='<option value="'.$ctr.'" '.
1.401     albertel 4190: 	    ($$symbx{$_} =~ /$curpage$/ ? 'selected="selected"' : '').
1.71      ng       4191: 	    '>'.$showtitle.'</option>'."\n";
1.70      ng       4192: 	$ctr++;
1.68      ng       4193:     }
1.485     albertel 4194:     $select.= '</select>';
1.539     riegler  4195:     $result.='&nbsp;<b>'.&mt('Problems from').':</b> '.$select."<br />\n";
1.485     albertel 4196: 
1.70      ng       4197:     $ctr=0;
                   4198:     foreach (@$titles) {
                   4199: 	my ($minder,$showtitle) = ($_ =~ /(\d+)\.(.*)/);
                   4200: 	$result.='<input type="hidden" name="page'.$ctr.'" value="'.$$symbx{$_}.'" />'."\n";
                   4201: 	$result.='<input type="hidden" name="title'.$ctr.'" value="'.$showtitle.'" />'."\n";
                   4202: 	$ctr++;
                   4203:     }
1.72      ng       4204:     $result.='<input type="hidden" name="page" />'."\n".
                   4205: 	'<input type="hidden" name="title" />'."\n";
1.68      ng       4206: 
1.485     albertel 4207:     my $options =
                   4208: 	'<label><input type="radio" name="vProb" value="no" checked="checked" /> '.&mt('no').' </label>'."\n".
                   4209: 	'<label><input type="radio" name="vProb" value="yes" /> '.&mt('yes').' </label>'."<br />\n";
1.539     riegler  4210:     $result.='&nbsp;<b>'.&mt('View Problem Text').': </b>'.$options;
1.485     albertel 4211: 
                   4212:     $options =
                   4213: 	'<label><input type="radio" name="lastSub" value="none" /> '.&mt('none').' </label>'."\n".
                   4214: 	'<label><input type="radio" name="lastSub" value="datesub" checked="checked" /> '.&mt('by dates and submissions').'</label>'."\n".
                   4215: 	'<label><input type="radio" name="lastSub" value="all" /> '.&mt('all details').' </label>'."\n";
1.539     riegler  4216:     $result.='&nbsp;<b>'.&mt('Submissions').': </b>'.$options;
1.432     banghart 4217:     
                   4218:     $result.=&build_section_inputs();
1.442     banghart 4219:     my $stu_status = join(':',&Apache::loncommon::get_env_multiple('form.Status'));
                   4220:     $result.='<input type="hidden" name="Status"  value="'.$stu_status.'" />'."\n".
1.72      ng       4221: 	'<input type="hidden" name="command" value="displayPage" />'."\n".
1.613     www      4222: 	'<input type="hidden" name="symb"    value="'.&Apache::lonenc::check_encrypt($symb).'" />'."<br />\n";
1.72      ng       4223: 
1.539     riegler  4224:     $result.='&nbsp;<b>'.&mt('Use CODE').': </b> <input type="text" name="CODE" value="" /> <br />'."\n";
1.382     albertel 4225: 
1.80      ng       4226:     $result.='&nbsp;<input type="button" '.
1.589     bisitz   4227:              'onclick="javascript:checkPickOne(this.form);" value="'.&mt('Next').' &rarr;" /><br />'."\n";
1.72      ng       4228: 
1.68      ng       4229:     $request->print($result);
                   4230: 
1.485     albertel 4231:     my $studentTable.='&nbsp;<b>'.&mt('Select a student you wish to grade and then click on the Next button.').'</b><br />'.
1.484     albertel 4232: 	&Apache::loncommon::start_data_table().
                   4233: 	&Apache::loncommon::start_data_table_header_row().
1.485     albertel 4234: 	'<th align="right">&nbsp;'.&mt('No.').'</th>'.
1.484     albertel 4235: 	'<th>'.&nameUserString('header').'</th>'.
1.485     albertel 4236: 	'<th align="right">&nbsp;'.&mt('No.').'</th>'.
1.484     albertel 4237: 	'<th>'.&nameUserString('header').'</th>'.
                   4238: 	&Apache::loncommon::end_data_table_header_row();
1.68      ng       4239:  
1.76      ng       4240:     my (undef,undef,$fullname) = &getclasslist($getsec,'1');
1.68      ng       4241:     my $ptr = 1;
1.294     albertel 4242:     foreach my $student (sort 
                   4243: 			 {
                   4244: 			     if (lc($$fullname{$a}) ne lc($$fullname{$b})) {
                   4245: 				 return (lc($$fullname{$a}) cmp lc($$fullname{$b}));
                   4246: 			     }
                   4247: 			     return $a cmp $b;
                   4248: 			 } (keys(%$fullname))) {
1.68      ng       4249: 	my ($uname,$udom) = split(/:/,$student);
1.484     albertel 4250: 	$studentTable.=($ptr%2==1 ? &Apache::loncommon::start_data_table_row()
                   4251:                                   : '</td>');
1.126     ng       4252: 	$studentTable.='<td align="right">'.$ptr.'&nbsp;</td>';
1.288     albertel 4253: 	$studentTable.='<td>&nbsp;<label><input type="radio" name="student" value="'.$student.'" /> '
                   4254: 	    .&nameUserString(undef,$$fullname{$student},$uname,$udom)."</label>\n";
1.484     albertel 4255: 	$studentTable.=
                   4256: 	    ($ptr%2 == 0 ? '</td>'.&Apache::loncommon::end_data_table_row() 
                   4257:                          : '');
1.68      ng       4258: 	$ptr++;
                   4259:     }
1.484     albertel 4260:     if ($ptr%2 == 0) {
                   4261: 	$studentTable.='</td><td>&nbsp;</td><td>&nbsp;</td>'.
                   4262: 	    &Apache::loncommon::end_data_table_row();
                   4263:     }
                   4264:     $studentTable.=&Apache::loncommon::end_data_table()."\n";
1.126     ng       4265:     $studentTable.='<input type="button" '.
1.589     bisitz   4266:                    'onclick="javascript:checkPickOne(this.form);" value="'.&mt('Next').' &rarr;" /></form>'."\n";
1.68      ng       4267: 
                   4268:     $request->print($studentTable);
                   4269: 
                   4270:     return '';
                   4271: }
                   4272: 
                   4273: sub getSymbMap {
1.582     raeburn  4274:     my ($map_error) = @_;
1.132     bowersj2 4275:     my $navmap = Apache::lonnavmaps::navmap->new();
1.582     raeburn  4276:     unless (ref($navmap)) {
                   4277:         if (ref($map_error)) {
                   4278:             $$map_error = 'navmap';
                   4279:         }
                   4280:         return;
                   4281:     }
1.68      ng       4282:     my %symbx = ();
                   4283:     my @titles = ();
1.117     bowersj2 4284:     my $minder = 0;
                   4285: 
                   4286:     # Gather every sequence that has problems.
1.240     albertel 4287:     my @sequences = $navmap->retrieveResources(undef, sub { shift->is_map(); },
                   4288: 					       1,0,1);
1.117     bowersj2 4289:     for my $sequence ($navmap->getById('0.0'), @sequences) {
1.241     albertel 4290: 	if ($navmap->hasResource($sequence, sub { shift->is_problem(); }, 0) ) {
1.381     albertel 4291: 	    my $title = $minder.'.'.
                   4292: 		&HTML::Entities::encode($sequence->compTitle(),'"\'&');
                   4293: 	    push(@titles, $title); # minder in case two titles are identical
                   4294: 	    $symbx{$title} = &HTML::Entities::encode($sequence->symb(),'"\'&');
1.117     bowersj2 4295: 	    $minder++;
1.241     albertel 4296: 	}
1.68      ng       4297:     }
                   4298:     return \@titles,\%symbx;
                   4299: }
                   4300: 
1.72      ng       4301: #
                   4302: #--- Displays a page/sequence w/wo problems, w/wo submissions
1.68      ng       4303: sub displayPage {
1.608     www      4304:     my ($request,$symb) = @_;
1.257     albertel 4305:     my $cdom      = $env{"course.$env{'request.course.id'}.domain"};
                   4306:     my $cnum      = $env{"course.$env{'request.course.id'}.num"};
                   4307:     my $getsec    = $env{'form.section'} eq '' ? 'all' : $env{'form.section'};
                   4308:     my $pageTitle = $env{'form.page'};
1.103     albertel 4309:     my ($classlist,undef,$fullname) = &getclasslist($getsec,'1');
1.257     albertel 4310:     my ($uname,$udom) = split(/:/,$env{'form.student'});
                   4311:     my $usec=$classlist->{$env{'form.student'}}[5];
1.168     albertel 4312: 
                   4313:     #need to make sure we have the correct data for later EXT calls, 
                   4314:     #thus invalidate the cache
                   4315:     &Apache::lonnet::devalidatecourseresdata(
1.257     albertel 4316:                  $env{'course.'.$env{'request.course.id'}.'.num'},
                   4317:                  $env{'course.'.$env{'request.course.id'}.'.domain'});
1.168     albertel 4318:     &Apache::lonnet::clear_EXT_cache_status();
                   4319: 
1.103     albertel 4320:     if (!&canview($usec)) {
1.485     albertel 4321: 	$request->print('<span class="LC_warning">'.&mt('Unable to view requested student. ([_1])',$env{'form.student'}).'</span>');
1.103     albertel 4322: 	return;
                   4323:     }
1.398     albertel 4324:     my $result='<h3><span class="LC_info">&nbsp;'.$env{'form.title'}.'</span></h3>';
1.485     albertel 4325:     $result.='<h3>&nbsp;'.&mt('Student: [_1]',&nameUserString(undef,$$fullname{$env{'form.student'}},$uname,$udom)).
1.129     ng       4326: 	'</h3>'."\n";
1.500     albertel 4327:     $env{'form.CODE'} = uc($env{'form.CODE'});
1.501     foxr     4328:     if (&Apache::lonnet::validCODE(uc($env{'form.CODE'}))) {
1.485     albertel 4329: 	$result.='<h3>&nbsp;'.&mt('CODE: [_1]',$env{'form.CODE'}).'</h3>'."\n";
1.382     albertel 4330:     } else {
                   4331: 	delete($env{'form.CODE'});
                   4332:     }
1.71      ng       4333:     &sub_page_js($request);
                   4334:     $request->print($result);
                   4335: 
1.132     bowersj2 4336:     my $navmap = Apache::lonnavmaps::navmap->new();
1.582     raeburn  4337:     unless (ref($navmap)) {
                   4338:         $request->print(&navmap_errormsg());
                   4339:         return;
                   4340:     }
1.257     albertel 4341:     my ($mapUrl, $id, $resUrl)=&Apache::lonnet::decode_symb($env{'form.page'});
1.68      ng       4342:     my $map = $navmap->getResourceByUrl($resUrl); # add to navmaps
1.288     albertel 4343:     if (!$map) {
1.485     albertel 4344: 	$request->print('<span class="LC_warning">'.&mt('Unable to view requested sequence. ([_1])',$resUrl).'</span>');
1.288     albertel 4345: 	return; 
                   4346:     }
1.68      ng       4347:     my $iterator = $navmap->getIterator($map->map_start(),
                   4348: 					$map->map_finish());
                   4349: 
1.71      ng       4350:     my $studentTable='<form action="/adm/grades" method="post" name="gradePage">'."\n".
1.72      ng       4351: 	'<input type="hidden" name="command" value="gradeByPage" />'."\n".
1.257     albertel 4352: 	'<input type="hidden" name="fullname" value="'.$$fullname{$env{'form.student'}}.'" />'."\n".
                   4353: 	'<input type="hidden" name="student" value="'.$env{'form.student'}.'" />'."\n".
1.72      ng       4354: 	'<input type="hidden" name="page"    value="'.$pageTitle.'" />'."\n".
1.257     albertel 4355: 	'<input type="hidden" name="title"   value="'.$env{'form.title'}.'" />'."\n".
1.418     albertel 4356: 	'<input type="hidden" name="symb"    value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
1.613     www      4357: 	'<input type="hidden" name="overRideScore" value="no" />'."\n";
1.71      ng       4358: 
1.382     albertel 4359:     if (defined($env{'form.CODE'})) {
                   4360: 	$studentTable.=
                   4361: 	    '<input type="hidden" name="CODE" value="'.$env{'form.CODE'}.'" />'."\n";
                   4362:     }
1.381     albertel 4363:     my $checkIcon = '<img alt="'.&mt('Check Mark').
1.485     albertel 4364: 	'" src="'.&Apache::loncommon::lonhttpdurl($request->dir_config('lonIconsURL').'/check.gif').'" height="16" border="0" />';
1.71      ng       4365: 
1.594     bisitz   4366:     $studentTable.='&nbsp;<span class="LC_info">'.
                   4367:         &mt('Problems graded correct by the computer are marked with a [_1] symbol.',$checkIcon).
                   4368:         '</span>'."\n".
1.484     albertel 4369: 	&Apache::loncommon::start_data_table().
                   4370: 	&Apache::loncommon::start_data_table_header_row().
                   4371: 	'<th align="center">&nbsp;Prob.&nbsp;</th>'.
1.485     albertel 4372: 	'<th>&nbsp;'.($env{'form.vProb'} eq 'no' ? &mt('Title') : &mt('Problem Text')).'/'.&mt('Grade').'</th>'.
1.484     albertel 4373: 	&Apache::loncommon::end_data_table_header_row();
1.71      ng       4374: 
1.329     albertel 4375:     &Apache::lonxml::clear_problem_counter();
1.196     albertel 4376:     my ($depth,$question,$prob) = (1,1,1);
1.68      ng       4377:     $iterator->next(); # skip the first BEGIN_MAP
                   4378:     my $curRes = $iterator->next(); # for "current resource"
1.101     albertel 4379:     while ($depth > 0) {
1.68      ng       4380:         if($curRes == $iterator->BEGIN_MAP) { $depth++; }
1.100     bowersj2 4381:         if($curRes == $iterator->END_MAP) { $depth--; }
1.68      ng       4382: 
1.385     albertel 4383:         if (ref($curRes) && $curRes->is_problem()) {
1.91      albertel 4384: 	    my $parts = $curRes->parts();
1.68      ng       4385:             my $title = $curRes->compTitle();
1.71      ng       4386: 	    my $symbx = $curRes->symb();
1.484     albertel 4387: 	    $studentTable.=
                   4388: 		&Apache::loncommon::start_data_table_row().
                   4389: 		'<td align="center" valign="top" >'.$prob.
1.485     albertel 4390: 		(scalar(@{$parts}) == 1 ? '' 
                   4391: 		                        : '<br />('.&mt('[_1]&nbsp;parts)',
                   4392: 							scalar(@{$parts}))
                   4393: 		 ).
                   4394: 		 '</td>';
1.71      ng       4395: 	    $studentTable.='<td valign="top">';
1.382     albertel 4396: 	    my %form = ('CODE' => $env{'form.CODE'},);
1.257     albertel 4397: 	    if ($env{'form.vProb'} eq 'yes' ) {
1.144     albertel 4398: 		$studentTable.=&show_problem($request,$symbx,$uname,$udom,1,
1.383     albertel 4399: 					     undef,'both',\%form);
1.71      ng       4400: 	    } else {
1.382     albertel 4401: 		my $companswer = &Apache::loncommon::get_student_answers($symbx,$uname,$udom,$env{'request.course.id'},%form);
1.80      ng       4402: 		$companswer =~ s|<form(.*?)>||g;
                   4403: 		$companswer =~ s|</form>||g;
1.71      ng       4404: #		while ($companswer =~ /(<a href\=\"javascript:newWindow.*?Script Vars<\/a>)/s) { #<a href="javascript:newWindow</a>
1.116     ng       4405: #		    $companswer =~ s/$1/ /ms;
1.326     albertel 4406: #		    $request->print('match='.$1."<br />\n");
1.71      ng       4407: #		}
1.116     ng       4408: #		$companswer =~ s|<table border=\"1\">|<table border=\"0\">|g;
1.539     riegler  4409: 		$studentTable.='&nbsp;<b>'.$title.'</b>&nbsp;<br />&nbsp;<b>'.&mt('Correct answer').':</b><br />'.$companswer;
1.71      ng       4410: 	    }
                   4411: 
1.257     albertel 4412: 	    my %record = &Apache::lonnet::restore($symbx,$env{'request.course.id'},$udom,$uname);
1.125     ng       4413: 
1.257     albertel 4414: 	    if ($env{'form.lastSub'} eq 'datesub') {
1.71      ng       4415: 		if ($record{'version'} eq '') {
1.485     albertel 4416: 		    $studentTable.='<br />&nbsp;<span class="LC_warning">'.&mt('No recorded submission for this problem.').'</span><br />';
1.71      ng       4417: 		} else {
1.116     ng       4418: 		    my %responseType = ();
                   4419: 		    foreach my $partid (@{$parts}) {
1.147     albertel 4420: 			my @responseIds =$curRes->responseIds($partid);
                   4421: 			my @responseType =$curRes->responseType($partid);
                   4422: 			my %responseIds;
                   4423: 			for (my $i=0;$i<=$#responseIds;$i++) {
                   4424: 			    $responseIds{$responseIds[$i]}=$responseType[$i];
                   4425: 			}
                   4426: 			$responseType{$partid} = \%responseIds;
1.116     ng       4427: 		    }
1.148     albertel 4428: 		    $studentTable.= &displaySubByDates($symbx,\%record,$parts,\%responseType,$checkIcon,$uname,$udom);
1.147     albertel 4429: 
1.71      ng       4430: 		}
1.257     albertel 4431: 	    } elsif ($env{'form.lastSub'} eq 'all') {
                   4432: 		my $last = ($env{'form.lastSub'} eq 'last' ? 'last' : '');
1.71      ng       4433: 		$studentTable.=&Apache::loncommon::get_previous_attempt($symbx,$uname,$udom,
1.257     albertel 4434: 									$env{'request.course.id'},
1.71      ng       4435: 									'','.submission');
                   4436:  
                   4437: 	    }
1.103     albertel 4438: 	    if (&canmodify($usec)) {
1.585     bisitz   4439:             $studentTable.=&gradeBox_start();
1.103     albertel 4440: 		foreach my $partid (@{$parts}) {
                   4441: 		    $studentTable.=&gradeBox($request,$symbx,$uname,$udom,$question,$partid,\%record);
                   4442: 		    $studentTable.='<input type="hidden" name="q_'.$question.'" value="'.$partid.'" />'."\n";
                   4443: 		    $question++;
                   4444: 		}
1.585     bisitz   4445:             $studentTable.=&gradeBox_end();
1.196     albertel 4446: 		$prob++;
1.71      ng       4447: 	    }
                   4448: 	    $studentTable.='</td></tr>';
1.68      ng       4449: 
1.103     albertel 4450: 	}
1.68      ng       4451:         $curRes = $iterator->next();
                   4452:     }
                   4453: 
1.589     bisitz   4454:     $studentTable.=
                   4455:         '</table>'."\n".
                   4456:         '<input type="button" value="'.&mt('Save').'" '.
                   4457:         'onclick="javascript:checkSubmitPage(this.form,'.$question.');" />'.
                   4458:         '</form>'."\n";
1.71      ng       4459:     $request->print($studentTable);
                   4460: 
                   4461:     return '';
1.119     ng       4462: }
                   4463: 
                   4464: sub displaySubByDates {
1.148     albertel 4465:     my ($symb,$record,$parts,$responseType,$checkIcon,$uname,$udom) = @_;
1.224     albertel 4466:     my $isCODE=0;
1.335     albertel 4467:     my $isTask = ($symb =~/\.task$/);
1.224     albertel 4468:     if (exists($record->{'resource.CODE'})) { $isCODE=1; }
1.467     albertel 4469:     my $studentTable=&Apache::loncommon::start_data_table().
                   4470: 	&Apache::loncommon::start_data_table_header_row().
                   4471: 	'<th>'.&mt('Date/Time').'</th>'.
                   4472: 	($isCODE?'<th>'.&mt('CODE').'</th>':'').
                   4473: 	'<th>'.&mt('Submission').'</th>'.
                   4474: 	'<th>'.&mt('Status').'</th>'.
                   4475: 	&Apache::loncommon::end_data_table_header_row();
1.119     ng       4476:     my ($version);
                   4477:     my %mark;
1.148     albertel 4478:     my %orders;
1.119     ng       4479:     $mark{'correct_by_student'} = $checkIcon;
1.147     albertel 4480:     if (!exists($$record{'1:timestamp'})) {
1.539     riegler  4481: 	return '<br />&nbsp;<span class="LC_warning">'.&mt('Nothing submitted - no attempts.').'</span><br />';
1.147     albertel 4482:     }
1.335     albertel 4483: 
                   4484:     my $interaction;
1.525     raeburn  4485:     my $no_increment = 1;
1.119     ng       4486:     for ($version=1;$version<=$$record{'version'};$version++) {
1.467     albertel 4487: 	my $timestamp = 
                   4488: 	    &Apache::lonlocal::locallocaltime($$record{$version.':timestamp'});
1.335     albertel 4489: 	if (exists($$record{$version.':resource.0.version'})) {
                   4490: 	    $interaction = $$record{$version.':resource.0.version'};
                   4491: 	}
                   4492: 
                   4493: 	my $where = ($isTask ? "$version:resource.$interaction"
                   4494: 		             : "$version:resource");
1.467     albertel 4495: 	$studentTable.=&Apache::loncommon::start_data_table_row().
                   4496: 	    '<td>'.$timestamp.'</td>';
1.224     albertel 4497: 	if ($isCODE) {
                   4498: 	    $studentTable.='<td>'.$record->{$version.':resource.CODE'}.'</td>';
                   4499: 	}
1.119     ng       4500: 	my @versionKeys = split(/\:/,$$record{$version.':keys'});
                   4501: 	my @displaySub = ();
                   4502: 	foreach my $partid (@{$parts}) {
1.596     raeburn  4503:             my $hidden;
                   4504:             if (($$record{$version.':resource.'.$partid.'.type'} eq 'anonsurvey') ||
                   4505:                 ($$record{$version.':resource.'.$partid.'.type'} eq 'anonsurveycred')) {
                   4506:                 $hidden = 1;
                   4507:             }
1.335     albertel 4508: 	    my @matchKey = ($isTask ? sort(grep /^resource\.\d+\.\Q$partid\E\.award$/,@versionKeys)
                   4509: 			            : sort(grep /^resource\.\Q$partid\E\..*?\.submission$/,@versionKeys));
                   4510: 	    
1.122     ng       4511: #	    next if ($$record{"$version:resource.$partid.solved"} eq '');
1.324     albertel 4512: 	    my $display_part=&get_display_part($partid,$symb);
1.147     albertel 4513: 	    foreach my $matchKey (@matchKey) {
1.198     albertel 4514: 		if (exists($$record{$version.':'.$matchKey}) &&
                   4515: 		    $$record{$version.':'.$matchKey} ne '') {
1.596     raeburn  4516:                     
1.335     albertel 4517: 		    my ($responseId)= ($isTask ? ($matchKey=~ /^resource\.(.*?)\.\Q$partid\E\.award$/)
                   4518: 				               : ($matchKey=~ /^resource\.\Q$partid\E\.(.*?)\.submission$/));
1.577     bisitz   4519:                     $displaySub[0].='<span class="LC_nobreak"';
                   4520:                     $displaySub[0].='<b>'.&mt('Part: [_1]',$display_part).'</b>'
                   4521:                                    .' <span class="LC_internal_info">'
                   4522:                                    .'('.&mt('Part ID: [_1]',$responseId).')'
                   4523:                                    .'</span>'
                   4524:                                    .' <b>';
1.596     raeburn  4525:                     if ($hidden) {
                   4526:                         $displaySub[0].= &mt('Anonymous Survey').'</b>';
                   4527:                     } else {
                   4528: 		        if ($$record{"$where.$partid.tries"} eq '') {
                   4529: 			    $displaySub[0].=&mt('Trial not counted');
                   4530: 		        } else {
                   4531: 			    $displaySub[0].=&mt('Trial: [_1]',
1.467     albertel 4532: 					    $$record{"$where.$partid.tries"});
1.596     raeburn  4533: 		        }
                   4534: 		        my $responseType=($isTask ? 'Task'
1.335     albertel 4535:                                               : $responseType->{$partid}->{$responseId});
1.596     raeburn  4536: 		        if (!exists($orders{$partid})) { $orders{$partid}={}; }
                   4537: 		        if (!exists($orders{$partid}->{$responseId})) {
                   4538: 			    $orders{$partid}->{$responseId}=
                   4539: 			        &get_order($partid,$responseId,$symb,$uname,$udom,
                   4540:                                            $no_increment);
                   4541: 		        }
                   4542: 		        $displaySub[0].='</b></span>'; # /nobreak
                   4543: 		        $displaySub[0].='&nbsp; '.
                   4544: 			    &cleanRecord($$record{$version.':'.$matchKey},$responseType,$symb,$partid,$responseId,$record,$orders{$partid}->{$responseId},"$version:",$uname,$udom).'<br />';
                   4545:                     }
1.147     albertel 4546: 		}
                   4547: 	    }
1.335     albertel 4548: 	    if (exists($$record{"$where.$partid.checkedin"})) {
1.485     albertel 4549: 		$displaySub[1].=&mt('Checked in by [_1] into slot [_2]',
                   4550: 				    $$record{"$where.$partid.checkedin"},
                   4551: 				    $$record{"$where.$partid.checkedin.slot"}).
                   4552: 					'<br />';
1.335     albertel 4553: 	    }
                   4554: 	    if (exists $$record{"$where.$partid.award"}) {
1.485     albertel 4555: 		$displaySub[1].='<b>'.&mt('Part:').'</b>&nbsp;'.$display_part.' &nbsp;'.
1.335     albertel 4556: 		    lc($$record{"$where.$partid.award"}).' '.
                   4557: 		    $mark{$$record{"$where.$partid.solved"}}.
1.147     albertel 4558: 		    '<br />';
                   4559: 	    }
1.335     albertel 4560: 	    if (exists $$record{"$where.$partid.regrader"}) {
                   4561: 		$displaySub[2].=$$record{"$where.$partid.regrader"}.
                   4562: 		    ' (<b>'.&mt('Part').':</b> '.$display_part.')';
                   4563: 	    } elsif ($$record{"$version:resource.$partid.regrader"} =~ /\S/) {
                   4564: 		$displaySub[2].=
                   4565: 		    $$record{"$version:resource.$partid.regrader"}.
1.207     albertel 4566: 		    ' (<b>'.&mt('Part').':</b> '.$display_part.')';
1.147     albertel 4567: 	    }
                   4568: 	}
                   4569: 	# needed because old essay regrader has not parts info
                   4570: 	if (exists $$record{"$version:resource.regrader"}) {
                   4571: 	    $displaySub[2].=$$record{"$version:resource.regrader"};
                   4572: 	}
                   4573: 	$studentTable.='<td>'.$displaySub[0].'&nbsp;</td><td>'.$displaySub[1];
                   4574: 	if ($displaySub[2]) {
1.467     albertel 4575: 	    $studentTable.=&mt('Manually graded by [_1]',$displaySub[2]);
1.147     albertel 4576: 	}
1.467     albertel 4577: 	$studentTable.='&nbsp;</td>'.
                   4578: 	    &Apache::loncommon::end_data_table_row();
1.119     ng       4579:     }
1.467     albertel 4580:     $studentTable.=&Apache::loncommon::end_data_table();
1.119     ng       4581:     return $studentTable;
1.71      ng       4582: }
                   4583: 
                   4584: sub updateGradeByPage {
1.608     www      4585:     my ($request,$symb) = @_;
1.71      ng       4586: 
1.257     albertel 4587:     my $cdom      = $env{"course.$env{'request.course.id'}.domain"};
                   4588:     my $cnum      = $env{"course.$env{'request.course.id'}.num"};
                   4589:     my $getsec    = $env{'form.section'} eq '' ? 'all' : $env{'form.section'};
                   4590:     my $pageTitle = $env{'form.page'};
1.103     albertel 4591:     my ($classlist,undef,$fullname) = &getclasslist($getsec,'1');
1.257     albertel 4592:     my ($uname,$udom) = split(/:/,$env{'form.student'});
                   4593:     my $usec=$classlist->{$env{'form.student'}}[5];
1.103     albertel 4594:     if (!&canmodify($usec)) {
1.526     raeburn  4595: 	$request->print('<span class="LC_warning">'.&mt('Unable to modify requested student ([_1])',$env{'form.student'}).'</span>');
1.103     albertel 4596: 	return;
                   4597:     }
1.398     albertel 4598:     my $result='<h3><span class="LC_info">&nbsp;'.$env{'form.title'}.'</span></h3>';
1.526     raeburn  4599:     $result.='<h3>&nbsp;'.&mt('Student: ').&nameUserString(undef,$env{'form.fullname'},$uname,$udom).
1.129     ng       4600: 	'</h3>'."\n";
1.70      ng       4601: 
1.68      ng       4602:     $request->print($result);
                   4603: 
1.582     raeburn  4604: 
1.132     bowersj2 4605:     my $navmap = Apache::lonnavmaps::navmap->new();
1.582     raeburn  4606:     unless (ref($navmap)) {
                   4607:         $request->print(&navmap_errormsg());
                   4608:         return;
                   4609:     }
1.257     albertel 4610:     my ($mapUrl, $id, $resUrl) = &Apache::lonnet::decode_symb( $env{'form.page'});
1.71      ng       4611:     my $map = $navmap->getResourceByUrl($resUrl); # add to navmaps
1.288     albertel 4612:     if (!$map) {
1.527     raeburn  4613: 	$request->print('<span class="LC_warning">'.&mt('Unable to grade requested sequence ([_1]).',$resUrl).'</span>');
1.288     albertel 4614: 	return; 
                   4615:     }
1.71      ng       4616:     my $iterator = $navmap->getIterator($map->map_start(),
                   4617: 					$map->map_finish());
1.70      ng       4618: 
1.484     albertel 4619:     my $studentTable=
                   4620: 	&Apache::loncommon::start_data_table().
                   4621: 	&Apache::loncommon::start_data_table_header_row().
1.485     albertel 4622: 	'<th align="center">&nbsp;'.&mt('Prob.').'&nbsp;</th>'.
                   4623: 	'<th>&nbsp;'.&mt('Title').'&nbsp;</th>'.
                   4624: 	'<th>&nbsp;'.&mt('Previous Score').'&nbsp;</th>'.
                   4625: 	'<th>&nbsp;'.&mt('New Score').'&nbsp;</th>'.
1.484     albertel 4626: 	&Apache::loncommon::end_data_table_header_row();
1.71      ng       4627: 
                   4628:     $iterator->next(); # skip the first BEGIN_MAP
                   4629:     my $curRes = $iterator->next(); # for "current resource"
1.196     albertel 4630:     my ($depth,$question,$prob,$changeflag)= (1,1,1,0);
1.101     albertel 4631:     while ($depth > 0) {
1.71      ng       4632:         if($curRes == $iterator->BEGIN_MAP) { $depth++; }
1.100     bowersj2 4633:         if($curRes == $iterator->END_MAP) { $depth--; }
1.71      ng       4634: 
1.385     albertel 4635:         if (ref($curRes) && $curRes->is_problem()) {
1.91      albertel 4636: 	    my $parts = $curRes->parts();
1.71      ng       4637:             my $title = $curRes->compTitle();
                   4638: 	    my $symbx = $curRes->symb();
1.484     albertel 4639: 	    $studentTable.=
                   4640: 		&Apache::loncommon::start_data_table_row().
                   4641: 		'<td align="center" valign="top" >'.$prob.
1.485     albertel 4642: 		(scalar(@{$parts}) == 1 ? '' 
1.526     raeburn  4643:                                         : '<br />('.&mt('[quant,_1,&nbsp;part]',scalar(@{$parts}))
                   4644: 		.')').'</td>';
1.71      ng       4645: 	    $studentTable.='<td valign="top">&nbsp;<b>'.$title.'</b>&nbsp;</td>';
                   4646: 
                   4647: 	    my %newrecord=();
                   4648: 	    my @displayPts=();
1.269     raeburn  4649:             my %aggregate = ();
                   4650:             my $aggregateflag = 0;
1.71      ng       4651: 	    foreach my $partid (@{$parts}) {
1.257     albertel 4652: 		my $newpts = $env{'form.GD_BOX'.$question.'_'.$partid};
                   4653: 		my $oldpts = $env{'form.oldpts'.$question.'_'.$partid};
1.71      ng       4654: 
1.257     albertel 4655: 		my $wgt = $env{'form.WGT'.$question.'_'.$partid} != 0 ? 
                   4656: 		    $env{'form.WGT'.$question.'_'.$partid} : 1;
1.71      ng       4657: 		my $partial = $newpts/$wgt;
                   4658: 		my $score;
                   4659: 		if ($partial > 0) {
                   4660: 		    $score = 'correct_by_override';
1.125     ng       4661: 		} elsif ($newpts ne '') { #empty is taken as 0
1.71      ng       4662: 		    $score = 'incorrect_by_override';
                   4663: 		}
1.257     albertel 4664: 		my $dropMenu = $env{'form.GD_SEL'.$question.'_'.$partid};
1.125     ng       4665: 		if ($dropMenu eq 'excused') {
1.71      ng       4666: 		    $partial = '';
                   4667: 		    $score = 'excused';
1.125     ng       4668: 		} elsif ($dropMenu eq 'reset status'
1.257     albertel 4669: 			 && $env{'form.solved'.$question.'_'.$partid} ne '') { #update only if previous record exists
1.125     ng       4670: 		    $newrecord{'resource.'.$partid.'.tries'} = 0;
                   4671: 		    $newrecord{'resource.'.$partid.'.solved'} = '';
                   4672: 		    $newrecord{'resource.'.$partid.'.award'} = '';
                   4673: 		    $newrecord{'resource.'.$partid.'.awarded'} = 0;
1.257     albertel 4674: 		    $newrecord{'resource.'.$partid.'.regrader'} = "$env{'user.name'}:$env{'user.domain'}";
1.125     ng       4675: 		    $changeflag++;
                   4676: 		    $newpts = '';
1.269     raeburn  4677:                     
                   4678:                     my $aggtries =  $env{'form.aggtries'.$question.'_'.$partid};
                   4679:                     my $totaltries = $env{'form.totaltries'.$question.'_'.$partid};
                   4680:                     my $solvedstatus = $env{'form.solved'.$question.'_'.$partid};
                   4681:                     if ($aggtries > 0) {
                   4682:                         &decrement_aggs($symbx,$partid,\%aggregate,$aggtries,$totaltries,$solvedstatus);
                   4683:                         $aggregateflag = 1;
                   4684:                     }
1.71      ng       4685: 		}
1.324     albertel 4686: 		my $display_part=&get_display_part($partid,$curRes->symb());
1.257     albertel 4687: 		my $oldstatus = $env{'form.solved'.$question.'_'.$partid};
1.526     raeburn  4688: 		$displayPts[0].='&nbsp;<b>'.&mt('Part').':</b> '.$display_part.' = '.
1.71      ng       4689: 		    (($oldstatus eq 'excused') ? 'excused' : $oldpts).
1.326     albertel 4690: 		    '&nbsp;<br />';
1.526     raeburn  4691: 		$displayPts[1].='&nbsp;<b>'.&mt('Part').':</b> '.$display_part.' = '.
1.125     ng       4692: 		     (($score eq 'excused') ? 'excused' : $newpts).
1.326     albertel 4693: 		    '&nbsp;<br />';
1.71      ng       4694: 		$question++;
1.380     albertel 4695: 		next if ($dropMenu eq 'reset status' || ($newpts eq $oldpts && $score ne 'excused'));
1.125     ng       4696: 
1.71      ng       4697: 		$newrecord{'resource.'.$partid.'.awarded'}  = $partial if $partial ne '';
1.125     ng       4698: 		$newrecord{'resource.'.$partid.'.solved'}   = $score if $score ne '';
1.257     albertel 4699: 		$newrecord{'resource.'.$partid.'.regrader'} = "$env{'user.name'}:$env{'user.domain'}"
1.125     ng       4700: 		    if (scalar(keys(%newrecord)) > 0);
1.71      ng       4701: 
                   4702: 		$changeflag++;
                   4703: 	    }
                   4704: 	    if (scalar(keys(%newrecord)) > 0) {
1.382     albertel 4705: 		my %record = 
                   4706: 		    &Apache::lonnet::restore($symbx,$env{'request.course.id'},
                   4707: 					     $udom,$uname);
                   4708: 
                   4709: 		if (&Apache::lonnet::validCODE($env{'form.CODE'})) {
                   4710: 		    $newrecord{'resource.CODE'} = $env{'form.CODE'};
                   4711: 		} elsif (&Apache::lonnet::validCODE($record{'resource.CODE'})) {
                   4712: 		    $newrecord{'resource.CODE'} = '';
                   4713: 		}
1.257     albertel 4714: 		&Apache::lonnet::cstore(\%newrecord,$symbx,$env{'request.course.id'},
1.71      ng       4715: 					$udom,$uname);
1.382     albertel 4716: 		%record = &Apache::lonnet::restore($symbx,
                   4717: 						   $env{'request.course.id'},
                   4718: 						   $udom,$uname);
1.380     albertel 4719: 		&check_and_remove_from_queue($parts,\%record,undef,$symbx,
                   4720: 					     $cdom,$cnum,$udom,$uname);
1.71      ng       4721: 	    }
1.380     albertel 4722: 	    
1.269     raeburn  4723:             if ($aggregateflag) {
                   4724:                 &Apache::lonnet::cinc('nohist_resourcetracker',\%aggregate,
                   4725:                       $env{'course.'.$env{'request.course.id'}.'.domain'},
                   4726:                       $env{'course.'.$env{'request.course.id'}.'.num'});
                   4727:             }
1.125     ng       4728: 
1.71      ng       4729: 	    $studentTable.='<td valign="top">'.$displayPts[0].'</td>'.
                   4730: 		'<td valign="top">'.$displayPts[1].'</td>'.
1.484     albertel 4731: 		&Apache::loncommon::end_data_table_row();
1.68      ng       4732: 
1.196     albertel 4733: 	    $prob++;
1.68      ng       4734: 	}
1.71      ng       4735:         $curRes = $iterator->next();
1.68      ng       4736:     }
1.98      albertel 4737: 
1.484     albertel 4738:     $studentTable.=&Apache::loncommon::end_data_table();
1.526     raeburn  4739:     my $grademsg=($changeflag == 0 ? &mt('No score was changed or updated.') :
                   4740: 		  &mt('The scores were changed for [quant,_1,problem].',
                   4741: 		  $changeflag));
1.76      ng       4742:     $request->print($grademsg.$studentTable);
1.68      ng       4743: 
1.70      ng       4744:     return '';
                   4745: }
                   4746: 
1.72      ng       4747: #-------- end of section for handling grading by page/sequence ---------
                   4748: #
                   4749: #-------------------------------------------------------------------
                   4750: 
1.581     www      4751: #-------------------- Bubblesheet (Scantron) Grading -------------------
1.75      albertel 4752: #
                   4753: #------ start of section for handling grading by page/sequence ---------
                   4754: 
1.423     albertel 4755: =pod
                   4756: 
                   4757: =head1 Bubble sheet grading routines
                   4758: 
1.424     albertel 4759:   For this documentation:
                   4760: 
                   4761:    'scanline' refers to the full line of characters
                   4762:    from the file that we are parsing that represents one entire sheet
                   4763: 
                   4764:    'bubble line' refers to the data
                   4765:    representing the line of bubbles that are on the physical bubble sheet
                   4766: 
                   4767: 
                   4768: The overall process is that a scanned in bubble sheet data is uploaded
                   4769: into a course. When a user wants to grade, they select a
                   4770: sequence/folder of resources, a file of bubble sheet info, and pick
                   4771: one of the predefined configurations for what each scanline looks
                   4772: like.
                   4773: 
                   4774: Next each scanline is checked for any errors of either 'missing
1.435     foxr     4775: bubbles' (it's an error because it may have been mis-scanned
1.424     albertel 4776: because too light bubbling), 'double bubble' (each bubble line should
                   4777: have no more that one letter picked), invalid or duplicated CODE,
1.556     weissno  4778: invalid student/employee ID
1.424     albertel 4779: 
                   4780: If the CODE option is used that determines the randomization of the
1.556     weissno  4781: homework problems, either way the student/employee ID is looked up into a
1.424     albertel 4782: username:domain.
                   4783: 
                   4784: During the validation phase the instructor can choose to skip scanlines. 
                   4785: 
1.435     foxr     4786: After the validation phase, there are now 3 bubble sheet files
1.424     albertel 4787: 
                   4788:   scantron_original_filename (unmodified original file)
                   4789:   scantron_corrected_filename (file where the corrected information has replaced the original information)
                   4790:   scantron_skipped_filename (contains the exact text of scanlines that where skipped)
                   4791: 
                   4792: Also there is a separate hash nohist_scantrondata that contains extra
                   4793: correction information that isn't representable in the bubble sheet
                   4794: file (see &scantron_getfile() for more information)
                   4795: 
                   4796: After all scanlines are either valid, marked as valid or skipped, then
                   4797: foreach line foreach problem in the picked sequence, an ssi request is
                   4798: made that simulates a user submitting their selected letter(s) against
                   4799: the homework problem.
1.423     albertel 4800: 
                   4801: =over 4
                   4802: 
                   4803: 
                   4804: 
                   4805: =item defaultFormData
                   4806: 
                   4807:   Returns html hidden inputs used to hold context/default values.
                   4808: 
                   4809:  Arguments:
                   4810:   $symb - $symb of the current resource 
                   4811: 
                   4812: =cut
1.422     foxr     4813: 
1.81      albertel 4814: sub defaultFormData {
1.324     albertel 4815:     my ($symb)=@_;
1.613     www      4816:     return '<input type="hidden" name="symb"    value="'.&Apache::lonenc::check_encrypt($symb).'" />';
1.81      albertel 4817: }
                   4818: 
1.447     foxr     4819: 
1.423     albertel 4820: =pod 
                   4821: 
                   4822: =item getSequenceDropDown
                   4823: 
                   4824:    Return html dropdown of possible sequences to grade
                   4825:  
                   4826:  Arguments:
1.582     raeburn  4827:    $symb - $symb of the current resource
                   4828:    $map_error - ref to scalar which will container error if
                   4829:                 $navmap object is unavailable in &getSymbMap().
1.423     albertel 4830: 
                   4831: =cut
1.422     foxr     4832: 
1.75      albertel 4833: sub getSequenceDropDown {
1.582     raeburn  4834:     my ($symb,$map_error)=@_;
1.75      albertel 4835:     my $result='<select name="selectpage">'."\n";
1.582     raeburn  4836:     my ($titles,$symbx) = &getSymbMap($map_error);
                   4837:     if (ref($map_error)) {
                   4838:         return if ($$map_error);
                   4839:     }
1.137     albertel 4840:     my ($curpage)=&Apache::lonnet::decode_symb($symb); 
1.75      albertel 4841:     my $ctr=0;
                   4842:     foreach (@$titles) {
                   4843: 	my ($minder,$showtitle) = ($_ =~ /(\d+)\.(.*)/);
                   4844: 	$result.='<option value="'.$$symbx{$_}.'" '.
1.401     albertel 4845: 	    ($$symbx{$_} =~ /$curpage$/ ? 'selected="selected"' : '').
1.75      albertel 4846: 	    '>'.$showtitle.'</option>'."\n";
                   4847: 	$ctr++;
                   4848:     }
                   4849:     $result.= '</select>';
                   4850:     return $result;
                   4851: }
                   4852: 
1.495     albertel 4853: my %bubble_lines_per_response;     # no. bubble lines for each response.
1.554     raeburn  4854:                                    # key is zero-based index - 0, 1, 2 ...
1.495     albertel 4855: 
                   4856: my %first_bubble_line;             # First bubble line no. for each bubble.
                   4857: 
1.509     raeburn  4858: my %subdivided_bubble_lines;       # no. bubble lines for optionresponse, 
                   4859:                                    # matchresponse or rankresponse, where 
                   4860:                                    # an individual response can have multiple 
                   4861:                                    # lines
1.503     raeburn  4862: 
                   4863: my %responsetype_per_response;     # responsetype for each response
                   4864: 
1.495     albertel 4865: # Save and restore the bubble lines array to the form env.
                   4866: 
                   4867: 
                   4868: sub save_bubble_lines {
                   4869:     foreach my $line (keys(%bubble_lines_per_response)) {
                   4870: 	$env{"form.scantron.bubblelines.$line"}  = $bubble_lines_per_response{$line};
                   4871: 	$env{"form.scantron.first_bubble_line.$line"} =
                   4872: 	    $first_bubble_line{$line};
1.503     raeburn  4873:         $env{"form.scantron.sub_bubblelines.$line"} = 
                   4874:             $subdivided_bubble_lines{$line};
                   4875:         $env{"form.scantron.responsetype.$line"} =
                   4876:             $responsetype_per_response{$line};
1.495     albertel 4877:     }
                   4878: }
                   4879: 
                   4880: 
                   4881: sub restore_bubble_lines {
                   4882:     my $line = 0;
                   4883:     %bubble_lines_per_response = ();
                   4884:     while ($env{"form.scantron.bubblelines.$line"}) {
                   4885: 	my $value = $env{"form.scantron.bubblelines.$line"};
                   4886: 	$bubble_lines_per_response{$line} = $value;
                   4887: 	$first_bubble_line{$line}  =
                   4888: 	    $env{"form.scantron.first_bubble_line.$line"};
1.503     raeburn  4889:         $subdivided_bubble_lines{$line} =
                   4890:             $env{"form.scantron.sub_bubblelines.$line"};
                   4891:         $responsetype_per_response{$line} =
                   4892:             $env{"form.scantron.responsetype.$line"};
1.495     albertel 4893: 	$line++;
                   4894:     }
                   4895: }
                   4896: 
                   4897: #  Given the parsed scanline, get the response for 
                   4898: #  'answer' number n:
                   4899: 
                   4900: sub get_response_bubbles {
                   4901:     my ($parsed_line, $response)  = @_;
                   4902: 
                   4903:     my $bubble_line = $first_bubble_line{$response-1} +1;
                   4904:     my $bubble_lines= $bubble_lines_per_response{$response-1};
                   4905:     
                   4906:     my $selected = "";
                   4907: 
                   4908:     for (my $bline = 0; $bline < $bubble_lines; $bline++) {
                   4909: 	$selected .= $$parsed_line{"scantron.$bubble_line.answer"}.":";
                   4910: 	$bubble_line++;
                   4911:     }
                   4912:     return $selected;
                   4913: }
1.423     albertel 4914: 
                   4915: =pod 
                   4916: 
                   4917: =item scantron_filenames
                   4918: 
                   4919:    Returns a list of the scantron files in the current course 
                   4920: 
                   4921: =cut
1.422     foxr     4922: 
1.202     albertel 4923: sub scantron_filenames {
1.257     albertel 4924:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
                   4925:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
1.517     raeburn  4926:     my $getpropath = 1;
1.157     albertel 4927:     my @files=&Apache::lonnet::dirlist('userfiles',$cdom,$cname,
1.517     raeburn  4928:                                        $getpropath);
1.202     albertel 4929:     my @possiblenames;
1.201     albertel 4930:     foreach my $filename (sort(@files)) {
1.157     albertel 4931: 	($filename)=split(/&/,$filename);
                   4932: 	if ($filename!~/^scantron_orig_/) { next ; }
                   4933: 	$filename=~s/^scantron_orig_//;
1.202     albertel 4934: 	push(@possiblenames,$filename);
                   4935:     }
                   4936:     return @possiblenames;
                   4937: }
                   4938: 
1.423     albertel 4939: =pod 
                   4940: 
                   4941: =item scantron_uploads
                   4942: 
                   4943:    Returns  html drop-down list of scantron files in current course.
                   4944: 
                   4945:  Arguments:
                   4946:    $file2grade - filename to set as selected in the dropdown
                   4947: 
                   4948: =cut
1.422     foxr     4949: 
1.202     albertel 4950: sub scantron_uploads {
1.209     ng       4951:     my ($file2grade) = @_;
1.202     albertel 4952:     my $result=	'<select name="scantron_selectfile">';
                   4953:     $result.="<option></option>";
                   4954:     foreach my $filename (sort(&scantron_filenames())) {
1.401     albertel 4955: 	$result.="<option".($filename eq $file2grade ? ' selected="selected"':'').">$filename</option>\n";
1.81      albertel 4956:     }
                   4957:     $result.="</select>";
                   4958:     return $result;
                   4959: }
                   4960: 
1.423     albertel 4961: =pod 
                   4962: 
                   4963: =item scantron_scantab
                   4964: 
                   4965:   Returns html drop down of the scantron formats in the scantronformat.tab
                   4966:   file.
                   4967: 
                   4968: =cut
1.422     foxr     4969: 
1.82      albertel 4970: sub scantron_scantab {
                   4971:     my $result='<select name="scantron_format">'."\n";
1.191     albertel 4972:     $result.='<option></option>'."\n";
1.518     raeburn  4973:     my @lines = &get_scantronformat_file();
                   4974:     if (@lines > 0) {
                   4975:         foreach my $line (@lines) {
                   4976:             next if (($line =~ /^\#/) || ($line eq ''));
                   4977: 	    my ($name,$descrip)=split(/:/,$line);
                   4978: 	    $result.='<option value="'.$name.'">'.$descrip.'</option>'."\n";
                   4979:         }
1.82      albertel 4980:     }
                   4981:     $result.='</select>'."\n";
1.518     raeburn  4982:     return $result;
                   4983: }
                   4984: 
                   4985: =pod
                   4986: 
                   4987: =item get_scantronformat_file
                   4988: 
                   4989:   Returns an array containing lines from the scantron format file for
                   4990:   the domain of the course.
                   4991: 
                   4992:   If a url for a custom.tab file is listed in domain's configuration.db, 
                   4993:   lines are from this file.
                   4994: 
                   4995:   Otherwise, if a default.tab has been published in RES space by the 
                   4996:   domainconfig user, lines are from this file.
                   4997: 
                   4998:   Otherwise, fall back to getting lines from the legacy file on the
1.519     raeburn  4999:   local server:  /home/httpd/lonTabs/default_scantronformat.tab    
1.82      albertel 5000: 
1.518     raeburn  5001: =cut
                   5002: 
                   5003: sub get_scantronformat_file {
                   5004:     my $cdom= $env{'course.'.$env{'request.course.id'}.'.domain'};
                   5005:     my %domconfig = &Apache::lonnet::get_dom('configuration',['scantron'],$cdom);
                   5006:     my $gottab = 0;
                   5007:     my @lines;
                   5008:     if (ref($domconfig{'scantron'}) eq 'HASH') {
                   5009:         if ($domconfig{'scantron'}{'scantronformat'} ne '') {
                   5010:             my $formatfile = &Apache::lonnet::getfile($Apache::lonnet::perlvar{'lonDocRoot'}.$domconfig{'scantron'}{'scantronformat'});
                   5011:             if ($formatfile ne '-1') {
                   5012:                 @lines = split("\n",$formatfile,-1);
                   5013:                 $gottab = 1;
                   5014:             }
                   5015:         }
                   5016:     }
                   5017:     if (!$gottab) {
                   5018:         my $confname = $cdom.'-domainconfig';
                   5019:         my $default = $Apache::lonnet::perlvar{'lonDocRoot'}.'/res/'.$cdom.'/'.$confname.'/default.tab';
                   5020:         my $formatfile =  &Apache::lonnet::getfile($default);
                   5021:         if ($formatfile ne '-1') {
                   5022:             @lines = split("\n",$formatfile,-1);
                   5023:             $gottab = 1;
                   5024:         }
                   5025:     }
                   5026:     if (!$gottab) {
1.519     raeburn  5027:         my @domains = &Apache::lonnet::current_machine_domains();
                   5028:         if (grep(/^\Q$cdom\E$/,@domains)) {
                   5029:             my $fh=Apache::File->new($Apache::lonnet::perlvar{'lonTabDir'}.'/scantronformat.tab');
                   5030:             @lines = <$fh>;
                   5031:             close($fh);
                   5032:         } else {
                   5033:             my $fh=Apache::File->new($Apache::lonnet::perlvar{'lonTabDir'}.'/default_scantronformat.tab');
                   5034:             @lines = <$fh>;
                   5035:             close($fh);
                   5036:         }
1.518     raeburn  5037:     }
                   5038:     return @lines;
1.82      albertel 5039: }
                   5040: 
1.423     albertel 5041: =pod 
                   5042: 
                   5043: =item scantron_CODElist
                   5044: 
                   5045:   Returns html drop down of the saved CODE lists from current course,
                   5046:   generated from earlier printings.
                   5047: 
                   5048: =cut
1.422     foxr     5049: 
1.186     albertel 5050: sub scantron_CODElist {
1.257     albertel 5051:     my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   5052:     my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
1.186     albertel 5053:     my @names=&Apache::lonnet::getkeys('CODEs',$cdom,$cnum);
                   5054:     my $namechoice='<option></option>';
1.225     albertel 5055:     foreach my $name (sort {uc($a) cmp uc($b)} @names) {
1.191     albertel 5056: 	if ($name =~ /^error: 2 /) { next; }
1.278     albertel 5057: 	if ($name =~ /^type\0/) { next; }
1.186     albertel 5058: 	$namechoice.='<option value="'.$name.'">'.$name.'</option>';
                   5059:     }
                   5060:     $namechoice='<select name="scantron_CODElist">'.$namechoice.'</select>';
                   5061:     return $namechoice;
                   5062: }
                   5063: 
1.423     albertel 5064: =pod 
                   5065: 
                   5066: =item scantron_CODEunique
                   5067: 
                   5068:   Returns the html for "Each CODE to be used once" radio.
                   5069: 
                   5070: =cut
1.422     foxr     5071: 
1.186     albertel 5072: sub scantron_CODEunique {
1.532     bisitz   5073:     my $result='<span class="LC_nobreak">
1.272     albertel 5074:                  <label><input type="radio" name="scantron_CODEunique"
1.423     albertel 5075:                         value="yes" checked="checked" />'.&mt('Yes').' </label>
1.381     albertel 5076:                 </span>
1.532     bisitz   5077:                 <span class="LC_nobreak">
1.272     albertel 5078:                  <label><input type="radio" name="scantron_CODEunique"
1.423     albertel 5079:                         value="no" />'.&mt('No').' </label>
1.381     albertel 5080:                 </span>';
1.186     albertel 5081:     return $result;
                   5082: }
1.423     albertel 5083: 
                   5084: =pod 
                   5085: 
                   5086: =item scantron_selectphase
                   5087: 
                   5088:   Generates the initial screen to start the bubble sheet process.
                   5089:   Allows for - starting a grading run.
1.424     albertel 5090:              - downloading existing scan data (original, corrected
1.423     albertel 5091:                                                 or skipped info)
                   5092: 
                   5093:              - uploading new scan data
                   5094: 
                   5095:  Arguments:
                   5096:   $r          - The Apache request object
                   5097:   $file2grade - name of the file that contain the scanned data to score
                   5098: 
                   5099: =cut
1.186     albertel 5100: 
1.75      albertel 5101: sub scantron_selectphase {
1.608     www      5102:     my ($r,$file2grade,$symb) = @_;
1.75      albertel 5103:     if (!$symb) {return '';}
1.582     raeburn  5104:     my $map_error;
                   5105:     my $sequence_selector=&getSequenceDropDown($symb,\$map_error);
                   5106:     if ($map_error) {
                   5107:         $r->print('<br />'.&navmap_errormsg().'<br />');
                   5108:         return;
                   5109:     }
1.324     albertel 5110:     my $default_form_data=&defaultFormData($symb);
1.209     ng       5111:     my $file_selector=&scantron_uploads($file2grade);
1.82      albertel 5112:     my $format_selector=&scantron_scantab();
1.186     albertel 5113:     my $CODE_selector=&scantron_CODElist();
                   5114:     my $CODE_unique=&scantron_CODEunique();
1.75      albertel 5115:     my $result;
1.422     foxr     5116: 
1.513     foxr     5117:     $ssi_error = 0;
                   5118: 
1.606     wenzelju 5119:     if (&Apache::lonnet::allowed('usc',$env{'request.role.domain'}) ||
                   5120:         &Apache::lonnet::allowed('usc',$env{'request.course.id'})) {
                   5121: 
                   5122: 	# Chunk of form to prompt for a scantron file upload.
                   5123: 
                   5124:         $r->print('
                   5125:     <br />
                   5126:     '.&Apache::loncommon::start_data_table('LC_scantron_action').'
                   5127:        '.&Apache::loncommon::start_data_table_header_row().'
                   5128:             <th>
                   5129:               &nbsp;'.&mt('Specify a bubblesheet data file to upload.').'
                   5130:             </th>
                   5131:        '.&Apache::loncommon::end_data_table_header_row().'
                   5132:        '.&Apache::loncommon::start_data_table_row().'
                   5133:             <td>
                   5134: ');
1.608     www      5135:     my $default_form_data=&defaultFormData($symb);
1.606     wenzelju 5136:     my $cdom= $env{'course.'.$env{'request.course.id'}.'.domain'};
                   5137:     my $cnum= $env{'course.'.$env{'request.course.id'}.'.num'};
                   5138:     $r->print(&Apache::lonhtmlcommon::scripttag('
                   5139:     function checkUpload(formname) {
                   5140: 	if (formname.upfile.value == "") {
                   5141: 	    alert("'.&mt('Please use the browse button to select a file from your local directory.').'");
                   5142: 	    return false;
                   5143: 	}
                   5144: 	formname.submit();
                   5145:     }'));
                   5146:     $r->print('
                   5147:               <form enctype="multipart/form-data" action="/adm/grades" name="rules" method="post">
                   5148:                 '.$default_form_data.'
                   5149:                 <input name="courseid" type="hidden" value="'.$cnum.'" />
                   5150:                 <input name="domainid" type="hidden" value="'.$cdom.'" />
                   5151:                 <input name="command" value="scantronupload_save" type="hidden" />
                   5152:                 '.&mt('File to upload: [_1]','<input type="file" name="upfile" size="50" />').'
                   5153:                 <br />
                   5154:                 <input type="button" onclick="javascript:checkUpload(this.form);" value="'.&mt('Upload Bubblesheet Data').'" />
                   5155:               </form>
                   5156: ');
                   5157: 
                   5158:         $r->print('
                   5159:             </td>
                   5160:        '.&Apache::loncommon::end_data_table_row().'
                   5161:        '.&Apache::loncommon::end_data_table().'
                   5162: ');
                   5163:     }
                   5164: 
1.422     foxr     5165:     # Chunk of form to prompt for a file to grade and how:
                   5166: 
1.489     albertel 5167:     $result.= '
                   5168:     <br />
                   5169:     <form method="post" enctype="multipart/form-data" action="/adm/grades" name="scantron_process">
                   5170:     <input type="hidden" name="command" value="scantron_warning" />
                   5171:     '.$default_form_data.'
                   5172:     '.&Apache::loncommon::start_data_table('LC_scantron_action').'
                   5173:        '.&Apache::loncommon::start_data_table_header_row().'
                   5174:             <th colspan="2">
1.492     albertel 5175:               &nbsp;'.&mt('Specify file and which Folder/Sequence to grade').'
1.489     albertel 5176:             </th>
                   5177:        '.&Apache::loncommon::end_data_table_header_row().'
                   5178:        '.&Apache::loncommon::start_data_table_row().'
1.492     albertel 5179:             <td> '.&mt('Sequence to grade:').' </td><td> '.$sequence_selector.' </td>
1.489     albertel 5180:        '.&Apache::loncommon::end_data_table_row().'
                   5181:        '.&Apache::loncommon::start_data_table_row().'
1.572     www      5182:             <td> '.&mt('Filename of bubblesheet data file:').' </td><td> '.$file_selector.' </td>
1.489     albertel 5183:        '.&Apache::loncommon::end_data_table_row().'
                   5184:        '.&Apache::loncommon::start_data_table_row().'
1.572     www      5185:             <td> '.&mt('Format of bubblesheet data file:').' </td><td> '.$format_selector.' </td>
1.489     albertel 5186:        '.&Apache::loncommon::end_data_table_row().'
                   5187:        '.&Apache::loncommon::start_data_table_row().'
1.492     albertel 5188:             <td> '.&mt('Saved CODEs to validate against:').' </td><td> '.$CODE_selector.' </td>
1.489     albertel 5189:        '.&Apache::loncommon::end_data_table_row().'
                   5190:        '.&Apache::loncommon::start_data_table_row().'
1.492     albertel 5191:             <td> '.&mt('Each CODE is only to be used once:').'</td><td> '.$CODE_unique.' </td>
1.489     albertel 5192:        '.&Apache::loncommon::end_data_table_row().'
                   5193:        '.&Apache::loncommon::start_data_table_row().'
1.492     albertel 5194: 	    <td> '.&mt('Options:').' </td>
1.187     albertel 5195:             <td>
1.492     albertel 5196: 	       <label><input type="checkbox" name="scantron_options_redo" value="redo_skipped"/> '.&mt('Do only previously skipped records').'</label> <br />
                   5197:                <label><input type="checkbox" name="scantron_options_ignore" value="ignore_corrections"/> '.&mt('Remove all existing corrections').'</label> <br />
                   5198:                <label><input type="checkbox" name="scantron_options_hidden" value="ignore_hidden"/> '.&mt('Skip hidden resources when grading').'</label>
1.187     albertel 5199: 	    </td>
1.489     albertel 5200:        '.&Apache::loncommon::end_data_table_row().'
                   5201:        '.&Apache::loncommon::start_data_table_row().'
1.174     albertel 5202:             <td colspan="2">
1.572     www      5203:               <input type="submit" value="'.&mt('Grading: Validate Bubblesheet Records').'" />
1.162     albertel 5204:             </td>
1.489     albertel 5205:        '.&Apache::loncommon::end_data_table_row().'
                   5206:     '.&Apache::loncommon::end_data_table().'
                   5207:     </form>
                   5208: ';
1.162     albertel 5209:    
                   5210:     $r->print($result);
                   5211: 
1.422     foxr     5212: 
                   5213: 
                   5214:     # Chunk of the form that prompts to view a scoring office file,
                   5215:     # corrected file, skipped records in a file.
                   5216: 
1.489     albertel 5217:     $r->print('
                   5218:    <br />
                   5219:    <form action="/adm/grades" name="scantron_download">
                   5220:      '.$default_form_data.'
                   5221:      <input type="hidden" name="command" value="scantron_download" />
                   5222:      '.&Apache::loncommon::start_data_table('LC_scantron_action').'
                   5223:        '.&Apache::loncommon::start_data_table_header_row().'
                   5224:               <th>
1.492     albertel 5225:                 &nbsp;'.&mt('Download a scoring office file').'
1.489     albertel 5226:               </th>
                   5227:        '.&Apache::loncommon::end_data_table_header_row().'
                   5228:        '.&Apache::loncommon::start_data_table_row().'
1.492     albertel 5229:               <td> '.&mt('Filename of scoring office file: [_1]',$file_selector).' 
1.489     albertel 5230:                 <br />
1.492     albertel 5231:                 <input type="submit" value="'.&mt('Download: Show List of Associated Files').'" />
1.489     albertel 5232:        '.&Apache::loncommon::end_data_table_row().'
                   5233:      '.&Apache::loncommon::end_data_table().'
                   5234:    </form>
                   5235:    <br />
                   5236: ');
1.162     albertel 5237: 
1.457     banghart 5238:     &Apache::lonpickcode::code_list($r,2);
1.523     raeburn  5239: 
1.528     raeburn  5240:     $r->print('<br /><form method="post" name="checkscantron">'.
1.523     raeburn  5241:              $default_form_data."\n".
                   5242:              &Apache::loncommon::start_data_table('LC_scantron_action')."\n".
                   5243:              &Apache::loncommon::start_data_table_header_row()."\n".
                   5244:              '<th colspan="2">
1.572     www      5245:               &nbsp;'.&mt('Review bubblesheet data and submissions for a previously graded folder/sequence')."\n".
1.523     raeburn  5246:              '</th>'."\n".
                   5247:               &Apache::loncommon::end_data_table_header_row()."\n".
                   5248:               &Apache::loncommon::start_data_table_row()."\n".
                   5249:               '<td> '.&mt('Graded folder/sequence:').' </td>'."\n".
                   5250:               '<td> '.$sequence_selector.' </td>'.
                   5251:               &Apache::loncommon::end_data_table_row()."\n".
                   5252:               &Apache::loncommon::start_data_table_row()."\n".
                   5253:               '<td> '.&mt('Filename of scoring office file:').' </td>'."\n".
                   5254:               '<td> '.$file_selector.' </td>'."\n".
                   5255:               &Apache::loncommon::end_data_table_row()."\n".
                   5256:               &Apache::loncommon::start_data_table_row()."\n".
                   5257:               '<td> '.&mt('Format of data file:').' </td>'."\n".
                   5258:               '<td> '.$format_selector.' </td>'."\n".
                   5259:               &Apache::loncommon::end_data_table_row()."\n".
                   5260:               &Apache::loncommon::start_data_table_row()."\n".
1.557     raeburn  5261:               '<td> '.&mt('Options').' </td>'."\n".
                   5262:               '<td> <label><input type="checkbox" name="scantron_options_hidden" value="ignore_hidden"/> '.&mt('Skip hidden resources').'</label></td>'.
                   5263:               &Apache::loncommon::end_data_table_row()."\n".
                   5264:               &Apache::loncommon::start_data_table_row()."\n".
1.523     raeburn  5265:               '<td colspan="2">'."\n".
                   5266:               '<input type="hidden" name="command" value="checksubmissions" />'."\n".
1.575     www      5267:               '<input type="submit" value="'.&mt('Review Bubblesheet Data and Submission Records').'" />'."\n".
1.523     raeburn  5268:               '</td>'."\n".
                   5269:               &Apache::loncommon::end_data_table_row()."\n".
                   5270:               &Apache::loncommon::end_data_table()."\n".
                   5271:               '</form><br />');
                   5272:     return;
1.75      albertel 5273: }
                   5274: 
1.423     albertel 5275: =pod
                   5276: 
                   5277: =item get_scantron_config
                   5278: 
                   5279:    Parse and return the scantron configuration line selected as a
                   5280:    hash of configuration file fields.
                   5281: 
                   5282:  Arguments:
                   5283:     which - the name of the configuration to parse from the file.
                   5284: 
                   5285: 
                   5286:  Returns:
                   5287:             If the named configuration is not in the file, an empty
                   5288:             hash is returned.
                   5289:     a hash with the fields
                   5290:       name         - internal name for the this configuration setup
                   5291:       description  - text to display to operator that describes this config
                   5292:       CODElocation - if 0 or the string 'none'
                   5293:                           - no CODE exists for this config
                   5294:                      if -1 || the string 'letter'
                   5295:                           - a CODE exists for this config and is
                   5296:                             a string of letters
                   5297:                      Unsupported value (but planned for future support)
                   5298:                           if a positive integer
                   5299:                                - The CODE exists as the first n items from
                   5300:                                  the question section of the form
                   5301:                           if the string 'number'
                   5302:                                - The CODE exists for this config and is
                   5303:                                  a string of numbers
                   5304:       CODEstart   - (only matter if a CODE exists) column in the line where
                   5305:                      the CODE starts
                   5306:       CODElength  - length of the CODE
1.573     bisitz   5307:       IDstart     - column where the student/employee ID starts
1.556     weissno  5308:       IDlength    - length of the student/employee ID info
1.423     albertel 5309:       Qstart      - column where the information from the bubbled
                   5310:                     'questions' start
                   5311:       Qlength     - number of columns comprising a single bubble line from
                   5312:                     the sheet. (usually either 1 or 10)
1.424     albertel 5313:       Qon         - either a single character representing the character used
1.423     albertel 5314:                     to signal a bubble was chosen in the positional setup, or
                   5315:                     the string 'letter' if the letter of the chosen bubble is
                   5316:                     in the final, or 'number' if a number representing the
                   5317:                     chosen bubble is in the file (1->A 0->J)
1.424     albertel 5318:       Qoff        - the character used to represent that a bubble was
                   5319:                     left blank
1.423     albertel 5320:       PaperID     - if the scanning process generates a unique number for each
                   5321:                     sheet scanned the column that this ID number starts in
                   5322:       PaperIDlength - number of columns that comprise the unique ID number
                   5323:                       for the sheet of paper
1.424     albertel 5324:       FirstName   - column that the first name starts in
1.423     albertel 5325:       FirstNameLength - number of columns that the first name spans
                   5326:  
                   5327:       LastName    - column that the last name starts in
                   5328:       LastNameLength - number of columns that the last name spans
                   5329: 
                   5330: =cut
1.422     foxr     5331: 
1.82      albertel 5332: sub get_scantron_config {
                   5333:     my ($which) = @_;
1.518     raeburn  5334:     my @lines = &get_scantronformat_file();
1.82      albertel 5335:     my %config;
1.157     albertel 5336:     #FIXME probably should move to XML it has already gotten a bit much now
1.518     raeburn  5337:     foreach my $line (@lines) {
1.82      albertel 5338: 	my ($name,$descrip)=split(/:/,$line);
                   5339: 	if ($name ne $which ) { next; }
                   5340: 	chomp($line);
                   5341: 	my @config=split(/:/,$line);
                   5342: 	$config{'name'}=$config[0];
                   5343: 	$config{'description'}=$config[1];
                   5344: 	$config{'CODElocation'}=$config[2];
                   5345: 	$config{'CODEstart'}=$config[3];
                   5346: 	$config{'CODElength'}=$config[4];
                   5347: 	$config{'IDstart'}=$config[5];
                   5348: 	$config{'IDlength'}=$config[6];
                   5349: 	$config{'Qstart'}=$config[7];
1.497     foxr     5350:  	$config{'Qlength'}=$config[8];
1.82      albertel 5351: 	$config{'Qoff'}=$config[9];
                   5352: 	$config{'Qon'}=$config[10];
1.157     albertel 5353: 	$config{'PaperID'}=$config[11];
                   5354: 	$config{'PaperIDlength'}=$config[12];
                   5355: 	$config{'FirstName'}=$config[13];
                   5356: 	$config{'FirstNamelength'}=$config[14];
                   5357: 	$config{'LastName'}=$config[15];
                   5358: 	$config{'LastNamelength'}=$config[16];
1.82      albertel 5359: 	last;
                   5360:     }
                   5361:     return %config;
                   5362: }
                   5363: 
1.423     albertel 5364: =pod 
                   5365: 
                   5366: =item username_to_idmap
                   5367: 
1.556     weissno  5368:     creates a hash keyed by student/employee ID with values of the corresponding
1.423     albertel 5369:     student username:domain.
                   5370: 
                   5371:   Arguments:
                   5372: 
                   5373:     $classlist - reference to the class list hash. This is a hash
                   5374:                  keyed by student name:domain  whose elements are references
1.424     albertel 5375:                  to arrays containing various chunks of information
1.423     albertel 5376:                  about the student. (See loncoursedata for more info).
                   5377: 
                   5378:   Returns
                   5379:     %idmap - the constructed hash
                   5380: 
                   5381: =cut
                   5382: 
1.82      albertel 5383: sub username_to_idmap {
                   5384:     my ($classlist)= @_;
                   5385:     my %idmap;
                   5386:     foreach my $student (keys(%$classlist)) {
                   5387: 	$idmap{$classlist->{$student}->[&Apache::loncoursedata::CL_ID]}=
                   5388: 	    $student;
                   5389:     }
                   5390:     return %idmap;
                   5391: }
1.423     albertel 5392: 
                   5393: =pod
                   5394: 
1.424     albertel 5395: =item scantron_fixup_scanline
1.423     albertel 5396: 
                   5397:    Process a requested correction to a scanline.
                   5398: 
                   5399:   Arguments:
                   5400:     $scantron_config   - hash from &get_scantron_config()
                   5401:     $scan_data         - hash of correction information 
                   5402:                           (see &scantron_getfile())
                   5403:     $line              - existing scanline
                   5404:     $whichline         - line number of the passed in scanline
                   5405:     $field             - type of change to process 
                   5406:                          (either 
1.573     bisitz   5407:                           'ID'     -> correct the student/employee ID
1.423     albertel 5408:                           'CODE'   -> correct the CODE
                   5409:                           'answer' -> fixup the submitted answers)
                   5410:     
                   5411:    $args               - hash of additional info,
                   5412:                           - 'ID' 
                   5413:                                'newid' -> studentID to use in replacement
1.424     albertel 5414:                                           of existing one
1.423     albertel 5415:                           - 'CODE' 
                   5416:                                'CODE_ignore_dup' - set to true if duplicates
                   5417:                                                    should be ignored.
                   5418: 	                       'CODE' - is new code or 'use_unfound'
1.424     albertel 5419:                                         if the existing unfound code should
1.423     albertel 5420:                                         be used as is
                   5421:                           - 'answer'
                   5422:                                'response' - new answer or 'none' if blank
                   5423:                                'question' - the bubble line to change
1.503     raeburn  5424:                                'questionnum' - the question identifier,
                   5425:                                                may include subquestion. 
1.423     albertel 5426: 
                   5427:   Returns:
                   5428:     $line - the modified scanline
                   5429: 
                   5430:   Side effects: 
                   5431:     $scan_data - may be updated
                   5432: 
                   5433: =cut
                   5434: 
1.82      albertel 5435: 
1.157     albertel 5436: sub scantron_fixup_scanline {
                   5437:     my ($scantron_config,$scan_data,$line,$whichline,$field,$args)=@_;
                   5438:     if ($field eq 'ID') {
                   5439: 	if (length($args->{'newid'}) > $$scantron_config{'IDlength'}) {
1.186     albertel 5440: 	    return ($line,1,'New value too large');
1.157     albertel 5441: 	}
                   5442: 	if (length($args->{'newid'}) < $$scantron_config{'IDlength'}) {
                   5443: 	    $args->{'newid'}=sprintf('%-'.$$scantron_config{'IDlength'}.'s',
                   5444: 				     $args->{'newid'});
                   5445: 	}
                   5446: 	substr($line,$$scantron_config{'IDstart'}-1,
                   5447: 	       $$scantron_config{'IDlength'})=$args->{'newid'};
                   5448: 	if ($args->{'newid'}=~/^\s*$/) {
                   5449: 	    &scan_data($scan_data,"$whichline.user",
                   5450: 		       $args->{'username'}.':'.$args->{'domain'});
                   5451: 	}
1.186     albertel 5452:     } elsif ($field eq 'CODE') {
1.192     albertel 5453: 	if ($args->{'CODE_ignore_dup'}) {
                   5454: 	    &scan_data($scan_data,"$whichline.CODE_ignore_dup",'1');
                   5455: 	}
                   5456: 	&scan_data($scan_data,"$whichline.useCODE",'1');
                   5457: 	if ($args->{'CODE'} ne 'use_unfound') {
1.191     albertel 5458: 	    if (length($args->{'CODE'}) > $$scantron_config{'CODElength'}) {
                   5459: 		return ($line,1,'New CODE value too large');
                   5460: 	    }
                   5461: 	    if (length($args->{'CODE'}) < $$scantron_config{'CODElength'}) {
                   5462: 		$args->{'CODE'}=sprintf('%-'.$$scantron_config{'CODElength'}.'s',$args->{'CODE'});
                   5463: 	    }
                   5464: 	    substr($line,$$scantron_config{'CODEstart'}-1,
                   5465: 		   $$scantron_config{'CODElength'})=$args->{'CODE'};
1.186     albertel 5466: 	}
1.157     albertel 5467:     } elsif ($field eq 'answer') {
1.497     foxr     5468: 	my $length=$scantron_config->{'Qlength'};
1.157     albertel 5469: 	my $off=$scantron_config->{'Qoff'};
                   5470: 	my $on=$scantron_config->{'Qon'};
1.497     foxr     5471: 	my $answer=${off}x$length;
                   5472: 	if ($args->{'response'} eq 'none') {
                   5473: 	    &scan_data($scan_data,
1.503     raeburn  5474: 		       "$whichline.no_bubble.".$args->{'questionnum'},'1');
1.497     foxr     5475: 	} else {
                   5476: 	    if ($on eq 'letter') {
                   5477: 		my @alphabet=('A'..'Z');
                   5478: 		$answer=$alphabet[$args->{'response'}];
                   5479: 	    } elsif ($on eq 'number') {
                   5480: 		$answer=$args->{'response'}+1;
                   5481: 		if ($answer == 10) { $answer = '0'; }
1.274     albertel 5482: 	    } else {
1.497     foxr     5483: 		substr($answer,$args->{'response'},1)=$on;
1.274     albertel 5484: 	    }
1.497     foxr     5485: 	    &scan_data($scan_data,
1.503     raeburn  5486: 		       "$whichline.no_bubble.".$args->{'questionnum'},undef,'1');
1.157     albertel 5487: 	}
1.497     foxr     5488: 	my $where=$length*($args->{'question'}-1)+$scantron_config->{'Qstart'};
                   5489: 	substr($line,$where-1,$length)=$answer;
1.157     albertel 5490:     }
                   5491:     return $line;
                   5492: }
1.423     albertel 5493: 
                   5494: =pod
                   5495: 
                   5496: =item scan_data
                   5497: 
                   5498:     Edit or look up  an item in the scan_data hash.
                   5499: 
                   5500:   Arguments:
                   5501:     $scan_data  - The hash (see scantron_getfile)
                   5502:     $key        - shorthand of the key to edit (actual key is
1.424     albertel 5503:                   scantronfilename_key).
1.423     albertel 5504:     $data        - New value of the hash entry.
                   5505:     $delete      - If true, the entry is removed from the hash.
                   5506: 
                   5507:   Returns:
                   5508:     The new value of the hash table field (undefined if deleted).
                   5509: 
                   5510: =cut
                   5511: 
                   5512: 
1.157     albertel 5513: sub scan_data {
                   5514:     my ($scan_data,$key,$value,$delete)=@_;
1.257     albertel 5515:     my $filename=$env{'form.scantron_selectfile'};
1.157     albertel 5516:     if (defined($value)) {
                   5517: 	$scan_data->{$filename.'_'.$key} = $value;
                   5518:     }
                   5519:     if ($delete) { delete($scan_data->{$filename.'_'.$key}); }
                   5520:     return $scan_data->{$filename.'_'.$key};
                   5521: }
1.423     albertel 5522: 
1.495     albertel 5523: # ----- These first few routines are general use routines.----
                   5524: 
                   5525: # Return the number of occurences of a pattern in a string.
                   5526: 
                   5527: sub occurence_count {
                   5528:     my ($string, $pattern) = @_;
                   5529: 
                   5530:     my @matches = ($string =~ /$pattern/g);
                   5531: 
                   5532:     return scalar(@matches);
                   5533: }
                   5534: 
                   5535: 
                   5536: # Take a string known to have digits and convert all the
                   5537: # digits into letters in the range J,A..I.
                   5538: 
                   5539: sub digits_to_letters {
                   5540:     my ($input) = @_;
                   5541: 
                   5542:     my @alphabet = ('J', 'A'..'I');
                   5543: 
                   5544:     my @input    = split(//, $input);
                   5545:     my $output ='';
                   5546:     for (my $i = 0; $i < scalar(@input); $i++) {
                   5547: 	if ($input[$i] =~ /\d/) {
                   5548: 	    $output .= $alphabet[$input[$i]];
                   5549: 	} else {
                   5550: 	    $output .= $input[$i];
                   5551: 	}
                   5552:     }
                   5553:     return $output;
                   5554: }
                   5555: 
1.423     albertel 5556: =pod 
                   5557: 
                   5558: =item scantron_parse_scanline
                   5559: 
                   5560:   Decodes a scanline from the selected scantron file
                   5561: 
                   5562:  Arguments:
                   5563:     line             - The text of the scantron file line to process
                   5564:     whichline        - Line number
                   5565:     scantron_config  - Hash describing the format of the scantron lines.
                   5566:     scan_data        - Hash of extra information about the scanline
                   5567:                        (see scantron_getfile for more information)
                   5568:     just_header      - True if should not process question answers but only
                   5569:                        the stuff to the left of the answers.
                   5570:  Returns:
                   5571:    Hash containing the result of parsing the scanline
                   5572: 
                   5573:    Keys are all proceeded by the string 'scantron.'
                   5574: 
                   5575:        CODE    - the CODE in use for this scanline
                   5576:        useCODE - 1 if the CODE is invalid but it usage has been forced
                   5577:                  by the operator
                   5578:        CODE_ignore_dup - 1 if the CODE is a duplicated use when unique
                   5579:                             CODEs were selected, but the usage has been
                   5580:                             forced by the operator
1.556     weissno  5581:        ID  - student/employee ID
1.423     albertel 5582:        PaperID - if used, the ID number printed on the sheet when the 
                   5583:                  paper was scanned
                   5584:        FirstName - first name from the sheet
                   5585:        LastName  - last name from the sheet
                   5586: 
                   5587:      if just_header was not true these key may also exist
                   5588: 
1.447     foxr     5589:        missingerror - a list of bubble ranges that are considered to be answers
                   5590:                       to a single question that don't have any bubbles filled in.
                   5591:                       Of the form questionnumber:firstbubblenumber:count.
                   5592:        doubleerror  - a list of bubble ranges that are considered to be answers
                   5593:                       to a single question that have more than one bubble filled in.
                   5594:                       Of the form questionnumber::firstbubblenumber:count
                   5595:    
                   5596:                 In the above, count is the number of bubble responses in the
                   5597:                 input line needed to represent the possible answers to the question.
                   5598:                 e.g. a radioresponse with 15 choices in an answer sheet with 10 choices
                   5599:                 per line would have count = 2.
                   5600: 
1.423     albertel 5601:        maxquest     - the number of the last bubble line that was parsed
                   5602: 
                   5603:        (<number> starts at 1)
                   5604:        <number>.answer - zero or more letters representing the selected
                   5605:                          letters from the scanline for the bubble line 
                   5606:                          <number>.
                   5607:                          if blank there was either no bubble or there where
                   5608:                          multiple bubbles, (consult the keys missingerror and
                   5609:                          doubleerror if this is an error condition)
                   5610: 
                   5611: =cut
                   5612: 
1.82      albertel 5613: sub scantron_parse_scanline {
1.423     albertel 5614:     my ($line,$whichline,$scantron_config,$scan_data,$just_header)=@_;
1.470     foxr     5615: 
1.82      albertel 5616:     my %record;
1.550     raeburn  5617:     my $lastpos = $env{'form.scantron_maxbubble'}*$$scantron_config{'Qlength'};
                   5618:     my $questions=substr($line,$$scantron_config{'Qstart'}-1,$lastpos);  # Answers
1.422     foxr     5619:     my $data=substr($line,0,$$scantron_config{'Qstart'}-1);     # earlier stuff
1.278     albertel 5620:     if (!($$scantron_config{'CODElocation'} eq 0 ||
                   5621: 	  $$scantron_config{'CODElocation'} eq 'none')) {
                   5622: 	if ($$scantron_config{'CODElocation'} < 0 ||
                   5623: 	    $$scantron_config{'CODElocation'} eq 'letter' ||
                   5624: 	    $$scantron_config{'CODElocation'} eq 'number') {
1.191     albertel 5625: 	    $record{'scantron.CODE'}=substr($data,
                   5626: 					    $$scantron_config{'CODEstart'}-1,
1.83      albertel 5627: 					    $$scantron_config{'CODElength'});
1.191     albertel 5628: 	    if (&scan_data($scan_data,"$whichline.useCODE")) {
                   5629: 		$record{'scantron.useCODE'}=1;
                   5630: 	    }
1.192     albertel 5631: 	    if (&scan_data($scan_data,"$whichline.CODE_ignore_dup")) {
                   5632: 		$record{'scantron.CODE_ignore_dup'}=1;
                   5633: 	    }
1.82      albertel 5634: 	} else {
                   5635: 	    #FIXME interpret first N questions
                   5636: 	}
                   5637:     }
1.83      albertel 5638:     $record{'scantron.ID'}=substr($data,$$scantron_config{'IDstart'}-1,
                   5639: 				  $$scantron_config{'IDlength'});
1.157     albertel 5640:     $record{'scantron.PaperID'}=
                   5641: 	substr($data,$$scantron_config{'PaperID'}-1,
                   5642: 	       $$scantron_config{'PaperIDlength'});
                   5643:     $record{'scantron.FirstName'}=
                   5644: 	substr($data,$$scantron_config{'FirstName'}-1,
                   5645: 	       $$scantron_config{'FirstNamelength'});
                   5646:     $record{'scantron.LastName'}=
                   5647: 	substr($data,$$scantron_config{'LastName'}-1,
                   5648: 	       $$scantron_config{'LastNamelength'});
1.423     albertel 5649:     if ($just_header) { return \%record; }
1.194     albertel 5650: 
1.82      albertel 5651:     my @alphabet=('A'..'Z');
                   5652:     my $questnum=0;
1.447     foxr     5653:     my $ansnum  =1;		# Multiple 'answer lines'/question.
                   5654: 
1.470     foxr     5655:     chomp($questions);		# Get rid of any trailing \n.
                   5656:     $questions =~ s/\r$//;      # Get rid of trailing \r too (MAC or Win uploads).
                   5657:     while (length($questions)) {
1.447     foxr     5658: 	my $answers_needed = $bubble_lines_per_response{$questnum};
1.503     raeburn  5659:         my $answer_length  = ($$scantron_config{'Qlength'} * $answers_needed)
                   5660:                              || 1;
                   5661:         $questnum++;
                   5662:         my $quest_id = $questnum;
                   5663:         my $currentquest = substr($questions,0,$answer_length);
                   5664:         $questions       = substr($questions,$answer_length);
                   5665:         if (length($currentquest) < $answer_length) { next; }
                   5666: 
                   5667:         if ($subdivided_bubble_lines{$questnum-1} =~ /,/) {
                   5668:             my $subquestnum = 1;
                   5669:             my $subquestions = $currentquest;
                   5670:             my @subanswers_needed = 
                   5671:                 split(/,/,$subdivided_bubble_lines{$questnum-1});  
                   5672:             foreach my $subans (@subanswers_needed) {
                   5673:                 my $subans_length =
                   5674:                     ($$scantron_config{'Qlength'} * $subans)  || 1;
                   5675:                 my $currsubquest = substr($subquestions,0,$subans_length);
                   5676:                 $subquestions   = substr($subquestions,$subans_length);
                   5677:                 $quest_id = "$questnum.$subquestnum";
                   5678:                 if (($$scantron_config{'Qon'} eq 'letter') ||
                   5679:                     ($$scantron_config{'Qon'} eq 'number')) {
                   5680:                     $ansnum = &scantron_validator_lettnum($ansnum, 
                   5681:                         $questnum,$quest_id,$subans,$currsubquest,$whichline,
                   5682:                         \@alphabet,\%record,$scantron_config,$scan_data);
                   5683:                 } else {
                   5684:                     $ansnum = &scantron_validator_positional($ansnum,
                   5685:                         $questnum,$quest_id,$subans,$currsubquest,$whichline,                        \@alphabet,\%record,$scantron_config,$scan_data);
                   5686:                 }
                   5687:                 $subquestnum ++;
                   5688:             }
                   5689:         } else {
                   5690:             if (($$scantron_config{'Qon'} eq 'letter') ||
                   5691:                 ($$scantron_config{'Qon'} eq 'number')) {
                   5692:                 $ansnum = &scantron_validator_lettnum($ansnum,$questnum,
                   5693:                     $quest_id,$answers_needed,$currentquest,$whichline,
                   5694:                     \@alphabet,\%record,$scantron_config,$scan_data);
                   5695:             } else {
                   5696:                 $ansnum = &scantron_validator_positional($ansnum,$questnum,
                   5697:                     $quest_id,$answers_needed,$currentquest,$whichline,
                   5698:                     \@alphabet,\%record,$scantron_config,$scan_data);
                   5699:             }
                   5700:         }
                   5701:     }
                   5702:     $record{'scantron.maxquest'}=$questnum;
                   5703:     return \%record;
                   5704: }
1.447     foxr     5705: 
1.503     raeburn  5706: sub scantron_validator_lettnum {
                   5707:     my ($ansnum,$questnum,$quest_id,$answers_needed,$currquest,$whichline,
                   5708:         $alphabet,$record,$scantron_config,$scan_data) = @_;
                   5709: 
                   5710:     # Qon 'letter' implies for each slot in currquest we have:
                   5711:     #    ? or * for doubles, a letter in A-Z for a bubble, and
                   5712:     #    about anything else (esp. a value of Qoff) for missing
                   5713:     #    bubbles.
                   5714:     #
                   5715:     # Qon 'number' implies each slot gives a digit that indexes the
                   5716:     #    bubbles filled, or Qoff, or a non-number for unbubbled lines,
                   5717:     #    and * or ? for double bubbles on a single line.
                   5718:     #
1.447     foxr     5719: 
1.503     raeburn  5720:     my $matchon;
                   5721:     if ($$scantron_config{'Qon'} eq 'letter') {
                   5722:         $matchon = '[A-Z]';
                   5723:     } elsif ($$scantron_config{'Qon'} eq 'number') {
                   5724:         $matchon = '\d';
                   5725:     }
                   5726:     my $occurrences = 0;
                   5727:     if (($responsetype_per_response{$questnum-1} eq 'essayresponse') ||
                   5728:         ($responsetype_per_response{$questnum-1} eq 'formularesponse') ||
1.510     raeburn  5729:         ($responsetype_per_response{$questnum-1} eq 'stringresponse') ||
                   5730:         ($responsetype_per_response{$questnum-1} eq 'imageresponse') ||
                   5731:         ($responsetype_per_response{$questnum-1} eq 'reactionresponse') ||
                   5732:         ($responsetype_per_response{$questnum-1} eq 'organicresponse')) {
1.503     raeburn  5733:         my @singlelines = split('',$currquest);
                   5734:         foreach my $entry (@singlelines) {
                   5735:             $occurrences = &occurence_count($entry,$matchon);
                   5736:             if ($occurrences > 1) {
                   5737:                 last;
                   5738:             }
                   5739:         } 
                   5740:     } else {
                   5741:         $occurrences = &occurence_count($currquest,$matchon); 
                   5742:     }
                   5743:     if (($currquest =~ /\?/ || $currquest =~ /\*/) || ($occurrences > 1)) {
                   5744:         push(@{$record->{'scantron.doubleerror'}},$quest_id);
                   5745:         for (my $ans=0; $ans<$answers_needed; $ans++) {
                   5746:             my $bubble = substr($currquest,$ans,1);
                   5747:             if ($bubble =~ /$matchon/ ) {
                   5748:                 if ($$scantron_config{'Qon'} eq 'number') {
                   5749:                     if ($bubble == 0) {
                   5750:                         $bubble = 10; 
                   5751:                     }
                   5752:                     $record->{"scantron.$ansnum.answer"} = 
                   5753:                         $alphabet->[$bubble-1];
                   5754:                 } else {
                   5755:                     $record->{"scantron.$ansnum.answer"} = $bubble;
                   5756:                 }
                   5757:             } else {
                   5758:                 $record->{"scantron.$ansnum.answer"}='';
                   5759:             }
                   5760:             $ansnum++;
                   5761:         }
                   5762:     } elsif (!defined($currquest)
                   5763:             || (&occurence_count($currquest, $$scantron_config{'Qoff'}) == length($currquest))
                   5764:             || (&occurence_count($currquest,$matchon) == 0)) {
                   5765:         for (my $ans=0; $ans<$answers_needed; $ans++ ) {
                   5766:             $record->{"scantron.$ansnum.answer"}='';
                   5767:             $ansnum++;
                   5768:         }
                   5769:         if (!&scan_data($scan_data,"$whichline.no_bubble.$quest_id")) {
                   5770:             push(@{$record->{'scantron.missingerror'}},$quest_id);
                   5771:         }
                   5772:     } else {
                   5773:         if ($$scantron_config{'Qon'} eq 'number') {
                   5774:             $currquest = &digits_to_letters($currquest);            
                   5775:         }
                   5776:         for (my $ans=0; $ans<$answers_needed; $ans++) {
                   5777:             my $bubble = substr($currquest,$ans,1);
                   5778:             $record->{"scantron.$ansnum.answer"} = $bubble;
                   5779:             $ansnum++;
                   5780:         }
                   5781:     }
                   5782:     return $ansnum;
                   5783: }
1.447     foxr     5784: 
1.503     raeburn  5785: sub scantron_validator_positional {
                   5786:     my ($ansnum,$questnum,$quest_id,$answers_needed,$currquest,
                   5787:         $whichline,$alphabet,$record,$scantron_config,$scan_data) = @_;
1.447     foxr     5788: 
1.503     raeburn  5789:     # Otherwise there's a positional notation;
                   5790:     # each bubble line requires Qlength items, and there are filled in
                   5791:     # bubbles for each case where there 'Qon' characters.
                   5792:     #
1.447     foxr     5793: 
1.503     raeburn  5794:     my @array=split($$scantron_config{'Qon'},$currquest,-1);
1.447     foxr     5795: 
1.503     raeburn  5796:     # If the split only gives us one element.. the full length of the
                   5797:     # answer string, no bubbles are filled in:
1.447     foxr     5798: 
1.507     raeburn  5799:     if ($answers_needed eq '') {
                   5800:         return;
                   5801:     }
                   5802: 
1.503     raeburn  5803:     if (length($array[0]) eq $$scantron_config{'Qlength'}*$answers_needed) {
                   5804:         for (my $ans=0; $ans<$answers_needed; $ans++ ) {
                   5805:             $record->{"scantron.$ansnum.answer"}='';
                   5806:             $ansnum++;
                   5807:         }
                   5808:         if (!&scan_data($scan_data,"$whichline.no_bubble.$quest_id")) {
                   5809:             push(@{$record->{"scantron.missingerror"}},$quest_id);
                   5810:         }
                   5811:     } elsif (scalar(@array) == 2) {
                   5812:         my $location = length($array[0]);
                   5813:         my $line_num = int($location / $$scantron_config{'Qlength'});
                   5814:         my $bubble   = $alphabet->[$location % $$scantron_config{'Qlength'}];
                   5815:         for (my $ans=0; $ans<$answers_needed; $ans++) {
                   5816:             if ($ans eq $line_num) {
                   5817:                 $record->{"scantron.$ansnum.answer"} = $bubble;
                   5818:             } else {
                   5819:                 $record->{"scantron.$ansnum.answer"} = ' ';
                   5820:             }
                   5821:             $ansnum++;
                   5822:          }
                   5823:     } else {
                   5824:         #  If there's more than one instance of a bubble character
                   5825:         #  That's a double bubble; with positional notation we can
                   5826:         #  record all the bubbles filled in as well as the
                   5827:         #  fact this response consists of multiple bubbles.
                   5828:         #
                   5829:         if (($responsetype_per_response{$questnum-1} eq 'essayresponse') ||
                   5830:             ($responsetype_per_response{$questnum-1} eq 'formularesponse') ||
1.510     raeburn  5831:             ($responsetype_per_response{$questnum-1} eq 'stringresponse') ||
                   5832:             ($responsetype_per_response{$questnum-1} eq 'imageresponse') ||
                   5833:             ($responsetype_per_response{$questnum-1} eq 'reactionresponse') ||
                   5834:             ($responsetype_per_response{$questnum-1} eq 'organicresponse')) {
1.503     raeburn  5835:             my $doubleerror = 0;
                   5836:             while (($currquest >= $$scantron_config{'Qlength'}) && 
                   5837:                    (!$doubleerror)) {
                   5838:                my $currline = substr($currquest,0,$$scantron_config{'Qlength'});
                   5839:                $currquest = substr($currquest,$$scantron_config{'Qlength'});
                   5840:                my @currarray = split($$scantron_config{'Qon'},$currline,-1);
                   5841:                if (length(@currarray) > 2) {
                   5842:                    $doubleerror = 1;
                   5843:                } 
                   5844:             }
                   5845:             if ($doubleerror) {
                   5846:                 push(@{$record->{'scantron.doubleerror'}},$quest_id);
                   5847:             }
                   5848:         } else {
                   5849:             push(@{$record->{'scantron.doubleerror'}},$quest_id);
                   5850:         }
                   5851:         my $item = $ansnum;
                   5852:         for (my $ans=0; $ans<$answers_needed; $ans++) {
                   5853:             $record->{"scantron.$item.answer"} = '';
                   5854:             $item ++;
                   5855:         }
1.447     foxr     5856: 
1.503     raeburn  5857:         my @ans=@array;
                   5858:         my $i=0;
                   5859:         my $increment = 0;
                   5860:         while ($#ans) {
                   5861:             $i+=length($ans[0]) + $increment;
                   5862:             my $line   = int($i/$$scantron_config{'Qlength'} + $ansnum);
                   5863:             my $bubble = $i%$$scantron_config{'Qlength'};
                   5864:             $record->{"scantron.$line.answer"}.=$alphabet->[$bubble];
                   5865:             shift(@ans);
                   5866:             $increment = 1;
                   5867:         }
                   5868:         $ansnum += $answers_needed;
1.82      albertel 5869:     }
1.503     raeburn  5870:     return $ansnum;
1.82      albertel 5871: }
                   5872: 
1.423     albertel 5873: =pod
                   5874: 
                   5875: =item scantron_add_delay
                   5876: 
                   5877:    Adds an error message that occurred during the grading phase to a
                   5878:    queue of messages to be shown after grading pass is complete
                   5879: 
                   5880:  Arguments:
1.424     albertel 5881:    $delayqueue  - arrary ref of hash ref of error messages
1.423     albertel 5882:    $scanline    - the scanline that caused the error
                   5883:    $errormesage - the error message
                   5884:    $errorcode   - a numeric code for the error
                   5885: 
                   5886:  Side Effects:
1.424     albertel 5887:    updates the $delayqueue to have a new hash ref of the error
1.423     albertel 5888: 
                   5889: =cut
                   5890: 
1.82      albertel 5891: sub scantron_add_delay {
1.140     albertel 5892:     my ($delayqueue,$scanline,$errormessage,$errorcode)=@_;
                   5893:     push(@$delayqueue,
                   5894: 	 {'line' => $scanline, 'emsg' => $errormessage,
                   5895: 	  'ecode' => $errorcode }
                   5896: 	 );
1.82      albertel 5897: }
                   5898: 
1.423     albertel 5899: =pod
                   5900: 
                   5901: =item scantron_find_student
                   5902: 
1.424     albertel 5903:    Finds the username for the current scanline
                   5904: 
                   5905:   Arguments:
                   5906:    $scantron_record - hash result from scantron_parse_scanline
                   5907:    $scan_data       - hash of correction information 
                   5908:                       (see &scantron_getfile() form more information)
                   5909:    $idmap           - hash from &username_to_idmap()
                   5910:    $line            - number of current scanline
                   5911:  
                   5912:   Returns:
                   5913:    Either 'username:domain' or undef if unknown
                   5914: 
1.423     albertel 5915: =cut
                   5916: 
1.82      albertel 5917: sub scantron_find_student {
1.157     albertel 5918:     my ($scantron_record,$scan_data,$idmap,$line)=@_;
1.83      albertel 5919:     my $scanID=$$scantron_record{'scantron.ID'};
1.157     albertel 5920:     if ($scanID =~ /^\s*$/) {
                   5921:  	return &scan_data($scan_data,"$line.user");
                   5922:     }
1.83      albertel 5923:     foreach my $id (keys(%$idmap)) {
1.157     albertel 5924:  	if (lc($id) eq lc($scanID)) {
                   5925:  	    return $$idmap{$id};
                   5926:  	}
1.83      albertel 5927:     }
                   5928:     return undef;
                   5929: }
                   5930: 
1.423     albertel 5931: =pod
                   5932: 
                   5933: =item scantron_filter
                   5934: 
1.424     albertel 5935:    Filter sub for lonnavmaps, filters out hidden resources if ignore
                   5936:    hidden resources was selected
                   5937: 
1.423     albertel 5938: =cut
                   5939: 
1.83      albertel 5940: sub scantron_filter {
                   5941:     my ($curres)=@_;
1.331     albertel 5942: 
                   5943:     if (ref($curres) && $curres->is_problem()) {
                   5944: 	# if the user has asked to not have either hidden
                   5945: 	# or 'randomout' controlled resources to be graded
                   5946: 	# don't include them
                   5947: 	if ($env{'form.scantron_options_hidden'} eq 'ignore_hidden'
                   5948: 	    && $curres->randomout) {
                   5949: 	    return 0;
                   5950: 	}
1.83      albertel 5951: 	return 1;
                   5952:     }
                   5953:     return 0;
1.82      albertel 5954: }
                   5955: 
1.423     albertel 5956: =pod
                   5957: 
                   5958: =item scantron_process_corrections
                   5959: 
1.424     albertel 5960:    Gets correction information out of submitted form data and corrects
                   5961:    the scanline
                   5962: 
1.423     albertel 5963: =cut
                   5964: 
1.157     albertel 5965: sub scantron_process_corrections {
                   5966:     my ($r) = @_;
1.257     albertel 5967:     my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
1.157     albertel 5968:     my ($scanlines,$scan_data)=&scantron_getfile();
                   5969:     my $classlist=&Apache::loncoursedata::get_classlist();
1.257     albertel 5970:     my $which=$env{'form.scantron_line'};
1.200     albertel 5971:     my $line=&scantron_get_line($scanlines,$scan_data,$which);
1.157     albertel 5972:     my ($skip,$err,$errmsg);
1.257     albertel 5973:     if ($env{'form.scantron_skip_record'}) {
1.157     albertel 5974: 	$skip=1;
1.257     albertel 5975:     } elsif ($env{'form.scantron_corrections'} =~ /^(duplicate|incorrect)ID$/) {
                   5976: 	my $newstudent=$env{'form.scantron_username'}.':'.
                   5977: 	    $env{'form.scantron_domain'};
1.157     albertel 5978: 	my $newid=$classlist->{$newstudent}->[&Apache::loncoursedata::CL_ID];
                   5979: 	($line,$err,$errmsg)=
                   5980: 	    &scantron_fixup_scanline(\%scantron_config,$scan_data,$line,$which,
                   5981: 				     'ID',{'newid'=>$newid,
1.257     albertel 5982: 				    'username'=>$env{'form.scantron_username'},
                   5983: 				    'domain'=>$env{'form.scantron_domain'}});
                   5984:     } elsif ($env{'form.scantron_corrections'} =~ /^(duplicate|incorrect)CODE$/) {
                   5985: 	my $resolution=$env{'form.scantron_CODE_resolution'};
1.190     albertel 5986: 	my $newCODE;
1.192     albertel 5987: 	my %args;
1.190     albertel 5988: 	if      ($resolution eq 'use_unfound') {
1.191     albertel 5989: 	    $newCODE='use_unfound';
1.190     albertel 5990: 	} elsif ($resolution eq 'use_found') {
1.257     albertel 5991: 	    $newCODE=$env{'form.scantron_CODE_selectedvalue'};
1.190     albertel 5992: 	} elsif ($resolution eq 'use_typed') {
1.257     albertel 5993: 	    $newCODE=$env{'form.scantron_CODE_newvalue'};
1.194     albertel 5994: 	} elsif ($resolution =~ /^use_closest_(\d+)/) {
1.257     albertel 5995: 	    $newCODE=$env{"form.scantron_CODE_closest_$1"};
1.190     albertel 5996: 	}
1.257     albertel 5997: 	if ($env{'form.scantron_corrections'} eq 'duplicateCODE') {
1.192     albertel 5998: 	    $args{'CODE_ignore_dup'}=1;
                   5999: 	}
                   6000: 	$args{'CODE'}=$newCODE;
1.186     albertel 6001: 	($line,$err,$errmsg)=
                   6002: 	    &scantron_fixup_scanline(\%scantron_config,$scan_data,$line,$which,
1.192     albertel 6003: 				     'CODE',\%args);
1.257     albertel 6004:     } elsif ($env{'form.scantron_corrections'} =~ /^(missing|double)bubble$/) {
                   6005: 	foreach my $question (split(',',$env{'form.scantron_questions'})) {
1.157     albertel 6006: 	    ($line,$err,$errmsg)=
                   6007: 		&scantron_fixup_scanline(\%scantron_config,$scan_data,$line,
                   6008: 					 $which,'answer',
                   6009: 					 { 'question'=>$question,
1.503     raeburn  6010: 		      		   'response'=>$env{"form.scantron_correct_Q_$question"},
                   6011:                                    'questionnum'=>$env{"form.scantron_questionnum_Q_$question"}});
1.157     albertel 6012: 	    if ($err) { last; }
                   6013: 	}
                   6014:     }
                   6015:     if ($err) {
1.398     albertel 6016: 	$r->print("<span class=\"LC_warning\">Unable to accept last correction, an error occurred :$errmsg:</span>");
1.157     albertel 6017:     } else {
1.200     albertel 6018: 	&scantron_put_line($scanlines,$scan_data,$which,$line,$skip);
1.157     albertel 6019: 	&scantron_putfile($scanlines,$scan_data);
                   6020:     }
                   6021: }
                   6022: 
1.423     albertel 6023: =pod
                   6024: 
                   6025: =item reset_skipping_status
                   6026: 
1.424     albertel 6027:    Forgets the current set of remember skipped scanlines (and thus
                   6028:    reverts back to considering all lines in the
                   6029:    scantron_skipped_<filename> file)
                   6030: 
1.423     albertel 6031: =cut
                   6032: 
1.200     albertel 6033: sub reset_skipping_status {
                   6034:     my ($scanlines,$scan_data)=&scantron_getfile();
                   6035:     &scan_data($scan_data,'remember_skipping',undef,1);
                   6036:     &scantron_putfile(undef,$scan_data);
                   6037: }
                   6038: 
1.423     albertel 6039: =pod
                   6040: 
                   6041: =item start_skipping
                   6042: 
1.424     albertel 6043:    Marks a scanline to be skipped. 
                   6044: 
1.423     albertel 6045: =cut
                   6046: 
1.376     albertel 6047: sub start_skipping {
1.200     albertel 6048:     my ($scan_data,$i)=@_;
                   6049:     my %remembered=split(':',&scan_data($scan_data,'remember_skipping'));
1.376     albertel 6050:     if ($env{'form.scantron_options_redo'} =~ /^redo_/) {
                   6051: 	$remembered{$i}=2;
                   6052:     } else {
                   6053: 	$remembered{$i}=1;
                   6054:     }
1.200     albertel 6055:     &scan_data($scan_data,'remember_skipping',join(':',%remembered));
                   6056: }
                   6057: 
1.423     albertel 6058: =pod
                   6059: 
                   6060: =item should_be_skipped
                   6061: 
1.424     albertel 6062:    Checks whether a scanline should be skipped.
                   6063: 
1.423     albertel 6064: =cut
                   6065: 
1.200     albertel 6066: sub should_be_skipped {
1.376     albertel 6067:     my ($scanlines,$scan_data,$i)=@_;
1.257     albertel 6068:     if ($env{'form.scantron_options_redo'} !~ /^redo_/) {
1.200     albertel 6069: 	# not redoing old skips
1.376     albertel 6070: 	if ($scanlines->{'skipped'}[$i]) { return 1; }
1.200     albertel 6071: 	return 0;
                   6072:     }
                   6073:     my %remembered=split(':',&scan_data($scan_data,'remember_skipping'));
1.376     albertel 6074: 
                   6075:     if (exists($remembered{$i}) && $remembered{$i} != 2 ) {
                   6076: 	return 0;
                   6077:     }
1.200     albertel 6078:     return 1;
                   6079: }
                   6080: 
1.423     albertel 6081: =pod
                   6082: 
                   6083: =item remember_current_skipped
                   6084: 
1.424     albertel 6085:    Discovers what scanlines are in the scantron_skipped_<filename>
                   6086:    file and remembers them into scan_data for later use.
                   6087: 
1.423     albertel 6088: =cut
                   6089: 
1.200     albertel 6090: sub remember_current_skipped {
                   6091:     my ($scanlines,$scan_data)=&scantron_getfile();
                   6092:     my %to_remember;
                   6093:     for (my $i=0;$i<=$scanlines->{'count'};$i++) {
                   6094: 	if ($scanlines->{'skipped'}[$i]) {
                   6095: 	    $to_remember{$i}=1;
                   6096: 	}
                   6097:     }
1.376     albertel 6098: 
1.200     albertel 6099:     &scan_data($scan_data,'remember_skipping',join(':',%to_remember));
                   6100:     &scantron_putfile(undef,$scan_data);
                   6101: }
                   6102: 
1.423     albertel 6103: =pod
                   6104: 
                   6105: =item check_for_error
                   6106: 
1.424     albertel 6107:     Checks if there was an error when attempting to remove a specific
                   6108:     scantron_.. bubble sheet data file. Prints out an error if
                   6109:     something went wrong.
                   6110: 
1.423     albertel 6111: =cut
                   6112: 
1.200     albertel 6113: sub check_for_error {
                   6114:     my ($r,$result)=@_;
                   6115:     if ($result ne 'ok' && $result ne 'not_found' ) {
1.492     albertel 6116: 	$r->print(&mt("An error occurred ([_1]) when trying to remove the existing corrections.",$result));
1.200     albertel 6117:     }
                   6118: }
1.157     albertel 6119: 
1.423     albertel 6120: =pod
                   6121: 
                   6122: =item scantron_warning_screen
                   6123: 
1.424     albertel 6124:    Interstitial screen to make sure the operator has selected the
                   6125:    correct options before we start the validation phase.
                   6126: 
1.423     albertel 6127: =cut
                   6128: 
1.203     albertel 6129: sub scantron_warning_screen {
                   6130:     my ($button_text)=@_;
1.257     albertel 6131:     my $title=&Apache::lonnet::gettitle($env{'form.selectpage'});
1.284     albertel 6132:     my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
1.373     albertel 6133:     my $CODElist;
1.284     albertel 6134:     if ($scantron_config{'CODElocation'} &&
                   6135: 	$scantron_config{'CODEstart'} &&
                   6136: 	$scantron_config{'CODElength'}) {
                   6137: 	$CODElist=$env{'form.scantron_CODElist'};
1.398     albertel 6138: 	if ($env{'form.scantron_CODElist'} eq '') { $CODElist='<span class="LC_warning">None</span>'; }
1.284     albertel 6139: 	$CODElist=
1.492     albertel 6140: 	    '<tr><td><b>'.&mt('List of CODES to validate against:').'</b></td><td><tt>'.
1.373     albertel 6141: 	    $env{'form.scantron_CODElist'}.'</tt></td></tr>';
1.284     albertel 6142:     }
1.492     albertel 6143:     return ('
1.203     albertel 6144: <p>
1.492     albertel 6145: <span class="LC_warning">
                   6146: '.&mt('Please double check the information below before clicking on \'[_1]\'',&mt($button_text)).'</span>
1.203     albertel 6147: </p>
                   6148: <table>
1.492     albertel 6149: <tr><td><b>'.&mt('Sequence to be Graded:').'</b></td><td>'.$title.'</td></tr>
                   6150: <tr><td><b>'.&mt('Data File that will be used:').'</b></td><td><tt>'.$env{'form.scantron_selectfile'}.'</tt></td></tr>
                   6151: '.$CODElist.'
1.203     albertel 6152: </table>
                   6153: <br />
1.492     albertel 6154: <p> '.&mt('If this information is correct, please click on \'[_1]\'.',&mt($button_text)).'</p>
                   6155: <p> '.&mt('If something is incorrect, please click the \'Grading Menu\' button to start over.').'</p>
1.203     albertel 6156: 
                   6157: <br />
1.492     albertel 6158: ');
1.203     albertel 6159: }
                   6160: 
1.423     albertel 6161: =pod
                   6162: 
                   6163: =item scantron_do_warning
                   6164: 
1.424     albertel 6165:    Check if the operator has picked something for all required
                   6166:    fields. Error out if something is missing.
                   6167: 
1.423     albertel 6168: =cut
                   6169: 
1.203     albertel 6170: sub scantron_do_warning {
1.608     www      6171:     my ($r,$symb)=@_;
1.203     albertel 6172:     if (!$symb) {return '';}
1.324     albertel 6173:     my $default_form_data=&defaultFormData($symb);
1.203     albertel 6174:     $r->print(&scantron_form_start().$default_form_data);
1.257     albertel 6175:     if ( $env{'form.selectpage'} eq '' ||
                   6176: 	 $env{'form.scantron_selectfile'} eq '' ||
                   6177: 	 $env{'form.scantron_format'} eq '' ) {
1.492     albertel 6178: 	$r->print("<p>".&mt('You have forgetten to specify some information. Please go Back and try again.')."</p>");
1.257     albertel 6179: 	if ( $env{'form.selectpage'} eq '') {
1.492     albertel 6180: 	    $r->print('<p><span class="LC_error">'.&mt('You have not selected a Sequence to grade').'</span></p>');
1.237     albertel 6181: 	} 
1.257     albertel 6182: 	if ( $env{'form.scantron_selectfile'} eq '') {
1.492     albertel 6183: 	    $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 6184: 	} 
1.257     albertel 6185: 	if ( $env{'form.scantron_format'} eq '') {
1.492     albertel 6186: 	    $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 6187: 	} 
                   6188:     } else {
1.265     www      6189: 	my $warning=&scantron_warning_screen('Grading: Validate Records');
1.492     albertel 6190: 	$r->print('
                   6191: '.$warning.'
                   6192: <input type="submit" name="submit" value="'.&mt('Grading: Validate Records').'" />
1.203     albertel 6193: <input type="hidden" name="command" value="scantron_validate" />
1.492     albertel 6194: ');
1.237     albertel 6195:     }
1.614     www      6196:     $r->print("</form><br />");
1.203     albertel 6197:     return '';
                   6198: }
                   6199: 
1.423     albertel 6200: =pod
                   6201: 
                   6202: =item scantron_form_start
                   6203: 
1.424     albertel 6204:     html hidden input for remembering all selected grading options
                   6205: 
1.423     albertel 6206: =cut
                   6207: 
1.203     albertel 6208: sub scantron_form_start {
                   6209:     my ($max_bubble)=@_;
                   6210:     my $result= <<SCANTRONFORM;
                   6211: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="scantronupload">
1.257     albertel 6212:   <input type="hidden" name="selectpage" value="$env{'form.selectpage'}" />
                   6213:   <input type="hidden" name="scantron_format" value="$env{'form.scantron_format'}" />
                   6214:   <input type="hidden" name="scantron_selectfile" value="$env{'form.scantron_selectfile'}" />
1.218     albertel 6215:   <input type="hidden" name="scantron_maxbubble" value="$max_bubble" />
1.257     albertel 6216:   <input type="hidden" name="scantron_CODElist" value="$env{'form.scantron_CODElist'}" />
                   6217:   <input type="hidden" name="scantron_CODEunique" value="$env{'form.scantron_CODEunique'}" />
                   6218:   <input type="hidden" name="scantron_options_redo" value="$env{'form.scantron_options_redo'}" />
                   6219:   <input type="hidden" name="scantron_options_ignore" value="$env{'form.scantron_options_ignore'}" />
1.331     albertel 6220:   <input type="hidden" name="scantron_options_hidden" value="$env{'form.scantron_options_hidden'}" />
1.203     albertel 6221: SCANTRONFORM
1.447     foxr     6222: 
                   6223:   my $line = 0;
                   6224:     while (defined($env{"form.scantron.bubblelines.$line"})) {
                   6225:        my $chunk =
                   6226: 	   '<input type="hidden" name="scantron.bubblelines.'.$line.'" value="'.$env{"form.scantron.bubblelines.$line"}.'" />'."\n";
1.448     foxr     6227:        $chunk .=
                   6228: 	   '<input type="hidden" name="scantron.first_bubble_line.'.$line.'" value="'.$env{"form.scantron.first_bubble_line.$line"}.'" />'."\n";
1.503     raeburn  6229:        $chunk .= 
                   6230:            '<input type="hidden" name="scantron.sub_bubblelines.'.$line.'" value="'.$env{"form.scantron.sub_bubblelines.$line"}.'" />'."\n";
1.504     raeburn  6231:        $chunk .=
                   6232:            '<input type="hidden" name="scantron.responsetype.'.$line.'" value="'.$env{"form.scantron.responsetype.$line"}.'" />'."\n";
1.447     foxr     6233:        $result .= $chunk;
                   6234:        $line++;
                   6235:    }
1.203     albertel 6236:     return $result;
                   6237: }
                   6238: 
1.423     albertel 6239: =pod
                   6240: 
                   6241: =item scantron_validate_file
                   6242: 
1.424     albertel 6243:     Dispatch routine for doing validation of a bubble sheet data file.
                   6244: 
                   6245:     Also processes any necessary information resets that need to
                   6246:     occur before validation begins (ignore previous corrections,
                   6247:     restarting the skipped records processing)
                   6248: 
1.423     albertel 6249: =cut
                   6250: 
1.157     albertel 6251: sub scantron_validate_file {
1.608     www      6252:     my ($r,$symb) = @_;
1.157     albertel 6253:     if (!$symb) {return '';}
1.324     albertel 6254:     my $default_form_data=&defaultFormData($symb);
1.200     albertel 6255:     
                   6256:     # do the detection of only doing skipped records first befroe we delete
1.424     albertel 6257:     # them when doing the corrections reset
1.257     albertel 6258:     if ($env{'form.scantron_options_redo'} ne 'redo_skipped_ready') {
1.200     albertel 6259: 	&reset_skipping_status();
                   6260:     }
1.257     albertel 6261:     if ($env{'form.scantron_options_redo'} eq 'redo_skipped') {
1.200     albertel 6262: 	&remember_current_skipped();
1.257     albertel 6263: 	$env{'form.scantron_options_redo'}='redo_skipped_ready';
1.200     albertel 6264:     }
                   6265: 
1.257     albertel 6266:     if ($env{'form.scantron_options_ignore'} eq 'ignore_corrections') {
1.200     albertel 6267: 	&check_for_error($r,&scantron_remove_file('corrected'));
                   6268: 	&check_for_error($r,&scantron_remove_file('skipped'));
                   6269: 	&check_for_error($r,&scantron_remove_scan_data());
1.257     albertel 6270: 	$env{'form.scantron_options_ignore'}='done';
1.192     albertel 6271:     }
1.200     albertel 6272: 
1.257     albertel 6273:     if ($env{'form.scantron_corrections'}) {
1.157     albertel 6274: 	&scantron_process_corrections($r);
                   6275:     }
1.503     raeburn  6276:     $r->print('<p>'.&mt('Gathering necessary information.').'</p>');$r->rflush();
1.157     albertel 6277:     #get the student pick code ready
                   6278:     $r->print(&Apache::loncommon::studentbrowser_javascript());
1.582     raeburn  6279:     my $nav_error;
                   6280:     my $max_bubble=&scantron_get_maxbubble(\$nav_error);
                   6281:     if ($nav_error) {
                   6282:         $r->print(&navmap_errormsg());
                   6283:         return '';
                   6284:     }
1.203     albertel 6285:     my $result=&scantron_form_start($max_bubble).$default_form_data;
1.157     albertel 6286:     $r->print($result);
                   6287:     
1.334     albertel 6288:     my @validate_phases=( 'sequence',
                   6289: 			  'ID',
1.157     albertel 6290: 			  'CODE',
                   6291: 			  'doublebubble',
                   6292: 			  'missingbubbles');
1.257     albertel 6293:     if (!$env{'form.validatepass'}) {
                   6294: 	$env{'form.validatepass'} = 0;
1.157     albertel 6295:     }
1.257     albertel 6296:     my $currentphase=$env{'form.validatepass'};
1.157     albertel 6297: 
1.448     foxr     6298: 
1.157     albertel 6299:     my $stop=0;
                   6300:     while (!$stop && $currentphase < scalar(@validate_phases)) {
1.503     raeburn  6301: 	$r->print(&mt('Validating '.$validate_phases[$currentphase]).'<br />');
1.157     albertel 6302: 	$r->rflush();
                   6303: 	my $which="scantron_validate_".$validate_phases[$currentphase];
                   6304: 	{
                   6305: 	    no strict 'refs';
                   6306: 	    ($stop,$currentphase)=&$which($r,$currentphase);
                   6307: 	}
                   6308:     }
                   6309:     if (!$stop) {
1.203     albertel 6310: 	my $warning=&scantron_warning_screen('Start Grading');
1.542     raeburn  6311: 	$r->print(&mt('Validation process complete.').'<br />'.
                   6312:                   $warning.
                   6313:                   &mt('Perform verification for each student after storage of submissions?').
                   6314:                   '&nbsp;<span class="LC_nobreak"><label>'.
                   6315:                   '<input type="radio" name="verifyrecord" value="1" />'.&mt('Yes').'</label>'.
                   6316:                   ('&nbsp;'x3).'<label>'.
                   6317:                   '<input type="radio" name="verifyrecord" value="0" checked="checked" />'.&mt('No').
                   6318:                   '</label></span><br />'.
                   6319:                   &mt('Grading will take longer if you use verification.').'<br />'.
1.572     www      6320:                   &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  6321:                   '<input type="submit" name="submit" value="'.&mt('Start Grading').'" />'.
                   6322:                   '<input type="hidden" name="command" value="scantron_process" />'."\n");
1.157     albertel 6323:     } else {
                   6324: 	$r->print('<input type="hidden" name="command" value="scantron_validate" />');
                   6325: 	$r->print("<input type='hidden' name='validatepass' value='".$currentphase."' />");
                   6326:     }
                   6327:     if ($stop) {
1.334     albertel 6328: 	if ($validate_phases[$currentphase] eq 'sequence') {
1.539     riegler  6329: 	    $r->print('<input type="submit" name="submit" value="'.&mt('Ignore').' &rarr; " />');
1.492     albertel 6330: 	    $r->print(' '.&mt('this error').' <br />');
1.334     albertel 6331: 
1.492     albertel 6332: 	    $r->print(" <p>".&mt("Or click the 'Grading Menu' button to start over.")."</p>");
1.334     albertel 6333: 	} else {
1.503     raeburn  6334:             if ($validate_phases[$currentphase] eq 'doublebubble' || $validate_phases[$currentphase] eq 'missingbubbles') {
1.539     riegler  6335: 	        $r->print('<input type="button" name="submitbutton" value="'.&mt('Continue').' &rarr;" onclick="javascript:verify_bubble_radio(this.form)" />');
1.503     raeburn  6336:             } else {
1.539     riegler  6337:                 $r->print('<input type="submit" name="submit" value="'.&mt('Continue').' &rarr;" />');
1.503     raeburn  6338:             }
1.492     albertel 6339: 	    $r->print(' '.&mt('using corrected info').' <br />');
                   6340: 	    $r->print("<input type='submit' value='".&mt("Skip")."' name='scantron_skip_record' />");
                   6341: 	    $r->print(" ".&mt("this scanline saving it for later."));
1.334     albertel 6342: 	}
1.157     albertel 6343:     }
1.614     www      6344:     $r->print(" </form><br />");
1.157     albertel 6345:     return '';
                   6346: }
                   6347: 
1.423     albertel 6348: 
                   6349: =pod
                   6350: 
                   6351: =item scantron_remove_file
                   6352: 
1.424     albertel 6353:    Removes the requested bubble sheet data file, makes sure that
                   6354:    scantron_original_<filename> is never removed
                   6355: 
                   6356: 
1.423     albertel 6357: =cut
                   6358: 
1.200     albertel 6359: sub scantron_remove_file {
1.192     albertel 6360:     my ($which)=@_;
1.257     albertel 6361:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   6362:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1.192     albertel 6363:     my $file='scantron_';
1.200     albertel 6364:     if ($which eq 'corrected' || $which eq 'skipped') {
                   6365: 	$file.=$which.'_';
1.192     albertel 6366:     } else {
                   6367: 	return 'refused';
                   6368:     }
1.257     albertel 6369:     $file.=$env{'form.scantron_selectfile'};
1.200     albertel 6370:     return &Apache::lonnet::removeuserfile($cname,$cdom,$file);
                   6371: }
                   6372: 
1.423     albertel 6373: 
                   6374: =pod
                   6375: 
                   6376: =item scantron_remove_scan_data
                   6377: 
1.424     albertel 6378:    Removes all scan_data correction for the requested bubble sheet
                   6379:    data file.  (In the case that both the are doing skipped records we need
                   6380:    to remember the old skipped lines for the time being so that element
                   6381:    persists for a while.)
                   6382: 
1.423     albertel 6383: =cut
                   6384: 
1.200     albertel 6385: sub scantron_remove_scan_data {
1.257     albertel 6386:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   6387:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1.192     albertel 6388:     my @keys=&Apache::lonnet::getkeys('nohist_scantrondata',$cdom,$cname);
                   6389:     my @todelete;
1.257     albertel 6390:     my $filename=$env{'form.scantron_selectfile'};
1.192     albertel 6391:     foreach my $key (@keys) {
                   6392: 	if ($key=~/^\Q$filename\E_/) {
1.257     albertel 6393: 	    if ($env{'form.scantron_options_redo'} eq 'redo_skipped_ready' &&
1.200     albertel 6394: 		$key=~/remember_skipping/) {
                   6395: 		next;
                   6396: 	    }
1.192     albertel 6397: 	    push(@todelete,$key);
                   6398: 	}
                   6399:     }
1.200     albertel 6400:     my $result;
1.192     albertel 6401:     if (@todelete) {
1.491     albertel 6402: 	$result = &Apache::lonnet::del('nohist_scantrondata',
                   6403: 				       \@todelete,$cdom,$cname);
                   6404:     } else {
                   6405: 	$result = 'ok';
1.192     albertel 6406:     }
                   6407:     return $result;
                   6408: }
                   6409: 
1.423     albertel 6410: 
                   6411: =pod
                   6412: 
                   6413: =item scantron_getfile
                   6414: 
1.424     albertel 6415:     Fetches the requested bubble sheet data file (all 3 versions), and
                   6416:     the scan_data hash
                   6417:   
                   6418:   Arguments:
                   6419:     None
                   6420: 
                   6421:   Returns:
                   6422:     2 hash references
                   6423: 
                   6424:      - first one has 
                   6425:          orig      -
                   6426:          corrected -
                   6427:          skipped   -  each of which points to an array ref of the specified
                   6428:                       file broken up into individual lines
                   6429:          count     - number of scanlines
                   6430:  
                   6431:      - second is the scan_data hash possible keys are
1.425     albertel 6432:        ($number refers to scanline numbered $number and thus the key affects
                   6433:         only that scanline
                   6434:         $bubline refers to the specific bubble line element and the aspects
                   6435:         refers to that specific bubble line element)
                   6436: 
                   6437:        $number.user - username:domain to use
                   6438:        $number.CODE_ignore_dup 
                   6439:                     - ignore the duplicate CODE error 
                   6440:        $number.useCODE
                   6441:                     - use the CODE in the scanline as is
                   6442:        $number.no_bubble.$bubline
                   6443:                     - it is valid that there is no bubbled in bubble
                   6444:                       at $number $bubline
                   6445:        remember_skipping
                   6446:                     - a frozen hash containing keys of $number and values
                   6447:                       of either 
                   6448:                         1 - we are on a 'do skipped records pass' and plan
                   6449:                             on processing this line
                   6450:                         2 - we are on a 'do skipped records pass' and this
                   6451:                             scanline has been marked to skip yet again
1.424     albertel 6452: 
1.423     albertel 6453: =cut
                   6454: 
1.157     albertel 6455: sub scantron_getfile {
1.200     albertel 6456:     #FIXME really would prefer a scantron directory
1.257     albertel 6457:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   6458:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1.157     albertel 6459:     my $lines;
                   6460:     $lines=&Apache::lonnet::getfile('/uploaded/'.$cdom.'/'.$cname.'/'.
1.257     albertel 6461: 		       'scantron_orig_'.$env{'form.scantron_selectfile'});
1.157     albertel 6462:     my %scanlines;
                   6463:     $scanlines{'orig'}=[(split("\n",$lines,-1))];
                   6464:     my $temp=$scanlines{'orig'};
                   6465:     $scanlines{'count'}=$#$temp;
                   6466: 
                   6467:     $lines=&Apache::lonnet::getfile('/uploaded/'.$cdom.'/'.$cname.'/'.
1.257     albertel 6468: 		       'scantron_corrected_'.$env{'form.scantron_selectfile'});
1.157     albertel 6469:     if ($lines eq '-1') {
                   6470: 	$scanlines{'corrected'}=[];
                   6471:     } else {
                   6472: 	$scanlines{'corrected'}=[(split("\n",$lines,-1))];
                   6473:     }
                   6474:     $lines=&Apache::lonnet::getfile('/uploaded/'.$cdom.'/'.$cname.'/'.
1.257     albertel 6475: 		       'scantron_skipped_'.$env{'form.scantron_selectfile'});
1.157     albertel 6476:     if ($lines eq '-1') {
                   6477: 	$scanlines{'skipped'}=[];
                   6478:     } else {
                   6479: 	$scanlines{'skipped'}=[(split("\n",$lines,-1))];
                   6480:     }
1.175     albertel 6481:     my @tmp=&Apache::lonnet::dump('nohist_scantrondata',$cdom,$cname);
1.157     albertel 6482:     if ($tmp[0] =~ /^(error:|no_such_host)/) { @tmp=(); }
                   6483:     my %scan_data = @tmp;
                   6484:     return (\%scanlines,\%scan_data);
                   6485: }
                   6486: 
1.423     albertel 6487: =pod
                   6488: 
                   6489: =item lonnet_putfile
                   6490: 
1.424     albertel 6491:    Wrapper routine to call &Apache::lonnet::finishuserfileupload
                   6492: 
                   6493:  Arguments:
                   6494:    $contents - data to store
                   6495:    $filename - filename to store $contents into
                   6496: 
                   6497:  Returns:
                   6498:    result value from &Apache::lonnet::finishuserfileupload
                   6499: 
1.423     albertel 6500: =cut
                   6501: 
1.157     albertel 6502: sub lonnet_putfile {
                   6503:     my ($contents,$filename)=@_;
1.257     albertel 6504:     my $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   6505:     my $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
                   6506:     $env{'form.sillywaytopassafilearound'}=$contents;
1.275     albertel 6507:     &Apache::lonnet::finishuserfileupload($docuname,$docudom,'sillywaytopassafilearound',$filename);
1.157     albertel 6508: 
                   6509: }
                   6510: 
1.423     albertel 6511: =pod
                   6512: 
                   6513: =item scantron_putfile
                   6514: 
1.424     albertel 6515:     Stores the current version of the bubble sheet data files, and the
                   6516:     scan_data hash. (Does not modify the original version only the
                   6517:     corrected and skipped versions.
                   6518: 
                   6519:  Arguments:
                   6520:     $scanlines - hash ref that looks like the first return value from
                   6521:                  &scantron_getfile()
                   6522:     $scan_data - hash ref that looks like the second return value from
                   6523:                  &scantron_getfile()
                   6524: 
1.423     albertel 6525: =cut
                   6526: 
1.157     albertel 6527: sub scantron_putfile {
                   6528:     my ($scanlines,$scan_data) = @_;
1.200     albertel 6529:     #FIXME really would prefer a scantron directory
1.257     albertel 6530:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   6531:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1.200     albertel 6532:     if ($scanlines) {
                   6533: 	my $prefix='scantron_';
1.157     albertel 6534: # no need to update orig, shouldn't change
                   6535: #   &lonnet_putfile(join("\n",@{$scanlines->{'orig'}}),$prefix.'orig_'.
1.257     albertel 6536: #		    $env{'form.scantron_selectfile'});
1.200     albertel 6537: 	&lonnet_putfile(join("\n",@{$scanlines->{'corrected'}}),
                   6538: 			$prefix.'corrected_'.
1.257     albertel 6539: 			$env{'form.scantron_selectfile'});
1.200     albertel 6540: 	&lonnet_putfile(join("\n",@{$scanlines->{'skipped'}}),
                   6541: 			$prefix.'skipped_'.
1.257     albertel 6542: 			$env{'form.scantron_selectfile'});
1.200     albertel 6543:     }
1.175     albertel 6544:     &Apache::lonnet::put('nohist_scantrondata',$scan_data,$cdom,$cname);
1.157     albertel 6545: }
                   6546: 
1.423     albertel 6547: =pod
                   6548: 
                   6549: =item scantron_get_line
                   6550: 
1.424     albertel 6551:    Returns the correct version of the scanline
                   6552: 
                   6553:  Arguments:
                   6554:     $scanlines - hash ref that looks like the first return value from
                   6555:                  &scantron_getfile()
                   6556:     $scan_data - hash ref that looks like the second return value from
                   6557:                  &scantron_getfile()
                   6558:     $i         - number of the requested line (starts at 0)
                   6559: 
                   6560:  Returns:
                   6561:    A scanline, (either the original or the corrected one if it
                   6562:    exists), or undef if the requested scanline should be
                   6563:    skipped. (Either because it's an skipped scanline, or it's an
                   6564:    unskipped scanline and we are not doing a 'do skipped scanlines'
                   6565:    pass.
                   6566: 
1.423     albertel 6567: =cut
                   6568: 
1.157     albertel 6569: sub scantron_get_line {
1.200     albertel 6570:     my ($scanlines,$scan_data,$i)=@_;
1.376     albertel 6571:     if (&should_be_skipped($scanlines,$scan_data,$i)) { return undef; }
                   6572:     #if ($scanlines->{'skipped'}[$i]) { return undef; }
1.157     albertel 6573:     if ($scanlines->{'corrected'}[$i]) {return $scanlines->{'corrected'}[$i];}
                   6574:     return $scanlines->{'orig'}[$i]; 
                   6575: }
                   6576: 
1.423     albertel 6577: =pod
                   6578: 
                   6579: =item scantron_todo_count
                   6580: 
1.424     albertel 6581:     Counts the number of scanlines that need processing.
                   6582: 
                   6583:  Arguments:
                   6584:     $scanlines - hash ref that looks like the first return value from
                   6585:                  &scantron_getfile()
                   6586:     $scan_data - hash ref that looks like the second return value from
                   6587:                  &scantron_getfile()
                   6588: 
                   6589:  Returns:
                   6590:     $count - number of scanlines to process
                   6591: 
1.423     albertel 6592: =cut
                   6593: 
1.200     albertel 6594: sub get_todo_count {
                   6595:     my ($scanlines,$scan_data)=@_;
                   6596:     my $count=0;
                   6597:     for (my $i=0;$i<=$scanlines->{'count'};$i++) {
                   6598: 	my $line=&scantron_get_line($scanlines,$scan_data,$i);
                   6599: 	if ($line=~/^[\s\cz]*$/) { next; }
                   6600: 	$count++;
                   6601:     }
                   6602:     return $count;
                   6603: }
                   6604: 
1.423     albertel 6605: =pod
                   6606: 
                   6607: =item scantron_put_line
                   6608: 
1.424     albertel 6609:     Updates the 'corrected' or 'skipped' versions of the bubble sheet
                   6610:     data file.
                   6611: 
                   6612:  Arguments:
                   6613:     $scanlines - hash ref that looks like the first return value from
                   6614:                  &scantron_getfile()
                   6615:     $scan_data - hash ref that looks like the second return value from
                   6616:                  &scantron_getfile()
                   6617:     $i         - line number to update
                   6618:     $newline   - contents of the updated scanline
                   6619:     $skip      - if true make the line for skipping and update the
                   6620:                  'skipped' file
                   6621: 
1.423     albertel 6622: =cut
                   6623: 
1.157     albertel 6624: sub scantron_put_line {
1.200     albertel 6625:     my ($scanlines,$scan_data,$i,$newline,$skip)=@_;
1.157     albertel 6626:     if ($skip) {
                   6627: 	$scanlines->{'skipped'}[$i]=$newline;
1.376     albertel 6628: 	&start_skipping($scan_data,$i);
1.157     albertel 6629: 	return;
                   6630:     }
                   6631:     $scanlines->{'corrected'}[$i]=$newline;
                   6632: }
                   6633: 
1.423     albertel 6634: =pod
                   6635: 
                   6636: =item scantron_clear_skip
                   6637: 
1.424     albertel 6638:    Remove a line from the 'skipped' file
                   6639: 
                   6640:  Arguments:
                   6641:     $scanlines - hash ref that looks like the first return value from
                   6642:                  &scantron_getfile()
                   6643:     $scan_data - hash ref that looks like the second return value from
                   6644:                  &scantron_getfile()
                   6645:     $i         - line number to update
                   6646: 
1.423     albertel 6647: =cut
                   6648: 
1.376     albertel 6649: sub scantron_clear_skip {
                   6650:     my ($scanlines,$scan_data,$i)=@_;
                   6651:     if (exists($scanlines->{'skipped'}[$i])) {
                   6652: 	undef($scanlines->{'skipped'}[$i]);
                   6653: 	return 1;
                   6654:     }
                   6655:     return 0;
                   6656: }
                   6657: 
1.423     albertel 6658: =pod
                   6659: 
                   6660: =item scantron_filter_not_exam
                   6661: 
1.424     albertel 6662:    Filter routine used by &Apache::lonnavmaps::retrieveResources(), to
                   6663:    filter out resources that are not marked as 'exam' mode
                   6664: 
1.423     albertel 6665: =cut
                   6666: 
1.334     albertel 6667: sub scantron_filter_not_exam {
                   6668:     my ($curres)=@_;
                   6669:     
                   6670:     if (ref($curres) && $curres->is_problem() && !$curres->is_exam()) {
                   6671: 	# if the user has asked to not have either hidden
                   6672: 	# or 'randomout' controlled resources to be graded
                   6673: 	# don't include them
                   6674: 	if ($env{'form.scantron_options_hidden'} eq 'ignore_hidden'
                   6675: 	    && $curres->randomout) {
                   6676: 	    return 0;
                   6677: 	}
                   6678: 	return 1;
                   6679:     }
                   6680:     return 0;
                   6681: }
                   6682: 
1.423     albertel 6683: =pod
                   6684: 
                   6685: =item scantron_validate_sequence
                   6686: 
1.424     albertel 6687:     Validates the selected sequence, checking for resource that are
                   6688:     not set to exam mode.
                   6689: 
1.423     albertel 6690: =cut
                   6691: 
1.334     albertel 6692: sub scantron_validate_sequence {
                   6693:     my ($r,$currentphase) = @_;
                   6694: 
                   6695:     my $navmap=Apache::lonnavmaps::navmap->new();
1.582     raeburn  6696:     unless (ref($navmap)) {
                   6697:         $r->print(&navmap_errormsg());
                   6698:         return (1,$currentphase);
                   6699:     }
1.334     albertel 6700:     my (undef,undef,$sequence)=
                   6701: 	&Apache::lonnet::decode_symb($env{'form.selectpage'});
                   6702: 
                   6703:     my $map=$navmap->getResourceByUrl($sequence);
                   6704: 
                   6705:     $r->print('<input type="hidden" name="validate_sequence_exam"
                   6706:                                     value="ignore" />');
                   6707:     if ($env{'form.validate_sequence_exam'} ne 'ignore') {
                   6708: 	my @resources=
                   6709: 	    $navmap->retrieveResources($map,\&scantron_filter_not_exam,1,0);
                   6710: 	if (@resources) {
1.357     banghart 6711: 	    $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 6712: 	    return (1,$currentphase);
                   6713: 	}
                   6714:     }
                   6715: 
                   6716:     return (0,$currentphase+1);
                   6717: }
                   6718: 
1.423     albertel 6719: 
                   6720: 
1.157     albertel 6721: sub scantron_validate_ID {
                   6722:     my ($r,$currentphase) = @_;
                   6723:     
                   6724:     #get student info
                   6725:     my $classlist=&Apache::loncoursedata::get_classlist();
                   6726:     my %idmap=&username_to_idmap($classlist);
                   6727: 
                   6728:     #get scantron line setup
1.257     albertel 6729:     my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
1.157     albertel 6730:     my ($scanlines,$scan_data)=&scantron_getfile();
1.582     raeburn  6731: 
                   6732:     my $nav_error;
                   6733:     &scantron_get_maxbubble(\$nav_error); # parse needs the bubble_lines.. array.
                   6734:     if ($nav_error) {
                   6735:         $r->print(&navmap_errormsg());
                   6736:         return(1,$currentphase);
                   6737:     }
1.157     albertel 6738: 
                   6739:     my %found=('ids'=>{},'usernames'=>{});
                   6740:     for (my $i=0;$i<=$scanlines->{'count'};$i++) {
1.200     albertel 6741: 	my $line=&scantron_get_line($scanlines,$scan_data,$i);
1.157     albertel 6742: 	if ($line=~/^[\s\cz]*$/) { next; }
                   6743: 	my $scan_record=&scantron_parse_scanline($line,$i,\%scantron_config,
                   6744: 						 $scan_data);
                   6745: 	my $id=$$scan_record{'scantron.ID'};
                   6746: 	my $found;
                   6747: 	foreach my $checkid (keys(%idmap)) {
                   6748: 	    if (lc($checkid) eq lc($id)) { $found=$checkid;last; }
                   6749: 	}
                   6750: 	if ($found) {
                   6751: 	    my $username=$idmap{$found};
                   6752: 	    if ($found{'ids'}{$found}) {
                   6753: 		&scantron_get_correction($r,$i,$scan_record,\%scantron_config,
                   6754: 					 $line,'duplicateID',$found);
1.194     albertel 6755: 		return(1,$currentphase);
1.157     albertel 6756: 	    } elsif ($found{'usernames'}{$username}) {
                   6757: 		&scantron_get_correction($r,$i,$scan_record,\%scantron_config,
                   6758: 					 $line,'duplicateID',$username);
1.194     albertel 6759: 		return(1,$currentphase);
1.157     albertel 6760: 	    }
1.186     albertel 6761: 	    #FIXME store away line we previously saw the ID on to use above
1.157     albertel 6762: 	    $found{'ids'}{$found}++;
                   6763: 	    $found{'usernames'}{$username}++;
                   6764: 	} else {
                   6765: 	    if ($id =~ /^\s*$/) {
1.158     albertel 6766: 		my $username=&scan_data($scan_data,"$i.user");
1.157     albertel 6767: 		if (defined($username) && $found{'usernames'}{$username}) {
                   6768: 		    &scantron_get_correction($r,$i,$scan_record,
                   6769: 					     \%scantron_config,
                   6770: 					     $line,'duplicateID',$username);
1.194     albertel 6771: 		    return(1,$currentphase);
1.157     albertel 6772: 		} elsif (!defined($username)) {
                   6773: 		    &scantron_get_correction($r,$i,$scan_record,
                   6774: 					     \%scantron_config,
                   6775: 					     $line,'incorrectID');
1.194     albertel 6776: 		    return(1,$currentphase);
1.157     albertel 6777: 		}
                   6778: 		$found{'usernames'}{$username}++;
                   6779: 	    } else {
                   6780: 		&scantron_get_correction($r,$i,$scan_record,\%scantron_config,
                   6781: 					 $line,'incorrectID');
1.194     albertel 6782: 		return(1,$currentphase);
1.157     albertel 6783: 	    }
                   6784: 	}
                   6785:     }
                   6786: 
                   6787:     return (0,$currentphase+1);
                   6788: }
                   6789: 
1.423     albertel 6790: 
1.157     albertel 6791: sub scantron_get_correction {
                   6792:     my ($r,$i,$scan_record,$scan_config,$line,$error,$arg)=@_;
1.454     banghart 6793: #FIXME in the case of a duplicated ID the previous line, probably need
1.157     albertel 6794: #to show both the current line and the previous one and allow skipping
                   6795: #the previous one or the current one
                   6796: 
1.333     albertel 6797:     if ( $$scan_record{'scantron.PaperID'} =~ /\S/) {
1.492     albertel 6798: 	$r->print("<p>".&mt("<b>An error was detected ($error)</b>".
                   6799: 			    " for PaperID <tt>[_1]</tt>",
                   6800: 			    $$scan_record{'scantron.PaperID'})."</p> \n");
1.157     albertel 6801:     } else {
1.492     albertel 6802: 	$r->print("<p>".&mt("<b>An error was detected ($error)</b>".
                   6803: 			    " in scanline [_1] <pre>[_2]</pre>",
                   6804: 			    $i,$line)."</p> \n");
                   6805:     }
                   6806:     my $message="<p>".&mt("The ID on the form is  <tt>[_1]</tt><br />".
                   6807: 			  "The name on the paper is [_2],[_3]",
                   6808: 			  $$scan_record{'scantron.ID'},
                   6809: 			  $$scan_record{'scantron.LastName'},
                   6810: 			  $$scan_record{'scantron.FirstName'})."</p>";
1.242     albertel 6811: 
1.157     albertel 6812:     $r->print('<input type="hidden" name="scantron_corrections" value="'.$error.'" />'."\n");
                   6813:     $r->print('<input type="hidden" name="scantron_line" value="'.$i.'" />'."\n");
1.503     raeburn  6814:                            # Array populated for doublebubble or
                   6815:     my @lines_to_correct;  # missingbubble errors to build javascript
                   6816:                            # to validate radio button checking   
                   6817: 
1.157     albertel 6818:     if ($error =~ /ID$/) {
1.186     albertel 6819: 	if ($error eq 'incorrectID') {
1.492     albertel 6820: 	    $r->print("<p>".&mt("The encoded ID is not in the classlist").
                   6821: 		      "</p>\n");
1.157     albertel 6822: 	} elsif ($error eq 'duplicateID') {
1.492     albertel 6823: 	    $r->print("<p>".&mt("The encoded ID has also been used by a previous paper [_1]",$arg)."</p>\n");
1.157     albertel 6824: 	}
1.242     albertel 6825: 	$r->print($message);
1.492     albertel 6826: 	$r->print("<p>".&mt("How should I handle this?")." <br /> \n");
1.157     albertel 6827: 	$r->print("\n<ul><li> ");
                   6828: 	#FIXME it would be nice if this sent back the user ID and
                   6829: 	#could do partial userID matches
                   6830: 	$r->print(&Apache::loncommon::selectstudent_link('scantronupload',
                   6831: 				       'scantron_username','scantron_domain'));
                   6832: 	$r->print(": <input type='text' name='scantron_username' value='' />");
                   6833: 	$r->print("\n@".
1.257     albertel 6834: 		 &Apache::loncommon::select_dom_form($env{'request.role.domain'},'scantron_domain'));
1.157     albertel 6835: 
                   6836: 	$r->print('</li>');
1.186     albertel 6837:     } elsif ($error =~ /CODE$/) {
                   6838: 	if ($error eq 'incorrectCODE') {
1.492     albertel 6839: 	    $r->print("<p>".&mt("The encoded CODE is not in the list of possible CODEs.")."</p>\n");
1.186     albertel 6840: 	} elsif ($error eq 'duplicateCODE') {
1.492     albertel 6841: 	    $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 6842: 	}
1.492     albertel 6843: 	$r->print("<p>".&mt("The CODE on the form is  <tt>'[_1]'</tt>",
                   6844: 			    $$scan_record{'scantron.CODE'})."<br />\n");
1.242     albertel 6845: 	$r->print($message);
1.492     albertel 6846: 	$r->print("<p>".&mt("How should I handle this?")." <br /> \n");
1.187     albertel 6847: 	$r->print("\n<br /> ");
1.194     albertel 6848: 	my $i=0;
1.273     albertel 6849: 	if ($error eq 'incorrectCODE' 
                   6850: 	    && $$scan_record{'scantron.CODE'}=~/\S/ ) {
1.194     albertel 6851: 	    my ($max,$closest)=&scantron_get_closely_matching_CODEs($arg,$$scan_record{'scantron.CODE'});
1.278     albertel 6852: 	    if ($closest > 0) {
                   6853: 		foreach my $testcode (@{$closest}) {
                   6854: 		    my $checked='';
1.569     bisitz   6855: 		    if (!$i) { $checked=' checked="checked"'; }
1.492     albertel 6856: 		    $r->print("
                   6857:    <label>
1.569     bisitz   6858:        <input type='radio' name='scantron_CODE_resolution' value='use_closest_$i'$checked />
1.492     albertel 6859:        ".&mt("Use the similar CODE [_1] instead.",
                   6860: 	    "<b><tt>".$testcode."</tt></b>")."
                   6861:     </label>
                   6862:     <input type='hidden' name='scantron_CODE_closest_$i' value='$testcode' />");
1.278     albertel 6863: 		    $r->print("\n<br />");
                   6864: 		    $i++;
                   6865: 		}
1.194     albertel 6866: 	    }
                   6867: 	}
1.273     albertel 6868: 	if ($$scan_record{'scantron.CODE'}=~/\S/ ) {
1.569     bisitz   6869: 	    my $checked; if (!$i) { $checked=' checked="checked"'; }
1.492     albertel 6870: 	    $r->print("
                   6871:     <label>
1.569     bisitz   6872:         <input type='radio' name='scantron_CODE_resolution' value='use_unfound'$checked />
1.492     albertel 6873:        ".&mt("Use the CODE [_1] that is was on the paper, ignoring the error.",
                   6874: 	     "<b><tt>".$$scan_record{'scantron.CODE'}."</tt></b>")."
                   6875:     </label>");
1.273     albertel 6876: 	    $r->print("\n<br />");
                   6877: 	}
1.194     albertel 6878: 
1.597     wenzelju 6879: 	$r->print(&Apache::lonhtmlcommon::scripttag(<<ENDSCRIPT));
1.188     albertel 6880: function change_radio(field) {
1.190     albertel 6881:     var slct=document.scantronupload.scantron_CODE_resolution;
1.188     albertel 6882:     var i;
                   6883:     for (i=0;i<slct.length;i++) {
                   6884:         if (slct[i].value==field) { slct[i].checked=true; }
                   6885:     }
                   6886: }
                   6887: ENDSCRIPT
1.187     albertel 6888: 	my $href="/adm/pickcode?".
1.359     www      6889: 	   "form=".&escape("scantronupload").
                   6890: 	   "&scantron_format=".&escape($env{'form.scantron_format'}).
                   6891: 	   "&scantron_CODElist=".&escape($env{'form.scantron_CODElist'}).
                   6892: 	   "&curCODE=".&escape($$scan_record{'scantron.CODE'}).
                   6893: 	   "&scantron_selectfile=".&escape($env{'form.scantron_selectfile'});
1.332     albertel 6894: 	if ($env{'form.scantron_CODElist'} =~ /\S/) { 
1.492     albertel 6895: 	    $r->print("
                   6896:     <label>
                   6897:        <input type='radio' name='scantron_CODE_resolution' value='use_found' />
                   6898:        ".&mt("[_1]Select[_2] a CODE from the list of all CODEs and use it.",
                   6899: 	     "<a target='_blank' href='$href'>","</a>")."
                   6900:     </label> 
1.558     bisitz   6901:     ".&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 6902: 	    $r->print("\n<br />");
                   6903: 	}
1.492     albertel 6904: 	$r->print("
                   6905:     <label>
                   6906:        <input type='radio' name='scantron_CODE_resolution' value='use_typed' />
                   6907:        ".&mt("Use [_1] as the CODE.",
                   6908: 	     "</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 6909: 	$r->print("\n<br /><br />");
1.157     albertel 6910:     } elsif ($error eq 'doublebubble') {
1.503     raeburn  6911: 	$r->print("<p>".&mt("There have been multiple bubbles scanned for some question(s)")."</p>\n");
1.497     foxr     6912: 
                   6913: 	# The form field scantron_questions is acutally a list of line numbers.
                   6914: 	# represented by this form so:
                   6915: 
                   6916: 	my $line_list = &questions_to_line_list($arg);
                   6917: 
1.157     albertel 6918: 	$r->print('<input type="hidden" name="scantron_questions" value="'.
1.497     foxr     6919: 		  $line_list.'" />');
1.242     albertel 6920: 	$r->print($message);
1.492     albertel 6921: 	$r->print("<p>".&mt("Please indicate which bubble should be used for grading")."</p>");
1.157     albertel 6922: 	foreach my $question (@{$arg}) {
1.503     raeburn  6923: 	    my @linenums = &prompt_for_corrections($r,$question,$scan_config,
                   6924:                                                    $scan_record, $error);
1.524     raeburn  6925:             push(@lines_to_correct,@linenums);
1.157     albertel 6926: 	}
1.503     raeburn  6927:         $r->print(&verify_bubbles_checked(@lines_to_correct));
1.157     albertel 6928:     } elsif ($error eq 'missingbubble') {
1.492     albertel 6929: 	$r->print("<p>".&mt("There have been <b>no</b> bubbles scanned for some question(s)")."</p>\n");
1.242     albertel 6930: 	$r->print($message);
1.492     albertel 6931: 	$r->print("<p>".&mt("Please indicate which bubble should be used for grading.")."</p>");
1.503     raeburn  6932: 	$r->print(&mt("Some questions have no scanned bubbles.")."\n");
1.497     foxr     6933: 
1.503     raeburn  6934: 	# The form field scantron_questions is actually a list of line numbers not
1.497     foxr     6935: 	# a list of question numbers. Therefore:
                   6936: 	#
                   6937: 	
                   6938: 	my $line_list = &questions_to_line_list($arg);
                   6939: 
1.157     albertel 6940: 	$r->print('<input type="hidden" name="scantron_questions" value="'.
1.497     foxr     6941: 		  $line_list.'" />');
1.157     albertel 6942: 	foreach my $question (@{$arg}) {
1.503     raeburn  6943: 	    my @linenums = &prompt_for_corrections($r,$question,$scan_config,
                   6944:                                                    $scan_record, $error);
1.524     raeburn  6945:             push(@lines_to_correct,@linenums);
1.157     albertel 6946: 	}
1.503     raeburn  6947:         $r->print(&verify_bubbles_checked(@lines_to_correct));
1.157     albertel 6948:     } else {
                   6949: 	$r->print("\n<ul>");
                   6950:     }
                   6951:     $r->print("\n</li></ul>");
1.497     foxr     6952: }
                   6953: 
1.503     raeburn  6954: sub verify_bubbles_checked {
                   6955:     my (@ansnums) = @_;
                   6956:     my $ansnumstr = join('","',@ansnums);
                   6957:     my $warning = &mt("A bubble or 'No bubble' selection has not been made for one or more lines.");
1.597     wenzelju 6958:     my $output = &Apache::lonhtmlcommon::scripttag((<<ENDSCRIPT));
1.503     raeburn  6959: function verify_bubble_radio(form) {
                   6960:     var ansnumArray = new Array ("$ansnumstr");
                   6961:     var need_bubble_count = 0;
                   6962:     for (var i=0; i<ansnumArray.length; i++) {
                   6963:         if (form.elements["scantron_correct_Q_"+ansnumArray[i]].length > 1) {
                   6964:             var bubble_picked = 0; 
                   6965:             for (var j=0; j<form.elements["scantron_correct_Q_"+ansnumArray[i]].length; j++) {
                   6966:                 if (form.elements["scantron_correct_Q_"+ansnumArray[i]][j].checked == true) {
                   6967:                     bubble_picked = 1;
                   6968:                 }
                   6969:             }
                   6970:             if (bubble_picked == 0) {
                   6971:                 need_bubble_count ++;
                   6972:             }
                   6973:         }
                   6974:     }
                   6975:     if (need_bubble_count) {
                   6976:         alert("$warning");
                   6977:         return;
                   6978:     }
                   6979:     form.submit(); 
                   6980: }
                   6981: ENDSCRIPT
                   6982:     return $output;
                   6983: }
                   6984: 
1.497     foxr     6985: =pod
                   6986: 
                   6987: =item  questions_to_line_list
1.157     albertel 6988: 
1.497     foxr     6989: Converts a list of questions into a string of comma separated
                   6990: line numbers in the answer sheet used by the questions.  This is
                   6991: used to fill in the scantron_questions form field.
                   6992: 
                   6993:   Arguments:
                   6994:      questions    - Reference to an array of questions.
                   6995: 
                   6996: =cut
                   6997: 
                   6998: 
                   6999: sub questions_to_line_list {
                   7000:     my ($questions) = @_;
                   7001:     my @lines;
                   7002: 
1.503     raeburn  7003:     foreach my $item (@{$questions}) {
                   7004:         my $question = $item;
                   7005:         my ($first,$count,$last);
                   7006:         if ($item =~ /^(\d+)\.(\d+)$/) {
                   7007:             $question = $1;
                   7008:             my $subquestion = $2;
                   7009:             $first = $first_bubble_line{$question-1} + 1;
                   7010:             my @subans = split(/,/,$subdivided_bubble_lines{$question-1});
                   7011:             my $subcount = 1;
                   7012:             while ($subcount<$subquestion) {
                   7013:                 $first += $subans[$subcount-1];
                   7014:                 $subcount ++;
                   7015:             }
                   7016:             $count = $subans[$subquestion-1];
                   7017:         } else {
                   7018: 	    $first   = $first_bubble_line{$question-1} + 1;
                   7019: 	    $count   = $bubble_lines_per_response{$question-1};
                   7020:         }
1.506     raeburn  7021:         $last = $first+$count-1;
1.503     raeburn  7022:         push(@lines, ($first..$last));
1.497     foxr     7023:     }
                   7024:     return join(',', @lines);
                   7025: }
                   7026: 
                   7027: =pod 
                   7028: 
                   7029: =item prompt_for_corrections
                   7030: 
                   7031: Prompts for a potentially multiline correction to the
                   7032: user's bubbling (factors out common code from scantron_get_correction
                   7033: for multi and missing bubble cases).
                   7034: 
                   7035:  Arguments:
                   7036:    $r           - Apache request object.
                   7037:    $question    - The question number to prompt for.
                   7038:    $scan_config - The scantron file configuration hash.
                   7039:    $scan_record - Reference to the hash that has the the parsed scanlines.
1.503     raeburn  7040:    $error       - Type of error
1.497     foxr     7041: 
                   7042:  Implicit inputs:
                   7043:    %bubble_lines_per_response   - Starting line numbers for each question.
                   7044:                                   Numbered from 0 (but question numbers are from
                   7045:                                   1.
                   7046:    %first_bubble_line           - Starting bubble line for each question.
1.509     raeburn  7047:    %subdivided_bubble_lines     - optionresponse, matchresponse and rankresponse 
                   7048:                                   type problems render as separate sub-questions, 
1.503     raeburn  7049:                                   in exam mode. This hash contains a 
                   7050:                                   comma-separated list of the lines per 
                   7051:                                   sub-question.
1.510     raeburn  7052:    %responsetype_per_response   - essayresponse, formularesponse,
                   7053:                                   stringresponse, imageresponse, reactionresponse,
                   7054:                                   and organicresponse type problem parts can have
1.503     raeburn  7055:                                   multiple lines per response if the weight
                   7056:                                   assigned exceeds 10.  In this case, only
                   7057:                                   one bubble per line is permitted, but more 
                   7058:                                   than one line might contain bubbles, e.g.
                   7059:                                   bubbling of: line 1 - J, line 2 - J, 
                   7060:                                   line 3 - B would assign 22 points.  
1.497     foxr     7061: 
                   7062: =cut
                   7063: 
                   7064: sub prompt_for_corrections {
1.503     raeburn  7065:     my ($r, $question, $scan_config, $scan_record, $error) = @_;
                   7066:     my ($current_line,$lines);
                   7067:     my @linenums;
                   7068:     my $questionnum = $question;
                   7069:     if ($question =~ /^(\d+)\.(\d+)$/) {
                   7070:         $question = $1;
                   7071:         $current_line = $first_bubble_line{$question-1} + 1 ;
                   7072:         my $subquestion = $2;
                   7073:         my @subans = split(/,/,$subdivided_bubble_lines{$question-1});
                   7074:         my $subcount = 1;
                   7075:         while ($subcount<$subquestion) {
                   7076:             $current_line += $subans[$subcount-1];
                   7077:             $subcount ++;
                   7078:         }
                   7079:         $lines = $subans[$subquestion-1];
                   7080:     } else {
                   7081:         $current_line = $first_bubble_line{$question-1} + 1 ;
                   7082:         $lines        = $bubble_lines_per_response{$question-1};
                   7083:     }
1.497     foxr     7084:     if ($lines > 1) {
1.503     raeburn  7085:         $r->print(&mt('The group of bubble lines below responds to a single question.').'<br />');
                   7086:         if (($responsetype_per_response{$question-1} eq 'essayresponse') ||
                   7087:             ($responsetype_per_response{$question-1} eq 'formularesponse') ||
1.510     raeburn  7088:             ($responsetype_per_response{$question-1} eq 'stringresponse') ||
                   7089:             ($responsetype_per_response{$question-1} eq 'imageresponse') ||
                   7090:             ($responsetype_per_response{$question-1} eq 'reactionresponse') ||
                   7091:             ($responsetype_per_response{$question-1} eq 'organicresponse')) {
1.572     www      7092:             $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  7093:         } else {
                   7094:             $r->print(&mt("Select at most one bubble in a single line and select 'No Bubble' in all the other lines. ")."<br />");
                   7095:         }
1.497     foxr     7096:     }
                   7097:     for (my $i =0; $i < $lines; $i++) {
1.503     raeburn  7098:         my $selected = $$scan_record{"scantron.$current_line.answer"};
                   7099: 	&scantron_bubble_selector($r,$scan_config,$current_line, 
                   7100: 	        		  $questionnum,$error,split('', $selected));
1.524     raeburn  7101:         push(@linenums,$current_line);
1.497     foxr     7102: 	$current_line++;
                   7103:     }
                   7104:     if ($lines > 1) {
                   7105: 	$r->print("<hr /><br />");
                   7106:     }
1.503     raeburn  7107:     return @linenums;
1.157     albertel 7108: }
1.423     albertel 7109: 
                   7110: =pod
                   7111: 
                   7112: =item scantron_bubble_selector
                   7113:   
                   7114:    Generates the html radiobuttons to correct a single bubble line
1.424     albertel 7115:    possibly showing the existing the selected bubbles if known
1.423     albertel 7116: 
                   7117:  Arguments:
                   7118:     $r           - Apache request object
                   7119:     $scan_config - hash from &get_scantron_config()
1.497     foxr     7120:     $line        - Number of the line being displayed.
1.503     raeburn  7121:     $questionnum - Question number (may include subquestion)
                   7122:     $error       - Type of error.
1.497     foxr     7123:     @selected    - Array of bubbles picked on this line.
1.423     albertel 7124: 
                   7125: =cut
                   7126: 
1.157     albertel 7127: sub scantron_bubble_selector {
1.503     raeburn  7128:     my ($r,$scan_config,$line,$questionnum,$error,@selected)=@_;
1.157     albertel 7129:     my $max=$$scan_config{'Qlength'};
1.274     albertel 7130: 
                   7131:     my $scmode=$$scan_config{'Qon'};
                   7132:     if ($scmode eq 'number' || $scmode eq 'letter') { $max=10; }	     
                   7133: 
1.157     albertel 7134:     my @alphabet=('A'..'Z');
1.503     raeburn  7135:     $r->print(&Apache::loncommon::start_data_table().
                   7136:               &Apache::loncommon::start_data_table_row());
                   7137:     $r->print('<td rowspan="2" class="LC_leftcol_header">'.$line.'</td>');
1.497     foxr     7138:     for (my $i=0;$i<$max+1;$i++) {
                   7139: 	$r->print("\n".'<td align="center">');
                   7140: 	if ($selected[0] eq $alphabet[$i]) { $r->print('X'); shift(@selected) }
                   7141: 	else { $r->print('&nbsp;'); }
                   7142: 	$r->print('</td>');
                   7143:     }
1.503     raeburn  7144:     $r->print(&Apache::loncommon::end_data_table_row().
                   7145:               &Apache::loncommon::start_data_table_row());
1.497     foxr     7146:     for (my $i=0;$i<$max;$i++) {
                   7147: 	$r->print("\n".
                   7148: 		  '<td><label><input type="radio" name="scantron_correct_Q_'.
                   7149: 		  $line.'" value="'.$i.'" />'.$alphabet[$i]."</label></td>");
                   7150:     }
1.503     raeburn  7151:     my $nobub_checked = ' ';
                   7152:     if ($error eq 'missingbubble') {
                   7153:         $nobub_checked = ' checked = "checked" ';
                   7154:     }
                   7155:     $r->print("\n".'<td><label><input type="radio" name="scantron_correct_Q_'.
                   7156: 	      $line.'" value="none"'.$nobub_checked.'/>'.&mt('No bubble').
                   7157:               '</label>'."\n".'<input type="hidden" name="scantron_questionnum_Q_'.
                   7158:               $line.'" value="'.$questionnum.'" /></td>');
                   7159:     $r->print(&Apache::loncommon::end_data_table_row().
                   7160:               &Apache::loncommon::end_data_table());
1.157     albertel 7161: }
                   7162: 
1.423     albertel 7163: =pod
                   7164: 
                   7165: =item num_matches
                   7166: 
1.424     albertel 7167:    Counts the number of characters that are the same between the two arguments.
                   7168: 
                   7169:  Arguments:
                   7170:    $orig - CODE from the scanline
                   7171:    $code - CODE to match against
                   7172: 
                   7173:  Returns:
                   7174:    $count - integer count of the number of same characters between the
                   7175:             two arguments
                   7176: 
1.423     albertel 7177: =cut
                   7178: 
1.194     albertel 7179: sub num_matches {
                   7180:     my ($orig,$code) = @_;
                   7181:     my @code=split(//,$code);
                   7182:     my @orig=split(//,$orig);
                   7183:     my $same=0;
                   7184:     for (my $i=0;$i<scalar(@code);$i++) {
                   7185: 	if ($code[$i] eq $orig[$i]) { $same++; }
                   7186:     }
                   7187:     return $same;
                   7188: }
                   7189: 
1.423     albertel 7190: =pod
                   7191: 
                   7192: =item scantron_get_closely_matching_CODEs
                   7193: 
1.424     albertel 7194:    Cycles through all CODEs and finds the set that has the greatest
                   7195:    number of same characters as the provided CODE
                   7196: 
                   7197:  Arguments:
                   7198:    $allcodes - hash ref returned by &get_codes()
                   7199:    $CODE     - CODE from the current scanline
                   7200: 
                   7201:  Returns:
                   7202:    2 element list
                   7203:     - first elements is number of how closely matching the best fit is 
                   7204:       (5 means best set has 5 matching characters)
                   7205:     - second element is an arrary ref containing the set of valid CODEs
                   7206:       that best fit the passed in CODE
                   7207: 
1.423     albertel 7208: =cut
                   7209: 
1.194     albertel 7210: sub scantron_get_closely_matching_CODEs {
                   7211:     my ($allcodes,$CODE)=@_;
                   7212:     my @CODEs;
                   7213:     foreach my $testcode (sort(keys(%{$allcodes}))) {
                   7214: 	push(@{$CODEs[&num_matches($CODE,$testcode)]},$testcode);
                   7215:     }
                   7216: 
                   7217:     return ($#CODEs,$CODEs[-1]);
                   7218: }
                   7219: 
1.423     albertel 7220: =pod
                   7221: 
                   7222: =item get_codes
                   7223: 
1.424     albertel 7224:    Builds a hash which has keys of all of the valid CODEs from the selected
                   7225:    set of remembered CODEs.
                   7226: 
                   7227:  Arguments:
                   7228:   $old_name - name of the set of remembered CODEs
                   7229:   $cdom     - domain of the course
                   7230:   $cnum     - internal course name
                   7231: 
                   7232:  Returns:
                   7233:   %allcodes - keys are the valid CODEs, values are all 1
                   7234: 
1.423     albertel 7235: =cut
                   7236: 
1.194     albertel 7237: sub get_codes {
1.280     foxr     7238:     my ($old_name, $cdom, $cnum) = @_;
                   7239:     if (!$old_name) {
                   7240: 	$old_name=$env{'form.scantron_CODElist'};
                   7241:     }
                   7242:     if (!$cdom) {
                   7243: 	$cdom =$env{'course.'.$env{'request.course.id'}.'.domain'};
                   7244:     }
                   7245:     if (!$cnum) {
                   7246: 	$cnum =$env{'course.'.$env{'request.course.id'}.'.num'};
                   7247:     }
1.278     albertel 7248:     my %result=&Apache::lonnet::get('CODEs',[$old_name,"type\0$old_name"],
                   7249: 				    $cdom,$cnum);
                   7250:     my %allcodes;
                   7251:     if ($result{"type\0$old_name"} eq 'number') {
                   7252: 	%allcodes=map {($_,1)} split(',',$result{$old_name});
                   7253:     } else {
                   7254: 	%allcodes=map {(&Apache::lonprintout::num_to_letters($_),1)} split(',',$result{$old_name});
                   7255:     }
1.194     albertel 7256:     return %allcodes;
                   7257: }
                   7258: 
1.423     albertel 7259: =pod
                   7260: 
                   7261: =item scantron_validate_CODE
                   7262: 
1.424     albertel 7263:    Validates all scanlines in the selected file to not have any
                   7264:    invalid or underspecified CODEs and that none of the codes are
                   7265:    duplicated if this was requested.
                   7266: 
1.423     albertel 7267: =cut
                   7268: 
1.157     albertel 7269: sub scantron_validate_CODE {
                   7270:     my ($r,$currentphase) = @_;
1.257     albertel 7271:     my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
1.186     albertel 7272:     if ($scantron_config{'CODElocation'} &&
                   7273: 	$scantron_config{'CODEstart'} &&
                   7274: 	$scantron_config{'CODElength'}) {
1.257     albertel 7275: 	if (!defined($env{'form.scantron_CODElist'})) {
1.186     albertel 7276: 	    &FIXME_blow_up()
                   7277: 	}
                   7278:     } else {
                   7279: 	return (0,$currentphase+1);
                   7280:     }
                   7281:     
                   7282:     my %usedCODEs;
                   7283: 
1.194     albertel 7284:     my %allcodes=&get_codes();
1.186     albertel 7285: 
1.582     raeburn  7286:     my $nav_error;
                   7287:     &scantron_get_maxbubble(\$nav_error); # parse needs the lines per response array.
                   7288:     if ($nav_error) {
                   7289:         $r->print(&navmap_errormsg());
                   7290:         return(1,$currentphase);
                   7291:     }
1.447     foxr     7292: 
1.186     albertel 7293:     my ($scanlines,$scan_data)=&scantron_getfile();
                   7294:     for (my $i=0;$i<=$scanlines->{'count'};$i++) {
1.200     albertel 7295: 	my $line=&scantron_get_line($scanlines,$scan_data,$i);
1.186     albertel 7296: 	if ($line=~/^[\s\cz]*$/) { next; }
                   7297: 	my $scan_record=&scantron_parse_scanline($line,$i,\%scantron_config,
                   7298: 						 $scan_data);
                   7299: 	my $CODE=$$scan_record{'scantron.CODE'};
                   7300: 	my $error=0;
1.224     albertel 7301: 	if (!&Apache::lonnet::validCODE($CODE)) {
                   7302: 	    &scantron_get_correction($r,$i,$scan_record,
                   7303: 				     \%scantron_config,
                   7304: 				     $line,'incorrectCODE',\%allcodes);
                   7305: 	    return(1,$currentphase);
                   7306: 	}
1.221     albertel 7307: 	if (%allcodes && !exists($allcodes{$CODE}) 
                   7308: 	    && !$$scan_record{'scantron.useCODE'}) {
1.186     albertel 7309: 	    &scantron_get_correction($r,$i,$scan_record,
                   7310: 				     \%scantron_config,
1.194     albertel 7311: 				     $line,'incorrectCODE',\%allcodes);
                   7312: 	    return(1,$currentphase);
1.186     albertel 7313: 	}
1.214     albertel 7314: 	if (exists($usedCODEs{$CODE}) 
1.257     albertel 7315: 	    && $env{'form.scantron_CODEunique'} eq 'yes'
1.192     albertel 7316: 	    && !$$scan_record{'scantron.CODE_ignore_dup'}) {
1.186     albertel 7317: 	    &scantron_get_correction($r,$i,$scan_record,
                   7318: 				     \%scantron_config,
1.194     albertel 7319: 				     $line,'duplicateCODE',$usedCODEs{$CODE});
                   7320: 	    return(1,$currentphase);
1.186     albertel 7321: 	}
1.524     raeburn  7322: 	push(@{$usedCODEs{$CODE}},$$scan_record{'scantron.PaperID'});
1.186     albertel 7323:     }
1.157     albertel 7324:     return (0,$currentphase+1);
                   7325: }
                   7326: 
1.423     albertel 7327: =pod
                   7328: 
                   7329: =item scantron_validate_doublebubble
                   7330: 
1.424     albertel 7331:    Validates all scanlines in the selected file to not have any
                   7332:    bubble lines with multiple bubbles marked.
                   7333: 
1.423     albertel 7334: =cut
                   7335: 
1.157     albertel 7336: sub scantron_validate_doublebubble {
                   7337:     my ($r,$currentphase) = @_;
                   7338:     #get student info
                   7339:     my $classlist=&Apache::loncoursedata::get_classlist();
                   7340:     my %idmap=&username_to_idmap($classlist);
                   7341: 
                   7342:     #get scantron line setup
1.257     albertel 7343:     my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
1.157     albertel 7344:     my ($scanlines,$scan_data)=&scantron_getfile();
1.583     raeburn  7345:     my $nav_error;
                   7346:     &scantron_get_maxbubble(\$nav_error); # parse needs the bubble line array.
                   7347:     if ($nav_error) {
                   7348:         $r->print(&navmap_errormsg());
                   7349:         return(1,$currentphase);
                   7350:     }
1.447     foxr     7351: 
1.157     albertel 7352:     for (my $i=0;$i<=$scanlines->{'count'};$i++) {
1.200     albertel 7353: 	my $line=&scantron_get_line($scanlines,$scan_data,$i);
1.157     albertel 7354: 	if ($line=~/^[\s\cz]*$/) { next; }
                   7355: 	my $scan_record=&scantron_parse_scanline($line,$i,\%scantron_config,
                   7356: 						 $scan_data);
                   7357: 	if (!defined($$scan_record{'scantron.doubleerror'})) { next; }
                   7358: 	&scantron_get_correction($r,$i,$scan_record,\%scantron_config,$line,
                   7359: 				 'doublebubble',
                   7360: 				 $$scan_record{'scantron.doubleerror'});
                   7361:     	return (1,$currentphase);
                   7362:     }
                   7363:     return (0,$currentphase+1);
                   7364: }
                   7365: 
1.423     albertel 7366: 
1.503     raeburn  7367: sub scantron_get_maxbubble {
1.582     raeburn  7368:     my ($nav_error) = @_;
1.257     albertel 7369:     if (defined($env{'form.scantron_maxbubble'}) &&
                   7370: 	$env{'form.scantron_maxbubble'}) {
1.447     foxr     7371: 	&restore_bubble_lines();
1.257     albertel 7372: 	return $env{'form.scantron_maxbubble'};
1.191     albertel 7373:     }
1.330     albertel 7374: 
1.447     foxr     7375:     my (undef, undef, $sequence) =
1.257     albertel 7376: 	&Apache::lonnet::decode_symb($env{'form.selectpage'});
1.330     albertel 7377: 
1.447     foxr     7378:     my $navmap=Apache::lonnavmaps::navmap->new();
1.582     raeburn  7379:     unless (ref($navmap)) {
                   7380:         if (ref($nav_error)) {
                   7381:             $$nav_error = 1;
                   7382:         }
1.591     raeburn  7383:         return;
1.582     raeburn  7384:     }
1.191     albertel 7385:     my $map=$navmap->getResourceByUrl($sequence);
                   7386:     my @resources=$navmap->retrieveResources($map,\&scantron_filter,1,0);
1.330     albertel 7387: 
                   7388:     &Apache::lonxml::clear_problem_counter();
                   7389: 
1.557     raeburn  7390:     my $uname       = $env{'user.name'};
                   7391:     my $udom        = $env{'user.domain'};
1.435     foxr     7392:     my $cid         = $env{'request.course.id'};
                   7393:     my $total_lines = 0;
                   7394:     %bubble_lines_per_response = ();
1.447     foxr     7395:     %first_bubble_line         = ();
1.503     raeburn  7396:     %subdivided_bubble_lines   = ();
                   7397:     %responsetype_per_response = ();
1.554     raeburn  7398: 
1.447     foxr     7399:     my $response_number = 0;
                   7400:     my $bubble_line     = 0;
1.191     albertel 7401:     foreach my $resource (@resources) {
1.542     raeburn  7402:         my ($analysis,$parts) = &scantron_partids_tograde($resource,$cid,$uname,$udom);
                   7403:         if ((ref($analysis) eq 'HASH') && (ref($parts) eq 'ARRAY')) {
                   7404: 	    foreach my $part_id (@{$parts}) {
                   7405:                 my $lines;
                   7406: 
                   7407: 	        # TODO - make this a persistent hash not an array.
                   7408: 
                   7409:                 # optionresponse, matchresponse and rankresponse type items 
                   7410:                 # render as separate sub-questions in exam mode.
                   7411:                 if (($analysis->{$part_id.'.type'} eq 'optionresponse') ||
                   7412:                     ($analysis->{$part_id.'.type'} eq 'matchresponse') ||
                   7413:                     ($analysis->{$part_id.'.type'} eq 'rankresponse')) {
                   7414:                     my ($numbub,$numshown);
                   7415:                     if ($analysis->{$part_id.'.type'} eq 'optionresponse') {
                   7416:                         if (ref($analysis->{$part_id.'.options'}) eq 'ARRAY') {
                   7417:                             $numbub = scalar(@{$analysis->{$part_id.'.options'}});
                   7418:                         }
                   7419:                     } elsif ($analysis->{$part_id.'.type'} eq 'matchresponse') {
                   7420:                         if (ref($analysis->{$part_id.'.items'}) eq 'ARRAY') {
                   7421:                             $numbub = scalar(@{$analysis->{$part_id.'.items'}});
                   7422:                         }
                   7423:                     } elsif ($analysis->{$part_id.'.type'} eq 'rankresponse') {
                   7424:                         if (ref($analysis->{$part_id.'.foils'}) eq 'ARRAY') {
                   7425:                             $numbub = scalar(@{$analysis->{$part_id.'.foils'}});
                   7426:                         }
                   7427:                     }
                   7428:                     if (ref($analysis->{$part_id.'.shown'}) eq 'ARRAY') {
                   7429:                         $numshown = scalar(@{$analysis->{$part_id.'.shown'}});
                   7430:                     }
                   7431:                     my $bubbles_per_line = 10;
                   7432:                     my $inner_bubble_lines = int($numbub/$bubbles_per_line);
                   7433:                     if (($numbub % $bubbles_per_line) != 0) {
                   7434:                         $inner_bubble_lines++;
                   7435:                     }
                   7436:                     for (my $i=0; $i<$numshown; $i++) {
                   7437:                         $subdivided_bubble_lines{$response_number} .= 
                   7438:                             $inner_bubble_lines.',';
                   7439:                     }
                   7440:                     $subdivided_bubble_lines{$response_number} =~ s/,$//;
                   7441:                     $lines = $numshown * $inner_bubble_lines;
                   7442:                 } else {
                   7443:                     $lines = $analysis->{"$part_id.bubble_lines"};
                   7444:                 } 
                   7445: 
                   7446:                 $first_bubble_line{$response_number} = $bubble_line;
                   7447: 	        $bubble_lines_per_response{$response_number} = $lines;
                   7448:                 $responsetype_per_response{$response_number} = 
                   7449:                     $analysis->{$part_id.'.type'};
                   7450: 	        $response_number++;
                   7451: 
                   7452: 	        $bubble_line +=  $lines;
                   7453: 	        $total_lines +=  $lines;
                   7454: 	    }
                   7455:         }
                   7456:     }
1.552     raeburn  7457:     &Apache::lonnet::delenv('scantron.');
1.542     raeburn  7458: 
                   7459:     &save_bubble_lines();
                   7460:     $env{'form.scantron_maxbubble'} =
                   7461: 	$total_lines;
                   7462:     return $env{'form.scantron_maxbubble'};
                   7463: }
1.523     raeburn  7464: 
1.157     albertel 7465: sub scantron_validate_missingbubbles {
                   7466:     my ($r,$currentphase) = @_;
                   7467:     #get student info
                   7468:     my $classlist=&Apache::loncoursedata::get_classlist();
                   7469:     my %idmap=&username_to_idmap($classlist);
                   7470: 
                   7471:     #get scantron line setup
1.257     albertel 7472:     my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
1.157     albertel 7473:     my ($scanlines,$scan_data)=&scantron_getfile();
1.582     raeburn  7474:     my $nav_error;
                   7475:     my $max_bubble=&scantron_get_maxbubble(\$nav_error);
                   7476:     if ($nav_error) {
                   7477:         return(1,$currentphase);
                   7478:     }
1.157     albertel 7479:     if (!$max_bubble) { $max_bubble=2**31; }
                   7480:     for (my $i=0;$i<=$scanlines->{'count'};$i++) {
1.200     albertel 7481: 	my $line=&scantron_get_line($scanlines,$scan_data,$i);
1.157     albertel 7482: 	if ($line=~/^[\s\cz]*$/) { next; }
                   7483: 	my $scan_record=&scantron_parse_scanline($line,$i,\%scantron_config,
                   7484: 						 $scan_data);
                   7485: 	if (!defined($$scan_record{'scantron.missingerror'})) { next; }
                   7486: 	my @to_correct;
1.470     foxr     7487: 	
                   7488: 	# Probably here's where the error is...
                   7489: 
1.157     albertel 7490: 	foreach my $missing (@{$$scan_record{'scantron.missingerror'}}) {
1.505     raeburn  7491:             my $lastbubble;
                   7492:             if ($missing =~ /^(\d+)\.(\d+)$/) {
                   7493:                my $question = $1;
                   7494:                my $subquestion = $2;
                   7495:                if (!defined($first_bubble_line{$question -1})) { next; }
                   7496:                my $first = $first_bubble_line{$question-1};
                   7497:                my @subans = split(/,/,$subdivided_bubble_lines{$question-1});
                   7498:                my $subcount = 1;
                   7499:                while ($subcount<$subquestion) {
                   7500:                    $first += $subans[$subcount-1];
                   7501:                    $subcount ++;
                   7502:                }
                   7503:                my $count = $subans[$subquestion-1];
                   7504:                $lastbubble = $first + $count;
                   7505:             } else {
                   7506:                 if (!defined($first_bubble_line{$missing - 1})) { next; }
                   7507:                 $lastbubble = $first_bubble_line{$missing - 1} + $bubble_lines_per_response{$missing - 1};
                   7508:             }
                   7509:             if ($lastbubble > $max_bubble) { next; }
1.157     albertel 7510: 	    push(@to_correct,$missing);
                   7511: 	}
                   7512: 	if (@to_correct) {
                   7513: 	    &scantron_get_correction($r,$i,$scan_record,\%scantron_config,
                   7514: 				     $line,'missingbubble',\@to_correct);
                   7515: 	    return (1,$currentphase);
                   7516: 	}
                   7517: 
                   7518:     }
                   7519:     return (0,$currentphase+1);
                   7520: }
                   7521: 
1.423     albertel 7522: 
1.82      albertel 7523: sub scantron_process_students {
1.608     www      7524:     my ($r,$symb) = @_;
1.513     foxr     7525: 
1.257     albertel 7526:     my (undef,undef,$sequence)=&Apache::lonnet::decode_symb($env{'form.selectpage'});
1.513     foxr     7527:     if (!$symb) {
                   7528: 	return '';
                   7529:     }
1.324     albertel 7530:     my $default_form_data=&defaultFormData($symb);
1.82      albertel 7531: 
1.257     albertel 7532:     my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
1.157     albertel 7533:     my ($scanlines,$scan_data)=&scantron_getfile();
1.82      albertel 7534:     my $classlist=&Apache::loncoursedata::get_classlist();
                   7535:     my %idmap=&username_to_idmap($classlist);
1.132     bowersj2 7536:     my $navmap=Apache::lonnavmaps::navmap->new();
1.582     raeburn  7537:     unless (ref($navmap)) {
                   7538:         $r->print(&navmap_errormsg());
                   7539:         return '';
                   7540:     }  
1.83      albertel 7541:     my $map=$navmap->getResourceByUrl($sequence);
                   7542:     my @resources=$navmap->retrieveResources($map,\&scantron_filter,1,0);
1.557     raeburn  7543:     my (%grader_partids_by_symb,%grader_randomlists_by_symb);
                   7544:     &graders_resources_pass(\@resources,\%grader_partids_by_symb,
                   7545:                             \%grader_randomlists_by_symb);
1.586     raeburn  7546:     my $resource_error;
1.557     raeburn  7547:     foreach my $resource (@resources) {
1.586     raeburn  7548:         my $ressymb;
                   7549:         if (ref($resource)) {
                   7550:             $ressymb = $resource->symb();
                   7551:         } else {
                   7552:             $resource_error = 1;
                   7553:             last;
                   7554:         }
1.557     raeburn  7555:         my ($analysis,$parts) =
                   7556:             &scantron_partids_tograde($resource,$env{'request.course.id'},
                   7557:                                       $env{'user.name'},$env{'user.domain'},1);
                   7558:         $grader_partids_by_symb{$ressymb} = $parts;
                   7559:         if (ref($analysis) eq 'HASH') {
                   7560:             if (ref($analysis->{'parts_withrandomlist'}) eq 'ARRAY') {
                   7561:                 $grader_randomlists_by_symb{$ressymb} = 
                   7562:                     $analysis->{'parts_withrandomlist'};
                   7563:             }
                   7564:         }
                   7565:     }
1.586     raeburn  7566:     if ($resource_error) {
                   7567:         $r->print(&navmap_errormsg());
                   7568:         return '';
                   7569:     }
1.557     raeburn  7570: 
1.554     raeburn  7571:     my ($uname,$udom);
1.82      albertel 7572:     my $result= <<SCANTRONFORM;
1.81      albertel 7573: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="scantronupload">
                   7574:   <input type="hidden" name="command" value="scantron_configphase" />
                   7575:   $default_form_data
                   7576: SCANTRONFORM
1.82      albertel 7577:     $r->print($result);
                   7578: 
                   7579:     my @delayqueue;
1.542     raeburn  7580:     my (%completedstudents,%scandata);
1.140     albertel 7581:     
1.520     www      7582:     my $lock=&Apache::lonnet::set_lock(&mt('Grading bubblesheet exam'));
1.200     albertel 7583:     my $count=&get_todo_count($scanlines,$scan_data);
1.575     www      7584:     my %prog_state=&Apache::lonhtmlcommon::Create_PrgWin($r,'Bubblesheet Status',
                   7585:  				    'Bubblesheet Progress',$count,
1.195     albertel 7586: 				    'inline',undef,'scantronupload');
1.140     albertel 7587:     &Apache::lonhtmlcommon::Update_PrgWin($r,\%prog_state,
                   7588: 					  'Processing first student');
1.542     raeburn  7589:     $r->print('<br />');
1.140     albertel 7590:     my $start=&Time::HiRes::time();
1.158     albertel 7591:     my $i=-1;
1.542     raeburn  7592:     my $started;
1.447     foxr     7593: 
1.582     raeburn  7594:     my $nav_error;
                   7595:     &scantron_get_maxbubble(\$nav_error); # Need the bubble lines array to parse.
                   7596:     if ($nav_error) {
                   7597:         $r->print(&navmap_errormsg());
                   7598:         return '';
                   7599:     }
                   7600: 
1.513     foxr     7601:     # If an ssi failed in scantron_get_maxbubble, put an error message out to
                   7602:     # the user and return.
                   7603: 
                   7604:     if ($ssi_error) {
                   7605: 	$r->print("</form>");
                   7606: 	&ssi_print_error($r);
1.520     www      7607:         &Apache::lonnet::remove_lock($lock);
1.513     foxr     7608: 	return '';		# Dunno why the other returns return '' rather than just returning.
                   7609:     }
1.447     foxr     7610: 
1.542     raeburn  7611:     my %lettdig = &letter_to_digits();
                   7612:     my $numletts = scalar(keys(%lettdig));
                   7613: 
1.157     albertel 7614:     while ($i<$scanlines->{'count'}) {
                   7615:  	($uname,$udom)=('','');
                   7616:  	$i++;
1.200     albertel 7617:  	my $line=&scantron_get_line($scanlines,$scan_data,$i);
1.157     albertel 7618:  	if ($line=~/^[\s\cz]*$/) { next; }
1.200     albertel 7619: 	if ($started) {
                   7620: 	    &Apache::lonhtmlcommon::Increment_PrgWin($r,\%prog_state,
                   7621: 						     'last student');
                   7622: 	}
                   7623: 	$started=1;
1.157     albertel 7624:  	my $scan_record=&scantron_parse_scanline($line,$i,\%scantron_config,
                   7625:  						 $scan_data);
                   7626:  	unless ($uname=&scantron_find_student($scan_record,$scan_data,
                   7627:  					      \%idmap,$i)) {
                   7628:   	    &scantron_add_delay(\@delayqueue,$line,
                   7629:  				'Unable to find a student that matches',1);
                   7630:  	    next;
                   7631:   	}
                   7632:  	if (exists $completedstudents{$uname}) {
                   7633:  	    &scantron_add_delay(\@delayqueue,$line,
                   7634:  				'Student '.$uname.' has multiple sheets',2);
                   7635:  	    next;
                   7636:  	}
                   7637:   	($uname,$udom)=split(/:/,$uname);
1.330     albertel 7638: 
1.586     raeburn  7639:         my (%partids_by_symb,$res_error);
1.554     raeburn  7640:         foreach my $resource (@resources) {
1.586     raeburn  7641:             my $ressymb;
                   7642:             if (ref($resource)) {
                   7643:                 $ressymb = $resource->symb();
                   7644:             } else {
                   7645:                 $res_error = 1;
                   7646:                 last;
                   7647:             }
1.557     raeburn  7648:             if ((exists($grader_randomlists_by_symb{$ressymb})) ||
                   7649:                 (ref($grader_partids_by_symb{$ressymb}) ne 'ARRAY')) {
                   7650:                 my ($analysis,$parts) =
                   7651:                     &scantron_partids_tograde($resource,$env{'request.course.id'},$uname,$udom);
                   7652:                 $partids_by_symb{$ressymb} = $parts;
                   7653:             } else {
                   7654:                 $partids_by_symb{$ressymb} = $grader_partids_by_symb{$ressymb};
                   7655:             }
1.554     raeburn  7656:         }
                   7657: 
1.586     raeburn  7658:         if ($res_error) {
                   7659:             &scantron_add_delay(\@delayqueue,$line,
                   7660:                                 'An error occurred while grading student '.$uname,2);
                   7661:             next;
                   7662:         }
                   7663: 
1.330     albertel 7664: 	&Apache::lonxml::clear_problem_counter();
1.514     raeburn  7665:   	&Apache::lonnet::appenv($scan_record);
1.376     albertel 7666: 
                   7667: 	if (&scantron_clear_skip($scanlines,$scan_data,$i)) {
                   7668: 	    &scantron_putfile($scanlines,$scan_data);
                   7669: 	}
1.161     albertel 7670: 	
1.542     raeburn  7671:         my $scancode;
                   7672:         if ((exists($scan_record->{'scantron.CODE'})) &&
                   7673:             (&Apache::lonnet::validCODE($scan_record->{'scantron.CODE'}))) {
                   7674:             $scancode = $scan_record->{'scantron.CODE'};
                   7675:         } else {
                   7676:             $scancode = '';
                   7677:         }
                   7678: 
                   7679:         if (&grade_student_bubbles($r,$uname,$udom,$scan_record,$scancode,
1.554     raeburn  7680:                                    \@resources,\%partids_by_symb) eq 'ssi_error') {
1.542     raeburn  7681:             $ssi_error = 0; # So end of handler error message does not trigger.
                   7682:             $r->print("</form>");
                   7683:             &ssi_print_error($r);
                   7684:             &Apache::lonnet::remove_lock($lock);
                   7685:             return '';      # Why return ''?  Beats me.
                   7686:         }
1.513     foxr     7687: 
1.140     albertel 7688: 	$completedstudents{$uname}={'line'=>$line};
1.542     raeburn  7689:         if ($env{'form.verifyrecord'}) {
                   7690:             my $lastpos = $env{'form.scantron_maxbubble'}*$scantron_config{'Qlength'};
                   7691:             my $studentdata = substr($line,$scantron_config{'Qstart'}-1,$lastpos);
                   7692:             chomp($studentdata);
                   7693:             $studentdata =~ s/\r$//;
                   7694:             my $studentrecord = '';
                   7695:             my $counter = -1;
                   7696:             foreach my $resource (@resources) {
1.554     raeburn  7697:                 my $ressymb = $resource->symb();
1.542     raeburn  7698:                 ($counter,my $recording) =
                   7699:                     &verify_scantron_grading($resource,$udom,$uname,$env{'request.course.id'},
1.554     raeburn  7700:                                              $counter,$studentdata,$partids_by_symb{$ressymb},
1.542     raeburn  7701:                                              \%scantron_config,\%lettdig,$numletts);
                   7702:                 $studentrecord .= $recording;
                   7703:             }
                   7704:             if ($studentrecord ne $studentdata) {
1.554     raeburn  7705:                 &Apache::lonxml::clear_problem_counter();
                   7706:                 if (&grade_student_bubbles($r,$uname,$udom,$scan_record,$scancode,
                   7707:                                            \@resources,\%partids_by_symb) eq 'ssi_error') {
                   7708:                     $ssi_error = 0; # So end of handler error message does not trigger.
                   7709:                     $r->print("</form>");
                   7710:                     &ssi_print_error($r);
                   7711:                     &Apache::lonnet::remove_lock($lock);
                   7712:                     delete($completedstudents{$uname});
                   7713:                     return '';
                   7714:                 }
1.542     raeburn  7715:                 $counter = -1;
                   7716:                 $studentrecord = '';
                   7717:                 foreach my $resource (@resources) {
1.554     raeburn  7718:                     my $ressymb = $resource->symb();
1.542     raeburn  7719:                     ($counter,my $recording) =
                   7720:                         &verify_scantron_grading($resource,$udom,$uname,$env{'request.course.id'},
1.554     raeburn  7721:                                                  $counter,$studentdata,$partids_by_symb{$ressymb},
1.542     raeburn  7722:                                                  \%scantron_config,\%lettdig,$numletts);
                   7723:                     $studentrecord .= $recording;
                   7724:                 }
                   7725:                 if ($studentrecord ne $studentdata) {
                   7726:                     $r->print('<p><span class="LC_error">');
                   7727:                     if ($scancode eq '') {
                   7728:                         $r->print(&mt('Mismatch grading bubble sheet for user: [_1] with ID: [_2].',
                   7729:                                   $uname.':'.$udom,$scan_record->{'scantron.ID'}));
                   7730:                     } else {
                   7731:                         $r->print(&mt('Mismatch grading bubble sheet for user: [_1] with ID: [_2] and CODE: [_3].',
                   7732:                                   $uname.':'.$udom,$scan_record->{'scantron.ID'},$scancode));
                   7733:                     }
                   7734:                     $r->print('</span><br />'.&Apache::loncommon::start_data_table()."\n".
                   7735:                               &Apache::loncommon::start_data_table_header_row()."\n".
                   7736:                               '<th>'.&mt('Source').'</th><th>'.&mt('Bubbled responses').'</th>'.
                   7737:                               &Apache::loncommon::end_data_table_header_row()."\n".
                   7738:                               &Apache::loncommon::start_data_table_row().
                   7739:                               '<td>'.&mt('Bubble Sheet').'</td>'.
                   7740:                               '<td><span class="LC_nobreak">'.$studentdata.'</span></td>'.
                   7741:                               &Apache::loncommon::end_data_table_row().
                   7742:                               &Apache::loncommon::start_data_table_row().
                   7743:                               '<td>Stored submissions</td>'.
                   7744:                               '<td><span class="LC_nobreak">'.$studentrecord.'</span></td>'."\n".
                   7745:                               &Apache::loncommon::end_data_table_row().
                   7746:                               &Apache::loncommon::end_data_table().'</p>');
                   7747:                 } else {
                   7748:                     $r->print('<br /><span class="LC_warning">'.
                   7749:                              &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 />'.
                   7750:                              &mt("As a consequence, this user's submission history records two tries.").
                   7751:                                  '</span><br />');
                   7752:                 }
                   7753:             }
                   7754:         }
1.543     raeburn  7755:         if (&Apache::loncommon::connection_aborted($r)) { last; }
1.140     albertel 7756:     } continue {
1.330     albertel 7757: 	&Apache::lonxml::clear_problem_counter();
1.552     raeburn  7758: 	&Apache::lonnet::delenv('scantron.');
1.82      albertel 7759:     }
1.140     albertel 7760:     &Apache::lonhtmlcommon::Close_PrgWin($r,\%prog_state);
1.520     www      7761:     &Apache::lonnet::remove_lock($lock);
1.172     albertel 7762: #    my $lasttime = &Time::HiRes::time()-$start;
                   7763: #    $r->print("<p>took $lasttime</p>");
1.140     albertel 7764: 
1.200     albertel 7765:     $r->print("</form>");
1.157     albertel 7766:     return '';
1.75      albertel 7767: }
1.157     albertel 7768: 
1.557     raeburn  7769: sub graders_resources_pass {
                   7770:     my ($resources,$grader_partids_by_symb,$grader_randomlists_by_symb) = @_;
                   7771:     if ((ref($resources) eq 'ARRAY') && (ref($grader_partids_by_symb)) && 
                   7772:         (ref($grader_randomlists_by_symb) eq 'HASH')) {
                   7773:         foreach my $resource (@{$resources}) {
                   7774:             my $ressymb = $resource->symb();
                   7775:             my ($analysis,$parts) =
                   7776:                 &scantron_partids_tograde($resource,$env{'request.course.id'},
                   7777:                                           $env{'user.name'},$env{'user.domain'},1);
                   7778:             $grader_partids_by_symb->{$ressymb} = $parts;
                   7779:             if (ref($analysis) eq 'HASH') {
                   7780:                 if (ref($analysis->{'parts_withrandomlist'}) eq 'ARRAY') {
                   7781:                     $grader_randomlists_by_symb->{$ressymb} =
                   7782:                         $analysis->{'parts_withrandomlist'};
                   7783:                 }
                   7784:             }
                   7785:         }
                   7786:     }
                   7787:     return;
                   7788: }
                   7789: 
1.542     raeburn  7790: sub grade_student_bubbles {
1.554     raeburn  7791:     my ($r,$uname,$udom,$scan_record,$scancode,$resources,$parts) = @_;
                   7792:     if (ref($resources) eq 'ARRAY') {
                   7793:         my $count = 0;
                   7794:         foreach my $resource (@{$resources}) {
                   7795:             my $ressymb = $resource->symb();
                   7796:             my %form = ('submitted'      => 'scantron',
                   7797:                         'grade_target'   => 'grade',
                   7798:                         'grade_username' => $uname,
                   7799:                         'grade_domain'   => $udom,
                   7800:                         'grade_courseid' => $env{'request.course.id'},
                   7801:                         'grade_symb'     => $ressymb,
                   7802:                         'CODE'           => $scancode
                   7803:                        );
                   7804:             if (ref($parts) eq 'HASH') {
                   7805:                 if (ref($parts->{$ressymb}) eq 'ARRAY') {
                   7806:                     foreach my $part (@{$parts->{$ressymb}}) {
                   7807:                         $form{'scantron_questnum_start.'.$part} =
                   7808:                             1+$env{'form.scantron.first_bubble_line.'.$count};
                   7809:                         $count++;
                   7810:                     }
                   7811:                 }
                   7812:             }
                   7813:             my $result=&ssi_with_retries($resource->src(),$ssi_retries,%form);
                   7814:             return 'ssi_error' if ($ssi_error);
                   7815:             last if (&Apache::loncommon::connection_aborted($r));
                   7816:         }
1.542     raeburn  7817:     }
                   7818:     return;
                   7819: }
                   7820: 
1.157     albertel 7821: sub scantron_upload_scantron_data {
1.608     www      7822:     my ($r,$symb)=@_;
1.565     raeburn  7823:     my $dom = $env{'request.role.domain'};
                   7824:     my $domdesc = &Apache::lonnet::domain($dom,'description');
                   7825:     $r->print(&Apache::loncommon::coursebrowser_javascript($dom));
1.157     albertel 7826:     my $select_link=&Apache::loncommon::selectcourse_link('rules','courseid',
1.181     albertel 7827: 							  'domainid',
1.565     raeburn  7828: 							  'coursename',$dom);
                   7829:     my $syllabuslink = '<a href="javascript:ToSyllabus();">'.&mt('Syllabus').'</a>'.
                   7830:                        ('&nbsp'x2).&mt('(shows course personnel)'); 
1.608     www      7831:     my $default_form_data=&defaultFormData($symb);
1.579     raeburn  7832:     my $nofile_alert = &mt('Please use the browse button to select a file from your local directory.');
                   7833:     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 7834:     $r->print(&Apache::lonhtmlcommon::scripttag('
1.157     albertel 7835:     function checkUpload(formname) {
                   7836: 	if (formname.upfile.value == "") {
1.579     raeburn  7837: 	    alert("'.$nofile_alert.'");
1.157     albertel 7838: 	    return false;
                   7839: 	}
1.565     raeburn  7840:         if (formname.courseid.value == "") {
1.579     raeburn  7841:             alert("'.$nocourseid_alert.'");
1.565     raeburn  7842:             return false;
                   7843:         }
1.157     albertel 7844: 	formname.submit();
                   7845:     }
1.565     raeburn  7846: 
                   7847:     function ToSyllabus() {
                   7848:         var cdom = '."'$dom'".';
                   7849:         var cnum = document.rules.courseid.value;
                   7850:         if (cdom == "" || cdom == null) {
                   7851:             return;
                   7852:         }
                   7853:         if (cnum == "" || cnum == null) {
                   7854:            return;
                   7855:         }
                   7856:         syllwin=window.open("/public/"+cdom+"/"+cnum+"/syllabus","LONCAPASyllabus",
                   7857:                             "height=350,width=350,scrollbars=yes,menubar=no");
                   7858:         return;
                   7859:     }
                   7860: 
1.597     wenzelju 7861: '));
                   7862:     $r->print('
1.566     raeburn  7863: <h3>'.&mt('Send scanned bubblesheet data to a course').'</h3>
                   7864: 
1.492     albertel 7865: <form enctype="multipart/form-data" action="/adm/grades" name="rules" method="post">
1.565     raeburn  7866: '.$default_form_data.
                   7867:   &Apache::lonhtmlcommon::start_pick_box().
                   7868:   &Apache::lonhtmlcommon::row_title(&mt('Course ID')).
                   7869:   '<input name="courseid" type="text" size="30" />'.$select_link.
                   7870:   &Apache::lonhtmlcommon::row_closure().
                   7871:   &Apache::lonhtmlcommon::row_title(&mt('Course Name')).
                   7872:   '<input name="coursename" type="text" size="30" />'.$syllabuslink.
                   7873:   &Apache::lonhtmlcommon::row_closure().
                   7874:   &Apache::lonhtmlcommon::row_title(&mt('Domain')).
                   7875:   '<input name="domainid" type="hidden" />'.$domdesc.
                   7876:   &Apache::lonhtmlcommon::row_closure().
                   7877:   &Apache::lonhtmlcommon::row_title(&mt('File to upload')).
                   7878:   '<input type="file" name="upfile" size="50" />'.
                   7879:   &Apache::lonhtmlcommon::row_closure(1).
                   7880:   &Apache::lonhtmlcommon::end_pick_box().'<br />
                   7881: 
1.492     albertel 7882: <input name="command" value="scantronupload_save" type="hidden" />
1.589     bisitz   7883: <input type="button" onclick="javascript:checkUpload(this.form);" value="'.&mt('Upload Bubblesheet Data').'" />
1.157     albertel 7884: </form>
1.492     albertel 7885: ');
1.157     albertel 7886:     return '';
                   7887: }
                   7888: 
1.423     albertel 7889: 
1.157     albertel 7890: sub scantron_upload_scantron_data_save {
1.608     www      7891:     my($r,$symb)=@_;
1.182     albertel 7892:     my $doanotherupload=
                   7893: 	'<br /><form action="/adm/grades" method="post">'."\n".
                   7894: 	'<input type="hidden" name="command" value="scantronupload" />'."\n".
1.492     albertel 7895: 	'<input type="submit" name="submit" value="'.&mt('Do Another Upload').'" />'."\n".
1.182     albertel 7896: 	'</form>'."\n";
1.257     albertel 7897:     if (!&Apache::lonnet::allowed('usc',$env{'form.domainid'}) &&
1.162     albertel 7898: 	!&Apache::lonnet::allowed('usc',
1.257     albertel 7899: 			    $env{'form.domainid'}.'_'.$env{'form.courseid'})) {
1.575     www      7900: 	$r->print(&mt("You are not allowed to upload bubblesheet data to the requested course.")."<br />");
1.614     www      7901: 	unless ($symb) {
1.182     albertel 7902: 	    $r->print($doanotherupload);
                   7903: 	}
1.162     albertel 7904: 	return '';
                   7905:     }
1.257     albertel 7906:     my %coursedata=&Apache::lonnet::coursedescription($env{'form.domainid'}.'_'.$env{'form.courseid'});
1.568     raeburn  7907:     my $uploadedfile;
1.567     raeburn  7908:     $r->print('<h3>'.&mt("Uploading file to [_1]",$coursedata{'description'}).'</h3>');
1.257     albertel 7909:     if (length($env{'form.upfile'}) < 2) {
1.568     raeburn  7910:         $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 7911:     } else {
1.568     raeburn  7912:         my $result = 
                   7913:             &Apache::lonnet::userfileupload('upfile','','scantron','','','',
                   7914:                                             $env{'form.courseid'},$env{'form.domainid'});
                   7915: 	if ($result =~ m{^/uploaded/}) {
1.567     raeburn  7916: 	    $r->print(&mt('[_1]Success:[_2] Successfully uploaded [_3] bytes of data into location: [_4]',
                   7917:                           '<span class="LC_success">','</span>',(length($env{'form.upfile'})-1),
                   7918: 			  '<span class="LC_filename">'.$result.'</span>'));
1.568     raeburn  7919:             ($uploadedfile) = ($result =~ m{/([^/]+)$});
1.567     raeburn  7920:             $r->print(&validate_uploaded_scantron_file($env{'form.domainid'},
1.568     raeburn  7921:                                                        $env{'form.courseid'},$uploadedfile));
1.210     albertel 7922: 	} else {
1.567     raeburn  7923: 	    $r->print(&mt('[_1]Error:[_2] An error ([_3]) occurred when attempting to upload the file, [_4]',
                   7924:                           '<span class="LC_error">','</span>',$result,
1.568     raeburn  7925: 			  '<span class="LC_filename">'.&HTML::Entities::encode($env{'form.upfile.filename'},'<>&"').'</span>'));
1.183     albertel 7926: 	}
                   7927:     }
1.174     albertel 7928:     if ($symb) {
1.612     www      7929: 	$r->print(&scantron_selectphase($r,$uploadedfile,$symb));
1.174     albertel 7930:     } else {
1.182     albertel 7931: 	$r->print($doanotherupload);
1.174     albertel 7932:     }
1.157     albertel 7933:     return '';
                   7934: }
                   7935: 
1.567     raeburn  7936: sub validate_uploaded_scantron_file {
                   7937:     my ($cdom,$cname,$fname) = @_;
                   7938:     my $scanlines=&Apache::lonnet::getfile('/uploaded/'.$cdom.'/'.$cname.'/'.$fname);
                   7939:     my @lines;
                   7940:     if ($scanlines ne '-1') {
                   7941:         @lines=split("\n",$scanlines,-1);
                   7942:     }
                   7943:     my $output;
                   7944:     if (@lines) {
                   7945:         my (%counts,$max_match_format);
                   7946:         my ($max_match_count,$max_match_pct) = (0,0);
                   7947:         my $classlist = &Apache::loncoursedata::get_classlist($cdom,$cname);
                   7948:         my %idmap = &username_to_idmap($classlist);
                   7949:         foreach my $key (keys(%idmap)) {
                   7950:             my $lckey = lc($key);
                   7951:             $idmap{$lckey} = $idmap{$key};
                   7952:         }
                   7953:         my %unique_formats;
                   7954:         my @formatlines = &get_scantronformat_file();
                   7955:         foreach my $line (@formatlines) {
                   7956:             chomp($line);
                   7957:             my @config = split(/:/,$line);
                   7958:             my $idstart = $config[5];
                   7959:             my $idlength = $config[6];
                   7960:             if (($idstart ne '') && ($idlength > 0)) {
                   7961:                 if (ref($unique_formats{$idstart.':'.$idlength}) eq 'ARRAY') {
                   7962:                     push(@{$unique_formats{$idstart.':'.$idlength}},$config[0].':'.$config[1]); 
                   7963:                 } else {
                   7964:                     $unique_formats{$idstart.':'.$idlength} = [$config[0].':'.$config[1]];
                   7965:                 }
                   7966:             }
                   7967:         }
                   7968:         foreach my $key (keys(%unique_formats)) {
                   7969:             my ($idstart,$idlength) = split(':',$key);
                   7970:             %{$counts{$key}} = (
                   7971:                                'found'   => 0,
                   7972:                                'total'   => 0,
                   7973:                               );
                   7974:             foreach my $line (@lines) {
                   7975:                 next if ($line =~ /^#/);
                   7976:                 next if ($line =~ /^[\s\cz]*$/);
                   7977:                 my $id = substr($line,$idstart-1,$idlength);
                   7978:                 $id = lc($id);
                   7979:                 if (exists($idmap{$id})) {
                   7980:                     $counts{$key}{'found'} ++;
                   7981:                 }
                   7982:                 $counts{$key}{'total'} ++;
                   7983:             }
                   7984:             if ($counts{$key}{'total'}) {
                   7985:                 my $percent_match = (100*$counts{$key}{'found'})/($counts{$key}{'total'});
                   7986:                 if (($max_match_format eq '') || ($percent_match > $max_match_pct)) {
                   7987:                     $max_match_pct = $percent_match;
                   7988:                     $max_match_format = $key;
                   7989:                     $max_match_count = $counts{$key}{'total'};
                   7990:                 }
                   7991:             }
                   7992:         }
                   7993:         if (ref($unique_formats{$max_match_format}) eq 'ARRAY') {
                   7994:             my $format_descs;
                   7995:             my $numwithformat = @{$unique_formats{$max_match_format}};
                   7996:             for (my $i=0; $i<$numwithformat; $i++) {
                   7997:                 my ($name,$desc) = split(':',$unique_formats{$max_match_format}[$i]);
                   7998:                 if ($i<$numwithformat-2) {
                   7999:                     $format_descs .= '"<i>'.$desc.'</i>", ';
                   8000:                 } elsif ($i==$numwithformat-2) {
                   8001:                     $format_descs .= '"<i>'.$desc.'</i>" '.&mt('and').' ';
                   8002:                 } elsif ($i==$numwithformat-1) {
                   8003:                     $format_descs .= '"<i>'.$desc.'</i>"';
                   8004:                 }
                   8005:             }
                   8006:             my $showpct = sprintf("%.0f",$max_match_pct).'%';
                   8007:             $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).
                   8008:                        '<br />'.&mt('A low percentage of matches results from one of the following:').'<ul>'.
                   8009:                        '<li>'.&mt('The file was uploaded to the wrong course').'</li>'.
                   8010:                        '<li>'.&mt('The data are not in the format expected for the domain: [_1]',
                   8011:                                   '<i>'.$cdom.'</i>').'</li>'.
                   8012:                        '<li>'.&mt('Students did not bubble their IDs, or mis-bubbled them').'</li>'.
                   8013:                        '<li>'.&mt('The course roster is not up to date').'</li>'.
                   8014:                        '</ul>';
                   8015:         }
                   8016:     } else {
                   8017:         $output = '<span class="LC_warning">'.&mt('Uploaded file contained no data').'</span>';
                   8018:     }
                   8019:     return $output;
                   8020: }
                   8021: 
1.202     albertel 8022: sub valid_file {
                   8023:     my ($requested_file)=@_;
                   8024:     foreach my $filename (sort(&scantron_filenames())) {
                   8025: 	if ($requested_file eq $filename) { return 1; }
                   8026:     }
                   8027:     return 0;
                   8028: }
                   8029: 
                   8030: sub scantron_download_scantron_data {
1.608     www      8031:     my ($r,$symb)=@_;
                   8032:     my $default_form_data=&defaultFormData($symb);
1.257     albertel 8033:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   8034:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
                   8035:     my $file=$env{'form.scantron_selectfile'};
1.202     albertel 8036:     if (! &valid_file($file)) {
1.492     albertel 8037: 	$r->print('
1.202     albertel 8038: 	<p>
1.492     albertel 8039: 	    '.&mt('The requested file name was invalid.').'
1.202     albertel 8040:         </p>
1.492     albertel 8041: ');
1.202     albertel 8042: 	return;
                   8043:     }
                   8044:     my $orig='/uploaded/'.$cdom.'/'.$cname.'/scantron_orig_'.$file;
                   8045:     my $corrected='/uploaded/'.$cdom.'/'.$cname.'/scantron_corrected_'.$file;
                   8046:     my $skipped='/uploaded/'.$cdom.'/'.$cname.'/scantron_skipped_'.$file;
                   8047:     &Apache::lonnet::allowuploaded('/adm/grades',$orig);
                   8048:     &Apache::lonnet::allowuploaded('/adm/grades',$corrected);
                   8049:     &Apache::lonnet::allowuploaded('/adm/grades',$skipped);
1.492     albertel 8050:     $r->print('
1.202     albertel 8051:     <p>
1.492     albertel 8052: 	'.&mt('[_1]Original[_2] file as uploaded by the scantron office.',
                   8053: 	      '<a href="'.$orig.'">','</a>').'
1.202     albertel 8054:     </p>
                   8055:     <p>
1.492     albertel 8056: 	'.&mt('[_1]Corrections[_2], a file of corrected records that were used in grading.',
                   8057: 	      '<a href="'.$corrected.'">','</a>').'
1.202     albertel 8058:     </p>
                   8059:     <p>
1.492     albertel 8060: 	'.&mt('[_1]Skipped[_2], a file of records that were skipped.',
                   8061: 	      '<a href="'.$skipped.'">','</a>').'
1.202     albertel 8062:     </p>
1.492     albertel 8063: ');
1.202     albertel 8064:     return '';
                   8065: }
1.157     albertel 8066: 
1.523     raeburn  8067: sub checkscantron_results {
1.608     www      8068:     my ($r,$symb) = @_;
1.523     raeburn  8069:     if (!$symb) {return '';}
                   8070:     my $cid = $env{'request.course.id'};
1.542     raeburn  8071:     my %lettdig = &letter_to_digits();
1.523     raeburn  8072:     my $numletts = scalar(keys(%lettdig));
                   8073:     my $cnum = $env{'course.'.$cid.'.num'};
                   8074:     my $cdom = $env{'course.'.$cid.'.domain'};
                   8075:     my (undef, undef, $sequence) = &Apache::lonnet::decode_symb($env{'form.selectpage'});
                   8076:     my %record;
                   8077:     my %scantron_config =
                   8078:         &Apache::grades::get_scantron_config($env{'form.scantron_format'});
                   8079:     my ($scanlines,$scan_data)=&Apache::grades::scantron_getfile();
                   8080:     my $classlist=&Apache::loncoursedata::get_classlist();
                   8081:     my %idmap=&Apache::grades::username_to_idmap($classlist);
                   8082:     my $navmap=Apache::lonnavmaps::navmap->new();
1.582     raeburn  8083:     unless (ref($navmap)) {
                   8084:         $r->print(&navmap_errormsg());
                   8085:         return '';
                   8086:     }
1.523     raeburn  8087:     my $map=$navmap->getResourceByUrl($sequence);
1.557     raeburn  8088:     my @resources=$navmap->retrieveResources($map,\&scantron_filter,1,0);
                   8089:     my (%grader_partids_by_symb,%grader_randomlists_by_symb);
                   8090:     &graders_resources_pass(\@resources,\%grader_partids_by_symb,                             \%grader_randomlists_by_symb);
                   8091: 
1.554     raeburn  8092:     my ($uname,$udom);
1.523     raeburn  8093:     my (%scandata,%lastname,%bylast);
                   8094:     $r->print('
                   8095: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="checkscantron">'."\n");
                   8096: 
                   8097:     my @delayqueue;
                   8098:     my %completedstudents;
                   8099: 
                   8100:     my $count=&Apache::grades::get_todo_count($scanlines,$scan_data);
1.581     www      8101:     my %prog_state=&Apache::lonhtmlcommon::Create_PrgWin($r,'Bubblesheet/Submissions Comparison Status',
                   8102:                                     'Progress of Bubblesheet Data/Submission Records Comparison',$count,
1.523     raeburn  8103:                                     'inline',undef,'checkscantron');
1.546     raeburn  8104:     my ($username,$domain,$started);
1.582     raeburn  8105:     my $nav_error;
                   8106:     &scantron_get_maxbubble(\$nav_error); # Need the bubble lines array to parse.
                   8107:     if ($nav_error) {
                   8108:         $r->print(&navmap_errormsg());
                   8109:         return '';
                   8110:     }
1.523     raeburn  8111: 
                   8112:     &Apache::lonhtmlcommon::Update_PrgWin($r,\%prog_state,
                   8113:                                           'Processing first student');
                   8114:     my $start=&Time::HiRes::time();
                   8115:     my $i=-1;
                   8116: 
                   8117:     while ($i<$scanlines->{'count'}) {
                   8118:         ($username,$domain,$uname)=('','','');
                   8119:         $i++;
                   8120:         my $line=&Apache::grades::scantron_get_line($scanlines,$scan_data,$i);
                   8121:         if ($line=~/^[\s\cz]*$/) { next; }
                   8122:         if ($started) {
                   8123:             &Apache::lonhtmlcommon::Increment_PrgWin($r,\%prog_state,
                   8124:                                                      'last student');
                   8125:         }
                   8126:         $started=1;
                   8127:         my $scan_record=
                   8128:             &Apache::grades::scantron_parse_scanline($line,$i,\%scantron_config,
                   8129:                                                      $scan_data);
                   8130:         unless ($uname=&Apache::grades::scantron_find_student($scan_record,$scan_data,
                   8131:                                                               \%idmap,$i)) {
                   8132:             &Apache::grades::scantron_add_delay(\@delayqueue,$line,
                   8133:                                 'Unable to find a student that matches',1);
                   8134:             next;
                   8135:         }
                   8136:         if (exists $completedstudents{$uname}) {
                   8137:             &Apache::grades::scantron_add_delay(\@delayqueue,$line,
                   8138:                                 'Student '.$uname.' has multiple sheets',2);
                   8139:             next;
                   8140:         }
                   8141:         my $pid = $scan_record->{'scantron.ID'};
                   8142:         $lastname{$pid} = $scan_record->{'scantron.LastName'};
                   8143:         push(@{$bylast{$lastname{$pid}}},$pid);
                   8144:         my $lastpos = $env{'form.scantron_maxbubble'}*$scantron_config{'Qlength'};
                   8145:         $scandata{$pid} = substr($line,$scantron_config{'Qstart'}-1,$lastpos);
                   8146:         chomp($scandata{$pid});
                   8147:         $scandata{$pid} =~ s/\r$//;
                   8148:         ($username,$domain)=split(/:/,$uname);
                   8149:         my $counter = -1;
                   8150:         foreach my $resource (@resources) {
1.557     raeburn  8151:             my $parts;
1.554     raeburn  8152:             my $ressymb = $resource->symb();
1.557     raeburn  8153:             if ((exists($grader_randomlists_by_symb{$ressymb})) ||
                   8154:                 (ref($grader_partids_by_symb{$ressymb}) ne 'ARRAY')) {
                   8155:                 (my $analysis,$parts) =
                   8156:                     &scantron_partids_tograde($resource,$env{'request.course.id'},$username,$domain);
                   8157:             } else {
                   8158:                 $parts = $grader_partids_by_symb{$ressymb};
                   8159:             }
1.542     raeburn  8160:             ($counter,my $recording) =
                   8161:                 &verify_scantron_grading($resource,$domain,$username,$cid,$counter,
1.554     raeburn  8162:                                          $scandata{$pid},$parts,
1.542     raeburn  8163:                                          \%scantron_config,\%lettdig,$numletts);
                   8164:             $record{$pid} .= $recording;
1.523     raeburn  8165:         }
                   8166:     }
                   8167:     &Apache::lonhtmlcommon::Close_PrgWin($r,\%prog_state);
                   8168:     $r->print('<br />');
                   8169:     my ($okstudents,$badstudents,$numstudents,$passed,$failed);
                   8170:     $passed = 0;
                   8171:     $failed = 0;
                   8172:     $numstudents = 0;
                   8173:     foreach my $last (sort(keys(%bylast))) {
                   8174:         if (ref($bylast{$last}) eq 'ARRAY') {
                   8175:             foreach my $pid (sort(@{$bylast{$last}})) {
                   8176:                 my $showscandata = $scandata{$pid};
                   8177:                 my $showrecord = $record{$pid};
                   8178:                 $showscandata =~ s/\s/&nbsp;/g;
                   8179:                 $showrecord =~ s/\s/&nbsp;/g;
                   8180:                 if ($scandata{$pid} eq $record{$pid}) {
                   8181:                     my $css_class = ($passed % 2)?'LC_odd_row':'LC_even_row';
                   8182:                     $okstudents .= '<tr class="'.$css_class.'">'.
1.581     www      8183: '<td>'.&mt('Bubblesheet').'</td><td>'.$showscandata.'</td><td rowspan="2">'.$last.'</td><td rowspan="2">'.$pid.'</td>'."\n".
1.523     raeburn  8184: '</tr>'."\n".
                   8185: '<tr class="'.$css_class.'">'."\n".
                   8186: '<td>Submissions</td><td>'.$showrecord.'</td></tr>'."\n";
                   8187:                     $passed ++;
                   8188:                 } else {
                   8189:                     my $css_class = ($failed % 2)?'LC_odd_row':'LC_even_row';
1.581     www      8190:                     $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  8191: '</tr>'."\n".
                   8192: '<tr class="'.$css_class.'">'."\n".
                   8193: '<td>Submissions</td><td><span class="LC_nobreak">'.$record{$pid}.'</span></td>'."\n".
                   8194: '</tr>'."\n";
                   8195:                     $failed ++;
                   8196:                 }
                   8197:                 $numstudents ++;
                   8198:             }
                   8199:         }
                   8200:     }
1.572     www      8201:     $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  8202:     $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>');
                   8203:     if ($passed) {
1.572     www      8204:         $r->print(&mt('Students with exact correspondence between bubblesheet data and submissions are as follows:').'<br /><br />');
1.523     raeburn  8205:         $r->print(&Apache::loncommon::start_data_table()."\n".
                   8206:                  &Apache::loncommon::start_data_table_header_row()."\n".
                   8207:                  '<th>'.&mt('Source').'</th><th>'.&mt('Bubble records').'</th><th>'.&mt('Name').'</th><th>'.&mt('ID').'</th>'.
                   8208:                  &Apache::loncommon::end_data_table_header_row()."\n".
                   8209:                  $okstudents."\n".
                   8210:                  &Apache::loncommon::end_data_table().'<br />');
                   8211:     }
                   8212:     if ($failed) {
1.572     www      8213:         $r->print(&mt('Students with differences between bubblesheet data and submissions are as follows:').'<br /><br />');
1.523     raeburn  8214:         $r->print(&Apache::loncommon::start_data_table()."\n".
                   8215:                  &Apache::loncommon::start_data_table_header_row()."\n".
                   8216:                  '<th>'.&mt('Source').'</th><th>'.&mt('Bubble records').'</th><th>'.&mt('Name').'</th><th>'.&mt('ID').'</th>'.
                   8217:                  &Apache::loncommon::end_data_table_header_row()."\n".
                   8218:                  $badstudents."\n".
                   8219:                  &Apache::loncommon::end_data_table()).'<br />'.
1.572     www      8220:                  &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  8221:     }
1.614     www      8222:     $r->print('</form><br />');
1.523     raeburn  8223:     return;
                   8224: }
                   8225: 
1.542     raeburn  8226: sub verify_scantron_grading {
1.554     raeburn  8227:     my ($resource,$domain,$username,$cid,$counter,$scandata,$partids,
1.542     raeburn  8228:         $scantron_config,$lettdig,$numletts) = @_;
                   8229:     my ($record,%expected,%startpos);
                   8230:     return ($counter,$record) if (!ref($resource));
                   8231:     return ($counter,$record) if (!$resource->is_problem());
                   8232:     my $symb = $resource->symb();
1.554     raeburn  8233:     return ($counter,$record) if (ref($partids) ne 'ARRAY');
                   8234:     foreach my $part_id (@{$partids}) {
1.542     raeburn  8235:         $counter ++;
                   8236:         $expected{$part_id} = 0;
                   8237:         if ($env{"form.scantron.sub_bubblelines.$counter"}) {
                   8238:             my @sub_lines = split(/,/,$env{"form.scantron.sub_bubblelines.$counter"});
                   8239:             foreach my $item (@sub_lines) {
                   8240:                 $expected{$part_id} += $item;
                   8241:             }
                   8242:         } else {
                   8243:             $expected{$part_id} = $env{"form.scantron.bubblelines.$counter"};
                   8244:         }
                   8245:         $startpos{$part_id} = $env{"form.scantron.first_bubble_line.$counter"};
                   8246:     }
                   8247:     if ($symb) {
                   8248:         my %recorded;
                   8249:         my (%returnhash) = &Apache::lonnet::restore($symb,$cid,$domain,$username);
                   8250:         if ($returnhash{'version'}) {
                   8251:             my %lasthash=();
                   8252:             my $version;
                   8253:             for ($version=1;$version<=$returnhash{'version'};$version++) {
                   8254:                 foreach my $key (sort(split(/\:/,$returnhash{$version.':keys'}))) {
                   8255:                     $lasthash{$key}=$returnhash{$version.':'.$key};
                   8256:                 }
                   8257:             }
                   8258:             foreach my $key (keys(%lasthash)) {
                   8259:                 if ($key =~ /\.scantron$/) {
                   8260:                     my $value = &unescape($lasthash{$key});
                   8261:                     my ($part_id) = ($key =~ /^resource\.(.+)\.scantron$/);
                   8262:                     if ($value eq '') {
                   8263:                         for (my $i=0; $i<$expected{$part_id}; $i++) {
                   8264:                             for (my $j=0; $j<$scantron_config->{'length'}; $j++) {
                   8265:                                 $recorded{$part_id} .= $scantron_config->{'Qoff'};
                   8266:                             }
                   8267:                         }
                   8268:                     } else {
                   8269:                         my @tocheck;
                   8270:                         my @items = split(//,$value);
                   8271:                         if (($scantron_config->{'Qon'} eq 'letter') ||
                   8272:                             ($scantron_config->{'Qon'} eq 'number')) {
                   8273:                             if (@items < $expected{$part_id}) {
                   8274:                                 my $fragment = substr($scandata,$startpos{$part_id},$expected{$part_id});
                   8275:                                 my @singles = split(//,$fragment);
                   8276:                                 foreach my $pos (@singles) {
                   8277:                                     if ($pos eq ' ') {
                   8278:                                         push(@tocheck,$pos);
                   8279:                                     } else {
                   8280:                                         my $next = shift(@items);
                   8281:                                         push(@tocheck,$next);
                   8282:                                     }
                   8283:                                 }
                   8284:                             } else {
                   8285:                                 @tocheck = @items;
                   8286:                             }
                   8287:                             foreach my $letter (@tocheck) {
                   8288:                                 if ($scantron_config->{'Qon'} eq 'letter') {
                   8289:                                     if ($letter !~ /^[A-J]$/) {
                   8290:                                         $letter = $scantron_config->{'Qoff'};
                   8291:                                     }
                   8292:                                     $recorded{$part_id} .= $letter;
                   8293:                                 } elsif ($scantron_config->{'Qon'} eq 'number') {
                   8294:                                     my $digit;
                   8295:                                     if ($letter !~ /^[A-J]$/) {
                   8296:                                         $digit = $scantron_config->{'Qoff'};
                   8297:                                     } else {
                   8298:                                         $digit = $lettdig->{$letter};
                   8299:                                     }
                   8300:                                     $recorded{$part_id} .= $digit;
                   8301:                                 }
                   8302:                             }
                   8303:                         } else {
                   8304:                             @tocheck = @items;
                   8305:                             for (my $i=0; $i<$expected{$part_id}; $i++) {
                   8306:                                 my $curr_sub = shift(@tocheck);
                   8307:                                 my $digit;
                   8308:                                 if ($curr_sub =~ /^[A-J]$/) {
                   8309:                                     $digit = $lettdig->{$curr_sub}-1;
                   8310:                                 }
                   8311:                                 if ($curr_sub eq 'J') {
                   8312:                                     $digit += scalar($numletts);
                   8313:                                 }
                   8314:                                 for (my $j=0; $j<$scantron_config->{'Qlength'}; $j++) {
                   8315:                                     if ($j == $digit) {
                   8316:                                         $recorded{$part_id} .= $scantron_config->{'Qon'};
                   8317:                                     } else {
                   8318:                                         $recorded{$part_id} .= $scantron_config->{'Qoff'};
                   8319:                                     }
                   8320:                                 }
                   8321:                             }
                   8322:                         }
                   8323:                     }
                   8324:                 }
                   8325:             }
                   8326:         }
1.554     raeburn  8327:         foreach my $part_id (@{$partids}) {
1.542     raeburn  8328:             if ($recorded{$part_id} eq '') {
                   8329:                 for (my $i=0; $i<$expected{$part_id}; $i++) {
                   8330:                     for (my $j=0; $j<$scantron_config->{'Qlength'}; $j++) {
                   8331:                         $recorded{$part_id} .= $scantron_config->{'Qoff'};
                   8332:                     }
                   8333:                 }
                   8334:             }
                   8335:             $record .= $recorded{$part_id};
                   8336:         }
                   8337:     }
                   8338:     return ($counter,$record);
                   8339: }
                   8340: 
                   8341: sub letter_to_digits { 
                   8342:     my %lettdig = (
                   8343:                     A => 1,
                   8344:                     B => 2,
                   8345:                     C => 3,
                   8346:                     D => 4,
                   8347:                     E => 5,
                   8348:                     F => 6,
                   8349:                     G => 7,
                   8350:                     H => 8,
                   8351:                     I => 9,
                   8352:                     J => 0,
                   8353:                   );
                   8354:     return %lettdig;
                   8355: }
                   8356: 
1.423     albertel 8357: 
1.75      albertel 8358: #-------- end of section for handling grading scantron forms -------
                   8359: #
                   8360: #-------------------------------------------------------------------
                   8361: 
1.72      ng       8362: #-------------------------- Menu interface -------------------------
                   8363: #
1.614     www      8364: #--- Href with symb and command ---
                   8365: 
                   8366: sub href_symb_cmd {
                   8367:     my ($symb,$cmd)=@_;
                   8368:     return '/adm/grades?symb='.&HTML::Entities::encode(&Apache::lonenc::check_encrypt($symb),'<>&"').'&command='.$cmd;
1.72      ng       8369: }
                   8370: 
1.443     banghart 8371: sub grading_menu {
1.608     www      8372:     my ($request,$symb) = @_;
1.443     banghart 8373:     if (!$symb) {return '';}
                   8374: 
                   8375:     my %fields = ('symb'=>&Apache::lonenc::check_encrypt($symb),
1.618     www      8376:                   'command'=>'individual');
1.538     schulted 8377:     
1.598     www      8378:     my $url1a = &Apache::lonhtmlcommon::build_url('grades/',\%fields);
                   8379: 
                   8380:     $fields{'command'}='ungraded';
                   8381:     my $url1b=&Apache::lonhtmlcommon::build_url('grades/',\%fields);
                   8382: 
                   8383:     $fields{'command'}='table';
                   8384:     my $url1c=&Apache::lonhtmlcommon::build_url('grades/',\%fields);
                   8385: 
                   8386:     $fields{'command'}='all_for_one';
                   8387:     my $url1d=&Apache::lonhtmlcommon::build_url('grades/',\%fields);
                   8388: 
1.443     banghart 8389:     $fields{'command'} = 'csvform';
1.538     schulted 8390:     my $url2 = &Apache::lonhtmlcommon::build_url('grades/',\%fields);
                   8391:     
1.443     banghart 8392:     $fields{'command'} = 'processclicker';
1.538     schulted 8393:     my $url3 = &Apache::lonhtmlcommon::build_url('grades/',\%fields);
                   8394:     
1.443     banghart 8395:     $fields{'command'} = 'scantron_selectphase';
1.538     schulted 8396:     my $url4 = &Apache::lonhtmlcommon::build_url('grades/',\%fields);
1.602     www      8397: 
                   8398:     $fields{'command'} = 'initialverifyreceipt';
                   8399:     my $url5 = &Apache::lonhtmlcommon::build_url('grades/',\%fields);
1.538     schulted 8400:     
1.598     www      8401:     my @menu = ({	categorytitle=>'Hand Grading',
1.538     schulted 8402:             items =>[
1.598     www      8403:                         {	linktext => 'Select individual students to grade',
                   8404:                     		url => $url1a,
1.538     schulted 8405:                     		permission => 'F',
                   8406:                     		icon => 'edit-find-replace.png',
1.598     www      8407:                     		linktitle => 'Grade current resource for a selection of students.'
                   8408:                         }, 
                   8409:                         {       linktext => 'Grade ungraded submissions.',
                   8410:                                 url => $url1b,
                   8411:                                 permission => 'F',
                   8412:                                 icon => 'edit-find-replace.png',
                   8413:                                 linktitle => 'Grade all submissions that have not been graded yet.'
1.538     schulted 8414:                         },
1.598     www      8415: 
                   8416:                         {       linktext => 'Grading table',
                   8417:                                 url => $url1c,
                   8418:                                 permission => 'F',
                   8419:                                 icon => 'edit-find-replace.png',
                   8420:                                 linktitle => 'Grade current resource for all students.'
                   8421:                         },
1.615     www      8422:                         {       linktext => 'Grade page/folder for one student',
1.598     www      8423:                                 url => $url1d,
                   8424:                                 permission => 'F',
                   8425:                                 icon => 'edit-find-replace.png',
                   8426:                                 linktitle => 'Grade all resources in current page/sequence/folder for one student.'
                   8427:                         }]},
                   8428:                          { categorytitle=>'Automated Grading',
                   8429:                items =>[
                   8430: 
1.538     schulted 8431:                 	    {	linktext => 'Upload Scores',
                   8432:                     		url => $url2,
                   8433:                     		permission => 'F',
                   8434:                     		icon => 'uploadscores.png',
                   8435:                     		linktitle => 'Specify a file containing the class scores for current resource.'
                   8436:                 	    },
                   8437:                 	    {	linktext => 'Process Clicker',
                   8438:                     		url => $url3,
                   8439:                     		permission => 'F',
                   8440:                     		icon => 'addClickerInfoFile.png',
                   8441:                     		linktitle => 'Specify a file containing the clicker information for this resource.'
                   8442:                 	    },
1.587     raeburn  8443:                 	    {	linktext => 'Grade/Manage/Review Bubblesheets',
1.538     schulted 8444:                     		url => $url4,
                   8445:                     		permission => 'F',
                   8446:                     		icon => 'stat.png',
                   8447:                     		linktitle => 'Grade scantron exams, upload/download scantron data files, and review previously graded scantron exams.'
1.602     www      8448:                 	    },
1.616     www      8449:                             {   linktext => 'Verify Receipt Number',
1.602     www      8450:                                 url => $url5,
                   8451:                                 permission => 'F',
                   8452:                                 icon => 'edit-find-replace.png',
                   8453:                                 linktitle => 'Verify a system-generated receipt number for correct problem solution.'
                   8454:                             }
                   8455: 
1.538     schulted 8456:                     ]
                   8457:             });
                   8458: 
1.443     banghart 8459:     # Create the menu
                   8460:     my $Str;
1.445     banghart 8461:     $Str .= '<form method="post" action="" name="gradingMenu">';
                   8462:     $Str .= '<input type="hidden" name="command" value="" />'.
1.618     www      8463:     	'<input type="hidden" name="symb"        value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n";
1.445     banghart 8464: 
1.602     www      8465:     $Str .= &Apache::lonhtmlcommon::generate_menu(@menu);
1.443     banghart 8466:     return $Str;    
                   8467: }
                   8468: 
1.598     www      8469: 
                   8470: sub ungraded {
                   8471:     my ($request)=@_;
                   8472:     &submit_options($request);
                   8473: }
                   8474: 
1.599     www      8475: sub submit_options_sequence {
1.608     www      8476:     my ($request,$symb) = @_;
1.599     www      8477:     if (!$symb) {return '';}
1.600     www      8478:     &commonJSfunctions($request);
                   8479:     my $result;
1.599     www      8480: 
1.600     www      8481:     $result.='<form action="/adm/grades" method="post" name="gradingMenu">'."\n".
1.618     www      8482:         '<input type="hidden" name="symb"        value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n";
1.600     www      8483:     $result.='
                   8484: <h2>
1.615     www      8485:   '.&mt('Grade page/folder for one student').'
1.601     www      8486: </h2>'.
                   8487:             &selectfield(0).
                   8488:             '<input type="hidden" name="command" value="pickStudentPage" />
1.600     www      8489:             <div>
                   8490:               <input type="submit" value="'.&mt('Next').' &rarr;" />
                   8491:             </div>
                   8492:         </div>
                   8493:   </form>';
                   8494:     return $result;
                   8495: }
                   8496: 
                   8497: sub submit_options_table {
1.608     www      8498:     my ($request,$symb) = @_;
1.600     www      8499:     if (!$symb) {return '';}
1.599     www      8500:     &commonJSfunctions($request);
                   8501:     my $result;
                   8502: 
                   8503:     $result.='<form action="/adm/grades" method="post" name="gradingMenu">'."\n".
1.618     www      8504:         '<input type="hidden" name="symb"        value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n";
1.599     www      8505: 
                   8506:     $result.='
                   8507: <h2>
1.600     www      8508:   '.&mt('Grading table').'
1.601     www      8509: </h2>'.
                   8510:             &selectfield(0).
                   8511:             '<input type="hidden" name="command" value="viewgrades" />
1.599     www      8512:             <div>
                   8513:               <input type="submit" value="'.&mt('Next').' &rarr;" />
                   8514:             </div>
                   8515:         </div>
                   8516:   </form>';
                   8517:     return $result;
                   8518: }
1.443     banghart 8519: 
1.600     www      8520: 
                   8521: 
1.443     banghart 8522: #--- Displays the submissions first page -------
                   8523: sub submit_options {
1.608     www      8524:     my ($request,$symb) = @_;
1.72      ng       8525:     if (!$symb) {return '';}
                   8526: 
1.118     ng       8527:     &commonJSfunctions($request);
1.473     albertel 8528:     my $result;
1.533     bisitz   8529: 
1.72      ng       8530:     $result.='<form action="/adm/grades" method="post" name="gradingMenu">'."\n".
1.618     www      8531: 	'<input type="hidden" name="symb"        value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n";
1.472     albertel 8532:     $result.='
1.533     bisitz   8533: <h2>
1.600     www      8534:   '.&mt('Select individual students to grade').'
1.601     www      8535: </h2>'.&selectfield(1).'
                   8536:                 <input type="hidden" name="command" value="submission" /> 
                   8537: 	      <input type="submit" value="'.&mt('Next').' &rarr;" />
                   8538:             </div>
                   8539:           </div>
                   8540: 
                   8541: 
                   8542:   </form>';
                   8543:     return $result;
                   8544: }
1.533     bisitz   8545: 
1.601     www      8546: sub selectfield {
                   8547:    my ($full)=@_;
                   8548:    my $result='<div class="LC_columnSection">
1.537     harmsja  8549:   
1.533     bisitz   8550:     <fieldset>
                   8551:       <legend>
                   8552:        '.&mt('Sections').'
                   8553:       </legend>
1.601     www      8554:       '.&Apache::lonstatistics::SectionSelect('section','multiple',5).'
1.533     bisitz   8555:     </fieldset>
1.537     harmsja  8556:   
1.533     bisitz   8557:     <fieldset>
                   8558:       <legend>
                   8559:         '.&mt('Groups').'
                   8560:       </legend>
                   8561:       '.&Apache::lonstatistics::GroupSelect('group','multiple',5).'
                   8562:     </fieldset>
1.537     harmsja  8563:   
1.533     bisitz   8564:     <fieldset>
                   8565:       <legend>
                   8566:         '.&mt('Access Status').'
                   8567:       </legend>
1.601     www      8568:       '.&Apache::lonhtmlcommon::StatusOptions(undef,undef,5,undef,'mult').'
                   8569:     </fieldset>';
                   8570:     if ($full) {
                   8571:        $result.='
1.533     bisitz   8572:     <fieldset>
                   8573:       <legend>
                   8574:         '.&mt('Submission Status').'
1.601     www      8575:       </legend>'.
                   8576:        &Apache::loncommon::select_form('all','submitonly',
                   8577:           (&Apache::lonlocal::texthash(
                   8578:              'yes'       => 'with submissions',
                   8579:              'queued'    => 'in grading queue',
                   8580:              'graded'    => 'with ungraded submissions',
                   8581:              'incorrect' => 'with incorrect submissions',
                   8582:              'all'       => 'with any status'),
                   8583:              'select_form_order' => ['yes','queued','graded','incorrect','all'])).
                   8584:    '</fieldset>';
                   8585:     }
                   8586:     $result.='</div><br />';
1.44      ng       8587:     return $result;
1.2       albertel 8588: }
                   8589: 
1.285     albertel 8590: sub reset_perm {
                   8591:     undef(%perm);
                   8592: }
                   8593: 
                   8594: sub init_perm {
                   8595:     &reset_perm();
1.300     albertel 8596:     foreach my $test_perm ('vgr','mgr','opa') {
                   8597: 
                   8598: 	my $scope = $env{'request.course.id'};
                   8599: 	if (!($perm{$test_perm}=&Apache::lonnet::allowed($test_perm,$scope))) {
                   8600: 
                   8601: 	    $scope .= '/'.$env{'request.course.sec'};
                   8602: 	    if ( $perm{$test_perm}=
                   8603: 		 &Apache::lonnet::allowed($test_perm,$scope)) {
                   8604: 		$perm{$test_perm.'_section'}=$env{'request.course.sec'};
                   8605: 	    } else {
                   8606: 		delete($perm{$test_perm});
                   8607: 	    }
1.285     albertel 8608: 	}
                   8609:     }
                   8610: }
                   8611: 
1.400     www      8612: sub gather_clicker_ids {
1.408     albertel 8613:     my %clicker_ids;
1.400     www      8614: 
                   8615:     my $classlist = &Apache::loncoursedata::get_classlist();
                   8616: 
                   8617:     # Set up a couple variables.
1.407     albertel 8618:     my $username_idx = &Apache::loncoursedata::CL_SNAME();
                   8619:     my $domain_idx   = &Apache::loncoursedata::CL_SDOM();
1.438     www      8620:     my $status_idx   = &Apache::loncoursedata::CL_STATUS();
1.400     www      8621: 
1.407     albertel 8622:     foreach my $student (keys(%$classlist)) {
1.438     www      8623:         if ($classlist->{$student}->[$status_idx] ne 'Active') { next; }
1.407     albertel 8624:         my $username = $classlist->{$student}->[$username_idx];
                   8625:         my $domain   = $classlist->{$student}->[$domain_idx];
1.400     www      8626:         my $clickers =
1.408     albertel 8627: 	    (&Apache::lonnet::userenvironment($domain,$username,'clickers'))[1];
1.400     www      8628:         foreach my $id (split(/\,/,$clickers)) {
1.414     www      8629:             $id=~s/^[\#0]+//;
1.421     www      8630:             $id=~s/[\-\:]//g;
1.407     albertel 8631:             if (exists($clicker_ids{$id})) {
1.408     albertel 8632: 		$clicker_ids{$id}.=','.$username.':'.$domain;
1.400     www      8633:             } else {
1.408     albertel 8634: 		$clicker_ids{$id}=$username.':'.$domain;
1.400     www      8635:             }
                   8636:         }
                   8637:     }
1.407     albertel 8638:     return %clicker_ids;
1.400     www      8639: }
                   8640: 
1.402     www      8641: sub gather_adv_clicker_ids {
1.408     albertel 8642:     my %clicker_ids;
1.402     www      8643:     my $cnum=$env{'course.'.$env{'request.course.id'}.'.num'};
                   8644:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
                   8645:     my %coursepersonnel=&Apache::lonnet::get_course_adv_roles($cdom.'/'.$cnum);
1.409     albertel 8646:     foreach my $element (sort(keys(%coursepersonnel))) {
1.402     www      8647:         foreach my $person (split(/\,/,$coursepersonnel{$element})) {
                   8648:             my ($puname,$pudom)=split(/\:/,$person);
                   8649:             my $clickers =
1.408     albertel 8650: 		(&Apache::lonnet::userenvironment($pudom,$puname,'clickers'))[1];
1.405     www      8651:             foreach my $id (split(/\,/,$clickers)) {
1.414     www      8652: 		$id=~s/^[\#0]+//;
1.421     www      8653:                 $id=~s/[\-\:]//g;
1.408     albertel 8654: 		if (exists($clicker_ids{$id})) {
                   8655: 		    $clicker_ids{$id}.=','.$puname.':'.$pudom;
                   8656: 		} else {
                   8657: 		    $clicker_ids{$id}=$puname.':'.$pudom;
                   8658: 		}
1.405     www      8659:             }
1.402     www      8660:         }
                   8661:     }
1.407     albertel 8662:     return %clicker_ids;
1.402     www      8663: }
                   8664: 
1.413     www      8665: sub clicker_grading_parameters {
                   8666:     return ('gradingmechanism' => 'scalar',
                   8667:             'upfiletype' => 'scalar',
                   8668:             'specificid' => 'scalar',
                   8669:             'pcorrect' => 'scalar',
                   8670:             'pincorrect' => 'scalar');
                   8671: }
                   8672: 
1.400     www      8673: sub process_clicker {
1.608     www      8674:     my ($r,$symb)=@_;
1.400     www      8675:     if (!$symb) {return '';}
                   8676:     my $result=&checkforfile_js();
                   8677:     $result.='<br /><table width="100%" border="0"><tr><td bgcolor="#777777">'."\n";
                   8678:     $result.='<table width="100%" border="0"><tr bgcolor="#e6ffff"><td>'."\n";
1.538     schulted 8679:     $result.='&nbsp;<b>'.&mt('Specify a file containing the clicker information for this resource.').
                   8680:         '</b></td></tr>'."\n";
1.601     www      8681:     $result.='<tr bgcolor="#ffffe6"><td>'."\n";
1.413     www      8682: # Attempt to restore parameters from last session, set defaults if not present
                   8683:     my %Saveable_Parameters=&clicker_grading_parameters();
                   8684:     &Apache::loncommon::restore_course_settings('grades_clicker',
                   8685:                                                  \%Saveable_Parameters);
                   8686:     if (!$env{'form.pcorrect'}) { $env{'form.pcorrect'}=100; }
                   8687:     if (!$env{'form.pincorrect'}) { $env{'form.pincorrect'}=100; }
                   8688:     if (!$env{'form.gradingmechanism'}) { $env{'form.gradingmechanism'}='attendance'; }
                   8689:     if (!$env{'form.upfiletype'}) { $env{'form.upfiletype'}='iclicker'; }
                   8690: 
                   8691:     my %checked;
1.521     www      8692:     foreach my $gradingmechanism ('attendance','personnel','specific','given') {
1.413     www      8693:        if ($env{'form.gradingmechanism'} eq $gradingmechanism) {
1.569     bisitz   8694:           $checked{$gradingmechanism}=' checked="checked"';
1.413     www      8695:        }
                   8696:     }
                   8697: 
1.400     www      8698:     my $upload=&mt("Upload File");
                   8699:     my $type=&mt("Type");
1.402     www      8700:     my $attendance=&mt("Award points just for participation");
                   8701:     my $personnel=&mt("Correctness determined from response by course personnel");
1.414     www      8702:     my $specific=&mt("Correctness determined from response with clicker ID(s)"); 
1.521     www      8703:     my $given=&mt("Correctness determined from given list of answers").' '.
                   8704:               '<font size="-2"><tt>('.&mt("Provide comma-separated list. Use '*' for any answer correct, '-' for skip").')</tt></font>';
1.402     www      8705:     my $pcorrect=&mt("Percentage points for correct solution");
                   8706:     my $pincorrect=&mt("Percentage points for incorrect solution");
1.413     www      8707:     my $selectform=&Apache::loncommon::select_form($env{'form.upfiletype'},'upfiletype',
1.419     www      8708: 						   ('iclicker' => 'i>clicker',
                   8709:                                                     'interwrite' => 'interwrite PRS'));
1.418     albertel 8710:     $symb = &Apache::lonenc::check_encrypt($symb);
1.597     wenzelju 8711:     $result.= &Apache::lonhtmlcommon::scripttag(<<ENDUPFORM);
1.402     www      8712: function sanitycheck() {
                   8713: // Accept only integer percentages
                   8714:    document.forms.gradesupload.pcorrect.value=Math.round(document.forms.gradesupload.pcorrect.value);
                   8715:    document.forms.gradesupload.pincorrect.value=Math.round(document.forms.gradesupload.pincorrect.value);
                   8716: // Find out grading choice
                   8717:    for (i=0; i<document.forms.gradesupload.gradingmechanism.length; i++) {
                   8718:       if (document.forms.gradesupload.gradingmechanism[i].checked) {
                   8719:          gradingchoice=document.forms.gradesupload.gradingmechanism[i].value;
                   8720:       }
                   8721:    }
                   8722: // By default, new choice equals user selection
                   8723:    newgradingchoice=gradingchoice;
                   8724: // Not good to give more points for false answers than correct ones
                   8725:    if (Math.round(document.forms.gradesupload.pcorrect.value)<Math.round(document.forms.gradesupload.pincorrect.value)) {
                   8726:       document.forms.gradesupload.pcorrect.value=document.forms.gradesupload.pincorrect.value;
                   8727:    }
                   8728: // If new choice is attendance only, and old choice was correctness-based, restore defaults
                   8729:    if ((gradingchoice=='attendance') && (document.forms.gradesupload.waschecked.value!='attendance')) {
                   8730:       document.forms.gradesupload.pcorrect.value=100;
                   8731:       document.forms.gradesupload.pincorrect.value=100;
                   8732:    }
                   8733: // If the values are different, cannot be attendance only
                   8734:    if ((Math.round(document.forms.gradesupload.pcorrect.value)!=Math.round(document.forms.gradesupload.pincorrect.value)) &&
                   8735:        (gradingchoice=='attendance')) {
                   8736:        newgradingchoice='personnel';
                   8737:    }
                   8738: // Change grading choice to new one
                   8739:    for (i=0; i<document.forms.gradesupload.gradingmechanism.length; i++) {
                   8740:       if (document.forms.gradesupload.gradingmechanism[i].value==newgradingchoice) {
                   8741:          document.forms.gradesupload.gradingmechanism[i].checked=true;
                   8742:       } else {
                   8743:          document.forms.gradesupload.gradingmechanism[i].checked=false;
                   8744:       }
                   8745:    }
                   8746: // Remember the old state
                   8747:    document.forms.gradesupload.waschecked.value=newgradingchoice;
                   8748: }
1.597     wenzelju 8749: ENDUPFORM
                   8750:     $result.= <<ENDUPFORM;
1.400     www      8751: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="gradesupload">
                   8752: <input type="hidden" name="symb" value="$symb" />
                   8753: <input type="hidden" name="command" value="processclickerfile" />
                   8754: <input type="file" name="upfile" size="50" />
                   8755: <br /><label>$type: $selectform</label>
1.589     bisitz   8756: <br /><label><input type="radio" name="gradingmechanism" value="attendance"$checked{'attendance'} onclick="sanitycheck()" />$attendance </label>
                   8757: <br /><label><input type="radio" name="gradingmechanism" value="personnel"$checked{'personnel'} onclick="sanitycheck()" />$personnel</label>
                   8758: <br /><label><input type="radio" name="gradingmechanism" value="specific"$checked{'specific'} onclick="sanitycheck()" />$specific </label>
1.414     www      8759: <input type="text" name="specificid" value="$env{'form.specificid'}" size="20" />
1.589     bisitz   8760: <br /><label><input type="radio" name="gradingmechanism" value="given"$checked{'given'} onclick="sanitycheck()" />$given </label>
1.521     www      8761: <br />&nbsp;&nbsp;&nbsp;
                   8762: <input type="text" name="givenanswer" size="50" />
1.413     www      8763: <input type="hidden" name="waschecked" value="$env{'form.gradingmechanism'}" />
1.589     bisitz   8764: <br /><label>$pcorrect: <input type="text" name="pcorrect" size="4" value="$env{'form.pcorrect'}" onchange="sanitycheck()" /></label>
                   8765: <br /><label>$pincorrect: <input type="text" name="pincorrect" size="4" value="$env{'form.pincorrect'}" onchange="sanitycheck()" /></label>
                   8766: <br /><input type="button" onclick="javascript:checkUpload(this.form);" value="$upload" />
1.597     wenzelju 8767: </form>'
1.400     www      8768: ENDUPFORM
                   8769:     $result.='</td></tr></table>'."\n".
                   8770:              '</td></tr></table><br /><br />'."\n";
                   8771:     return $result;
                   8772: }
                   8773: 
                   8774: sub process_clicker_file {
1.608     www      8775:     my ($r,$symb)=@_;
1.400     www      8776:     if (!$symb) {return '';}
1.413     www      8777: 
                   8778:     my %Saveable_Parameters=&clicker_grading_parameters();
                   8779:     &Apache::loncommon::store_course_settings('grades_clicker',
                   8780:                                               \%Saveable_Parameters);
1.598     www      8781:     my $result='';
1.404     www      8782:     if (($env{'form.gradingmechanism'} eq 'specific') && ($env{'form.specificid'}!~/\w/)) {
1.408     albertel 8783: 	$result.='<span class="LC_error">'.&mt('You need to specify a clicker ID for the correct answer').'</span>';
1.614     www      8784: 	return $result;
1.404     www      8785:     }
1.522     www      8786:     if (($env{'form.gradingmechanism'} eq 'given') && ($env{'form.givenanswer'}!~/\S/)) {
1.521     www      8787:         $result.='<span class="LC_error">'.&mt('You need to specify the correct answer').'</span>';
1.614     www      8788:         return $result;
1.521     www      8789:     }
1.522     www      8790:     my $foundgiven=0;
1.521     www      8791:     if ($env{'form.gradingmechanism'} eq 'given') {
                   8792:         $env{'form.givenanswer'}=~s/^\s*//gs;
                   8793:         $env{'form.givenanswer'}=~s/\s*$//gs;
                   8794:         $env{'form.givenanswer'}=~s/[^a-zA-Z0-9\.\*\-]+/\,/g;
                   8795:         $env{'form.givenanswer'}=uc($env{'form.givenanswer'});
1.522     www      8796:         my @answers=split(/\,/,$env{'form.givenanswer'});
                   8797:         $foundgiven=$#answers+1;
1.521     www      8798:     }
1.407     albertel 8799:     my %clicker_ids=&gather_clicker_ids();
1.408     albertel 8800:     my %correct_ids;
1.404     www      8801:     if ($env{'form.gradingmechanism'} eq 'personnel') {
1.408     albertel 8802: 	%correct_ids=&gather_adv_clicker_ids();
1.404     www      8803:     }
                   8804:     if ($env{'form.gradingmechanism'} eq 'specific') {
1.414     www      8805: 	foreach my $correct_id (split(/[\s\,]/,$env{'form.specificid'})) {;
                   8806: 	   $correct_id=~tr/a-z/A-Z/;
                   8807: 	   $correct_id=~s/\s//gs;
                   8808: 	   $correct_id=~s/^[\#0]+//;
1.421     www      8809:            $correct_id=~s/[\-\:]//g;
1.414     www      8810:            if ($correct_id) {
                   8811: 	      $correct_ids{$correct_id}='specified';
                   8812:            }
                   8813:         }
1.400     www      8814:     }
1.404     www      8815:     if ($env{'form.gradingmechanism'} eq 'attendance') {
1.408     albertel 8816: 	$result.=&mt('Score based on attendance only');
1.521     www      8817:     } elsif ($env{'form.gradingmechanism'} eq 'given') {
1.522     www      8818:         $result.=&mt('Score based on [_1] ([_2] answers)','<tt>'.$env{'form.givenanswer'}.'</tt>',$foundgiven);
1.404     www      8819:     } else {
1.408     albertel 8820: 	my $number=0;
1.411     www      8821: 	$result.='<p><b>'.&mt('Correctness determined by the following IDs').'</b>';
1.408     albertel 8822: 	foreach my $id (sort(keys(%correct_ids))) {
1.411     www      8823: 	    $result.='<br /><tt>'.$id.'</tt> - ';
1.408     albertel 8824: 	    if ($correct_ids{$id} eq 'specified') {
                   8825: 		$result.=&mt('specified');
                   8826: 	    } else {
                   8827: 		my ($uname,$udom)=split(/\:/,$correct_ids{$id});
                   8828: 		$result.=&Apache::loncommon::plainname($uname,$udom);
                   8829: 	    }
                   8830: 	    $number++;
                   8831: 	}
1.411     www      8832:         $result.="</p>\n";
1.408     albertel 8833: 	if ($number==0) {
                   8834: 	    $result.='<span class="LC_error">'.&mt('No IDs found to determine correct answer').'</span>';
1.614     www      8835: 	    return $result;
1.408     albertel 8836: 	}
1.404     www      8837:     }
1.405     www      8838:     if (length($env{'form.upfile'}) < 2) {
1.407     albertel 8839:         $result.=&mt('[_1] Error: [_2] The file you attempted to upload, [_3] contained no information. Please check that you entered the correct filename.',
                   8840: 		     '<span class="LC_error">',
                   8841: 		     '</span>',
                   8842: 		     '<span class="LC_filename">'.&HTML::Entities::encode($env{'form.upfile.filename'},'<>&"').'</span>');
1.614     www      8843:         return $result;
1.405     www      8844:     }
1.410     www      8845: 
                   8846: # Were able to get all the info needed, now analyze the file
                   8847: 
1.411     www      8848:     $result.=&Apache::loncommon::studentbrowser_javascript();
1.418     albertel 8849:     $symb = &Apache::lonenc::check_encrypt($symb);
1.410     www      8850:     my $heading=&mt('Scanning clicker file');
                   8851:     $result.=(<<ENDHEADER);
                   8852: <br /><table width="100%" border="0"><tr><td bgcolor="#777777">
                   8853: <table width="100%" border="0"><tr bgcolor="#e6ffff"><td>
                   8854: <b>$heading</b></td></tr><tr bgcolor=#ffffe6><td>
                   8855: <form method="post" action="/adm/grades" name="clickeranalysis">
                   8856: <input type="hidden" name="symb" value="$symb" />
                   8857: <input type="hidden" name="command" value="assignclickergrades" />
1.411     www      8858: <input type="hidden" name="gradingmechanism" value="$env{'form.gradingmechanism'}" />
                   8859: <input type="hidden" name="pcorrect" value="$env{'form.pcorrect'}" />
                   8860: <input type="hidden" name="pincorrect" value="$env{'form.pincorrect'}" />
1.410     www      8861: ENDHEADER
1.522     www      8862:     if ($env{'form.gradingmechanism'} eq 'given') {
                   8863:        $result.='<input type="hidden" name="correct:given" value="'.$env{'form.givenanswer'}.'" />';
                   8864:     } 
1.408     albertel 8865:     my %responses;
                   8866:     my @questiontitles;
1.405     www      8867:     my $errormsg='';
                   8868:     my $number=0;
                   8869:     if ($env{'form.upfiletype'} eq 'iclicker') {
1.408     albertel 8870: 	($errormsg,$number)=&iclicker_eval(\@questiontitles,\%responses);
1.406     www      8871:     }
1.419     www      8872:     if ($env{'form.upfiletype'} eq 'interwrite') {
                   8873:         ($errormsg,$number)=&interwrite_eval(\@questiontitles,\%responses);
                   8874:     }
1.411     www      8875:     $result.='<br />'.&mt('Found [_1] question(s)',$number).'<br />'.
                   8876:              '<input type="hidden" name="number" value="'.$number.'" />'.
                   8877:              &mt('Awarding [_1] percent for correct and [_2] percent for incorrect responses',
                   8878:                  $env{'form.pcorrect'},$env{'form.pincorrect'}).
                   8879:              '<br />';
1.522     www      8880:     if (($env{'form.gradingmechanism'} eq 'given') && ($number!=$foundgiven)) {
                   8881:        $result.='<span class="LC_error">'.&mt('Number of given answers does not agree with number of questions in file.').'</span>';
1.614     www      8882:        return $result;
1.522     www      8883:     } 
1.414     www      8884: # Remember Question Titles
                   8885: # FIXME: Possibly need delimiter other than ":"
                   8886:     for (my $i=0;$i<$number;$i++) {
                   8887:         $result.='<input type="hidden" name="question:'.$i.'" value="'.
                   8888:                  &HTML::Entities::encode($questiontitles[$i],'"&<>').'" />';
                   8889:     }
1.411     www      8890:     my $correct_count=0;
                   8891:     my $student_count=0;
                   8892:     my $unknown_count=0;
1.414     www      8893: # Match answers with usernames
                   8894: # FIXME: Possibly need delimiter other than ":"
1.409     albertel 8895:     foreach my $id (keys(%responses)) {
1.410     www      8896:        if ($correct_ids{$id}) {
1.414     www      8897:           $result.="\n".'<input type="hidden" name="correct:'.$correct_count.':'.$correct_ids{$id}.'" value="'.$responses{$id}.'" />';
1.411     www      8898:           $correct_count++;
1.410     www      8899:        } elsif ($clicker_ids{$id}) {
1.437     www      8900:           if ($clicker_ids{$id}=~/\,/) {
                   8901: # More than one user with the same clicker!
                   8902:              $result.="\n<hr />".&mt('Clicker registered more than once').": <tt>".$id."</tt><br />";
                   8903:              $result.="\n".'<input type="hidden" name="unknown:'.$id.'" value="'.$responses{$id}.'" />'.
                   8904:                            "<select name='multi".$id."'>";
                   8905:              foreach my $reguser (sort(split(/\,/,$clicker_ids{$id}))) {
                   8906:                  $result.="<option value='".$reguser."'>".&Apache::loncommon::plainname(split(/\:/,$reguser)).' ('.$reguser.')</option>';
                   8907:              }
                   8908:              $result.='</select>';
                   8909:              $unknown_count++;
                   8910:           } else {
                   8911: # Good: found one and only one user with the right clicker
                   8912:              $result.="\n".'<input type="hidden" name="student:'.$clicker_ids{$id}.'" value="'.$responses{$id}.'" />';
                   8913:              $student_count++;
                   8914:           }
1.410     www      8915:        } else {
1.411     www      8916:           $result.="\n<hr />".&mt('Unregistered Clicker')." <tt>".$id."</tt><br />";
                   8917:           $result.="\n".'<input type="hidden" name="unknown:'.$id.'" value="'.$responses{$id}.'" />'.
                   8918:                    "\n".&mt("Username").": <input type='text' name='uname".$id."' />&nbsp;".
                   8919:                    "\n".&mt("Domain").": ".
                   8920:                    &Apache::loncommon::select_dom_form($env{'course.'.$env{'request.course.id'}.'.domain'},'udom'.$id).'&nbsp;'.
                   8921:                    &Apache::loncommon::selectstudent_link('clickeranalysis','uname'.$id,'udom'.$id);
                   8922:           $unknown_count++;
1.410     www      8923:        }
1.405     www      8924:     }
1.412     www      8925:     $result.='<hr />'.
                   8926:              &mt('Found [_1] registered and [_2] unregistered clickers.',$student_count,$unknown_count);
1.521     www      8927:     if (($env{'form.gradingmechanism'} ne 'attendance') && ($env{'form.gradingmechanism'} ne 'given')) {
1.412     www      8928:        if ($correct_count==0) {
                   8929:           $errormsg.="Found no correct answers answers for grading!";
                   8930:        } elsif ($correct_count>1) {
1.414     www      8931:           $result.='<br /><span class="LC_warning">'.&mt("Found [_1] entries for grading!",$correct_count).'</span>';
1.412     www      8932:        }
                   8933:     }
1.428     www      8934:     if ($number<1) {
                   8935:        $errormsg.="Found no questions.";
                   8936:     }
1.412     www      8937:     if ($errormsg) {
                   8938:        $result.='<br /><span class="LC_error">'.&mt($errormsg).'</span>';
                   8939:     } else {
                   8940:        $result.='<br /><input type="submit" name="finalize" value="'.&mt('Finalize Grading').'" />';
                   8941:     }
                   8942:     $result.='</form></td></tr></table>'."\n".
1.410     www      8943:              '</td></tr></table><br /><br />'."\n";
1.614     www      8944:     return $result;
1.400     www      8945: }
                   8946: 
1.405     www      8947: sub iclicker_eval {
1.406     www      8948:     my ($questiontitles,$responses)=@_;
1.405     www      8949:     my $number=0;
                   8950:     my $errormsg='';
                   8951:     foreach my $line (split(/[\n\r]/,$env{'form.upfile'})) {
1.410     www      8952:         my %components=&Apache::loncommon::record_sep($line);
                   8953:         my @entries=map {$components{$_}} (sort(keys(%components)));
1.408     albertel 8954: 	if ($entries[0] eq 'Question') {
                   8955: 	    for (my $i=3;$i<$#entries;$i+=6) {
                   8956: 		$$questiontitles[$number]=$entries[$i];
                   8957: 		$number++;
                   8958: 	    }
                   8959: 	}
                   8960: 	if ($entries[0]=~/^\#/) {
                   8961: 	    my $id=$entries[0];
                   8962: 	    my @idresponses;
                   8963: 	    $id=~s/^[\#0]+//;
                   8964: 	    for (my $i=0;$i<$number;$i++) {
                   8965: 		my $idx=3+$i*6;
                   8966: 		push(@idresponses,$entries[$idx]);
                   8967: 	    }
                   8968: 	    $$responses{$id}=join(',',@idresponses);
                   8969: 	}
1.405     www      8970:     }
                   8971:     return ($errormsg,$number);
                   8972: }
                   8973: 
1.419     www      8974: sub interwrite_eval {
                   8975:     my ($questiontitles,$responses)=@_;
                   8976:     my $number=0;
                   8977:     my $errormsg='';
1.420     www      8978:     my $skipline=1;
                   8979:     my $questionnumber=0;
                   8980:     my %idresponses=();
1.419     www      8981:     foreach my $line (split(/[\n\r]/,$env{'form.upfile'})) {
                   8982:         my %components=&Apache::loncommon::record_sep($line);
                   8983:         my @entries=map {$components{$_}} (sort(keys(%components)));
1.420     www      8984:         if ($entries[1] eq 'Time') { $skipline=0; next; }
                   8985:         if ($entries[1] eq 'Response') { $skipline=1; }
                   8986:         next if $skipline;
                   8987:         if ($entries[0]!=$questionnumber) {
                   8988:            $questionnumber=$entries[0];
                   8989:            $$questiontitles[$number]=&mt('Question [_1]',$questionnumber);
                   8990:            $number++;
1.419     www      8991:         }
1.420     www      8992:         my $id=$entries[4];
                   8993:         $id=~s/^[\#0]+//;
1.421     www      8994:         $id=~s/^v\d*\://i;
                   8995:         $id=~s/[\-\:]//g;
1.420     www      8996:         $idresponses{$id}[$number]=$entries[6];
                   8997:     }
1.524     raeburn  8998:     foreach my $id (keys(%idresponses)) {
1.420     www      8999:        $$responses{$id}=join(',',@{$idresponses{$id}});
                   9000:        $$responses{$id}=~s/^\s*\,//;
1.419     www      9001:     }
                   9002:     return ($errormsg,$number);
                   9003: }
                   9004: 
1.414     www      9005: sub assign_clicker_grades {
1.608     www      9006:     my ($r,$symb)=@_;
1.414     www      9007:     if (!$symb) {return '';}
1.416     www      9008: # See which part we are saving to
1.582     raeburn  9009:     my $res_error;
                   9010:     my ($partlist,$handgrade,$responseType) = &response_type($symb,\$res_error);
                   9011:     if ($res_error) {
                   9012:         return &navmap_errormsg();
                   9013:     }
1.416     www      9014: # FIXME: This should probably look for the first handgradeable part
                   9015:     my $part=$$partlist[0];
                   9016: # Start screen output
1.598     www      9017:     my $result='';
1.416     www      9018: 
1.414     www      9019:     my $heading=&mt('Assigning grades based on clicker file');
                   9020:     $result.=(<<ENDHEADER);
                   9021: <br /><table width="100%" border="0"><tr><td bgcolor="#777777">
                   9022: <table width="100%" border="0"><tr bgcolor="#e6ffff"><td>
                   9023: <b>$heading</b></td></tr><tr bgcolor=#ffffe6><td>
                   9024: ENDHEADER
                   9025: # Get correct result
                   9026: # FIXME: Possibly need delimiter other than ":"
                   9027:     my @correct=();
1.415     www      9028:     my $gradingmechanism=$env{'form.gradingmechanism'};
                   9029:     my $number=$env{'form.number'};
                   9030:     if ($gradingmechanism ne 'attendance') {
1.414     www      9031:        foreach my $key (keys(%env)) {
                   9032:           if ($key=~/^form\.correct\:/) {
                   9033:              my @input=split(/\,/,$env{$key});
                   9034:              for (my $i=0;$i<=$#input;$i++) {
                   9035:                  if (($correct[$i]) && ($input[$i]) &&
                   9036:                      ($correct[$i] ne $input[$i])) {
                   9037:                     $result.='<br /><span class="LC_warning">'.
                   9038:                              &mt('More than one correct result given for question "[_1]": [_2] versus [_3].',
                   9039:                                  $env{'form.question:'.$i},$correct[$i],$input[$i]).'</span>';
                   9040:                  } elsif ($input[$i]) {
                   9041:                     $correct[$i]=$input[$i];
                   9042:                  }
                   9043:              }
                   9044:           }
                   9045:        }
1.415     www      9046:        for (my $i=0;$i<$number;$i++) {
1.414     www      9047:           if (!$correct[$i]) {
                   9048:              $result.='<br /><span class="LC_error">'.
                   9049:                       &mt('No correct result given for question "[_1]"!',
                   9050:                           $env{'form.question:'.$i}).'</span>';
                   9051:           }
                   9052:        }
                   9053:        $result.='<br />'.&mt("Correct answer: [_1]",join(', ',map { ($_?$_:'-') } @correct));
                   9054:     }
                   9055: # Start grading
1.415     www      9056:     my $pcorrect=$env{'form.pcorrect'};
                   9057:     my $pincorrect=$env{'form.pincorrect'};
1.416     www      9058:     my $storecount=0;
1.415     www      9059:     foreach my $key (keys(%env)) {
1.420     www      9060:        my $user='';
1.415     www      9061:        if ($key=~/^form\.student\:(.*)$/) {
1.420     www      9062:           $user=$1;
                   9063:        }
                   9064:        if ($key=~/^form\.unknown\:(.*)$/) {
                   9065:           my $id=$1;
                   9066:           if (($env{'form.uname'.$id}) && ($env{'form.udom'.$id})) {
                   9067:              $user=$env{'form.uname'.$id}.':'.$env{'form.udom'.$id};
1.437     www      9068:           } elsif ($env{'form.multi'.$id}) {
                   9069:              $user=$env{'form.multi'.$id};
1.420     www      9070:           }
                   9071:        }
                   9072:        if ($user) { 
1.415     www      9073:           my @answer=split(/\,/,$env{$key});
                   9074:           my $sum=0;
1.522     www      9075:           my $realnumber=$number;
1.415     www      9076:           for (my $i=0;$i<$number;$i++) {
1.576     www      9077:              if  ($correct[$i] eq '-') {
                   9078:                 $realnumber--;
                   9079:              } elsif ($answer[$i]) {
1.415     www      9080:                 if ($gradingmechanism eq 'attendance') {
                   9081:                    $sum+=$pcorrect;
1.576     www      9082:                 } elsif ($correct[$i] eq '*') {
1.522     www      9083:                    $sum+=$pcorrect;
1.415     www      9084:                 } else {
                   9085:                    if ($answer[$i] eq $correct[$i]) {
                   9086:                       $sum+=$pcorrect;
                   9087:                    } else {
                   9088:                       $sum+=$pincorrect;
                   9089:                    }
                   9090:                 }
                   9091:              }
                   9092:           }
1.522     www      9093:           my $ave=$sum/(100*$realnumber);
1.416     www      9094: # Store
                   9095:           my ($username,$domain)=split(/\:/,$user);
                   9096:           my %grades=();
                   9097:           $grades{"resource.$part.solved"}='correct_by_override';
                   9098:           $grades{"resource.$part.awarded"}=$ave;
                   9099:           $grades{"resource.regrader"}="$env{'user.name'}:$env{'user.domain'}";
                   9100:           my $returncode=&Apache::lonnet::cstore(\%grades,$symb,
                   9101:                                                  $env{'request.course.id'},
                   9102:                                                  $domain,$username);
                   9103:           if ($returncode ne 'ok') {
                   9104:              $result.="<br /><span class=\"LC_error\">Failed to save student $username:$domain. Message when trying to save was ($returncode)</span>";
                   9105:           } else {
                   9106:              $storecount++;
                   9107:           }
1.415     www      9108:        }
                   9109:     }
                   9110: # We are done
1.549     hauer    9111:     $result.='<br />'.&mt('Successfully stored grades for [quant,_1,student].',$storecount).
1.416     www      9112:              '</td></tr></table>'."\n".
1.414     www      9113:              '</td></tr></table><br /><br />'."\n";
1.614     www      9114:     return $result;
1.414     www      9115: }
                   9116: 
1.582     raeburn  9117: sub navmap_errormsg {
                   9118:     return '<div class="LC_error">'.
                   9119:            &mt('An error occurred retrieving information about resources in the course.').'<br />'.
1.595     raeburn  9120:            &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  9121:            '</div>';
                   9122: }
1.607     droeschl 9123: 
1.609     www      9124: sub startpage {
1.613     www      9125:     my ($r,$symb,$crumbs,$onlyfolderflag,$nodisplayflag) = @_;
1.614     www      9126:     unshift(@$crumbs,{href=>&href_symb_cmd($symb,'gradingmenu'),text=>"Grading"});
1.607     droeschl 9127:     $r->print(&Apache::loncommon::start_page('Grading',undef,
1.610     www      9128:                                           {'bread_crumbs' => $crumbs}));
1.613     www      9129:     unless ($nodisplayflag) {
                   9130:        $r->print(&Apache::lonhtmlcommon::resource_info_box($symb,$onlyfolderflag));
                   9131:     }
1.607     droeschl 9132: }
1.582     raeburn  9133: 
1.1       albertel 9134: sub handler {
1.41      ng       9135:     my $request=$_[0];
1.434     albertel 9136:     &reset_caches();
1.257     albertel 9137:     if ($env{'browser.mathml'}) {
1.141     www      9138: 	&Apache::loncommon::content_type($request,'text/xml');
1.41      ng       9139:     } else {
1.141     www      9140: 	&Apache::loncommon::content_type($request,'text/html');
1.41      ng       9141:     }
                   9142:     $request->send_http_header;
1.44      ng       9143:     return '' if $request->header_only;
1.41      ng       9144:     &Apache::loncommon::get_unprocessed_cgi($ENV{'QUERY_STRING'});
1.608     www      9145: 
                   9146: # see what command we need to execute
                   9147: 
1.160     albertel 9148:     my @commands=&Apache::loncommon::get_env_multiple('form.command');
                   9149:     my $command=$commands[0];
1.447     foxr     9150: 
1.160     albertel 9151:     if ($#commands > 0) {
                   9152: 	&Apache::lonnet::logthis("grades got multiple commands ".join(':',@commands));
                   9153:     }
1.608     www      9154: 
                   9155: # see what the symb is
                   9156: 
                   9157:     my $symb=$env{'form.symb'};
                   9158:     unless ($symb) {
                   9159:        (my $url=$env{'form.url'}) =~ s-^https*://($ENV{'SERVER_NAME'}|$ENV{'HTTP_HOST'})--;
                   9160:        $symb=&Apache::lonnet::symbread($url);
                   9161:     }
                   9162:     &Apache::lonenc::check_decrypt(\$symb);                             
                   9163: 
1.513     foxr     9164:     $ssi_error = 0;
1.324     albertel 9165:     if ($symb eq '' && $command eq '') {
1.601     www      9166: #
                   9167: # Not called from a resource
                   9168: #    
                   9169: 
1.41      ng       9170:     } else {
1.285     albertel 9171: 	&init_perm();
1.104     albertel 9172: 	if ($command eq 'submission' && $perm{'vgr'}) {
1.608     www      9173:             &startpage($request,$symb,[{href=>"", text=>"Student Submissions"}]);
1.611     www      9174: 	    ($env{'form.student'} eq '' ? &listStudents($request,$symb) : &submission($request,0,0,$symb));
1.103     albertel 9175: 	} elsif ($command eq 'pickStudentPage' && $perm{'vgr'}) {
1.615     www      9176:             &startpage($request,$symb,[{href=>&href_symb_cmd($symb,'all_for_one'),text=>'Grade page/folder for one student'},
                   9177:                                        {href=>'',text=>'Select student'}],1,1);
1.608     www      9178: 	    &pickStudentPage($request,$symb);
1.103     albertel 9179: 	} elsif ($command eq 'displayPage' && $perm{'vgr'}) {
1.615     www      9180:             &startpage($request,$symb,
                   9181:                                       [{href=>&href_symb_cmd($symb,'all_for_one'),text=>'Grade page/folder for one student'},
                   9182:                                        {href=>'',text=>'Select student'},
                   9183:                                        {href=>'',text=>'Grade student'}],1,1);
1.608     www      9184: 	    &displayPage($request,$symb);
1.104     albertel 9185: 	} elsif ($command eq 'gradeByPage' && $perm{'mgr'}) {
1.616     www      9186:             &startpage($request,$symb,[{href=>&href_symb_cmd($symb,'all_for_one'),text=>'Grade page/folder for one student'},
                   9187:                                        {href=>'',text=>'Select student'},
                   9188:                                        {href=>'',text=>'Grade student'},
                   9189:                                        {href=>'',text=>'Store grades'}],1,1);
1.608     www      9190: 	    &updateGradeByPage($request,$symb);
1.104     albertel 9191: 	} elsif ($command eq 'processGroup' && $perm{'vgr'}) {
1.619   ! www      9192:             &startpage($request,$symb,[{href=>'',text=>'...'},
        !          9193:                                        {href=>'',text=>'Modify grades'}]);
1.608     www      9194: 	    &processGroup($request,$symb);
1.104     albertel 9195: 	} elsif ($command eq 'gradingmenu' && $perm{'vgr'}) {
1.608     www      9196:             &startpage($request,$symb);
                   9197: 	    $request->print(&grading_menu($request,$symb));
1.598     www      9198: 	} elsif ($command eq 'individual' && $perm{'vgr'}) {
1.617     www      9199:             &startpage($request,$symb,[{href=>'',text=>'Select individual students to grade'}]);
1.608     www      9200: 	    $request->print(&submit_options($request,$symb));
1.598     www      9201:         } elsif ($command eq 'ungraded' && $perm{'vgr'}) {
1.617     www      9202:             &startpage($request,$symb,[{href=>'',text=>'Grade ungraded submissions'}]);
                   9203:             $request->print(&listStudents($request,$symb,'graded'));
1.598     www      9204:         } elsif ($command eq 'table' && $perm{'vgr'}) {
1.614     www      9205:             &startpage($request,$symb,[{href=>"", text=>"Grading table"}]);
1.611     www      9206:             $request->print(&submit_options_table($request,$symb));
1.598     www      9207:         } elsif ($command eq 'all_for_one' && $perm{'vgr'}) {
1.615     www      9208:             &startpage($request,$symb,[{href=>'',text=>'Grade page/folder for one student'}],1,1);
1.608     www      9209:             $request->print(&submit_options_sequence($request,$symb));
1.104     albertel 9210: 	} elsif ($command eq 'viewgrades' && $perm{'vgr'}) {
1.614     www      9211:             &startpage($request,$symb,[{href=>&href_symb_cmd($symb,"table"), text=>"Grading table"},{href=>'', text=>"Modify grades"}]);
1.608     www      9212: 	    $request->print(&viewgrades($request,$symb));
1.104     albertel 9213: 	} elsif ($command eq 'handgrade' && $perm{'mgr'}) {
1.611     www      9214:             &startpage($request,$symb);
1.608     www      9215: 	    $request->print(&processHandGrade($request,$symb));
1.106     albertel 9216: 	} elsif ($command eq 'editgrades' && $perm{'mgr'}) {
1.614     www      9217:             &startpage($request,$symb,[{href=>&href_symb_cmd($symb,"table"), text=>"Grading table"},
                   9218:                                        {href=>&href_symb_cmd($symb,'viewgrades').'&group=all&section=all&Status=Active',
                   9219:                                                                              text=>"Modify grades"},
                   9220:                                        {href=>'', text=>"Store grades"}]);
1.608     www      9221: 	    $request->print(&editgrades($request,$symb));
1.602     www      9222:         } elsif ($command eq 'initialverifyreceipt' && $perm{'vgr'}) {
1.616     www      9223:             &startpage($request,$symb,[{href=>'',text=>'Verify Receipt Number'}]);
1.611     www      9224:             $request->print(&initialverifyreceipt($request,$symb));
1.106     albertel 9225: 	} elsif ($command eq 'verify' && $perm{'vgr'}) {
1.616     www      9226:             &startpage($request,$symb,[{href=>&href_symb_cmd($symb,"initialverifyreceipt"),text=>'Verify Receipt Number'},
                   9227:                                        {href=>'',text=>'Verification Result'}]);
1.608     www      9228: 	    $request->print(&verifyreceipt($request,$symb));
1.400     www      9229:         } elsif ($command eq 'processclicker' && $perm{'mgr'}) {
1.615     www      9230:             &startpage($request,$symb,[{href=>'', text=>'Process clicker'}]);
1.608     www      9231:             $request->print(&process_clicker($request,$symb));
1.400     www      9232:         } elsif ($command eq 'processclickerfile' && $perm{'mgr'}) {
1.615     www      9233:             &startpage($request,$symb,[{href=>&href_symb_cmd($symb,'processclicker'), text=>'Process clicker'},
                   9234:                                        {href=>'', text=>'Process clicker file'}]);
1.608     www      9235:             $request->print(&process_clicker_file($request,$symb));
1.414     www      9236:         } elsif ($command eq 'assignclickergrades' && $perm{'mgr'}) {
1.615     www      9237:             &startpage($request,$symb,[{href=>&href_symb_cmd($symb,'processclicker'), text=>'Process clicker'},
                   9238:                                        {href=>'', text=>'Process clicker file'},
                   9239:                                        {href=>'', text=>'Store grades'}]);
1.608     www      9240:             $request->print(&assign_clicker_grades($request,$symb));
1.106     albertel 9241: 	} elsif ($command eq 'csvform' && $perm{'mgr'}) {
1.616     www      9242:             &startpage($request,$symb,[{href=>'', text=>'Grade/Manage/Review Bubblesheets'}],1,1);
1.608     www      9243: 	    $request->print(&upcsvScores_form($request,$symb));
1.106     albertel 9244: 	} elsif ($command eq 'csvupload' && $perm{'mgr'}) {
1.616     www      9245:             &startpage($request,$symb,[{href=>'', text=>'Grade/Manage/Review Bubblesheets'}],1,1);
1.608     www      9246: 	    $request->print(&csvupload($request,$symb));
1.106     albertel 9247: 	} elsif ($command eq 'csvuploadmap' && $perm{'mgr'} ) {
1.616     www      9248:             &startpage($request,$symb,[{href=>'', text=>'Grade/Manage/Review Bubblesheets'}],1,1);
1.608     www      9249: 	    $request->print(&csvuploadmap($request,$symb));
1.246     albertel 9250: 	} elsif ($command eq 'csvuploadoptions' && $perm{'mgr'}) {
1.257     albertel 9251: 	    if ($env{'form.associate'} ne 'Reverse Association') {
1.616     www      9252:                 &startpage($request,$symb,[{href=>'', text=>'Grade/Manage/Review Bubblesheets'}],1,1);
1.608     www      9253: 		$request->print(&csvuploadoptions($request,$symb));
1.41      ng       9254: 	    } else {
1.257     albertel 9255: 		if ( $env{'form.upfile_associate'} ne 'reverse' ) {
                   9256: 		    $env{'form.upfile_associate'} = 'reverse';
1.41      ng       9257: 		} else {
1.257     albertel 9258: 		    $env{'form.upfile_associate'} = 'forward';
1.41      ng       9259: 		}
1.616     www      9260:                 &startpage($request,$symb,[{href=>'', text=>'Grade/Manage/Review Bubblesheets'}],1,1);
1.608     www      9261: 		$request->print(&csvuploadmap($request,$symb));
1.41      ng       9262: 	    }
1.246     albertel 9263: 	} elsif ($command eq 'csvuploadassign' && $perm{'mgr'} ) {
1.616     www      9264:             &startpage($request,$symb,[{href=>'', text=>'Grade/Manage/Review Bubblesheets'}],1,1);
1.608     www      9265: 	    $request->print(&csvuploadassign($request,$symb));
1.106     albertel 9266: 	} elsif ($command eq 'scantron_selectphase' && $perm{'mgr'}) {
1.616     www      9267:             &startpage($request,$symb,[{href=>'', text=>'Grade/Manage/Review Bubblesheets'}],1,1);
1.612     www      9268: 	    $request->print(&scantron_selectphase($request,undef,$symb));
1.203     albertel 9269:  	} elsif ($command eq 'scantron_warning' && $perm{'mgr'}) {
1.616     www      9270:             &startpage($request,$symb,[{href=>'', text=>'Grade/Manage/Review Bubblesheets'}],1,1);
1.608     www      9271:  	    $request->print(&scantron_do_warning($request,$symb));
1.142     albertel 9272: 	} elsif ($command eq 'scantron_validate' && $perm{'mgr'}) {
1.616     www      9273:             &startpage($request,$symb,[{href=>'', text=>'Grade/Manage/Review Bubblesheets'}],1,1);
1.608     www      9274: 	    $request->print(&scantron_validate_file($request,$symb));
1.106     albertel 9275: 	} elsif ($command eq 'scantron_process' && $perm{'mgr'}) {
1.616     www      9276:             &startpage($request,$symb,[{href=>'', text=>'Grade/Manage/Review Bubblesheets'}],1,1);
1.608     www      9277: 	    $request->print(&scantron_process_students($request,$symb));
1.157     albertel 9278:  	} elsif ($command eq 'scantronupload' && 
1.257     albertel 9279:  		 (&Apache::lonnet::allowed('usc',$env{'request.role.domain'})||
                   9280: 		  &Apache::lonnet::allowed('usc',$env{'request.course.id'}))) {
1.616     www      9281:             &startpage($request,$symb,[{href=>'', text=>'Grade/Manage/Review Bubblesheets'}],1,1);
1.608     www      9282:  	    $request->print(&scantron_upload_scantron_data($request,$symb)); 
1.157     albertel 9283:  	} elsif ($command eq 'scantronupload_save' &&
1.257     albertel 9284:  		 (&Apache::lonnet::allowed('usc',$env{'request.role.domain'})||
                   9285: 		  &Apache::lonnet::allowed('usc',$env{'request.course.id'}))) {
1.616     www      9286:             &startpage($request,$symb,[{href=>'', text=>'Grade/Manage/Review Bubblesheets'}],1,1);
1.608     www      9287:  	    $request->print(&scantron_upload_scantron_data_save($request,$symb));
1.202     albertel 9288:  	} elsif ($command eq 'scantron_download' &&
1.257     albertel 9289: 		 &Apache::lonnet::allowed('usc',$env{'request.course.id'})) {
1.616     www      9290:             &startpage($request,$symb,[{href=>'', text=>'Grade/Manage/Review Bubblesheets'}],1,1);
1.608     www      9291:  	    $request->print(&scantron_download_scantron_data($request,$symb));
1.523     raeburn  9292:         } elsif ($command eq 'checksubmissions' && $perm{'vgr'}) {
1.616     www      9293:             &startpage($request,$symb,[{href=>'', text=>'Grade/Manage/Review Bubblesheets'}],1,1);
1.608     www      9294:             $request->print(&checkscantron_results($request,$symb));     
1.106     albertel 9295: 	} elsif ($command) {
1.611     www      9296:             &startpage($request,$symb);
1.562     bisitz   9297: 	    $request->print('<p class="LC_error">'.&mt('Access Denied ([_1])',$command).'</p>');
1.26      albertel 9298: 	}
1.2       albertel 9299:     }
1.513     foxr     9300:     if ($ssi_error) {
                   9301: 	&ssi_print_error($request);
                   9302:     }
1.353     albertel 9303:     $request->print(&Apache::loncommon::end_page());
1.434     albertel 9304:     &reset_caches();
1.44      ng       9305:     return '';
                   9306: }
                   9307: 
1.1       albertel 9308: 1;
                   9309: 
1.13      albertel 9310: __END__;
1.531     jms      9311: 
                   9312: 
                   9313: =head1 NAME
                   9314: 
                   9315: Apache::grades
                   9316: 
                   9317: =head1 SYNOPSIS
                   9318: 
                   9319: Handles the viewing of grades.
                   9320: 
                   9321: This is part of the LearningOnline Network with CAPA project
                   9322: described at http://www.lon-capa.org.
                   9323: 
                   9324: =head1 OVERVIEW
                   9325: 
                   9326: Do an ssi with retries:
                   9327: While I'd love to factor out this with the vesrion in lonprintout,
                   9328: 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
                   9329: I'm not quite ready to invent (e.g. an ssi_with_retry object).
                   9330: 
                   9331: At least the logic that drives this has been pulled out into loncommon.
                   9332: 
                   9333: 
                   9334: 
                   9335: ssi_with_retries - Does the server side include of a resource.
                   9336:                      if the ssi call returns an error we'll retry it up to
                   9337:                      the number of times requested by the caller.
                   9338:                      If we still have a proble, no text is appended to the
                   9339:                      output and we set some global variables.
                   9340:                      to indicate to the caller an SSI error occurred.  
                   9341:                      All of this is supposed to deal with the issues described
                   9342:                      in LonCAPA BZ 5631 see:
                   9343:                      http://bugs.lon-capa.org/show_bug.cgi?id=5631
                   9344:                      by informing the user that this happened.
                   9345: 
                   9346: Parameters:
                   9347:   resource   - The resource to include.  This is passed directly, without
                   9348:                interpretation to lonnet::ssi.
                   9349:   form       - The form hash parameters that guide the interpretation of the resource
                   9350:                
                   9351:   retries    - Number of retries allowed before giving up completely.
                   9352: Returns:
                   9353:   On success, returns the rendered resource identified by the resource parameter.
                   9354: Side Effects:
                   9355:   The following global variables can be set:
                   9356:    ssi_error                - If an unrecoverable error occurred this becomes true.
                   9357:                               It is up to the caller to initialize this to false
                   9358:                               if desired.
                   9359:    ssi_error_resource  - If an unrecoverable error occurred, this is the value
                   9360:                               of the resource that could not be rendered by the ssi
                   9361:                               call.
                   9362:    ssi_error_message   - The error string fetched from the ssi response
                   9363:                               in the event of an error.
                   9364: 
                   9365: 
                   9366: =head1 HANDLER SUBROUTINE
                   9367: 
                   9368: ssi_with_retries()
                   9369: 
                   9370: =head1 SUBROUTINES
                   9371: 
                   9372: =over
                   9373: 
                   9374: =item scantron_get_correction() : 
                   9375: 
                   9376:    Builds the interface screen to interact with the operator to fix a
                   9377:    specific error condition in a specific scanline
                   9378: 
                   9379:  Arguments:
                   9380:     $r           - Apache request object
                   9381:     $i           - number of the current scanline
                   9382:     $scan_record - hash ref as returned from &scantron_parse_scanline()
                   9383:     $scan_config - hash ref as returned from &get_scantron_config()
                   9384:     $line        - full contents of the current scanline
                   9385:     $error       - error condition, valid values are
                   9386:                    'incorrectCODE', 'duplicateCODE',
                   9387:                    'doublebubble', 'missingbubble',
                   9388:                    'duplicateID', 'incorrectID'
                   9389:     $arg         - extra information needed
                   9390:        For errors:
                   9391:          - duplicateID   - paper number that this studentID was seen before on
                   9392:          - duplicateCODE - array ref of the paper numbers this CODE was
                   9393:                            seen on before
                   9394:          - incorrectCODE - current incorrect CODE 
                   9395:          - doublebubble  - array ref of the bubble lines that have double
                   9396:                            bubble errors
                   9397:          - missingbubble - array ref of the bubble lines that have missing
                   9398:                            bubble errors
                   9399: 
                   9400: =item  scantron_get_maxbubble() : 
                   9401: 
1.582     raeburn  9402:    Arguments:
                   9403:        $nav_error  - Reference to scalar which is a flag to indicate a
                   9404:                       failure to retrieve a navmap object.
                   9405:        if $nav_error is set to 1 by scantron_get_maxbubble(), the 
                   9406:        calling routine should trap the error condition and display the warning
                   9407:        found in &navmap_errormsg().
                   9408: 
1.531     jms      9409:    Returns the maximum number of bubble lines that are expected to
                   9410:    occur. Does this by walking the selected sequence rendering the
                   9411:    resource and then checking &Apache::lonxml::get_problem_counter()
                   9412:    for what the current value of the problem counter is.
                   9413: 
                   9414:    Caches the results to $env{'form.scantron_maxbubble'},
                   9415:    $env{'form.scantron.bubble_lines.n'}, 
                   9416:    $env{'form.scantron.first_bubble_line.n'} and
                   9417:    $env{"form.scantron.sub_bubblelines.n"}
                   9418:    which are the total number of bubble, lines, the number of bubble
                   9419:    lines for response n and number of the first bubble line for response n,
                   9420:    and a comma separated list of numbers of bubble lines for sub-questions
                   9421:    (for optionresponse, matchresponse, and rankresponse items), for response n.  
                   9422: 
                   9423: 
                   9424: =item  scantron_validate_missingbubbles() : 
                   9425: 
                   9426:    Validates all scanlines in the selected file to not have any
                   9427:     answers that don't have bubbles that have not been verified
                   9428:     to be bubble free.
                   9429: 
                   9430: =item  scantron_process_students() : 
                   9431: 
                   9432:    Routine that does the actual grading of the bubble sheet information.
                   9433: 
                   9434:    The parsed scanline hash is added to %env 
                   9435: 
                   9436:    Then foreach unskipped scanline it does an &Apache::lonnet::ssi()
                   9437:    foreach resource , with the form data of
                   9438: 
                   9439: 	'submitted'     =>'scantron' 
                   9440: 	'grade_target'  =>'grade',
                   9441: 	'grade_username'=> username of student
                   9442: 	'grade_domain'  => domain of student
                   9443: 	'grade_courseid'=> of course
                   9444: 	'grade_symb'    => symb of resource to grade
                   9445: 
                   9446:     This triggers a grading pass. The problem grading code takes care
                   9447:     of converting the bubbled letter information (now in %env) into a
                   9448:     valid submission.
                   9449: 
                   9450: =item  scantron_upload_scantron_data() :
                   9451: 
                   9452:     Creates the screen for adding a new bubble sheet data file to a course.
                   9453: 
                   9454: =item  scantron_upload_scantron_data_save() : 
                   9455: 
                   9456:    Adds a provided bubble information data file to the course if user
                   9457:    has the correct privileges to do so. 
                   9458: 
                   9459: =item  valid_file() :
                   9460: 
                   9461:    Validates that the requested bubble data file exists in the course.
                   9462: 
                   9463: =item  scantron_download_scantron_data() : 
                   9464: 
                   9465:    Shows a list of the three internal files (original, corrected,
                   9466:    skipped) for a specific bubble sheet data file that exists in the
                   9467:    course.
                   9468: 
                   9469: =item  scantron_validate_ID() : 
                   9470: 
                   9471:    Validates all scanlines in the selected file to not have any
1.556     weissno  9472:    invalid or underspecified student/employee IDs
1.531     jms      9473: 
1.582     raeburn  9474: =item navmap_errormsg() :
                   9475: 
                   9476:    Returns HTML mark-up inside a <div></div> with a link to re-initialize the course.
                   9477:    Should be called whenever the request to instantiate a navmap object fails.  
                   9478: 
1.531     jms      9479: =back
                   9480: 
                   9481: =cut

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