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

1.17      albertel    1: # The LearningOnline Network with CAPA
1.13      albertel    2: # The LON-CAPA Grading handler
1.17      albertel    3: #
1.632   ! www         4: # $Id: grades.pm,v 1.631 2010/04/25 13:18:32 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.622     www        46: use Apache::lonstathelpers;
1.170     albertel   47: use String::Similarity;
1.359     www        48: use LONCAPA;
                     49: 
1.315     bowersj2   50: use POSIX qw(floor);
1.87      www        51: 
1.435     foxr       52: 
1.513     foxr       53: 
1.435     foxr       54: my %perm=();
1.447     foxr       55: 
1.513     foxr       56: #  These variables are used to recover from ssi errors
                     57: 
                     58: my $ssi_retries = 5;
                     59: my $ssi_error;
                     60: my $ssi_error_resource;
                     61: my $ssi_error_message;
                     62: 
                     63: 
                     64: sub ssi_with_retries {
                     65:     my ($resource, $retries, %form) = @_;
                     66:     my ($content, $response) = &Apache::loncommon::ssi_with_retries($resource, $retries, %form);
                     67:     if ($response->is_error) {
                     68: 	$ssi_error          = 1;
                     69: 	$ssi_error_resource = $resource;
                     70: 	$ssi_error_message  = $response->code . " " . $response->message;
                     71:     }
                     72: 
                     73:     return $content;
                     74: 
                     75: }
                     76: #
                     77: #  Prodcuces an ssi retry failure error message to the user:
                     78: #
                     79: 
                     80: sub ssi_print_error {
                     81:     my ($r) = @_;
1.516     raeburn    82:     my $helpurl = &Apache::loncommon::top_nav_help('Helpdesk');
                     83:     $r->print('
                     84: <br />
                     85: <h2>'.&mt('An unrecoverable network error occurred:').'</h2>
                     86: <p>
                     87: '.&mt('Unable to retrieve a resource from a server:').'<br />
                     88: '.&mt('Resource:').' '.$ssi_error_resource.'<br />
                     89: '.&mt('Error:').' '.$ssi_error_message.'
                     90: </p>
                     91: <p>'.
                     92: &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 />'.
                     93: &mt('If the error persists, please contact the [_1] for assistance.',$helpurl).
                     94: '</p>');
                     95:     return;
1.513     foxr       96: }
                     97: 
1.44      ng         98: #
1.146     albertel   99: # --- Retrieve the parts from the metadata file.---
1.598     www       100: # Returns an array of everything that the resources stores away
                    101: #
                    102: 
1.44      ng        103: sub getpartlist {
1.582     raeburn   104:     my ($symb,$errorref) = @_;
1.439     albertel  105: 
                    106:     my $navmap   = Apache::lonnavmaps::navmap->new();
1.582     raeburn   107:     unless (ref($navmap)) {
                    108:         if (ref($errorref)) { 
                    109:             $$errorref = 'navmap';
                    110:             return;
                    111:         }
                    112:     }
1.439     albertel  113:     my $res      = $navmap->getBySymb($symb);
                    114:     my $partlist = $res->parts();
                    115:     my $url      = $res->src();
                    116:     my @metakeys = split(/,/,&Apache::lonnet::metadata($url,'keys'));
                    117: 
1.146     albertel  118:     my @stores;
1.439     albertel  119:     foreach my $part (@{ $partlist }) {
1.146     albertel  120: 	foreach my $key (@metakeys) {
                    121: 	    if ($key =~ m/^stores_\Q$part\E_/) { push(@stores,$key); }
                    122: 	}
                    123:     }
                    124:     return @stores;
1.2       albertel  125: }
                    126: 
1.129     ng        127: #--- Format fullname, username:domain if different for display
                    128: #--- Use anywhere where the student names are listed
                    129: sub nameUserString {
                    130:     my ($type,$fullname,$uname,$udom) = @_;
                    131:     if ($type eq 'header') {
1.485     albertel  132: 	return '<b>&nbsp;'.&mt('Fullname').'&nbsp;</b><span class="LC_internal_info">('.&mt('Username').')</span>';
1.129     ng        133:     } else {
1.398     albertel  134: 	return '&nbsp;'.$fullname.'<span class="LC_internal_info">&nbsp;('.$uname.
                    135: 	    ($env{'user.domain'} eq $udom ? '' : ' ('.$udom.')').')</span>';
1.129     ng        136:     }
                    137: }
                    138: 
1.44      ng        139: #--- Get the partlist and the response type for a given problem. ---
                    140: #--- Indicate if a response type is coded handgraded or not. ---
1.623     www       141: #--- Sets response_error pointer to "1" if navmaps object broken ---
1.39      ng        142: sub response_type {
1.582     raeburn   143:     my ($symb,$response_error) = @_;
1.377     albertel  144: 
                    145:     my $navmap = Apache::lonnavmaps::navmap->new();
1.582     raeburn   146:     unless (ref($navmap)) {
                    147:         if (ref($response_error)) {
                    148:             $$response_error = 1;
                    149:         }
                    150:         return;
                    151:     }
1.377     albertel  152:     my $res = $navmap->getBySymb($symb);
1.593     raeburn   153:     unless (ref($res)) {
                    154:         $$response_error = 1;
                    155:         return;
                    156:     }
1.377     albertel  157:     my $partlist = $res->parts();
1.392     albertel  158:     my %vPart = 
                    159: 	map { $_ => 1 } (&Apache::loncommon::get_env_multiple('form.vPart'));
1.377     albertel  160:     my (%response_types,%handgrade);
                    161:     foreach my $part (@{ $partlist }) {
1.392     albertel  162: 	next if (%vPart && !exists($vPart{$part}));
                    163: 
1.377     albertel  164: 	my @types = $res->responseType($part);
                    165: 	my @ids = $res->responseIds($part);
                    166: 	for (my $i=0; $i < scalar(@ids); $i++) {
                    167: 	    $response_types{$part}{$ids[$i]} = $types[$i];
                    168: 	    $handgrade{$part.'_'.$ids[$i]} = 
                    169: 		&Apache::lonnet::EXT('resource.'.$part.'_'.$ids[$i].
                    170: 				     '.handgrade',$symb);
1.41      ng        171: 	}
                    172:     }
1.377     albertel  173:     return ($partlist,\%handgrade,\%response_types);
1.39      ng        174: }
                    175: 
1.375     albertel  176: sub flatten_responseType {
                    177:     my ($responseType) = @_;
                    178:     my @part_response_id =
                    179: 	map { 
                    180: 	    my $part = $_;
                    181: 	    map {
                    182: 		[$part,$_]
                    183: 		} sort(keys(%{ $responseType->{$part} }));
                    184: 	} sort(keys(%$responseType));
                    185:     return @part_response_id;
                    186: }
                    187: 
1.207     albertel  188: sub get_display_part {
1.324     albertel  189:     my ($partID,$symb)=@_;
1.207     albertel  190:     my $display=&Apache::lonnet::EXT('resource.'.$partID.'.display',$symb);
                    191:     if (defined($display) and $display ne '') {
1.577     bisitz    192:         $display.= ' (<span class="LC_internal_info">'
                    193:                   .&mt('Part ID: [_1]',$partID).'</span>)';
1.207     albertel  194:     } else {
                    195: 	$display=$partID;
                    196:     }
                    197:     return $display;
                    198: }
1.269     raeburn   199: 
1.434     albertel  200: sub reset_caches {
                    201:     &reset_analyze_cache();
                    202:     &reset_perm();
                    203: }
                    204: 
                    205: {
                    206:     my %analyze_cache;
1.557     raeburn   207:     my %analyze_cache_formkeys;
1.148     albertel  208: 
1.434     albertel  209:     sub reset_analyze_cache {
                    210: 	undef(%analyze_cache);
1.557     raeburn   211:         undef(%analyze_cache_formkeys);
1.434     albertel  212:     }
                    213: 
                    214:     sub get_analyze {
1.557     raeburn   215: 	my ($symb,$uname,$udom,$no_increment,$add_to_hash)=@_;
1.434     albertel  216: 	my $key = "$symb\0$uname\0$udom";
1.557     raeburn   217: 	if (exists($analyze_cache{$key})) {
                    218:             my $getupdate = 0;
                    219:             if (ref($add_to_hash) eq 'HASH') {
                    220:                 foreach my $item (keys(%{$add_to_hash})) {
                    221:                     if (ref($analyze_cache_formkeys{$key}) eq 'HASH') {
                    222:                         if (!exists($analyze_cache_formkeys{$key}{$item})) {
                    223:                             $getupdate = 1;
                    224:                             last;
                    225:                         }
                    226:                     } else {
                    227:                         $getupdate = 1;
                    228:                     }
                    229:                 }
                    230:             }
                    231:             if (!$getupdate) {
                    232:                 return $analyze_cache{$key};
                    233:             }
                    234:         }
1.434     albertel  235: 
                    236: 	my (undef,undef,$url)=&Apache::lonnet::decode_symb($symb);
                    237: 	$url=&Apache::lonnet::clutter($url);
1.557     raeburn   238:         my %form = ('grade_target'      => 'analyze',
                    239:                     'grade_domain'      => $udom,
                    240:                     'grade_symb'        => $symb,
                    241:                     'grade_courseid'    =>  $env{'request.course.id'},
                    242:                     'grade_username'    => $uname,
                    243:                     'grade_noincrement' => $no_increment);
                    244:         if (ref($add_to_hash)) {
                    245:             %form = (%form,%{$add_to_hash});
                    246:         } 
                    247: 	my $subresult=&ssi_with_retries($url, $ssi_retries,%form);
1.434     albertel  248: 	(undef,$subresult)=split(/_HASH_REF__/,$subresult,2);
                    249: 	my %analyze=&Apache::lonnet::str2hash($subresult);
1.557     raeburn   250:         if (ref($add_to_hash) eq 'HASH') {
                    251:             $analyze_cache_formkeys{$key} = $add_to_hash;
                    252:         } else {
                    253:             $analyze_cache_formkeys{$key} = {};
                    254:         }
1.434     albertel  255: 	return $analyze_cache{$key} = \%analyze;
                    256:     }
                    257: 
                    258:     sub get_order {
1.525     raeburn   259: 	my ($partid,$respid,$symb,$uname,$udom,$no_increment)=@_;
                    260: 	my $analyze = &get_analyze($symb,$uname,$udom,$no_increment);
1.434     albertel  261: 	return $analyze->{"$partid.$respid.shown"};
                    262:     }
                    263: 
                    264:     sub get_radiobutton_correct_foil {
                    265: 	my ($partid,$respid,$symb,$uname,$udom)=@_;
                    266: 	my $analyze = &get_analyze($symb,$uname,$udom);
1.555     raeburn   267:         my $foils = &get_order($partid,$respid,$symb,$uname,$udom);
                    268:         if (ref($foils) eq 'ARRAY') {
                    269: 	    foreach my $foil (@{$foils}) {
                    270: 	        if ($analyze->{"$partid.$respid.foil.value.$foil"} eq 'true') {
                    271: 		    return $foil;
                    272: 	        }
1.434     albertel  273: 	    }
                    274: 	}
                    275:     }
1.554     raeburn   276: 
                    277:     sub scantron_partids_tograde {
1.557     raeburn   278:         my ($resource,$cid,$uname,$udom,$check_for_randomlist) = @_;
1.554     raeburn   279:         my (%analysis,@parts);
                    280:         if (ref($resource)) {
                    281:             my $symb = $resource->symb();
1.557     raeburn   282:             my $add_to_form;
                    283:             if ($check_for_randomlist) {
                    284:                 $add_to_form = { 'check_parts_withrandomlist' => 1,};
                    285:             }
                    286:             my $analyze = &get_analyze($symb,$uname,$udom,undef,$add_to_form);
1.554     raeburn   287:             if (ref($analyze) eq 'HASH') {
                    288:                 %analysis = %{$analyze};
                    289:             }
                    290:             if (ref($analysis{'parts'}) eq 'ARRAY') {
                    291:                 foreach my $part (@{$analysis{'parts'}}) {
                    292:                     my ($id,$respid) = split(/\./,$part);
                    293:                     if (!&Apache::loncommon::check_if_partid_hidden($id,$symb,$udom,$uname)) {
                    294:                         push(@parts,$part);
                    295:                     }
                    296:                 }
                    297:             }
                    298:         }
                    299:         return (\%analysis,\@parts);
                    300:     }
                    301: 
1.148     albertel  302: }
1.434     albertel  303: 
1.118     ng        304: #--- Clean response type for display
1.335     albertel  305: #--- Currently filters option/rank/radiobutton/match/essay/Task
                    306: #        response types only.
1.118     ng        307: sub cleanRecord {
1.336     albertel  308:     my ($answer,$response,$symb,$partid,$respid,$record,$order,$version,
                    309: 	$uname,$udom) = @_;
1.398     albertel  310:     my $grayFont = '<span class="LC_internal_info">';
1.148     albertel  311:     if ($response =~ /^(option|rank)$/) {
                    312: 	my %answer=&Apache::lonnet::str2hash($answer);
                    313: 	my %grading=&Apache::lonnet::str2hash($record->{$version."resource.$partid.$respid.submissiongrading"});
                    314: 	my ($toprow,$bottomrow);
                    315: 	foreach my $foil (@$order) {
                    316: 	    if ($grading{$foil} == 1) {
                    317: 		$toprow.='<td><b>'.$answer{$foil}.'&nbsp;</b></td>';
                    318: 	    } else {
                    319: 		$toprow.='<td><i>'.$answer{$foil}.'&nbsp;</i></td>';
                    320: 	    }
1.398     albertel  321: 	    $bottomrow.='<td>'.$grayFont.$foil.'</span>&nbsp;</td>';
1.148     albertel  322: 	}
                    323: 	return '<blockquote><table border="1">'.
1.466     albertel  324: 	    '<tr valign="top"><td>'.&mt('Answer').'</td>'.$toprow.'</tr>'.
                    325: 	    '<tr valign="top"><td>'.$grayFont.&mt('Option ID').'</span></td>'.
1.148     albertel  326: 	    $grayFont.$bottomrow.'</tr>'.'</table></blockquote>';
                    327:     } elsif ($response eq 'match') {
                    328: 	my %answer=&Apache::lonnet::str2hash($answer);
                    329: 	my %grading=&Apache::lonnet::str2hash($record->{$version."resource.$partid.$respid.submissiongrading"});
                    330: 	my @items=&Apache::lonnet::str2array($record->{$version."resource.$partid.$respid.submissionitems"});
                    331: 	my ($toprow,$middlerow,$bottomrow);
                    332: 	foreach my $foil (@$order) {
                    333: 	    my $item=shift(@items);
                    334: 	    if ($grading{$foil} == 1) {
                    335: 		$toprow.='<td><b>'.$item.'&nbsp;</b></td>';
1.398     albertel  336: 		$middlerow.='<td><b>'.$grayFont.$answer{$foil}.'&nbsp;</span></b></td>';
1.148     albertel  337: 	    } else {
                    338: 		$toprow.='<td><i>'.$item.'&nbsp;</i></td>';
1.398     albertel  339: 		$middlerow.='<td><i>'.$grayFont.$answer{$foil}.'&nbsp;</span></i></td>';
1.148     albertel  340: 	    }
1.398     albertel  341: 	    $bottomrow.='<td>'.$grayFont.$foil.'</span>&nbsp;</td>';
1.118     ng        342: 	}
1.126     ng        343: 	return '<blockquote><table border="1">'.
1.466     albertel  344: 	    '<tr valign="top"><td>'.&mt('Answer').'</td>'.$toprow.'</tr>'.
                    345: 	    '<tr valign="top"><td>'.$grayFont.&mt('Item ID').'</span></td>'.
1.148     albertel  346: 	    $middlerow.'</tr>'.
1.466     albertel  347: 	    '<tr valign="top"><td>'.$grayFont.&mt('Option ID').'</span></td>'.
1.148     albertel  348: 	    $bottomrow.'</tr>'.'</table></blockquote>';
                    349:     } elsif ($response eq 'radiobutton') {
                    350: 	my %answer=&Apache::lonnet::str2hash($answer);
                    351: 	my ($toprow,$bottomrow);
1.434     albertel  352: 	my $correct = 
                    353: 	    &get_radiobutton_correct_foil($partid,$respid,$symb,$uname,$udom);
                    354: 	foreach my $foil (@$order) {
1.148     albertel  355: 	    if (exists($answer{$foil})) {
1.434     albertel  356: 		if ($foil eq $correct) {
1.466     albertel  357: 		    $toprow.='<td><b>'.&mt('true').'</b></td>';
1.148     albertel  358: 		} else {
1.466     albertel  359: 		    $toprow.='<td><i>'.&mt('true').'</i></td>';
1.148     albertel  360: 		}
                    361: 	    } else {
1.466     albertel  362: 		$toprow.='<td>'.&mt('false').'</td>';
1.148     albertel  363: 	    }
1.398     albertel  364: 	    $bottomrow.='<td>'.$grayFont.$foil.'</span>&nbsp;</td>';
1.148     albertel  365: 	}
                    366: 	return '<blockquote><table border="1">'.
1.466     albertel  367: 	    '<tr valign="top"><td>'.&mt('Answer').'</td>'.$toprow.'</tr>'.
                    368: 	    '<tr valign="top"><td>'.$grayFont.&mt('Option ID').'</span></td>'.
1.597     wenzelju  369: 	    $bottomrow.'</tr>'.'</table></blockquote>';
1.148     albertel  370:     } elsif ($response eq 'essay') {
1.257     albertel  371: 	if (! exists ($env{'form.'.$symb})) {
1.122     ng        372: 	    my (%keyhash) = &Apache::lonnet::dump('nohist_handgrade',
1.257     albertel  373: 						  $env{'course.'.$env{'request.course.id'}.'.domain'},
                    374: 						  $env{'course.'.$env{'request.course.id'}.'.num'});
1.122     ng        375: 
1.257     albertel  376: 	    my $loginuser = $env{'user.name'}.':'.$env{'user.domain'};
                    377: 	    $env{'form.keywords'} = $keyhash{$symb.'_keywords'} ne '' ? $keyhash{$symb.'_keywords'} : '';
                    378: 	    $env{'form.kwclr'}    = $keyhash{$loginuser.'_kwclr'} ne '' ? $keyhash{$loginuser.'_kwclr'} : 'red';
                    379: 	    $env{'form.kwsize'}   = $keyhash{$loginuser.'_kwsize'} ne '' ? $keyhash{$loginuser.'_kwsize'} : '0';
                    380: 	    $env{'form.kwstyle'}  = $keyhash{$loginuser.'_kwstyle'} ne '' ? $keyhash{$loginuser.'_kwstyle'} : '';
                    381: 	    $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        382: 	}
1.166     albertel  383: 	$answer =~ s-\n-<br />-g;
                    384: 	return '<br /><br /><blockquote><tt>'.&keywords_highlight($answer).'</tt></blockquote>';
1.268     albertel  385:     } elsif ( $response eq 'organic') {
                    386: 	my $result='Smile representation: "<tt>'.$answer.'</tt>"';
                    387: 	my $jme=$record->{$version."resource.$partid.$respid.molecule"};
                    388: 	$result.=&Apache::chemresponse::jme_img($jme,$answer,400);
                    389: 	return $result;
1.335     albertel  390:     } elsif ( $response eq 'Task') {
                    391: 	if ( $answer eq 'SUBMITTED') {
                    392: 	    my $files = $record->{$version."resource.$respid.$partid.bridgetask.portfiles"};
1.336     albertel  393: 	    my $result = &Apache::bridgetask::file_list($files,$uname,$udom);
1.335     albertel  394: 	    return $result;
                    395: 	} elsif ( grep(/^\Q$version\E.*?\.instance$/, keys(%{$record})) ) {
                    396: 	    my @matches = grep(/^\Q$version\E.*?\.instance$/,
                    397: 			       keys(%{$record}));
                    398: 	    return join('<br />',($version,@matches));
                    399: 			       
                    400: 			       
                    401: 	} else {
                    402: 	    my $result =
                    403: 		'<p>'
                    404: 		.&mt('Overall result: [_1]',
                    405: 		     $record->{$version."resource.$respid.$partid.status"})
                    406: 		.'</p>';
                    407: 	    
                    408: 	    $result .= '<ul>';
                    409: 	    my @grade = grep(/^\Q${version}resource.$respid.$partid.\E[^.]*[.]status$/,
                    410: 			     keys(%{$record}));
                    411: 	    foreach my $grade (sort(@grade)) {
                    412: 		my ($dim) = ($grade =~/[.]([^.]+)[.]status$/);
                    413: 		$result.= '<li>'.&mt("Dimension: [_1], status [_2] ",
                    414: 				     $dim, $record->{$grade}).
                    415: 			  '</li>';
                    416: 	    }
                    417: 	    $result.='</ul>';
                    418: 	    return $result;
                    419: 	}
1.440     albertel  420:     } elsif ( $response =~ m/(?:numerical|formula)/) {
                    421: 	$answer = 
                    422: 	    &Apache::loncommon::format_previous_attempt_value('submission',
                    423: 							      $answer);
1.122     ng        424:     }
1.118     ng        425:     return $answer;
                    426: }
                    427: 
                    428: #-- A couple of common js functions
                    429: sub commonJSfunctions {
                    430:     my $request = shift;
1.597     wenzelju  431:     $request->print(&Apache::lonhtmlcommon::scripttag(<<COMMONJSFUNCTIONS));
1.118     ng        432:     function radioSelection(radioButton) {
                    433: 	var selection=null;
                    434: 	if (radioButton.length > 1) {
                    435: 	    for (var i=0; i<radioButton.length; i++) {
                    436: 		if (radioButton[i].checked) {
                    437: 		    return radioButton[i].value;
                    438: 		}
                    439: 	    }
                    440: 	} else {
                    441: 	    if (radioButton.checked) return radioButton.value;
                    442: 	}
                    443: 	return selection;
                    444:     }
                    445: 
                    446:     function pullDownSelection(selectOne) {
                    447: 	var selection="";
                    448: 	if (selectOne.length > 1) {
                    449: 	    for (var i=0; i<selectOne.length; i++) {
                    450: 		if (selectOne[i].selected) {
                    451: 		    return selectOne[i].value;
                    452: 		}
                    453: 	    }
                    454: 	} else {
1.138     albertel  455:             // only one value it must be the selected one
                    456: 	    return selectOne.value;
1.118     ng        457: 	}
                    458:     }
                    459: COMMONJSFUNCTIONS
                    460: }
                    461: 
1.44      ng        462: #--- Dumps the class list with usernames,list of sections,
                    463: #--- section, ids and fullnames for each user.
                    464: sub getclasslist {
1.449     banghart  465:     my ($getsec,$filterlist,$getgroup) = @_;
1.291     albertel  466:     my @getsec;
1.450     banghart  467:     my @getgroup;
1.442     banghart  468:     my $stu_status = join(':',&Apache::loncommon::get_env_multiple('form.Status'));
1.291     albertel  469:     if (!ref($getsec)) {
                    470: 	if ($getsec ne '' && $getsec ne 'all') {
                    471: 	    @getsec=($getsec);
                    472: 	}
                    473:     } else {
                    474: 	@getsec=@{$getsec};
                    475:     }
                    476:     if (grep(/^all$/,@getsec)) { undef(@getsec); }
1.450     banghart  477:     if (!ref($getgroup)) {
                    478: 	if ($getgroup ne '' && $getgroup ne 'all') {
                    479: 	    @getgroup=($getgroup);
                    480: 	}
                    481:     } else {
                    482: 	@getgroup=@{$getgroup};
                    483:     }
                    484:     if (grep(/^all$/,@getgroup)) { undef(@getgroup); }
1.291     albertel  485: 
1.449     banghart  486:     my ($classlist,$keylist)=&Apache::loncoursedata::get_classlist();
1.49      albertel  487:     # Bail out if we were unable to get the classlist
1.56      matthew   488:     return if (! defined($classlist));
1.449     banghart  489:     &Apache::loncoursedata::get_group_memberships($classlist,$keylist);
1.56      matthew   490:     #
                    491:     my %sections;
                    492:     my %fullnames;
1.205     matthew   493:     foreach my $student (keys(%$classlist)) {
                    494:         my $end      = 
                    495:             $classlist->{$student}->[&Apache::loncoursedata::CL_END()];
                    496:         my $start    = 
                    497:             $classlist->{$student}->[&Apache::loncoursedata::CL_START()];
                    498:         my $id       = 
                    499:             $classlist->{$student}->[&Apache::loncoursedata::CL_ID()];
                    500:         my $section  = 
                    501:             $classlist->{$student}->[&Apache::loncoursedata::CL_SECTION()];
                    502:         my $fullname = 
                    503:             $classlist->{$student}->[&Apache::loncoursedata::CL_FULLNAME()];
                    504:         my $status   = 
                    505:             $classlist->{$student}->[&Apache::loncoursedata::CL_STATUS()];
1.449     banghart  506:         my $group   = 
                    507:             $classlist->{$student}->[&Apache::loncoursedata::CL_GROUP()];
1.76      ng        508: 	# filter students according to status selected
1.442     banghart  509: 	if ($filterlist && (!($stu_status =~ /Any/))) {
                    510: 	    if (!($stu_status =~ $status)) {
1.450     banghart  511: 		delete($classlist->{$student});
1.76      ng        512: 		next;
                    513: 	    }
                    514: 	}
1.450     banghart  515: 	# filter students according to groups selected
1.453     banghart  516: 	my @stu_groups = split(/,/,$group);
1.450     banghart  517: 	if (@getgroup) {
                    518: 	    my $exclude = 1;
1.454     banghart  519: 	    foreach my $grp (@getgroup) {
                    520: 	        foreach my $stu_group (@stu_groups) {
1.453     banghart  521: 	            if ($stu_group eq $grp) {
                    522: 	                $exclude = 0;
                    523:     	            } 
1.450     banghart  524: 	        }
1.453     banghart  525:     	        if (($grp eq 'none') && !$group) {
                    526:         	        $exclude = 0;
                    527:         	}
1.450     banghart  528: 	    }
                    529: 	    if ($exclude) {
                    530: 	        delete($classlist->{$student});
                    531: 	    }
                    532: 	}
1.205     matthew   533: 	$section = ($section ne '' ? $section : 'none');
1.106     albertel  534: 	if (&canview($section)) {
1.291     albertel  535: 	    if (!@getsec || grep(/^\Q$section\E$/,@getsec)) {
1.103     albertel  536: 		$sections{$section}++;
1.450     banghart  537: 		if ($classlist->{$student}) {
                    538: 		    $fullnames{$student}=$fullname;
                    539: 		}
1.103     albertel  540: 	    } else {
1.205     matthew   541: 		delete($classlist->{$student});
1.103     albertel  542: 	    }
                    543: 	} else {
1.205     matthew   544: 	    delete($classlist->{$student});
1.103     albertel  545: 	}
1.44      ng        546:     }
                    547:     my %seen = ();
1.56      matthew   548:     my @sections = sort(keys(%sections));
                    549:     return ($classlist,\@sections,\%fullnames);
1.44      ng        550: }
                    551: 
1.103     albertel  552: sub canmodify {
                    553:     my ($sec)=@_;
                    554:     if ($perm{'mgr'}) {
                    555: 	if (!defined($perm{'mgr_section'})) {
                    556: 	    # can modify whole class
                    557: 	    return 1;
                    558: 	} else {
                    559: 	    if ($sec eq $perm{'mgr_section'}) {
                    560: 		#can modify the requested section
                    561: 		return 1;
                    562: 	    } else {
                    563: 		# can't modify the request section
                    564: 		return 0;
                    565: 	    }
                    566: 	}
                    567:     }
                    568:     #can't modify
                    569:     return 0;
                    570: }
                    571: 
                    572: sub canview {
                    573:     my ($sec)=@_;
                    574:     if ($perm{'vgr'}) {
                    575: 	if (!defined($perm{'vgr_section'})) {
                    576: 	    # can modify whole class
                    577: 	    return 1;
                    578: 	} else {
                    579: 	    if ($sec eq $perm{'vgr_section'}) {
                    580: 		#can modify the requested section
                    581: 		return 1;
                    582: 	    } else {
                    583: 		# can't modify the request section
                    584: 		return 0;
                    585: 	    }
                    586: 	}
                    587:     }
                    588:     #can't modify
                    589:     return 0;
                    590: }
                    591: 
1.44      ng        592: #--- Retrieve the grade status of a student for all the parts
                    593: sub student_gradeStatus {
1.324     albertel  594:     my ($symb,$udom,$uname,$partlist) = @_;
1.257     albertel  595:     my %record     = &Apache::lonnet::restore($symb,$env{'request.course.id'},$udom,$uname);
1.44      ng        596:     my %partstatus = ();
                    597:     foreach (@$partlist) {
1.128     ng        598: 	my ($status,undef)   = split(/_/,$record{"resource.$_.solved"},2);
1.44      ng        599: 	$status              = 'nothing' if ($status eq '');
                    600: 	$partstatus{$_}      = $status;
                    601: 	my $subkey           = "resource.$_.submitted_by";
                    602: 	$partstatus{$subkey} = $record{$subkey} if ($record{$subkey} ne '');
                    603:     }
                    604:     return %partstatus;
                    605: }
                    606: 
1.45      ng        607: # hidden form and javascript that calls the form
                    608: # Use by verifyscript and viewgrades
                    609: # Shows a student's view of problem and submission
                    610: sub jscriptNform {
1.324     albertel  611:     my ($symb) = @_;
1.442     banghart  612:     my $stu_status = join(':',&Apache::loncommon::get_env_multiple('form.Status'));
1.597     wenzelju  613:     my $jscript= &Apache::lonhtmlcommon::scripttag(
1.45      ng        614: 	'    function viewOneStudent(user,domain) {'."\n".
                    615: 	'	document.onestudent.student.value = user;'."\n".
                    616: 	'	document.onestudent.userdom.value = domain;'."\n".
                    617: 	'	document.onestudent.submit();'."\n".
                    618: 	'    }'."\n".
1.597     wenzelju  619: 	"\n");
1.45      ng        620:     $jscript.= '<form action="/adm/grades" method="post" name="onestudent">'."\n".
1.418     albertel  621: 	'<input type="hidden" name="symb"    value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
1.442     banghart  622: 	'<input type="hidden" name="Status"  value="'.$stu_status.'" />'."\n".
1.45      ng        623: 	'<input type="hidden" name="command" value="submission" />'."\n".
                    624: 	'<input type="hidden" name="student" value="" />'."\n".
                    625: 	'<input type="hidden" name="userdom" value="" />'."\n".
                    626: 	'</form>'."\n";
                    627:     return $jscript;
                    628: }
1.39      ng        629: 
1.447     foxr      630: 
                    631: 
1.315     bowersj2  632: # Given the score (as a number [0-1] and the weight) what is the final
                    633: # point value? This function will round to the nearest tenth, third,
                    634: # or quarter if one of those is within the tolerance of .00001.
1.316     albertel  635: sub compute_points {
1.315     bowersj2  636:     my ($score, $weight) = @_;
                    637:     
                    638:     my $tolerance = .00001;
                    639:     my $points = $score * $weight;
                    640: 
                    641:     # Check for nearness to 1/x.
                    642:     my $check_for_nearness = sub {
                    643:         my ($factor) = @_;
                    644:         my $num = ($points * $factor) + $tolerance;
                    645:         my $floored_num = floor($num);
1.316     albertel  646:         if ($num - $floored_num < 2 * $tolerance * $factor) {
1.315     bowersj2  647:             return $floored_num / $factor;
                    648:         }
                    649:         return $points;
                    650:     };
                    651: 
                    652:     $points = $check_for_nearness->(10);
                    653:     $points = $check_for_nearness->(3);
                    654:     $points = $check_for_nearness->(4);
                    655:     
                    656:     return $points;
                    657: }
                    658: 
1.44      ng        659: #------------------ End of general use routines --------------------
1.87      www       660: 
                    661: #
                    662: # Find most similar essay
                    663: #
                    664: 
                    665: sub most_similar {
1.426     albertel  666:     my ($uname,$udom,$uessay,$old_essays)=@_;
1.87      www       667: 
                    668: # ignore spaces and punctuation
                    669: 
                    670:     $uessay=~s/\W+/ /gs;
                    671: 
1.282     www       672: # ignore empty submissions (occuring when only files are sent)
                    673: 
1.598     www       674:     unless ($uessay=~/\w+/s) { return ''; }
1.282     www       675: 
1.87      www       676: # these will be returned. Do not care if not at least 50 percent similar
1.88      www       677:     my $limit=0.6;
1.87      www       678:     my $sname='';
                    679:     my $sdom='';
                    680:     my $scrsid='';
                    681:     my $sessay='';
                    682: # go through all essays ...
1.426     albertel  683:     foreach my $tkey (keys(%$old_essays)) {
                    684: 	my ($tname,$tdom,$tcrsid)=map {&unescape($_)} (split(/\./,$tkey));
1.87      www       685: # ... except the same student
1.426     albertel  686:         next if (($tname eq $uname) && ($tdom eq $udom));
                    687: 	my $tessay=$old_essays->{$tkey};
                    688: 	$tessay=~s/\W+/ /gs;
1.87      www       689: # String similarity gives up if not even limit
1.426     albertel  690: 	my $tsimilar=&String::Similarity::similarity($uessay,$tessay,$limit);
1.87      www       691: # Found one
1.426     albertel  692: 	if ($tsimilar>$limit) {
                    693: 	    $limit=$tsimilar;
                    694: 	    $sname=$tname;
                    695: 	    $sdom=$tdom;
                    696: 	    $scrsid=$tcrsid;
                    697: 	    $sessay=$old_essays->{$tkey};
                    698: 	}
1.87      www       699:     }
1.88      www       700:     if ($limit>0.6) {
1.87      www       701:        return ($sname,$sdom,$scrsid,$sessay,$limit);
                    702:     } else {
                    703:        return ('','','','',0);
                    704:     }
                    705: }
                    706: 
1.44      ng        707: #-------------------------------------------------------------------
                    708: 
                    709: #------------------------------------ Receipt Verification Routines
1.45      ng        710: #
1.602     www       711: 
                    712: sub initialverifyreceipt {
1.608     www       713:    my ($request,$symb) = @_;
1.602     www       714:    &commonJSfunctions($request);
1.605     www       715:    return '<form name="gradingMenu"><input type="submit" value="'.&mt('Verify Receipt Number.').'" />'.
1.602     www       716:         &Apache::lonnet::recprefix($env{'request.course.id'}).
                    717:         '-<input type="text" name="receipt" size="4" />'.
1.603     www       718:         '<input type="hidden" name="symb" value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
                    719:         '<input type="hidden" name="command" value="verify" />'.
                    720:         "</form>\n";
1.602     www       721: }
                    722: 
1.44      ng        723: #--- Check whether a receipt number is valid.---
                    724: sub verifyreceipt {
1.608     www       725:     my ($request,$symb)  = @_;
1.44      ng        726: 
1.257     albertel  727:     my $courseid = $env{'request.course.id'};
1.184     www       728:     my $receipt  = &Apache::lonnet::recprefix($courseid).'-'.
1.257     albertel  729: 	$env{'form.receipt'};
1.44      ng        730:     $receipt     =~ s/[^\-\d]//g;
                    731: 
1.487     albertel  732:     my $title.=
                    733: 	'<h3><span class="LC_info">'.
1.605     www       734: 	&mt('Verifying Receipt Number [_1]',$receipt).
                    735: 	'</span></h3>'."\n";
1.44      ng        736: 
                    737:     my ($string,$contents,$matches) = ('','',0);
1.56      matthew   738:     my (undef,undef,$fullname) = &getclasslist('all','0');
1.177     albertel  739:     
                    740:     my $receiptparts=0;
1.390     albertel  741:     if ($env{"course.$courseid.receiptalg"} eq 'receipt2' ||
                    742: 	$env{"course.$courseid.receiptalg"} eq 'receipt3') { $receiptparts=1; }
1.177     albertel  743:     my $parts=['0'];
1.582     raeburn   744:     if ($receiptparts) {
                    745:         my $res_error; 
                    746:         ($parts)=&response_type($symb,\$res_error);
                    747:         if ($res_error) {
                    748:             return &navmap_errormsg();
                    749:         } 
                    750:     }
1.486     albertel  751:     
                    752:     my $header = 
                    753: 	&Apache::loncommon::start_data_table().
                    754: 	&Apache::loncommon::start_data_table_header_row().
1.487     albertel  755: 	'<th>&nbsp;'.&mt('Fullname').'&nbsp;</th>'."\n".
                    756: 	'<th>&nbsp;'.&mt('Username').'&nbsp;</th>'."\n".
                    757: 	'<th>&nbsp;'.&mt('Domain').'&nbsp;</th>';
1.486     albertel  758:     if ($receiptparts) {
1.487     albertel  759: 	$header.='<th>&nbsp;'.&mt('Problem Part').'&nbsp;</th>';
1.486     albertel  760:     }
                    761:     $header.=
                    762: 	&Apache::loncommon::end_data_table_header_row();
                    763: 
1.294     albertel  764:     foreach (sort 
                    765: 	     {
                    766: 		 if (lc($$fullname{$a}) ne lc($$fullname{$b})) {
                    767: 		     return (lc($$fullname{$a}) cmp lc($$fullname{$b}));
                    768: 		 }
                    769: 		 return $a cmp $b;
                    770: 	     } (keys(%$fullname))) {
1.44      ng        771: 	my ($uname,$udom)=split(/\:/);
1.177     albertel  772: 	foreach my $part (@$parts) {
                    773: 	    if ($receipt eq &Apache::lonnet::ireceipt($uname,$udom,$courseid,$symb,$part)) {
1.486     albertel  774: 		$contents.=
                    775: 		    &Apache::loncommon::start_data_table_row().
                    776: 		    '<td>&nbsp;'."\n".
1.177     albertel  777: 		    '<a href="javascript:viewOneStudent(\''.$uname.'\',\''.$udom.
1.417     albertel  778: 		    '\');" target="_self">'.$$fullname{$_}.'</a>&nbsp;</td>'."\n".
1.177     albertel  779: 		    '<td>&nbsp;'.$uname.'&nbsp;</td>'.
                    780: 		    '<td>&nbsp;'.$udom.'&nbsp;</td>';
                    781: 		if ($receiptparts) {
                    782: 		    $contents.='<td>&nbsp;'.$part.'&nbsp;</td>';
                    783: 		}
1.486     albertel  784: 		$contents.= 
                    785: 		    &Apache::loncommon::end_data_table_row()."\n";
1.177     albertel  786: 		
                    787: 		$matches++;
                    788: 	    }
1.44      ng        789: 	}
                    790:     }
                    791:     if ($matches == 0) {
1.584     bisitz    792:         $string = $title
                    793:                  .'<p class="LC_warning">'
                    794:                  .&mt('No match found for the above receipt number.')
                    795:                  .'</p>';
1.44      ng        796:     } else {
1.324     albertel  797: 	$string = &jscriptNform($symb).$title.
1.487     albertel  798: 	    '<p>'.
1.584     bisitz    799: 	    &mt('The above receipt number matches the following [quant,_1,student].',$matches).
1.487     albertel  800: 	    '</p>'.
1.486     albertel  801: 	    $header.
                    802: 	    $contents.
                    803: 	    &Apache::loncommon::end_data_table()."\n";
1.44      ng        804:     }
1.614     www       805:     return $string;
1.44      ng        806: }
                    807: 
                    808: #--- This is called by a number of programs.
                    809: #--- Called from the Grading Menu - View/Grade an individual student
                    810: #--- Also called directly when one clicks on the subm button 
                    811: #    on the problem page.
1.30      ng        812: sub listStudents {
1.617     www       813:     my ($request,$symb,$submitonly) = @_;
1.49      albertel  814: 
1.257     albertel  815:     my $cdom      = $env{"course.$env{'request.course.id'}.domain"};
                    816:     my $cnum      = $env{"course.$env{'request.course.id'}.num"};
                    817:     my $getsec    = $env{'form.section'} eq '' ? 'all' : $env{'form.section'};
1.449     banghart  818:     my $getgroup  = $env{'form.group'} eq '' ? 'all' : $env{'form.group'};
1.617     www       819:     unless ($submitonly) {
                    820:        $submitonly= $env{'form.submitonly'} eq '' ? 'all' : $env{'form.submitonly'};
                    821:     }
1.49      albertel  822: 
1.632   ! www       823:     my $result='';
1.623     www       824:     my $res_error;
                    825:     my ($partlist,$handgrade,$responseType) = &response_type($symb,\$res_error);
1.49      albertel  826: 
1.559     raeburn   827:     my %lt = &Apache::lonlocal::texthash (
                    828: 		'multiple' => 'Please select a student or group of students before clicking on the Next button.',
                    829: 		'single'   => 'Please select the student before clicking on the Next button.',
                    830: 	     );
1.597     wenzelju  831:     $request->print(&Apache::lonhtmlcommon::scripttag(<<LISTJAVASCRIPT));
1.110     ng        832:     function checkSelect(checkBox) {
                    833: 	var ctr=0;
                    834: 	var sense="";
                    835: 	if (checkBox.length > 1) {
                    836: 	    for (var i=0; i<checkBox.length; i++) {
                    837: 		if (checkBox[i].checked) {
                    838: 		    ctr++;
                    839: 		}
                    840: 	    }
1.485     albertel  841: 	    sense = '$lt{'multiple'}';
1.110     ng        842: 	} else {
                    843: 	    if (checkBox.checked) {
                    844: 		ctr = 1;
                    845: 	    }
1.485     albertel  846: 	    sense = '$lt{'single'}';
1.110     ng        847: 	}
                    848: 	if (ctr == 0) {
1.485     albertel  849: 	    alert(sense);
1.110     ng        850: 	    return false;
                    851: 	}
                    852: 	document.gradesub.submit();
                    853:     }
                    854: 
                    855:     function reLoadList(formname) {
1.112     ng        856: 	if (formname.saveStatusOld.value == pullDownSelection(formname.Status)) {return;}
1.110     ng        857: 	formname.command.value = 'submission';
                    858: 	formname.submit();
                    859:     }
1.45      ng        860: LISTJAVASCRIPT
                    861: 
1.118     ng        862:     &commonJSfunctions($request);
1.41      ng        863:     $request->print($result);
1.39      ng        864: 
1.154     albertel  865:     my $gradeTable='<form action="/adm/grades" method="post" name="gradesub">'.
1.598     www       866: 	"\n";
1.485     albertel  867: 	
1.561     bisitz    868:     $gradeTable .= &Apache::lonhtmlcommon::start_pick_box();
                    869:     $gradeTable .= &Apache::lonhtmlcommon::row_title(&mt('View Problem Text'))
                    870:                   .'<label><input type="radio" name="vProb" value="no" checked="checked" /> '.&mt('no').' </label>'."\n"
                    871:                   .'<label><input type="radio" name="vProb" value="yes" /> '.&mt('one student').' </label>'."\n"
                    872:                   .'<label><input type="radio" name="vProb" value="all" /> '.&mt('all students').' </label><br />'."\n"
                    873:                   .&Apache::lonhtmlcommon::row_closure();
                    874:     $gradeTable .= &Apache::lonhtmlcommon::row_title(&mt('View Answer'))
                    875:                   .'<label><input type="radio" name="vAns" value="no"  /> '.&mt('no').' </label>'."\n"
                    876:                   .'<label><input type="radio" name="vAns" value="yes" /> '.&mt('one student').' </label>'."\n"
                    877:                   .'<label><input type="radio" name="vAns" value="all" checked="checked" /> '.&mt('all students').' </label><br />'."\n"
                    878:                   .&Apache::lonhtmlcommon::row_closure();
1.485     albertel  879: 
                    880:     my $submission_options;
1.442     banghart  881:     my $stu_status = join(':',&Apache::loncommon::get_env_multiple('form.Status'));
                    882:     my $saveStatus = $stu_status eq '' ? 'Active' : $stu_status;
1.257     albertel  883:     $env{'form.Status'} = $saveStatus;
1.485     albertel  884:     $submission_options.=
1.592     bisitz    885:         '<span class="LC_nobreak">'.
1.624     www       886:         '<label><input type="radio" name="lastSub" value="lastonly" /> '.
1.592     bisitz    887:         &mt('last submission only').' </label></span>'."\n".
                    888:         '<span class="LC_nobreak">'.
                    889:         '<label><input type="radio" name="lastSub" value="last" /> '.
                    890:         &mt('last submission &amp; parts info').' </label></span>'."\n".
                    891:         '<span class="LC_nobreak">'.
1.628     www       892:         '<label><input type="radio" name="lastSub" value="datesub" checked="checked" /> '.
1.592     bisitz    893:         &mt('by dates and submissions').'</label></span>'."\n".
                    894:         '<span class="LC_nobreak">'.
                    895:         '<label><input type="radio" name="lastSub" value="all" /> '.
                    896:         &mt('all details').'</label></span>';
1.561     bisitz    897:     $gradeTable .= &Apache::lonhtmlcommon::row_title(&mt('Submissions'))
                    898:                   .$submission_options
                    899:                   .&Apache::lonhtmlcommon::row_closure();
                    900: 
                    901:     $gradeTable .= &Apache::lonhtmlcommon::row_title(&mt('Grading Increments'))
                    902:                   .'<select name="increment">'
                    903:                   .'<option value="1">'.&mt('Whole Points').'</option>'
                    904:                   .'<option value=".5">'.&mt('Half Points').'</option>'
                    905:                   .'<option value=".25">'.&mt('Quarter Points').'</option>'
                    906:                   .'<option value=".1">'.&mt('Tenths of a Point').'</option>'
                    907:                   .'</select>'
                    908:                   .&Apache::lonhtmlcommon::row_closure();
1.485     albertel  909: 
                    910:     $gradeTable .= 
1.432     banghart  911:         &build_section_inputs().
1.45      ng        912: 	'<input type="hidden" name="submitonly"  value="'.$submitonly.'" />'."\n".
1.418     albertel  913: 	'<input type="hidden" name="symb" value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
1.110     ng        914: 	'<input type="hidden" name="saveStatusOld" value="'.$saveStatus.'" />'."\n";
                    915: 
1.618     www       916:     if (exists($env{'form.Status'})) {
1.561     bisitz    917: 	$gradeTable .= '<input type="hidden" name="Status" value="'.$stu_status.'" />'."\n";
1.124     ng        918:     } else {
1.561     bisitz    919:         $gradeTable .= &Apache::lonhtmlcommon::row_title(&mt('Student Status'))
                    920:                       .&Apache::lonhtmlcommon::StatusOptions(
                    921:                            $saveStatus,undef,1,'javascript:reLoadList(this.form);')
                    922:                       .&Apache::lonhtmlcommon::row_closure();
1.124     ng        923:     }
1.112     ng        924: 
1.561     bisitz    925:     $gradeTable .= &Apache::lonhtmlcommon::row_title(&mt('Check For Plagiarism'))
                    926:                   .'<input type="checkbox" name="checkPlag" checked="checked" />'
                    927:                   .&Apache::lonhtmlcommon::row_closure(1)
                    928:                   .&Apache::lonhtmlcommon::end_pick_box();
                    929: 
                    930:     $gradeTable .= '<p>'
1.618     www       931:                   .&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    932:                   .'<input type="hidden" name="command" value="processGroup" />'
                    933:                   .'</p>';
1.249     albertel  934: 
                    935: # checkall buttons
                    936:     $gradeTable.=&check_script('gradesub', 'stuinfo');
1.110     ng        937:     $gradeTable.='<input type="button" '."\n".
1.589     bisitz    938:         'onclick="javascript:checkSelect(this.form.stuinfo);" '."\n".
                    939:         'value="'.&mt('Next').' &rarr;" /> <br />'."\n";
1.249     albertel  940:     $gradeTable.=&check_buttons();
1.450     banghart  941:     my ($classlist, undef, $fullname) = &getclasslist($getsec,'1',$getgroup);
1.474     albertel  942:     $gradeTable.= &Apache::loncommon::start_data_table().
                    943: 	&Apache::loncommon::start_data_table_header_row();
1.110     ng        944:     my $loop = 0;
                    945:     while ($loop < 2) {
1.485     albertel  946: 	$gradeTable.='<th>'.&mt('No.').'</th><th>'.&mt('Select').'</th>'.
                    947: 	    '<th>'.&nameUserString('header').'&nbsp;'.&mt('Section/Group').'</th>';
1.618     www       948: 	if (($submitonly ne 'queued') && ($submitonly ne 'all')) {
1.485     albertel  949: 	    foreach my $part (sort(@$partlist)) {
                    950: 		my $display_part=
                    951: 		    &get_display_part((split(/_/,$part))[0],$symb);
                    952: 		$gradeTable.=
                    953: 		    '<th>'.&mt('Part: [_1] Status',$display_part).'</th>';
1.110     ng        954: 	    }
1.301     albertel  955: 	} elsif ($submitonly eq 'queued') {
1.474     albertel  956: 	    $gradeTable.='<th>'.&mt('Queue Status').'&nbsp;</th>';
1.110     ng        957: 	}
                    958: 	$loop++;
1.126     ng        959: #	$gradeTable.='<td></td>' if ($loop%2 ==1);
1.41      ng        960:     }
1.474     albertel  961:     $gradeTable.=&Apache::loncommon::end_data_table_header_row()."\n";
1.41      ng        962: 
1.45      ng        963:     my $ctr = 0;
1.294     albertel  964:     foreach my $student (sort 
                    965: 			 {
                    966: 			     if (lc($$fullname{$a}) ne lc($$fullname{$b})) {
                    967: 				 return (lc($$fullname{$a}) cmp lc($$fullname{$b}));
                    968: 			     }
                    969: 			     return $a cmp $b;
                    970: 			 }
                    971: 			 (keys(%$fullname))) {
1.41      ng        972: 	my ($uname,$udom) = split(/:/,$student);
1.301     albertel  973: 
1.110     ng        974: 	my %status = ();
1.301     albertel  975: 
                    976: 	if ($submitonly eq 'queued') {
                    977: 	    my %queue_status = 
                    978: 		&Apache::bridgetask::get_student_status($symb,$cdom,$cnum,
                    979: 							$udom,$uname);
                    980: 	    next if (!defined($queue_status{'gradingqueue'}));
                    981: 	    $status{'gradingqueue'} = $queue_status{'gradingqueue'};
                    982: 	}
                    983: 
1.618     www       984: 	if (($submitonly ne 'queued') && ($submitonly ne 'all')) {
1.324     albertel  985: 	    (%status) =&student_gradeStatus($symb,$udom,$uname,$partlist);
1.145     albertel  986: 	    my $submitted = 0;
1.164     albertel  987: 	    my $graded = 0;
1.248     albertel  988: 	    my $incorrect = 0;
1.110     ng        989: 	    foreach (keys(%status)) {
1.145     albertel  990: 		$submitted = 1 if ($status{$_} ne 'nothing');
1.248     albertel  991: 		$graded = 1 if ($status{$_} =~ /^ungraded/);
                    992: 		$incorrect = 1 if ($status{$_} =~ /^incorrect/);
                    993: 		
1.110     ng        994: 		my ($foo,$partid,$foo1) = split(/\./,$_);
                    995: 		if ($status{'resource.'.$partid.'.submitted_by'} ne '') {
1.145     albertel  996: 		    $submitted = 0;
1.150     albertel  997: 		    my ($part)=split(/\./,$partid);
1.110     ng        998: 		    $gradeTable.='<input type="hidden" name="'.
1.150     albertel  999: 			$student.':'.$part.':submitted_by" value="'.
1.110     ng       1000: 			$status{'resource.'.$partid.'.submitted_by'}.'" />';
                   1001: 		}
1.41      ng       1002: 	    }
1.248     albertel 1003: 	    
1.156     albertel 1004: 	    next if (!$submitted && ($submitonly eq 'yes' ||
                   1005: 				     $submitonly eq 'incorrect' ||
                   1006: 				     $submitonly eq 'graded'));
1.248     albertel 1007: 	    next if (!$graded && ($submitonly eq 'graded'));
                   1008: 	    next if (!$incorrect && $submitonly eq 'incorrect');
1.41      ng       1009: 	}
1.34      ng       1010: 
1.45      ng       1011: 	$ctr++;
1.249     albertel 1012: 	my $section = $classlist->{$student}->[&Apache::loncoursedata::CL_SECTION()];
1.452     banghart 1013:         my $group = $classlist->{$student}->[&Apache::loncoursedata::CL_GROUP()];
1.104     albertel 1014: 	if ( $perm{'vgr'} eq 'F' ) {
1.474     albertel 1015: 	    if ($ctr%2 ==1) {
                   1016: 		$gradeTable.= &Apache::loncommon::start_data_table_row();
                   1017: 	    }
1.126     ng       1018: 	    $gradeTable.='<td align="right">'.$ctr.'&nbsp;</td>'.
1.563     bisitz   1019:                '<td align="center"><label><input type="checkbox" name="stuinfo" value="'.
1.249     albertel 1020:                $student.':'.$$fullname{$student}.':::SECTION'.$section.
                   1021: 	       ')&nbsp;" />&nbsp;&nbsp;</label></td>'."\n".'<td>'.
                   1022: 	       &nameUserString(undef,$$fullname{$student},$uname,$udom).
1.474     albertel 1023: 	       '&nbsp;'.$section.($group ne '' ?'/'.$group:'').'</td>'."\n";
1.110     ng       1024: 
1.618     www      1025: 	    if ($submitonly ne 'all') {
1.524     raeburn  1026: 		foreach (sort(keys(%status))) {
1.485     albertel 1027: 		    next if ($_ =~ /^resource.*?submitted_by$/);
                   1028: 		    $gradeTable.='<td align="center">&nbsp;'.&mt($status{$_}).'&nbsp;</td>'."\n";
1.110     ng       1029: 		}
1.41      ng       1030: 	    }
1.126     ng       1031: #	    $gradeTable.='<td></td>' if ($ctr%2 ==1);
1.474     albertel 1032: 	    if ($ctr%2 ==0) {
                   1033: 		$gradeTable.=&Apache::loncommon::end_data_table_row()."\n";
                   1034: 	    }
1.41      ng       1035: 	}
                   1036:     }
1.110     ng       1037:     if ($ctr%2 ==1) {
1.126     ng       1038: 	$gradeTable.='<td>&nbsp;</td><td>&nbsp;</td><td>&nbsp;</td>';
1.618     www      1039: 	    if (($submitonly ne 'queued') && ($submitonly ne 'all')) {
1.110     ng       1040: 		foreach (@$partlist) {
                   1041: 		    $gradeTable.='<td>&nbsp;</td>';
                   1042: 		}
1.301     albertel 1043: 	    } elsif ($submitonly eq 'queued') {
                   1044: 		$gradeTable.='<td>&nbsp;</td>';
1.110     ng       1045: 	    }
1.474     albertel 1046: 	$gradeTable.=&Apache::loncommon::end_data_table_row();
1.110     ng       1047:     }
                   1048: 
1.474     albertel 1049:     $gradeTable.=&Apache::loncommon::end_data_table()."\n".
1.589     bisitz   1050:         '<input type="button" '.
                   1051:         'onclick="javascript:checkSelect(this.form.stuinfo);" '.
                   1052:         'value="'.&mt('Next').' &rarr;" /></form>'."\n";
1.45      ng       1053:     if ($ctr == 0) {
1.96      albertel 1054: 	my $num_students=(scalar(keys(%$fullname)));
                   1055: 	if ($num_students eq 0) {
1.485     albertel 1056: 	    $gradeTable='<br />&nbsp;<span class="LC_warning">'.&mt('There are no students currently enrolled.').'</span>';
1.96      albertel 1057: 	} else {
1.171     albertel 1058: 	    my $submissions='submissions';
                   1059: 	    if ($submitonly eq 'incorrect') { $submissions = 'incorrect submissions'; }
                   1060: 	    if ($submitonly eq 'graded'   ) { $submissions = 'ungraded submissions'; }
1.301     albertel 1061: 	    if ($submitonly eq 'queued'   ) { $submissions = 'queued submissions'; }
1.398     albertel 1062: 	    $gradeTable='<br />&nbsp;<span class="LC_warning">'.
1.485     albertel 1063: 		&mt('No '.$submissions.' found for this resource for any students. ([_1] students checked for '.$submissions.')',
                   1064: 		    $num_students).
                   1065: 		'</span><br />';
1.96      albertel 1066: 	}
1.46      ng       1067:     } elsif ($ctr == 1) {
1.474     albertel 1068: 	$gradeTable =~ s/type="checkbox"/type="checkbox" checked="checked"/;
1.45      ng       1069:     }
                   1070:     $request->print($gradeTable);
1.44      ng       1071:     return '';
1.10      ng       1072: }
                   1073: 
1.44      ng       1074: #---- Called from the listStudents routine
1.249     albertel 1075: 
                   1076: sub check_script {
                   1077:     my ($form, $type)=@_;
1.597     wenzelju 1078:     my $chkallscript= &Apache::lonhtmlcommon::scripttag('
1.249     albertel 1079:     function checkall() {
                   1080:         for (i=0; i<document.forms.'.$form.'.elements.length; i++) {
                   1081:             ele = document.forms.'.$form.'.elements[i];
                   1082:             if (ele.name == "'.$type.'") {
                   1083:             document.forms.'.$form.'.elements[i].checked=true;
                   1084:                                        }
                   1085:         }
                   1086:     }
                   1087: 
                   1088:     function checksec() {
                   1089:         for (i=0; i<document.forms.'.$form.'.elements.length; i++) {
                   1090:             ele = document.forms.'.$form.'.elements[i];
                   1091:            string = document.forms.'.$form.'.chksec.value;
                   1092:            if
                   1093:           (ele.value.indexOf(":::SECTION"+string)>0) {
                   1094:               document.forms.'.$form.'.elements[i].checked=true;
                   1095:             }
                   1096:         }
                   1097:     }
                   1098: 
                   1099: 
                   1100:     function uncheckall() {
                   1101:         for (i=0; i<document.forms.'.$form.'.elements.length; i++) {
                   1102:             ele = document.forms.'.$form.'.elements[i];
                   1103:             if (ele.name == "'.$type.'") {
                   1104:             document.forms.'.$form.'.elements[i].checked=false;
                   1105:                                        }
                   1106:         }
                   1107:     }
                   1108: 
1.597     wenzelju 1109: '."\n");
1.249     albertel 1110:     return $chkallscript;
                   1111: }
                   1112: 
                   1113: sub check_buttons {
1.485     albertel 1114:     my $buttons.='<input type="button" onclick="checkall()" value="'.&mt('Check All').'" />';
                   1115:     $buttons.='<input type="button" onclick="uncheckall()" value="'.&mt('Uncheck All').'" />&nbsp;';
                   1116:     $buttons.='<input type="button" onclick="checksec()" value="'.&mt('Check Section/Group').'" />';
1.249     albertel 1117:     $buttons.='<input type="text" size="5" name="chksec" />&nbsp;';
                   1118:     return $buttons;
                   1119: }
                   1120: 
1.44      ng       1121: #     Displays the submissions for one student or a group of students
1.34      ng       1122: sub processGroup {
1.619     www      1123:     my ($request,$symb)  = @_;
1.41      ng       1124:     my $ctr        = 0;
1.155     albertel 1125:     my @stuchecked = &Apache::loncommon::get_env_multiple('form.stuinfo');
1.41      ng       1126:     my $total      = scalar(@stuchecked)-1;
1.45      ng       1127: 
1.396     banghart 1128:     foreach my $student (@stuchecked) {
                   1129: 	my ($uname,$udom,$fullname) = split(/:/,$student);
1.257     albertel 1130: 	$env{'form.student'}        = $uname;
                   1131: 	$env{'form.userdom'}        = $udom;
                   1132: 	$env{'form.fullname'}       = $fullname;
1.619     www      1133: 	&submission($request,$ctr,$total,$symb);
1.41      ng       1134: 	$ctr++;
                   1135:     }
                   1136:     return '';
1.35      ng       1137: }
1.34      ng       1138: 
1.44      ng       1139: #------------------------------------------------------------------------------------
                   1140: #
                   1141: #-------------------------- Next few routines handles grading by student, essentially
                   1142: #                           handles essay response type problem/part
                   1143: #
                   1144: #--- Javascript to handle the submission page functionality ---
                   1145: sub sub_page_js {
                   1146:     my $request = shift;
1.539     riegler  1147: 	    my $alertmsg = &mt('A number equal or greater than 0 is expected. Entered value = ');
1.597     wenzelju 1148:     $request->print(&Apache::lonhtmlcommon::scripttag(<<SUBJAVASCRIPT));
1.71      ng       1149:     function updateRadio(formname,id,weight) {
1.125     ng       1150: 	var gradeBox = formname["GD_BOX"+id];
                   1151: 	var radioButton = formname["RADVAL"+id];
                   1152: 	var oldpts = formname["oldpts"+id].value;
1.72      ng       1153: 	var pts = checkSolved(formname,id) == 'update' ? gradeBox.value : oldpts;
1.71      ng       1154: 	gradeBox.value = pts;
                   1155: 	var resetbox = false;
                   1156: 	if (isNaN(pts) || pts < 0) {
1.539     riegler  1157: 	    alert("$alertmsg"+pts);
1.71      ng       1158: 	    for (var i=0; i<radioButton.length; i++) {
                   1159: 		if (radioButton[i].checked) {
                   1160: 		    gradeBox.value = i;
                   1161: 		    resetbox = true;
                   1162: 		}
                   1163: 	    }
                   1164: 	    if (!resetbox) {
                   1165: 		formtextbox.value = "";
                   1166: 	    }
                   1167: 	    return;
1.44      ng       1168: 	}
1.71      ng       1169: 
                   1170: 	if (pts > weight) {
                   1171: 	    var resp = confirm("You entered a value ("+pts+
                   1172: 			       ") greater than the weight for the part. Accept?");
                   1173: 	    if (resp == false) {
1.125     ng       1174: 		gradeBox.value = oldpts;
1.71      ng       1175: 		return;
                   1176: 	    }
1.44      ng       1177: 	}
1.13      albertel 1178: 
1.71      ng       1179: 	for (var i=0; i<radioButton.length; i++) {
                   1180: 	    radioButton[i].checked=false;
                   1181: 	    if (pts == i && pts != "") {
                   1182: 		radioButton[i].checked=true;
                   1183: 	    }
                   1184: 	}
                   1185: 	updateSelect(formname,id);
1.125     ng       1186: 	formname["stores"+id].value = "0";
1.41      ng       1187:     }
1.5       albertel 1188: 
1.72      ng       1189:     function writeBox(formname,id,pts) {
1.125     ng       1190: 	var gradeBox = formname["GD_BOX"+id];
1.71      ng       1191: 	if (checkSolved(formname,id) == 'update') {
                   1192: 	    gradeBox.value = pts;
                   1193: 	} else {
1.125     ng       1194: 	    var oldpts = formname["oldpts"+id].value;
1.72      ng       1195: 	    gradeBox.value = oldpts;
1.125     ng       1196: 	    var radioButton = formname["RADVAL"+id];
1.71      ng       1197: 	    for (var i=0; i<radioButton.length; i++) {
                   1198: 		radioButton[i].checked=false;
1.72      ng       1199: 		if (i == oldpts) {
1.71      ng       1200: 		    radioButton[i].checked=true;
                   1201: 		}
                   1202: 	    }
1.41      ng       1203: 	}
1.125     ng       1204: 	formname["stores"+id].value = "0";
1.71      ng       1205: 	updateSelect(formname,id);
                   1206: 	return;
1.41      ng       1207:     }
1.44      ng       1208: 
1.71      ng       1209:     function clearRadBox(formname,id) {
                   1210: 	if (checkSolved(formname,id) == 'noupdate') {
                   1211: 	    updateSelect(formname,id);
                   1212: 	    return;
                   1213: 	}
1.125     ng       1214: 	gradeSelect = formname["GD_SEL"+id];
1.71      ng       1215: 	for (var i=0; i<gradeSelect.length; i++) {
                   1216: 	    if (gradeSelect[i].selected) {
                   1217: 		var selectx=i;
                   1218: 	    }
                   1219: 	}
1.125     ng       1220: 	var stores = formname["stores"+id];
1.71      ng       1221: 	if (selectx == stores.value) { return };
1.125     ng       1222: 	var gradeBox = formname["GD_BOX"+id];
1.71      ng       1223: 	gradeBox.value = "";
1.125     ng       1224: 	var radioButton = formname["RADVAL"+id];
1.71      ng       1225: 	for (var i=0; i<radioButton.length; i++) {
                   1226: 	    radioButton[i].checked=false;
                   1227: 	}
                   1228: 	stores.value = selectx;
                   1229:     }
1.5       albertel 1230: 
1.71      ng       1231:     function checkSolved(formname,id) {
1.125     ng       1232: 	if (formname["solved"+id].value == "correct_by_student" && formname.overRideScore.value == 'no') {
1.118     ng       1233: 	    var reply = confirm("This problem has been graded correct by the computer. Do you want to change the score?");
                   1234: 	    if (!reply) {return "noupdate";}
1.120     ng       1235: 	    formname.overRideScore.value = 'yes';
1.41      ng       1236: 	}
1.71      ng       1237: 	return "update";
1.13      albertel 1238:     }
1.71      ng       1239: 
                   1240:     function updateSelect(formname,id) {
1.125     ng       1241: 	formname["GD_SEL"+id][0].selected = true;
1.71      ng       1242: 	return;
1.41      ng       1243:     }
1.33      ng       1244: 
1.121     ng       1245: //=========== Check that a point is assigned for all the parts  ============
1.71      ng       1246:     function checksubmit(formname,val,total,parttot) {
1.121     ng       1247: 	formname.gradeOpt.value = val;
1.71      ng       1248: 	if (val == "Save & Next") {
                   1249: 	    for (i=0;i<=total;i++) {
                   1250: 		for (j=0;j<parttot;j++) {
1.125     ng       1251: 		    var partid = formname["partid"+i+"_"+j].value;
1.127     ng       1252: 		    if (formname["GD_SEL"+i+"_"+partid][0].selected) {
1.125     ng       1253: 			var points = formname["GD_BOX"+i+"_"+partid].value;
1.71      ng       1254: 			if (points == "") {
1.125     ng       1255: 			    var name = formname["name"+i].value;
1.129     ng       1256: 			    var studentID = (name != '' ? name : formname["unamedom"+i].value);
                   1257: 			    var resp = confirm("You did not assign a score for "+studentID+
                   1258: 					       ", part "+partid+". Continue?");
1.71      ng       1259: 			    if (resp == false) {
1.125     ng       1260: 				formname["GD_BOX"+i+"_"+partid].focus();
1.71      ng       1261: 				return false;
                   1262: 			    }
                   1263: 			}
                   1264: 		    }
                   1265: 		    
                   1266: 		}
                   1267: 	    }
                   1268: 	    
                   1269: 	}
1.121     ng       1270: 	if (val == "Grade Student") {
                   1271: 	    if (formname.Status.value == "") {
                   1272: 		formname.Status.value = "Active";
                   1273: 	    }
                   1274: 	    formname.studentNo.value = total;
                   1275: 	}
1.120     ng       1276: 	formname.submit();
                   1277:     }
                   1278: 
1.71      ng       1279: //======= Check that a score is assigned for all the problems (page/sequence grading only) =========
                   1280:     function checkSubmitPage(formname,total) {
                   1281: 	noscore = new Array(100);
                   1282: 	var ptr = 0;
                   1283: 	for (i=1;i<total;i++) {
1.125     ng       1284: 	    var partid = formname["q_"+i].value;
1.127     ng       1285: 	    if (formname["GD_SEL"+i+"_"+partid][0].selected) {
1.125     ng       1286: 		var points = formname["GD_BOX"+i+"_"+partid].value;
                   1287: 		var status = formname["solved"+i+"_"+partid].value;
1.71      ng       1288: 		if (points == "" && status != "correct_by_student") {
                   1289: 		    noscore[ptr] = i;
                   1290: 		    ptr++;
                   1291: 		}
                   1292: 	    }
                   1293: 	}
                   1294: 	if (ptr != 0) {
                   1295: 	    var sense = ptr == 1 ? ": " : "s: ";
                   1296: 	    var prolist = "";
                   1297: 	    if (ptr == 1) {
                   1298: 		prolist = noscore[0];
                   1299: 	    } else {
                   1300: 		var i = 0;
                   1301: 		while (i < ptr-1) {
                   1302: 		    prolist += noscore[i]+", ";
                   1303: 		    i++;
                   1304: 		}
                   1305: 		prolist += "and "+noscore[i];
                   1306: 	    }
                   1307: 	    var resp = confirm("You did not assign any score for the following problem"+sense+prolist+". Continue?");
                   1308: 	    if (resp == false) {
                   1309: 		return false;
                   1310: 	    }
                   1311: 	}
1.45      ng       1312: 
1.71      ng       1313: 	formname.submit();
                   1314:     }
                   1315: SUBJAVASCRIPT
                   1316: }
1.45      ng       1317: 
1.71      ng       1318: #--- javascript for essay type problem --
                   1319: sub sub_page_kw_js {
                   1320:     my $request = shift;
1.80      ng       1321:     my $iconpath = $request->dir_config('lonIconsURL');
1.118     ng       1322:     &commonJSfunctions($request);
1.350     albertel 1323: 
1.629     www      1324:     my $inner_js_msg_central= (<<INNERJS);
                   1325: <script type="text/javascript">
1.350     albertel 1326:     function checkInput() {
                   1327:       opener.document.SCORE.msgsub.value = opener.checkEntities(document.msgcenter.msgsub.value);
                   1328:       var nmsg   = opener.document.SCORE.savemsgN.value;
                   1329:       var usrctr = document.msgcenter.usrctr.value;
                   1330:       var newval = opener.document.SCORE["newmsg"+usrctr];
                   1331:       newval.value = opener.checkEntities(document.msgcenter.newmsg.value);
                   1332: 
                   1333:       var msgchk = "";
                   1334:       if (document.msgcenter.subchk.checked) {
                   1335:          msgchk = "msgsub,";
                   1336:       }
                   1337:       var includemsg = 0;
                   1338:       for (var i=1; i<=nmsg; i++) {
                   1339:           var opnmsg = opener.document.SCORE["savemsg"+i];
                   1340:           var frmmsg = document.msgcenter["msg"+i];
                   1341:           opnmsg.value = opener.checkEntities(frmmsg.value);
                   1342:           var showflg = opener.document.SCORE["shownOnce"+i];
                   1343:           showflg.value = "1";
                   1344:           var chkbox = document.msgcenter["msgn"+i];
                   1345:           if (chkbox.checked) {
                   1346:              msgchk += "savemsg"+i+",";
                   1347:              includemsg = 1;
                   1348:           }
                   1349:       }
                   1350:       if (document.msgcenter.newmsgchk.checked) {
                   1351:          msgchk += "newmsg"+usrctr;
                   1352:          includemsg = 1;
                   1353:       }
                   1354:       imgformname = opener.document.SCORE["mailicon"+usrctr];
                   1355:       imgformname.src = "$iconpath/"+((includemsg) ? "mailto.gif" : "mailbkgrd.gif");
                   1356:       var includemsg = opener.document.SCORE["includemsg"+usrctr];
                   1357:       includemsg.value = msgchk;
                   1358: 
                   1359:       self.close()
                   1360: 
                   1361:     }
1.629     www      1362: </script>
1.350     albertel 1363: INNERJS
                   1364: 
1.629     www      1365:     my $inner_js_highlight_central= (<<INNERJS);
                   1366: <script type="text/javascript">
1.351     albertel 1367:     function updateChoice(flag) {
                   1368:       opener.document.SCORE.kwclr.value = opener.radioSelection(document.hlCenter.kwdclr);
                   1369:       opener.document.SCORE.kwsize.value = opener.radioSelection(document.hlCenter.kwdsize);
                   1370:       opener.document.SCORE.kwstyle.value = opener.radioSelection(document.hlCenter.kwdstyle);
                   1371:       opener.document.SCORE.refresh.value = "on";
                   1372:       if (opener.document.SCORE.keywords.value!=""){
                   1373:          opener.document.SCORE.submit();
                   1374:       }
                   1375:       self.close()
                   1376:     }
1.629     www      1377: </script>
1.351     albertel 1378: INNERJS
                   1379: 
                   1380:     my $start_page_msg_central = 
                   1381:         &Apache::loncommon::start_page('Message Central',$inner_js_msg_central,
                   1382: 				       {'js_ready'  => 1,
                   1383: 					'only_body' => 1,
                   1384: 					'bgcolor'   =>'#FFFFFF',});
                   1385:     my $end_page_msg_central = 
                   1386: 	&Apache::loncommon::end_page({'js_ready' => 1});
                   1387: 
                   1388: 
                   1389:     my $start_page_highlight_central = 
                   1390:         &Apache::loncommon::start_page('Highlight Central',
                   1391: 				       $inner_js_highlight_central,
1.350     albertel 1392: 				       {'js_ready'  => 1,
                   1393: 					'only_body' => 1,
                   1394: 					'bgcolor'   =>'#FFFFFF',});
1.351     albertel 1395:     my $end_page_highlight_central = 
1.350     albertel 1396: 	&Apache::loncommon::end_page({'js_ready' => 1});
                   1397: 
1.219     www      1398:     my $docopen=&Apache::lonhtmlcommon::javascript_docopen();
1.236     albertel 1399:     $docopen=~s/^document\.//;
1.539     riegler  1400:     my $alertmsg = &mt('Please select a word or group of words from document and then click this link.');
1.597     wenzelju 1401:     $request->print(&Apache::lonhtmlcommon::scripttag(<<SUBJAVASCRIPT));
1.45      ng       1402: 
1.44      ng       1403: //===================== Show list of keywords ====================
1.122     ng       1404:   function keywords(formname) {
                   1405:     var nret = prompt("Keywords list, separated by a space. Add/delete to list if desired.",formname.keywords.value);
1.44      ng       1406:     if (nret==null) return;
1.122     ng       1407:     formname.keywords.value = nret;
1.44      ng       1408: 
1.122     ng       1409:     if (formname.keywords.value != "") {
1.128     ng       1410: 	formname.refresh.value = "on";
1.122     ng       1411: 	formname.submit();
1.44      ng       1412:     }
                   1413:     return;
                   1414:   }
                   1415: 
                   1416: //===================== Script to view submitted by ==================
                   1417:   function viewSubmitter(submitter) {
                   1418:     document.SCORE.refresh.value = "on";
                   1419:     document.SCORE.NCT.value = "1";
                   1420:     document.SCORE.unamedom0.value = submitter;
                   1421:     document.SCORE.submit();
                   1422:     return;
                   1423:   }
                   1424: 
                   1425: //===================== Script to add keyword(s) ==================
                   1426:   function getSel() {
                   1427:     if (document.getSelection) txt = document.getSelection();
                   1428:     else if (document.selection) txt = document.selection.createRange().text;
                   1429:     else return;
                   1430:     var cleantxt = txt.replace(new RegExp('([\\f\\n\\r\\t\\v ])+', 'g')," ");
                   1431:     if (cleantxt=="") {
1.539     riegler  1432: 	alert("$alertmsg");
1.44      ng       1433: 	return;
                   1434:     }
                   1435:     var nret = prompt("Add selection to keyword list? Edit if desired.",cleantxt);
                   1436:     if (nret==null) return;
1.127     ng       1437:     document.SCORE.keywords.value = document.SCORE.keywords.value+" "+nret;
1.44      ng       1438:     if (document.SCORE.keywords.value != "") {
1.127     ng       1439: 	document.SCORE.refresh.value = "on";
1.44      ng       1440: 	document.SCORE.submit();
                   1441:     }
                   1442:     return;
                   1443:   }
                   1444: 
                   1445: //====================== Script for composing message ==============
1.80      ng       1446:    // preload images
                   1447:    img1 = new Image();
                   1448:    img1.src = "$iconpath/mailbkgrd.gif";
                   1449:    img2 = new Image();
                   1450:    img2.src = "$iconpath/mailto.gif";
                   1451: 
1.44      ng       1452:   function msgCenter(msgform,usrctr,fullname) {
                   1453:     var Nmsg  = msgform.savemsgN.value;
                   1454:     savedMsgHeader(Nmsg,usrctr,fullname);
                   1455:     var subject = msgform.msgsub.value;
1.127     ng       1456:     var msgchk = document.SCORE["includemsg"+usrctr].value;
1.44      ng       1457:     re = /msgsub/;
                   1458:     var shwsel = "";
                   1459:     if (re.test(msgchk)) { shwsel = "checked" }
1.123     ng       1460:     subject = (document.SCORE.shownSub.value == 0 ? checkEntities(subject) : subject);
                   1461:     displaySubject(checkEntities(subject),shwsel);
1.44      ng       1462:     for (var i=1; i<=Nmsg; i++) {
1.123     ng       1463: 	var testmsg = "savemsg"+i+",";
                   1464: 	re = new RegExp(testmsg,"g");
1.44      ng       1465: 	shwsel = "";
                   1466: 	if (re.test(msgchk)) { shwsel = "checked" }
1.125     ng       1467: 	var message = document.SCORE["savemsg"+i].value;
1.126     ng       1468: 	message = (document.SCORE["shownOnce"+i].value == 0 ? checkEntities(message) : message);
1.123     ng       1469: 	displaySavedMsg(i,message,shwsel); //I do not get it. w/o checkEntities on saved messages,
                   1470: 	                                   //any &lt; is already converted to <, etc. However, only once!!
1.44      ng       1471:     }
1.125     ng       1472:     newmsg = document.SCORE["newmsg"+usrctr].value;
1.44      ng       1473:     shwsel = "";
                   1474:     re = /newmsg/;
                   1475:     if (re.test(msgchk)) { shwsel = "checked" }
                   1476:     newMsg(newmsg,shwsel);
                   1477:     msgTail(); 
                   1478:     return;
                   1479:   }
                   1480: 
1.123     ng       1481:   function checkEntities(strx) {
                   1482:     if (strx.length == 0) return strx;
                   1483:     var orgStr = ["&", "<", ">", '"']; 
                   1484:     var newStr = ["&amp;", "&lt;", "&gt;", "&quot;"];
                   1485:     var counter = 0;
                   1486:     while (counter < 4) {
                   1487: 	strx = strReplace(strx,orgStr[counter],newStr[counter]);
                   1488: 	counter++;
                   1489:     }
                   1490:     return strx;
                   1491:   }
                   1492: 
                   1493:   function strReplace(strx, orgStr, newStr) {
                   1494:     return strx.split(orgStr).join(newStr);
                   1495:   }
                   1496: 
1.44      ng       1497:   function savedMsgHeader(Nmsg,usrctr,fullname) {
1.76      ng       1498:     var height = 70*Nmsg+250;
1.44      ng       1499:     var scrollbar = "no";
                   1500:     if (height > 600) {
                   1501: 	height = 600;
                   1502: 	scrollbar = "yes";
                   1503:     }
1.118     ng       1504:     var xpos = (screen.width-600)/2;
                   1505:     xpos = (xpos < 0) ? '0' : xpos;
                   1506:     var ypos = (screen.height-height)/2-30;
                   1507:     ypos = (ypos < 0) ? '0' : ypos;
                   1508: 
1.206     albertel 1509:     pWin = window.open('', 'MessageCenter', 'resizable=yes,toolbar=no,location=no,scrollbars='+scrollbar+',screenx='+xpos+',screeny='+ypos+',width=600,height='+height);
1.76      ng       1510:     pWin.focus();
                   1511:     pDoc = pWin.document;
1.219     www      1512:     pDoc.$docopen;
1.351     albertel 1513:     pDoc.write('$start_page_msg_central');
1.76      ng       1514: 
                   1515:     pDoc.write("<form action=\\"inactive\\" name=\\"msgcenter\\">");
                   1516:     pDoc.write("<input value=\\""+usrctr+"\\" name=\\"usrctr\\" type=\\"hidden\\">");
1.465     albertel 1517:     pDoc.write("<h3><span class=\\"LC_info\\">&nbsp;Compose Message for \"+fullname+\"<\\/span><\\/h3><br /><br />");
1.76      ng       1518: 
1.564     bisitz   1519:     pDoc.write('<table border="0" width="100%"><tr><td bgcolor="#777777">');
                   1520:     pDoc.write('<table border="0" width="100%"><tr bgcolor="#DDFFFF">');
1.465     albertel 1521:     pDoc.write("<td><b>Type<\\/b><\\/td><td><b>Include<\\/b><\\/td><td><b>Message<\\/td><\\/tr>");
1.44      ng       1522: }
                   1523:     function displaySubject(msg,shwsel) {
1.76      ng       1524:     pDoc = pWin.document;
                   1525:     pDoc.write("<tr bgcolor=\\"#ffffdd\\">");
1.465     albertel 1526:     pDoc.write("<td>Subject<\\/td>");
                   1527:     pDoc.write("<td align=\\"center\\"><input name=\\"subchk\\" type=\\"checkbox\\"" +shwsel+"><\\/td>");
                   1528:     pDoc.write("<td><input name=\\"msgsub\\" type=\\"text\\" value=\\""+msg+"\\"size=\\"60\\" maxlength=\\"80\\"><\\/td><\\/tr>");
1.44      ng       1529: }
                   1530: 
1.72      ng       1531:   function displaySavedMsg(ctr,msg,shwsel) {
1.76      ng       1532:     pDoc = pWin.document;
                   1533:     pDoc.write("<tr bgcolor=\\"#ffffdd\\">");
1.465     albertel 1534:     pDoc.write("<td align=\\"center\\">"+ctr+"<\\/td>");
                   1535:     pDoc.write("<td align=\\"center\\"><input name=\\"msgn"+ctr+"\\" type=\\"checkbox\\"" +shwsel+"><\\/td>");
                   1536:     pDoc.write("<td><textarea name=\\"msg"+ctr+"\\" cols=\\"60\\" rows=\\"3\\">"+msg+"<\\/textarea><\\/td><\\/tr>");
1.44      ng       1537: }
                   1538: 
                   1539:   function newMsg(newmsg,shwsel) {
1.76      ng       1540:     pDoc = pWin.document;
                   1541:     pDoc.write("<tr bgcolor=\\"#ffffdd\\">");
1.465     albertel 1542:     pDoc.write("<td align=\\"center\\">New<\\/td>");
                   1543:     pDoc.write("<td align=\\"center\\"><input name=\\"newmsgchk\\" type=\\"checkbox\\"" +shwsel+"><\\/td>");
                   1544:     pDoc.write("<td><textarea name=\\"newmsg\\" cols=\\"60\\" rows=\\"3\\" onchange=\\"javascript:this.form.newmsgchk.checked=true\\" >"+newmsg+"<\\/textarea><\\/td><\\/tr>");
1.44      ng       1545: }
                   1546: 
                   1547:   function msgTail() {
1.76      ng       1548:     pDoc = pWin.document;
1.465     albertel 1549:     pDoc.write("<\\/table>");
                   1550:     pDoc.write("<\\/td><\\/tr><\\/table>&nbsp;");
1.589     bisitz   1551:     pDoc.write("<input type=\\"button\\" value=\\"Save\\" onclick=\\"javascript:checkInput()\\">&nbsp;&nbsp;");
                   1552:     pDoc.write("<input type=\\"button\\" value=\\"Cancel\\" onclick=\\"self.close()\\"><br /><br />");
1.465     albertel 1553:     pDoc.write("<\\/form>");
1.351     albertel 1554:     pDoc.write('$end_page_msg_central');
1.128     ng       1555:     pDoc.close();
1.44      ng       1556: }
                   1557: 
                   1558: //====================== Script for keyword highlight options ==============
                   1559:   function kwhighlight() {
                   1560:     var kwclr    = document.SCORE.kwclr.value;
                   1561:     var kwsize   = document.SCORE.kwsize.value;
                   1562:     var kwstyle  = document.SCORE.kwstyle.value;
                   1563:     var redsel = "";
                   1564:     var grnsel = "";
                   1565:     var blusel = "";
                   1566:     if (kwclr=="red")   {var redsel="checked"};
                   1567:     if (kwclr=="green") {var grnsel="checked"};
                   1568:     if (kwclr=="blue")  {var blusel="checked"};
                   1569:     var sznsel = "";
                   1570:     var sz1sel = "";
                   1571:     var sz2sel = "";
                   1572:     if (kwsize=="0")  {var sznsel="checked"};
                   1573:     if (kwsize=="+1") {var sz1sel="checked"};
                   1574:     if (kwsize=="+2") {var sz2sel="checked"};
                   1575:     var synsel = "";
                   1576:     var syisel = "";
                   1577:     var sybsel = "";
                   1578:     if (kwstyle=="")    {var synsel="checked"};
                   1579:     if (kwstyle=="<i>") {var syisel="checked"};
                   1580:     if (kwstyle=="<b>") {var sybsel="checked"};
                   1581:     highlightCentral();
                   1582:     highlightbody('red','red',redsel,'0','normal',sznsel,'','normal',synsel);
                   1583:     highlightbody('green','green',grnsel,'+1','+1',sz1sel,'<i>','italic',syisel);
                   1584:     highlightbody('blue','blue',blusel,'+2','+2',sz2sel,'<b>','bold',sybsel);
                   1585:     highlightend();
                   1586:     return;
                   1587:   }
                   1588: 
                   1589:   function highlightCentral() {
1.76      ng       1590: //    if (window.hwdWin) window.hwdWin.close();
1.118     ng       1591:     var xpos = (screen.width-400)/2;
                   1592:     xpos = (xpos < 0) ? '0' : xpos;
                   1593:     var ypos = (screen.height-330)/2-30;
                   1594:     ypos = (ypos < 0) ? '0' : ypos;
                   1595: 
1.206     albertel 1596:     hwdWin = window.open('', 'KeywordHighlightCentral', 'resizeable=yes,toolbar=no,location=no,scrollbars=no,width=400,height=300,screenx='+xpos+',screeny='+ypos);
1.76      ng       1597:     hwdWin.focus();
                   1598:     var hDoc = hwdWin.document;
1.219     www      1599:     hDoc.$docopen;
1.351     albertel 1600:     hDoc.write('$start_page_highlight_central');
1.76      ng       1601:     hDoc.write("<form action=\\"inactive\\" name=\\"hlCenter\\">");
1.465     albertel 1602:     hDoc.write("<h3><span class=\\"LC_info\\">&nbsp;Keyword Highlight Options<\\/span><\\/h3><br /><br />");
1.76      ng       1603: 
1.564     bisitz   1604:     hDoc.write('<table border="0" width="100%"><tr><td bgcolor="#777777">');
                   1605:     hDoc.write('<table border="0" width="100%"><tr bgcolor="#DDFFFF">');
1.465     albertel 1606:     hDoc.write("<td><b>Text Color<\\/b><\\/td><td><b>Font Size<\\/b><\\/td><td><b>Font Style<\\/td><\\/tr>");
1.44      ng       1607:   }
                   1608: 
                   1609:   function highlightbody(clrval,clrtxt,clrsel,szval,sztxt,szsel,syval,sytxt,sysel) { 
1.76      ng       1610:     var hDoc = hwdWin.document;
                   1611:     hDoc.write("<tr bgcolor=\\"#ffffdd\\">");
                   1612:     hDoc.write("<td align=\\"left\\">");
1.465     albertel 1613:     hDoc.write("<input name=\\"kwdclr\\" type=\\"radio\\" value=\\""+clrval+"\\" "+clrsel+">&nbsp;"+clrtxt+"<\\/td>");
1.76      ng       1614:     hDoc.write("<td align=\\"left\\">");
1.465     albertel 1615:     hDoc.write("<input name=\\"kwdsize\\" type=\\"radio\\" value=\\""+szval+"\\" "+szsel+">&nbsp;"+sztxt+"<\\/td>");
1.76      ng       1616:     hDoc.write("<td align=\\"left\\">");
1.465     albertel 1617:     hDoc.write("<input name=\\"kwdstyle\\" type=\\"radio\\" value=\\""+syval+"\\" "+sysel+">&nbsp;"+sytxt+"<\\/td>");
                   1618:     hDoc.write("<\\/tr>");
1.44      ng       1619:   }
                   1620: 
                   1621:   function highlightend() { 
1.76      ng       1622:     var hDoc = hwdWin.document;
1.465     albertel 1623:     hDoc.write("<\\/table>");
                   1624:     hDoc.write("<\\/td><\\/tr><\\/table>&nbsp;");
1.589     bisitz   1625:     hDoc.write("<input type=\\"button\\" value=\\"Save\\" onclick=\\"javascript:updateChoice(1)\\">&nbsp;&nbsp;");
                   1626:     hDoc.write("<input type=\\"button\\" value=\\"Cancel\\" onclick=\\"self.close()\\"><br /><br />");
1.465     albertel 1627:     hDoc.write("<\\/form>");
1.351     albertel 1628:     hDoc.write('$end_page_highlight_central');
1.128     ng       1629:     hDoc.close();
1.44      ng       1630:   }
                   1631: 
                   1632: SUBJAVASCRIPT
                   1633: }
                   1634: 
1.349     albertel 1635: sub get_increment {
1.348     bowersj2 1636:     my $increment = $env{'form.increment'};
                   1637:     if ($increment != 1 && $increment != .5 && $increment != .25 &&
                   1638:         $increment != .1) {
                   1639:         $increment = 1;
                   1640:     }
                   1641:     return $increment;
                   1642: }
                   1643: 
1.585     bisitz   1644: sub gradeBox_start {
                   1645:     return (
                   1646:         &Apache::loncommon::start_data_table()
                   1647:        .&Apache::loncommon::start_data_table_header_row()
                   1648:        .'<th>'.&mt('Part').'</th>'
                   1649:        .'<th>'.&mt('Points').'</th>'
                   1650:        .'<th>&nbsp;</th>'
                   1651:        .'<th>'.&mt('Assign Grade').'</th>'
                   1652:        .'<th>'.&mt('Weight').'</th>'
                   1653:        .'<th>'.&mt('Grade Status').'</th>'
                   1654:        .&Apache::loncommon::end_data_table_header_row()
                   1655:     );
                   1656: }
                   1657: 
                   1658: sub gradeBox_end {
                   1659:     return (
                   1660:         &Apache::loncommon::end_data_table()
                   1661:     );
                   1662: }
1.71      ng       1663: #--- displays the grading box, used in essay type problem and grading by page/sequence
                   1664: sub gradeBox {
1.322     albertel 1665:     my ($request,$symb,$uname,$udom,$counter,$partid,$record) = @_;
1.381     albertel 1666:     my $checkIcon = '<img alt="'.&mt('Check Mark').
1.485     albertel 1667: 	'" src="'.&Apache::loncommon::lonhttpdurl($request->dir_config('lonIconsURL').'/check.gif').'" height="16" border="0" />';
1.71      ng       1668:     my $wgt    = &Apache::lonnet::EXT('resource.'.$partid.'.weight',$symb,$udom,$uname);
1.466     albertel 1669:     my $wgtmsg = ($wgt > 0) ? &mt('(problem weight)') 
                   1670:                            : '<span class="LC_info">'.&mt('problem weight assigned by computer').'</span>';
1.71      ng       1671:     $wgt       = ($wgt > 0 ? $wgt : '1');
                   1672:     my $score  = ($$record{'resource.'.$partid.'.awarded'} eq '' ?
1.320     albertel 1673: 		  '' : &compute_points($$record{'resource.'.$partid.'.awarded'},$wgt));
1.71      ng       1674:     my $result='<input type="hidden" name="WGT'.$counter.'_'.$partid.'" value="'.$wgt.'" />'."\n";
1.466     albertel 1675:     my $display_part= &get_display_part($partid,$symb);
1.270     albertel 1676:     my %last_resets = &get_last_resets($symb,$env{'request.course.id'},
                   1677: 				       [$partid]);
                   1678:     my $aggtries = $$record{'resource.'.$partid.'.tries'};
1.269     raeburn  1679:     if ($last_resets{$partid}) {
                   1680:         $aggtries = &get_num_tries($record,$last_resets{$partid},$partid);
                   1681:     }
1.585     bisitz   1682:     $result.=&Apache::loncommon::start_data_table_row();
1.71      ng       1683:     my $ctr = 0;
1.348     bowersj2 1684:     my $thisweight = 0;
1.349     albertel 1685:     my $increment = &get_increment();
1.485     albertel 1686: 
                   1687:     my $radio.='<table border="0"><tr>'."\n";  # display radio buttons in a nice table 10 across
1.348     bowersj2 1688:     while ($thisweight<=$wgt) {
1.532     bisitz   1689: 	$radio.= '<td><span class="LC_nobreak"><label><input type="radio" name="RADVAL'.$counter.'_'.$partid.'" '.
1.589     bisitz   1690:         'onclick="javascript:writeBox(this.form,\''.$counter.'_'.$partid.'\','.
1.348     bowersj2 1691: 	    $thisweight.')" value="'.$thisweight.'" '.
1.401     albertel 1692: 	    ($score eq $thisweight ? 'checked="checked"':'').' /> '.$thisweight."</label></span></td>\n";
1.485     albertel 1693: 	$radio.=(($ctr+1)%10 == 0 ? '</tr><tr>' : '');
1.348     bowersj2 1694:         $thisweight += $increment;
1.71      ng       1695: 	$ctr++;
                   1696:     }
1.485     albertel 1697:     $radio.='</tr></table>';
                   1698: 
                   1699:     my $line.='<input type="text" name="GD_BOX'.$counter.'_'.$partid.'"'.
1.71      ng       1700: 	($score ne ''? ' value = "'.$score.'"':'').' size="4" '.
1.589     bisitz   1701: 	'onchange="javascript:updateRadio(this.form,\''.$counter.'_'.$partid.'\','.
1.71      ng       1702: 	$wgt.')" /></td>'."\n";
1.485     albertel 1703:     $line.='<td>/'.$wgt.' '.$wgtmsg.
1.71      ng       1704: 	($$record{'resource.'.$partid.'.solved'} eq 'correct_by_student' ? '&nbsp;'.$checkIcon : '').
1.585     bisitz   1705: 	' </td>'."\n";
                   1706:     $line.='<td><select name="GD_SEL'.$counter.'_'.$partid.'" '.
1.589     bisitz   1707: 	'onchange="javascript:clearRadBox(this.form,\''.$counter.'_'.$partid.'\')" >'."\n";
1.71      ng       1708:     if ($$record{'resource.'.$partid.'.solved'} eq 'excused') {
1.485     albertel 1709: 	$line.='<option></option>'.
                   1710: 	    '<option value="excused" selected="selected">'.&mt('excused').'</option>';
1.71      ng       1711:     } else {
1.485     albertel 1712: 	$line.='<option selected="selected"></option>'.
                   1713: 	    '<option value="excused" >'.&mt('excused').'</option>';
1.71      ng       1714:     }
1.485     albertel 1715:     $line.='<option value="reset status">'.&mt('reset status').'</option></select>'."\n";
                   1716: 
                   1717: 
                   1718:     $result .= 
1.585     bisitz   1719: 	    '<td>'.$display_part.'</td><td>'.$radio.'</td><td>'.&mt('or').'</td><td>'.$line.'</td>';
                   1720:     $result.=&Apache::loncommon::end_data_table_row();
1.71      ng       1721:     $result.='<input type="hidden" name="stores'.$counter.'_'.$partid.'" value="" />'."\n".
                   1722: 	'<input type="hidden" name="oldpts'.$counter.'_'.$partid.'" value="'.$score.'" />'."\n".
                   1723: 	'<input type="hidden" name="solved'.$counter.'_'.$partid.'" value="'.
1.269     raeburn  1724: 	$$record{'resource.'.$partid.'.solved'}.'" />'."\n".
                   1725:         '<input type="hidden" name="totaltries'.$counter.'_'.$partid.'" value="'.
                   1726:         $$record{'resource.'.$partid.'.tries'}.'" />'."\n".
                   1727:         '<input type="hidden" name="aggtries'.$counter.'_'.$partid.'" value="'.
                   1728:         $aggtries.'" />'."\n";
1.582     raeburn  1729:     my $res_error;
                   1730:     $result.=&handback_box($symb,$uname,$udom,$counter,$partid,$record,\$res_error);
                   1731:     if ($res_error) {
                   1732:         return &navmap_errormsg();
                   1733:     }
1.318     banghart 1734:     return $result;
                   1735: }
1.322     albertel 1736: 
                   1737: sub handback_box {
1.623     www      1738:     my ($symb,$uname,$udom,$counter,$partid,$record,$res_error_pointer) = @_;
                   1739:     my ($partlist,$handgrade,$responseType) = &response_type($symb,$res_error_pointer);
1.323     banghart 1740:     my (@respids);
1.375     albertel 1741:      my @part_response_id = &flatten_responseType($responseType);
                   1742:     foreach my $part_response_id (@part_response_id) {
                   1743:     	my ($part,$resp) = @{ $part_response_id };
1.323     banghart 1744:         if ($part eq $partid) {
1.375     albertel 1745:             push(@respids,$resp);
1.323     banghart 1746:         }
                   1747:     }
1.318     banghart 1748:     my $result;
1.323     banghart 1749:     foreach my $respid (@respids) {
1.322     albertel 1750: 	my $prefix = $counter.'_'.$partid.'_'.$respid.'_';
                   1751: 	my $files=&get_submitted_files($udom,$uname,$partid,$respid,$record);
                   1752: 	next if (!@$files);
                   1753: 	my $file_counter = 1;
1.313     banghart 1754: 	foreach my $file (@$files) {
1.368     banghart 1755: 	    if ($file =~ /\/portfolio\//) {
                   1756:     	        my ($file_path, $file_disp) = ($file =~ m|(.+/)(.+)$|);
                   1757:     	        my ($name,$version,$ext) = &file_name_version_ext($file_disp);
                   1758:     	        $file_disp = "$name.$ext";
                   1759:     	        $file = $file_path.$file_disp;
                   1760:     	        $result.=&mt('Return commented version of [_1] to student.',
                   1761:     			 '<span class="LC_filename">'.$file_disp.'</span>');
                   1762:     	        $result.='<input type="file"   name="'.$prefix.'returndoc'.$file_counter.'" />'."\n";
                   1763:     	        $result.='<input type="hidden" name="'.$prefix.'origdoc'.$file_counter.'" value="'.$file.'" /><br />';
1.485     albertel 1764:     	        $result.='('.&mt('File will be uploaded when you click on Save &amp; Next below.').')<br />';
1.368     banghart 1765:     	        $file_counter++;
                   1766: 	    }
1.322     albertel 1767: 	}
1.313     banghart 1768:     }
1.318     banghart 1769:     return $result;    
1.71      ng       1770: }
1.44      ng       1771: 
1.58      albertel 1772: sub show_problem {
1.382     albertel 1773:     my ($request,$symb,$uname,$udom,$removeform,$viewon,$mode,$form) = @_;
1.144     albertel 1774:     my $rendered;
1.382     albertel 1775:     my %form = ((ref($form) eq 'HASH')? %{$form} : ());
1.329     albertel 1776:     &Apache::lonxml::remember_problem_counter();
1.144     albertel 1777:     if ($mode eq 'both' or $mode eq 'text') {
                   1778: 	$rendered=&Apache::loncommon::get_student_view($symb,$uname,$udom,
1.382     albertel 1779: 						       $env{'request.course.id'},
                   1780: 						       undef,\%form);
1.144     albertel 1781:     }
1.58      albertel 1782:     if ($removeform) {
                   1783: 	$rendered=~s|<form(.*?)>||g;
                   1784: 	$rendered=~s|</form>||g;
1.374     albertel 1785: 	$rendered=~s|(<input[^>]*name\s*=\s*"?)(\w+)("?)|$1would_have_been_$2$3|g;
1.58      albertel 1786:     }
1.144     albertel 1787:     my $companswer;
                   1788:     if ($mode eq 'both' or $mode eq 'answer') {
1.329     albertel 1789: 	&Apache::lonxml::restore_problem_counter();
1.382     albertel 1790: 	$companswer=
                   1791: 	    &Apache::loncommon::get_student_answers($symb,$uname,$udom,
                   1792: 						    $env{'request.course.id'},
                   1793: 						    %form);
1.144     albertel 1794:     }
1.58      albertel 1795:     if ($removeform) {
                   1796: 	$companswer=~s|<form(.*?)>||g;
                   1797: 	$companswer=~s|</form>||g;
1.144     albertel 1798: 	$companswer=~s|name="submit"|name="would_have_been_submit"|g;
1.58      albertel 1799:     }
1.468     albertel 1800:     $rendered=
1.588     bisitz   1801:         '<div class="LC_Box">'
                   1802:        .'<h3 class="LC_hcell">'.&mt('View of the problem').'</h3>'
                   1803:        .$rendered
                   1804:        .'</div>';
1.468     albertel 1805:     $companswer=
1.588     bisitz   1806:         '<div class="LC_Box">'
                   1807:        .'<h3 class="LC_hcell">'.&mt('Correct answer').'</h3>'
                   1808:        .$companswer
                   1809:        .'</div>';
1.468     albertel 1810:     my $result;
1.144     albertel 1811:     if ($mode eq 'both') {
1.588     bisitz   1812:         $result=$rendered.$companswer;
1.144     albertel 1813:     } elsif ($mode eq 'text') {
1.588     bisitz   1814:         $result=$rendered;
1.144     albertel 1815:     } elsif ($mode eq 'answer') {
1.588     bisitz   1816:         $result=$companswer;
1.144     albertel 1817:     }
1.71      ng       1818:     return $result;
1.58      albertel 1819: }
1.397     albertel 1820: 
1.396     banghart 1821: sub files_exist {
                   1822:     my ($r, $symb) = @_;
                   1823:     my @students = &Apache::loncommon::get_env_multiple('form.stuinfo');
1.397     albertel 1824: 
1.396     banghart 1825:     foreach my $student (@students) {
                   1826:         my ($uname,$udom,$fullname) = split(/:/,$student);
1.397     albertel 1827:         my %record = &Apache::lonnet::restore($symb,$env{'request.course.id'},
                   1828: 					      $udom,$uname);
1.396     banghart 1829:         my ($string,$timestamp)= &get_last_submission(\%record);
1.397     albertel 1830:         foreach my $submission (@$string) {
                   1831:             my ($partid,$respid) =
                   1832: 		($submission =~ /^resource\.([^\.]*)\.([^\.]*)\.submission/);
                   1833:             my $files=&get_submitted_files($udom,$uname,$partid,$respid,
                   1834: 					   \%record);
                   1835:             return 1 if (@$files);
1.396     banghart 1836:         }
                   1837:     }
1.397     albertel 1838:     return 0;
1.396     banghart 1839: }
1.397     albertel 1840: 
1.394     banghart 1841: sub download_all_link {
                   1842:     my ($r,$symb) = @_;
1.621     www      1843:     unless (&files_exist($r, $symb)) {
                   1844:        $r->print(&mt('There are currently no submitted documents.'));
                   1845:        return;
                   1846:     }
                   1847: 
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.621     www      1860:     return;
                   1861: }
                   1862: 
                   1863: sub submit_download_link {
                   1864:     my ($request,$symb) = @_;
                   1865:     if (!$symb) { return ''; }
                   1866: #FIXME: Figure out which type of problem this is and provide appropriate download
                   1867:     &download_all_link($request,$symb);
1.394     banghart 1868: }
1.395     albertel 1869: 
1.432     banghart 1870: sub build_section_inputs {
                   1871:     my $section_inputs;
                   1872:     if ($env{'form.section'} eq '') {
                   1873:         $section_inputs .= '<input type="hidden" name="section" value="all" />'."\n";
                   1874:     } else {
                   1875:         my @sections = &Apache::loncommon::get_env_multiple('form.section');
1.434     albertel 1876:         foreach my $section (@sections) {
1.432     banghart 1877:             $section_inputs .= '<input type="hidden" name="section" value="'.$section.'" />'."\n";
                   1878:         }
                   1879:     }
                   1880:     return $section_inputs;
                   1881: }
                   1882: 
1.44      ng       1883: # --------------------------- show submissions of a student, option to grade 
                   1884: sub submission {
1.608     www      1885:     my ($request,$counter,$total,$symb) = @_;
1.257     albertel 1886:     my ($uname,$udom)     = ($env{'form.student'},$env{'form.userdom'});
                   1887:     $udom = ($udom eq '' ? $env{'user.domain'} : $udom); #has form.userdom changed for a student?
                   1888:     my $usec = &Apache::lonnet::getsection($udom,$uname,$env{'request.course.id'});
                   1889:     $env{'form.fullname'} = &Apache::loncommon::plainname($uname,$udom,'lastname') if $env{'form.fullname'} eq '';
1.608     www      1890: 
1.605     www      1891:     my $probtitle=&Apache::lonnet::gettitle($symb); 
1.324     albertel 1892:     if ($symb eq '') { $request->print("Unable to handle ambiguous references:."); return ''; }
1.104     albertel 1893: 
                   1894:     if (!&canview($usec)) {
1.398     albertel 1895: 	$request->print('<span class="LC_warning">Unable to view requested student.('.
                   1896: 			$uname.':'.$udom.' in section '.$usec.' in course id '.
                   1897: 			$env{'request.course.id'}.')</span>');
1.104     albertel 1898: 	return;
                   1899:     }
                   1900: 
1.257     albertel 1901:     if (!$env{'form.lastSub'}) { $env{'form.lastSub'} = 'datesub'; }
                   1902:     if (!$env{'form.vProb'}) { $env{'form.vProb'} = 'yes'; }
                   1903:     if (!$env{'form.vAns'}) { $env{'form.vAns'} = 'yes'; }
                   1904:     my $last = ($env{'form.lastSub'} eq 'last' ? 'last' : '');
1.381     albertel 1905:     my $checkIcon = '<img alt="'.&mt('Check Mark').
                   1906: 	'" src="'.$request->dir_config('lonIconsURL').
1.122     ng       1907: 	'/check.gif" height="16" border="0" />';
1.41      ng       1908: 
1.426     albertel 1909:     my %old_essays;
1.41      ng       1910:     # header info
                   1911:     if ($counter == 0) {
                   1912: 	&sub_page_js($request);
1.621     www      1913: 	&sub_page_kw_js($request);
1.118     ng       1914: 
1.44      ng       1915: 	# option to display problem, only once else it cause problems 
                   1916:         # with the form later since the problem has a form.
1.257     albertel 1917: 	if ($env{'form.vProb'} eq 'yes' or $env{'form.vAns'} eq 'yes') {
1.144     albertel 1918: 	    my $mode;
1.257     albertel 1919: 	    if ($env{'form.vProb'} eq 'yes' && $env{'form.vAns'} eq 'yes') {
1.144     albertel 1920: 		$mode='both';
1.257     albertel 1921: 	    } elsif ($env{'form.vProb'} eq 'yes') {
1.144     albertel 1922: 		$mode='text';
1.257     albertel 1923: 	    } elsif ($env{'form.vAns'} eq 'yes') {
1.144     albertel 1924: 		$mode='answer';
                   1925: 	    }
1.329     albertel 1926: 	    &Apache::lonxml::clear_problem_counter();
1.144     albertel 1927: 	    $request->print(&show_problem($request,$symb,$uname,$udom,0,1,$mode));
1.41      ng       1928: 	}
1.441     www      1929: 
1.44      ng       1930: 	# kwclr is the only variable that is guaranteed to be non blank 
                   1931:         # if this subroutine has been called once.
1.41      ng       1932: 	my %keyhash = ();
1.624     www      1933: #	if ($env{'form.kwclr'} eq '' && $env{'form.handgrade'} eq 'yes') {
                   1934:         if (1) {
1.41      ng       1935: 	    %keyhash = &Apache::lonnet::dump('nohist_handgrade',
1.257     albertel 1936: 					     $env{'course.'.$env{'request.course.id'}.'.domain'},
                   1937: 					     $env{'course.'.$env{'request.course.id'}.'.num'});
1.41      ng       1938: 
1.257     albertel 1939: 	    my $loginuser = $env{'user.name'}.':'.$env{'user.domain'};
                   1940: 	    $env{'form.keywords'} = $keyhash{$symb.'_keywords'} ne '' ? $keyhash{$symb.'_keywords'} : '';
                   1941: 	    $env{'form.kwclr'}    = $keyhash{$loginuser.'_kwclr'} ne '' ? $keyhash{$loginuser.'_kwclr'} : 'red';
                   1942: 	    $env{'form.kwsize'}   = $keyhash{$loginuser.'_kwsize'} ne '' ? $keyhash{$loginuser.'_kwsize'} : '0';
                   1943: 	    $env{'form.kwstyle'}  = $keyhash{$loginuser.'_kwstyle'} ne '' ? $keyhash{$loginuser.'_kwstyle'} : '';
                   1944: 	    $env{'form.msgsub'}   = $keyhash{$symb.'_subject'} ne '' ? 
1.605     www      1945: 		$keyhash{$symb.'_subject'} : $probtitle;
1.257     albertel 1946: 	    $env{'form.savemsgN'} = $keyhash{$symb.'_savemsgN'} ne '' ? $keyhash{$symb.'_savemsgN'} : '0';
1.41      ng       1947: 	}
1.257     albertel 1948: 	my $overRideScore = $env{'form.overRideScore'} eq '' ? 'no' : $env{'form.overRideScore'};
1.442     banghart 1949: 	my $stu_status = join(':',&Apache::loncommon::get_env_multiple('form.Status'));
1.303     banghart 1950: 	$request->print('<form action="/adm/grades" method="post" name="SCORE" enctype="multipart/form-data">'."\n".
1.41      ng       1951: 			'<input type="hidden" name="command"    value="handgrade" />'."\n".
1.442     banghart 1952: 			'<input type="hidden" name="Status"     value="'.$stu_status.'" />'."\n".
1.120     ng       1953: 			'<input type="hidden" name="overRideScore" value="'.$overRideScore.'" />'."\n".
1.41      ng       1954: 			'<input type="hidden" name="refresh"    value="off" />'."\n".
1.120     ng       1955: 			'<input type="hidden" name="studentNo"  value="" />'."\n".
                   1956: 			'<input type="hidden" name="gradeOpt"   value="" />'."\n".
1.418     albertel 1957: 			'<input type="hidden" name="symb"       value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
1.257     albertel 1958: 			'<input type="hidden" name="vProb"      value="'.$env{'form.vProb'}.'" />'."\n".
                   1959: 			'<input type="hidden" name="vAns"       value="'.$env{'form.vAns'}.'" />'."\n".
                   1960: 			'<input type="hidden" name="lastSub"    value="'.$env{'form.lastSub'}.'" />'."\n".
1.432     banghart 1961: 			&build_section_inputs().
1.326     albertel 1962: 			'<input type="hidden" name="submitonly" value="'.$env{'form.submitonly'}.'" />'."\n".
1.41      ng       1963: 			'<input type="hidden" name="NCT"'.
1.257     albertel 1964: 			' value="'.($env{'form.NTSTU'} ne '' ? $env{'form.NTSTU'} : $total+1).'" />'."\n");
1.624     www      1965: #	if ($env{'form.handgrade'} eq 'yes') {
                   1966:         if (1) {
1.257     albertel 1967: 	    $request->print('<input type="hidden" name="keywords" value="'.$env{'form.keywords'}.'" />'."\n".
                   1968: 			    '<input type="hidden" name="kwclr"    value="'.$env{'form.kwclr'}.'" />'."\n".
                   1969: 			    '<input type="hidden" name="kwsize"   value="'.$env{'form.kwsize'}.'" />'."\n".
                   1970: 			    '<input type="hidden" name="kwstyle"  value="'.$env{'form.kwstyle'}.'" />'."\n".
                   1971: 			    '<input type="hidden" name="msgsub"   value="'.$env{'form.msgsub'}.'" />'."\n".
1.123     ng       1972: 			    '<input type="hidden" name="shownSub" value="0" />'."\n".
1.257     albertel 1973: 			    '<input type="hidden" name="savemsgN" value="'.$env{'form.savemsgN'}.'" />'."\n");
1.154     albertel 1974: 	    foreach my $partid (&Apache::loncommon::get_env_multiple('form.vPart')) {
                   1975: 		$request->print('<input type="hidden" name="vPart" value="'.$partid.'" />'."\n");
                   1976: 	    }
1.123     ng       1977: 	}
1.41      ng       1978: 	
                   1979: 	my ($cts,$prnmsg) = (1,'');
1.257     albertel 1980: 	while ($cts <= $env{'form.savemsgN'}) {
1.41      ng       1981: 	    $prnmsg.='<input type="hidden" name="savemsg'.$cts.'" value="'.
1.123     ng       1982: 		(!exists($keyhash{$symb.'_savemsg'.$cts}) ? 
1.257     albertel 1983: 		 &Apache::lonfeedback::clear_out_html($env{'form.savemsg'.$cts}) :
1.80      ng       1984: 		 &Apache::lonfeedback::clear_out_html($keyhash{$symb.'_savemsg'.$cts})).
1.123     ng       1985: 		'" />'."\n".
                   1986: 		'<input type="hidden" name="shownOnce'.$cts.'" value="0" />'."\n";
1.41      ng       1987: 	    $cts++;
                   1988: 	}
                   1989: 	$request->print($prnmsg);
1.32      ng       1990: 
1.624     www      1991: #	if ($env{'form.handgrade'} eq 'yes') {
                   1992:         if (1) {
1.88      www      1993: #
                   1994: # Print out the keyword options line
                   1995: #
1.41      ng       1996: 	    $request->print(<<KEYWORDS);
1.38      ng       1997: &nbsp;<b>Keyword Options:</b>&nbsp;
1.417     albertel 1998: <a href="javascript:keywords(document.SCORE);" target="_self">List</a>&nbsp; &nbsp;
1.589     bisitz   1999: <a href="#" onmousedown="javascript:getSel(); return false"
1.38      ng       2000:  CLASS="page">Paste Selection to List</a>&nbsp; &nbsp;
1.417     albertel 2001: <a href="javascript:kwhighlight();" target="_self">Highlight Attribute</a><br /><br />
1.38      ng       2002: KEYWORDS
1.88      www      2003: #
                   2004: # Load the other essays for similarity check
                   2005: #
1.324     albertel 2006:             my (undef,undef,$essayurl) = &Apache::lonnet::decode_symb($symb);
1.384     albertel 2007: 	    my ($adom,$aname,$apath)=($essayurl=~/^($LONCAPA::domain_re)\/($LONCAPA::username_re)\/(.*)$/);
1.359     www      2008: 	    $apath=&escape($apath);
1.88      www      2009: 	    $apath=~s/\W/\_/gs;
1.426     albertel 2010: 	    %old_essays=&Apache::lonnet::dump('nohist_essay_'.$apath,$adom,$aname);
1.41      ng       2011:         }
                   2012:     }
1.44      ng       2013: 
1.441     www      2014: # This is where output for one specific student would start
1.592     bisitz   2015:     my $add_class = ($counter%2) ? ' LC_grade_show_user_odd_row' : '';
                   2016:     $request->print(
                   2017:         "\n\n"
                   2018:        .'<div class="LC_grade_show_user'.$add_class.'">'
                   2019:        .'<h2>'.&nameUserString(undef,$env{'form.fullname'},$uname,$udom).'</h2>'
                   2020:        ."\n"
                   2021:     );
1.441     www      2022: 
1.592     bisitz   2023:     # Show additional functions if allowed
                   2024:     if ($perm{'vgr'}) {
                   2025:         $request->print(
                   2026:             &Apache::loncommon::track_student_link(
                   2027:                 &mt('View recent activity'),
                   2028:                 $uname,$udom,'check')
                   2029:            .' '
                   2030:         );
                   2031:     }
                   2032:     if ($perm{'opa'}) {
                   2033:         $request->print(
                   2034:             &Apache::loncommon::pprmlink(
                   2035:                 &mt('Set/Change parameters'),
                   2036:                 $uname,$udom,$symb,'check'));
                   2037:     }
                   2038: 
                   2039:     # Show Problem
1.257     albertel 2040:     if ($env{'form.vProb'} eq 'all' or $env{'form.vAns'} eq 'all') {
1.144     albertel 2041: 	my $mode;
1.257     albertel 2042: 	if ($env{'form.vProb'} eq 'all' && $env{'form.vAns'} eq 'all') {
1.144     albertel 2043: 	    $mode='both';
1.257     albertel 2044: 	} elsif ($env{'form.vProb'} eq 'all' ) {
1.144     albertel 2045: 	    $mode='text';
1.257     albertel 2046: 	} elsif ($env{'form.vAns'} eq 'all') {
1.144     albertel 2047: 	    $mode='answer';
                   2048: 	}
1.329     albertel 2049: 	&Apache::lonxml::clear_problem_counter();
1.475     albertel 2050: 	$request->print(&show_problem($request,$symb,$uname,$udom,1,1,$mode,{'request.prefix' => 'ctr'.$counter}));
1.58      albertel 2051:     }
1.144     albertel 2052: 
1.257     albertel 2053:     my %record = &Apache::lonnet::restore($symb,$env{'request.course.id'},$udom,$uname);
1.582     raeburn  2054:     my $res_error;
                   2055:     my ($partlist,$handgrade,$responseType) = &response_type($symb,\$res_error);
                   2056:     if ($res_error) {
                   2057:         $request->print(&navmap_errormsg());
                   2058:         return;
                   2059:     }
1.41      ng       2060: 
1.44      ng       2061:     # Display student info
1.41      ng       2062:     $request->print(($counter == 0 ? '' : '<br />'));
1.590     bisitz   2063: 
                   2064:     my $result='<div class="LC_Box">'
                   2065:               .'<h3 class="LC_hcell">'.&mt('Submissions').'</h3>';
1.45      ng       2066:     $result.='<input type="hidden" name="name'.$counter.
1.588     bisitz   2067:              '" value="'.$env{'form.fullname'}.'" />'."\n";
1.624     www      2068: #    if ($env{'form.handgrade'} eq 'no') {
                   2069:     if (1) {
1.588     bisitz   2070:         $result.='<p class="LC_info">'
                   2071:                 .&mt('Part(s) graded correct by the computer is marked with a [_1] symbol.',$checkIcon)
                   2072:                 ."</p>\n";
1.469     albertel 2073:     }
                   2074: 
1.118     ng       2075:     # If any part of the problem is an essay-response (handgraded), then check for collaborators
1.464     albertel 2076:     my $fullname;
                   2077:     my $col_fullnames = [];
1.624     www      2078: #    if ($env{'form.handgrade'} eq 'yes') {
                   2079:     if (1) {
1.464     albertel 2080: 	(my $sub_result,$fullname,$col_fullnames)=
                   2081: 	    &check_collaborators($symb,$uname,$udom,\%record,$handgrade,
                   2082: 				 $counter);
                   2083: 	$result.=$sub_result;
1.41      ng       2084:     }
1.44      ng       2085:     $request->print($result."\n");
1.588     bisitz   2086: 
1.44      ng       2087:     # print student answer/submission
1.588     bisitz   2088:     # Options are (1) Handgraded submission only
1.44      ng       2089:     #             (2) Last submission, includes submission that is not handgraded 
                   2090:     #                  (for multi-response type part)
                   2091:     #             (3) Last submission plus the parts info
                   2092:     #             (4) The whole record for this student
1.257     albertel 2093:     if ($env{'form.lastSub'} =~ /^(lastonly|hdgrade)$/) {
1.151     albertel 2094: 	my ($string,$timestamp)= &get_last_submission(\%record);
1.468     albertel 2095: 	
                   2096: 	my $lastsubonly;
                   2097: 
1.588     bisitz   2098:         if ($$timestamp eq '') {
                   2099:             $lastsubonly.='<div class="LC_grade_submissions_body">'.$$string[0].'</div>'; 
                   2100:         } else {
1.592     bisitz   2101:             $lastsubonly =
                   2102:                 '<div class="LC_grade_submissions_body">'
                   2103:                .'<b>'.&mt('Date Submitted:').'</b> '.$$timestamp."\n";
1.468     albertel 2104: 
1.151     albertel 2105: 	    my %seenparts;
1.375     albertel 2106: 	    my @part_response_id = &flatten_responseType($responseType);
                   2107: 	    foreach my $part (@part_response_id) {
1.393     albertel 2108: 		next if ($env{'form.lastSub'} eq 'hdgrade' 
                   2109: 			 && $$handgrade{$$part[0].'_'.$$part[1]} ne 'yes');
                   2110: 
1.375     albertel 2111: 		my ($partid,$respid) = @{ $part };
1.324     albertel 2112: 		my $display_part=&get_display_part($partid,$symb);
1.257     albertel 2113: 		if ($env{"form.$uname:$udom:$partid:submitted_by"}) {
1.151     albertel 2114: 		    if (exists($seenparts{$partid})) { next; }
                   2115: 		    $seenparts{$partid}=1;
1.207     albertel 2116: 		    my $submitby='<b>Part:</b> '.$display_part.
                   2117: 			' <b>Collaborative submission by:</b> '.
1.151     albertel 2118: 			'<a href="javascript:viewSubmitter(\''.
1.257     albertel 2119: 			$env{"form.$uname:$udom:$partid:submitted_by"}.
1.417     albertel 2120: 			'\');" target="_self">'.
1.257     albertel 2121: 			$$fullname{$env{"form.$uname:$udom:$partid:submitted_by"}}.'</a><br />';
1.151     albertel 2122: 		    $request->print($submitby);
                   2123: 		    next;
                   2124: 		}
                   2125: 		my $responsetype = $responseType->{$partid}->{$respid};
                   2126: 		if (!exists($record{"resource.$partid.$respid.submission"})) {
1.577     bisitz   2127:                     $lastsubonly.="\n".'<div class="LC_grade_submission_part">'.
                   2128:                         '<b>'.&mt('Part: [_1]',$display_part).'</b>'.
                   2129:                         ' <span class="LC_internal_info">'.
1.623     www      2130:                         '('.&mt('Response ID: [_1]',$respid).')'.
1.577     bisitz   2131:                         '</span>&nbsp; &nbsp;'.
1.539     riegler  2132: 			'<span class="LC_warning">'.&mt('Nothing submitted - no attempts.').'</span><br /><br /></div>';
1.151     albertel 2133: 		    next;
                   2134: 		}
1.468     albertel 2135: 		foreach my $submission (@$string) {
                   2136: 		    my ($partid,$respid) = ($submission =~ /^resource\.([^\.]*)\.([^\.]*)\.submission/);
1.375     albertel 2137: 		    if (join('_',@{$part}) ne ($partid.'_'.$respid)) { next; }
1.596     raeburn  2138: 		    my ($ressub,$hide,$subval) = split(/:/,$submission,3);
1.151     albertel 2139: 		    # Similarity check
                   2140: 		    my $similar='';
1.257     albertel 2141: 		    if($env{'form.checkPlag'}){
1.151     albertel 2142: 			my ($oname,$odom,$ocrsid,$oessay,$osim)=
1.426     albertel 2143: 			    &most_similar($uname,$udom,$subval,\%old_essays);
1.151     albertel 2144: 			if ($osim) {
                   2145: 			    $osim=int($osim*100.0);
1.426     albertel 2146: 			    my %old_course_desc = 
                   2147: 				&Apache::lonnet::coursedescription($ocrsid,
                   2148: 								   {'one_time' => 1});
                   2149: 
1.596     raeburn  2150:                             if ($hide) {
                   2151:                                 $similar='<hr /><span class="LC_warning">'.&mt("Essay was found to be similar to another essay submitted for this assignment.").'<br />'.
                   2152:                                          &mt('As the current submission is for an anonymous survey, no other details are available.').'</span><hr />';
                   2153:                             } else {
                   2154: 			        $similar="<hr /><h3><span class=\"LC_warning\">".
                   2155: 				    &mt('Essay is [_1]% similar to an essay by [_2] in course [_3] (course id [_4]:[_5])',
                   2156: 				        $osim,
                   2157: 				        &Apache::loncommon::plainname($oname,$odom).' ('.$oname.':'.$odom.')',
                   2158: 				        $old_course_desc{'description'},
                   2159: 				        $old_course_desc{'num'},
                   2160: 				        $old_course_desc{'domain'}).
                   2161: 				    '</span></h3><blockquote><i>'.
                   2162: 				    &keywords_highlight($oessay).
                   2163: 				    '</i></blockquote><hr />';
                   2164:                             }
1.151     albertel 2165: 			}
1.150     albertel 2166: 		    }
1.151     albertel 2167: 		    my $order=&get_order($partid,$respid,$symb,$uname,$udom);
1.257     albertel 2168: 		    if ($env{'form.lastSub'} eq 'lastonly' || 
                   2169: 			($env{'form.lastSub'} eq 'hdgrade' && 
1.377     albertel 2170: 			 $$handgrade{$$part[0].'_'.$$part[1]} eq 'yes')) {
1.324     albertel 2171: 			my $display_part=&get_display_part($partid,$symb);
1.577     bisitz   2172:                         $lastsubonly.='<div class="LC_grade_submission_part">'.
                   2173:                             '<b>'.&mt('Part: [_1]',$display_part).'</b>'.
                   2174:                             ' <span class="LC_internal_info">'.
1.623     www      2175:                             '('.&mt('Response ID: [_1]',$respid).')'.
1.597     wenzelju 2176:                             '</span>&nbsp; &nbsp;';
1.313     banghart 2177: 			my $files=&get_submitted_files($udom,$uname,$partid,$respid,\%record);
                   2178: 			if (@$files) {
1.596     raeburn  2179:                             if ($hide) {
                   2180:                                 $lastsubonly.='<br />'.&mt('[quant,_1,file] uploaded to this anonymous survey',scalar(@{$files}));
                   2181:                             } else {
                   2182:                                 $lastsubonly.='<br /><span class="LC_warning">'.&mt('Like all files provided by users, this file may contain viruses').'</span><br />';
                   2183:                                 foreach my $file (@$files) {
                   2184:                                     &Apache::lonnet::allowuploaded('/adm/grades',$file);
                   2185:                                     $lastsubonly.='<br /><a href="'.$file.'?rawmode=1" target="lonGRDs"><img src="'.&Apache::loncommon::icon($file).'" border="0" /> '.$file.'</a>';
                   2186:                                 }
                   2187:                             }
1.236     albertel 2188: 			    $lastsubonly.='<br />';
1.41      ng       2189: 			}
1.596     raeburn  2190:                         if ($hide) {
                   2191:                             $lastsubonly.='<b>'.&mt('Anonymous Survey').'</b>'; 
                   2192:                         } else {
                   2193: 			    $lastsubonly.='<b>'.&mt('Submitted Answer:').' </b>'.
                   2194: 			        &cleanRecord($subval,$responsetype,$symb,$partid,
                   2195: 					     $respid,\%record,$order,undef,$uname,$udom);
                   2196:                         }
1.151     albertel 2197: 			if ($similar) {$lastsubonly.="<br /><br />$similar\n";}
1.468     albertel 2198: 			$lastsubonly.='</div>';
1.41      ng       2199: 		    }
                   2200: 		}
                   2201: 	    }
1.588     bisitz   2202: 	    $lastsubonly.='</div>'."\n"; # End: LC_grade_submissions_body
1.151     albertel 2203: 	}
                   2204: 	$request->print($lastsubonly);
1.468     albertel 2205:    } elsif ($env{'form.lastSub'} eq 'datesub') {
1.623     www      2206:         my ($parts,$handgrade,$responseType) = &response_type($symb,\$res_error);
1.148     albertel 2207: 	$request->print(&displaySubByDates($symb,\%record,$parts,$responseType,$checkIcon,$uname,$udom));
1.257     albertel 2208:     } elsif ($env{'form.lastSub'} =~ /^(last|all)$/) {
1.41      ng       2209: 	$request->print(&Apache::loncommon::get_previous_attempt($symb,$uname,$udom,
1.257     albertel 2210: 								 $env{'request.course.id'},
1.44      ng       2211: 								 $last,'.submission',
                   2212: 								 'Apache::grades::keywords_highlight'));
1.41      ng       2213:     }
1.121     ng       2214:     $request->print('<input type="hidden" name="unamedom'.$counter.'" value="'.$uname.':'
                   2215: 	.$udom.'" />'."\n");
1.44      ng       2216:     # return if view submission with no grading option
1.619     www      2217: # FIXME: the logic seems off here. Why show the grade button if you cannot grade?
1.618     www      2218:     if (!&canmodify($usec)) {
1.120     ng       2219: 	my $toGrade.='<input type="button" value="Grade Student" '.
1.589     bisitz   2220: 	    'onclick="javascript:checksubmit(this.form,\'Grade Student\',\''
1.417     albertel 2221: 	    .$counter.'\');" target="_self" /> &nbsp;'."\n" if (&canmodify($usec));
1.468     albertel 2222: 	$toGrade.='</div>'."\n";
1.180     albertel 2223: 	$request->print($toGrade);
1.41      ng       2224: 	return;
1.180     albertel 2225:     } else {
1.468     albertel 2226: 	$request->print('</div>'."\n");
1.41      ng       2227:     }
1.33      ng       2228: 
1.121     ng       2229:     # essay grading message center
1.624     www      2230: #    if ($env{'form.handgrade'} eq 'yes') {
                   2231:     if (1) {
1.468     albertel 2232: 	my $result='<div class="LC_grade_message_center">';
                   2233:     
                   2234: 	$result.='<div class="LC_grade_message_center_header">'.
                   2235: 	    &mt('Send Message').'</div><div class="LC_grade_message_center_body">';
1.257     albertel 2236: 	my ($lastname,$givenn) = split(/,/,$env{'form.fullname'});
1.118     ng       2237: 	my $msgfor = $givenn.' '.$lastname;
1.464     albertel 2238: 	if (scalar(@$col_fullnames) > 0) {
                   2239: 	    my $lastone = pop(@$col_fullnames);
                   2240: 	    $msgfor .= ', '.(join ', ',@$col_fullnames).' and '.$lastone.'.';
1.118     ng       2241: 	}
                   2242: 	$msgfor =~ s/\'/\\'/g; #' stupid emacs - no! javascript
1.468     albertel 2243: 	$result.='<input type="hidden" name="includemsg'.$counter.'" value="" />'."\n".
1.121     ng       2244: 	    '<input type="hidden" name="newmsg'.$counter.'" value="" />'."\n";
                   2245: 	$result.='&nbsp;<a href="javascript:msgCenter(document.SCORE,'.$counter.
1.417     albertel 2246: 	    ',\''.$msgfor.'\');" target="_self">'.
1.464     albertel 2247: 	    &mt('Compose message to student').(scalar(@$col_fullnames) >= 1 ? 's' : '').'</a><label> ('.
1.350     albertel 2248: 	    &mt('incl. grades').' <input type="checkbox" name="withgrades'.$counter.'" /></label>)'.
1.118     ng       2249: 	    '<img src="'.$request->dir_config('lonIconsURL').
                   2250: 	    '/mailbkgrd.gif" width="14" height="10" name="mailicon'.$counter.'" />'."\n".
1.298     www      2251: 	    '<br />&nbsp;('.
1.468     albertel 2252: 	    &mt('Message will be sent when you click on Save &amp; Next below.').")\n";
                   2253: 	$result.='</div></div>';
1.121     ng       2254: 	$request->print($result);
1.118     ng       2255:     }
1.41      ng       2256: 
                   2257:     my %seen = ();
                   2258:     my @partlist;
1.129     ng       2259:     my @gradePartRespid;
1.375     albertel 2260:     my @part_response_id = &flatten_responseType($responseType);
1.585     bisitz   2261:     $request->print(
1.588     bisitz   2262:         '<div class="LC_Box">'
                   2263:        .'<h3 class="LC_hcell">'.&mt('Assign Grades').'</h3>'
1.585     bisitz   2264:     );
1.592     bisitz   2265:     $request->print(&gradeBox_start());
1.375     albertel 2266:     foreach my $part_response_id (@part_response_id) {
                   2267:     	my ($partid,$respid) = @{ $part_response_id };
                   2268: 	my $part_resp = join('_',@{ $part_response_id });
1.322     albertel 2269: 	next if ($seen{$partid} > 0);
1.41      ng       2270: 	$seen{$partid}++;
1.393     albertel 2271: 	next if ($$handgrade{$part_resp} ne 'yes' 
                   2272: 		 && $env{'form.lastSub'} eq 'hdgrade');
1.524     raeburn  2273: 	push(@partlist,$partid);
                   2274: 	push(@gradePartRespid,$partid.'.'.$respid);
1.322     albertel 2275: 	$request->print(&gradeBox($request,$symb,$uname,$udom,$counter,$partid,\%record));
1.41      ng       2276:     }
1.585     bisitz   2277:     $request->print(&gradeBox_end()); # </div>
                   2278:     $request->print('</div>');
1.468     albertel 2279: 
                   2280:     $request->print('<div class="LC_grade_info_links">');
                   2281:     $request->print('</div>');
                   2282: 
1.45      ng       2283:     $result='<input type="hidden" name="partlist'.$counter.
                   2284: 	'" value="'.(join ":",@partlist).'" />'."\n";
1.129     ng       2285:     $result.='<input type="hidden" name="gradePartRespid'.
                   2286: 	'" value="'.(join ":",@gradePartRespid).'" />'."\n" if ($counter == 0);
1.45      ng       2287:     my $ctr = 0;
                   2288:     while ($ctr < scalar(@partlist)) {
                   2289: 	$result.='<input type="hidden" name="partid'.$counter.'_'.$ctr.'" value="'.
                   2290: 	    $partlist[$ctr].'" />'."\n";
                   2291: 	$ctr++;
                   2292:     }
1.468     albertel 2293:     $request->print($result.''."\n");
1.41      ng       2294: 
1.441     www      2295: # Done with printing info for one student
                   2296: 
1.468     albertel 2297:     $request->print('</div>');#LC_grade_show_user
1.441     www      2298: 
                   2299: 
1.41      ng       2300:     # print end of form
                   2301:     if ($counter == $total) {
1.592     bisitz   2302:         my $endform='<br /><hr /><table border="0"><tr><td>'."\n";
1.485     albertel 2303: 	$endform.='<input type="button" value="'.&mt('Save &amp; Next').'" '.
1.589     bisitz   2304: 	    'onclick="javascript:checksubmit(this.form,\'Save & Next\','.
1.417     albertel 2305: 	    $total.','.scalar(@partlist).');" target="_self" /> &nbsp;'."\n";
1.119     ng       2306: 	my $ntstu ='<select name="NTSTU">'.
                   2307: 	    '<option>1</option><option>2</option>'.
                   2308: 	    '<option>3</option><option>5</option>'.
                   2309: 	    '<option>7</option><option>10</option></select>'."\n";
1.257     albertel 2310: 	my $nsel = ($env{'form.NTSTU'} ne '' ? $env{'form.NTSTU'} : '1');
1.401     albertel 2311: 	$ntstu =~ s/<option>$nsel</<option selected="selected">$nsel</;
1.578     raeburn  2312:         $endform.=&mt('[_1]student(s)',$ntstu);
1.485     albertel 2313: 	$endform.='&nbsp;&nbsp;<input type="button" value="'.&mt('Previous').'" '.
1.589     bisitz   2314: 	    'onclick="javascript:checksubmit(this.form,\'Previous\');" target="_self" /> &nbsp;'."\n".
1.485     albertel 2315: 	    '<input type="button" value="'.&mt('Next').'" '.
1.589     bisitz   2316: 	    'onclick="javascript:checksubmit(this.form,\'Next\');" target="_self" /> &nbsp;';
1.592     bisitz   2317:         $endform.='<span class="LC_warning">'.
                   2318:                   &mt('(Next and Previous (student) do not save the scores.)').
                   2319:                   '</span>'."\n" ;
1.349     albertel 2320:         $endform.="<input type='hidden' value='".&get_increment().
1.348     bowersj2 2321:             "' name='increment' />";
1.485     albertel 2322: 	$endform.='</td></tr></table></form>';
1.41      ng       2323: 	$request->print($endform);
                   2324:     }
                   2325:     return '';
1.38      ng       2326: }
                   2327: 
1.464     albertel 2328: sub check_collaborators {
                   2329:     my ($symb,$uname,$udom,$record,$handgrade,$counter) = @_;
                   2330:     my ($result,@col_fullnames);
                   2331:     my ($classlist,undef,$fullname) = &getclasslist('all','0');
                   2332:     foreach my $part (keys(%$handgrade)) {
                   2333: 	my $ncol = &Apache::lonnet::EXT('resource.'.$part.
                   2334: 					'.maxcollaborators',
                   2335: 					$symb,$udom,$uname);
                   2336: 	next if ($ncol <= 0);
                   2337: 	$part =~ s/\_/\./g;
                   2338: 	next if ($record->{'resource.'.$part.'.collaborators'} eq '');
                   2339: 	my (@good_collaborators, @bad_collaborators);
                   2340: 	foreach my $possible_collaborator
1.630     www      2341: 	    (split(/[,;\s]+/,$record->{'resource.'.$part.'.collaborators'})) { 
1.464     albertel 2342: 	    $possible_collaborator =~ s/[\$\^\(\)]//g;
                   2343: 	    next if ($possible_collaborator eq '');
1.631     www      2344: 	    my ($co_name,$co_dom) = split(/:/,$possible_collaborator);
1.464     albertel 2345: 	    $co_dom = $udom if (! defined($co_dom) || $co_dom =~ /^domain$/i);
                   2346: 	    next if ($co_name eq $uname && $co_dom eq $udom);
                   2347: 	    # Doing this grep allows 'fuzzy' specification
                   2348: 	    my @matches = grep(/^\Q$co_name\E:\Q$co_dom\E$/i, 
                   2349: 			       keys(%$classlist));
                   2350: 	    if (! scalar(@matches)) {
                   2351: 		push(@bad_collaborators, $possible_collaborator);
                   2352: 	    } else {
                   2353: 		push(@good_collaborators, @matches);
                   2354: 	    }
                   2355: 	}
                   2356: 	if (scalar(@good_collaborators) != 0) {
1.630     www      2357: 	    $result.='<br />'.&mt('Collaborators:').'<ol>';
1.464     albertel 2358: 	    foreach my $name (@good_collaborators) {
                   2359: 		my ($lastname,$givenn) = split(/,/,$$fullname{$name});
                   2360: 		push(@col_fullnames, $givenn.' '.$lastname);
1.630     www      2361: 		$result.='<li>'.$fullname->{$name}.'</li>';
1.464     albertel 2362: 	    }
1.630     www      2363: 	    $result.='</ol><br />'."\n";
1.466     albertel 2364: 	    my ($part)=split(/\./,$part);
1.464     albertel 2365: 	    $result.='<input type="hidden" name="collaborator'.$counter.
                   2366: 		'" value="'.$part.':'.(join ':',@good_collaborators).'" />'.
                   2367: 		"\n";
                   2368: 	}
                   2369: 	if (scalar(@bad_collaborators) > 0) {
1.466     albertel 2370: 	    $result.='<div class="LC_warning">';
1.464     albertel 2371: 	    $result.=&mt('This student has submitted [quant,_1,invalid collaborator]: [_2]',scalar(@bad_collaborators),join(', ',@bad_collaborators));
                   2372: 	    $result .= '</div>';
                   2373: 	}         
                   2374: 	if (scalar(@bad_collaborators > $ncol)) {
1.466     albertel 2375: 	    $result .= '<div class="LC_warning">';
1.464     albertel 2376: 	    $result .= &mt('This student has submitted too many '.
                   2377: 		'collaborators.  Maximum is [_1].',$ncol);
                   2378: 	    $result .= '</div>';
                   2379: 	}
                   2380:     }
                   2381:     return ($result,$fullname,\@col_fullnames);
                   2382: }
                   2383: 
1.44      ng       2384: #--- Retrieve the last submission for all the parts
1.38      ng       2385: sub get_last_submission {
1.119     ng       2386:     my ($returnhash)=@_;
1.596     raeburn  2387:     my (@string,$timestamp,%lasthidden);
1.119     ng       2388:     if ($$returnhash{'version'}) {
1.46      ng       2389: 	my %lasthash=();
                   2390: 	my ($version);
1.119     ng       2391: 	for ($version=1;$version<=$$returnhash{'version'};$version++) {
1.397     albertel 2392: 	    foreach my $key (sort(split(/\:/,
                   2393: 					$$returnhash{$version.':keys'}))) {
                   2394: 		$lasthash{$key}=$$returnhash{$version.':'.$key};
                   2395: 		$timestamp = 
1.545     raeburn  2396: 		    &Apache::lonlocal::locallocaltime($$returnhash{$version.':timestamp'});
1.46      ng       2397: 	    }
                   2398: 	}
1.596     raeburn  2399:         my %typeparts;
                   2400:         my $showsurv = 
                   2401:             &Apache::lonnet::allowed('vas',$env{'request.course.id'});
                   2402:         foreach my $key (sort(keys(%lasthash))) {
                   2403:             if ($key =~ /\.type$/) {
                   2404:                 if (($lasthash{$key} eq 'anonsurvey') || 
                   2405:                     ($lasthash{$key} eq 'anonsurveycred')) {
                   2406:                     my ($ign,@parts) = split(/\./,$key);
                   2407:                     pop(@parts);
                   2408:                     unless ($showsurv) {
                   2409:                         my $id = join(',',@parts);
                   2410:                         $typeparts{$ign.'.'.$id} = $lasthash{$key};
                   2411:                     }
                   2412:                     delete($lasthash{$key});
                   2413:                 }
                   2414:             }
                   2415:         }
                   2416:         my @hidden = keys(%typeparts);
1.397     albertel 2417: 	foreach my $key (keys(%lasthash)) {
                   2418: 	    next if ($key !~ /\.submission$/);
1.596     raeburn  2419:             my $hide;
                   2420:             if (@hidden) {
                   2421:                 foreach my $id (@hidden) {
                   2422:                     if ($key =~ /^\Q$id\E/) {
                   2423:                         $hide = 1;
                   2424:                         last;
                   2425:                     }
                   2426:                 }
                   2427:             }
1.397     albertel 2428: 	    my ($partid,$foo) = split(/submission$/,$key);
                   2429: 	    my $draft  = $lasthash{$partid.'awarddetail'} eq 'DRAFT' ?
1.398     albertel 2430: 		'<span class="LC_warning">Draft Copy</span> ' : '';
1.596     raeburn  2431: 	    push(@string, join(':', $key, $hide, $draft.$lasthash{$key}));
1.41      ng       2432: 	}
                   2433:     }
1.397     albertel 2434:     if (!@string) {
                   2435: 	$string[0] =
1.539     riegler  2436: 	    '<span class="LC_warning">'.&mt('Nothing submitted - no attempts.').'</span>';
1.397     albertel 2437:     }
                   2438:     return (\@string,\$timestamp);
1.38      ng       2439: }
1.35      ng       2440: 
1.44      ng       2441: #--- High light keywords, with style choosen by user.
1.38      ng       2442: sub keywords_highlight {
1.44      ng       2443:     my $string    = shift;
1.257     albertel 2444:     my $size      = $env{'form.kwsize'} eq '0' ? '' : 'size='.$env{'form.kwsize'};
                   2445:     my $styleon   = $env{'form.kwstyle'} eq ''  ? '' : $env{'form.kwstyle'};
1.41      ng       2446:     (my $styleoff = $styleon) =~ s/\</\<\//;
1.257     albertel 2447:     my @keylist   = split(/[,\s+]/,$env{'form.keywords'});
1.398     albertel 2448:     foreach my $keyword (@keylist) {
                   2449: 	$string =~ s/\b\Q$keyword\E(\b|\.)/<font color\=$env{'form.kwclr'} $size\>$styleon$keyword$styleoff<\/font>/gi;
1.41      ng       2450:     }
                   2451:     return $string;
1.38      ng       2452: }
1.36      ng       2453: 
1.44      ng       2454: #--- Called from submission routine
1.38      ng       2455: sub processHandGrade {
1.608     www      2456:     my ($request,$symb) = @_;
1.324     albertel 2457:     my (undef,undef,$url) = &Apache::lonnet::decode_symb($symb);
1.257     albertel 2458:     my $button = $env{'form.gradeOpt'};
                   2459:     my $ngrade = $env{'form.NCT'};
                   2460:     my $ntstu  = $env{'form.NTSTU'};
1.301     albertel 2461:     my $cdom   = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   2462:     my $cnum   = $env{'course.'.$env{'request.course.id'}.'.num'};
                   2463: 
1.44      ng       2464:     if ($button eq 'Save & Next') {
                   2465: 	my $ctr = 0;
                   2466: 	while ($ctr < $ngrade) {
1.257     albertel 2467: 	    my ($uname,$udom) = split(/:/,$env{'form.unamedom'.$ctr});
1.324     albertel 2468: 	    my ($errorflag,$pts,$wgt) = &saveHandGrade($request,$symb,$uname,$udom,$ctr);
1.71      ng       2469: 	    if ($errorflag eq 'no_score') {
                   2470: 		$ctr++;
                   2471: 		next;
                   2472: 	    }
1.104     albertel 2473: 	    if ($errorflag eq 'not_allowed') {
1.398     albertel 2474: 		$request->print("<span class=\"LC_warning\">Not allowed to modify grades for $uname:$udom</span>");
1.104     albertel 2475: 		$ctr++;
                   2476: 		next;
                   2477: 	    }
1.257     albertel 2478: 	    my $includemsg = $env{'form.includemsg'.$ctr};
1.44      ng       2479: 	    my ($subject,$message,$msgstatus) = ('','','');
1.418     albertel 2480: 	    my $restitle = &Apache::lonnet::gettitle($symb);
                   2481:             my ($feedurl,$showsymb) =
                   2482: 		&get_feedurl_and_symb($symb,$uname,$udom);
                   2483: 	    my $messagetail;
1.62      albertel 2484: 	    if ($includemsg =~ /savemsg|newmsg\Q$ctr\E/) {
1.298     www      2485: 		$subject = $env{'form.msgsub'} if ($includemsg =~ /msgsub/);
1.295     www      2486: 		unless ($subject=~/\w/) { $subject=&mt('Grading Feedback'); }
1.386     raeburn  2487: 		$subject.=' ['.$restitle.']';
1.44      ng       2488: 		my (@msgnum) = split(/,/,$includemsg);
                   2489: 		foreach (@msgnum) {
1.257     albertel 2490: 		    $message.=$env{'form.'.$_} if ($_ =~ /savemsg|newmsg/ && $_ ne '');
1.44      ng       2491: 		}
1.80      ng       2492: 		$message =&Apache::lonfeedback::clear_out_html($message);
1.298     www      2493: 		if ($env{'form.withgrades'.$ctr}) {
                   2494: 		    $message.="\n\nPoint".($pts > 1 ? 's':'').' awarded = '.$pts.' out of '.$wgt;
1.386     raeburn  2495: 		    $messagetail = " for <a href=\"".
1.605     www      2496: 		                   $feedurl."?symb=$showsymb\">$restitle</a>";
1.386     raeburn  2497: 		}
                   2498: 		$msgstatus = 
                   2499:                     &Apache::lonmsg::user_normal_msg($uname,$udom,$subject,
                   2500: 						     $message.$messagetail,
1.418     albertel 2501:                                                      undef,$feedurl,undef,
1.386     raeburn  2502:                                                      undef,undef,$showsymb,
                   2503:                                                      $restitle);
1.574     bisitz   2504: 		$request->print('<br />'.&mt('Sending message to [_1]',$uname.':'.$udom).': '.
1.296     www      2505: 				$msgstatus);
1.44      ng       2506: 	    }
1.257     albertel 2507: 	    if ($env{'form.collaborator'.$ctr}) {
1.155     albertel 2508: 		my @collabstrs=&Apache::loncommon::get_env_multiple("form.collaborator$ctr");
1.150     albertel 2509: 		foreach my $collabstr (@collabstrs) {
                   2510: 		    my ($part,@collaborators) = split(/:/,$collabstr);
1.310     banghart 2511: 		    foreach my $collaborator (@collaborators) {
1.150     albertel 2512: 			my ($errorflag,$pts,$wgt) = 
1.324     albertel 2513: 			    &saveHandGrade($request,$symb,$collaborator,$udom,$ctr,
1.257     albertel 2514: 					   $env{'form.unamedom'.$ctr},$part);
1.150     albertel 2515: 			if ($errorflag eq 'not_allowed') {
1.362     albertel 2516: 			    $request->print("<span class=\"LC_error\">".&mt('Not allowed to modify grades for [_1]',"$collaborator:$udom")."</span>");
1.150     albertel 2517: 			    next;
1.418     albertel 2518: 			} elsif ($message ne '') {
                   2519: 			    my ($baseurl,$showsymb) = 
                   2520: 				&get_feedurl_and_symb($symb,$collaborator,
                   2521: 						      $udom);
                   2522: 			    if ($env{'form.withgrades'.$ctr}) {
                   2523: 				$messagetail = " for <a href=\"".
1.605     www      2524:                                     $baseurl."?symb=$showsymb\">$restitle</a>";
1.150     albertel 2525: 			    }
1.418     albertel 2526: 			    $msgstatus = 
                   2527: 				&Apache::lonmsg::user_normal_msg($collaborator,$udom,$subject,$message.$messagetail,undef,$baseurl,undef,undef,undef,$showsymb,$restitle);
1.104     albertel 2528: 			}
1.44      ng       2529: 		    }
                   2530: 		}
                   2531: 	    }
                   2532: 	    $ctr++;
                   2533: 	}
                   2534:     }
                   2535: 
1.624     www      2536: #    if ($env{'form.handgrade'} eq 'yes') {
                   2537:     if (1) {
1.119     ng       2538: 	# Keywords sorted in alphabatical order
1.257     albertel 2539: 	my $loginuser = $env{'user.name'}.':'.$env{'user.domain'};
1.119     ng       2540: 	my %keyhash = ();
1.257     albertel 2541: 	$env{'form.keywords'}           =~ s/,\s{0,}|\s+/ /g;
                   2542: 	$env{'form.keywords'}           =~ s/^\s+|\s+$//;
                   2543: 	my (@keywords) = sort(split(/\s+/,$env{'form.keywords'}));
                   2544: 	$env{'form.keywords'} = join(' ',@keywords);
                   2545: 	$keyhash{$symb.'_keywords'}     = $env{'form.keywords'};
                   2546: 	$keyhash{$symb.'_subject'}      = $env{'form.msgsub'};
                   2547: 	$keyhash{$loginuser.'_kwclr'}   = $env{'form.kwclr'};
                   2548: 	$keyhash{$loginuser.'_kwsize'}  = $env{'form.kwsize'};
                   2549: 	$keyhash{$loginuser.'_kwstyle'} = $env{'form.kwstyle'};
1.119     ng       2550: 
                   2551: 	# message center - Order of message gets changed. Blank line is eliminated.
1.257     albertel 2552: 	# New messages are saved in env for the next student.
1.119     ng       2553: 	# All messages are saved in nohist_handgrade.db
                   2554: 	my ($ctr,$idx) = (1,1);
1.257     albertel 2555: 	while ($ctr <= $env{'form.savemsgN'}) {
                   2556: 	    if ($env{'form.savemsg'.$ctr} ne '') {
                   2557: 		$keyhash{$symb.'_savemsg'.$idx} = $env{'form.savemsg'.$ctr};
1.119     ng       2558: 		$idx++;
                   2559: 	    }
                   2560: 	    $ctr++;
1.41      ng       2561: 	}
1.119     ng       2562: 	$ctr = 0;
                   2563: 	while ($ctr < $ngrade) {
1.257     albertel 2564: 	    if ($env{'form.newmsg'.$ctr} ne '') {
                   2565: 		$keyhash{$symb.'_savemsg'.$idx} = $env{'form.newmsg'.$ctr};
                   2566: 		$env{'form.savemsg'.$idx} = $env{'form.newmsg'.$ctr};
1.119     ng       2567: 		$idx++;
                   2568: 	    }
                   2569: 	    $ctr++;
1.41      ng       2570: 	}
1.257     albertel 2571: 	$env{'form.savemsgN'} = --$idx;
                   2572: 	$keyhash{$symb.'_savemsgN'} = $env{'form.savemsgN'};
1.119     ng       2573: 	my $putresult = &Apache::lonnet::put
1.301     albertel 2574: 	    ('nohist_handgrade',\%keyhash,$cdom,$cnum);
1.41      ng       2575:     }
1.44      ng       2576:     # Called by Save & Refresh from Highlight Attribute Window
1.257     albertel 2577:     my (undef,undef,$fullname) = &getclasslist($env{'form.section'},'1');
                   2578:     if ($env{'form.refresh'} eq 'on') {
1.86      ng       2579: 	my ($ctr,$total) = (0,0);
                   2580: 	while ($ctr < $ngrade) {
1.257     albertel 2581: 	    $total++ if  $env{'form.unamedom'.$ctr} ne '';
1.86      ng       2582: 	    $ctr++;
                   2583: 	}
1.257     albertel 2584: 	$env{'form.NTSTU'}=$ngrade;
1.86      ng       2585: 	$ctr = 0;
                   2586: 	while ($ctr < $total) {
1.257     albertel 2587: 	    my $processUser = $env{'form.unamedom'.$ctr};
                   2588: 	    ($env{'form.student'},$env{'form.userdom'}) = split(/:/,$processUser);
                   2589: 	    $env{'form.fullname'} = $$fullname{$processUser};
1.625     www      2590: 	    &submission($request,$ctr,$total-1,$symb);
1.41      ng       2591: 	    $ctr++;
                   2592: 	}
                   2593: 	return '';
                   2594:     }
1.36      ng       2595: 
1.121     ng       2596: # Go directly to grade student - from submission or link from chart page
1.625     www      2597: # FIXME: looks like reading off the button label!
1.120     ng       2598:     if ($button eq 'Grade Student') {
1.257     albertel 2599: 	my $processUser = $env{'form.unamedom'.$env{'form.studentNo'}};
                   2600: 	($env{'form.student'},$env{'form.userdom'}) = split(/:/,$processUser);
                   2601: 	$env{'form.fullname'} = $$fullname{$processUser};
1.625     www      2602: 	&submission($request,0,0,$symb);
1.120     ng       2603: 	return '';
                   2604:     }
                   2605: 
1.44      ng       2606:     # Get the next/previous one or group of students
1.257     albertel 2607:     my $firststu = $env{'form.unamedom0'};
                   2608:     my $laststu = $env{'form.unamedom'.($ngrade-1)};
1.119     ng       2609:     my $ctr = 2;
1.41      ng       2610:     while ($laststu eq '') {
1.257     albertel 2611: 	$laststu  = $env{'form.unamedom'.($ngrade-$ctr)};
1.41      ng       2612: 	$ctr++;
                   2613: 	$laststu = $firststu if ($ctr > $ngrade);
                   2614:     }
1.44      ng       2615: 
1.41      ng       2616:     my (@parsedlist,@nextlist);
                   2617:     my ($nextflg) = 0;
1.524     raeburn  2618:     foreach my $item (sort 
1.294     albertel 2619: 	     {
                   2620: 		 if (lc($$fullname{$a}) ne lc($$fullname{$b})) {
                   2621: 		     return (lc($$fullname{$a}) cmp lc($$fullname{$b}));
                   2622: 		 }
                   2623: 		 return $a cmp $b;
                   2624: 	     } (keys(%$fullname))) {
1.605     www      2625: # FIXME: this is fishy, looks like the button label
1.41      ng       2626: 	if ($nextflg == 1 && $button =~ /Next$/) {
1.524     raeburn  2627: 	    push(@parsedlist,$item);
1.41      ng       2628: 	}
1.524     raeburn  2629: 	$nextflg = 1 if ($item eq $laststu);
1.41      ng       2630: 	if ($button eq 'Previous') {
1.524     raeburn  2631: 	    last if ($item eq $firststu);
                   2632: 	    push(@parsedlist,$item);
1.41      ng       2633: 	}
                   2634:     }
                   2635:     $ctr = 0;
1.605     www      2636: # FIXME: this is fishy, looks like the button label
1.41      ng       2637:     @parsedlist = reverse @parsedlist if ($button eq 'Previous');
1.582     raeburn  2638:     my $res_error;
                   2639:     my ($partlist) = &response_type($symb,\$res_error);
                   2640:     if ($res_error) {
                   2641:         $request->print(&navmap_errormsg());
                   2642:         return;
                   2643:     }
1.41      ng       2644:     foreach my $student (@parsedlist) {
1.257     albertel 2645: 	my $submitonly=$env{'form.submitonly'};
1.41      ng       2646: 	my ($uname,$udom) = split(/:/,$student);
1.301     albertel 2647: 	
                   2648: 	if ($submitonly eq 'queued') {
                   2649: 	    my %queue_status = 
                   2650: 		&Apache::bridgetask::get_student_status($symb,$cdom,$cnum,
                   2651: 							$udom,$uname);
                   2652: 	    next if (!defined($queue_status{'gradingqueue'}));
                   2653: 	}
                   2654: 
1.156     albertel 2655: 	if ($submitonly =~ /^(yes|graded|incorrect)$/) {
1.257     albertel 2656: #	    my %record = &Apache::lonnet::restore($symb,$env{'request.course.id'},$udom,$uname);
1.324     albertel 2657: 	    my %status=&student_gradeStatus($symb,$udom,$uname,$partlist);
1.145     albertel 2658: 	    my $submitted = 0;
1.248     albertel 2659: 	    my $ungraded = 0;
                   2660: 	    my $incorrect = 0;
1.524     raeburn  2661: 	    foreach my $item (keys(%status)) {
                   2662: 		$submitted = 1 if ($status{$item} ne 'nothing');
                   2663: 		$ungraded = 1 if ($status{$item} =~ /^ungraded/);
                   2664: 		$incorrect = 1 if ($status{$item} =~ /^incorrect/);
                   2665: 		my ($foo,$partid,$foo1) = split(/\./,$item);
1.145     albertel 2666: 		if ($status{'resource.'.$partid.'.submitted_by'} ne '') {
                   2667: 		    $submitted = 0;
                   2668: 		}
1.41      ng       2669: 	    }
1.156     albertel 2670: 	    next if (!$submitted && ($submitonly eq 'yes' ||
                   2671: 				     $submitonly eq 'incorrect' ||
                   2672: 				     $submitonly eq 'graded'));
1.248     albertel 2673: 	    next if (!$ungraded && ($submitonly eq 'graded'));
                   2674: 	    next if (!$incorrect && $submitonly eq 'incorrect');
1.41      ng       2675: 	}
1.524     raeburn  2676: 	push(@nextlist,$student) if ($ctr < $ntstu);
1.129     ng       2677: 	last if ($ctr == $ntstu);
1.41      ng       2678: 	$ctr++;
                   2679:     }
1.36      ng       2680: 
1.41      ng       2681:     $ctr = 0;
                   2682:     my $total = scalar(@nextlist)-1;
1.39      ng       2683: 
1.524     raeburn  2684:     foreach (sort(@nextlist)) {
1.41      ng       2685: 	my ($uname,$udom,$submitter) = split(/:/);
1.257     albertel 2686: 	$env{'form.student'}  = $uname;
                   2687: 	$env{'form.userdom'}  = $udom;
                   2688: 	$env{'form.fullname'} = $$fullname{$_};
1.625     www      2689: 	&submission($request,$ctr,$total,$symb);
1.41      ng       2690: 	$ctr++;
                   2691:     }
                   2692:     if ($total < 0) {
1.632   ! www      2693: 	my $the_end.=&mt('<b>Message: </b> No more students for this section or class.').'<br /><br />'."\n";
1.41      ng       2694: 	$request->print($the_end);
                   2695:     }
                   2696:     return '';
1.38      ng       2697: }
1.36      ng       2698: 
1.44      ng       2699: #---- Save the score and award for each student, if changed
1.38      ng       2700: sub saveHandGrade {
1.324     albertel 2701:     my ($request,$symb,$stuname,$domain,$newflg,$submitter,$part) = @_;
1.342     banghart 2702:     my @version_parts;
1.104     albertel 2703:     my $usec = &Apache::lonnet::getsection($domain,$stuname,
1.257     albertel 2704: 					   $env{'request.course.id'});
1.104     albertel 2705:     if (!&canmodify($usec)) { return('not_allowed'); }
1.337     banghart 2706:     my %record = &Apache::lonnet::restore($symb,$env{'request.course.id'},$domain,$stuname);
1.251     banghart 2707:     my @parts_graded;
1.77      ng       2708:     my %newrecord  = ();
                   2709:     my ($pts,$wgt) = ('','');
1.269     raeburn  2710:     my %aggregate = ();
                   2711:     my $aggregateflag = 0;
1.301     albertel 2712:     my @parts = split(/:/,$env{'form.partlist'.$newflg});
                   2713:     foreach my $new_part (@parts) {
1.337     banghart 2714: 	#collaborator ($submi may vary for different parts
1.259     banghart 2715: 	if ($submitter && $new_part ne $part) { next; }
                   2716: 	my $dropMenu = $env{'form.GD_SEL'.$newflg.'_'.$new_part};
1.125     ng       2717: 	if ($dropMenu eq 'excused') {
1.259     banghart 2718: 	    if ($record{'resource.'.$new_part.'.solved'} ne 'excused') {
                   2719: 		$newrecord{'resource.'.$new_part.'.solved'} = 'excused';
                   2720: 		if (exists($record{'resource.'.$new_part.'.awarded'})) {
                   2721: 		    $newrecord{'resource.'.$new_part.'.awarded'} = '';
1.58      albertel 2722: 		}
1.364     banghart 2723: 	        $newrecord{'resource.'.$new_part.'.regrader'}="$env{'user.name'}:$env{'user.domain'}";
1.58      albertel 2724: 	    }
1.125     ng       2725: 	} elsif ($dropMenu eq 'reset status'
1.259     banghart 2726: 		 && exists($record{'resource.'.$new_part.'.solved'})) { #don't bother if no old records -> no attempts
1.524     raeburn  2727: 	    foreach my $key (keys(%record)) {
1.259     banghart 2728: 		if ($key=~/^resource\.\Q$new_part\E\./) { $newrecord{$key} = ''; }
1.197     albertel 2729: 	    }
1.259     banghart 2730: 	    $newrecord{'resource.'.$new_part.'.regrader'}=
1.257     albertel 2731: 		"$env{'user.name'}:$env{'user.domain'}";
1.270     albertel 2732:             my $totaltries = $record{'resource.'.$part.'.tries'};
                   2733: 
                   2734:             my %last_resets = &get_last_resets($symb,$env{'request.course.id'},
                   2735: 					       [$new_part]);
                   2736:             my $aggtries =$totaltries;
1.269     raeburn  2737:             if ($last_resets{$new_part}) {
1.270     albertel 2738:                 $aggtries = &get_num_tries(\%record,$last_resets{$new_part},
                   2739: 					   $new_part);
1.269     raeburn  2740:             }
1.270     albertel 2741: 
                   2742:             my $solvedstatus = $record{'resource.'.$new_part.'.solved'};
1.269     raeburn  2743:             if ($aggtries > 0) {
1.327     albertel 2744:                 &decrement_aggs($symb,$new_part,\%aggregate,$aggtries,$totaltries,$solvedstatus);
1.269     raeburn  2745:                 $aggregateflag = 1;
                   2746:             }
1.125     ng       2747: 	} elsif ($dropMenu eq '') {
1.259     banghart 2748: 	    $pts = ($env{'form.GD_BOX'.$newflg.'_'.$new_part} ne '' ? 
                   2749: 		    $env{'form.GD_BOX'.$newflg.'_'.$new_part} : 
                   2750: 		    $env{'form.RADVAL'.$newflg.'_'.$new_part});
                   2751: 	    if ($pts eq '' && $env{'form.GD_SEL'.$newflg.'_'.$new_part} eq '') {
1.153     albertel 2752: 		next;
                   2753: 	    }
1.259     banghart 2754: 	    $wgt = $env{'form.WGT'.$newflg.'_'.$new_part} eq '' ? 1 : 
                   2755: 		$env{'form.WGT'.$newflg.'_'.$new_part};
1.41      ng       2756: 	    my $partial= $pts/$wgt;
1.259     banghart 2757: 	    if ($partial eq $record{'resource.'.$new_part.'.awarded'}) {
1.153     albertel 2758: 		#do not update score for part if not changed.
1.346     banghart 2759:                 &handback_files($request,$symb,$stuname,$domain,$newflg,$new_part,\%newrecord);
1.153     albertel 2760: 		next;
1.251     banghart 2761: 	    } else {
1.524     raeburn  2762: 	        push(@parts_graded,$new_part);
1.153     albertel 2763: 	    }
1.259     banghart 2764: 	    if ($record{'resource.'.$new_part.'.awarded'} ne $partial) {
                   2765: 		$newrecord{'resource.'.$new_part.'.awarded'}  = $partial;
1.153     albertel 2766: 	    }
1.259     banghart 2767: 	    my $reckey = 'resource.'.$new_part.'.solved';
1.41      ng       2768: 	    if ($partial == 0) {
1.153     albertel 2769: 		if ($record{$reckey} ne 'incorrect_by_override') {
                   2770: 		    $newrecord{$reckey} = 'incorrect_by_override';
                   2771: 		}
1.41      ng       2772: 	    } else {
1.153     albertel 2773: 		if ($record{$reckey} ne 'correct_by_override') {
                   2774: 		    $newrecord{$reckey} = 'correct_by_override';
                   2775: 		}
                   2776: 	    }	    
                   2777: 	    if ($submitter && 
1.259     banghart 2778: 		($record{'resource.'.$new_part.'.submitted_by'} ne $submitter)) {
                   2779: 		$newrecord{'resource.'.$new_part.'.submitted_by'} = $submitter;
1.41      ng       2780: 	    }
1.259     banghart 2781: 	    $newrecord{'resource.'.$new_part.'.regrader'}=
1.257     albertel 2782: 		"$env{'user.name'}:$env{'user.domain'}";
1.41      ng       2783: 	}
1.259     banghart 2784: 	# unless problem has been graded, set flag to version the submitted files
1.305     banghart 2785: 	unless ($record{'resource.'.$new_part.'.solved'} =~ /^correct_/  || 
                   2786: 	        $record{'resource.'.$new_part.'.solved'} eq 'incorrect_by_override' ||
                   2787: 	        $dropMenu eq 'reset status')
                   2788: 	   {
1.524     raeburn  2789: 	    push(@version_parts,$new_part);
1.259     banghart 2790: 	}
1.41      ng       2791:     }
1.301     albertel 2792:     my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   2793:     my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   2794: 
1.344     albertel 2795:     if (%newrecord) {
                   2796:         if (@version_parts) {
1.364     banghart 2797:             my @changed_keys = &version_portfiles(\%record, \@parts_graded, 
                   2798:                                 $env{'request.course.id'}, $symb, $domain, $stuname, \@version_parts);
1.344     albertel 2799: 	    @newrecord{@changed_keys} = @record{@changed_keys};
1.367     albertel 2800: 	    foreach my $new_part (@version_parts) {
                   2801: 		&handback_files($request,$symb,$stuname,$domain,$newflg,
                   2802: 				$new_part,\%newrecord);
                   2803: 	    }
1.259     banghart 2804:         }
1.44      ng       2805: 	&Apache::lonnet::cstore(\%newrecord,$symb,
1.257     albertel 2806: 				$env{'request.course.id'},$domain,$stuname);
1.380     albertel 2807: 	&check_and_remove_from_queue(\@parts,\%record,\%newrecord,$symb,
                   2808: 				     $cdom,$cnum,$domain,$stuname);
1.41      ng       2809:     }
1.269     raeburn  2810:     if ($aggregateflag) {
                   2811:         &Apache::lonnet::cinc('nohist_resourcetracker',\%aggregate,
1.301     albertel 2812: 			      $cdom,$cnum);
1.269     raeburn  2813:     }
1.301     albertel 2814:     return ('',$pts,$wgt);
1.36      ng       2815: }
1.322     albertel 2816: 
1.380     albertel 2817: sub check_and_remove_from_queue {
                   2818:     my ($parts,$record,$newrecord,$symb,$cdom,$cnum,$domain,$stuname) = @_;
                   2819:     my @ungraded_parts;
                   2820:     foreach my $part (@{$parts}) {
                   2821: 	if (    $record->{   'resource.'.$part.'.awarded'} eq ''
                   2822: 	     && $record->{   'resource.'.$part.'.solved' } ne 'excused'
                   2823: 	     && $newrecord->{'resource.'.$part.'.awarded'} eq ''
                   2824: 	     && $newrecord->{'resource.'.$part.'.solved' } ne 'excused'
                   2825: 		) {
                   2826: 	    push(@ungraded_parts, $part);
                   2827: 	}
                   2828:     }
                   2829:     if ( !@ungraded_parts ) {
                   2830: 	&Apache::bridgetask::remove_from_queue('gradingqueue',$symb,$cdom,
                   2831: 					       $cnum,$domain,$stuname);
                   2832:     }
                   2833: }
                   2834: 
1.337     banghart 2835: sub handback_files {
                   2836:     my ($request,$symb,$stuname,$domain,$newflg,$new_part,$newrecord) = @_;
1.517     raeburn  2837:     my $portfolio_root = '/userfiles/portfolio';
1.582     raeburn  2838:     my $res_error;
                   2839:     my ($partlist,$handgrade,$responseType) = &response_type($symb,\$res_error);
                   2840:     if ($res_error) {
                   2841:         $request->print('<br />'.&navmap_errormsg().'<br />');
                   2842:         return;
                   2843:     }
1.375     albertel 2844:     my @part_response_id = &flatten_responseType($responseType);
                   2845:     foreach my $part_response_id (@part_response_id) {
                   2846:     	my ($part_id,$resp_id) = @{ $part_response_id };
                   2847: 	my $part_resp = join('_',@{ $part_response_id });
1.337     banghart 2848:             if (($env{'form.'.$newflg.'_'.$part_resp.'_returndoc1'}) && ($new_part == $part_id)) {
                   2849:                 # if multiple files are uploaded names will be 'returndoc2','returndoc3'
                   2850:                 my $file_counter = 1;
1.367     albertel 2851: 		my $file_msg;
1.337     banghart 2852:                 while ($env{'form.'.$newflg.'_'.$part_resp.'_returndoc'.$file_counter}) {
                   2853:                     my $fname=$env{'form.'.$newflg.'_'.$part_resp.'_returndoc'.$file_counter.'.filename'};
1.338     banghart 2854:                     my ($directory,$answer_file) = 
                   2855:                         ($env{'form.'.$newflg.'_'.$part_resp.'_origdoc'.$file_counter} =~ /^(.*?)([^\/]*)$/);
                   2856:                     my ($answer_name,$answer_ver,$answer_ext) =
                   2857: 		        &file_name_version_ext($answer_file);
1.355     banghart 2858: 		    my ($portfolio_path) = ($directory =~ /^.+$stuname\/portfolio(.*)/);
1.517     raeburn  2859:                     my $getpropath = 1;
                   2860: 		    my @dir_list = &Apache::lonnet::dirlist($portfolio_root.$portfolio_path,$domain,$stuname,$getpropath);
1.338     banghart 2861: 		    my $version = &get_next_version($answer_name, $answer_ext, \@dir_list);
1.355     banghart 2862:                     # fix file name
                   2863:                     my ($save_file_name) = (($directory.$answer_name.".$version.".$answer_ext) =~ /^.+\/${stuname}\/(.*)/);
                   2864:                     my $result=&Apache::lonnet::finishuserfileupload($stuname,$domain,
                   2865:             	                                $newflg.'_'.$part_resp.'_returndoc'.$file_counter,
                   2866:             	                                $save_file_name);
1.337     banghart 2867:                     if ($result !~ m|^/uploaded/|) {
1.536     raeburn  2868:                         $request->print('<br /><span class="LC_error">'.
                   2869:                             &mt('An error occurred ([_1]) while trying to upload [_2].',
                   2870:                                 $result,$newflg.'_'.$part_resp.'_returndoc'.$file_counter).
                   2871:                                         '</span>');
1.356     banghart 2872:                     } else {
1.360     banghart 2873:                         # mark the file as read only
                   2874:                         my @files = ($save_file_name);
1.372     albertel 2875:                         my @what = ($symb,$env{'request.course.id'},'handback');
1.360     banghart 2876:                         &Apache::lonnet::mark_as_readonly($domain,$stuname,\@files,\@what);
1.367     albertel 2877: 			if (exists($$newrecord{"resource.$new_part.$resp_id.handback"})) {
                   2878: 			    $$newrecord{"resource.$new_part.$resp_id.handback"}.=',';
                   2879: 			}
                   2880:                         $$newrecord{"resource.$new_part.$resp_id.handback"} .= $save_file_name;
                   2881: 			$file_msg.= "\n".'<br /><span class="LC_filename"><a href="/uploaded/'."$domain/$stuname/".$save_file_name.'">'.$save_file_name."</a></span><br />";
                   2882: 
1.337     banghart 2883:                     }
                   2884:                     $request->print("<br />".$fname." will be the uploaded file name");
1.354     albertel 2885:                     $request->print(" ".$env{'form.'.$newflg.'_'.$part_resp.'_origdoc'.$file_counter});
1.337     banghart 2886:                     $file_counter++;
                   2887:                 }
1.367     albertel 2888: 		my $subject = "File Handed Back by Instructor ";
                   2889: 		my $message = "A file has been returned that was originally submitted in reponse to: <br />";
                   2890: 		$message .= "<strong>".&Apache::lonnet::gettitle($symb)."</strong><br />";
                   2891: 		$message .= ' The returned file(s) are named: '. $file_msg;
                   2892: 		$message .= " and can be found in your portfolio space.";
1.418     albertel 2893: 		my ($feedurl,$showsymb) = 
                   2894: 		    &get_feedurl_and_symb($symb,$domain,$stuname);
1.386     raeburn  2895:                 my $restitle = &Apache::lonnet::gettitle($symb);
                   2896: 		my $msgstatus = 
                   2897:                    &Apache::lonmsg::user_normal_msg($stuname,$domain,$subject.
                   2898: 			 ' (File Returned) ['.$restitle.']',$message,undef,
1.418     albertel 2899:                          $feedurl,undef,undef,undef,$showsymb,$restitle);
1.337     banghart 2900:             }
                   2901:         }
1.338     banghart 2902:     return;
1.337     banghart 2903: }
                   2904: 
1.418     albertel 2905: sub get_feedurl_and_symb {
                   2906:     my ($symb,$uname,$udom) = @_;
                   2907:     my (undef,undef,$url) = &Apache::lonnet::decode_symb($symb);
                   2908:     $url = &Apache::lonnet::clutter($url);
                   2909:     my $encrypturl=&Apache::lonnet::EXT('resource.0.encrypturl',
                   2910: 					$symb,$udom,$uname);
                   2911:     if ($encrypturl =~ /^yes$/i) {
                   2912: 	&Apache::lonenc::encrypted(\$url,1);
                   2913: 	&Apache::lonenc::encrypted(\$symb,1);
                   2914:     }
                   2915:     return ($url,$symb);
                   2916: }
                   2917: 
1.313     banghart 2918: sub get_submitted_files {
                   2919:     my ($udom,$uname,$partid,$respid,$record) = @_;
                   2920:     my @files;
                   2921:     if ($$record{"resource.$partid.$respid.portfiles"}) {
                   2922:         my $file_url = '/uploaded/'.$udom.'/'.$uname.'/portfolio';
                   2923:         foreach my $file (split(',',$$record{"resource.$partid.$respid.portfiles"})) {
                   2924:     	    push(@files,$file_url.$file);
                   2925:         }
                   2926:     }
                   2927:     if ($$record{"resource.$partid.$respid.uploadedurl"}) {
                   2928:         push(@files,$$record{"resource.$partid.$respid.uploadedurl"});
                   2929:     }
                   2930:     return (\@files);
                   2931: }
1.322     albertel 2932: 
1.269     raeburn  2933: # ----------- Provides number of tries since last reset.
                   2934: sub get_num_tries {
                   2935:     my ($record,$last_reset,$part) = @_;
                   2936:     my $timestamp = '';
                   2937:     my $num_tries = 0;
                   2938:     if ($$record{'version'}) {
                   2939:         for (my $version=$$record{'version'};$version>=1;$version--) {
                   2940:             if (exists($$record{$version.':resource.'.$part.'.solved'})) {
                   2941:                 $timestamp = $$record{$version.':timestamp'};
                   2942:                 if ($timestamp > $last_reset) {
                   2943:                     $num_tries ++;
                   2944:                 } else {
                   2945:                     last;
                   2946:                 }
                   2947:             }
                   2948:         }
                   2949:     }
                   2950:     return $num_tries;
                   2951: }
                   2952: 
                   2953: # ----------- Determine decrements required in aggregate totals 
                   2954: sub decrement_aggs {
                   2955:     my ($symb,$part,$aggregate,$aggtries,$totaltries,$solvedstatus) = @_;
                   2956:     my %decrement = (
                   2957:                         attempts => 0,
                   2958:                         users => 0,
                   2959:                         correct => 0
                   2960:                     );
                   2961:     $decrement{'attempts'} = $aggtries;
                   2962:     if ($solvedstatus =~ /^correct/) {
                   2963:         $decrement{'correct'} = 1;
                   2964:     }
                   2965:     if ($aggtries == $totaltries) {
                   2966:         $decrement{'users'} = 1;
                   2967:     }
1.524     raeburn  2968:     foreach my $type (keys(%decrement)) {
1.269     raeburn  2969:         $$aggregate{$symb."\0".$part."\0".$type} = -$decrement{$type};
                   2970:     }
                   2971:     return;
                   2972: }
                   2973: 
                   2974: # ----------- Determine timestamps for last reset of aggregate totals for parts  
                   2975: sub get_last_resets {
1.270     albertel 2976:     my ($symb,$courseid,$partids) =@_;
                   2977:     my %last_resets;
1.269     raeburn  2978:     my $cdom = $env{'course.'.$courseid.'.domain'};
                   2979:     my $cname = $env{'course.'.$courseid.'.num'};
1.271     albertel 2980:     my @keys;
                   2981:     foreach my $part (@{$partids}) {
                   2982: 	push(@keys,"$symb\0$part\0resettime");
                   2983:     }
                   2984:     my %results=&Apache::lonnet::get('nohist_resourcetracker',\@keys,
                   2985: 				     $cdom,$cname);
                   2986:     foreach my $part (@{$partids}) {
                   2987: 	$last_resets{$part}=$results{"$symb\0$part\0resettime"};
1.269     raeburn  2988:     }
1.270     albertel 2989:     return %last_resets;
1.269     raeburn  2990: }
                   2991: 
1.251     banghart 2992: # ----------- Handles creating versions for portfolio files as answers
                   2993: sub version_portfiles {
1.343     banghart 2994:     my ($record, $parts_graded, $courseid, $symb, $domain, $stu_name, $v_flag) = @_;
1.263     banghart 2995:     my $version_parts = join('|',@$v_flag);
1.343     banghart 2996:     my @returned_keys;
1.255     banghart 2997:     my $parts = join('|', @$parts_graded);
1.517     raeburn  2998:     my $portfolio_root = '/userfiles/portfolio';
1.277     albertel 2999:     foreach my $key (keys(%$record)) {
1.259     banghart 3000:         my $new_portfiles;
1.263     banghart 3001:         if ($key =~ /^resource\.($version_parts)\./ && $key =~ /\.portfiles$/ ) {
1.342     banghart 3002:             my @versioned_portfiles;
1.367     albertel 3003:             my @portfiles = split(/\s*,\s*/,$$record{$key});
1.252     banghart 3004:             foreach my $file (@portfiles) {
1.306     banghart 3005:                 &Apache::lonnet::unmark_as_readonly($domain,$stu_name,[$symb,$env{'request.course.id'}],$file);
1.304     albertel 3006:                 my ($directory,$answer_file) =($file =~ /^(.*?)([^\/]*)$/);
                   3007: 		my ($answer_name,$answer_ver,$answer_ext) =
                   3008: 		    &file_name_version_ext($answer_file);
1.517     raeburn  3009:                 my $getpropath = 1;    
                   3010:                 my @dir_list = &Apache::lonnet::dirlist($portfolio_root.$directory,$domain,$stu_name,$getpropath);
1.342     banghart 3011:                 my $version = &get_next_version($answer_name, $answer_ext, \@dir_list);
1.306     banghart 3012:                 my $new_answer = &version_selected_portfile($domain, $stu_name, $directory, $answer_file, $version);
                   3013:                 if ($new_answer ne 'problem getting file') {
1.342     banghart 3014:                     push(@versioned_portfiles, $directory.$new_answer);
1.306     banghart 3015:                     &Apache::lonnet::mark_as_readonly($domain,$stu_name,
1.367     albertel 3016:                         [$directory.$new_answer],
1.306     banghart 3017:                         [$symb,$env{'request.course.id'},'graded']);
1.259     banghart 3018:                 }
1.252     banghart 3019:             }
1.343     banghart 3020:             $$record{$key} = join(',',@versioned_portfiles);
                   3021:             push(@returned_keys,$key);
1.251     banghart 3022:         }
                   3023:     } 
1.343     banghart 3024:     return (@returned_keys);   
1.305     banghart 3025: }
                   3026: 
1.307     banghart 3027: sub get_next_version {
1.341     banghart 3028:     my ($answer_name, $answer_ext, $dir_list) = @_;
1.307     banghart 3029:     my $version;
                   3030:     foreach my $row (@$dir_list) {
                   3031:         my ($file) = split(/\&/,$row,2);
                   3032:         my ($file_name,$file_version,$file_ext) =
                   3033: 	    &file_name_version_ext($file);
                   3034:         if (($file_name eq $answer_name) && 
                   3035: 	    ($file_ext eq $answer_ext)) {
                   3036:                 # gets here if filename and extension match, regardless of version
                   3037:                 if ($file_version ne '') {
                   3038:                 # a versioned file is found  so save it for later
                   3039:                 if ($file_version > $version) {
                   3040: 		    $version = $file_version;
                   3041: 	        }
                   3042:             }
                   3043:         }
                   3044:     } 
                   3045:     $version ++;
                   3046:     return($version);
                   3047: }
                   3048: 
1.305     banghart 3049: sub version_selected_portfile {
1.306     banghart 3050:     my ($domain,$stu_name,$directory,$file_name,$version) = @_;
                   3051:     my ($answer_name,$answer_ver,$answer_ext) =
                   3052:         &file_name_version_ext($file_name);
                   3053:     my $new_answer;
                   3054:     $env{'form.copy'} = &Apache::lonnet::getfile("/uploaded/$domain/$stu_name/portfolio$directory$file_name");
                   3055:     if($env{'form.copy'} eq '-1') {
                   3056:         $new_answer = 'problem getting file';
                   3057:     } else {
                   3058:         $new_answer = $answer_name.'.'.$version.'.'.$answer_ext;
                   3059:         my $copy_result = &Apache::lonnet::finishuserfileupload(
                   3060:                             $stu_name,$domain,'copy',
                   3061: 		        '/portfolio'.$directory.$new_answer);
                   3062:     }    
                   3063:     return ($new_answer);
1.251     banghart 3064: }
                   3065: 
1.304     albertel 3066: sub file_name_version_ext {
                   3067:     my ($file)=@_;
                   3068:     my @file_parts = split(/\./, $file);
                   3069:     my ($name,$version,$ext);
                   3070:     if (@file_parts > 1) {
                   3071: 	$ext=pop(@file_parts);
                   3072: 	if (@file_parts > 1 && $file_parts[-1] =~ /^\d+$/) {
                   3073: 	    $version=pop(@file_parts);
                   3074: 	}
                   3075: 	$name=join('.',@file_parts);
                   3076:     } else {
                   3077: 	$name=join('.',@file_parts);
                   3078:     }
                   3079:     return($name,$version,$ext);
                   3080: }
                   3081: 
1.44      ng       3082: #--------------------------------------------------------------------------------------
                   3083: #
                   3084: #-------------------------- Next few routines handles grading by section or whole class
                   3085: #
                   3086: #--- Javascript to handle grading by section or whole class
1.42      ng       3087: sub viewgrades_js {
                   3088:     my ($request) = shift;
                   3089: 
1.539     riegler  3090:     my $alertmsg = &mt('A number equal or greater than 0 is expected. Entered value = ');
1.597     wenzelju 3091:     $request->print(&Apache::lonhtmlcommon::scripttag(<<VIEWJAVASCRIPT));
1.45      ng       3092:    function writePoint(partid,weight,point) {
1.125     ng       3093: 	var radioButton = document.classgrade["RADVAL_"+partid];
                   3094: 	var textbox = document.classgrade["TEXTVAL_"+partid];
1.42      ng       3095: 	if (point == "textval") {
1.125     ng       3096: 	    point = document.classgrade["TEXTVAL_"+partid].value;
1.109     matthew  3097: 	    if (isNaN(point) || parseFloat(point) < 0) {
1.539     riegler  3098: 		alert("$alertmsg"+parseFloat(point));
1.42      ng       3099: 		var resetbox = false;
                   3100: 		for (var i=0; i<radioButton.length; i++) {
                   3101: 		    if (radioButton[i].checked) {
                   3102: 			textbox.value = i;
                   3103: 			resetbox = true;
                   3104: 		    }
                   3105: 		}
                   3106: 		if (!resetbox) {
                   3107: 		    textbox.value = "";
                   3108: 		}
                   3109: 		return;
                   3110: 	    }
1.109     matthew  3111: 	    if (parseFloat(point) > parseFloat(weight)) {
                   3112: 		var resp = confirm("You entered a value ("+parseFloat(point)+
1.44      ng       3113: 				   ") greater than the weight for the part. Accept?");
                   3114: 		if (resp == false) {
                   3115: 		    textbox.value = "";
                   3116: 		    return;
                   3117: 		}
                   3118: 	    }
1.42      ng       3119: 	    for (var i=0; i<radioButton.length; i++) {
                   3120: 		radioButton[i].checked=false;
1.109     matthew  3121: 		if (parseFloat(point) == i) {
1.42      ng       3122: 		    radioButton[i].checked=true;
                   3123: 		}
                   3124: 	    }
1.41      ng       3125: 
1.42      ng       3126: 	} else {
1.125     ng       3127: 	    textbox.value = parseFloat(point);
1.42      ng       3128: 	}
1.41      ng       3129: 	for (i=0;i<document.classgrade.total.value;i++) {
1.125     ng       3130: 	    var user = document.classgrade["ctr"+i].value;
1.289     albertel 3131: 	    user = user.replace(new RegExp(':', 'g'),"_");
1.125     ng       3132: 	    var scorename = document.classgrade["GD_"+user+"_"+partid+"_awarded"];
                   3133: 	    var saveval   = document.classgrade["GD_"+user+"_"+partid+"_solved_s"].value;
                   3134: 	    var selname   = document.classgrade["GD_"+user+"_"+partid+"_solved"];
1.42      ng       3135: 	    if (saveval != "correct") {
                   3136: 		scorename.value = point;
1.43      ng       3137: 		if (selname[0].selected != true) {
                   3138: 		    selname[0].selected = true;
                   3139: 		}
1.42      ng       3140: 	    }
                   3141: 	}
1.125     ng       3142: 	document.classgrade["SELVAL_"+partid][0].selected = true;
1.42      ng       3143:     }
                   3144: 
                   3145:     function writeRadText(partid,weight) {
1.125     ng       3146: 	var selval   = document.classgrade["SELVAL_"+partid];
                   3147: 	var radioButton = document.classgrade["RADVAL_"+partid];
1.265     www      3148:         var override = document.classgrade["FORCE_"+partid].checked;
1.125     ng       3149: 	var textbox = document.classgrade["TEXTVAL_"+partid];
                   3150: 	if (selval[1].selected || selval[2].selected) {
1.42      ng       3151: 	    for (var i=0; i<radioButton.length; i++) {
                   3152: 		radioButton[i].checked=false;
                   3153: 
                   3154: 	    }
                   3155: 	    textbox.value = "";
                   3156: 
                   3157: 	    for (i=0;i<document.classgrade.total.value;i++) {
1.125     ng       3158: 		var user = document.classgrade["ctr"+i].value;
1.289     albertel 3159: 		user = user.replace(new RegExp(':', 'g'),"_");
1.125     ng       3160: 		var scorename = document.classgrade["GD_"+user+"_"+partid+"_awarded"];
                   3161: 		var saveval   = document.classgrade["GD_"+user+"_"+partid+"_solved_s"].value;
                   3162: 		var selname   = document.classgrade["GD_"+user+"_"+partid+"_solved"];
1.265     www      3163: 		if ((saveval != "correct") || override) {
1.42      ng       3164: 		    scorename.value = "";
1.125     ng       3165: 		    if (selval[1].selected) {
                   3166: 			selname[1].selected = true;
                   3167: 		    } else {
                   3168: 			selname[2].selected = true;
                   3169: 			if (Number(document.classgrade["GD_"+user+"_"+partid+"_tries"].value)) 
                   3170: 			{document.classgrade["GD_"+user+"_"+partid+"_tries"].value = '0';}
                   3171: 		    }
1.42      ng       3172: 		}
                   3173: 	    }
1.43      ng       3174: 	} else {
                   3175: 	    for (i=0;i<document.classgrade.total.value;i++) {
1.125     ng       3176: 		var user = document.classgrade["ctr"+i].value;
1.289     albertel 3177: 		user = user.replace(new RegExp(':', 'g'),"_");
1.125     ng       3178: 		var scorename = document.classgrade["GD_"+user+"_"+partid+"_awarded"];
                   3179: 		var saveval   = document.classgrade["GD_"+user+"_"+partid+"_solved_s"].value;
                   3180: 		var selname   = document.classgrade["GD_"+user+"_"+partid+"_solved"];
1.265     www      3181: 		if ((saveval != "correct") || override) {
1.125     ng       3182: 		    scorename.value = document.classgrade["GD_"+user+"_"+partid+"_awarded_s"].value;
1.43      ng       3183: 		    selname[0].selected = true;
                   3184: 		}
                   3185: 	    }
                   3186: 	}	    
1.42      ng       3187:     }
                   3188: 
                   3189:     function changeSelect(partid,user) {
1.125     ng       3190: 	var selval = document.classgrade["GD_"+user+'_'+partid+"_solved"];
                   3191: 	var textbox = document.classgrade["GD_"+user+'_'+partid+"_awarded"];
1.44      ng       3192: 	var point  = textbox.value;
1.125     ng       3193: 	var weight = document.classgrade["weight_"+partid].value;
1.44      ng       3194: 
1.109     matthew  3195: 	if (isNaN(point) || parseFloat(point) < 0) {
1.539     riegler  3196: 	    alert("$alertmsg"+parseFloat(point));
1.44      ng       3197: 	    textbox.value = "";
                   3198: 	    return;
                   3199: 	}
1.109     matthew  3200: 	if (parseFloat(point) > parseFloat(weight)) {
                   3201: 	    var resp = confirm("You entered a value ("+parseFloat(point)+
1.44      ng       3202: 			       ") greater than the weight of the part. Accept?");
                   3203: 	    if (resp == false) {
                   3204: 		textbox.value = "";
                   3205: 		return;
                   3206: 	    }
                   3207: 	}
1.42      ng       3208: 	selval[0].selected = true;
                   3209:     }
                   3210: 
                   3211:     function changeOneScore(partid,user) {
1.125     ng       3212: 	var selval = document.classgrade["GD_"+user+'_'+partid+"_solved"];
                   3213: 	if (selval[1].selected || selval[2].selected) {
                   3214: 	    document.classgrade["GD_"+user+'_'+partid+"_awarded"].value = "";
                   3215: 	    if (selval[2].selected) {
                   3216: 		document.classgrade["GD_"+user+'_'+partid+"_tries"].value = "0";
                   3217: 	    }
1.269     raeburn  3218:         }
1.42      ng       3219:     }
                   3220: 
                   3221:     function resetEntry(numpart) {
                   3222: 	for (ctpart=0;ctpart<numpart;ctpart++) {
1.125     ng       3223: 	    var partid = document.classgrade["partid_"+ctpart].value;
                   3224: 	    var radioButton = document.classgrade["RADVAL_"+partid];
                   3225: 	    var textbox = document.classgrade["TEXTVAL_"+partid];
                   3226: 	    var selval  = document.classgrade["SELVAL_"+partid];
1.42      ng       3227: 	    for (var i=0; i<radioButton.length; i++) {
                   3228: 		radioButton[i].checked=false;
                   3229: 
                   3230: 	    }
                   3231: 	    textbox.value = "";
                   3232: 	    selval[0].selected = true;
                   3233: 
                   3234: 	    for (i=0;i<document.classgrade.total.value;i++) {
1.125     ng       3235: 		var user = document.classgrade["ctr"+i].value;
1.289     albertel 3236: 		user = user.replace(new RegExp(':', 'g'),"_");
1.125     ng       3237: 		var resetscore = document.classgrade["GD_"+user+"_"+partid+"_awarded"];
                   3238: 		resetscore.value = document.classgrade["GD_"+user+"_"+partid+"_awarded_s"].value;
                   3239: 		var resettries = document.classgrade["GD_"+user+"_"+partid+"_tries"];
                   3240: 		resettries.value = document.classgrade["GD_"+user+"_"+partid+"_tries_s"].value;
                   3241: 		var saveselval   = document.classgrade["GD_"+user+"_"+partid+"_solved_s"].value;
                   3242: 		var selname   = document.classgrade["GD_"+user+"_"+partid+"_solved"];
1.42      ng       3243: 		if (saveselval == "excused") {
1.43      ng       3244: 		    if (selname[1].selected == false) { selname[1].selected = true;}
1.42      ng       3245: 		} else {
1.43      ng       3246: 		    if (selname[0].selected == false) {selname[0].selected = true};
1.42      ng       3247: 		}
                   3248: 	    }
1.41      ng       3249: 	}
1.42      ng       3250:     }
                   3251: 
1.41      ng       3252: VIEWJAVASCRIPT
1.42      ng       3253: }
                   3254: 
1.44      ng       3255: #--- show scores for a section or whole class w/ option to change/update a score
1.42      ng       3256: sub viewgrades {
1.608     www      3257:     my ($request,$symb) = @_;
1.42      ng       3258:     &viewgrades_js($request);
1.41      ng       3259: 
1.168     albertel 3260:     #need to make sure we have the correct data for later EXT calls, 
                   3261:     #thus invalidate the cache
                   3262:     &Apache::lonnet::devalidatecourseresdata(
1.257     albertel 3263:                  $env{'course.'.$env{'request.course.id'}.'.num'},
                   3264:                  $env{'course.'.$env{'request.course.id'}.'.domain'});
1.168     albertel 3265:     &Apache::lonnet::clear_EXT_cache_status();
                   3266: 
1.398     albertel 3267:     my $result='<h3><span class="LC_info">'.&mt('Manual Grading').'</span></h3>';
1.41      ng       3268: 
                   3269:     #view individual student submission form - called using Javascript viewOneStudent
1.324     albertel 3270:     $result.=&jscriptNform($symb);
1.41      ng       3271: 
1.44      ng       3272:     #beginning of class grading form
1.442     banghart 3273:     my $stu_status = join(':',&Apache::loncommon::get_env_multiple('form.Status'));
1.41      ng       3274:     $result.= '<form action="/adm/grades" method="post" name="classgrade">'."\n".
1.418     albertel 3275: 	'<input type="hidden" name="symb"    value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
1.38      ng       3276: 	'<input type="hidden" name="command" value="editgrades" />'."\n".
1.432     banghart 3277: 	&build_section_inputs().
1.442     banghart 3278: 	'<input type="hidden" name="Status" value="'.$env{'stu_status'}.'" />'."\n".
1.72      ng       3279: 
1.560     raeburn  3280:     my ($common_header,$specific_header);
1.257     albertel 3281:     if ($env{'form.section'} eq 'all') {
1.560     raeburn  3282: 	$common_header = &mt('Assign Common Grade to Class');
                   3283:         $specific_header = &mt('Assign Grade to Specific Students in Class');
1.257     albertel 3284:     } elsif ($env{'form.section'} eq 'none') {
1.560     raeburn  3285:         $common_header = &mt('Assign Common Grade to Students in no Section');
                   3286: 	$specific_header = &mt('Assign Grade to Specific Students in no Section');
1.52      albertel 3287:     } else {
1.560     raeburn  3288:         my $section_display = join (", ",&Apache::loncommon::get_env_multiple('form.section'));
                   3289:         $common_header = &mt('Assign Common Grade to Students in Section(s) [_1]',$section_display);
                   3290: 	$specific_header = &mt('Assign Grade to Specific Students in Section(s) [_1]',$section_display);
1.52      albertel 3291:     }
1.560     raeburn  3292:     $result.= '<h3>'.$common_header.'</h3>'.&Apache::loncommon::start_data_table();
1.44      ng       3293:     #radio buttons/text box for assigning points for a section or class.
                   3294:     #handles different parts of a problem
1.582     raeburn  3295:     my $res_error;
                   3296:     my ($partlist,$handgrade,$responseType) = &response_type($symb,\$res_error);
                   3297:     if ($res_error) {
                   3298:         return &navmap_errormsg();
                   3299:     }
1.42      ng       3300:     my %weight = ();
                   3301:     my $ctsparts = 0;
1.45      ng       3302:     my %seen = ();
1.375     albertel 3303:     my @part_response_id = &flatten_responseType($responseType);
                   3304:     foreach my $part_response_id (@part_response_id) {
                   3305:     	my ($partid,$respid) = @{ $part_response_id };
                   3306: 	my $part_resp = join('_',@{ $part_response_id });
1.45      ng       3307: 	next if $seen{$partid};
                   3308: 	$seen{$partid}++;
1.375     albertel 3309: 	my $handgrade=$$handgrade{$part_resp};
1.42      ng       3310: 	my $wgt = &Apache::lonnet::EXT('resource.'.$partid.'.weight',$symb);
                   3311: 	$weight{$partid} = $wgt eq '' ? '1' : $wgt;
                   3312: 
1.324     albertel 3313: 	my $display_part=&get_display_part($partid,$symb);
1.485     albertel 3314: 	my $radio.='<table border="0"><tr>';  
1.41      ng       3315: 	my $ctr = 0;
1.42      ng       3316: 	while ($ctr<=$weight{$partid}) { # display radio buttons in a nice table 10 across
1.485     albertel 3317: 	    $radio.= '<td><label><input type="radio" name="RADVAL_'.$partid.'" '.
1.54      albertel 3318: 		'onclick="javascript:writePoint(\''.$partid.'\','.$weight{$partid}.
1.288     albertel 3319: 		','.$ctr.')" />'.$ctr."</label></td>\n";
1.41      ng       3320: 	    $result.=(($ctr+1)%10 == 0 ? '</tr><tr>' : '');
                   3321: 	    $ctr++;
                   3322: 	}
1.485     albertel 3323: 	$radio.='</tr></table>';
                   3324: 	my $line = '<input type="text" name="TEXTVAL_'.
1.589     bisitz   3325: 	    $partid.'" size="4" '.'onchange="javascript:writePoint(\''.
1.54      albertel 3326: 		$partid.'\','.$weight{$partid}.',\'textval\')" /> /'.
1.539     riegler  3327: 	    $weight{$partid}.' '.&mt('(problem weight)').'</td>'."\n";
                   3328: 	$line.= '<td><b>'.&mt('Grade Status').':</b><select name="SELVAL_'.$partid.'"'.
1.589     bisitz   3329: 	    'onchange="javascript:writeRadText(\''.$partid.'\','.
1.59      albertel 3330: 		$weight{$partid}.')"> '.
1.401     albertel 3331: 	    '<option selected="selected"> </option>'.
1.485     albertel 3332: 	    '<option value="excused">'.&mt('excused').'</option>'.
                   3333: 	    '<option value="reset status">'.&mt('reset status').'</option>'.
                   3334: 	    '</select></td>'.
                   3335:             '<td><label><input type="checkbox" name="FORCE_'.$partid.'" />'.&mt('Override "Correct"').'</label>';
                   3336: 	$line.='<input type="hidden" name="partid_'.
                   3337: 	    $ctsparts.'" value="'.$partid.'" />'."\n";
                   3338: 	$line.='<input type="hidden" name="weight_'.
                   3339: 	    $partid.'" value="'.$weight{$partid}.'" />'."\n";
                   3340: 
                   3341: 	$result.=
                   3342: 	    &Apache::loncommon::start_data_table_row()."\n".
1.577     bisitz   3343: 	    '<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 3344: 	    &Apache::loncommon::end_data_table_row()."\n";
1.42      ng       3345: 	$ctsparts++;
1.41      ng       3346:     }
1.474     albertel 3347:     $result.=&Apache::loncommon::end_data_table()."\n".
1.52      albertel 3348: 	'<input type="hidden" name="totalparts" value="'.$ctsparts.'" />';
1.485     albertel 3349:     $result.='<input type="button" value="'.&mt('Revert to Default').'" '.
1.589     bisitz   3350: 	'onclick="javascript:resetEntry('.$ctsparts.');" />';
1.41      ng       3351: 
1.44      ng       3352:     #table listing all the students in a section/class
                   3353:     #header of table
1.560     raeburn  3354:     $result.= '<h3>'.$specific_header.'</h3>'.
                   3355:               &Apache::loncommon::start_data_table().
                   3356: 	      &Apache::loncommon::start_data_table_header_row().
                   3357: 	      '<th>'.&mt('No.').'</th>'.
                   3358: 	      '<th>'.&nameUserString('header')."</th>\n";
1.582     raeburn  3359:     my $partserror;
                   3360:     my (@parts) = sort(&getpartlist($symb,\$partserror));
                   3361:     if ($partserror) {
                   3362:         return &navmap_errormsg();
                   3363:     }
1.324     albertel 3364:     my (undef,undef,$url)=&Apache::lonnet::decode_symb($symb);
1.269     raeburn  3365:     my @partids = ();
1.41      ng       3366:     foreach my $part (@parts) {
                   3367: 	my $display=&Apache::lonnet::metadata($url,$part.'.display');
1.539     riegler  3368:         my $narrowtext = &mt('Tries');
                   3369: 	$display =~ s|^Number of Attempts|$narrowtext <br />|; # makes the column narrower
1.41      ng       3370: 	if  (!$display) { $display = &Apache::lonnet::metadata($url,$part.'.name'); }
1.207     albertel 3371: 	my ($partid) = &split_part_type($part);
1.524     raeburn  3372:         push(@partids,$partid);
1.628     www      3373: #
                   3374: # FIXME: Looks like $display looks at English text
                   3375: #
1.324     albertel 3376: 	my $display_part=&get_display_part($partid,$symb);
1.41      ng       3377: 	if ($display =~ /^Partial Credit Factor/) {
1.485     albertel 3378: 	    $result.='<th>'.
                   3379: 		&mt('Score Part: [_1]<br /> (weight = [_2])',
                   3380: 		    $display_part,$weight{$partid}).'</th>'."\n";
1.41      ng       3381: 	    next;
1.485     albertel 3382: 	    
1.207     albertel 3383: 	} else {
1.485     albertel 3384: 	    if ($display =~ /Problem Status/) {
                   3385: 		my $grade_status_mt = &mt('Grade Status');
                   3386: 		$display =~ s{Problem Status}{$grade_status_mt<br />};
                   3387: 	    }
                   3388: 	    my $part_mt = &mt('Part:');
                   3389: 	    $display =~s{\[Part: \Q$partid\E\]}{$part_mt $display_part};
1.41      ng       3390: 	}
1.485     albertel 3391: 
1.474     albertel 3392: 	$result.='<th>'.$display.'</th>'."\n";
1.41      ng       3393:     }
1.474     albertel 3394:     $result.=&Apache::loncommon::end_data_table_header_row();
1.44      ng       3395: 
1.270     albertel 3396:     my %last_resets = 
                   3397: 	&get_last_resets($symb,$env{'request.course.id'},\@partids);
1.269     raeburn  3398: 
1.41      ng       3399:     #get info for each student
1.44      ng       3400:     #list all the students - with points and grade status
1.257     albertel 3401:     my (undef,undef,$fullname) = &getclasslist($env{'form.section'},'1');
1.41      ng       3402:     my $ctr = 0;
1.294     albertel 3403:     foreach (sort 
                   3404: 	     {
                   3405: 		 if (lc($$fullname{$a}) ne lc($$fullname{$b})) {
                   3406: 		     return (lc($$fullname{$a}) cmp lc($$fullname{$b}));
                   3407: 		 }
                   3408: 		 return $a cmp $b;
                   3409: 	     } (keys(%$fullname))) {
1.126     ng       3410: 	$ctr++;
1.324     albertel 3411: 	$result.=&viewstudentgrade($symb,$env{'request.course.id'},
1.269     raeburn  3412: 				   $_,$$fullname{$_},\@parts,\%weight,$ctr,\%last_resets);
1.41      ng       3413:     }
1.474     albertel 3414:     $result.=&Apache::loncommon::end_data_table();
1.41      ng       3415:     $result.='<input type="hidden" name="total" value="'.$ctr.'" />'."\n";
1.485     albertel 3416:     $result.='<input type="button" value="'.&mt('Save').'" '.
1.589     bisitz   3417: 	'onclick="javascript:submit();" target="_self" /></form>'."\n";
1.96      albertel 3418:     if (scalar(%$fullname) eq 0) {
                   3419: 	my $colspan=3+scalar(@parts);
1.433     banghart 3420: 	my $section_display = join (", ",&Apache::loncommon::get_env_multiple('form.section'));
1.442     banghart 3421:         my $stu_status = join(' or ',&Apache::loncommon::get_env_multiple('form.Status'));
1.433     banghart 3422: 	$result='<span class="LC_warning">'.
1.485     albertel 3423: 	    &mt('There are no students in section(s) [_1] with enrollment status [_2] to modify or grade.',
1.442     banghart 3424: 	        $section_display, $stu_status).
1.433     banghart 3425: 	    '</span>';
1.96      albertel 3426:     }
1.41      ng       3427:     return $result;
                   3428: }
                   3429: 
1.44      ng       3430: #--- call by previous routine to display each student
1.41      ng       3431: sub viewstudentgrade {
1.324     albertel 3432:     my ($symb,$courseid,$student,$fullname,$parts,$weight,$ctr,$last_resets) = @_;
1.44      ng       3433:     my ($uname,$udom) = split(/:/,$student);
                   3434:     my %record=&Apache::lonnet::restore($symb,$courseid,$udom,$uname);
1.269     raeburn  3435:     my %aggregates = (); 
1.474     albertel 3436:     my $result=&Apache::loncommon::start_data_table_row().'<td align="right">'.
1.233     albertel 3437: 	'<input type="hidden" name="ctr'.($ctr-1).'" value="'.$student.'" />'.
                   3438: 	"\n".$ctr.'&nbsp;</td><td>&nbsp;'.
1.44      ng       3439: 	'<a href="javascript:viewOneStudent(\''.$uname.'\',\''.$udom.
1.417     albertel 3440: 	'\');" target="_self">'.$fullname.'</a> '.
1.398     albertel 3441: 	'<span class="LC_internal_info">('.$uname.($env{'user.domain'} eq $udom ? '' : ':'.$udom).')</span></td>'."\n";
1.281     albertel 3442:     $student=~s/:/_/; # colon doen't work in javascript for names
1.63      albertel 3443:     foreach my $apart (@$parts) {
                   3444: 	my ($part,$type) = &split_part_type($apart);
1.41      ng       3445: 	my $score=$record{"resource.$part.$type"};
1.276     albertel 3446:         $result.='<td align="center">';
1.269     raeburn  3447:         my ($aggtries,$totaltries);
                   3448:         unless (exists($aggregates{$part})) {
1.270     albertel 3449: 	    $totaltries = $record{'resource.'.$part.'.tries'};
                   3450: 
                   3451: 	    $aggtries = $totaltries;
1.269     raeburn  3452:             if ($$last_resets{$part}) {  
1.270     albertel 3453:                 $aggtries = &get_num_tries(\%record,$$last_resets{$part},
                   3454: 					   $part);
                   3455:             }
1.269     raeburn  3456:             $result.='<input type="hidden" name="'.
                   3457:                 'GD_'.$student.'_'.$part.'_aggtries" value="'.$aggtries.'" />'."\n";
                   3458:             $result.='<input type="hidden" name="'.
                   3459:                 'GD_'.$student.'_'.$part.'_totaltries" value="'.$totaltries.'" />'."\n";
                   3460:             $aggregates{$part} = 1;
                   3461:         }
1.41      ng       3462: 	if ($type eq 'awarded') {
1.320     albertel 3463: 	    my $pts = $score eq '' ? '' : &compute_points($score,$$weight{$part});
1.42      ng       3464: 	    $result.='<input type="hidden" name="'.
1.89      albertel 3465: 		'GD_'.$student.'_'.$part.'_awarded_s" value="'.$pts.'" />'."\n";
1.233     albertel 3466: 	    $result.='<input type="text" name="'.
1.89      albertel 3467: 		'GD_'.$student.'_'.$part.'_awarded" '.
1.589     bisitz   3468:                 'onchange="javascript:changeSelect(\''.$part.'\',\''.$student.
1.44      ng       3469: 		'\')" value="'.$pts.'" size="4" /></td>'."\n";
1.41      ng       3470: 	} elsif ($type eq 'solved') {
                   3471: 	    my ($status,$foo)=split(/_/,$score,2);
                   3472: 	    $status = 'nothing' if ($status eq '');
1.89      albertel 3473: 	    $result.='<input type="hidden" name="'.'GD_'.$student.'_'.
1.54      albertel 3474: 		$part.'_solved_s" value="'.$status.'" />'."\n";
1.233     albertel 3475: 	    $result.='&nbsp;<select name="'.
1.89      albertel 3476: 		'GD_'.$student.'_'.$part.'_solved" '.
1.589     bisitz   3477:                 'onchange="javascript:changeOneScore(\''.$part.'\',\''.$student.'\')" >'."\n";
1.485     albertel 3478: 	    $result.= (($status eq 'excused') ? '<option> </option><option selected="selected" value="excused">'.&mt('excused').'</option>' 
                   3479: 		: '<option selected="selected"> </option><option value="excused">'.&mt('excused').'</option>')."\n";
                   3480: 	    $result.='<option value="reset status">'.&mt('reset status').'</option>';
1.126     ng       3481: 	    $result.="</select>&nbsp;</td>\n";
1.122     ng       3482: 	} else {
                   3483: 	    $result.='<input type="hidden" name="'.
                   3484: 		'GD_'.$student.'_'.$part.'_'.$type.'_s" value="'.$score.'" />'.
                   3485: 		    "\n";
1.233     albertel 3486: 	    $result.='<input type="text" name="'.
1.122     ng       3487: 		'GD_'.$student.'_'.$part.'_'.$type.'" '.
                   3488: 		'value="'.$score.'" size="4" /></td>'."\n";
1.41      ng       3489: 	}
                   3490:     }
1.474     albertel 3491:     $result.=&Apache::loncommon::end_data_table_row();
1.41      ng       3492:     return $result;
1.38      ng       3493: }
                   3494: 
1.44      ng       3495: #--- change scores for all the students in a section/class
                   3496: #    record does not get update if unchanged
1.38      ng       3497: sub editgrades {
1.608     www      3498:     my ($request,$symb) = @_;
1.41      ng       3499: 
1.433     banghart 3500:     my $section_display = join (", ",&Apache::loncommon::get_env_multiple('form.section'));
1.477     albertel 3501:     my $title='<h2>'.&mt('Current Grade Status').'</h2>';
1.433     banghart 3502:     $title.='<h4>'.&mt('<b>Section: </b>[_1]',$section_display).'</h4>'."\n";
1.126     ng       3503: 
1.477     albertel 3504:     my $result= &Apache::loncommon::start_data_table().
                   3505: 	&Apache::loncommon::start_data_table_header_row().
                   3506: 	'<th rowspan="2" valign="middle">'.&mt('No.').'</th>'.
                   3507: 	'<th rowspan="2" valign="middle">'.&nameUserString('header')."</th>\n";
1.43      ng       3508:     my %scoreptr = (
                   3509: 		    'correct'  =>'correct_by_override',
                   3510: 		    'incorrect'=>'incorrect_by_override',
                   3511: 		    'excused'  =>'excused',
                   3512: 		    'ungraded' =>'ungraded_attempted',
1.596     raeburn  3513:                     'credited' =>'credit_attempted',
1.43      ng       3514: 		    'nothing'  => '',
                   3515: 		    );
1.257     albertel 3516:     my ($classlist,undef,$fullname) = &getclasslist($env{'form.section'},'0');
1.34      ng       3517: 
1.44      ng       3518:     my (@partid);
                   3519:     my %weight = ();
1.54      albertel 3520:     my %columns = ();
1.44      ng       3521:     my ($i,$ctr,$count,$rec_update) = (0,0,0,0);
1.54      albertel 3522: 
1.582     raeburn  3523:     my $partserror;
                   3524:     my (@parts) = sort(&getpartlist($symb,\$partserror));
                   3525:     if ($partserror) {
                   3526:         return &navmap_errormsg();
                   3527:     }
1.54      albertel 3528:     my $header;
1.257     albertel 3529:     while ($ctr < $env{'form.totalparts'}) {
                   3530: 	my $partid = $env{'form.partid_'.$ctr};
1.524     raeburn  3531: 	push(@partid,$partid);
1.257     albertel 3532: 	$weight{$partid} = $env{'form.weight_'.$partid};
1.44      ng       3533: 	$ctr++;
1.54      albertel 3534:     }
1.324     albertel 3535:     my (undef,undef,$url) = &Apache::lonnet::decode_symb($symb);
1.54      albertel 3536:     foreach my $partid (@partid) {
1.478     albertel 3537: 	$header .= '<th align="center">'.&mt('Old Score').'</th>'.
                   3538: 	    '<th align="center">'.&mt('New Score').'</th>';
1.54      albertel 3539: 	$columns{$partid}=2;
                   3540: 	foreach my $stores (@parts) {
                   3541: 	    my ($part,$type) = &split_part_type($stores);
                   3542: 	    if ($part !~ m/^\Q$partid\E/) { next;}
                   3543: 	    if ($type eq 'awarded' || $type eq 'solved') { next; }
                   3544: 	    my $display=&Apache::lonnet::metadata($url,$stores.'.display');
1.551     raeburn  3545: 	    $display =~ s/\[Part: \Q$part\E\]//;
1.539     riegler  3546:             my $narrowtext = &mt('Tries');
                   3547: 	    $display =~ s/Number of Attempts/$narrowtext/;
                   3548: 	    $header .= '<th align="center">'.&mt('Old').' '.$display.'</th>'.
                   3549: 		'<th align="center">'.&mt('New').' '.$display.'</th>';
1.54      albertel 3550: 	    $columns{$partid}+=2;
                   3551: 	}
                   3552:     }
                   3553:     foreach my $partid (@partid) {
1.324     albertel 3554: 	my $display_part=&get_display_part($partid,$symb);
1.478     albertel 3555: 	$result .= '<th colspan="'.$columns{$partid}.'" align="center">'.
                   3556: 	    &mt('Part: [_1] (Weight = [_2])',$display_part,$weight{$partid}).
                   3557: 	    '</th>';
1.54      albertel 3558: 
1.44      ng       3559:     }
1.477     albertel 3560:     $result .= &Apache::loncommon::end_data_table_header_row().
                   3561: 	&Apache::loncommon::start_data_table_header_row().
                   3562: 	$header.
                   3563: 	&Apache::loncommon::end_data_table_header_row();
                   3564:     my @noupdate;
1.126     ng       3565:     my ($updateCtr,$noupdateCtr) = (1,1);
1.257     albertel 3566:     for ($i=0; $i<$env{'form.total'}; $i++) {
1.93      albertel 3567: 	my $line;
1.257     albertel 3568: 	my $user = $env{'form.ctr'.$i};
1.281     albertel 3569: 	my ($uname,$udom)=split(/:/,$user);
1.44      ng       3570: 	my %newrecord;
                   3571: 	my $updateflag = 0;
1.281     albertel 3572: 	$line .= '<td>'.&nameUserString(undef,$$fullname{$user},$uname,$udom).'</td>';
1.108     albertel 3573: 	my $usec=$classlist->{"$uname:$udom"}[5];
1.105     albertel 3574: 	if (!&canmodify($usec)) {
1.126     ng       3575: 	    my $numcols=scalar(@partid)*4+2;
1.477     albertel 3576: 	    push(@noupdate,
1.478     albertel 3577: 		 $line."<td colspan=\"$numcols\"><span class=\"LC_warning\">".
                   3578: 		 &mt('Not allowed to modify student')."</span></td></tr>");
1.105     albertel 3579: 	    next;
                   3580: 	}
1.269     raeburn  3581:         my %aggregate = ();
                   3582:         my $aggregateflag = 0;
1.281     albertel 3583: 	$user=~s/:/_/; # colon doen't work in javascript for names
1.44      ng       3584: 	foreach (@partid) {
1.257     albertel 3585: 	    my $old_aw    = $env{'form.GD_'.$user.'_'.$_.'_awarded_s'};
1.54      albertel 3586: 	    my $old_part_pcr = $old_aw/($weight{$_} ne '0' ? $weight{$_}:1);
                   3587: 	    my $old_part  = $old_aw eq '' ? '' : $old_part_pcr;
1.257     albertel 3588: 	    my $old_score = $scoreptr{$env{'form.GD_'.$user.'_'.$_.'_solved_s'}};
                   3589: 	    my $awarded   = $env{'form.GD_'.$user.'_'.$_.'_awarded'};
1.54      albertel 3590: 	    my $pcr       = $awarded/($weight{$_} ne '0' ? $weight{$_} : 1);
                   3591: 	    my $partial   = $awarded eq '' ? '' : $pcr;
1.44      ng       3592: 	    my $score;
                   3593: 	    if ($partial eq '') {
1.257     albertel 3594: 		$score = $scoreptr{$env{'form.GD_'.$user.'_'.$_.'_solved_s'}};
1.44      ng       3595: 	    } elsif ($partial > 0) {
                   3596: 		$score = 'correct_by_override';
                   3597: 	    } elsif ($partial == 0) {
                   3598: 		$score = 'incorrect_by_override';
                   3599: 	    }
1.257     albertel 3600: 	    my $dropMenu = $env{'form.GD_'.$user.'_'.$_.'_solved'};
1.125     ng       3601: 	    $score = 'excused' if (($dropMenu eq 'excused') && ($score ne 'excused'));
                   3602: 
1.292     albertel 3603: 	    $newrecord{'resource.'.$_.'.regrader'}=
                   3604: 		"$env{'user.name'}:$env{'user.domain'}";
1.125     ng       3605: 	    if ($dropMenu eq 'reset status' &&
                   3606: 		$old_score ne '') { # ignore if no previous attempts => nothing to reset
1.299     albertel 3607: 		$newrecord{'resource.'.$_.'.tries'} = '';
1.125     ng       3608: 		$newrecord{'resource.'.$_.'.solved'} = '';
                   3609: 		$newrecord{'resource.'.$_.'.award'} = '';
1.299     albertel 3610: 		$newrecord{'resource.'.$_.'.awarded'} = '';
1.125     ng       3611: 		$updateflag = 1;
1.269     raeburn  3612:                 if ($env{'form.GD_'.$user.'_'.$_.'_aggtries'} > 0) {
                   3613:                     my $aggtries = $env{'form.GD_'.$user.'_'.$_.'_aggtries'};
                   3614:                     my $totaltries = $env{'form.GD_'.$user.'_'.$_.'_totaltries'};
                   3615:                     my $solvedstatus = $env{'form.GD_'.$user.'_'.$_.'_solved_s'};
                   3616:                     &decrement_aggs($symb,$_,\%aggregate,$aggtries,$totaltries,$solvedstatus);
                   3617:                     $aggregateflag = 1;
                   3618:                 }
1.139     albertel 3619: 	    } elsif (!($old_part eq $partial && $old_score eq $score)) {
                   3620: 		$updateflag = 1;
                   3621: 		$newrecord{'resource.'.$_.'.awarded'}  = $partial if $partial ne '';
                   3622: 		$newrecord{'resource.'.$_.'.solved'}   = $score;
                   3623: 		$rec_update++;
1.125     ng       3624: 	    }
                   3625: 
1.93      albertel 3626: 	    $line .= '<td align="center">'.$old_aw.'&nbsp;</td>'.
1.44      ng       3627: 		'<td align="center">'.$awarded.
                   3628: 		($score eq 'excused' ? $score : '').'&nbsp;</td>';
1.5       albertel 3629: 
1.54      albertel 3630: 
                   3631: 	    my $partid=$_;
                   3632: 	    foreach my $stores (@parts) {
                   3633: 		my ($part,$type) = &split_part_type($stores);
                   3634: 		if ($part !~ m/^\Q$partid\E/) { next;}
                   3635: 		if ($type eq 'awarded' || $type eq 'solved') { next; }
1.257     albertel 3636: 		my $old_aw    = $env{'form.GD_'.$user.'_'.$part.'_'.$type.'_s'};
                   3637: 		my $awarded   = $env{'form.GD_'.$user.'_'.$part.'_'.$type};
1.54      albertel 3638: 		if ($awarded ne '' && $awarded ne $old_aw) {
                   3639: 		    $newrecord{'resource.'.$part.'.'.$type}= $awarded;
1.257     albertel 3640: 		    $newrecord{'resource.'.$part.'.regrader'}="$env{'user.name'}:$env{'user.domain'}";
1.54      albertel 3641: 		    $updateflag=1;
                   3642: 		}
1.93      albertel 3643: 		$line .= '<td align="center">'.$old_aw.'&nbsp;</td>'.
1.54      albertel 3644: 		    '<td align="center">'.$awarded.'&nbsp;</td>';
                   3645: 	    }
1.44      ng       3646: 	}
1.477     albertel 3647: 	$line.="\n";
1.301     albertel 3648: 
                   3649: 	my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   3650: 	my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   3651: 
1.44      ng       3652: 	if ($updateflag) {
                   3653: 	    $count++;
1.257     albertel 3654: 	    &Apache::lonnet::cstore(\%newrecord,$symb,$env{'request.course.id'},
1.89      albertel 3655: 				    $udom,$uname);
1.301     albertel 3656: 
                   3657: 	    if (&Apache::bridgetask::in_queue('gradingqueue',$symb,$cdom,
                   3658: 					      $cnum,$udom,$uname)) {
                   3659: 		# need to figure out if should be in queue.
                   3660: 		my %record =  
                   3661: 		    &Apache::lonnet::restore($symb,$env{'request.course.id'},
                   3662: 					     $udom,$uname);
                   3663: 		my $all_graded = 1;
                   3664: 		my $none_graded = 1;
                   3665: 		foreach my $part (@parts) {
                   3666: 		    if ( $record{'resource.'.$part.'.awarded'} eq '' ) {
                   3667: 			$all_graded = 0;
                   3668: 		    } else {
                   3669: 			$none_graded = 0;
                   3670: 		    }
                   3671: 		}
                   3672: 
                   3673: 		if ($all_graded || $none_graded) {
                   3674: 		    &Apache::bridgetask::remove_from_queue('gradingqueue',
                   3675: 							   $symb,$cdom,$cnum,
                   3676: 							   $udom,$uname);
                   3677: 		}
                   3678: 	    }
                   3679: 
1.477     albertel 3680: 	    $result.=&Apache::loncommon::start_data_table_row().
                   3681: 		'<td align="right">&nbsp;'.$updateCtr.'&nbsp;</td>'.$line.
                   3682: 		&Apache::loncommon::end_data_table_row();
1.126     ng       3683: 	    $updateCtr++;
1.93      albertel 3684: 	} else {
1.477     albertel 3685: 	    push(@noupdate,
                   3686: 		 '<td align="right">&nbsp;'.$noupdateCtr.'&nbsp;</td>'.$line);
1.126     ng       3687: 	    $noupdateCtr++;
1.44      ng       3688: 	}
1.269     raeburn  3689:         if ($aggregateflag) {
                   3690:             &Apache::lonnet::cinc('nohist_resourcetracker',\%aggregate,
1.301     albertel 3691: 				  $cdom,$cnum);
1.269     raeburn  3692:         }
1.93      albertel 3693:     }
1.477     albertel 3694:     if (@noupdate) {
1.126     ng       3695: #	my $numcols=(scalar(@partid)*(scalar(@parts)-1)*2)+3;
                   3696: 	my $numcols=scalar(@partid)*4+2;
1.477     albertel 3697: 	$result .= &Apache::loncommon::start_data_table_row('LC_empty_row').
1.478     albertel 3698: 	    '<td align="center" colspan="'.$numcols.'">'.
                   3699: 	    &mt('No Changes Occurred For the Students Below').
                   3700: 	    '</td>'.
1.477     albertel 3701: 	    &Apache::loncommon::end_data_table_row();
                   3702: 	foreach my $line (@noupdate) {
                   3703: 	    $result.=
                   3704: 		&Apache::loncommon::start_data_table_row().
                   3705: 		$line.
                   3706: 		&Apache::loncommon::end_data_table_row();
                   3707: 	}
1.44      ng       3708:     }
1.614     www      3709:     $result .= &Apache::loncommon::end_data_table();
1.478     albertel 3710:     my $msg = '<p><b>'.
                   3711: 	&mt('Number of records updated = [_1] for [quant,_2,student].',
                   3712: 	    $rec_update,$count).'</b><br />'.
                   3713: 	'<b>'.&mt('Total number of students = [_1]',$env{'form.total'}).
                   3714: 	'</b></p>';
1.44      ng       3715:     return $title.$msg.$result;
1.5       albertel 3716: }
1.54      albertel 3717: 
                   3718: sub split_part_type {
                   3719:     my ($partstr) = @_;
                   3720:     my ($temp,@allparts)=split(/_/,$partstr);
                   3721:     my $type=pop(@allparts);
1.439     albertel 3722:     my $part=join('_',@allparts);
1.54      albertel 3723:     return ($part,$type);
                   3724: }
                   3725: 
1.44      ng       3726: #------------- end of section for handling grading by section/class ---------
                   3727: #
                   3728: #----------------------------------------------------------------------------
                   3729: 
1.5       albertel 3730: 
1.44      ng       3731: #----------------------------------------------------------------------------
                   3732: #
                   3733: #-------------------------- Next few routines handles grading by csv upload
                   3734: #
                   3735: #--- Javascript to handle csv upload
1.27      albertel 3736: sub csvupload_javascript_reverse_associate {
1.573     bisitz   3737:     my $error1=&mt('You need to specify the username or the student/employee ID');
1.246     albertel 3738:     my $error2=&mt('You need to specify at least one grading field');
1.27      albertel 3739:   return(<<ENDPICK);
                   3740:   function verify(vf) {
                   3741:     var foundsomething=0;
                   3742:     var founduname=0;
1.243     albertel 3743:     var foundID=0;
1.27      albertel 3744:     for (i=0;i<=vf.nfields.value;i++) {
                   3745:       tw=eval('vf.f'+i+'.selectedIndex');
1.243     albertel 3746:       if (i==0 && tw!=0) { foundID=1; }
                   3747:       if (i==1 && tw!=0) { founduname=1; }
                   3748:       if (i!=0 && i!=1 && i!=2 && tw!=0) { foundsomething=1; }
1.27      albertel 3749:     }
1.246     albertel 3750:     if (founduname==0 && foundID==0) {
                   3751: 	alert('$error1');
                   3752: 	return;
1.27      albertel 3753:     }
                   3754:     if (foundsomething==0) {
1.246     albertel 3755: 	alert('$error2');
                   3756: 	return;
1.27      albertel 3757:     }
                   3758:     vf.submit();
                   3759:   }
                   3760:   function flip(vf,tf) {
                   3761:     var nw=eval('vf.f'+tf+'.selectedIndex');
                   3762:     var i;
                   3763:     for (i=0;i<=vf.nfields.value;i++) {
                   3764:       //can not pick the same destination field for both name and domain
                   3765:       if (((i ==0)||(i ==1)) && 
                   3766:           ((tf==0)||(tf==1)) && 
                   3767:           (i!=tf) &&
                   3768:           (eval('vf.f'+i+'.selectedIndex')==nw)) {
                   3769:         eval('vf.f'+i+'.selectedIndex=0;')
                   3770:       }
                   3771:     }
                   3772:   }
                   3773: ENDPICK
                   3774: }
                   3775: 
                   3776: sub csvupload_javascript_forward_associate {
1.573     bisitz   3777:     my $error1=&mt('You need to specify the username or the student/employee ID');
1.246     albertel 3778:     my $error2=&mt('You need to specify at least one grading field');
1.27      albertel 3779:   return(<<ENDPICK);
                   3780:   function verify(vf) {
                   3781:     var foundsomething=0;
                   3782:     var founduname=0;
1.243     albertel 3783:     var foundID=0;
1.27      albertel 3784:     for (i=0;i<=vf.nfields.value;i++) {
                   3785:       tw=eval('vf.f'+i+'.selectedIndex');
1.243     albertel 3786:       if (tw==1) { foundID=1; }
                   3787:       if (tw==2) { founduname=1; }
                   3788:       if (tw>3) { foundsomething=1; }
1.27      albertel 3789:     }
1.246     albertel 3790:     if (founduname==0 && foundID==0) {
                   3791: 	alert('$error1');
                   3792: 	return;
1.27      albertel 3793:     }
                   3794:     if (foundsomething==0) {
1.246     albertel 3795: 	alert('$error2');
                   3796: 	return;
1.27      albertel 3797:     }
                   3798:     vf.submit();
                   3799:   }
                   3800:   function flip(vf,tf) {
                   3801:     var nw=eval('vf.f'+tf+'.selectedIndex');
                   3802:     var i;
                   3803:     //can not pick the same destination field twice
                   3804:     for (i=0;i<=vf.nfields.value;i++) {
                   3805:       if ((i!=tf) && (eval('vf.f'+i+'.selectedIndex')==nw)) {
                   3806:         eval('vf.f'+i+'.selectedIndex=0;')
                   3807:       }
                   3808:     }
                   3809:   }
                   3810: ENDPICK
                   3811: }
                   3812: 
1.26      albertel 3813: sub csvuploadmap_header {
1.324     albertel 3814:     my ($request,$symb,$datatoken,$distotal)= @_;
1.41      ng       3815:     my $javascript;
1.257     albertel 3816:     if ($env{'form.upfile_associate'} eq 'reverse') {
1.41      ng       3817: 	$javascript=&csvupload_javascript_reverse_associate();
                   3818:     } else {
                   3819: 	$javascript=&csvupload_javascript_forward_associate();
                   3820:     }
1.45      ng       3821: 
1.418     albertel 3822:     $symb = &Apache::lonenc::check_encrypt($symb);
1.632   ! www      3823:     $request->print('<form method="post" enctype="multipart/form-data" action="/adm/grades" name="gradesupload">'.
        !          3824:                     &mt('Total number of records found in file: [_1]',$distotal).'<hr />'.
        !          3825:                     &mt('Associate entries from the uploaded file with as many fields as you can.'));
        !          3826:     my $reverse=&mt("Reverse Association");
1.41      ng       3827:     $request->print(<<ENDPICK);
1.632   ! www      3828: <br />
        !          3829: <input type="button" value="$reverse" onclick="javascript:this.form.associate.value='Reverse Association';submit(this.form);" />
1.26      albertel 3830: <input type="hidden" name="associate"  value="" />
                   3831: <input type="hidden" name="phase"      value="three" />
                   3832: <input type="hidden" name="datatoken"  value="$datatoken" />
1.257     albertel 3833: <input type="hidden" name="fileupload" value="$env{'form.fileupload'}" />
                   3834: <input type="hidden" name="upfiletype" value="$env{'form.upfiletype'}" />
1.26      albertel 3835: <input type="hidden" name="upfile_associate" 
1.257     albertel 3836:                                        value="$env{'form.upfile_associate'}" />
1.26      albertel 3837: <input type="hidden" name="symb"       value="$symb" />
1.246     albertel 3838: <input type="hidden" name="command"    value="csvuploadoptions" />
1.26      albertel 3839: <hr />
                   3840: ENDPICK
1.597     wenzelju 3841:     $request->print(&Apache::lonhtmlcommon::scripttag($javascript));
1.118     ng       3842:     return '';
1.26      albertel 3843: 
                   3844: }
                   3845: 
                   3846: sub csvupload_fields {
1.582     raeburn  3847:     my ($symb,$errorref) = @_;
                   3848:     my (@parts) = &getpartlist($symb,$errorref);
                   3849:     if (ref($errorref)) {
                   3850:         if ($$errorref) {
                   3851:             return;
                   3852:         }
                   3853:     }
                   3854: 
1.556     weissno  3855:     my @fields=(['ID','Student/Employee ID'],
1.243     albertel 3856: 		['username','Student Username'],
                   3857: 		['domain','Student Domain']);
1.324     albertel 3858:     my (undef,undef,$url) = &Apache::lonnet::decode_symb($symb);
1.41      ng       3859:     foreach my $part (sort(@parts)) {
                   3860: 	my @datum;
                   3861: 	my $display=&Apache::lonnet::metadata($url,$part.'.display');
                   3862: 	my $name=$part;
                   3863: 	if  (!$display) { $display = $name; }
                   3864: 	@datum=($name,$display);
1.244     albertel 3865: 	if ($name=~/^stores_(.*)_awarded/) {
                   3866: 	    push(@fields,['stores_'.$1.'_points',"Points [Part: $1]"]);
                   3867: 	}
1.41      ng       3868: 	push(@fields,\@datum);
                   3869:     }
                   3870:     return (@fields);
1.26      albertel 3871: }
                   3872: 
                   3873: sub csvuploadmap_footer {
1.41      ng       3874:     my ($request,$i,$keyfields) =@_;
                   3875:     $request->print(<<ENDPICK);
1.26      albertel 3876: </table>
                   3877: <input type="hidden" name="nfields" value="$i" />
                   3878: <input type="hidden" name="keyfields" value="$keyfields" />
1.589     bisitz   3879: <input type="button" onclick="javascript:verify(this.form)" value="Assign Grades" /><br />
1.26      albertel 3880: </form>
                   3881: ENDPICK
                   3882: }
                   3883: 
1.283     albertel 3884: sub checkforfile_js {
1.539     riegler  3885:     my $alertmsg = &mt('Please use the browse button to select a file from your local directory.');
1.597     wenzelju 3886:     my $result = &Apache::lonhtmlcommon::scripttag(<<CSVFORMJS);
1.86      ng       3887:     function checkUpload(formname) {
                   3888: 	if (formname.upfile.value == "") {
1.539     riegler  3889: 	    alert("$alertmsg");
1.86      ng       3890: 	    return false;
                   3891: 	}
                   3892: 	formname.submit();
                   3893:     }
                   3894: CSVFORMJS
1.283     albertel 3895:     return $result;
                   3896: }
                   3897: 
                   3898: sub upcsvScores_form {
1.608     www      3899:     my ($request,$symb) = @_;
1.283     albertel 3900:     if (!$symb) {return '';}
                   3901:     my $result=&checkforfile_js();
1.632   ! www      3902:     $result.=&Apache::loncommon::start_data_table().
        !          3903:              &Apache::loncommon::start_data_table_header_row().
        !          3904:              '<th>'.&mt('Specify a file containing the class scores for current resource.').'</th>'.
        !          3905:              &Apache::loncommon::end_data_table_header_row().
        !          3906:              &Apache::loncommon::start_data_table_row().'<td>';
1.370     www      3907:     my $upload=&mt("Upload Scores");
1.86      ng       3908:     my $upfile_select=&Apache::loncommon::upfile_select_html();
1.245     albertel 3909:     my $ignore=&mt('Ignore First Line');
1.418     albertel 3910:     $symb = &Apache::lonenc::check_encrypt($symb);
1.86      ng       3911:     $result.=<<ENDUPFORM;
1.106     albertel 3912: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="gradesupload">
1.86      ng       3913: <input type="hidden" name="symb" value="$symb" />
                   3914: <input type="hidden" name="command" value="csvuploadmap" />
                   3915: $upfile_select
1.589     bisitz   3916: <br /><input type="button" onclick="javascript:checkUpload(this.form);" value="$upload" />
1.86      ng       3917: </form>
                   3918: ENDUPFORM
1.370     www      3919:     $result.=&Apache::loncommon::help_open_topic("Course_Convert_To_CSV",
1.632   ! www      3920:                            &mt("How do I create a CSV file from a spreadsheet")).
        !          3921:              '</td>'.
        !          3922:             &Apache::loncommon::end_data_table_row().
        !          3923:             &Apache::loncommon::end_data_table();
1.86      ng       3924:     return $result;
                   3925: }
                   3926: 
                   3927: 
1.26      albertel 3928: sub csvuploadmap {
1.608     www      3929:     my ($request,$symb)= @_;
1.41      ng       3930:     if (!$symb) {return '';}
1.72      ng       3931: 
1.41      ng       3932:     my $datatoken;
1.257     albertel 3933:     if (!$env{'form.datatoken'}) {
1.41      ng       3934: 	$datatoken=&Apache::loncommon::upfile_store($request);
1.26      albertel 3935:     } else {
1.257     albertel 3936: 	$datatoken=$env{'form.datatoken'};
1.41      ng       3937: 	&Apache::loncommon::load_tmp_file($request);
1.26      albertel 3938:     }
1.41      ng       3939:     my @records=&Apache::loncommon::upfile_record_sep();
1.324     albertel 3940:     &csvuploadmap_header($request,$symb,$datatoken,$#records+1);
1.41      ng       3941:     my ($i,$keyfields);
                   3942:     if (@records) {
1.582     raeburn  3943:         my $fieldserror;
                   3944: 	my @fields=&csvupload_fields($symb,\$fieldserror);
                   3945:         if ($fieldserror) {
                   3946:             $request->print(&navmap_errormsg());
                   3947:             return;
                   3948:         }
1.257     albertel 3949: 	if ($env{'form.upfile_associate'} eq 'reverse') {	
1.41      ng       3950: 	    &Apache::loncommon::csv_print_samples($request,\@records);
                   3951: 	    $i=&Apache::loncommon::csv_print_select_table($request,\@records,
                   3952: 							  \@fields);
                   3953: 	    foreach (@fields) { $keyfields.=$_->[0].','; }
                   3954: 	    chop($keyfields);
                   3955: 	} else {
                   3956: 	    unshift(@fields,['none','']);
                   3957: 	    $i=&Apache::loncommon::csv_samples_select_table($request,\@records,
                   3958: 							    \@fields);
1.311     banghart 3959:             foreach my $rec (@records) {
                   3960:                 my %temp = &Apache::loncommon::record_sep($rec);
                   3961:                 if (%temp) {
                   3962:                     $keyfields=join(',',sort(keys(%temp)));
                   3963:                     last;
                   3964:                 }
                   3965:             }
1.41      ng       3966: 	}
                   3967:     }
                   3968:     &csvuploadmap_footer($request,$i,$keyfields);
1.72      ng       3969: 
1.41      ng       3970:     return '';
1.27      albertel 3971: }
                   3972: 
1.246     albertel 3973: sub csvuploadoptions {
1.608     www      3974:     my ($request,$symb)= @_;
1.632   ! www      3975:     my $overwrite=&mt('Overwrite any existing score');
1.246     albertel 3976:     $request->print(<<ENDPICK);
                   3977: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="gradesupload">
                   3978: <input type="hidden" name="command"    value="csvuploadassign" />
                   3979: <p>
                   3980: <label>
                   3981:    <input type="checkbox" name="overwite_scores" checked="checked" />
1.632   ! www      3982:    $overwrite
1.246     albertel 3983: </label>
                   3984: </p>
                   3985: ENDPICK
                   3986:     my %fields=&get_fields();
                   3987:     if (!defined($fields{'domain'})) {
1.257     albertel 3988: 	my $domform = &Apache::loncommon::select_dom_form($env{'request.role.domain'},'default_domain');
1.632   ! www      3989: 	$request->print("\n<p>".&mt('Users are in domain: [_1]',$domform)."</p>\n");
1.246     albertel 3990:     }
1.257     albertel 3991:     foreach my $key (sort(keys(%env))) {
1.246     albertel 3992: 	if ($key !~ /^form\.(.*)$/) { next; }
                   3993: 	my $cleankey=$1;
                   3994: 	if ($cleankey eq 'command') { next; }
                   3995: 	$request->print('<input type="hidden" name="'.$cleankey.
1.257     albertel 3996: 			'"  value="'.$env{$key}.'" />'."\n");
1.246     albertel 3997:     }
                   3998:     # FIXME do a check for any duplicated user ids...
                   3999:     # FIXME do a check for any invalid user ids?...
1.290     albertel 4000:     $request->print('<input type="submit" value="Assign Grades" /><br />
                   4001: <hr /></form>'."\n");
1.246     albertel 4002:     return '';
                   4003: }
                   4004: 
                   4005: sub get_fields {
                   4006:     my %fields;
1.257     albertel 4007:     my @keyfields = split(/\,/,$env{'form.keyfields'});
                   4008:     for (my $i=0; $i<=$env{'form.nfields'}; $i++) {
                   4009: 	if ($env{'form.upfile_associate'} eq 'reverse') {
                   4010: 	    if ($env{'form.f'.$i} ne 'none') {
                   4011: 		$fields{$keyfields[$i]}=$env{'form.f'.$i};
1.41      ng       4012: 	    }
                   4013: 	} else {
1.257     albertel 4014: 	    if ($env{'form.f'.$i} ne 'none') {
                   4015: 		$fields{$env{'form.f'.$i}}=$keyfields[$i];
1.41      ng       4016: 	    }
                   4017: 	}
1.27      albertel 4018:     }
1.246     albertel 4019:     return %fields;
                   4020: }
                   4021: 
                   4022: sub csvuploadassign {
1.608     www      4023:     my ($request,$symb)= @_;
1.246     albertel 4024:     if (!$symb) {return '';}
1.345     bowersj2 4025:     my $error_msg = '';
1.246     albertel 4026:     &Apache::loncommon::load_tmp_file($request);
                   4027:     my @gradedata = &Apache::loncommon::upfile_record_sep();
                   4028:     my %fields=&get_fields();
1.257     albertel 4029:     my $courseid=$env{'request.course.id'};
1.97      albertel 4030:     my ($classlist) = &getclasslist('all',0);
1.106     albertel 4031:     my @notallowed;
1.41      ng       4032:     my @skipped;
                   4033:     my $countdone=0;
                   4034:     foreach my $grade (@gradedata) {
                   4035: 	my %entries=&Apache::loncommon::record_sep($grade);
1.246     albertel 4036: 	my $domain;
                   4037: 	if ($entries{$fields{'domain'}}) {
                   4038: 	    $domain=$entries{$fields{'domain'}};
                   4039: 	} else {
1.257     albertel 4040: 	    $domain=$env{'form.default_domain'};
1.246     albertel 4041: 	}
1.243     albertel 4042: 	$domain=~s/\s//g;
1.41      ng       4043: 	my $username=$entries{$fields{'username'}};
1.160     albertel 4044: 	$username=~s/\s//g;
1.243     albertel 4045: 	if (!$username) {
                   4046: 	    my $id=$entries{$fields{'ID'}};
1.247     albertel 4047: 	    $id=~s/\s//g;
1.243     albertel 4048: 	    my %ids=&Apache::lonnet::idget($domain,$id);
                   4049: 	    $username=$ids{$id};
                   4050: 	}
1.41      ng       4051: 	if (!exists($$classlist{"$username:$domain"})) {
1.247     albertel 4052: 	    my $id=$entries{$fields{'ID'}};
                   4053: 	    $id=~s/\s//g;
                   4054: 	    if ($id) {
                   4055: 		push(@skipped,"$id:$domain");
                   4056: 	    } else {
                   4057: 		push(@skipped,"$username:$domain");
                   4058: 	    }
1.41      ng       4059: 	    next;
                   4060: 	}
1.108     albertel 4061: 	my $usec=$classlist->{"$username:$domain"}[5];
1.106     albertel 4062: 	if (!&canmodify($usec)) {
                   4063: 	    push(@notallowed,"$username:$domain");
                   4064: 	    next;
                   4065: 	}
1.244     albertel 4066: 	my %points;
1.41      ng       4067: 	my %grades;
                   4068: 	foreach my $dest (keys(%fields)) {
1.244     albertel 4069: 	    if ($dest eq 'ID' || $dest eq 'username' ||
                   4070: 		$dest eq 'domain') { next; }
                   4071: 	    if ($entries{$fields{$dest}} =~ /^\s*$/) { next; }
                   4072: 	    if ($dest=~/stores_(.*)_points/) {
                   4073: 		my $part=$1;
                   4074: 		my $wgt =&Apache::lonnet::EXT('resource.'.$part.'.weight',
                   4075: 					      $symb,$domain,$username);
1.345     bowersj2 4076:                 if ($wgt) {
                   4077:                     $entries{$fields{$dest}}=~s/\s//g;
                   4078:                     my $pcr=$entries{$fields{$dest}} / $wgt;
1.463     albertel 4079:                     my $award=($pcr == 0) ? 'incorrect_by_override'
                   4080:                                           : 'correct_by_override';
1.345     bowersj2 4081:                     $grades{"resource.$part.awarded"}=$pcr;
                   4082:                     $grades{"resource.$part.solved"}=$award;
                   4083:                     $points{$part}=1;
                   4084:                 } else {
                   4085:                     $error_msg = "<br />" .
                   4086:                         &mt("Some point values were assigned"
                   4087:                             ." for problems with a weight "
                   4088:                             ."of zero. These values were "
                   4089:                             ."ignored.");
                   4090:                 }
1.244     albertel 4091: 	    } else {
                   4092: 		if ($dest=~/stores_(.*)_awarded/) { if ($points{$1}) {next;} }
                   4093: 		if ($dest=~/stores_(.*)_solved/)  { if ($points{$1}) {next;} }
                   4094: 		my $store_key=$dest;
                   4095: 		$store_key=~s/^stores/resource/;
                   4096: 		$store_key=~s/_/\./g;
                   4097: 		$grades{$store_key}=$entries{$fields{$dest}};
                   4098: 	    }
1.41      ng       4099: 	}
1.508     www      4100: 	if (! %grades) { 
                   4101:            push(@skipped,&mt("[_1]: no data to save","$username:$domain")); 
                   4102:         } else {
                   4103: 	   $grades{"resource.regrader"}="$env{'user.name'}:$env{'user.domain'}";
                   4104: 	   my $result=&Apache::lonnet::cstore(\%grades,$symb,
1.302     albertel 4105: 					   $env{'request.course.id'},
                   4106: 					   $domain,$username);
1.508     www      4107: 	   if ($result eq 'ok') {
1.627     www      4108: # Successfully stored
1.508     www      4109: 	      $request->print('.');
1.627     www      4110: # Remove from grading queue
                   4111:               &Apache::bridgetask::remove_from_queue('gradingqueue',$symb,
                   4112:                                              $env{'course.'.$env{'request.course.id'}.'.domain'},
                   4113:                                              $env{'course.'.$env{'request.course.id'}.'.num'},
                   4114:                                              $domain,$username);
                   4115:               $countdone++;
                   4116:            } else {
1.508     www      4117: 	      $request->print("<p><span class=\"LC_error\">".
                   4118:                               &mt("Failed to save data for student [_1]. Message when trying to save was: [_2]",
                   4119:                                   "$username:$domain",$result)."</span></p>");
                   4120: 	   }
                   4121: 	   $request->rflush();
                   4122:         }
1.41      ng       4123:     }
1.570     www      4124:     $request->print('<br />'.&Apache::lonhtmlcommon::confirm_success(&mt("Saved scores for [quant,_1,student]",$countdone),$countdone==0));
1.41      ng       4125:     if (@skipped) {
1.571     www      4126: 	$request->print('<br />'.&Apache::lonhtmlcommon::confirm_success(&mt('No scores stored for the following username(s):'),1).'<br />');
                   4127:         $request->print(join(', ',@skipped));
1.106     albertel 4128:     }
                   4129:     if (@notallowed) {
1.571     www      4130: 	$request->print('<br />'.&Apache::lonhtmlcommon::confirm_success(&mt('Modification of scores not allowed for the following username(s):'),1).'<br />');
                   4131: 	$request->print(join(', ',@notallowed));
1.41      ng       4132:     }
1.106     albertel 4133:     $request->print("<br />\n");
1.345     bowersj2 4134:     return $error_msg;
1.26      albertel 4135: }
1.44      ng       4136: #------------- end of section for handling csv file upload ---------
                   4137: #
                   4138: #-------------------------------------------------------------------
                   4139: #
1.122     ng       4140: #-------------- Next few routines handle grading by page/sequence
1.72      ng       4141: #
                   4142: #--- Select a page/sequence and a student to grade
1.68      ng       4143: sub pickStudentPage {
1.608     www      4144:     my ($request,$symb) = @_;
1.68      ng       4145: 
1.539     riegler  4146:     my $alertmsg = &mt('Please select the student you wish to grade.');
1.597     wenzelju 4147:     $request->print(&Apache::lonhtmlcommon::scripttag(<<LISTJAVASCRIPT));
1.68      ng       4148: 
                   4149: function checkPickOne(formname) {
1.76      ng       4150:     if (radioSelection(formname.student) == null) {
1.539     riegler  4151: 	alert("$alertmsg");
1.68      ng       4152: 	return;
                   4153:     }
1.125     ng       4154:     ptr = pullDownSelection(formname.selectpage);
                   4155:     formname.page.value = formname["page"+ptr].value;
                   4156:     formname.title.value = formname["title"+ptr].value;
1.68      ng       4157:     formname.submit();
                   4158: }
                   4159: 
                   4160: LISTJAVASCRIPT
1.118     ng       4161:     &commonJSfunctions($request);
1.608     www      4162: 
1.257     albertel 4163:     my $cdom      = $env{"course.$env{'request.course.id'}.domain"};
                   4164:     my $cnum      = $env{"course.$env{'request.course.id'}.num"};
                   4165:     my $getsec    = $env{'form.section'} eq '' ? 'all' : $env{'form.section'};
1.68      ng       4166: 
1.398     albertel 4167:     my $result='<h3><span class="LC_info">&nbsp;'.
1.485     albertel 4168: 	&mt('Manual Grading by Page or Sequence').'</span></h3>';
1.68      ng       4169: 
1.80      ng       4170:     $result.='<form action="/adm/grades" method="post" name="displayPage">'."\n";
1.582     raeburn  4171:     my $map_error;
                   4172:     my ($titles,$symbx) = &getSymbMap($map_error);
                   4173:     if ($map_error) {
                   4174:         $request->print(&navmap_errormsg());
                   4175:         return; 
                   4176:     }
1.137     albertel 4177:     my ($curpage) =&Apache::lonnet::decode_symb($symb); 
                   4178: #    my ($curpage,$mapId) =&Apache::lonnet::decode_symb($symb); 
                   4179: #    my $type=($curpage =~ /\.(page|sequence)/);
1.485     albertel 4180:     my $select = '<select name="selectpage">'."\n";
1.70      ng       4181:     my $ctr=0;
1.68      ng       4182:     foreach (@$titles) {
                   4183: 	my ($minder,$showtitle) = ($_ =~ /(\d+)\.(.*)/);
1.485     albertel 4184: 	$select.='<option value="'.$ctr.'" '.
1.401     albertel 4185: 	    ($$symbx{$_} =~ /$curpage$/ ? 'selected="selected"' : '').
1.71      ng       4186: 	    '>'.$showtitle.'</option>'."\n";
1.70      ng       4187: 	$ctr++;
1.68      ng       4188:     }
1.485     albertel 4189:     $select.= '</select>';
1.539     riegler  4190:     $result.='&nbsp;<b>'.&mt('Problems from').':</b> '.$select."<br />\n";
1.485     albertel 4191: 
1.70      ng       4192:     $ctr=0;
                   4193:     foreach (@$titles) {
                   4194: 	my ($minder,$showtitle) = ($_ =~ /(\d+)\.(.*)/);
                   4195: 	$result.='<input type="hidden" name="page'.$ctr.'" value="'.$$symbx{$_}.'" />'."\n";
                   4196: 	$result.='<input type="hidden" name="title'.$ctr.'" value="'.$showtitle.'" />'."\n";
                   4197: 	$ctr++;
                   4198:     }
1.72      ng       4199:     $result.='<input type="hidden" name="page" />'."\n".
                   4200: 	'<input type="hidden" name="title" />'."\n";
1.68      ng       4201: 
1.485     albertel 4202:     my $options =
                   4203: 	'<label><input type="radio" name="vProb" value="no" checked="checked" /> '.&mt('no').' </label>'."\n".
                   4204: 	'<label><input type="radio" name="vProb" value="yes" /> '.&mt('yes').' </label>'."<br />\n";
1.539     riegler  4205:     $result.='&nbsp;<b>'.&mt('View Problem Text').': </b>'.$options;
1.485     albertel 4206: 
                   4207:     $options =
                   4208: 	'<label><input type="radio" name="lastSub" value="none" /> '.&mt('none').' </label>'."\n".
                   4209: 	'<label><input type="radio" name="lastSub" value="datesub" checked="checked" /> '.&mt('by dates and submissions').'</label>'."\n".
                   4210: 	'<label><input type="radio" name="lastSub" value="all" /> '.&mt('all details').' </label>'."\n";
1.539     riegler  4211:     $result.='&nbsp;<b>'.&mt('Submissions').': </b>'.$options;
1.432     banghart 4212:     
                   4213:     $result.=&build_section_inputs();
1.442     banghart 4214:     my $stu_status = join(':',&Apache::loncommon::get_env_multiple('form.Status'));
                   4215:     $result.='<input type="hidden" name="Status"  value="'.$stu_status.'" />'."\n".
1.72      ng       4216: 	'<input type="hidden" name="command" value="displayPage" />'."\n".
1.613     www      4217: 	'<input type="hidden" name="symb"    value="'.&Apache::lonenc::check_encrypt($symb).'" />'."<br />\n";
1.72      ng       4218: 
1.539     riegler  4219:     $result.='&nbsp;<b>'.&mt('Use CODE').': </b> <input type="text" name="CODE" value="" /> <br />'."\n";
1.382     albertel 4220: 
1.80      ng       4221:     $result.='&nbsp;<input type="button" '.
1.589     bisitz   4222:              'onclick="javascript:checkPickOne(this.form);" value="'.&mt('Next').' &rarr;" /><br />'."\n";
1.72      ng       4223: 
1.68      ng       4224:     $request->print($result);
                   4225: 
1.485     albertel 4226:     my $studentTable.='&nbsp;<b>'.&mt('Select a student you wish to grade and then click on the Next button.').'</b><br />'.
1.484     albertel 4227: 	&Apache::loncommon::start_data_table().
                   4228: 	&Apache::loncommon::start_data_table_header_row().
1.485     albertel 4229: 	'<th align="right">&nbsp;'.&mt('No.').'</th>'.
1.484     albertel 4230: 	'<th>'.&nameUserString('header').'</th>'.
1.485     albertel 4231: 	'<th align="right">&nbsp;'.&mt('No.').'</th>'.
1.484     albertel 4232: 	'<th>'.&nameUserString('header').'</th>'.
                   4233: 	&Apache::loncommon::end_data_table_header_row();
1.68      ng       4234:  
1.76      ng       4235:     my (undef,undef,$fullname) = &getclasslist($getsec,'1');
1.68      ng       4236:     my $ptr = 1;
1.294     albertel 4237:     foreach my $student (sort 
                   4238: 			 {
                   4239: 			     if (lc($$fullname{$a}) ne lc($$fullname{$b})) {
                   4240: 				 return (lc($$fullname{$a}) cmp lc($$fullname{$b}));
                   4241: 			     }
                   4242: 			     return $a cmp $b;
                   4243: 			 } (keys(%$fullname))) {
1.68      ng       4244: 	my ($uname,$udom) = split(/:/,$student);
1.484     albertel 4245: 	$studentTable.=($ptr%2==1 ? &Apache::loncommon::start_data_table_row()
                   4246:                                   : '</td>');
1.126     ng       4247: 	$studentTable.='<td align="right">'.$ptr.'&nbsp;</td>';
1.288     albertel 4248: 	$studentTable.='<td>&nbsp;<label><input type="radio" name="student" value="'.$student.'" /> '
                   4249: 	    .&nameUserString(undef,$$fullname{$student},$uname,$udom)."</label>\n";
1.484     albertel 4250: 	$studentTable.=
                   4251: 	    ($ptr%2 == 0 ? '</td>'.&Apache::loncommon::end_data_table_row() 
                   4252:                          : '');
1.68      ng       4253: 	$ptr++;
                   4254:     }
1.484     albertel 4255:     if ($ptr%2 == 0) {
                   4256: 	$studentTable.='</td><td>&nbsp;</td><td>&nbsp;</td>'.
                   4257: 	    &Apache::loncommon::end_data_table_row();
                   4258:     }
                   4259:     $studentTable.=&Apache::loncommon::end_data_table()."\n";
1.126     ng       4260:     $studentTable.='<input type="button" '.
1.589     bisitz   4261:                    'onclick="javascript:checkPickOne(this.form);" value="'.&mt('Next').' &rarr;" /></form>'."\n";
1.68      ng       4262: 
                   4263:     $request->print($studentTable);
                   4264: 
                   4265:     return '';
                   4266: }
                   4267: 
                   4268: sub getSymbMap {
1.582     raeburn  4269:     my ($map_error) = @_;
1.132     bowersj2 4270:     my $navmap = Apache::lonnavmaps::navmap->new();
1.582     raeburn  4271:     unless (ref($navmap)) {
                   4272:         if (ref($map_error)) {
                   4273:             $$map_error = 'navmap';
                   4274:         }
                   4275:         return;
                   4276:     }
1.68      ng       4277:     my %symbx = ();
                   4278:     my @titles = ();
1.117     bowersj2 4279:     my $minder = 0;
                   4280: 
                   4281:     # Gather every sequence that has problems.
1.240     albertel 4282:     my @sequences = $navmap->retrieveResources(undef, sub { shift->is_map(); },
                   4283: 					       1,0,1);
1.117     bowersj2 4284:     for my $sequence ($navmap->getById('0.0'), @sequences) {
1.241     albertel 4285: 	if ($navmap->hasResource($sequence, sub { shift->is_problem(); }, 0) ) {
1.381     albertel 4286: 	    my $title = $minder.'.'.
                   4287: 		&HTML::Entities::encode($sequence->compTitle(),'"\'&');
                   4288: 	    push(@titles, $title); # minder in case two titles are identical
                   4289: 	    $symbx{$title} = &HTML::Entities::encode($sequence->symb(),'"\'&');
1.117     bowersj2 4290: 	    $minder++;
1.241     albertel 4291: 	}
1.68      ng       4292:     }
                   4293:     return \@titles,\%symbx;
                   4294: }
                   4295: 
1.72      ng       4296: #
                   4297: #--- Displays a page/sequence w/wo problems, w/wo submissions
1.68      ng       4298: sub displayPage {
1.608     www      4299:     my ($request,$symb) = @_;
1.257     albertel 4300:     my $cdom      = $env{"course.$env{'request.course.id'}.domain"};
                   4301:     my $cnum      = $env{"course.$env{'request.course.id'}.num"};
                   4302:     my $getsec    = $env{'form.section'} eq '' ? 'all' : $env{'form.section'};
                   4303:     my $pageTitle = $env{'form.page'};
1.103     albertel 4304:     my ($classlist,undef,$fullname) = &getclasslist($getsec,'1');
1.257     albertel 4305:     my ($uname,$udom) = split(/:/,$env{'form.student'});
                   4306:     my $usec=$classlist->{$env{'form.student'}}[5];
1.168     albertel 4307: 
                   4308:     #need to make sure we have the correct data for later EXT calls, 
                   4309:     #thus invalidate the cache
                   4310:     &Apache::lonnet::devalidatecourseresdata(
1.257     albertel 4311:                  $env{'course.'.$env{'request.course.id'}.'.num'},
                   4312:                  $env{'course.'.$env{'request.course.id'}.'.domain'});
1.168     albertel 4313:     &Apache::lonnet::clear_EXT_cache_status();
                   4314: 
1.103     albertel 4315:     if (!&canview($usec)) {
1.485     albertel 4316: 	$request->print('<span class="LC_warning">'.&mt('Unable to view requested student. ([_1])',$env{'form.student'}).'</span>');
1.103     albertel 4317: 	return;
                   4318:     }
1.398     albertel 4319:     my $result='<h3><span class="LC_info">&nbsp;'.$env{'form.title'}.'</span></h3>';
1.485     albertel 4320:     $result.='<h3>&nbsp;'.&mt('Student: [_1]',&nameUserString(undef,$$fullname{$env{'form.student'}},$uname,$udom)).
1.129     ng       4321: 	'</h3>'."\n";
1.500     albertel 4322:     $env{'form.CODE'} = uc($env{'form.CODE'});
1.501     foxr     4323:     if (&Apache::lonnet::validCODE(uc($env{'form.CODE'}))) {
1.485     albertel 4324: 	$result.='<h3>&nbsp;'.&mt('CODE: [_1]',$env{'form.CODE'}).'</h3>'."\n";
1.382     albertel 4325:     } else {
                   4326: 	delete($env{'form.CODE'});
                   4327:     }
1.71      ng       4328:     &sub_page_js($request);
                   4329:     $request->print($result);
                   4330: 
1.132     bowersj2 4331:     my $navmap = Apache::lonnavmaps::navmap->new();
1.582     raeburn  4332:     unless (ref($navmap)) {
                   4333:         $request->print(&navmap_errormsg());
                   4334:         return;
                   4335:     }
1.257     albertel 4336:     my ($mapUrl, $id, $resUrl)=&Apache::lonnet::decode_symb($env{'form.page'});
1.68      ng       4337:     my $map = $navmap->getResourceByUrl($resUrl); # add to navmaps
1.288     albertel 4338:     if (!$map) {
1.485     albertel 4339: 	$request->print('<span class="LC_warning">'.&mt('Unable to view requested sequence. ([_1])',$resUrl).'</span>');
1.288     albertel 4340: 	return; 
                   4341:     }
1.68      ng       4342:     my $iterator = $navmap->getIterator($map->map_start(),
                   4343: 					$map->map_finish());
                   4344: 
1.71      ng       4345:     my $studentTable='<form action="/adm/grades" method="post" name="gradePage">'."\n".
1.72      ng       4346: 	'<input type="hidden" name="command" value="gradeByPage" />'."\n".
1.257     albertel 4347: 	'<input type="hidden" name="fullname" value="'.$$fullname{$env{'form.student'}}.'" />'."\n".
                   4348: 	'<input type="hidden" name="student" value="'.$env{'form.student'}.'" />'."\n".
1.72      ng       4349: 	'<input type="hidden" name="page"    value="'.$pageTitle.'" />'."\n".
1.257     albertel 4350: 	'<input type="hidden" name="title"   value="'.$env{'form.title'}.'" />'."\n".
1.418     albertel 4351: 	'<input type="hidden" name="symb"    value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
1.613     www      4352: 	'<input type="hidden" name="overRideScore" value="no" />'."\n";
1.71      ng       4353: 
1.382     albertel 4354:     if (defined($env{'form.CODE'})) {
                   4355: 	$studentTable.=
                   4356: 	    '<input type="hidden" name="CODE" value="'.$env{'form.CODE'}.'" />'."\n";
                   4357:     }
1.381     albertel 4358:     my $checkIcon = '<img alt="'.&mt('Check Mark').
1.485     albertel 4359: 	'" src="'.&Apache::loncommon::lonhttpdurl($request->dir_config('lonIconsURL').'/check.gif').'" height="16" border="0" />';
1.71      ng       4360: 
1.594     bisitz   4361:     $studentTable.='&nbsp;<span class="LC_info">'.
                   4362:         &mt('Problems graded correct by the computer are marked with a [_1] symbol.',$checkIcon).
                   4363:         '</span>'."\n".
1.484     albertel 4364: 	&Apache::loncommon::start_data_table().
                   4365: 	&Apache::loncommon::start_data_table_header_row().
                   4366: 	'<th align="center">&nbsp;Prob.&nbsp;</th>'.
1.485     albertel 4367: 	'<th>&nbsp;'.($env{'form.vProb'} eq 'no' ? &mt('Title') : &mt('Problem Text')).'/'.&mt('Grade').'</th>'.
1.484     albertel 4368: 	&Apache::loncommon::end_data_table_header_row();
1.71      ng       4369: 
1.329     albertel 4370:     &Apache::lonxml::clear_problem_counter();
1.196     albertel 4371:     my ($depth,$question,$prob) = (1,1,1);
1.68      ng       4372:     $iterator->next(); # skip the first BEGIN_MAP
                   4373:     my $curRes = $iterator->next(); # for "current resource"
1.101     albertel 4374:     while ($depth > 0) {
1.68      ng       4375:         if($curRes == $iterator->BEGIN_MAP) { $depth++; }
1.100     bowersj2 4376:         if($curRes == $iterator->END_MAP) { $depth--; }
1.68      ng       4377: 
1.385     albertel 4378:         if (ref($curRes) && $curRes->is_problem()) {
1.91      albertel 4379: 	    my $parts = $curRes->parts();
1.68      ng       4380:             my $title = $curRes->compTitle();
1.71      ng       4381: 	    my $symbx = $curRes->symb();
1.484     albertel 4382: 	    $studentTable.=
                   4383: 		&Apache::loncommon::start_data_table_row().
                   4384: 		'<td align="center" valign="top" >'.$prob.
1.485     albertel 4385: 		(scalar(@{$parts}) == 1 ? '' 
                   4386: 		                        : '<br />('.&mt('[_1]&nbsp;parts)',
                   4387: 							scalar(@{$parts}))
                   4388: 		 ).
                   4389: 		 '</td>';
1.71      ng       4390: 	    $studentTable.='<td valign="top">';
1.382     albertel 4391: 	    my %form = ('CODE' => $env{'form.CODE'},);
1.257     albertel 4392: 	    if ($env{'form.vProb'} eq 'yes' ) {
1.144     albertel 4393: 		$studentTable.=&show_problem($request,$symbx,$uname,$udom,1,
1.383     albertel 4394: 					     undef,'both',\%form);
1.71      ng       4395: 	    } else {
1.382     albertel 4396: 		my $companswer = &Apache::loncommon::get_student_answers($symbx,$uname,$udom,$env{'request.course.id'},%form);
1.80      ng       4397: 		$companswer =~ s|<form(.*?)>||g;
                   4398: 		$companswer =~ s|</form>||g;
1.71      ng       4399: #		while ($companswer =~ /(<a href\=\"javascript:newWindow.*?Script Vars<\/a>)/s) { #<a href="javascript:newWindow</a>
1.116     ng       4400: #		    $companswer =~ s/$1/ /ms;
1.326     albertel 4401: #		    $request->print('match='.$1."<br />\n");
1.71      ng       4402: #		}
1.116     ng       4403: #		$companswer =~ s|<table border=\"1\">|<table border=\"0\">|g;
1.539     riegler  4404: 		$studentTable.='&nbsp;<b>'.$title.'</b>&nbsp;<br />&nbsp;<b>'.&mt('Correct answer').':</b><br />'.$companswer;
1.71      ng       4405: 	    }
                   4406: 
1.257     albertel 4407: 	    my %record = &Apache::lonnet::restore($symbx,$env{'request.course.id'},$udom,$uname);
1.125     ng       4408: 
1.257     albertel 4409: 	    if ($env{'form.lastSub'} eq 'datesub') {
1.71      ng       4410: 		if ($record{'version'} eq '') {
1.485     albertel 4411: 		    $studentTable.='<br />&nbsp;<span class="LC_warning">'.&mt('No recorded submission for this problem.').'</span><br />';
1.71      ng       4412: 		} else {
1.116     ng       4413: 		    my %responseType = ();
                   4414: 		    foreach my $partid (@{$parts}) {
1.147     albertel 4415: 			my @responseIds =$curRes->responseIds($partid);
                   4416: 			my @responseType =$curRes->responseType($partid);
                   4417: 			my %responseIds;
                   4418: 			for (my $i=0;$i<=$#responseIds;$i++) {
                   4419: 			    $responseIds{$responseIds[$i]}=$responseType[$i];
                   4420: 			}
                   4421: 			$responseType{$partid} = \%responseIds;
1.116     ng       4422: 		    }
1.148     albertel 4423: 		    $studentTable.= &displaySubByDates($symbx,\%record,$parts,\%responseType,$checkIcon,$uname,$udom);
1.147     albertel 4424: 
1.71      ng       4425: 		}
1.257     albertel 4426: 	    } elsif ($env{'form.lastSub'} eq 'all') {
                   4427: 		my $last = ($env{'form.lastSub'} eq 'last' ? 'last' : '');
1.71      ng       4428: 		$studentTable.=&Apache::loncommon::get_previous_attempt($symbx,$uname,$udom,
1.257     albertel 4429: 									$env{'request.course.id'},
1.71      ng       4430: 									'','.submission');
                   4431:  
                   4432: 	    }
1.103     albertel 4433: 	    if (&canmodify($usec)) {
1.585     bisitz   4434:             $studentTable.=&gradeBox_start();
1.103     albertel 4435: 		foreach my $partid (@{$parts}) {
                   4436: 		    $studentTable.=&gradeBox($request,$symbx,$uname,$udom,$question,$partid,\%record);
                   4437: 		    $studentTable.='<input type="hidden" name="q_'.$question.'" value="'.$partid.'" />'."\n";
                   4438: 		    $question++;
                   4439: 		}
1.585     bisitz   4440:             $studentTable.=&gradeBox_end();
1.196     albertel 4441: 		$prob++;
1.71      ng       4442: 	    }
                   4443: 	    $studentTable.='</td></tr>';
1.68      ng       4444: 
1.103     albertel 4445: 	}
1.68      ng       4446:         $curRes = $iterator->next();
                   4447:     }
                   4448: 
1.589     bisitz   4449:     $studentTable.=
                   4450:         '</table>'."\n".
                   4451:         '<input type="button" value="'.&mt('Save').'" '.
                   4452:         'onclick="javascript:checkSubmitPage(this.form,'.$question.');" />'.
                   4453:         '</form>'."\n";
1.71      ng       4454:     $request->print($studentTable);
                   4455: 
                   4456:     return '';
1.119     ng       4457: }
                   4458: 
                   4459: sub displaySubByDates {
1.148     albertel 4460:     my ($symb,$record,$parts,$responseType,$checkIcon,$uname,$udom) = @_;
1.224     albertel 4461:     my $isCODE=0;
1.335     albertel 4462:     my $isTask = ($symb =~/\.task$/);
1.224     albertel 4463:     if (exists($record->{'resource.CODE'})) { $isCODE=1; }
1.467     albertel 4464:     my $studentTable=&Apache::loncommon::start_data_table().
                   4465: 	&Apache::loncommon::start_data_table_header_row().
                   4466: 	'<th>'.&mt('Date/Time').'</th>'.
                   4467: 	($isCODE?'<th>'.&mt('CODE').'</th>':'').
                   4468: 	'<th>'.&mt('Submission').'</th>'.
                   4469: 	'<th>'.&mt('Status').'</th>'.
                   4470: 	&Apache::loncommon::end_data_table_header_row();
1.119     ng       4471:     my ($version);
                   4472:     my %mark;
1.148     albertel 4473:     my %orders;
1.119     ng       4474:     $mark{'correct_by_student'} = $checkIcon;
1.147     albertel 4475:     if (!exists($$record{'1:timestamp'})) {
1.539     riegler  4476: 	return '<br />&nbsp;<span class="LC_warning">'.&mt('Nothing submitted - no attempts.').'</span><br />';
1.147     albertel 4477:     }
1.335     albertel 4478: 
                   4479:     my $interaction;
1.525     raeburn  4480:     my $no_increment = 1;
1.119     ng       4481:     for ($version=1;$version<=$$record{'version'};$version++) {
1.467     albertel 4482: 	my $timestamp = 
                   4483: 	    &Apache::lonlocal::locallocaltime($$record{$version.':timestamp'});
1.335     albertel 4484: 	if (exists($$record{$version.':resource.0.version'})) {
                   4485: 	    $interaction = $$record{$version.':resource.0.version'};
                   4486: 	}
                   4487: 
                   4488: 	my $where = ($isTask ? "$version:resource.$interaction"
                   4489: 		             : "$version:resource");
1.467     albertel 4490: 	$studentTable.=&Apache::loncommon::start_data_table_row().
                   4491: 	    '<td>'.$timestamp.'</td>';
1.224     albertel 4492: 	if ($isCODE) {
                   4493: 	    $studentTable.='<td>'.$record->{$version.':resource.CODE'}.'</td>';
                   4494: 	}
1.119     ng       4495: 	my @versionKeys = split(/\:/,$$record{$version.':keys'});
                   4496: 	my @displaySub = ();
                   4497: 	foreach my $partid (@{$parts}) {
1.596     raeburn  4498:             my $hidden;
                   4499:             if (($$record{$version.':resource.'.$partid.'.type'} eq 'anonsurvey') ||
                   4500:                 ($$record{$version.':resource.'.$partid.'.type'} eq 'anonsurveycred')) {
                   4501:                 $hidden = 1;
                   4502:             }
1.335     albertel 4503: 	    my @matchKey = ($isTask ? sort(grep /^resource\.\d+\.\Q$partid\E\.award$/,@versionKeys)
                   4504: 			            : sort(grep /^resource\.\Q$partid\E\..*?\.submission$/,@versionKeys));
                   4505: 	    
1.122     ng       4506: #	    next if ($$record{"$version:resource.$partid.solved"} eq '');
1.324     albertel 4507: 	    my $display_part=&get_display_part($partid,$symb);
1.147     albertel 4508: 	    foreach my $matchKey (@matchKey) {
1.198     albertel 4509: 		if (exists($$record{$version.':'.$matchKey}) &&
                   4510: 		    $$record{$version.':'.$matchKey} ne '') {
1.596     raeburn  4511:                     
1.335     albertel 4512: 		    my ($responseId)= ($isTask ? ($matchKey=~ /^resource\.(.*?)\.\Q$partid\E\.award$/)
                   4513: 				               : ($matchKey=~ /^resource\.\Q$partid\E\.(.*?)\.submission$/));
1.577     bisitz   4514:                     $displaySub[0].='<span class="LC_nobreak"';
                   4515:                     $displaySub[0].='<b>'.&mt('Part: [_1]',$display_part).'</b>'
                   4516:                                    .' <span class="LC_internal_info">'
1.625     www      4517:                                    .'('.&mt('Response ID: [_1]',$responseId).')'
1.577     bisitz   4518:                                    .'</span>'
                   4519:                                    .' <b>';
1.596     raeburn  4520:                     if ($hidden) {
                   4521:                         $displaySub[0].= &mt('Anonymous Survey').'</b>';
                   4522:                     } else {
                   4523: 		        if ($$record{"$where.$partid.tries"} eq '') {
                   4524: 			    $displaySub[0].=&mt('Trial not counted');
                   4525: 		        } else {
                   4526: 			    $displaySub[0].=&mt('Trial: [_1]',
1.467     albertel 4527: 					    $$record{"$where.$partid.tries"});
1.596     raeburn  4528: 		        }
                   4529: 		        my $responseType=($isTask ? 'Task'
1.335     albertel 4530:                                               : $responseType->{$partid}->{$responseId});
1.596     raeburn  4531: 		        if (!exists($orders{$partid})) { $orders{$partid}={}; }
                   4532: 		        if (!exists($orders{$partid}->{$responseId})) {
                   4533: 			    $orders{$partid}->{$responseId}=
                   4534: 			        &get_order($partid,$responseId,$symb,$uname,$udom,
                   4535:                                            $no_increment);
                   4536: 		        }
                   4537: 		        $displaySub[0].='</b></span>'; # /nobreak
                   4538: 		        $displaySub[0].='&nbsp; '.
                   4539: 			    &cleanRecord($$record{$version.':'.$matchKey},$responseType,$symb,$partid,$responseId,$record,$orders{$partid}->{$responseId},"$version:",$uname,$udom).'<br />';
                   4540:                     }
1.147     albertel 4541: 		}
                   4542: 	    }
1.335     albertel 4543: 	    if (exists($$record{"$where.$partid.checkedin"})) {
1.485     albertel 4544: 		$displaySub[1].=&mt('Checked in by [_1] into slot [_2]',
                   4545: 				    $$record{"$where.$partid.checkedin"},
                   4546: 				    $$record{"$where.$partid.checkedin.slot"}).
                   4547: 					'<br />';
1.335     albertel 4548: 	    }
                   4549: 	    if (exists $$record{"$where.$partid.award"}) {
1.485     albertel 4550: 		$displaySub[1].='<b>'.&mt('Part:').'</b>&nbsp;'.$display_part.' &nbsp;'.
1.335     albertel 4551: 		    lc($$record{"$where.$partid.award"}).' '.
                   4552: 		    $mark{$$record{"$where.$partid.solved"}}.
1.147     albertel 4553: 		    '<br />';
                   4554: 	    }
1.335     albertel 4555: 	    if (exists $$record{"$where.$partid.regrader"}) {
                   4556: 		$displaySub[2].=$$record{"$where.$partid.regrader"}.
                   4557: 		    ' (<b>'.&mt('Part').':</b> '.$display_part.')';
                   4558: 	    } elsif ($$record{"$version:resource.$partid.regrader"} =~ /\S/) {
                   4559: 		$displaySub[2].=
                   4560: 		    $$record{"$version:resource.$partid.regrader"}.
1.207     albertel 4561: 		    ' (<b>'.&mt('Part').':</b> '.$display_part.')';
1.147     albertel 4562: 	    }
                   4563: 	}
                   4564: 	# needed because old essay regrader has not parts info
                   4565: 	if (exists $$record{"$version:resource.regrader"}) {
                   4566: 	    $displaySub[2].=$$record{"$version:resource.regrader"};
                   4567: 	}
                   4568: 	$studentTable.='<td>'.$displaySub[0].'&nbsp;</td><td>'.$displaySub[1];
                   4569: 	if ($displaySub[2]) {
1.467     albertel 4570: 	    $studentTable.=&mt('Manually graded by [_1]',$displaySub[2]);
1.147     albertel 4571: 	}
1.467     albertel 4572: 	$studentTable.='&nbsp;</td>'.
                   4573: 	    &Apache::loncommon::end_data_table_row();
1.119     ng       4574:     }
1.467     albertel 4575:     $studentTable.=&Apache::loncommon::end_data_table();
1.119     ng       4576:     return $studentTable;
1.71      ng       4577: }
                   4578: 
                   4579: sub updateGradeByPage {
1.608     www      4580:     my ($request,$symb) = @_;
1.71      ng       4581: 
1.257     albertel 4582:     my $cdom      = $env{"course.$env{'request.course.id'}.domain"};
                   4583:     my $cnum      = $env{"course.$env{'request.course.id'}.num"};
                   4584:     my $getsec    = $env{'form.section'} eq '' ? 'all' : $env{'form.section'};
                   4585:     my $pageTitle = $env{'form.page'};
1.103     albertel 4586:     my ($classlist,undef,$fullname) = &getclasslist($getsec,'1');
1.257     albertel 4587:     my ($uname,$udom) = split(/:/,$env{'form.student'});
                   4588:     my $usec=$classlist->{$env{'form.student'}}[5];
1.103     albertel 4589:     if (!&canmodify($usec)) {
1.526     raeburn  4590: 	$request->print('<span class="LC_warning">'.&mt('Unable to modify requested student ([_1])',$env{'form.student'}).'</span>');
1.103     albertel 4591: 	return;
                   4592:     }
1.398     albertel 4593:     my $result='<h3><span class="LC_info">&nbsp;'.$env{'form.title'}.'</span></h3>';
1.526     raeburn  4594:     $result.='<h3>&nbsp;'.&mt('Student: ').&nameUserString(undef,$env{'form.fullname'},$uname,$udom).
1.129     ng       4595: 	'</h3>'."\n";
1.70      ng       4596: 
1.68      ng       4597:     $request->print($result);
                   4598: 
1.582     raeburn  4599: 
1.132     bowersj2 4600:     my $navmap = Apache::lonnavmaps::navmap->new();
1.582     raeburn  4601:     unless (ref($navmap)) {
                   4602:         $request->print(&navmap_errormsg());
                   4603:         return;
                   4604:     }
1.257     albertel 4605:     my ($mapUrl, $id, $resUrl) = &Apache::lonnet::decode_symb( $env{'form.page'});
1.71      ng       4606:     my $map = $navmap->getResourceByUrl($resUrl); # add to navmaps
1.288     albertel 4607:     if (!$map) {
1.527     raeburn  4608: 	$request->print('<span class="LC_warning">'.&mt('Unable to grade requested sequence ([_1]).',$resUrl).'</span>');
1.288     albertel 4609: 	return; 
                   4610:     }
1.71      ng       4611:     my $iterator = $navmap->getIterator($map->map_start(),
                   4612: 					$map->map_finish());
1.70      ng       4613: 
1.484     albertel 4614:     my $studentTable=
                   4615: 	&Apache::loncommon::start_data_table().
                   4616: 	&Apache::loncommon::start_data_table_header_row().
1.485     albertel 4617: 	'<th align="center">&nbsp;'.&mt('Prob.').'&nbsp;</th>'.
                   4618: 	'<th>&nbsp;'.&mt('Title').'&nbsp;</th>'.
                   4619: 	'<th>&nbsp;'.&mt('Previous Score').'&nbsp;</th>'.
                   4620: 	'<th>&nbsp;'.&mt('New Score').'&nbsp;</th>'.
1.484     albertel 4621: 	&Apache::loncommon::end_data_table_header_row();
1.71      ng       4622: 
                   4623:     $iterator->next(); # skip the first BEGIN_MAP
                   4624:     my $curRes = $iterator->next(); # for "current resource"
1.196     albertel 4625:     my ($depth,$question,$prob,$changeflag)= (1,1,1,0);
1.101     albertel 4626:     while ($depth > 0) {
1.71      ng       4627:         if($curRes == $iterator->BEGIN_MAP) { $depth++; }
1.100     bowersj2 4628:         if($curRes == $iterator->END_MAP) { $depth--; }
1.71      ng       4629: 
1.385     albertel 4630:         if (ref($curRes) && $curRes->is_problem()) {
1.91      albertel 4631: 	    my $parts = $curRes->parts();
1.71      ng       4632:             my $title = $curRes->compTitle();
                   4633: 	    my $symbx = $curRes->symb();
1.484     albertel 4634: 	    $studentTable.=
                   4635: 		&Apache::loncommon::start_data_table_row().
                   4636: 		'<td align="center" valign="top" >'.$prob.
1.485     albertel 4637: 		(scalar(@{$parts}) == 1 ? '' 
1.526     raeburn  4638:                                         : '<br />('.&mt('[quant,_1,&nbsp;part]',scalar(@{$parts}))
                   4639: 		.')').'</td>';
1.71      ng       4640: 	    $studentTable.='<td valign="top">&nbsp;<b>'.$title.'</b>&nbsp;</td>';
                   4641: 
                   4642: 	    my %newrecord=();
                   4643: 	    my @displayPts=();
1.269     raeburn  4644:             my %aggregate = ();
                   4645:             my $aggregateflag = 0;
1.71      ng       4646: 	    foreach my $partid (@{$parts}) {
1.257     albertel 4647: 		my $newpts = $env{'form.GD_BOX'.$question.'_'.$partid};
                   4648: 		my $oldpts = $env{'form.oldpts'.$question.'_'.$partid};
1.71      ng       4649: 
1.257     albertel 4650: 		my $wgt = $env{'form.WGT'.$question.'_'.$partid} != 0 ? 
                   4651: 		    $env{'form.WGT'.$question.'_'.$partid} : 1;
1.71      ng       4652: 		my $partial = $newpts/$wgt;
                   4653: 		my $score;
                   4654: 		if ($partial > 0) {
                   4655: 		    $score = 'correct_by_override';
1.125     ng       4656: 		} elsif ($newpts ne '') { #empty is taken as 0
1.71      ng       4657: 		    $score = 'incorrect_by_override';
                   4658: 		}
1.257     albertel 4659: 		my $dropMenu = $env{'form.GD_SEL'.$question.'_'.$partid};
1.125     ng       4660: 		if ($dropMenu eq 'excused') {
1.71      ng       4661: 		    $partial = '';
                   4662: 		    $score = 'excused';
1.125     ng       4663: 		} elsif ($dropMenu eq 'reset status'
1.257     albertel 4664: 			 && $env{'form.solved'.$question.'_'.$partid} ne '') { #update only if previous record exists
1.125     ng       4665: 		    $newrecord{'resource.'.$partid.'.tries'} = 0;
                   4666: 		    $newrecord{'resource.'.$partid.'.solved'} = '';
                   4667: 		    $newrecord{'resource.'.$partid.'.award'} = '';
                   4668: 		    $newrecord{'resource.'.$partid.'.awarded'} = 0;
1.257     albertel 4669: 		    $newrecord{'resource.'.$partid.'.regrader'} = "$env{'user.name'}:$env{'user.domain'}";
1.125     ng       4670: 		    $changeflag++;
                   4671: 		    $newpts = '';
1.269     raeburn  4672:                     
                   4673:                     my $aggtries =  $env{'form.aggtries'.$question.'_'.$partid};
                   4674:                     my $totaltries = $env{'form.totaltries'.$question.'_'.$partid};
                   4675:                     my $solvedstatus = $env{'form.solved'.$question.'_'.$partid};
                   4676:                     if ($aggtries > 0) {
                   4677:                         &decrement_aggs($symbx,$partid,\%aggregate,$aggtries,$totaltries,$solvedstatus);
                   4678:                         $aggregateflag = 1;
                   4679:                     }
1.71      ng       4680: 		}
1.324     albertel 4681: 		my $display_part=&get_display_part($partid,$curRes->symb());
1.257     albertel 4682: 		my $oldstatus = $env{'form.solved'.$question.'_'.$partid};
1.526     raeburn  4683: 		$displayPts[0].='&nbsp;<b>'.&mt('Part').':</b> '.$display_part.' = '.
1.71      ng       4684: 		    (($oldstatus eq 'excused') ? 'excused' : $oldpts).
1.326     albertel 4685: 		    '&nbsp;<br />';
1.526     raeburn  4686: 		$displayPts[1].='&nbsp;<b>'.&mt('Part').':</b> '.$display_part.' = '.
1.125     ng       4687: 		     (($score eq 'excused') ? 'excused' : $newpts).
1.326     albertel 4688: 		    '&nbsp;<br />';
1.71      ng       4689: 		$question++;
1.380     albertel 4690: 		next if ($dropMenu eq 'reset status' || ($newpts eq $oldpts && $score ne 'excused'));
1.125     ng       4691: 
1.71      ng       4692: 		$newrecord{'resource.'.$partid.'.awarded'}  = $partial if $partial ne '';
1.125     ng       4693: 		$newrecord{'resource.'.$partid.'.solved'}   = $score if $score ne '';
1.257     albertel 4694: 		$newrecord{'resource.'.$partid.'.regrader'} = "$env{'user.name'}:$env{'user.domain'}"
1.125     ng       4695: 		    if (scalar(keys(%newrecord)) > 0);
1.71      ng       4696: 
                   4697: 		$changeflag++;
                   4698: 	    }
                   4699: 	    if (scalar(keys(%newrecord)) > 0) {
1.382     albertel 4700: 		my %record = 
                   4701: 		    &Apache::lonnet::restore($symbx,$env{'request.course.id'},
                   4702: 					     $udom,$uname);
                   4703: 
                   4704: 		if (&Apache::lonnet::validCODE($env{'form.CODE'})) {
                   4705: 		    $newrecord{'resource.CODE'} = $env{'form.CODE'};
                   4706: 		} elsif (&Apache::lonnet::validCODE($record{'resource.CODE'})) {
                   4707: 		    $newrecord{'resource.CODE'} = '';
                   4708: 		}
1.257     albertel 4709: 		&Apache::lonnet::cstore(\%newrecord,$symbx,$env{'request.course.id'},
1.71      ng       4710: 					$udom,$uname);
1.382     albertel 4711: 		%record = &Apache::lonnet::restore($symbx,
                   4712: 						   $env{'request.course.id'},
                   4713: 						   $udom,$uname);
1.380     albertel 4714: 		&check_and_remove_from_queue($parts,\%record,undef,$symbx,
                   4715: 					     $cdom,$cnum,$udom,$uname);
1.71      ng       4716: 	    }
1.380     albertel 4717: 	    
1.269     raeburn  4718:             if ($aggregateflag) {
                   4719:                 &Apache::lonnet::cinc('nohist_resourcetracker',\%aggregate,
                   4720:                       $env{'course.'.$env{'request.course.id'}.'.domain'},
                   4721:                       $env{'course.'.$env{'request.course.id'}.'.num'});
                   4722:             }
1.125     ng       4723: 
1.71      ng       4724: 	    $studentTable.='<td valign="top">'.$displayPts[0].'</td>'.
                   4725: 		'<td valign="top">'.$displayPts[1].'</td>'.
1.484     albertel 4726: 		&Apache::loncommon::end_data_table_row();
1.68      ng       4727: 
1.196     albertel 4728: 	    $prob++;
1.68      ng       4729: 	}
1.71      ng       4730:         $curRes = $iterator->next();
1.68      ng       4731:     }
1.98      albertel 4732: 
1.484     albertel 4733:     $studentTable.=&Apache::loncommon::end_data_table();
1.526     raeburn  4734:     my $grademsg=($changeflag == 0 ? &mt('No score was changed or updated.') :
                   4735: 		  &mt('The scores were changed for [quant,_1,problem].',
                   4736: 		  $changeflag));
1.76      ng       4737:     $request->print($grademsg.$studentTable);
1.68      ng       4738: 
1.70      ng       4739:     return '';
                   4740: }
                   4741: 
1.72      ng       4742: #-------- end of section for handling grading by page/sequence ---------
                   4743: #
                   4744: #-------------------------------------------------------------------
                   4745: 
1.581     www      4746: #-------------------- Bubblesheet (Scantron) Grading -------------------
1.75      albertel 4747: #
                   4748: #------ start of section for handling grading by page/sequence ---------
                   4749: 
1.423     albertel 4750: =pod
                   4751: 
                   4752: =head1 Bubble sheet grading routines
                   4753: 
1.424     albertel 4754:   For this documentation:
                   4755: 
                   4756:    'scanline' refers to the full line of characters
                   4757:    from the file that we are parsing that represents one entire sheet
                   4758: 
                   4759:    'bubble line' refers to the data
                   4760:    representing the line of bubbles that are on the physical bubble sheet
                   4761: 
                   4762: 
                   4763: The overall process is that a scanned in bubble sheet data is uploaded
                   4764: into a course. When a user wants to grade, they select a
                   4765: sequence/folder of resources, a file of bubble sheet info, and pick
                   4766: one of the predefined configurations for what each scanline looks
                   4767: like.
                   4768: 
                   4769: Next each scanline is checked for any errors of either 'missing
1.435     foxr     4770: bubbles' (it's an error because it may have been mis-scanned
1.424     albertel 4771: because too light bubbling), 'double bubble' (each bubble line should
                   4772: have no more that one letter picked), invalid or duplicated CODE,
1.556     weissno  4773: invalid student/employee ID
1.424     albertel 4774: 
                   4775: If the CODE option is used that determines the randomization of the
1.556     weissno  4776: homework problems, either way the student/employee ID is looked up into a
1.424     albertel 4777: username:domain.
                   4778: 
                   4779: During the validation phase the instructor can choose to skip scanlines. 
                   4780: 
1.435     foxr     4781: After the validation phase, there are now 3 bubble sheet files
1.424     albertel 4782: 
                   4783:   scantron_original_filename (unmodified original file)
                   4784:   scantron_corrected_filename (file where the corrected information has replaced the original information)
                   4785:   scantron_skipped_filename (contains the exact text of scanlines that where skipped)
                   4786: 
                   4787: Also there is a separate hash nohist_scantrondata that contains extra
                   4788: correction information that isn't representable in the bubble sheet
                   4789: file (see &scantron_getfile() for more information)
                   4790: 
                   4791: After all scanlines are either valid, marked as valid or skipped, then
                   4792: foreach line foreach problem in the picked sequence, an ssi request is
                   4793: made that simulates a user submitting their selected letter(s) against
                   4794: the homework problem.
1.423     albertel 4795: 
                   4796: =over 4
                   4797: 
                   4798: 
                   4799: 
                   4800: =item defaultFormData
                   4801: 
                   4802:   Returns html hidden inputs used to hold context/default values.
                   4803: 
                   4804:  Arguments:
                   4805:   $symb - $symb of the current resource 
                   4806: 
                   4807: =cut
1.422     foxr     4808: 
1.81      albertel 4809: sub defaultFormData {
1.324     albertel 4810:     my ($symb)=@_;
1.613     www      4811:     return '<input type="hidden" name="symb"    value="'.&Apache::lonenc::check_encrypt($symb).'" />';
1.81      albertel 4812: }
                   4813: 
1.447     foxr     4814: 
1.423     albertel 4815: =pod 
                   4816: 
                   4817: =item getSequenceDropDown
                   4818: 
                   4819:    Return html dropdown of possible sequences to grade
                   4820:  
                   4821:  Arguments:
1.582     raeburn  4822:    $symb - $symb of the current resource
                   4823:    $map_error - ref to scalar which will container error if
                   4824:                 $navmap object is unavailable in &getSymbMap().
1.423     albertel 4825: 
                   4826: =cut
1.422     foxr     4827: 
1.75      albertel 4828: sub getSequenceDropDown {
1.582     raeburn  4829:     my ($symb,$map_error)=@_;
1.75      albertel 4830:     my $result='<select name="selectpage">'."\n";
1.582     raeburn  4831:     my ($titles,$symbx) = &getSymbMap($map_error);
                   4832:     if (ref($map_error)) {
                   4833:         return if ($$map_error);
                   4834:     }
1.137     albertel 4835:     my ($curpage)=&Apache::lonnet::decode_symb($symb); 
1.75      albertel 4836:     my $ctr=0;
                   4837:     foreach (@$titles) {
                   4838: 	my ($minder,$showtitle) = ($_ =~ /(\d+)\.(.*)/);
                   4839: 	$result.='<option value="'.$$symbx{$_}.'" '.
1.401     albertel 4840: 	    ($$symbx{$_} =~ /$curpage$/ ? 'selected="selected"' : '').
1.75      albertel 4841: 	    '>'.$showtitle.'</option>'."\n";
                   4842: 	$ctr++;
                   4843:     }
                   4844:     $result.= '</select>';
                   4845:     return $result;
                   4846: }
                   4847: 
1.495     albertel 4848: my %bubble_lines_per_response;     # no. bubble lines for each response.
1.554     raeburn  4849:                                    # key is zero-based index - 0, 1, 2 ...
1.495     albertel 4850: 
                   4851: my %first_bubble_line;             # First bubble line no. for each bubble.
                   4852: 
1.509     raeburn  4853: my %subdivided_bubble_lines;       # no. bubble lines for optionresponse, 
                   4854:                                    # matchresponse or rankresponse, where 
                   4855:                                    # an individual response can have multiple 
                   4856:                                    # lines
1.503     raeburn  4857: 
                   4858: my %responsetype_per_response;     # responsetype for each response
                   4859: 
1.495     albertel 4860: # Save and restore the bubble lines array to the form env.
                   4861: 
                   4862: 
                   4863: sub save_bubble_lines {
                   4864:     foreach my $line (keys(%bubble_lines_per_response)) {
                   4865: 	$env{"form.scantron.bubblelines.$line"}  = $bubble_lines_per_response{$line};
                   4866: 	$env{"form.scantron.first_bubble_line.$line"} =
                   4867: 	    $first_bubble_line{$line};
1.503     raeburn  4868:         $env{"form.scantron.sub_bubblelines.$line"} = 
                   4869:             $subdivided_bubble_lines{$line};
                   4870:         $env{"form.scantron.responsetype.$line"} =
                   4871:             $responsetype_per_response{$line};
1.495     albertel 4872:     }
                   4873: }
                   4874: 
                   4875: 
                   4876: sub restore_bubble_lines {
                   4877:     my $line = 0;
                   4878:     %bubble_lines_per_response = ();
                   4879:     while ($env{"form.scantron.bubblelines.$line"}) {
                   4880: 	my $value = $env{"form.scantron.bubblelines.$line"};
                   4881: 	$bubble_lines_per_response{$line} = $value;
                   4882: 	$first_bubble_line{$line}  =
                   4883: 	    $env{"form.scantron.first_bubble_line.$line"};
1.503     raeburn  4884:         $subdivided_bubble_lines{$line} =
                   4885:             $env{"form.scantron.sub_bubblelines.$line"};
                   4886:         $responsetype_per_response{$line} =
                   4887:             $env{"form.scantron.responsetype.$line"};
1.495     albertel 4888: 	$line++;
                   4889:     }
                   4890: }
                   4891: 
                   4892: #  Given the parsed scanline, get the response for 
                   4893: #  'answer' number n:
                   4894: 
                   4895: sub get_response_bubbles {
                   4896:     my ($parsed_line, $response)  = @_;
                   4897: 
                   4898:     my $bubble_line = $first_bubble_line{$response-1} +1;
                   4899:     my $bubble_lines= $bubble_lines_per_response{$response-1};
                   4900:     
                   4901:     my $selected = "";
                   4902: 
                   4903:     for (my $bline = 0; $bline < $bubble_lines; $bline++) {
                   4904: 	$selected .= $$parsed_line{"scantron.$bubble_line.answer"}.":";
                   4905: 	$bubble_line++;
                   4906:     }
                   4907:     return $selected;
                   4908: }
1.423     albertel 4909: 
                   4910: =pod 
                   4911: 
                   4912: =item scantron_filenames
                   4913: 
                   4914:    Returns a list of the scantron files in the current course 
                   4915: 
                   4916: =cut
1.422     foxr     4917: 
1.202     albertel 4918: sub scantron_filenames {
1.257     albertel 4919:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
                   4920:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
1.517     raeburn  4921:     my $getpropath = 1;
1.157     albertel 4922:     my @files=&Apache::lonnet::dirlist('userfiles',$cdom,$cname,
1.517     raeburn  4923:                                        $getpropath);
1.202     albertel 4924:     my @possiblenames;
1.201     albertel 4925:     foreach my $filename (sort(@files)) {
1.157     albertel 4926: 	($filename)=split(/&/,$filename);
                   4927: 	if ($filename!~/^scantron_orig_/) { next ; }
                   4928: 	$filename=~s/^scantron_orig_//;
1.202     albertel 4929: 	push(@possiblenames,$filename);
                   4930:     }
                   4931:     return @possiblenames;
                   4932: }
                   4933: 
1.423     albertel 4934: =pod 
                   4935: 
                   4936: =item scantron_uploads
                   4937: 
                   4938:    Returns  html drop-down list of scantron files in current course.
                   4939: 
                   4940:  Arguments:
                   4941:    $file2grade - filename to set as selected in the dropdown
                   4942: 
                   4943: =cut
1.422     foxr     4944: 
1.202     albertel 4945: sub scantron_uploads {
1.209     ng       4946:     my ($file2grade) = @_;
1.202     albertel 4947:     my $result=	'<select name="scantron_selectfile">';
                   4948:     $result.="<option></option>";
                   4949:     foreach my $filename (sort(&scantron_filenames())) {
1.401     albertel 4950: 	$result.="<option".($filename eq $file2grade ? ' selected="selected"':'').">$filename</option>\n";
1.81      albertel 4951:     }
                   4952:     $result.="</select>";
                   4953:     return $result;
                   4954: }
                   4955: 
1.423     albertel 4956: =pod 
                   4957: 
                   4958: =item scantron_scantab
                   4959: 
                   4960:   Returns html drop down of the scantron formats in the scantronformat.tab
                   4961:   file.
                   4962: 
                   4963: =cut
1.422     foxr     4964: 
1.82      albertel 4965: sub scantron_scantab {
                   4966:     my $result='<select name="scantron_format">'."\n";
1.191     albertel 4967:     $result.='<option></option>'."\n";
1.518     raeburn  4968:     my @lines = &get_scantronformat_file();
                   4969:     if (@lines > 0) {
                   4970:         foreach my $line (@lines) {
                   4971:             next if (($line =~ /^\#/) || ($line eq ''));
                   4972: 	    my ($name,$descrip)=split(/:/,$line);
                   4973: 	    $result.='<option value="'.$name.'">'.$descrip.'</option>'."\n";
                   4974:         }
1.82      albertel 4975:     }
                   4976:     $result.='</select>'."\n";
1.518     raeburn  4977:     return $result;
                   4978: }
                   4979: 
                   4980: =pod
                   4981: 
                   4982: =item get_scantronformat_file
                   4983: 
                   4984:   Returns an array containing lines from the scantron format file for
                   4985:   the domain of the course.
                   4986: 
                   4987:   If a url for a custom.tab file is listed in domain's configuration.db, 
                   4988:   lines are from this file.
                   4989: 
                   4990:   Otherwise, if a default.tab has been published in RES space by the 
                   4991:   domainconfig user, lines are from this file.
                   4992: 
                   4993:   Otherwise, fall back to getting lines from the legacy file on the
1.519     raeburn  4994:   local server:  /home/httpd/lonTabs/default_scantronformat.tab    
1.82      albertel 4995: 
1.518     raeburn  4996: =cut
                   4997: 
                   4998: sub get_scantronformat_file {
                   4999:     my $cdom= $env{'course.'.$env{'request.course.id'}.'.domain'};
                   5000:     my %domconfig = &Apache::lonnet::get_dom('configuration',['scantron'],$cdom);
                   5001:     my $gottab = 0;
                   5002:     my @lines;
                   5003:     if (ref($domconfig{'scantron'}) eq 'HASH') {
                   5004:         if ($domconfig{'scantron'}{'scantronformat'} ne '') {
                   5005:             my $formatfile = &Apache::lonnet::getfile($Apache::lonnet::perlvar{'lonDocRoot'}.$domconfig{'scantron'}{'scantronformat'});
                   5006:             if ($formatfile ne '-1') {
                   5007:                 @lines = split("\n",$formatfile,-1);
                   5008:                 $gottab = 1;
                   5009:             }
                   5010:         }
                   5011:     }
                   5012:     if (!$gottab) {
                   5013:         my $confname = $cdom.'-domainconfig';
                   5014:         my $default = $Apache::lonnet::perlvar{'lonDocRoot'}.'/res/'.$cdom.'/'.$confname.'/default.tab';
                   5015:         my $formatfile =  &Apache::lonnet::getfile($default);
                   5016:         if ($formatfile ne '-1') {
                   5017:             @lines = split("\n",$formatfile,-1);
                   5018:             $gottab = 1;
                   5019:         }
                   5020:     }
                   5021:     if (!$gottab) {
1.519     raeburn  5022:         my @domains = &Apache::lonnet::current_machine_domains();
                   5023:         if (grep(/^\Q$cdom\E$/,@domains)) {
                   5024:             my $fh=Apache::File->new($Apache::lonnet::perlvar{'lonTabDir'}.'/scantronformat.tab');
                   5025:             @lines = <$fh>;
                   5026:             close($fh);
                   5027:         } else {
                   5028:             my $fh=Apache::File->new($Apache::lonnet::perlvar{'lonTabDir'}.'/default_scantronformat.tab');
                   5029:             @lines = <$fh>;
                   5030:             close($fh);
                   5031:         }
1.518     raeburn  5032:     }
                   5033:     return @lines;
1.82      albertel 5034: }
                   5035: 
1.423     albertel 5036: =pod 
                   5037: 
                   5038: =item scantron_CODElist
                   5039: 
                   5040:   Returns html drop down of the saved CODE lists from current course,
                   5041:   generated from earlier printings.
                   5042: 
                   5043: =cut
1.422     foxr     5044: 
1.186     albertel 5045: sub scantron_CODElist {
1.257     albertel 5046:     my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   5047:     my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
1.186     albertel 5048:     my @names=&Apache::lonnet::getkeys('CODEs',$cdom,$cnum);
                   5049:     my $namechoice='<option></option>';
1.225     albertel 5050:     foreach my $name (sort {uc($a) cmp uc($b)} @names) {
1.191     albertel 5051: 	if ($name =~ /^error: 2 /) { next; }
1.278     albertel 5052: 	if ($name =~ /^type\0/) { next; }
1.186     albertel 5053: 	$namechoice.='<option value="'.$name.'">'.$name.'</option>';
                   5054:     }
                   5055:     $namechoice='<select name="scantron_CODElist">'.$namechoice.'</select>';
                   5056:     return $namechoice;
                   5057: }
                   5058: 
1.423     albertel 5059: =pod 
                   5060: 
                   5061: =item scantron_CODEunique
                   5062: 
                   5063:   Returns the html for "Each CODE to be used once" radio.
                   5064: 
                   5065: =cut
1.422     foxr     5066: 
1.186     albertel 5067: sub scantron_CODEunique {
1.532     bisitz   5068:     my $result='<span class="LC_nobreak">
1.272     albertel 5069:                  <label><input type="radio" name="scantron_CODEunique"
1.423     albertel 5070:                         value="yes" checked="checked" />'.&mt('Yes').' </label>
1.381     albertel 5071:                 </span>
1.532     bisitz   5072:                 <span class="LC_nobreak">
1.272     albertel 5073:                  <label><input type="radio" name="scantron_CODEunique"
1.423     albertel 5074:                         value="no" />'.&mt('No').' </label>
1.381     albertel 5075:                 </span>';
1.186     albertel 5076:     return $result;
                   5077: }
1.423     albertel 5078: 
                   5079: =pod 
                   5080: 
                   5081: =item scantron_selectphase
                   5082: 
                   5083:   Generates the initial screen to start the bubble sheet process.
                   5084:   Allows for - starting a grading run.
1.424     albertel 5085:              - downloading existing scan data (original, corrected
1.423     albertel 5086:                                                 or skipped info)
                   5087: 
                   5088:              - uploading new scan data
                   5089: 
                   5090:  Arguments:
                   5091:   $r          - The Apache request object
                   5092:   $file2grade - name of the file that contain the scanned data to score
                   5093: 
                   5094: =cut
1.186     albertel 5095: 
1.75      albertel 5096: sub scantron_selectphase {
1.608     www      5097:     my ($r,$file2grade,$symb) = @_;
1.75      albertel 5098:     if (!$symb) {return '';}
1.582     raeburn  5099:     my $map_error;
                   5100:     my $sequence_selector=&getSequenceDropDown($symb,\$map_error);
                   5101:     if ($map_error) {
                   5102:         $r->print('<br />'.&navmap_errormsg().'<br />');
                   5103:         return;
                   5104:     }
1.324     albertel 5105:     my $default_form_data=&defaultFormData($symb);
1.209     ng       5106:     my $file_selector=&scantron_uploads($file2grade);
1.82      albertel 5107:     my $format_selector=&scantron_scantab();
1.186     albertel 5108:     my $CODE_selector=&scantron_CODElist();
                   5109:     my $CODE_unique=&scantron_CODEunique();
1.75      albertel 5110:     my $result;
1.422     foxr     5111: 
1.513     foxr     5112:     $ssi_error = 0;
                   5113: 
1.606     wenzelju 5114:     if (&Apache::lonnet::allowed('usc',$env{'request.role.domain'}) ||
                   5115:         &Apache::lonnet::allowed('usc',$env{'request.course.id'})) {
                   5116: 
                   5117: 	# Chunk of form to prompt for a scantron file upload.
                   5118: 
                   5119:         $r->print('
                   5120:     <br />
                   5121:     '.&Apache::loncommon::start_data_table('LC_scantron_action').'
                   5122:        '.&Apache::loncommon::start_data_table_header_row().'
                   5123:             <th>
                   5124:               &nbsp;'.&mt('Specify a bubblesheet data file to upload.').'
                   5125:             </th>
                   5126:        '.&Apache::loncommon::end_data_table_header_row().'
                   5127:        '.&Apache::loncommon::start_data_table_row().'
                   5128:             <td>
                   5129: ');
1.608     www      5130:     my $default_form_data=&defaultFormData($symb);
1.606     wenzelju 5131:     my $cdom= $env{'course.'.$env{'request.course.id'}.'.domain'};
                   5132:     my $cnum= $env{'course.'.$env{'request.course.id'}.'.num'};
                   5133:     $r->print(&Apache::lonhtmlcommon::scripttag('
                   5134:     function checkUpload(formname) {
                   5135: 	if (formname.upfile.value == "") {
                   5136: 	    alert("'.&mt('Please use the browse button to select a file from your local directory.').'");
                   5137: 	    return false;
                   5138: 	}
                   5139: 	formname.submit();
                   5140:     }'));
                   5141:     $r->print('
                   5142:               <form enctype="multipart/form-data" action="/adm/grades" name="rules" method="post">
                   5143:                 '.$default_form_data.'
                   5144:                 <input name="courseid" type="hidden" value="'.$cnum.'" />
                   5145:                 <input name="domainid" type="hidden" value="'.$cdom.'" />
                   5146:                 <input name="command" value="scantronupload_save" type="hidden" />
                   5147:                 '.&mt('File to upload: [_1]','<input type="file" name="upfile" size="50" />').'
                   5148:                 <br />
                   5149:                 <input type="button" onclick="javascript:checkUpload(this.form);" value="'.&mt('Upload Bubblesheet Data').'" />
                   5150:               </form>
                   5151: ');
                   5152: 
                   5153:         $r->print('
                   5154:             </td>
                   5155:        '.&Apache::loncommon::end_data_table_row().'
                   5156:        '.&Apache::loncommon::end_data_table().'
                   5157: ');
                   5158:     }
                   5159: 
1.422     foxr     5160:     # Chunk of form to prompt for a file to grade and how:
                   5161: 
1.489     albertel 5162:     $result.= '
                   5163:     <br />
                   5164:     <form method="post" enctype="multipart/form-data" action="/adm/grades" name="scantron_process">
                   5165:     <input type="hidden" name="command" value="scantron_warning" />
                   5166:     '.$default_form_data.'
                   5167:     '.&Apache::loncommon::start_data_table('LC_scantron_action').'
                   5168:        '.&Apache::loncommon::start_data_table_header_row().'
                   5169:             <th colspan="2">
1.492     albertel 5170:               &nbsp;'.&mt('Specify file and which Folder/Sequence to grade').'
1.489     albertel 5171:             </th>
                   5172:        '.&Apache::loncommon::end_data_table_header_row().'
                   5173:        '.&Apache::loncommon::start_data_table_row().'
1.492     albertel 5174:             <td> '.&mt('Sequence to grade:').' </td><td> '.$sequence_selector.' </td>
1.489     albertel 5175:        '.&Apache::loncommon::end_data_table_row().'
                   5176:        '.&Apache::loncommon::start_data_table_row().'
1.572     www      5177:             <td> '.&mt('Filename of bubblesheet data file:').' </td><td> '.$file_selector.' </td>
1.489     albertel 5178:        '.&Apache::loncommon::end_data_table_row().'
                   5179:        '.&Apache::loncommon::start_data_table_row().'
1.572     www      5180:             <td> '.&mt('Format of bubblesheet data file:').' </td><td> '.$format_selector.' </td>
1.489     albertel 5181:        '.&Apache::loncommon::end_data_table_row().'
                   5182:        '.&Apache::loncommon::start_data_table_row().'
1.492     albertel 5183:             <td> '.&mt('Saved CODEs to validate against:').' </td><td> '.$CODE_selector.' </td>
1.489     albertel 5184:        '.&Apache::loncommon::end_data_table_row().'
                   5185:        '.&Apache::loncommon::start_data_table_row().'
1.492     albertel 5186:             <td> '.&mt('Each CODE is only to be used once:').'</td><td> '.$CODE_unique.' </td>
1.489     albertel 5187:        '.&Apache::loncommon::end_data_table_row().'
                   5188:        '.&Apache::loncommon::start_data_table_row().'
1.492     albertel 5189: 	    <td> '.&mt('Options:').' </td>
1.187     albertel 5190:             <td>
1.492     albertel 5191: 	       <label><input type="checkbox" name="scantron_options_redo" value="redo_skipped"/> '.&mt('Do only previously skipped records').'</label> <br />
                   5192:                <label><input type="checkbox" name="scantron_options_ignore" value="ignore_corrections"/> '.&mt('Remove all existing corrections').'</label> <br />
                   5193:                <label><input type="checkbox" name="scantron_options_hidden" value="ignore_hidden"/> '.&mt('Skip hidden resources when grading').'</label>
1.187     albertel 5194: 	    </td>
1.489     albertel 5195:        '.&Apache::loncommon::end_data_table_row().'
                   5196:        '.&Apache::loncommon::start_data_table_row().'
1.174     albertel 5197:             <td colspan="2">
1.572     www      5198:               <input type="submit" value="'.&mt('Grading: Validate Bubblesheet Records').'" />
1.162     albertel 5199:             </td>
1.489     albertel 5200:        '.&Apache::loncommon::end_data_table_row().'
                   5201:     '.&Apache::loncommon::end_data_table().'
                   5202:     </form>
                   5203: ';
1.162     albertel 5204:    
                   5205:     $r->print($result);
                   5206: 
1.422     foxr     5207: 
                   5208: 
                   5209:     # Chunk of the form that prompts to view a scoring office file,
                   5210:     # corrected file, skipped records in a file.
                   5211: 
1.489     albertel 5212:     $r->print('
                   5213:    <br />
                   5214:    <form action="/adm/grades" name="scantron_download">
                   5215:      '.$default_form_data.'
                   5216:      <input type="hidden" name="command" value="scantron_download" />
                   5217:      '.&Apache::loncommon::start_data_table('LC_scantron_action').'
                   5218:        '.&Apache::loncommon::start_data_table_header_row().'
                   5219:               <th>
1.492     albertel 5220:                 &nbsp;'.&mt('Download a scoring office file').'
1.489     albertel 5221:               </th>
                   5222:        '.&Apache::loncommon::end_data_table_header_row().'
                   5223:        '.&Apache::loncommon::start_data_table_row().'
1.492     albertel 5224:               <td> '.&mt('Filename of scoring office file: [_1]',$file_selector).' 
1.489     albertel 5225:                 <br />
1.492     albertel 5226:                 <input type="submit" value="'.&mt('Download: Show List of Associated Files').'" />
1.489     albertel 5227:        '.&Apache::loncommon::end_data_table_row().'
                   5228:      '.&Apache::loncommon::end_data_table().'
                   5229:    </form>
                   5230:    <br />
                   5231: ');
1.162     albertel 5232: 
1.457     banghart 5233:     &Apache::lonpickcode::code_list($r,2);
1.523     raeburn  5234: 
1.528     raeburn  5235:     $r->print('<br /><form method="post" name="checkscantron">'.
1.523     raeburn  5236:              $default_form_data."\n".
                   5237:              &Apache::loncommon::start_data_table('LC_scantron_action')."\n".
                   5238:              &Apache::loncommon::start_data_table_header_row()."\n".
                   5239:              '<th colspan="2">
1.572     www      5240:               &nbsp;'.&mt('Review bubblesheet data and submissions for a previously graded folder/sequence')."\n".
1.523     raeburn  5241:              '</th>'."\n".
                   5242:               &Apache::loncommon::end_data_table_header_row()."\n".
                   5243:               &Apache::loncommon::start_data_table_row()."\n".
                   5244:               '<td> '.&mt('Graded folder/sequence:').' </td>'."\n".
                   5245:               '<td> '.$sequence_selector.' </td>'.
                   5246:               &Apache::loncommon::end_data_table_row()."\n".
                   5247:               &Apache::loncommon::start_data_table_row()."\n".
                   5248:               '<td> '.&mt('Filename of scoring office file:').' </td>'."\n".
                   5249:               '<td> '.$file_selector.' </td>'."\n".
                   5250:               &Apache::loncommon::end_data_table_row()."\n".
                   5251:               &Apache::loncommon::start_data_table_row()."\n".
                   5252:               '<td> '.&mt('Format of data file:').' </td>'."\n".
                   5253:               '<td> '.$format_selector.' </td>'."\n".
                   5254:               &Apache::loncommon::end_data_table_row()."\n".
                   5255:               &Apache::loncommon::start_data_table_row()."\n".
1.557     raeburn  5256:               '<td> '.&mt('Options').' </td>'."\n".
                   5257:               '<td> <label><input type="checkbox" name="scantron_options_hidden" value="ignore_hidden"/> '.&mt('Skip hidden resources').'</label></td>'.
                   5258:               &Apache::loncommon::end_data_table_row()."\n".
                   5259:               &Apache::loncommon::start_data_table_row()."\n".
1.523     raeburn  5260:               '<td colspan="2">'."\n".
                   5261:               '<input type="hidden" name="command" value="checksubmissions" />'."\n".
1.575     www      5262:               '<input type="submit" value="'.&mt('Review Bubblesheet Data and Submission Records').'" />'."\n".
1.523     raeburn  5263:               '</td>'."\n".
                   5264:               &Apache::loncommon::end_data_table_row()."\n".
                   5265:               &Apache::loncommon::end_data_table()."\n".
                   5266:               '</form><br />');
                   5267:     return;
1.75      albertel 5268: }
                   5269: 
1.423     albertel 5270: =pod
                   5271: 
                   5272: =item get_scantron_config
                   5273: 
                   5274:    Parse and return the scantron configuration line selected as a
                   5275:    hash of configuration file fields.
                   5276: 
                   5277:  Arguments:
                   5278:     which - the name of the configuration to parse from the file.
                   5279: 
                   5280: 
                   5281:  Returns:
                   5282:             If the named configuration is not in the file, an empty
                   5283:             hash is returned.
                   5284:     a hash with the fields
                   5285:       name         - internal name for the this configuration setup
                   5286:       description  - text to display to operator that describes this config
                   5287:       CODElocation - if 0 or the string 'none'
                   5288:                           - no CODE exists for this config
                   5289:                      if -1 || the string 'letter'
                   5290:                           - a CODE exists for this config and is
                   5291:                             a string of letters
                   5292:                      Unsupported value (but planned for future support)
                   5293:                           if a positive integer
                   5294:                                - The CODE exists as the first n items from
                   5295:                                  the question section of the form
                   5296:                           if the string 'number'
                   5297:                                - The CODE exists for this config and is
                   5298:                                  a string of numbers
                   5299:       CODEstart   - (only matter if a CODE exists) column in the line where
                   5300:                      the CODE starts
                   5301:       CODElength  - length of the CODE
1.573     bisitz   5302:       IDstart     - column where the student/employee ID starts
1.556     weissno  5303:       IDlength    - length of the student/employee ID info
1.423     albertel 5304:       Qstart      - column where the information from the bubbled
                   5305:                     'questions' start
                   5306:       Qlength     - number of columns comprising a single bubble line from
                   5307:                     the sheet. (usually either 1 or 10)
1.424     albertel 5308:       Qon         - either a single character representing the character used
1.423     albertel 5309:                     to signal a bubble was chosen in the positional setup, or
                   5310:                     the string 'letter' if the letter of the chosen bubble is
                   5311:                     in the final, or 'number' if a number representing the
                   5312:                     chosen bubble is in the file (1->A 0->J)
1.424     albertel 5313:       Qoff        - the character used to represent that a bubble was
                   5314:                     left blank
1.423     albertel 5315:       PaperID     - if the scanning process generates a unique number for each
                   5316:                     sheet scanned the column that this ID number starts in
                   5317:       PaperIDlength - number of columns that comprise the unique ID number
                   5318:                       for the sheet of paper
1.424     albertel 5319:       FirstName   - column that the first name starts in
1.423     albertel 5320:       FirstNameLength - number of columns that the first name spans
                   5321:  
                   5322:       LastName    - column that the last name starts in
                   5323:       LastNameLength - number of columns that the last name spans
                   5324: 
                   5325: =cut
1.422     foxr     5326: 
1.82      albertel 5327: sub get_scantron_config {
                   5328:     my ($which) = @_;
1.518     raeburn  5329:     my @lines = &get_scantronformat_file();
1.82      albertel 5330:     my %config;
1.157     albertel 5331:     #FIXME probably should move to XML it has already gotten a bit much now
1.518     raeburn  5332:     foreach my $line (@lines) {
1.82      albertel 5333: 	my ($name,$descrip)=split(/:/,$line);
                   5334: 	if ($name ne $which ) { next; }
                   5335: 	chomp($line);
                   5336: 	my @config=split(/:/,$line);
                   5337: 	$config{'name'}=$config[0];
                   5338: 	$config{'description'}=$config[1];
                   5339: 	$config{'CODElocation'}=$config[2];
                   5340: 	$config{'CODEstart'}=$config[3];
                   5341: 	$config{'CODElength'}=$config[4];
                   5342: 	$config{'IDstart'}=$config[5];
                   5343: 	$config{'IDlength'}=$config[6];
                   5344: 	$config{'Qstart'}=$config[7];
1.497     foxr     5345:  	$config{'Qlength'}=$config[8];
1.82      albertel 5346: 	$config{'Qoff'}=$config[9];
                   5347: 	$config{'Qon'}=$config[10];
1.157     albertel 5348: 	$config{'PaperID'}=$config[11];
                   5349: 	$config{'PaperIDlength'}=$config[12];
                   5350: 	$config{'FirstName'}=$config[13];
                   5351: 	$config{'FirstNamelength'}=$config[14];
                   5352: 	$config{'LastName'}=$config[15];
                   5353: 	$config{'LastNamelength'}=$config[16];
1.82      albertel 5354: 	last;
                   5355:     }
                   5356:     return %config;
                   5357: }
                   5358: 
1.423     albertel 5359: =pod 
                   5360: 
                   5361: =item username_to_idmap
                   5362: 
1.556     weissno  5363:     creates a hash keyed by student/employee ID with values of the corresponding
1.423     albertel 5364:     student username:domain.
                   5365: 
                   5366:   Arguments:
                   5367: 
                   5368:     $classlist - reference to the class list hash. This is a hash
                   5369:                  keyed by student name:domain  whose elements are references
1.424     albertel 5370:                  to arrays containing various chunks of information
1.423     albertel 5371:                  about the student. (See loncoursedata for more info).
                   5372: 
                   5373:   Returns
                   5374:     %idmap - the constructed hash
                   5375: 
                   5376: =cut
                   5377: 
1.82      albertel 5378: sub username_to_idmap {
                   5379:     my ($classlist)= @_;
                   5380:     my %idmap;
                   5381:     foreach my $student (keys(%$classlist)) {
                   5382: 	$idmap{$classlist->{$student}->[&Apache::loncoursedata::CL_ID]}=
                   5383: 	    $student;
                   5384:     }
                   5385:     return %idmap;
                   5386: }
1.423     albertel 5387: 
                   5388: =pod
                   5389: 
1.424     albertel 5390: =item scantron_fixup_scanline
1.423     albertel 5391: 
                   5392:    Process a requested correction to a scanline.
                   5393: 
                   5394:   Arguments:
                   5395:     $scantron_config   - hash from &get_scantron_config()
                   5396:     $scan_data         - hash of correction information 
                   5397:                           (see &scantron_getfile())
                   5398:     $line              - existing scanline
                   5399:     $whichline         - line number of the passed in scanline
                   5400:     $field             - type of change to process 
                   5401:                          (either 
1.573     bisitz   5402:                           'ID'     -> correct the student/employee ID
1.423     albertel 5403:                           'CODE'   -> correct the CODE
                   5404:                           'answer' -> fixup the submitted answers)
                   5405:     
                   5406:    $args               - hash of additional info,
                   5407:                           - 'ID' 
                   5408:                                'newid' -> studentID to use in replacement
1.424     albertel 5409:                                           of existing one
1.423     albertel 5410:                           - 'CODE' 
                   5411:                                'CODE_ignore_dup' - set to true if duplicates
                   5412:                                                    should be ignored.
                   5413: 	                       'CODE' - is new code or 'use_unfound'
1.424     albertel 5414:                                         if the existing unfound code should
1.423     albertel 5415:                                         be used as is
                   5416:                           - 'answer'
                   5417:                                'response' - new answer or 'none' if blank
                   5418:                                'question' - the bubble line to change
1.503     raeburn  5419:                                'questionnum' - the question identifier,
                   5420:                                                may include subquestion. 
1.423     albertel 5421: 
                   5422:   Returns:
                   5423:     $line - the modified scanline
                   5424: 
                   5425:   Side effects: 
                   5426:     $scan_data - may be updated
                   5427: 
                   5428: =cut
                   5429: 
1.82      albertel 5430: 
1.157     albertel 5431: sub scantron_fixup_scanline {
                   5432:     my ($scantron_config,$scan_data,$line,$whichline,$field,$args)=@_;
                   5433:     if ($field eq 'ID') {
                   5434: 	if (length($args->{'newid'}) > $$scantron_config{'IDlength'}) {
1.186     albertel 5435: 	    return ($line,1,'New value too large');
1.157     albertel 5436: 	}
                   5437: 	if (length($args->{'newid'}) < $$scantron_config{'IDlength'}) {
                   5438: 	    $args->{'newid'}=sprintf('%-'.$$scantron_config{'IDlength'}.'s',
                   5439: 				     $args->{'newid'});
                   5440: 	}
                   5441: 	substr($line,$$scantron_config{'IDstart'}-1,
                   5442: 	       $$scantron_config{'IDlength'})=$args->{'newid'};
                   5443: 	if ($args->{'newid'}=~/^\s*$/) {
                   5444: 	    &scan_data($scan_data,"$whichline.user",
                   5445: 		       $args->{'username'}.':'.$args->{'domain'});
                   5446: 	}
1.186     albertel 5447:     } elsif ($field eq 'CODE') {
1.192     albertel 5448: 	if ($args->{'CODE_ignore_dup'}) {
                   5449: 	    &scan_data($scan_data,"$whichline.CODE_ignore_dup",'1');
                   5450: 	}
                   5451: 	&scan_data($scan_data,"$whichline.useCODE",'1');
                   5452: 	if ($args->{'CODE'} ne 'use_unfound') {
1.191     albertel 5453: 	    if (length($args->{'CODE'}) > $$scantron_config{'CODElength'}) {
                   5454: 		return ($line,1,'New CODE value too large');
                   5455: 	    }
                   5456: 	    if (length($args->{'CODE'}) < $$scantron_config{'CODElength'}) {
                   5457: 		$args->{'CODE'}=sprintf('%-'.$$scantron_config{'CODElength'}.'s',$args->{'CODE'});
                   5458: 	    }
                   5459: 	    substr($line,$$scantron_config{'CODEstart'}-1,
                   5460: 		   $$scantron_config{'CODElength'})=$args->{'CODE'};
1.186     albertel 5461: 	}
1.157     albertel 5462:     } elsif ($field eq 'answer') {
1.497     foxr     5463: 	my $length=$scantron_config->{'Qlength'};
1.157     albertel 5464: 	my $off=$scantron_config->{'Qoff'};
                   5465: 	my $on=$scantron_config->{'Qon'};
1.497     foxr     5466: 	my $answer=${off}x$length;
                   5467: 	if ($args->{'response'} eq 'none') {
                   5468: 	    &scan_data($scan_data,
1.503     raeburn  5469: 		       "$whichline.no_bubble.".$args->{'questionnum'},'1');
1.497     foxr     5470: 	} else {
                   5471: 	    if ($on eq 'letter') {
                   5472: 		my @alphabet=('A'..'Z');
                   5473: 		$answer=$alphabet[$args->{'response'}];
                   5474: 	    } elsif ($on eq 'number') {
                   5475: 		$answer=$args->{'response'}+1;
                   5476: 		if ($answer == 10) { $answer = '0'; }
1.274     albertel 5477: 	    } else {
1.497     foxr     5478: 		substr($answer,$args->{'response'},1)=$on;
1.274     albertel 5479: 	    }
1.497     foxr     5480: 	    &scan_data($scan_data,
1.503     raeburn  5481: 		       "$whichline.no_bubble.".$args->{'questionnum'},undef,'1');
1.157     albertel 5482: 	}
1.497     foxr     5483: 	my $where=$length*($args->{'question'}-1)+$scantron_config->{'Qstart'};
                   5484: 	substr($line,$where-1,$length)=$answer;
1.157     albertel 5485:     }
                   5486:     return $line;
                   5487: }
1.423     albertel 5488: 
                   5489: =pod
                   5490: 
                   5491: =item scan_data
                   5492: 
                   5493:     Edit or look up  an item in the scan_data hash.
                   5494: 
                   5495:   Arguments:
                   5496:     $scan_data  - The hash (see scantron_getfile)
                   5497:     $key        - shorthand of the key to edit (actual key is
1.424     albertel 5498:                   scantronfilename_key).
1.423     albertel 5499:     $data        - New value of the hash entry.
                   5500:     $delete      - If true, the entry is removed from the hash.
                   5501: 
                   5502:   Returns:
                   5503:     The new value of the hash table field (undefined if deleted).
                   5504: 
                   5505: =cut
                   5506: 
                   5507: 
1.157     albertel 5508: sub scan_data {
                   5509:     my ($scan_data,$key,$value,$delete)=@_;
1.257     albertel 5510:     my $filename=$env{'form.scantron_selectfile'};
1.157     albertel 5511:     if (defined($value)) {
                   5512: 	$scan_data->{$filename.'_'.$key} = $value;
                   5513:     }
                   5514:     if ($delete) { delete($scan_data->{$filename.'_'.$key}); }
                   5515:     return $scan_data->{$filename.'_'.$key};
                   5516: }
1.423     albertel 5517: 
1.495     albertel 5518: # ----- These first few routines are general use routines.----
                   5519: 
                   5520: # Return the number of occurences of a pattern in a string.
                   5521: 
                   5522: sub occurence_count {
                   5523:     my ($string, $pattern) = @_;
                   5524: 
                   5525:     my @matches = ($string =~ /$pattern/g);
                   5526: 
                   5527:     return scalar(@matches);
                   5528: }
                   5529: 
                   5530: 
                   5531: # Take a string known to have digits and convert all the
                   5532: # digits into letters in the range J,A..I.
                   5533: 
                   5534: sub digits_to_letters {
                   5535:     my ($input) = @_;
                   5536: 
                   5537:     my @alphabet = ('J', 'A'..'I');
                   5538: 
                   5539:     my @input    = split(//, $input);
                   5540:     my $output ='';
                   5541:     for (my $i = 0; $i < scalar(@input); $i++) {
                   5542: 	if ($input[$i] =~ /\d/) {
                   5543: 	    $output .= $alphabet[$input[$i]];
                   5544: 	} else {
                   5545: 	    $output .= $input[$i];
                   5546: 	}
                   5547:     }
                   5548:     return $output;
                   5549: }
                   5550: 
1.423     albertel 5551: =pod 
                   5552: 
                   5553: =item scantron_parse_scanline
                   5554: 
                   5555:   Decodes a scanline from the selected scantron file
                   5556: 
                   5557:  Arguments:
                   5558:     line             - The text of the scantron file line to process
                   5559:     whichline        - Line number
                   5560:     scantron_config  - Hash describing the format of the scantron lines.
                   5561:     scan_data        - Hash of extra information about the scanline
                   5562:                        (see scantron_getfile for more information)
                   5563:     just_header      - True if should not process question answers but only
                   5564:                        the stuff to the left of the answers.
                   5565:  Returns:
                   5566:    Hash containing the result of parsing the scanline
                   5567: 
                   5568:    Keys are all proceeded by the string 'scantron.'
                   5569: 
                   5570:        CODE    - the CODE in use for this scanline
                   5571:        useCODE - 1 if the CODE is invalid but it usage has been forced
                   5572:                  by the operator
                   5573:        CODE_ignore_dup - 1 if the CODE is a duplicated use when unique
                   5574:                             CODEs were selected, but the usage has been
                   5575:                             forced by the operator
1.556     weissno  5576:        ID  - student/employee ID
1.423     albertel 5577:        PaperID - if used, the ID number printed on the sheet when the 
                   5578:                  paper was scanned
                   5579:        FirstName - first name from the sheet
                   5580:        LastName  - last name from the sheet
                   5581: 
                   5582:      if just_header was not true these key may also exist
                   5583: 
1.447     foxr     5584:        missingerror - a list of bubble ranges that are considered to be answers
                   5585:                       to a single question that don't have any bubbles filled in.
                   5586:                       Of the form questionnumber:firstbubblenumber:count.
                   5587:        doubleerror  - a list of bubble ranges that are considered to be answers
                   5588:                       to a single question that have more than one bubble filled in.
                   5589:                       Of the form questionnumber::firstbubblenumber:count
                   5590:    
                   5591:                 In the above, count is the number of bubble responses in the
                   5592:                 input line needed to represent the possible answers to the question.
                   5593:                 e.g. a radioresponse with 15 choices in an answer sheet with 10 choices
                   5594:                 per line would have count = 2.
                   5595: 
1.423     albertel 5596:        maxquest     - the number of the last bubble line that was parsed
                   5597: 
                   5598:        (<number> starts at 1)
                   5599:        <number>.answer - zero or more letters representing the selected
                   5600:                          letters from the scanline for the bubble line 
                   5601:                          <number>.
                   5602:                          if blank there was either no bubble or there where
                   5603:                          multiple bubbles, (consult the keys missingerror and
                   5604:                          doubleerror if this is an error condition)
                   5605: 
                   5606: =cut
                   5607: 
1.82      albertel 5608: sub scantron_parse_scanline {
1.423     albertel 5609:     my ($line,$whichline,$scantron_config,$scan_data,$just_header)=@_;
1.470     foxr     5610: 
1.82      albertel 5611:     my %record;
1.550     raeburn  5612:     my $lastpos = $env{'form.scantron_maxbubble'}*$$scantron_config{'Qlength'};
                   5613:     my $questions=substr($line,$$scantron_config{'Qstart'}-1,$lastpos);  # Answers
1.422     foxr     5614:     my $data=substr($line,0,$$scantron_config{'Qstart'}-1);     # earlier stuff
1.278     albertel 5615:     if (!($$scantron_config{'CODElocation'} eq 0 ||
                   5616: 	  $$scantron_config{'CODElocation'} eq 'none')) {
                   5617: 	if ($$scantron_config{'CODElocation'} < 0 ||
                   5618: 	    $$scantron_config{'CODElocation'} eq 'letter' ||
                   5619: 	    $$scantron_config{'CODElocation'} eq 'number') {
1.191     albertel 5620: 	    $record{'scantron.CODE'}=substr($data,
                   5621: 					    $$scantron_config{'CODEstart'}-1,
1.83      albertel 5622: 					    $$scantron_config{'CODElength'});
1.191     albertel 5623: 	    if (&scan_data($scan_data,"$whichline.useCODE")) {
                   5624: 		$record{'scantron.useCODE'}=1;
                   5625: 	    }
1.192     albertel 5626: 	    if (&scan_data($scan_data,"$whichline.CODE_ignore_dup")) {
                   5627: 		$record{'scantron.CODE_ignore_dup'}=1;
                   5628: 	    }
1.82      albertel 5629: 	} else {
                   5630: 	    #FIXME interpret first N questions
                   5631: 	}
                   5632:     }
1.83      albertel 5633:     $record{'scantron.ID'}=substr($data,$$scantron_config{'IDstart'}-1,
                   5634: 				  $$scantron_config{'IDlength'});
1.157     albertel 5635:     $record{'scantron.PaperID'}=
                   5636: 	substr($data,$$scantron_config{'PaperID'}-1,
                   5637: 	       $$scantron_config{'PaperIDlength'});
                   5638:     $record{'scantron.FirstName'}=
                   5639: 	substr($data,$$scantron_config{'FirstName'}-1,
                   5640: 	       $$scantron_config{'FirstNamelength'});
                   5641:     $record{'scantron.LastName'}=
                   5642: 	substr($data,$$scantron_config{'LastName'}-1,
                   5643: 	       $$scantron_config{'LastNamelength'});
1.423     albertel 5644:     if ($just_header) { return \%record; }
1.194     albertel 5645: 
1.82      albertel 5646:     my @alphabet=('A'..'Z');
                   5647:     my $questnum=0;
1.447     foxr     5648:     my $ansnum  =1;		# Multiple 'answer lines'/question.
                   5649: 
1.470     foxr     5650:     chomp($questions);		# Get rid of any trailing \n.
                   5651:     $questions =~ s/\r$//;      # Get rid of trailing \r too (MAC or Win uploads).
                   5652:     while (length($questions)) {
1.447     foxr     5653: 	my $answers_needed = $bubble_lines_per_response{$questnum};
1.503     raeburn  5654:         my $answer_length  = ($$scantron_config{'Qlength'} * $answers_needed)
                   5655:                              || 1;
                   5656:         $questnum++;
                   5657:         my $quest_id = $questnum;
                   5658:         my $currentquest = substr($questions,0,$answer_length);
                   5659:         $questions       = substr($questions,$answer_length);
                   5660:         if (length($currentquest) < $answer_length) { next; }
                   5661: 
                   5662:         if ($subdivided_bubble_lines{$questnum-1} =~ /,/) {
                   5663:             my $subquestnum = 1;
                   5664:             my $subquestions = $currentquest;
                   5665:             my @subanswers_needed = 
                   5666:                 split(/,/,$subdivided_bubble_lines{$questnum-1});  
                   5667:             foreach my $subans (@subanswers_needed) {
                   5668:                 my $subans_length =
                   5669:                     ($$scantron_config{'Qlength'} * $subans)  || 1;
                   5670:                 my $currsubquest = substr($subquestions,0,$subans_length);
                   5671:                 $subquestions   = substr($subquestions,$subans_length);
                   5672:                 $quest_id = "$questnum.$subquestnum";
                   5673:                 if (($$scantron_config{'Qon'} eq 'letter') ||
                   5674:                     ($$scantron_config{'Qon'} eq 'number')) {
                   5675:                     $ansnum = &scantron_validator_lettnum($ansnum, 
                   5676:                         $questnum,$quest_id,$subans,$currsubquest,$whichline,
                   5677:                         \@alphabet,\%record,$scantron_config,$scan_data);
                   5678:                 } else {
                   5679:                     $ansnum = &scantron_validator_positional($ansnum,
                   5680:                         $questnum,$quest_id,$subans,$currsubquest,$whichline,                        \@alphabet,\%record,$scantron_config,$scan_data);
                   5681:                 }
                   5682:                 $subquestnum ++;
                   5683:             }
                   5684:         } else {
                   5685:             if (($$scantron_config{'Qon'} eq 'letter') ||
                   5686:                 ($$scantron_config{'Qon'} eq 'number')) {
                   5687:                 $ansnum = &scantron_validator_lettnum($ansnum,$questnum,
                   5688:                     $quest_id,$answers_needed,$currentquest,$whichline,
                   5689:                     \@alphabet,\%record,$scantron_config,$scan_data);
                   5690:             } else {
                   5691:                 $ansnum = &scantron_validator_positional($ansnum,$questnum,
                   5692:                     $quest_id,$answers_needed,$currentquest,$whichline,
                   5693:                     \@alphabet,\%record,$scantron_config,$scan_data);
                   5694:             }
                   5695:         }
                   5696:     }
                   5697:     $record{'scantron.maxquest'}=$questnum;
                   5698:     return \%record;
                   5699: }
1.447     foxr     5700: 
1.503     raeburn  5701: sub scantron_validator_lettnum {
                   5702:     my ($ansnum,$questnum,$quest_id,$answers_needed,$currquest,$whichline,
                   5703:         $alphabet,$record,$scantron_config,$scan_data) = @_;
                   5704: 
                   5705:     # Qon 'letter' implies for each slot in currquest we have:
                   5706:     #    ? or * for doubles, a letter in A-Z for a bubble, and
                   5707:     #    about anything else (esp. a value of Qoff) for missing
                   5708:     #    bubbles.
                   5709:     #
                   5710:     # Qon 'number' implies each slot gives a digit that indexes the
                   5711:     #    bubbles filled, or Qoff, or a non-number for unbubbled lines,
                   5712:     #    and * or ? for double bubbles on a single line.
                   5713:     #
1.447     foxr     5714: 
1.503     raeburn  5715:     my $matchon;
                   5716:     if ($$scantron_config{'Qon'} eq 'letter') {
                   5717:         $matchon = '[A-Z]';
                   5718:     } elsif ($$scantron_config{'Qon'} eq 'number') {
                   5719:         $matchon = '\d';
                   5720:     }
                   5721:     my $occurrences = 0;
                   5722:     if (($responsetype_per_response{$questnum-1} eq 'essayresponse') ||
                   5723:         ($responsetype_per_response{$questnum-1} eq 'formularesponse') ||
1.510     raeburn  5724:         ($responsetype_per_response{$questnum-1} eq 'stringresponse') ||
                   5725:         ($responsetype_per_response{$questnum-1} eq 'imageresponse') ||
                   5726:         ($responsetype_per_response{$questnum-1} eq 'reactionresponse') ||
                   5727:         ($responsetype_per_response{$questnum-1} eq 'organicresponse')) {
1.503     raeburn  5728:         my @singlelines = split('',$currquest);
                   5729:         foreach my $entry (@singlelines) {
                   5730:             $occurrences = &occurence_count($entry,$matchon);
                   5731:             if ($occurrences > 1) {
                   5732:                 last;
                   5733:             }
                   5734:         } 
                   5735:     } else {
                   5736:         $occurrences = &occurence_count($currquest,$matchon); 
                   5737:     }
                   5738:     if (($currquest =~ /\?/ || $currquest =~ /\*/) || ($occurrences > 1)) {
                   5739:         push(@{$record->{'scantron.doubleerror'}},$quest_id);
                   5740:         for (my $ans=0; $ans<$answers_needed; $ans++) {
                   5741:             my $bubble = substr($currquest,$ans,1);
                   5742:             if ($bubble =~ /$matchon/ ) {
                   5743:                 if ($$scantron_config{'Qon'} eq 'number') {
                   5744:                     if ($bubble == 0) {
                   5745:                         $bubble = 10; 
                   5746:                     }
                   5747:                     $record->{"scantron.$ansnum.answer"} = 
                   5748:                         $alphabet->[$bubble-1];
                   5749:                 } else {
                   5750:                     $record->{"scantron.$ansnum.answer"} = $bubble;
                   5751:                 }
                   5752:             } else {
                   5753:                 $record->{"scantron.$ansnum.answer"}='';
                   5754:             }
                   5755:             $ansnum++;
                   5756:         }
                   5757:     } elsif (!defined($currquest)
                   5758:             || (&occurence_count($currquest, $$scantron_config{'Qoff'}) == length($currquest))
                   5759:             || (&occurence_count($currquest,$matchon) == 0)) {
                   5760:         for (my $ans=0; $ans<$answers_needed; $ans++ ) {
                   5761:             $record->{"scantron.$ansnum.answer"}='';
                   5762:             $ansnum++;
                   5763:         }
                   5764:         if (!&scan_data($scan_data,"$whichline.no_bubble.$quest_id")) {
                   5765:             push(@{$record->{'scantron.missingerror'}},$quest_id);
                   5766:         }
                   5767:     } else {
                   5768:         if ($$scantron_config{'Qon'} eq 'number') {
                   5769:             $currquest = &digits_to_letters($currquest);            
                   5770:         }
                   5771:         for (my $ans=0; $ans<$answers_needed; $ans++) {
                   5772:             my $bubble = substr($currquest,$ans,1);
                   5773:             $record->{"scantron.$ansnum.answer"} = $bubble;
                   5774:             $ansnum++;
                   5775:         }
                   5776:     }
                   5777:     return $ansnum;
                   5778: }
1.447     foxr     5779: 
1.503     raeburn  5780: sub scantron_validator_positional {
                   5781:     my ($ansnum,$questnum,$quest_id,$answers_needed,$currquest,
                   5782:         $whichline,$alphabet,$record,$scantron_config,$scan_data) = @_;
1.447     foxr     5783: 
1.503     raeburn  5784:     # Otherwise there's a positional notation;
                   5785:     # each bubble line requires Qlength items, and there are filled in
                   5786:     # bubbles for each case where there 'Qon' characters.
                   5787:     #
1.447     foxr     5788: 
1.503     raeburn  5789:     my @array=split($$scantron_config{'Qon'},$currquest,-1);
1.447     foxr     5790: 
1.503     raeburn  5791:     # If the split only gives us one element.. the full length of the
                   5792:     # answer string, no bubbles are filled in:
1.447     foxr     5793: 
1.507     raeburn  5794:     if ($answers_needed eq '') {
                   5795:         return;
                   5796:     }
                   5797: 
1.503     raeburn  5798:     if (length($array[0]) eq $$scantron_config{'Qlength'}*$answers_needed) {
                   5799:         for (my $ans=0; $ans<$answers_needed; $ans++ ) {
                   5800:             $record->{"scantron.$ansnum.answer"}='';
                   5801:             $ansnum++;
                   5802:         }
                   5803:         if (!&scan_data($scan_data,"$whichline.no_bubble.$quest_id")) {
                   5804:             push(@{$record->{"scantron.missingerror"}},$quest_id);
                   5805:         }
                   5806:     } elsif (scalar(@array) == 2) {
                   5807:         my $location = length($array[0]);
                   5808:         my $line_num = int($location / $$scantron_config{'Qlength'});
                   5809:         my $bubble   = $alphabet->[$location % $$scantron_config{'Qlength'}];
                   5810:         for (my $ans=0; $ans<$answers_needed; $ans++) {
                   5811:             if ($ans eq $line_num) {
                   5812:                 $record->{"scantron.$ansnum.answer"} = $bubble;
                   5813:             } else {
                   5814:                 $record->{"scantron.$ansnum.answer"} = ' ';
                   5815:             }
                   5816:             $ansnum++;
                   5817:          }
                   5818:     } else {
                   5819:         #  If there's more than one instance of a bubble character
                   5820:         #  That's a double bubble; with positional notation we can
                   5821:         #  record all the bubbles filled in as well as the
                   5822:         #  fact this response consists of multiple bubbles.
                   5823:         #
                   5824:         if (($responsetype_per_response{$questnum-1} eq 'essayresponse') ||
                   5825:             ($responsetype_per_response{$questnum-1} eq 'formularesponse') ||
1.510     raeburn  5826:             ($responsetype_per_response{$questnum-1} eq 'stringresponse') ||
                   5827:             ($responsetype_per_response{$questnum-1} eq 'imageresponse') ||
                   5828:             ($responsetype_per_response{$questnum-1} eq 'reactionresponse') ||
                   5829:             ($responsetype_per_response{$questnum-1} eq 'organicresponse')) {
1.503     raeburn  5830:             my $doubleerror = 0;
                   5831:             while (($currquest >= $$scantron_config{'Qlength'}) && 
                   5832:                    (!$doubleerror)) {
                   5833:                my $currline = substr($currquest,0,$$scantron_config{'Qlength'});
                   5834:                $currquest = substr($currquest,$$scantron_config{'Qlength'});
                   5835:                my @currarray = split($$scantron_config{'Qon'},$currline,-1);
                   5836:                if (length(@currarray) > 2) {
                   5837:                    $doubleerror = 1;
                   5838:                } 
                   5839:             }
                   5840:             if ($doubleerror) {
                   5841:                 push(@{$record->{'scantron.doubleerror'}},$quest_id);
                   5842:             }
                   5843:         } else {
                   5844:             push(@{$record->{'scantron.doubleerror'}},$quest_id);
                   5845:         }
                   5846:         my $item = $ansnum;
                   5847:         for (my $ans=0; $ans<$answers_needed; $ans++) {
                   5848:             $record->{"scantron.$item.answer"} = '';
                   5849:             $item ++;
                   5850:         }
1.447     foxr     5851: 
1.503     raeburn  5852:         my @ans=@array;
                   5853:         my $i=0;
                   5854:         my $increment = 0;
                   5855:         while ($#ans) {
                   5856:             $i+=length($ans[0]) + $increment;
                   5857:             my $line   = int($i/$$scantron_config{'Qlength'} + $ansnum);
                   5858:             my $bubble = $i%$$scantron_config{'Qlength'};
                   5859:             $record->{"scantron.$line.answer"}.=$alphabet->[$bubble];
                   5860:             shift(@ans);
                   5861:             $increment = 1;
                   5862:         }
                   5863:         $ansnum += $answers_needed;
1.82      albertel 5864:     }
1.503     raeburn  5865:     return $ansnum;
1.82      albertel 5866: }
                   5867: 
1.423     albertel 5868: =pod
                   5869: 
                   5870: =item scantron_add_delay
                   5871: 
                   5872:    Adds an error message that occurred during the grading phase to a
                   5873:    queue of messages to be shown after grading pass is complete
                   5874: 
                   5875:  Arguments:
1.424     albertel 5876:    $delayqueue  - arrary ref of hash ref of error messages
1.423     albertel 5877:    $scanline    - the scanline that caused the error
                   5878:    $errormesage - the error message
                   5879:    $errorcode   - a numeric code for the error
                   5880: 
                   5881:  Side Effects:
1.424     albertel 5882:    updates the $delayqueue to have a new hash ref of the error
1.423     albertel 5883: 
                   5884: =cut
                   5885: 
1.82      albertel 5886: sub scantron_add_delay {
1.140     albertel 5887:     my ($delayqueue,$scanline,$errormessage,$errorcode)=@_;
                   5888:     push(@$delayqueue,
                   5889: 	 {'line' => $scanline, 'emsg' => $errormessage,
                   5890: 	  'ecode' => $errorcode }
                   5891: 	 );
1.82      albertel 5892: }
                   5893: 
1.423     albertel 5894: =pod
                   5895: 
                   5896: =item scantron_find_student
                   5897: 
1.424     albertel 5898:    Finds the username for the current scanline
                   5899: 
                   5900:   Arguments:
                   5901:    $scantron_record - hash result from scantron_parse_scanline
                   5902:    $scan_data       - hash of correction information 
                   5903:                       (see &scantron_getfile() form more information)
                   5904:    $idmap           - hash from &username_to_idmap()
                   5905:    $line            - number of current scanline
                   5906:  
                   5907:   Returns:
                   5908:    Either 'username:domain' or undef if unknown
                   5909: 
1.423     albertel 5910: =cut
                   5911: 
1.82      albertel 5912: sub scantron_find_student {
1.157     albertel 5913:     my ($scantron_record,$scan_data,$idmap,$line)=@_;
1.83      albertel 5914:     my $scanID=$$scantron_record{'scantron.ID'};
1.157     albertel 5915:     if ($scanID =~ /^\s*$/) {
                   5916:  	return &scan_data($scan_data,"$line.user");
                   5917:     }
1.83      albertel 5918:     foreach my $id (keys(%$idmap)) {
1.157     albertel 5919:  	if (lc($id) eq lc($scanID)) {
                   5920:  	    return $$idmap{$id};
                   5921:  	}
1.83      albertel 5922:     }
                   5923:     return undef;
                   5924: }
                   5925: 
1.423     albertel 5926: =pod
                   5927: 
                   5928: =item scantron_filter
                   5929: 
1.424     albertel 5930:    Filter sub for lonnavmaps, filters out hidden resources if ignore
                   5931:    hidden resources was selected
                   5932: 
1.423     albertel 5933: =cut
                   5934: 
1.83      albertel 5935: sub scantron_filter {
                   5936:     my ($curres)=@_;
1.331     albertel 5937: 
                   5938:     if (ref($curres) && $curres->is_problem()) {
                   5939: 	# if the user has asked to not have either hidden
                   5940: 	# or 'randomout' controlled resources to be graded
                   5941: 	# don't include them
                   5942: 	if ($env{'form.scantron_options_hidden'} eq 'ignore_hidden'
                   5943: 	    && $curres->randomout) {
                   5944: 	    return 0;
                   5945: 	}
1.83      albertel 5946: 	return 1;
                   5947:     }
                   5948:     return 0;
1.82      albertel 5949: }
                   5950: 
1.423     albertel 5951: =pod
                   5952: 
                   5953: =item scantron_process_corrections
                   5954: 
1.424     albertel 5955:    Gets correction information out of submitted form data and corrects
                   5956:    the scanline
                   5957: 
1.423     albertel 5958: =cut
                   5959: 
1.157     albertel 5960: sub scantron_process_corrections {
                   5961:     my ($r) = @_;
1.257     albertel 5962:     my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
1.157     albertel 5963:     my ($scanlines,$scan_data)=&scantron_getfile();
                   5964:     my $classlist=&Apache::loncoursedata::get_classlist();
1.257     albertel 5965:     my $which=$env{'form.scantron_line'};
1.200     albertel 5966:     my $line=&scantron_get_line($scanlines,$scan_data,$which);
1.157     albertel 5967:     my ($skip,$err,$errmsg);
1.257     albertel 5968:     if ($env{'form.scantron_skip_record'}) {
1.157     albertel 5969: 	$skip=1;
1.257     albertel 5970:     } elsif ($env{'form.scantron_corrections'} =~ /^(duplicate|incorrect)ID$/) {
                   5971: 	my $newstudent=$env{'form.scantron_username'}.':'.
                   5972: 	    $env{'form.scantron_domain'};
1.157     albertel 5973: 	my $newid=$classlist->{$newstudent}->[&Apache::loncoursedata::CL_ID];
                   5974: 	($line,$err,$errmsg)=
                   5975: 	    &scantron_fixup_scanline(\%scantron_config,$scan_data,$line,$which,
                   5976: 				     'ID',{'newid'=>$newid,
1.257     albertel 5977: 				    'username'=>$env{'form.scantron_username'},
                   5978: 				    'domain'=>$env{'form.scantron_domain'}});
                   5979:     } elsif ($env{'form.scantron_corrections'} =~ /^(duplicate|incorrect)CODE$/) {
                   5980: 	my $resolution=$env{'form.scantron_CODE_resolution'};
1.190     albertel 5981: 	my $newCODE;
1.192     albertel 5982: 	my %args;
1.190     albertel 5983: 	if      ($resolution eq 'use_unfound') {
1.191     albertel 5984: 	    $newCODE='use_unfound';
1.190     albertel 5985: 	} elsif ($resolution eq 'use_found') {
1.257     albertel 5986: 	    $newCODE=$env{'form.scantron_CODE_selectedvalue'};
1.190     albertel 5987: 	} elsif ($resolution eq 'use_typed') {
1.257     albertel 5988: 	    $newCODE=$env{'form.scantron_CODE_newvalue'};
1.194     albertel 5989: 	} elsif ($resolution =~ /^use_closest_(\d+)/) {
1.257     albertel 5990: 	    $newCODE=$env{"form.scantron_CODE_closest_$1"};
1.190     albertel 5991: 	}
1.257     albertel 5992: 	if ($env{'form.scantron_corrections'} eq 'duplicateCODE') {
1.192     albertel 5993: 	    $args{'CODE_ignore_dup'}=1;
                   5994: 	}
                   5995: 	$args{'CODE'}=$newCODE;
1.186     albertel 5996: 	($line,$err,$errmsg)=
                   5997: 	    &scantron_fixup_scanline(\%scantron_config,$scan_data,$line,$which,
1.192     albertel 5998: 				     'CODE',\%args);
1.257     albertel 5999:     } elsif ($env{'form.scantron_corrections'} =~ /^(missing|double)bubble$/) {
                   6000: 	foreach my $question (split(',',$env{'form.scantron_questions'})) {
1.157     albertel 6001: 	    ($line,$err,$errmsg)=
                   6002: 		&scantron_fixup_scanline(\%scantron_config,$scan_data,$line,
                   6003: 					 $which,'answer',
                   6004: 					 { 'question'=>$question,
1.503     raeburn  6005: 		      		   'response'=>$env{"form.scantron_correct_Q_$question"},
                   6006:                                    'questionnum'=>$env{"form.scantron_questionnum_Q_$question"}});
1.157     albertel 6007: 	    if ($err) { last; }
                   6008: 	}
                   6009:     }
                   6010:     if ($err) {
1.398     albertel 6011: 	$r->print("<span class=\"LC_warning\">Unable to accept last correction, an error occurred :$errmsg:</span>");
1.157     albertel 6012:     } else {
1.200     albertel 6013: 	&scantron_put_line($scanlines,$scan_data,$which,$line,$skip);
1.157     albertel 6014: 	&scantron_putfile($scanlines,$scan_data);
                   6015:     }
                   6016: }
                   6017: 
1.423     albertel 6018: =pod
                   6019: 
                   6020: =item reset_skipping_status
                   6021: 
1.424     albertel 6022:    Forgets the current set of remember skipped scanlines (and thus
                   6023:    reverts back to considering all lines in the
                   6024:    scantron_skipped_<filename> file)
                   6025: 
1.423     albertel 6026: =cut
                   6027: 
1.200     albertel 6028: sub reset_skipping_status {
                   6029:     my ($scanlines,$scan_data)=&scantron_getfile();
                   6030:     &scan_data($scan_data,'remember_skipping',undef,1);
                   6031:     &scantron_putfile(undef,$scan_data);
                   6032: }
                   6033: 
1.423     albertel 6034: =pod
                   6035: 
                   6036: =item start_skipping
                   6037: 
1.424     albertel 6038:    Marks a scanline to be skipped. 
                   6039: 
1.423     albertel 6040: =cut
                   6041: 
1.376     albertel 6042: sub start_skipping {
1.200     albertel 6043:     my ($scan_data,$i)=@_;
                   6044:     my %remembered=split(':',&scan_data($scan_data,'remember_skipping'));
1.376     albertel 6045:     if ($env{'form.scantron_options_redo'} =~ /^redo_/) {
                   6046: 	$remembered{$i}=2;
                   6047:     } else {
                   6048: 	$remembered{$i}=1;
                   6049:     }
1.200     albertel 6050:     &scan_data($scan_data,'remember_skipping',join(':',%remembered));
                   6051: }
                   6052: 
1.423     albertel 6053: =pod
                   6054: 
                   6055: =item should_be_skipped
                   6056: 
1.424     albertel 6057:    Checks whether a scanline should be skipped.
                   6058: 
1.423     albertel 6059: =cut
                   6060: 
1.200     albertel 6061: sub should_be_skipped {
1.376     albertel 6062:     my ($scanlines,$scan_data,$i)=@_;
1.257     albertel 6063:     if ($env{'form.scantron_options_redo'} !~ /^redo_/) {
1.200     albertel 6064: 	# not redoing old skips
1.376     albertel 6065: 	if ($scanlines->{'skipped'}[$i]) { return 1; }
1.200     albertel 6066: 	return 0;
                   6067:     }
                   6068:     my %remembered=split(':',&scan_data($scan_data,'remember_skipping'));
1.376     albertel 6069: 
                   6070:     if (exists($remembered{$i}) && $remembered{$i} != 2 ) {
                   6071: 	return 0;
                   6072:     }
1.200     albertel 6073:     return 1;
                   6074: }
                   6075: 
1.423     albertel 6076: =pod
                   6077: 
                   6078: =item remember_current_skipped
                   6079: 
1.424     albertel 6080:    Discovers what scanlines are in the scantron_skipped_<filename>
                   6081:    file and remembers them into scan_data for later use.
                   6082: 
1.423     albertel 6083: =cut
                   6084: 
1.200     albertel 6085: sub remember_current_skipped {
                   6086:     my ($scanlines,$scan_data)=&scantron_getfile();
                   6087:     my %to_remember;
                   6088:     for (my $i=0;$i<=$scanlines->{'count'};$i++) {
                   6089: 	if ($scanlines->{'skipped'}[$i]) {
                   6090: 	    $to_remember{$i}=1;
                   6091: 	}
                   6092:     }
1.376     albertel 6093: 
1.200     albertel 6094:     &scan_data($scan_data,'remember_skipping',join(':',%to_remember));
                   6095:     &scantron_putfile(undef,$scan_data);
                   6096: }
                   6097: 
1.423     albertel 6098: =pod
                   6099: 
                   6100: =item check_for_error
                   6101: 
1.424     albertel 6102:     Checks if there was an error when attempting to remove a specific
                   6103:     scantron_.. bubble sheet data file. Prints out an error if
                   6104:     something went wrong.
                   6105: 
1.423     albertel 6106: =cut
                   6107: 
1.200     albertel 6108: sub check_for_error {
                   6109:     my ($r,$result)=@_;
                   6110:     if ($result ne 'ok' && $result ne 'not_found' ) {
1.492     albertel 6111: 	$r->print(&mt("An error occurred ([_1]) when trying to remove the existing corrections.",$result));
1.200     albertel 6112:     }
                   6113: }
1.157     albertel 6114: 
1.423     albertel 6115: =pod
                   6116: 
                   6117: =item scantron_warning_screen
                   6118: 
1.424     albertel 6119:    Interstitial screen to make sure the operator has selected the
                   6120:    correct options before we start the validation phase.
                   6121: 
1.423     albertel 6122: =cut
                   6123: 
1.203     albertel 6124: sub scantron_warning_screen {
                   6125:     my ($button_text)=@_;
1.257     albertel 6126:     my $title=&Apache::lonnet::gettitle($env{'form.selectpage'});
1.284     albertel 6127:     my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
1.373     albertel 6128:     my $CODElist;
1.284     albertel 6129:     if ($scantron_config{'CODElocation'} &&
                   6130: 	$scantron_config{'CODEstart'} &&
                   6131: 	$scantron_config{'CODElength'}) {
                   6132: 	$CODElist=$env{'form.scantron_CODElist'};
1.398     albertel 6133: 	if ($env{'form.scantron_CODElist'} eq '') { $CODElist='<span class="LC_warning">None</span>'; }
1.284     albertel 6134: 	$CODElist=
1.492     albertel 6135: 	    '<tr><td><b>'.&mt('List of CODES to validate against:').'</b></td><td><tt>'.
1.373     albertel 6136: 	    $env{'form.scantron_CODElist'}.'</tt></td></tr>';
1.284     albertel 6137:     }
1.492     albertel 6138:     return ('
1.203     albertel 6139: <p>
1.492     albertel 6140: <span class="LC_warning">
                   6141: '.&mt('Please double check the information below before clicking on \'[_1]\'',&mt($button_text)).'</span>
1.203     albertel 6142: </p>
                   6143: <table>
1.492     albertel 6144: <tr><td><b>'.&mt('Sequence to be Graded:').'</b></td><td>'.$title.'</td></tr>
                   6145: <tr><td><b>'.&mt('Data File that will be used:').'</b></td><td><tt>'.$env{'form.scantron_selectfile'}.'</tt></td></tr>
                   6146: '.$CODElist.'
1.203     albertel 6147: </table>
                   6148: <br />
1.492     albertel 6149: <p> '.&mt('If this information is correct, please click on \'[_1]\'.',&mt($button_text)).'</p>
                   6150: <p> '.&mt('If something is incorrect, please click the \'Grading Menu\' button to start over.').'</p>
1.203     albertel 6151: 
                   6152: <br />
1.492     albertel 6153: ');
1.203     albertel 6154: }
                   6155: 
1.423     albertel 6156: =pod
                   6157: 
                   6158: =item scantron_do_warning
                   6159: 
1.424     albertel 6160:    Check if the operator has picked something for all required
                   6161:    fields. Error out if something is missing.
                   6162: 
1.423     albertel 6163: =cut
                   6164: 
1.203     albertel 6165: sub scantron_do_warning {
1.608     www      6166:     my ($r,$symb)=@_;
1.203     albertel 6167:     if (!$symb) {return '';}
1.324     albertel 6168:     my $default_form_data=&defaultFormData($symb);
1.203     albertel 6169:     $r->print(&scantron_form_start().$default_form_data);
1.257     albertel 6170:     if ( $env{'form.selectpage'} eq '' ||
                   6171: 	 $env{'form.scantron_selectfile'} eq '' ||
                   6172: 	 $env{'form.scantron_format'} eq '' ) {
1.492     albertel 6173: 	$r->print("<p>".&mt('You have forgetten to specify some information. Please go Back and try again.')."</p>");
1.257     albertel 6174: 	if ( $env{'form.selectpage'} eq '') {
1.492     albertel 6175: 	    $r->print('<p><span class="LC_error">'.&mt('You have not selected a Sequence to grade').'</span></p>');
1.237     albertel 6176: 	} 
1.257     albertel 6177: 	if ( $env{'form.scantron_selectfile'} eq '') {
1.492     albertel 6178: 	    $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 6179: 	} 
1.257     albertel 6180: 	if ( $env{'form.scantron_format'} eq '') {
1.492     albertel 6181: 	    $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 6182: 	} 
                   6183:     } else {
1.265     www      6184: 	my $warning=&scantron_warning_screen('Grading: Validate Records');
1.492     albertel 6185: 	$r->print('
                   6186: '.$warning.'
                   6187: <input type="submit" name="submit" value="'.&mt('Grading: Validate Records').'" />
1.203     albertel 6188: <input type="hidden" name="command" value="scantron_validate" />
1.492     albertel 6189: ');
1.237     albertel 6190:     }
1.614     www      6191:     $r->print("</form><br />");
1.203     albertel 6192:     return '';
                   6193: }
                   6194: 
1.423     albertel 6195: =pod
                   6196: 
                   6197: =item scantron_form_start
                   6198: 
1.424     albertel 6199:     html hidden input for remembering all selected grading options
                   6200: 
1.423     albertel 6201: =cut
                   6202: 
1.203     albertel 6203: sub scantron_form_start {
                   6204:     my ($max_bubble)=@_;
                   6205:     my $result= <<SCANTRONFORM;
                   6206: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="scantronupload">
1.257     albertel 6207:   <input type="hidden" name="selectpage" value="$env{'form.selectpage'}" />
                   6208:   <input type="hidden" name="scantron_format" value="$env{'form.scantron_format'}" />
                   6209:   <input type="hidden" name="scantron_selectfile" value="$env{'form.scantron_selectfile'}" />
1.218     albertel 6210:   <input type="hidden" name="scantron_maxbubble" value="$max_bubble" />
1.257     albertel 6211:   <input type="hidden" name="scantron_CODElist" value="$env{'form.scantron_CODElist'}" />
                   6212:   <input type="hidden" name="scantron_CODEunique" value="$env{'form.scantron_CODEunique'}" />
                   6213:   <input type="hidden" name="scantron_options_redo" value="$env{'form.scantron_options_redo'}" />
                   6214:   <input type="hidden" name="scantron_options_ignore" value="$env{'form.scantron_options_ignore'}" />
1.331     albertel 6215:   <input type="hidden" name="scantron_options_hidden" value="$env{'form.scantron_options_hidden'}" />
1.203     albertel 6216: SCANTRONFORM
1.447     foxr     6217: 
                   6218:   my $line = 0;
                   6219:     while (defined($env{"form.scantron.bubblelines.$line"})) {
                   6220:        my $chunk =
                   6221: 	   '<input type="hidden" name="scantron.bubblelines.'.$line.'" value="'.$env{"form.scantron.bubblelines.$line"}.'" />'."\n";
1.448     foxr     6222:        $chunk .=
                   6223: 	   '<input type="hidden" name="scantron.first_bubble_line.'.$line.'" value="'.$env{"form.scantron.first_bubble_line.$line"}.'" />'."\n";
1.503     raeburn  6224:        $chunk .= 
                   6225:            '<input type="hidden" name="scantron.sub_bubblelines.'.$line.'" value="'.$env{"form.scantron.sub_bubblelines.$line"}.'" />'."\n";
1.504     raeburn  6226:        $chunk .=
                   6227:            '<input type="hidden" name="scantron.responsetype.'.$line.'" value="'.$env{"form.scantron.responsetype.$line"}.'" />'."\n";
1.447     foxr     6228:        $result .= $chunk;
                   6229:        $line++;
                   6230:    }
1.203     albertel 6231:     return $result;
                   6232: }
                   6233: 
1.423     albertel 6234: =pod
                   6235: 
                   6236: =item scantron_validate_file
                   6237: 
1.424     albertel 6238:     Dispatch routine for doing validation of a bubble sheet data file.
                   6239: 
                   6240:     Also processes any necessary information resets that need to
                   6241:     occur before validation begins (ignore previous corrections,
                   6242:     restarting the skipped records processing)
                   6243: 
1.423     albertel 6244: =cut
                   6245: 
1.157     albertel 6246: sub scantron_validate_file {
1.608     www      6247:     my ($r,$symb) = @_;
1.157     albertel 6248:     if (!$symb) {return '';}
1.324     albertel 6249:     my $default_form_data=&defaultFormData($symb);
1.200     albertel 6250:     
                   6251:     # do the detection of only doing skipped records first befroe we delete
1.424     albertel 6252:     # them when doing the corrections reset
1.257     albertel 6253:     if ($env{'form.scantron_options_redo'} ne 'redo_skipped_ready') {
1.200     albertel 6254: 	&reset_skipping_status();
                   6255:     }
1.257     albertel 6256:     if ($env{'form.scantron_options_redo'} eq 'redo_skipped') {
1.200     albertel 6257: 	&remember_current_skipped();
1.257     albertel 6258: 	$env{'form.scantron_options_redo'}='redo_skipped_ready';
1.200     albertel 6259:     }
                   6260: 
1.257     albertel 6261:     if ($env{'form.scantron_options_ignore'} eq 'ignore_corrections') {
1.200     albertel 6262: 	&check_for_error($r,&scantron_remove_file('corrected'));
                   6263: 	&check_for_error($r,&scantron_remove_file('skipped'));
                   6264: 	&check_for_error($r,&scantron_remove_scan_data());
1.257     albertel 6265: 	$env{'form.scantron_options_ignore'}='done';
1.192     albertel 6266:     }
1.200     albertel 6267: 
1.257     albertel 6268:     if ($env{'form.scantron_corrections'}) {
1.157     albertel 6269: 	&scantron_process_corrections($r);
                   6270:     }
1.503     raeburn  6271:     $r->print('<p>'.&mt('Gathering necessary information.').'</p>');$r->rflush();
1.157     albertel 6272:     #get the student pick code ready
                   6273:     $r->print(&Apache::loncommon::studentbrowser_javascript());
1.582     raeburn  6274:     my $nav_error;
                   6275:     my $max_bubble=&scantron_get_maxbubble(\$nav_error);
                   6276:     if ($nav_error) {
                   6277:         $r->print(&navmap_errormsg());
                   6278:         return '';
                   6279:     }
1.203     albertel 6280:     my $result=&scantron_form_start($max_bubble).$default_form_data;
1.157     albertel 6281:     $r->print($result);
                   6282:     
1.334     albertel 6283:     my @validate_phases=( 'sequence',
                   6284: 			  'ID',
1.157     albertel 6285: 			  'CODE',
                   6286: 			  'doublebubble',
                   6287: 			  'missingbubbles');
1.257     albertel 6288:     if (!$env{'form.validatepass'}) {
                   6289: 	$env{'form.validatepass'} = 0;
1.157     albertel 6290:     }
1.257     albertel 6291:     my $currentphase=$env{'form.validatepass'};
1.157     albertel 6292: 
1.448     foxr     6293: 
1.157     albertel 6294:     my $stop=0;
                   6295:     while (!$stop && $currentphase < scalar(@validate_phases)) {
1.503     raeburn  6296: 	$r->print(&mt('Validating '.$validate_phases[$currentphase]).'<br />');
1.157     albertel 6297: 	$r->rflush();
                   6298: 	my $which="scantron_validate_".$validate_phases[$currentphase];
                   6299: 	{
                   6300: 	    no strict 'refs';
                   6301: 	    ($stop,$currentphase)=&$which($r,$currentphase);
                   6302: 	}
                   6303:     }
                   6304:     if (!$stop) {
1.203     albertel 6305: 	my $warning=&scantron_warning_screen('Start Grading');
1.542     raeburn  6306: 	$r->print(&mt('Validation process complete.').'<br />'.
                   6307:                   $warning.
                   6308:                   &mt('Perform verification for each student after storage of submissions?').
                   6309:                   '&nbsp;<span class="LC_nobreak"><label>'.
                   6310:                   '<input type="radio" name="verifyrecord" value="1" />'.&mt('Yes').'</label>'.
                   6311:                   ('&nbsp;'x3).'<label>'.
                   6312:                   '<input type="radio" name="verifyrecord" value="0" checked="checked" />'.&mt('No').
                   6313:                   '</label></span><br />'.
                   6314:                   &mt('Grading will take longer if you use verification.').'<br />'.
1.572     www      6315:                   &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  6316:                   '<input type="submit" name="submit" value="'.&mt('Start Grading').'" />'.
                   6317:                   '<input type="hidden" name="command" value="scantron_process" />'."\n");
1.157     albertel 6318:     } else {
                   6319: 	$r->print('<input type="hidden" name="command" value="scantron_validate" />');
                   6320: 	$r->print("<input type='hidden' name='validatepass' value='".$currentphase."' />");
                   6321:     }
                   6322:     if ($stop) {
1.334     albertel 6323: 	if ($validate_phases[$currentphase] eq 'sequence') {
1.539     riegler  6324: 	    $r->print('<input type="submit" name="submit" value="'.&mt('Ignore').' &rarr; " />');
1.492     albertel 6325: 	    $r->print(' '.&mt('this error').' <br />');
1.334     albertel 6326: 
1.492     albertel 6327: 	    $r->print(" <p>".&mt("Or click the 'Grading Menu' button to start over.")."</p>");
1.334     albertel 6328: 	} else {
1.503     raeburn  6329:             if ($validate_phases[$currentphase] eq 'doublebubble' || $validate_phases[$currentphase] eq 'missingbubbles') {
1.539     riegler  6330: 	        $r->print('<input type="button" name="submitbutton" value="'.&mt('Continue').' &rarr;" onclick="javascript:verify_bubble_radio(this.form)" />');
1.503     raeburn  6331:             } else {
1.539     riegler  6332:                 $r->print('<input type="submit" name="submit" value="'.&mt('Continue').' &rarr;" />');
1.503     raeburn  6333:             }
1.492     albertel 6334: 	    $r->print(' '.&mt('using corrected info').' <br />');
                   6335: 	    $r->print("<input type='submit' value='".&mt("Skip")."' name='scantron_skip_record' />");
                   6336: 	    $r->print(" ".&mt("this scanline saving it for later."));
1.334     albertel 6337: 	}
1.157     albertel 6338:     }
1.614     www      6339:     $r->print(" </form><br />");
1.157     albertel 6340:     return '';
                   6341: }
                   6342: 
1.423     albertel 6343: 
                   6344: =pod
                   6345: 
                   6346: =item scantron_remove_file
                   6347: 
1.424     albertel 6348:    Removes the requested bubble sheet data file, makes sure that
                   6349:    scantron_original_<filename> is never removed
                   6350: 
                   6351: 
1.423     albertel 6352: =cut
                   6353: 
1.200     albertel 6354: sub scantron_remove_file {
1.192     albertel 6355:     my ($which)=@_;
1.257     albertel 6356:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   6357:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1.192     albertel 6358:     my $file='scantron_';
1.200     albertel 6359:     if ($which eq 'corrected' || $which eq 'skipped') {
                   6360: 	$file.=$which.'_';
1.192     albertel 6361:     } else {
                   6362: 	return 'refused';
                   6363:     }
1.257     albertel 6364:     $file.=$env{'form.scantron_selectfile'};
1.200     albertel 6365:     return &Apache::lonnet::removeuserfile($cname,$cdom,$file);
                   6366: }
                   6367: 
1.423     albertel 6368: 
                   6369: =pod
                   6370: 
                   6371: =item scantron_remove_scan_data
                   6372: 
1.424     albertel 6373:    Removes all scan_data correction for the requested bubble sheet
                   6374:    data file.  (In the case that both the are doing skipped records we need
                   6375:    to remember the old skipped lines for the time being so that element
                   6376:    persists for a while.)
                   6377: 
1.423     albertel 6378: =cut
                   6379: 
1.200     albertel 6380: sub scantron_remove_scan_data {
1.257     albertel 6381:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   6382:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1.192     albertel 6383:     my @keys=&Apache::lonnet::getkeys('nohist_scantrondata',$cdom,$cname);
                   6384:     my @todelete;
1.257     albertel 6385:     my $filename=$env{'form.scantron_selectfile'};
1.192     albertel 6386:     foreach my $key (@keys) {
                   6387: 	if ($key=~/^\Q$filename\E_/) {
1.257     albertel 6388: 	    if ($env{'form.scantron_options_redo'} eq 'redo_skipped_ready' &&
1.200     albertel 6389: 		$key=~/remember_skipping/) {
                   6390: 		next;
                   6391: 	    }
1.192     albertel 6392: 	    push(@todelete,$key);
                   6393: 	}
                   6394:     }
1.200     albertel 6395:     my $result;
1.192     albertel 6396:     if (@todelete) {
1.491     albertel 6397: 	$result = &Apache::lonnet::del('nohist_scantrondata',
                   6398: 				       \@todelete,$cdom,$cname);
                   6399:     } else {
                   6400: 	$result = 'ok';
1.192     albertel 6401:     }
                   6402:     return $result;
                   6403: }
                   6404: 
1.423     albertel 6405: 
                   6406: =pod
                   6407: 
                   6408: =item scantron_getfile
                   6409: 
1.424     albertel 6410:     Fetches the requested bubble sheet data file (all 3 versions), and
                   6411:     the scan_data hash
                   6412:   
                   6413:   Arguments:
                   6414:     None
                   6415: 
                   6416:   Returns:
                   6417:     2 hash references
                   6418: 
                   6419:      - first one has 
                   6420:          orig      -
                   6421:          corrected -
                   6422:          skipped   -  each of which points to an array ref of the specified
                   6423:                       file broken up into individual lines
                   6424:          count     - number of scanlines
                   6425:  
                   6426:      - second is the scan_data hash possible keys are
1.425     albertel 6427:        ($number refers to scanline numbered $number and thus the key affects
                   6428:         only that scanline
                   6429:         $bubline refers to the specific bubble line element and the aspects
                   6430:         refers to that specific bubble line element)
                   6431: 
                   6432:        $number.user - username:domain to use
                   6433:        $number.CODE_ignore_dup 
                   6434:                     - ignore the duplicate CODE error 
                   6435:        $number.useCODE
                   6436:                     - use the CODE in the scanline as is
                   6437:        $number.no_bubble.$bubline
                   6438:                     - it is valid that there is no bubbled in bubble
                   6439:                       at $number $bubline
                   6440:        remember_skipping
                   6441:                     - a frozen hash containing keys of $number and values
                   6442:                       of either 
                   6443:                         1 - we are on a 'do skipped records pass' and plan
                   6444:                             on processing this line
                   6445:                         2 - we are on a 'do skipped records pass' and this
                   6446:                             scanline has been marked to skip yet again
1.424     albertel 6447: 
1.423     albertel 6448: =cut
                   6449: 
1.157     albertel 6450: sub scantron_getfile {
1.200     albertel 6451:     #FIXME really would prefer a scantron directory
1.257     albertel 6452:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   6453:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1.157     albertel 6454:     my $lines;
                   6455:     $lines=&Apache::lonnet::getfile('/uploaded/'.$cdom.'/'.$cname.'/'.
1.257     albertel 6456: 		       'scantron_orig_'.$env{'form.scantron_selectfile'});
1.157     albertel 6457:     my %scanlines;
                   6458:     $scanlines{'orig'}=[(split("\n",$lines,-1))];
                   6459:     my $temp=$scanlines{'orig'};
                   6460:     $scanlines{'count'}=$#$temp;
                   6461: 
                   6462:     $lines=&Apache::lonnet::getfile('/uploaded/'.$cdom.'/'.$cname.'/'.
1.257     albertel 6463: 		       'scantron_corrected_'.$env{'form.scantron_selectfile'});
1.157     albertel 6464:     if ($lines eq '-1') {
                   6465: 	$scanlines{'corrected'}=[];
                   6466:     } else {
                   6467: 	$scanlines{'corrected'}=[(split("\n",$lines,-1))];
                   6468:     }
                   6469:     $lines=&Apache::lonnet::getfile('/uploaded/'.$cdom.'/'.$cname.'/'.
1.257     albertel 6470: 		       'scantron_skipped_'.$env{'form.scantron_selectfile'});
1.157     albertel 6471:     if ($lines eq '-1') {
                   6472: 	$scanlines{'skipped'}=[];
                   6473:     } else {
                   6474: 	$scanlines{'skipped'}=[(split("\n",$lines,-1))];
                   6475:     }
1.175     albertel 6476:     my @tmp=&Apache::lonnet::dump('nohist_scantrondata',$cdom,$cname);
1.157     albertel 6477:     if ($tmp[0] =~ /^(error:|no_such_host)/) { @tmp=(); }
                   6478:     my %scan_data = @tmp;
                   6479:     return (\%scanlines,\%scan_data);
                   6480: }
                   6481: 
1.423     albertel 6482: =pod
                   6483: 
                   6484: =item lonnet_putfile
                   6485: 
1.424     albertel 6486:    Wrapper routine to call &Apache::lonnet::finishuserfileupload
                   6487: 
                   6488:  Arguments:
                   6489:    $contents - data to store
                   6490:    $filename - filename to store $contents into
                   6491: 
                   6492:  Returns:
                   6493:    result value from &Apache::lonnet::finishuserfileupload
                   6494: 
1.423     albertel 6495: =cut
                   6496: 
1.157     albertel 6497: sub lonnet_putfile {
                   6498:     my ($contents,$filename)=@_;
1.257     albertel 6499:     my $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   6500:     my $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
                   6501:     $env{'form.sillywaytopassafilearound'}=$contents;
1.275     albertel 6502:     &Apache::lonnet::finishuserfileupload($docuname,$docudom,'sillywaytopassafilearound',$filename);
1.157     albertel 6503: 
                   6504: }
                   6505: 
1.423     albertel 6506: =pod
                   6507: 
                   6508: =item scantron_putfile
                   6509: 
1.424     albertel 6510:     Stores the current version of the bubble sheet data files, and the
                   6511:     scan_data hash. (Does not modify the original version only the
                   6512:     corrected and skipped versions.
                   6513: 
                   6514:  Arguments:
                   6515:     $scanlines - hash ref that looks like the first return value from
                   6516:                  &scantron_getfile()
                   6517:     $scan_data - hash ref that looks like the second return value from
                   6518:                  &scantron_getfile()
                   6519: 
1.423     albertel 6520: =cut
                   6521: 
1.157     albertel 6522: sub scantron_putfile {
                   6523:     my ($scanlines,$scan_data) = @_;
1.200     albertel 6524:     #FIXME really would prefer a scantron directory
1.257     albertel 6525:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   6526:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1.200     albertel 6527:     if ($scanlines) {
                   6528: 	my $prefix='scantron_';
1.157     albertel 6529: # no need to update orig, shouldn't change
                   6530: #   &lonnet_putfile(join("\n",@{$scanlines->{'orig'}}),$prefix.'orig_'.
1.257     albertel 6531: #		    $env{'form.scantron_selectfile'});
1.200     albertel 6532: 	&lonnet_putfile(join("\n",@{$scanlines->{'corrected'}}),
                   6533: 			$prefix.'corrected_'.
1.257     albertel 6534: 			$env{'form.scantron_selectfile'});
1.200     albertel 6535: 	&lonnet_putfile(join("\n",@{$scanlines->{'skipped'}}),
                   6536: 			$prefix.'skipped_'.
1.257     albertel 6537: 			$env{'form.scantron_selectfile'});
1.200     albertel 6538:     }
1.175     albertel 6539:     &Apache::lonnet::put('nohist_scantrondata',$scan_data,$cdom,$cname);
1.157     albertel 6540: }
                   6541: 
1.423     albertel 6542: =pod
                   6543: 
                   6544: =item scantron_get_line
                   6545: 
1.424     albertel 6546:    Returns the correct version of the scanline
                   6547: 
                   6548:  Arguments:
                   6549:     $scanlines - hash ref that looks like the first return value from
                   6550:                  &scantron_getfile()
                   6551:     $scan_data - hash ref that looks like the second return value from
                   6552:                  &scantron_getfile()
                   6553:     $i         - number of the requested line (starts at 0)
                   6554: 
                   6555:  Returns:
                   6556:    A scanline, (either the original or the corrected one if it
                   6557:    exists), or undef if the requested scanline should be
                   6558:    skipped. (Either because it's an skipped scanline, or it's an
                   6559:    unskipped scanline and we are not doing a 'do skipped scanlines'
                   6560:    pass.
                   6561: 
1.423     albertel 6562: =cut
                   6563: 
1.157     albertel 6564: sub scantron_get_line {
1.200     albertel 6565:     my ($scanlines,$scan_data,$i)=@_;
1.376     albertel 6566:     if (&should_be_skipped($scanlines,$scan_data,$i)) { return undef; }
                   6567:     #if ($scanlines->{'skipped'}[$i]) { return undef; }
1.157     albertel 6568:     if ($scanlines->{'corrected'}[$i]) {return $scanlines->{'corrected'}[$i];}
                   6569:     return $scanlines->{'orig'}[$i]; 
                   6570: }
                   6571: 
1.423     albertel 6572: =pod
                   6573: 
                   6574: =item scantron_todo_count
                   6575: 
1.424     albertel 6576:     Counts the number of scanlines that need processing.
                   6577: 
                   6578:  Arguments:
                   6579:     $scanlines - hash ref that looks like the first return value from
                   6580:                  &scantron_getfile()
                   6581:     $scan_data - hash ref that looks like the second return value from
                   6582:                  &scantron_getfile()
                   6583: 
                   6584:  Returns:
                   6585:     $count - number of scanlines to process
                   6586: 
1.423     albertel 6587: =cut
                   6588: 
1.200     albertel 6589: sub get_todo_count {
                   6590:     my ($scanlines,$scan_data)=@_;
                   6591:     my $count=0;
                   6592:     for (my $i=0;$i<=$scanlines->{'count'};$i++) {
                   6593: 	my $line=&scantron_get_line($scanlines,$scan_data,$i);
                   6594: 	if ($line=~/^[\s\cz]*$/) { next; }
                   6595: 	$count++;
                   6596:     }
                   6597:     return $count;
                   6598: }
                   6599: 
1.423     albertel 6600: =pod
                   6601: 
                   6602: =item scantron_put_line
                   6603: 
1.424     albertel 6604:     Updates the 'corrected' or 'skipped' versions of the bubble sheet
                   6605:     data file.
                   6606: 
                   6607:  Arguments:
                   6608:     $scanlines - hash ref that looks like the first return value from
                   6609:                  &scantron_getfile()
                   6610:     $scan_data - hash ref that looks like the second return value from
                   6611:                  &scantron_getfile()
                   6612:     $i         - line number to update
                   6613:     $newline   - contents of the updated scanline
                   6614:     $skip      - if true make the line for skipping and update the
                   6615:                  'skipped' file
                   6616: 
1.423     albertel 6617: =cut
                   6618: 
1.157     albertel 6619: sub scantron_put_line {
1.200     albertel 6620:     my ($scanlines,$scan_data,$i,$newline,$skip)=@_;
1.157     albertel 6621:     if ($skip) {
                   6622: 	$scanlines->{'skipped'}[$i]=$newline;
1.376     albertel 6623: 	&start_skipping($scan_data,$i);
1.157     albertel 6624: 	return;
                   6625:     }
                   6626:     $scanlines->{'corrected'}[$i]=$newline;
                   6627: }
                   6628: 
1.423     albertel 6629: =pod
                   6630: 
                   6631: =item scantron_clear_skip
                   6632: 
1.424     albertel 6633:    Remove a line from the 'skipped' file
                   6634: 
                   6635:  Arguments:
                   6636:     $scanlines - hash ref that looks like the first return value from
                   6637:                  &scantron_getfile()
                   6638:     $scan_data - hash ref that looks like the second return value from
                   6639:                  &scantron_getfile()
                   6640:     $i         - line number to update
                   6641: 
1.423     albertel 6642: =cut
                   6643: 
1.376     albertel 6644: sub scantron_clear_skip {
                   6645:     my ($scanlines,$scan_data,$i)=@_;
                   6646:     if (exists($scanlines->{'skipped'}[$i])) {
                   6647: 	undef($scanlines->{'skipped'}[$i]);
                   6648: 	return 1;
                   6649:     }
                   6650:     return 0;
                   6651: }
                   6652: 
1.423     albertel 6653: =pod
                   6654: 
                   6655: =item scantron_filter_not_exam
                   6656: 
1.424     albertel 6657:    Filter routine used by &Apache::lonnavmaps::retrieveResources(), to
                   6658:    filter out resources that are not marked as 'exam' mode
                   6659: 
1.423     albertel 6660: =cut
                   6661: 
1.334     albertel 6662: sub scantron_filter_not_exam {
                   6663:     my ($curres)=@_;
                   6664:     
                   6665:     if (ref($curres) && $curres->is_problem() && !$curres->is_exam()) {
                   6666: 	# if the user has asked to not have either hidden
                   6667: 	# or 'randomout' controlled resources to be graded
                   6668: 	# don't include them
                   6669: 	if ($env{'form.scantron_options_hidden'} eq 'ignore_hidden'
                   6670: 	    && $curres->randomout) {
                   6671: 	    return 0;
                   6672: 	}
                   6673: 	return 1;
                   6674:     }
                   6675:     return 0;
                   6676: }
                   6677: 
1.423     albertel 6678: =pod
                   6679: 
                   6680: =item scantron_validate_sequence
                   6681: 
1.424     albertel 6682:     Validates the selected sequence, checking for resource that are
                   6683:     not set to exam mode.
                   6684: 
1.423     albertel 6685: =cut
                   6686: 
1.334     albertel 6687: sub scantron_validate_sequence {
                   6688:     my ($r,$currentphase) = @_;
                   6689: 
                   6690:     my $navmap=Apache::lonnavmaps::navmap->new();
1.582     raeburn  6691:     unless (ref($navmap)) {
                   6692:         $r->print(&navmap_errormsg());
                   6693:         return (1,$currentphase);
                   6694:     }
1.334     albertel 6695:     my (undef,undef,$sequence)=
                   6696: 	&Apache::lonnet::decode_symb($env{'form.selectpage'});
                   6697: 
                   6698:     my $map=$navmap->getResourceByUrl($sequence);
                   6699: 
                   6700:     $r->print('<input type="hidden" name="validate_sequence_exam"
                   6701:                                     value="ignore" />');
                   6702:     if ($env{'form.validate_sequence_exam'} ne 'ignore') {
                   6703: 	my @resources=
                   6704: 	    $navmap->retrieveResources($map,\&scantron_filter_not_exam,1,0);
                   6705: 	if (@resources) {
1.357     banghart 6706: 	    $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 6707: 	    return (1,$currentphase);
                   6708: 	}
                   6709:     }
                   6710: 
                   6711:     return (0,$currentphase+1);
                   6712: }
                   6713: 
1.423     albertel 6714: 
                   6715: 
1.157     albertel 6716: sub scantron_validate_ID {
                   6717:     my ($r,$currentphase) = @_;
                   6718:     
                   6719:     #get student info
                   6720:     my $classlist=&Apache::loncoursedata::get_classlist();
                   6721:     my %idmap=&username_to_idmap($classlist);
                   6722: 
                   6723:     #get scantron line setup
1.257     albertel 6724:     my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
1.157     albertel 6725:     my ($scanlines,$scan_data)=&scantron_getfile();
1.582     raeburn  6726: 
                   6727:     my $nav_error;
                   6728:     &scantron_get_maxbubble(\$nav_error); # parse needs the bubble_lines.. array.
                   6729:     if ($nav_error) {
                   6730:         $r->print(&navmap_errormsg());
                   6731:         return(1,$currentphase);
                   6732:     }
1.157     albertel 6733: 
                   6734:     my %found=('ids'=>{},'usernames'=>{});
                   6735:     for (my $i=0;$i<=$scanlines->{'count'};$i++) {
1.200     albertel 6736: 	my $line=&scantron_get_line($scanlines,$scan_data,$i);
1.157     albertel 6737: 	if ($line=~/^[\s\cz]*$/) { next; }
                   6738: 	my $scan_record=&scantron_parse_scanline($line,$i,\%scantron_config,
                   6739: 						 $scan_data);
                   6740: 	my $id=$$scan_record{'scantron.ID'};
                   6741: 	my $found;
                   6742: 	foreach my $checkid (keys(%idmap)) {
                   6743: 	    if (lc($checkid) eq lc($id)) { $found=$checkid;last; }
                   6744: 	}
                   6745: 	if ($found) {
                   6746: 	    my $username=$idmap{$found};
                   6747: 	    if ($found{'ids'}{$found}) {
                   6748: 		&scantron_get_correction($r,$i,$scan_record,\%scantron_config,
                   6749: 					 $line,'duplicateID',$found);
1.194     albertel 6750: 		return(1,$currentphase);
1.157     albertel 6751: 	    } elsif ($found{'usernames'}{$username}) {
                   6752: 		&scantron_get_correction($r,$i,$scan_record,\%scantron_config,
                   6753: 					 $line,'duplicateID',$username);
1.194     albertel 6754: 		return(1,$currentphase);
1.157     albertel 6755: 	    }
1.186     albertel 6756: 	    #FIXME store away line we previously saw the ID on to use above
1.157     albertel 6757: 	    $found{'ids'}{$found}++;
                   6758: 	    $found{'usernames'}{$username}++;
                   6759: 	} else {
                   6760: 	    if ($id =~ /^\s*$/) {
1.158     albertel 6761: 		my $username=&scan_data($scan_data,"$i.user");
1.157     albertel 6762: 		if (defined($username) && $found{'usernames'}{$username}) {
                   6763: 		    &scantron_get_correction($r,$i,$scan_record,
                   6764: 					     \%scantron_config,
                   6765: 					     $line,'duplicateID',$username);
1.194     albertel 6766: 		    return(1,$currentphase);
1.157     albertel 6767: 		} elsif (!defined($username)) {
                   6768: 		    &scantron_get_correction($r,$i,$scan_record,
                   6769: 					     \%scantron_config,
                   6770: 					     $line,'incorrectID');
1.194     albertel 6771: 		    return(1,$currentphase);
1.157     albertel 6772: 		}
                   6773: 		$found{'usernames'}{$username}++;
                   6774: 	    } else {
                   6775: 		&scantron_get_correction($r,$i,$scan_record,\%scantron_config,
                   6776: 					 $line,'incorrectID');
1.194     albertel 6777: 		return(1,$currentphase);
1.157     albertel 6778: 	    }
                   6779: 	}
                   6780:     }
                   6781: 
                   6782:     return (0,$currentphase+1);
                   6783: }
                   6784: 
1.423     albertel 6785: 
1.157     albertel 6786: sub scantron_get_correction {
                   6787:     my ($r,$i,$scan_record,$scan_config,$line,$error,$arg)=@_;
1.454     banghart 6788: #FIXME in the case of a duplicated ID the previous line, probably need
1.157     albertel 6789: #to show both the current line and the previous one and allow skipping
                   6790: #the previous one or the current one
                   6791: 
1.333     albertel 6792:     if ( $$scan_record{'scantron.PaperID'} =~ /\S/) {
1.492     albertel 6793: 	$r->print("<p>".&mt("<b>An error was detected ($error)</b>".
                   6794: 			    " for PaperID <tt>[_1]</tt>",
                   6795: 			    $$scan_record{'scantron.PaperID'})."</p> \n");
1.157     albertel 6796:     } else {
1.492     albertel 6797: 	$r->print("<p>".&mt("<b>An error was detected ($error)</b>".
                   6798: 			    " in scanline [_1] <pre>[_2]</pre>",
                   6799: 			    $i,$line)."</p> \n");
                   6800:     }
                   6801:     my $message="<p>".&mt("The ID on the form is  <tt>[_1]</tt><br />".
                   6802: 			  "The name on the paper is [_2],[_3]",
                   6803: 			  $$scan_record{'scantron.ID'},
                   6804: 			  $$scan_record{'scantron.LastName'},
                   6805: 			  $$scan_record{'scantron.FirstName'})."</p>";
1.242     albertel 6806: 
1.157     albertel 6807:     $r->print('<input type="hidden" name="scantron_corrections" value="'.$error.'" />'."\n");
                   6808:     $r->print('<input type="hidden" name="scantron_line" value="'.$i.'" />'."\n");
1.503     raeburn  6809:                            # Array populated for doublebubble or
                   6810:     my @lines_to_correct;  # missingbubble errors to build javascript
                   6811:                            # to validate radio button checking   
                   6812: 
1.157     albertel 6813:     if ($error =~ /ID$/) {
1.186     albertel 6814: 	if ($error eq 'incorrectID') {
1.492     albertel 6815: 	    $r->print("<p>".&mt("The encoded ID is not in the classlist").
                   6816: 		      "</p>\n");
1.157     albertel 6817: 	} elsif ($error eq 'duplicateID') {
1.492     albertel 6818: 	    $r->print("<p>".&mt("The encoded ID has also been used by a previous paper [_1]",$arg)."</p>\n");
1.157     albertel 6819: 	}
1.242     albertel 6820: 	$r->print($message);
1.492     albertel 6821: 	$r->print("<p>".&mt("How should I handle this?")." <br /> \n");
1.157     albertel 6822: 	$r->print("\n<ul><li> ");
                   6823: 	#FIXME it would be nice if this sent back the user ID and
                   6824: 	#could do partial userID matches
                   6825: 	$r->print(&Apache::loncommon::selectstudent_link('scantronupload',
                   6826: 				       'scantron_username','scantron_domain'));
                   6827: 	$r->print(": <input type='text' name='scantron_username' value='' />");
                   6828: 	$r->print("\n@".
1.257     albertel 6829: 		 &Apache::loncommon::select_dom_form($env{'request.role.domain'},'scantron_domain'));
1.157     albertel 6830: 
                   6831: 	$r->print('</li>');
1.186     albertel 6832:     } elsif ($error =~ /CODE$/) {
                   6833: 	if ($error eq 'incorrectCODE') {
1.492     albertel 6834: 	    $r->print("<p>".&mt("The encoded CODE is not in the list of possible CODEs.")."</p>\n");
1.186     albertel 6835: 	} elsif ($error eq 'duplicateCODE') {
1.492     albertel 6836: 	    $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 6837: 	}
1.492     albertel 6838: 	$r->print("<p>".&mt("The CODE on the form is  <tt>'[_1]'</tt>",
                   6839: 			    $$scan_record{'scantron.CODE'})."<br />\n");
1.242     albertel 6840: 	$r->print($message);
1.492     albertel 6841: 	$r->print("<p>".&mt("How should I handle this?")." <br /> \n");
1.187     albertel 6842: 	$r->print("\n<br /> ");
1.194     albertel 6843: 	my $i=0;
1.273     albertel 6844: 	if ($error eq 'incorrectCODE' 
                   6845: 	    && $$scan_record{'scantron.CODE'}=~/\S/ ) {
1.194     albertel 6846: 	    my ($max,$closest)=&scantron_get_closely_matching_CODEs($arg,$$scan_record{'scantron.CODE'});
1.278     albertel 6847: 	    if ($closest > 0) {
                   6848: 		foreach my $testcode (@{$closest}) {
                   6849: 		    my $checked='';
1.569     bisitz   6850: 		    if (!$i) { $checked=' checked="checked"'; }
1.492     albertel 6851: 		    $r->print("
                   6852:    <label>
1.569     bisitz   6853:        <input type='radio' name='scantron_CODE_resolution' value='use_closest_$i'$checked />
1.492     albertel 6854:        ".&mt("Use the similar CODE [_1] instead.",
                   6855: 	    "<b><tt>".$testcode."</tt></b>")."
                   6856:     </label>
                   6857:     <input type='hidden' name='scantron_CODE_closest_$i' value='$testcode' />");
1.278     albertel 6858: 		    $r->print("\n<br />");
                   6859: 		    $i++;
                   6860: 		}
1.194     albertel 6861: 	    }
                   6862: 	}
1.273     albertel 6863: 	if ($$scan_record{'scantron.CODE'}=~/\S/ ) {
1.569     bisitz   6864: 	    my $checked; if (!$i) { $checked=' checked="checked"'; }
1.492     albertel 6865: 	    $r->print("
                   6866:     <label>
1.569     bisitz   6867:         <input type='radio' name='scantron_CODE_resolution' value='use_unfound'$checked />
1.492     albertel 6868:        ".&mt("Use the CODE [_1] that is was on the paper, ignoring the error.",
                   6869: 	     "<b><tt>".$$scan_record{'scantron.CODE'}."</tt></b>")."
                   6870:     </label>");
1.273     albertel 6871: 	    $r->print("\n<br />");
                   6872: 	}
1.194     albertel 6873: 
1.597     wenzelju 6874: 	$r->print(&Apache::lonhtmlcommon::scripttag(<<ENDSCRIPT));
1.188     albertel 6875: function change_radio(field) {
1.190     albertel 6876:     var slct=document.scantronupload.scantron_CODE_resolution;
1.188     albertel 6877:     var i;
                   6878:     for (i=0;i<slct.length;i++) {
                   6879:         if (slct[i].value==field) { slct[i].checked=true; }
                   6880:     }
                   6881: }
                   6882: ENDSCRIPT
1.187     albertel 6883: 	my $href="/adm/pickcode?".
1.359     www      6884: 	   "form=".&escape("scantronupload").
                   6885: 	   "&scantron_format=".&escape($env{'form.scantron_format'}).
                   6886: 	   "&scantron_CODElist=".&escape($env{'form.scantron_CODElist'}).
                   6887: 	   "&curCODE=".&escape($$scan_record{'scantron.CODE'}).
                   6888: 	   "&scantron_selectfile=".&escape($env{'form.scantron_selectfile'});
1.332     albertel 6889: 	if ($env{'form.scantron_CODElist'} =~ /\S/) { 
1.492     albertel 6890: 	    $r->print("
                   6891:     <label>
                   6892:        <input type='radio' name='scantron_CODE_resolution' value='use_found' />
                   6893:        ".&mt("[_1]Select[_2] a CODE from the list of all CODEs and use it.",
                   6894: 	     "<a target='_blank' href='$href'>","</a>")."
                   6895:     </label> 
1.558     bisitz   6896:     ".&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 6897: 	    $r->print("\n<br />");
                   6898: 	}
1.492     albertel 6899: 	$r->print("
                   6900:     <label>
                   6901:        <input type='radio' name='scantron_CODE_resolution' value='use_typed' />
                   6902:        ".&mt("Use [_1] as the CODE.",
                   6903: 	     "</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 6904: 	$r->print("\n<br /><br />");
1.157     albertel 6905:     } elsif ($error eq 'doublebubble') {
1.503     raeburn  6906: 	$r->print("<p>".&mt("There have been multiple bubbles scanned for some question(s)")."</p>\n");
1.497     foxr     6907: 
                   6908: 	# The form field scantron_questions is acutally a list of line numbers.
                   6909: 	# represented by this form so:
                   6910: 
                   6911: 	my $line_list = &questions_to_line_list($arg);
                   6912: 
1.157     albertel 6913: 	$r->print('<input type="hidden" name="scantron_questions" value="'.
1.497     foxr     6914: 		  $line_list.'" />');
1.242     albertel 6915: 	$r->print($message);
1.492     albertel 6916: 	$r->print("<p>".&mt("Please indicate which bubble should be used for grading")."</p>");
1.157     albertel 6917: 	foreach my $question (@{$arg}) {
1.503     raeburn  6918: 	    my @linenums = &prompt_for_corrections($r,$question,$scan_config,
                   6919:                                                    $scan_record, $error);
1.524     raeburn  6920:             push(@lines_to_correct,@linenums);
1.157     albertel 6921: 	}
1.503     raeburn  6922:         $r->print(&verify_bubbles_checked(@lines_to_correct));
1.157     albertel 6923:     } elsif ($error eq 'missingbubble') {
1.492     albertel 6924: 	$r->print("<p>".&mt("There have been <b>no</b> bubbles scanned for some question(s)")."</p>\n");
1.242     albertel 6925: 	$r->print($message);
1.492     albertel 6926: 	$r->print("<p>".&mt("Please indicate which bubble should be used for grading.")."</p>");
1.503     raeburn  6927: 	$r->print(&mt("Some questions have no scanned bubbles.")."\n");
1.497     foxr     6928: 
1.503     raeburn  6929: 	# The form field scantron_questions is actually a list of line numbers not
1.497     foxr     6930: 	# a list of question numbers. Therefore:
                   6931: 	#
                   6932: 	
                   6933: 	my $line_list = &questions_to_line_list($arg);
                   6934: 
1.157     albertel 6935: 	$r->print('<input type="hidden" name="scantron_questions" value="'.
1.497     foxr     6936: 		  $line_list.'" />');
1.157     albertel 6937: 	foreach my $question (@{$arg}) {
1.503     raeburn  6938: 	    my @linenums = &prompt_for_corrections($r,$question,$scan_config,
                   6939:                                                    $scan_record, $error);
1.524     raeburn  6940:             push(@lines_to_correct,@linenums);
1.157     albertel 6941: 	}
1.503     raeburn  6942:         $r->print(&verify_bubbles_checked(@lines_to_correct));
1.157     albertel 6943:     } else {
                   6944: 	$r->print("\n<ul>");
                   6945:     }
                   6946:     $r->print("\n</li></ul>");
1.497     foxr     6947: }
                   6948: 
1.503     raeburn  6949: sub verify_bubbles_checked {
                   6950:     my (@ansnums) = @_;
                   6951:     my $ansnumstr = join('","',@ansnums);
                   6952:     my $warning = &mt("A bubble or 'No bubble' selection has not been made for one or more lines.");
1.597     wenzelju 6953:     my $output = &Apache::lonhtmlcommon::scripttag((<<ENDSCRIPT));
1.503     raeburn  6954: function verify_bubble_radio(form) {
                   6955:     var ansnumArray = new Array ("$ansnumstr");
                   6956:     var need_bubble_count = 0;
                   6957:     for (var i=0; i<ansnumArray.length; i++) {
                   6958:         if (form.elements["scantron_correct_Q_"+ansnumArray[i]].length > 1) {
                   6959:             var bubble_picked = 0; 
                   6960:             for (var j=0; j<form.elements["scantron_correct_Q_"+ansnumArray[i]].length; j++) {
                   6961:                 if (form.elements["scantron_correct_Q_"+ansnumArray[i]][j].checked == true) {
                   6962:                     bubble_picked = 1;
                   6963:                 }
                   6964:             }
                   6965:             if (bubble_picked == 0) {
                   6966:                 need_bubble_count ++;
                   6967:             }
                   6968:         }
                   6969:     }
                   6970:     if (need_bubble_count) {
                   6971:         alert("$warning");
                   6972:         return;
                   6973:     }
                   6974:     form.submit(); 
                   6975: }
                   6976: ENDSCRIPT
                   6977:     return $output;
                   6978: }
                   6979: 
1.497     foxr     6980: =pod
                   6981: 
                   6982: =item  questions_to_line_list
1.157     albertel 6983: 
1.497     foxr     6984: Converts a list of questions into a string of comma separated
                   6985: line numbers in the answer sheet used by the questions.  This is
                   6986: used to fill in the scantron_questions form field.
                   6987: 
                   6988:   Arguments:
                   6989:      questions    - Reference to an array of questions.
                   6990: 
                   6991: =cut
                   6992: 
                   6993: 
                   6994: sub questions_to_line_list {
                   6995:     my ($questions) = @_;
                   6996:     my @lines;
                   6997: 
1.503     raeburn  6998:     foreach my $item (@{$questions}) {
                   6999:         my $question = $item;
                   7000:         my ($first,$count,$last);
                   7001:         if ($item =~ /^(\d+)\.(\d+)$/) {
                   7002:             $question = $1;
                   7003:             my $subquestion = $2;
                   7004:             $first = $first_bubble_line{$question-1} + 1;
                   7005:             my @subans = split(/,/,$subdivided_bubble_lines{$question-1});
                   7006:             my $subcount = 1;
                   7007:             while ($subcount<$subquestion) {
                   7008:                 $first += $subans[$subcount-1];
                   7009:                 $subcount ++;
                   7010:             }
                   7011:             $count = $subans[$subquestion-1];
                   7012:         } else {
                   7013: 	    $first   = $first_bubble_line{$question-1} + 1;
                   7014: 	    $count   = $bubble_lines_per_response{$question-1};
                   7015:         }
1.506     raeburn  7016:         $last = $first+$count-1;
1.503     raeburn  7017:         push(@lines, ($first..$last));
1.497     foxr     7018:     }
                   7019:     return join(',', @lines);
                   7020: }
                   7021: 
                   7022: =pod 
                   7023: 
                   7024: =item prompt_for_corrections
                   7025: 
                   7026: Prompts for a potentially multiline correction to the
                   7027: user's bubbling (factors out common code from scantron_get_correction
                   7028: for multi and missing bubble cases).
                   7029: 
                   7030:  Arguments:
                   7031:    $r           - Apache request object.
                   7032:    $question    - The question number to prompt for.
                   7033:    $scan_config - The scantron file configuration hash.
                   7034:    $scan_record - Reference to the hash that has the the parsed scanlines.
1.503     raeburn  7035:    $error       - Type of error
1.497     foxr     7036: 
                   7037:  Implicit inputs:
                   7038:    %bubble_lines_per_response   - Starting line numbers for each question.
                   7039:                                   Numbered from 0 (but question numbers are from
                   7040:                                   1.
                   7041:    %first_bubble_line           - Starting bubble line for each question.
1.509     raeburn  7042:    %subdivided_bubble_lines     - optionresponse, matchresponse and rankresponse 
                   7043:                                   type problems render as separate sub-questions, 
1.503     raeburn  7044:                                   in exam mode. This hash contains a 
                   7045:                                   comma-separated list of the lines per 
                   7046:                                   sub-question.
1.510     raeburn  7047:    %responsetype_per_response   - essayresponse, formularesponse,
                   7048:                                   stringresponse, imageresponse, reactionresponse,
                   7049:                                   and organicresponse type problem parts can have
1.503     raeburn  7050:                                   multiple lines per response if the weight
                   7051:                                   assigned exceeds 10.  In this case, only
                   7052:                                   one bubble per line is permitted, but more 
                   7053:                                   than one line might contain bubbles, e.g.
                   7054:                                   bubbling of: line 1 - J, line 2 - J, 
                   7055:                                   line 3 - B would assign 22 points.  
1.497     foxr     7056: 
                   7057: =cut
                   7058: 
                   7059: sub prompt_for_corrections {
1.503     raeburn  7060:     my ($r, $question, $scan_config, $scan_record, $error) = @_;
                   7061:     my ($current_line,$lines);
                   7062:     my @linenums;
                   7063:     my $questionnum = $question;
                   7064:     if ($question =~ /^(\d+)\.(\d+)$/) {
                   7065:         $question = $1;
                   7066:         $current_line = $first_bubble_line{$question-1} + 1 ;
                   7067:         my $subquestion = $2;
                   7068:         my @subans = split(/,/,$subdivided_bubble_lines{$question-1});
                   7069:         my $subcount = 1;
                   7070:         while ($subcount<$subquestion) {
                   7071:             $current_line += $subans[$subcount-1];
                   7072:             $subcount ++;
                   7073:         }
                   7074:         $lines = $subans[$subquestion-1];
                   7075:     } else {
                   7076:         $current_line = $first_bubble_line{$question-1} + 1 ;
                   7077:         $lines        = $bubble_lines_per_response{$question-1};
                   7078:     }
1.497     foxr     7079:     if ($lines > 1) {
1.503     raeburn  7080:         $r->print(&mt('The group of bubble lines below responds to a single question.').'<br />');
                   7081:         if (($responsetype_per_response{$question-1} eq 'essayresponse') ||
                   7082:             ($responsetype_per_response{$question-1} eq 'formularesponse') ||
1.510     raeburn  7083:             ($responsetype_per_response{$question-1} eq 'stringresponse') ||
                   7084:             ($responsetype_per_response{$question-1} eq 'imageresponse') ||
                   7085:             ($responsetype_per_response{$question-1} eq 'reactionresponse') ||
                   7086:             ($responsetype_per_response{$question-1} eq 'organicresponse')) {
1.572     www      7087:             $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  7088:         } else {
                   7089:             $r->print(&mt("Select at most one bubble in a single line and select 'No Bubble' in all the other lines. ")."<br />");
                   7090:         }
1.497     foxr     7091:     }
                   7092:     for (my $i =0; $i < $lines; $i++) {
1.503     raeburn  7093:         my $selected = $$scan_record{"scantron.$current_line.answer"};
                   7094: 	&scantron_bubble_selector($r,$scan_config,$current_line, 
                   7095: 	        		  $questionnum,$error,split('', $selected));
1.524     raeburn  7096:         push(@linenums,$current_line);
1.497     foxr     7097: 	$current_line++;
                   7098:     }
                   7099:     if ($lines > 1) {
                   7100: 	$r->print("<hr /><br />");
                   7101:     }
1.503     raeburn  7102:     return @linenums;
1.157     albertel 7103: }
1.423     albertel 7104: 
                   7105: =pod
                   7106: 
                   7107: =item scantron_bubble_selector
                   7108:   
                   7109:    Generates the html radiobuttons to correct a single bubble line
1.424     albertel 7110:    possibly showing the existing the selected bubbles if known
1.423     albertel 7111: 
                   7112:  Arguments:
                   7113:     $r           - Apache request object
                   7114:     $scan_config - hash from &get_scantron_config()
1.497     foxr     7115:     $line        - Number of the line being displayed.
1.503     raeburn  7116:     $questionnum - Question number (may include subquestion)
                   7117:     $error       - Type of error.
1.497     foxr     7118:     @selected    - Array of bubbles picked on this line.
1.423     albertel 7119: 
                   7120: =cut
                   7121: 
1.157     albertel 7122: sub scantron_bubble_selector {
1.503     raeburn  7123:     my ($r,$scan_config,$line,$questionnum,$error,@selected)=@_;
1.157     albertel 7124:     my $max=$$scan_config{'Qlength'};
1.274     albertel 7125: 
                   7126:     my $scmode=$$scan_config{'Qon'};
                   7127:     if ($scmode eq 'number' || $scmode eq 'letter') { $max=10; }	     
                   7128: 
1.157     albertel 7129:     my @alphabet=('A'..'Z');
1.503     raeburn  7130:     $r->print(&Apache::loncommon::start_data_table().
                   7131:               &Apache::loncommon::start_data_table_row());
                   7132:     $r->print('<td rowspan="2" class="LC_leftcol_header">'.$line.'</td>');
1.497     foxr     7133:     for (my $i=0;$i<$max+1;$i++) {
                   7134: 	$r->print("\n".'<td align="center">');
                   7135: 	if ($selected[0] eq $alphabet[$i]) { $r->print('X'); shift(@selected) }
                   7136: 	else { $r->print('&nbsp;'); }
                   7137: 	$r->print('</td>');
                   7138:     }
1.503     raeburn  7139:     $r->print(&Apache::loncommon::end_data_table_row().
                   7140:               &Apache::loncommon::start_data_table_row());
1.497     foxr     7141:     for (my $i=0;$i<$max;$i++) {
                   7142: 	$r->print("\n".
                   7143: 		  '<td><label><input type="radio" name="scantron_correct_Q_'.
                   7144: 		  $line.'" value="'.$i.'" />'.$alphabet[$i]."</label></td>");
                   7145:     }
1.503     raeburn  7146:     my $nobub_checked = ' ';
                   7147:     if ($error eq 'missingbubble') {
                   7148:         $nobub_checked = ' checked = "checked" ';
                   7149:     }
                   7150:     $r->print("\n".'<td><label><input type="radio" name="scantron_correct_Q_'.
                   7151: 	      $line.'" value="none"'.$nobub_checked.'/>'.&mt('No bubble').
                   7152:               '</label>'."\n".'<input type="hidden" name="scantron_questionnum_Q_'.
                   7153:               $line.'" value="'.$questionnum.'" /></td>');
                   7154:     $r->print(&Apache::loncommon::end_data_table_row().
                   7155:               &Apache::loncommon::end_data_table());
1.157     albertel 7156: }
                   7157: 
1.423     albertel 7158: =pod
                   7159: 
                   7160: =item num_matches
                   7161: 
1.424     albertel 7162:    Counts the number of characters that are the same between the two arguments.
                   7163: 
                   7164:  Arguments:
                   7165:    $orig - CODE from the scanline
                   7166:    $code - CODE to match against
                   7167: 
                   7168:  Returns:
                   7169:    $count - integer count of the number of same characters between the
                   7170:             two arguments
                   7171: 
1.423     albertel 7172: =cut
                   7173: 
1.194     albertel 7174: sub num_matches {
                   7175:     my ($orig,$code) = @_;
                   7176:     my @code=split(//,$code);
                   7177:     my @orig=split(//,$orig);
                   7178:     my $same=0;
                   7179:     for (my $i=0;$i<scalar(@code);$i++) {
                   7180: 	if ($code[$i] eq $orig[$i]) { $same++; }
                   7181:     }
                   7182:     return $same;
                   7183: }
                   7184: 
1.423     albertel 7185: =pod
                   7186: 
                   7187: =item scantron_get_closely_matching_CODEs
                   7188: 
1.424     albertel 7189:    Cycles through all CODEs and finds the set that has the greatest
                   7190:    number of same characters as the provided CODE
                   7191: 
                   7192:  Arguments:
                   7193:    $allcodes - hash ref returned by &get_codes()
                   7194:    $CODE     - CODE from the current scanline
                   7195: 
                   7196:  Returns:
                   7197:    2 element list
                   7198:     - first elements is number of how closely matching the best fit is 
                   7199:       (5 means best set has 5 matching characters)
                   7200:     - second element is an arrary ref containing the set of valid CODEs
                   7201:       that best fit the passed in CODE
                   7202: 
1.423     albertel 7203: =cut
                   7204: 
1.194     albertel 7205: sub scantron_get_closely_matching_CODEs {
                   7206:     my ($allcodes,$CODE)=@_;
                   7207:     my @CODEs;
                   7208:     foreach my $testcode (sort(keys(%{$allcodes}))) {
                   7209: 	push(@{$CODEs[&num_matches($CODE,$testcode)]},$testcode);
                   7210:     }
                   7211: 
                   7212:     return ($#CODEs,$CODEs[-1]);
                   7213: }
                   7214: 
1.423     albertel 7215: =pod
                   7216: 
                   7217: =item get_codes
                   7218: 
1.424     albertel 7219:    Builds a hash which has keys of all of the valid CODEs from the selected
                   7220:    set of remembered CODEs.
                   7221: 
                   7222:  Arguments:
                   7223:   $old_name - name of the set of remembered CODEs
                   7224:   $cdom     - domain of the course
                   7225:   $cnum     - internal course name
                   7226: 
                   7227:  Returns:
                   7228:   %allcodes - keys are the valid CODEs, values are all 1
                   7229: 
1.423     albertel 7230: =cut
                   7231: 
1.194     albertel 7232: sub get_codes {
1.280     foxr     7233:     my ($old_name, $cdom, $cnum) = @_;
                   7234:     if (!$old_name) {
                   7235: 	$old_name=$env{'form.scantron_CODElist'};
                   7236:     }
                   7237:     if (!$cdom) {
                   7238: 	$cdom =$env{'course.'.$env{'request.course.id'}.'.domain'};
                   7239:     }
                   7240:     if (!$cnum) {
                   7241: 	$cnum =$env{'course.'.$env{'request.course.id'}.'.num'};
                   7242:     }
1.278     albertel 7243:     my %result=&Apache::lonnet::get('CODEs',[$old_name,"type\0$old_name"],
                   7244: 				    $cdom,$cnum);
                   7245:     my %allcodes;
                   7246:     if ($result{"type\0$old_name"} eq 'number') {
                   7247: 	%allcodes=map {($_,1)} split(',',$result{$old_name});
                   7248:     } else {
                   7249: 	%allcodes=map {(&Apache::lonprintout::num_to_letters($_),1)} split(',',$result{$old_name});
                   7250:     }
1.194     albertel 7251:     return %allcodes;
                   7252: }
                   7253: 
1.423     albertel 7254: =pod
                   7255: 
                   7256: =item scantron_validate_CODE
                   7257: 
1.424     albertel 7258:    Validates all scanlines in the selected file to not have any
                   7259:    invalid or underspecified CODEs and that none of the codes are
                   7260:    duplicated if this was requested.
                   7261: 
1.423     albertel 7262: =cut
                   7263: 
1.157     albertel 7264: sub scantron_validate_CODE {
                   7265:     my ($r,$currentphase) = @_;
1.257     albertel 7266:     my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
1.186     albertel 7267:     if ($scantron_config{'CODElocation'} &&
                   7268: 	$scantron_config{'CODEstart'} &&
                   7269: 	$scantron_config{'CODElength'}) {
1.257     albertel 7270: 	if (!defined($env{'form.scantron_CODElist'})) {
1.186     albertel 7271: 	    &FIXME_blow_up()
                   7272: 	}
                   7273:     } else {
                   7274: 	return (0,$currentphase+1);
                   7275:     }
                   7276:     
                   7277:     my %usedCODEs;
                   7278: 
1.194     albertel 7279:     my %allcodes=&get_codes();
1.186     albertel 7280: 
1.582     raeburn  7281:     my $nav_error;
                   7282:     &scantron_get_maxbubble(\$nav_error); # parse needs the lines per response array.
                   7283:     if ($nav_error) {
                   7284:         $r->print(&navmap_errormsg());
                   7285:         return(1,$currentphase);
                   7286:     }
1.447     foxr     7287: 
1.186     albertel 7288:     my ($scanlines,$scan_data)=&scantron_getfile();
                   7289:     for (my $i=0;$i<=$scanlines->{'count'};$i++) {
1.200     albertel 7290: 	my $line=&scantron_get_line($scanlines,$scan_data,$i);
1.186     albertel 7291: 	if ($line=~/^[\s\cz]*$/) { next; }
                   7292: 	my $scan_record=&scantron_parse_scanline($line,$i,\%scantron_config,
                   7293: 						 $scan_data);
                   7294: 	my $CODE=$$scan_record{'scantron.CODE'};
                   7295: 	my $error=0;
1.224     albertel 7296: 	if (!&Apache::lonnet::validCODE($CODE)) {
                   7297: 	    &scantron_get_correction($r,$i,$scan_record,
                   7298: 				     \%scantron_config,
                   7299: 				     $line,'incorrectCODE',\%allcodes);
                   7300: 	    return(1,$currentphase);
                   7301: 	}
1.221     albertel 7302: 	if (%allcodes && !exists($allcodes{$CODE}) 
                   7303: 	    && !$$scan_record{'scantron.useCODE'}) {
1.186     albertel 7304: 	    &scantron_get_correction($r,$i,$scan_record,
                   7305: 				     \%scantron_config,
1.194     albertel 7306: 				     $line,'incorrectCODE',\%allcodes);
                   7307: 	    return(1,$currentphase);
1.186     albertel 7308: 	}
1.214     albertel 7309: 	if (exists($usedCODEs{$CODE}) 
1.257     albertel 7310: 	    && $env{'form.scantron_CODEunique'} eq 'yes'
1.192     albertel 7311: 	    && !$$scan_record{'scantron.CODE_ignore_dup'}) {
1.186     albertel 7312: 	    &scantron_get_correction($r,$i,$scan_record,
                   7313: 				     \%scantron_config,
1.194     albertel 7314: 				     $line,'duplicateCODE',$usedCODEs{$CODE});
                   7315: 	    return(1,$currentphase);
1.186     albertel 7316: 	}
1.524     raeburn  7317: 	push(@{$usedCODEs{$CODE}},$$scan_record{'scantron.PaperID'});
1.186     albertel 7318:     }
1.157     albertel 7319:     return (0,$currentphase+1);
                   7320: }
                   7321: 
1.423     albertel 7322: =pod
                   7323: 
                   7324: =item scantron_validate_doublebubble
                   7325: 
1.424     albertel 7326:    Validates all scanlines in the selected file to not have any
                   7327:    bubble lines with multiple bubbles marked.
                   7328: 
1.423     albertel 7329: =cut
                   7330: 
1.157     albertel 7331: sub scantron_validate_doublebubble {
                   7332:     my ($r,$currentphase) = @_;
                   7333:     #get student info
                   7334:     my $classlist=&Apache::loncoursedata::get_classlist();
                   7335:     my %idmap=&username_to_idmap($classlist);
                   7336: 
                   7337:     #get scantron line setup
1.257     albertel 7338:     my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
1.157     albertel 7339:     my ($scanlines,$scan_data)=&scantron_getfile();
1.583     raeburn  7340:     my $nav_error;
                   7341:     &scantron_get_maxbubble(\$nav_error); # parse needs the bubble line array.
                   7342:     if ($nav_error) {
                   7343:         $r->print(&navmap_errormsg());
                   7344:         return(1,$currentphase);
                   7345:     }
1.447     foxr     7346: 
1.157     albertel 7347:     for (my $i=0;$i<=$scanlines->{'count'};$i++) {
1.200     albertel 7348: 	my $line=&scantron_get_line($scanlines,$scan_data,$i);
1.157     albertel 7349: 	if ($line=~/^[\s\cz]*$/) { next; }
                   7350: 	my $scan_record=&scantron_parse_scanline($line,$i,\%scantron_config,
                   7351: 						 $scan_data);
                   7352: 	if (!defined($$scan_record{'scantron.doubleerror'})) { next; }
                   7353: 	&scantron_get_correction($r,$i,$scan_record,\%scantron_config,$line,
                   7354: 				 'doublebubble',
                   7355: 				 $$scan_record{'scantron.doubleerror'});
                   7356:     	return (1,$currentphase);
                   7357:     }
                   7358:     return (0,$currentphase+1);
                   7359: }
                   7360: 
1.423     albertel 7361: 
1.503     raeburn  7362: sub scantron_get_maxbubble {
1.582     raeburn  7363:     my ($nav_error) = @_;
1.257     albertel 7364:     if (defined($env{'form.scantron_maxbubble'}) &&
                   7365: 	$env{'form.scantron_maxbubble'}) {
1.447     foxr     7366: 	&restore_bubble_lines();
1.257     albertel 7367: 	return $env{'form.scantron_maxbubble'};
1.191     albertel 7368:     }
1.330     albertel 7369: 
1.447     foxr     7370:     my (undef, undef, $sequence) =
1.257     albertel 7371: 	&Apache::lonnet::decode_symb($env{'form.selectpage'});
1.330     albertel 7372: 
1.447     foxr     7373:     my $navmap=Apache::lonnavmaps::navmap->new();
1.582     raeburn  7374:     unless (ref($navmap)) {
                   7375:         if (ref($nav_error)) {
                   7376:             $$nav_error = 1;
                   7377:         }
1.591     raeburn  7378:         return;
1.582     raeburn  7379:     }
1.191     albertel 7380:     my $map=$navmap->getResourceByUrl($sequence);
                   7381:     my @resources=$navmap->retrieveResources($map,\&scantron_filter,1,0);
1.330     albertel 7382: 
                   7383:     &Apache::lonxml::clear_problem_counter();
                   7384: 
1.557     raeburn  7385:     my $uname       = $env{'user.name'};
                   7386:     my $udom        = $env{'user.domain'};
1.435     foxr     7387:     my $cid         = $env{'request.course.id'};
                   7388:     my $total_lines = 0;
                   7389:     %bubble_lines_per_response = ();
1.447     foxr     7390:     %first_bubble_line         = ();
1.503     raeburn  7391:     %subdivided_bubble_lines   = ();
                   7392:     %responsetype_per_response = ();
1.554     raeburn  7393: 
1.447     foxr     7394:     my $response_number = 0;
                   7395:     my $bubble_line     = 0;
1.191     albertel 7396:     foreach my $resource (@resources) {
1.542     raeburn  7397:         my ($analysis,$parts) = &scantron_partids_tograde($resource,$cid,$uname,$udom);
                   7398:         if ((ref($analysis) eq 'HASH') && (ref($parts) eq 'ARRAY')) {
                   7399: 	    foreach my $part_id (@{$parts}) {
                   7400:                 my $lines;
                   7401: 
                   7402: 	        # TODO - make this a persistent hash not an array.
                   7403: 
                   7404:                 # optionresponse, matchresponse and rankresponse type items 
                   7405:                 # render as separate sub-questions in exam mode.
                   7406:                 if (($analysis->{$part_id.'.type'} eq 'optionresponse') ||
                   7407:                     ($analysis->{$part_id.'.type'} eq 'matchresponse') ||
                   7408:                     ($analysis->{$part_id.'.type'} eq 'rankresponse')) {
                   7409:                     my ($numbub,$numshown);
                   7410:                     if ($analysis->{$part_id.'.type'} eq 'optionresponse') {
                   7411:                         if (ref($analysis->{$part_id.'.options'}) eq 'ARRAY') {
                   7412:                             $numbub = scalar(@{$analysis->{$part_id.'.options'}});
                   7413:                         }
                   7414:                     } elsif ($analysis->{$part_id.'.type'} eq 'matchresponse') {
                   7415:                         if (ref($analysis->{$part_id.'.items'}) eq 'ARRAY') {
                   7416:                             $numbub = scalar(@{$analysis->{$part_id.'.items'}});
                   7417:                         }
                   7418:                     } elsif ($analysis->{$part_id.'.type'} eq 'rankresponse') {
                   7419:                         if (ref($analysis->{$part_id.'.foils'}) eq 'ARRAY') {
                   7420:                             $numbub = scalar(@{$analysis->{$part_id.'.foils'}});
                   7421:                         }
                   7422:                     }
                   7423:                     if (ref($analysis->{$part_id.'.shown'}) eq 'ARRAY') {
                   7424:                         $numshown = scalar(@{$analysis->{$part_id.'.shown'}});
                   7425:                     }
                   7426:                     my $bubbles_per_line = 10;
                   7427:                     my $inner_bubble_lines = int($numbub/$bubbles_per_line);
                   7428:                     if (($numbub % $bubbles_per_line) != 0) {
                   7429:                         $inner_bubble_lines++;
                   7430:                     }
                   7431:                     for (my $i=0; $i<$numshown; $i++) {
                   7432:                         $subdivided_bubble_lines{$response_number} .= 
                   7433:                             $inner_bubble_lines.',';
                   7434:                     }
                   7435:                     $subdivided_bubble_lines{$response_number} =~ s/,$//;
                   7436:                     $lines = $numshown * $inner_bubble_lines;
                   7437:                 } else {
                   7438:                     $lines = $analysis->{"$part_id.bubble_lines"};
                   7439:                 } 
                   7440: 
                   7441:                 $first_bubble_line{$response_number} = $bubble_line;
                   7442: 	        $bubble_lines_per_response{$response_number} = $lines;
                   7443:                 $responsetype_per_response{$response_number} = 
                   7444:                     $analysis->{$part_id.'.type'};
                   7445: 	        $response_number++;
                   7446: 
                   7447: 	        $bubble_line +=  $lines;
                   7448: 	        $total_lines +=  $lines;
                   7449: 	    }
                   7450:         }
                   7451:     }
1.552     raeburn  7452:     &Apache::lonnet::delenv('scantron.');
1.542     raeburn  7453: 
                   7454:     &save_bubble_lines();
                   7455:     $env{'form.scantron_maxbubble'} =
                   7456: 	$total_lines;
                   7457:     return $env{'form.scantron_maxbubble'};
                   7458: }
1.523     raeburn  7459: 
1.157     albertel 7460: sub scantron_validate_missingbubbles {
                   7461:     my ($r,$currentphase) = @_;
                   7462:     #get student info
                   7463:     my $classlist=&Apache::loncoursedata::get_classlist();
                   7464:     my %idmap=&username_to_idmap($classlist);
                   7465: 
                   7466:     #get scantron line setup
1.257     albertel 7467:     my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
1.157     albertel 7468:     my ($scanlines,$scan_data)=&scantron_getfile();
1.582     raeburn  7469:     my $nav_error;
                   7470:     my $max_bubble=&scantron_get_maxbubble(\$nav_error);
                   7471:     if ($nav_error) {
                   7472:         return(1,$currentphase);
                   7473:     }
1.157     albertel 7474:     if (!$max_bubble) { $max_bubble=2**31; }
                   7475:     for (my $i=0;$i<=$scanlines->{'count'};$i++) {
1.200     albertel 7476: 	my $line=&scantron_get_line($scanlines,$scan_data,$i);
1.157     albertel 7477: 	if ($line=~/^[\s\cz]*$/) { next; }
                   7478: 	my $scan_record=&scantron_parse_scanline($line,$i,\%scantron_config,
                   7479: 						 $scan_data);
                   7480: 	if (!defined($$scan_record{'scantron.missingerror'})) { next; }
                   7481: 	my @to_correct;
1.470     foxr     7482: 	
                   7483: 	# Probably here's where the error is...
                   7484: 
1.157     albertel 7485: 	foreach my $missing (@{$$scan_record{'scantron.missingerror'}}) {
1.505     raeburn  7486:             my $lastbubble;
                   7487:             if ($missing =~ /^(\d+)\.(\d+)$/) {
                   7488:                my $question = $1;
                   7489:                my $subquestion = $2;
                   7490:                if (!defined($first_bubble_line{$question -1})) { next; }
                   7491:                my $first = $first_bubble_line{$question-1};
                   7492:                my @subans = split(/,/,$subdivided_bubble_lines{$question-1});
                   7493:                my $subcount = 1;
                   7494:                while ($subcount<$subquestion) {
                   7495:                    $first += $subans[$subcount-1];
                   7496:                    $subcount ++;
                   7497:                }
                   7498:                my $count = $subans[$subquestion-1];
                   7499:                $lastbubble = $first + $count;
                   7500:             } else {
                   7501:                 if (!defined($first_bubble_line{$missing - 1})) { next; }
                   7502:                 $lastbubble = $first_bubble_line{$missing - 1} + $bubble_lines_per_response{$missing - 1};
                   7503:             }
                   7504:             if ($lastbubble > $max_bubble) { next; }
1.157     albertel 7505: 	    push(@to_correct,$missing);
                   7506: 	}
                   7507: 	if (@to_correct) {
                   7508: 	    &scantron_get_correction($r,$i,$scan_record,\%scantron_config,
                   7509: 				     $line,'missingbubble',\@to_correct);
                   7510: 	    return (1,$currentphase);
                   7511: 	}
                   7512: 
                   7513:     }
                   7514:     return (0,$currentphase+1);
                   7515: }
                   7516: 
1.423     albertel 7517: 
1.82      albertel 7518: sub scantron_process_students {
1.608     www      7519:     my ($r,$symb) = @_;
1.513     foxr     7520: 
1.257     albertel 7521:     my (undef,undef,$sequence)=&Apache::lonnet::decode_symb($env{'form.selectpage'});
1.513     foxr     7522:     if (!$symb) {
                   7523: 	return '';
                   7524:     }
1.324     albertel 7525:     my $default_form_data=&defaultFormData($symb);
1.82      albertel 7526: 
1.257     albertel 7527:     my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
1.157     albertel 7528:     my ($scanlines,$scan_data)=&scantron_getfile();
1.82      albertel 7529:     my $classlist=&Apache::loncoursedata::get_classlist();
                   7530:     my %idmap=&username_to_idmap($classlist);
1.132     bowersj2 7531:     my $navmap=Apache::lonnavmaps::navmap->new();
1.582     raeburn  7532:     unless (ref($navmap)) {
                   7533:         $r->print(&navmap_errormsg());
                   7534:         return '';
                   7535:     }  
1.83      albertel 7536:     my $map=$navmap->getResourceByUrl($sequence);
                   7537:     my @resources=$navmap->retrieveResources($map,\&scantron_filter,1,0);
1.557     raeburn  7538:     my (%grader_partids_by_symb,%grader_randomlists_by_symb);
                   7539:     &graders_resources_pass(\@resources,\%grader_partids_by_symb,
                   7540:                             \%grader_randomlists_by_symb);
1.586     raeburn  7541:     my $resource_error;
1.557     raeburn  7542:     foreach my $resource (@resources) {
1.586     raeburn  7543:         my $ressymb;
                   7544:         if (ref($resource)) {
                   7545:             $ressymb = $resource->symb();
                   7546:         } else {
                   7547:             $resource_error = 1;
                   7548:             last;
                   7549:         }
1.557     raeburn  7550:         my ($analysis,$parts) =
                   7551:             &scantron_partids_tograde($resource,$env{'request.course.id'},
                   7552:                                       $env{'user.name'},$env{'user.domain'},1);
                   7553:         $grader_partids_by_symb{$ressymb} = $parts;
                   7554:         if (ref($analysis) eq 'HASH') {
                   7555:             if (ref($analysis->{'parts_withrandomlist'}) eq 'ARRAY') {
                   7556:                 $grader_randomlists_by_symb{$ressymb} = 
                   7557:                     $analysis->{'parts_withrandomlist'};
                   7558:             }
                   7559:         }
                   7560:     }
1.586     raeburn  7561:     if ($resource_error) {
                   7562:         $r->print(&navmap_errormsg());
                   7563:         return '';
                   7564:     }
1.557     raeburn  7565: 
1.554     raeburn  7566:     my ($uname,$udom);
1.82      albertel 7567:     my $result= <<SCANTRONFORM;
1.81      albertel 7568: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="scantronupload">
                   7569:   <input type="hidden" name="command" value="scantron_configphase" />
                   7570:   $default_form_data
                   7571: SCANTRONFORM
1.82      albertel 7572:     $r->print($result);
                   7573: 
                   7574:     my @delayqueue;
1.542     raeburn  7575:     my (%completedstudents,%scandata);
1.140     albertel 7576:     
1.520     www      7577:     my $lock=&Apache::lonnet::set_lock(&mt('Grading bubblesheet exam'));
1.200     albertel 7578:     my $count=&get_todo_count($scanlines,$scan_data);
1.575     www      7579:     my %prog_state=&Apache::lonhtmlcommon::Create_PrgWin($r,'Bubblesheet Status',
                   7580:  				    'Bubblesheet Progress',$count,
1.195     albertel 7581: 				    'inline',undef,'scantronupload');
1.140     albertel 7582:     &Apache::lonhtmlcommon::Update_PrgWin($r,\%prog_state,
                   7583: 					  'Processing first student');
1.542     raeburn  7584:     $r->print('<br />');
1.140     albertel 7585:     my $start=&Time::HiRes::time();
1.158     albertel 7586:     my $i=-1;
1.542     raeburn  7587:     my $started;
1.447     foxr     7588: 
1.582     raeburn  7589:     my $nav_error;
                   7590:     &scantron_get_maxbubble(\$nav_error); # Need the bubble lines array to parse.
                   7591:     if ($nav_error) {
                   7592:         $r->print(&navmap_errormsg());
                   7593:         return '';
                   7594:     }
                   7595: 
1.513     foxr     7596:     # If an ssi failed in scantron_get_maxbubble, put an error message out to
                   7597:     # the user and return.
                   7598: 
                   7599:     if ($ssi_error) {
                   7600: 	$r->print("</form>");
                   7601: 	&ssi_print_error($r);
1.520     www      7602:         &Apache::lonnet::remove_lock($lock);
1.513     foxr     7603: 	return '';		# Dunno why the other returns return '' rather than just returning.
                   7604:     }
1.447     foxr     7605: 
1.542     raeburn  7606:     my %lettdig = &letter_to_digits();
                   7607:     my $numletts = scalar(keys(%lettdig));
                   7608: 
1.157     albertel 7609:     while ($i<$scanlines->{'count'}) {
                   7610:  	($uname,$udom)=('','');
                   7611:  	$i++;
1.200     albertel 7612:  	my $line=&scantron_get_line($scanlines,$scan_data,$i);
1.157     albertel 7613:  	if ($line=~/^[\s\cz]*$/) { next; }
1.200     albertel 7614: 	if ($started) {
                   7615: 	    &Apache::lonhtmlcommon::Increment_PrgWin($r,\%prog_state,
                   7616: 						     'last student');
                   7617: 	}
                   7618: 	$started=1;
1.157     albertel 7619:  	my $scan_record=&scantron_parse_scanline($line,$i,\%scantron_config,
                   7620:  						 $scan_data);
                   7621:  	unless ($uname=&scantron_find_student($scan_record,$scan_data,
                   7622:  					      \%idmap,$i)) {
                   7623:   	    &scantron_add_delay(\@delayqueue,$line,
                   7624:  				'Unable to find a student that matches',1);
                   7625:  	    next;
                   7626:   	}
                   7627:  	if (exists $completedstudents{$uname}) {
                   7628:  	    &scantron_add_delay(\@delayqueue,$line,
                   7629:  				'Student '.$uname.' has multiple sheets',2);
                   7630:  	    next;
                   7631:  	}
                   7632:   	($uname,$udom)=split(/:/,$uname);
1.330     albertel 7633: 
1.586     raeburn  7634:         my (%partids_by_symb,$res_error);
1.554     raeburn  7635:         foreach my $resource (@resources) {
1.586     raeburn  7636:             my $ressymb;
                   7637:             if (ref($resource)) {
                   7638:                 $ressymb = $resource->symb();
                   7639:             } else {
                   7640:                 $res_error = 1;
                   7641:                 last;
                   7642:             }
1.557     raeburn  7643:             if ((exists($grader_randomlists_by_symb{$ressymb})) ||
                   7644:                 (ref($grader_partids_by_symb{$ressymb}) ne 'ARRAY')) {
                   7645:                 my ($analysis,$parts) =
                   7646:                     &scantron_partids_tograde($resource,$env{'request.course.id'},$uname,$udom);
                   7647:                 $partids_by_symb{$ressymb} = $parts;
                   7648:             } else {
                   7649:                 $partids_by_symb{$ressymb} = $grader_partids_by_symb{$ressymb};
                   7650:             }
1.554     raeburn  7651:         }
                   7652: 
1.586     raeburn  7653:         if ($res_error) {
                   7654:             &scantron_add_delay(\@delayqueue,$line,
                   7655:                                 'An error occurred while grading student '.$uname,2);
                   7656:             next;
                   7657:         }
                   7658: 
1.330     albertel 7659: 	&Apache::lonxml::clear_problem_counter();
1.514     raeburn  7660:   	&Apache::lonnet::appenv($scan_record);
1.376     albertel 7661: 
                   7662: 	if (&scantron_clear_skip($scanlines,$scan_data,$i)) {
                   7663: 	    &scantron_putfile($scanlines,$scan_data);
                   7664: 	}
1.161     albertel 7665: 	
1.542     raeburn  7666:         my $scancode;
                   7667:         if ((exists($scan_record->{'scantron.CODE'})) &&
                   7668:             (&Apache::lonnet::validCODE($scan_record->{'scantron.CODE'}))) {
                   7669:             $scancode = $scan_record->{'scantron.CODE'};
                   7670:         } else {
                   7671:             $scancode = '';
                   7672:         }
                   7673: 
                   7674:         if (&grade_student_bubbles($r,$uname,$udom,$scan_record,$scancode,
1.554     raeburn  7675:                                    \@resources,\%partids_by_symb) eq 'ssi_error') {
1.542     raeburn  7676:             $ssi_error = 0; # So end of handler error message does not trigger.
                   7677:             $r->print("</form>");
                   7678:             &ssi_print_error($r);
                   7679:             &Apache::lonnet::remove_lock($lock);
                   7680:             return '';      # Why return ''?  Beats me.
                   7681:         }
1.513     foxr     7682: 
1.140     albertel 7683: 	$completedstudents{$uname}={'line'=>$line};
1.542     raeburn  7684:         if ($env{'form.verifyrecord'}) {
                   7685:             my $lastpos = $env{'form.scantron_maxbubble'}*$scantron_config{'Qlength'};
                   7686:             my $studentdata = substr($line,$scantron_config{'Qstart'}-1,$lastpos);
                   7687:             chomp($studentdata);
                   7688:             $studentdata =~ s/\r$//;
                   7689:             my $studentrecord = '';
                   7690:             my $counter = -1;
                   7691:             foreach my $resource (@resources) {
1.554     raeburn  7692:                 my $ressymb = $resource->symb();
1.542     raeburn  7693:                 ($counter,my $recording) =
                   7694:                     &verify_scantron_grading($resource,$udom,$uname,$env{'request.course.id'},
1.554     raeburn  7695:                                              $counter,$studentdata,$partids_by_symb{$ressymb},
1.542     raeburn  7696:                                              \%scantron_config,\%lettdig,$numletts);
                   7697:                 $studentrecord .= $recording;
                   7698:             }
                   7699:             if ($studentrecord ne $studentdata) {
1.554     raeburn  7700:                 &Apache::lonxml::clear_problem_counter();
                   7701:                 if (&grade_student_bubbles($r,$uname,$udom,$scan_record,$scancode,
                   7702:                                            \@resources,\%partids_by_symb) eq 'ssi_error') {
                   7703:                     $ssi_error = 0; # So end of handler error message does not trigger.
                   7704:                     $r->print("</form>");
                   7705:                     &ssi_print_error($r);
                   7706:                     &Apache::lonnet::remove_lock($lock);
                   7707:                     delete($completedstudents{$uname});
                   7708:                     return '';
                   7709:                 }
1.542     raeburn  7710:                 $counter = -1;
                   7711:                 $studentrecord = '';
                   7712:                 foreach my $resource (@resources) {
1.554     raeburn  7713:                     my $ressymb = $resource->symb();
1.542     raeburn  7714:                     ($counter,my $recording) =
                   7715:                         &verify_scantron_grading($resource,$udom,$uname,$env{'request.course.id'},
1.554     raeburn  7716:                                                  $counter,$studentdata,$partids_by_symb{$ressymb},
1.542     raeburn  7717:                                                  \%scantron_config,\%lettdig,$numletts);
                   7718:                     $studentrecord .= $recording;
                   7719:                 }
                   7720:                 if ($studentrecord ne $studentdata) {
                   7721:                     $r->print('<p><span class="LC_error">');
                   7722:                     if ($scancode eq '') {
                   7723:                         $r->print(&mt('Mismatch grading bubble sheet for user: [_1] with ID: [_2].',
                   7724:                                   $uname.':'.$udom,$scan_record->{'scantron.ID'}));
                   7725:                     } else {
                   7726:                         $r->print(&mt('Mismatch grading bubble sheet for user: [_1] with ID: [_2] and CODE: [_3].',
                   7727:                                   $uname.':'.$udom,$scan_record->{'scantron.ID'},$scancode));
                   7728:                     }
                   7729:                     $r->print('</span><br />'.&Apache::loncommon::start_data_table()."\n".
                   7730:                               &Apache::loncommon::start_data_table_header_row()."\n".
                   7731:                               '<th>'.&mt('Source').'</th><th>'.&mt('Bubbled responses').'</th>'.
                   7732:                               &Apache::loncommon::end_data_table_header_row()."\n".
                   7733:                               &Apache::loncommon::start_data_table_row().
                   7734:                               '<td>'.&mt('Bubble Sheet').'</td>'.
                   7735:                               '<td><span class="LC_nobreak">'.$studentdata.'</span></td>'.
                   7736:                               &Apache::loncommon::end_data_table_row().
                   7737:                               &Apache::loncommon::start_data_table_row().
                   7738:                               '<td>Stored submissions</td>'.
                   7739:                               '<td><span class="LC_nobreak">'.$studentrecord.'</span></td>'."\n".
                   7740:                               &Apache::loncommon::end_data_table_row().
                   7741:                               &Apache::loncommon::end_data_table().'</p>');
                   7742:                 } else {
                   7743:                     $r->print('<br /><span class="LC_warning">'.
                   7744:                              &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 />'.
                   7745:                              &mt("As a consequence, this user's submission history records two tries.").
                   7746:                                  '</span><br />');
                   7747:                 }
                   7748:             }
                   7749:         }
1.543     raeburn  7750:         if (&Apache::loncommon::connection_aborted($r)) { last; }
1.140     albertel 7751:     } continue {
1.330     albertel 7752: 	&Apache::lonxml::clear_problem_counter();
1.552     raeburn  7753: 	&Apache::lonnet::delenv('scantron.');
1.82      albertel 7754:     }
1.140     albertel 7755:     &Apache::lonhtmlcommon::Close_PrgWin($r,\%prog_state);
1.520     www      7756:     &Apache::lonnet::remove_lock($lock);
1.172     albertel 7757: #    my $lasttime = &Time::HiRes::time()-$start;
                   7758: #    $r->print("<p>took $lasttime</p>");
1.140     albertel 7759: 
1.200     albertel 7760:     $r->print("</form>");
1.157     albertel 7761:     return '';
1.75      albertel 7762: }
1.157     albertel 7763: 
1.557     raeburn  7764: sub graders_resources_pass {
                   7765:     my ($resources,$grader_partids_by_symb,$grader_randomlists_by_symb) = @_;
                   7766:     if ((ref($resources) eq 'ARRAY') && (ref($grader_partids_by_symb)) && 
                   7767:         (ref($grader_randomlists_by_symb) eq 'HASH')) {
                   7768:         foreach my $resource (@{$resources}) {
                   7769:             my $ressymb = $resource->symb();
                   7770:             my ($analysis,$parts) =
                   7771:                 &scantron_partids_tograde($resource,$env{'request.course.id'},
                   7772:                                           $env{'user.name'},$env{'user.domain'},1);
                   7773:             $grader_partids_by_symb->{$ressymb} = $parts;
                   7774:             if (ref($analysis) eq 'HASH') {
                   7775:                 if (ref($analysis->{'parts_withrandomlist'}) eq 'ARRAY') {
                   7776:                     $grader_randomlists_by_symb->{$ressymb} =
                   7777:                         $analysis->{'parts_withrandomlist'};
                   7778:                 }
                   7779:             }
                   7780:         }
                   7781:     }
                   7782:     return;
                   7783: }
                   7784: 
1.542     raeburn  7785: sub grade_student_bubbles {
1.554     raeburn  7786:     my ($r,$uname,$udom,$scan_record,$scancode,$resources,$parts) = @_;
                   7787:     if (ref($resources) eq 'ARRAY') {
                   7788:         my $count = 0;
                   7789:         foreach my $resource (@{$resources}) {
                   7790:             my $ressymb = $resource->symb();
                   7791:             my %form = ('submitted'      => 'scantron',
                   7792:                         'grade_target'   => 'grade',
                   7793:                         'grade_username' => $uname,
                   7794:                         'grade_domain'   => $udom,
                   7795:                         'grade_courseid' => $env{'request.course.id'},
                   7796:                         'grade_symb'     => $ressymb,
                   7797:                         'CODE'           => $scancode
                   7798:                        );
                   7799:             if (ref($parts) eq 'HASH') {
                   7800:                 if (ref($parts->{$ressymb}) eq 'ARRAY') {
                   7801:                     foreach my $part (@{$parts->{$ressymb}}) {
                   7802:                         $form{'scantron_questnum_start.'.$part} =
                   7803:                             1+$env{'form.scantron.first_bubble_line.'.$count};
                   7804:                         $count++;
                   7805:                     }
                   7806:                 }
                   7807:             }
                   7808:             my $result=&ssi_with_retries($resource->src(),$ssi_retries,%form);
                   7809:             return 'ssi_error' if ($ssi_error);
                   7810:             last if (&Apache::loncommon::connection_aborted($r));
                   7811:         }
1.542     raeburn  7812:     }
                   7813:     return;
                   7814: }
                   7815: 
1.157     albertel 7816: sub scantron_upload_scantron_data {
1.608     www      7817:     my ($r,$symb)=@_;
1.565     raeburn  7818:     my $dom = $env{'request.role.domain'};
                   7819:     my $domdesc = &Apache::lonnet::domain($dom,'description');
                   7820:     $r->print(&Apache::loncommon::coursebrowser_javascript($dom));
1.157     albertel 7821:     my $select_link=&Apache::loncommon::selectcourse_link('rules','courseid',
1.181     albertel 7822: 							  'domainid',
1.565     raeburn  7823: 							  'coursename',$dom);
                   7824:     my $syllabuslink = '<a href="javascript:ToSyllabus();">'.&mt('Syllabus').'</a>'.
                   7825:                        ('&nbsp'x2).&mt('(shows course personnel)'); 
1.608     www      7826:     my $default_form_data=&defaultFormData($symb);
1.579     raeburn  7827:     my $nofile_alert = &mt('Please use the browse button to select a file from your local directory.');
                   7828:     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 7829:     $r->print(&Apache::lonhtmlcommon::scripttag('
1.157     albertel 7830:     function checkUpload(formname) {
                   7831: 	if (formname.upfile.value == "") {
1.579     raeburn  7832: 	    alert("'.$nofile_alert.'");
1.157     albertel 7833: 	    return false;
                   7834: 	}
1.565     raeburn  7835:         if (formname.courseid.value == "") {
1.579     raeburn  7836:             alert("'.$nocourseid_alert.'");
1.565     raeburn  7837:             return false;
                   7838:         }
1.157     albertel 7839: 	formname.submit();
                   7840:     }
1.565     raeburn  7841: 
                   7842:     function ToSyllabus() {
                   7843:         var cdom = '."'$dom'".';
                   7844:         var cnum = document.rules.courseid.value;
                   7845:         if (cdom == "" || cdom == null) {
                   7846:             return;
                   7847:         }
                   7848:         if (cnum == "" || cnum == null) {
                   7849:            return;
                   7850:         }
                   7851:         syllwin=window.open("/public/"+cdom+"/"+cnum+"/syllabus","LONCAPASyllabus",
                   7852:                             "height=350,width=350,scrollbars=yes,menubar=no");
                   7853:         return;
                   7854:     }
                   7855: 
1.597     wenzelju 7856: '));
                   7857:     $r->print('
1.566     raeburn  7858: <h3>'.&mt('Send scanned bubblesheet data to a course').'</h3>
                   7859: 
1.492     albertel 7860: <form enctype="multipart/form-data" action="/adm/grades" name="rules" method="post">
1.565     raeburn  7861: '.$default_form_data.
                   7862:   &Apache::lonhtmlcommon::start_pick_box().
                   7863:   &Apache::lonhtmlcommon::row_title(&mt('Course ID')).
                   7864:   '<input name="courseid" type="text" size="30" />'.$select_link.
                   7865:   &Apache::lonhtmlcommon::row_closure().
                   7866:   &Apache::lonhtmlcommon::row_title(&mt('Course Name')).
                   7867:   '<input name="coursename" type="text" size="30" />'.$syllabuslink.
                   7868:   &Apache::lonhtmlcommon::row_closure().
                   7869:   &Apache::lonhtmlcommon::row_title(&mt('Domain')).
                   7870:   '<input name="domainid" type="hidden" />'.$domdesc.
                   7871:   &Apache::lonhtmlcommon::row_closure().
                   7872:   &Apache::lonhtmlcommon::row_title(&mt('File to upload')).
                   7873:   '<input type="file" name="upfile" size="50" />'.
                   7874:   &Apache::lonhtmlcommon::row_closure(1).
                   7875:   &Apache::lonhtmlcommon::end_pick_box().'<br />
                   7876: 
1.492     albertel 7877: <input name="command" value="scantronupload_save" type="hidden" />
1.589     bisitz   7878: <input type="button" onclick="javascript:checkUpload(this.form);" value="'.&mt('Upload Bubblesheet Data').'" />
1.157     albertel 7879: </form>
1.492     albertel 7880: ');
1.157     albertel 7881:     return '';
                   7882: }
                   7883: 
1.423     albertel 7884: 
1.157     albertel 7885: sub scantron_upload_scantron_data_save {
1.608     www      7886:     my($r,$symb)=@_;
1.182     albertel 7887:     my $doanotherupload=
                   7888: 	'<br /><form action="/adm/grades" method="post">'."\n".
                   7889: 	'<input type="hidden" name="command" value="scantronupload" />'."\n".
1.492     albertel 7890: 	'<input type="submit" name="submit" value="'.&mt('Do Another Upload').'" />'."\n".
1.182     albertel 7891: 	'</form>'."\n";
1.257     albertel 7892:     if (!&Apache::lonnet::allowed('usc',$env{'form.domainid'}) &&
1.162     albertel 7893: 	!&Apache::lonnet::allowed('usc',
1.257     albertel 7894: 			    $env{'form.domainid'}.'_'.$env{'form.courseid'})) {
1.575     www      7895: 	$r->print(&mt("You are not allowed to upload bubblesheet data to the requested course.")."<br />");
1.614     www      7896: 	unless ($symb) {
1.182     albertel 7897: 	    $r->print($doanotherupload);
                   7898: 	}
1.162     albertel 7899: 	return '';
                   7900:     }
1.257     albertel 7901:     my %coursedata=&Apache::lonnet::coursedescription($env{'form.domainid'}.'_'.$env{'form.courseid'});
1.568     raeburn  7902:     my $uploadedfile;
1.567     raeburn  7903:     $r->print('<h3>'.&mt("Uploading file to [_1]",$coursedata{'description'}).'</h3>');
1.257     albertel 7904:     if (length($env{'form.upfile'}) < 2) {
1.568     raeburn  7905:         $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 7906:     } else {
1.568     raeburn  7907:         my $result = 
                   7908:             &Apache::lonnet::userfileupload('upfile','','scantron','','','',
                   7909:                                             $env{'form.courseid'},$env{'form.domainid'});
                   7910: 	if ($result =~ m{^/uploaded/}) {
1.567     raeburn  7911: 	    $r->print(&mt('[_1]Success:[_2] Successfully uploaded [_3] bytes of data into location: [_4]',
                   7912:                           '<span class="LC_success">','</span>',(length($env{'form.upfile'})-1),
                   7913: 			  '<span class="LC_filename">'.$result.'</span>'));
1.568     raeburn  7914:             ($uploadedfile) = ($result =~ m{/([^/]+)$});
1.567     raeburn  7915:             $r->print(&validate_uploaded_scantron_file($env{'form.domainid'},
1.568     raeburn  7916:                                                        $env{'form.courseid'},$uploadedfile));
1.210     albertel 7917: 	} else {
1.567     raeburn  7918: 	    $r->print(&mt('[_1]Error:[_2] An error ([_3]) occurred when attempting to upload the file, [_4]',
                   7919:                           '<span class="LC_error">','</span>',$result,
1.568     raeburn  7920: 			  '<span class="LC_filename">'.&HTML::Entities::encode($env{'form.upfile.filename'},'<>&"').'</span>'));
1.183     albertel 7921: 	}
                   7922:     }
1.174     albertel 7923:     if ($symb) {
1.612     www      7924: 	$r->print(&scantron_selectphase($r,$uploadedfile,$symb));
1.174     albertel 7925:     } else {
1.182     albertel 7926: 	$r->print($doanotherupload);
1.174     albertel 7927:     }
1.157     albertel 7928:     return '';
                   7929: }
                   7930: 
1.567     raeburn  7931: sub validate_uploaded_scantron_file {
                   7932:     my ($cdom,$cname,$fname) = @_;
                   7933:     my $scanlines=&Apache::lonnet::getfile('/uploaded/'.$cdom.'/'.$cname.'/'.$fname);
                   7934:     my @lines;
                   7935:     if ($scanlines ne '-1') {
                   7936:         @lines=split("\n",$scanlines,-1);
                   7937:     }
                   7938:     my $output;
                   7939:     if (@lines) {
                   7940:         my (%counts,$max_match_format);
                   7941:         my ($max_match_count,$max_match_pct) = (0,0);
                   7942:         my $classlist = &Apache::loncoursedata::get_classlist($cdom,$cname);
                   7943:         my %idmap = &username_to_idmap($classlist);
                   7944:         foreach my $key (keys(%idmap)) {
                   7945:             my $lckey = lc($key);
                   7946:             $idmap{$lckey} = $idmap{$key};
                   7947:         }
                   7948:         my %unique_formats;
                   7949:         my @formatlines = &get_scantronformat_file();
                   7950:         foreach my $line (@formatlines) {
                   7951:             chomp($line);
                   7952:             my @config = split(/:/,$line);
                   7953:             my $idstart = $config[5];
                   7954:             my $idlength = $config[6];
                   7955:             if (($idstart ne '') && ($idlength > 0)) {
                   7956:                 if (ref($unique_formats{$idstart.':'.$idlength}) eq 'ARRAY') {
                   7957:                     push(@{$unique_formats{$idstart.':'.$idlength}},$config[0].':'.$config[1]); 
                   7958:                 } else {
                   7959:                     $unique_formats{$idstart.':'.$idlength} = [$config[0].':'.$config[1]];
                   7960:                 }
                   7961:             }
                   7962:         }
                   7963:         foreach my $key (keys(%unique_formats)) {
                   7964:             my ($idstart,$idlength) = split(':',$key);
                   7965:             %{$counts{$key}} = (
                   7966:                                'found'   => 0,
                   7967:                                'total'   => 0,
                   7968:                               );
                   7969:             foreach my $line (@lines) {
                   7970:                 next if ($line =~ /^#/);
                   7971:                 next if ($line =~ /^[\s\cz]*$/);
                   7972:                 my $id = substr($line,$idstart-1,$idlength);
                   7973:                 $id = lc($id);
                   7974:                 if (exists($idmap{$id})) {
                   7975:                     $counts{$key}{'found'} ++;
                   7976:                 }
                   7977:                 $counts{$key}{'total'} ++;
                   7978:             }
                   7979:             if ($counts{$key}{'total'}) {
                   7980:                 my $percent_match = (100*$counts{$key}{'found'})/($counts{$key}{'total'});
                   7981:                 if (($max_match_format eq '') || ($percent_match > $max_match_pct)) {
                   7982:                     $max_match_pct = $percent_match;
                   7983:                     $max_match_format = $key;
                   7984:                     $max_match_count = $counts{$key}{'total'};
                   7985:                 }
                   7986:             }
                   7987:         }
                   7988:         if (ref($unique_formats{$max_match_format}) eq 'ARRAY') {
                   7989:             my $format_descs;
                   7990:             my $numwithformat = @{$unique_formats{$max_match_format}};
                   7991:             for (my $i=0; $i<$numwithformat; $i++) {
                   7992:                 my ($name,$desc) = split(':',$unique_formats{$max_match_format}[$i]);
                   7993:                 if ($i<$numwithformat-2) {
                   7994:                     $format_descs .= '"<i>'.$desc.'</i>", ';
                   7995:                 } elsif ($i==$numwithformat-2) {
                   7996:                     $format_descs .= '"<i>'.$desc.'</i>" '.&mt('and').' ';
                   7997:                 } elsif ($i==$numwithformat-1) {
                   7998:                     $format_descs .= '"<i>'.$desc.'</i>"';
                   7999:                 }
                   8000:             }
                   8001:             my $showpct = sprintf("%.0f",$max_match_pct).'%';
                   8002:             $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).
                   8003:                        '<br />'.&mt('A low percentage of matches results from one of the following:').'<ul>'.
                   8004:                        '<li>'.&mt('The file was uploaded to the wrong course').'</li>'.
                   8005:                        '<li>'.&mt('The data are not in the format expected for the domain: [_1]',
                   8006:                                   '<i>'.$cdom.'</i>').'</li>'.
                   8007:                        '<li>'.&mt('Students did not bubble their IDs, or mis-bubbled them').'</li>'.
                   8008:                        '<li>'.&mt('The course roster is not up to date').'</li>'.
                   8009:                        '</ul>';
                   8010:         }
                   8011:     } else {
                   8012:         $output = '<span class="LC_warning">'.&mt('Uploaded file contained no data').'</span>';
                   8013:     }
                   8014:     return $output;
                   8015: }
                   8016: 
1.202     albertel 8017: sub valid_file {
                   8018:     my ($requested_file)=@_;
                   8019:     foreach my $filename (sort(&scantron_filenames())) {
                   8020: 	if ($requested_file eq $filename) { return 1; }
                   8021:     }
                   8022:     return 0;
                   8023: }
                   8024: 
                   8025: sub scantron_download_scantron_data {
1.608     www      8026:     my ($r,$symb)=@_;
                   8027:     my $default_form_data=&defaultFormData($symb);
1.257     albertel 8028:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   8029:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
                   8030:     my $file=$env{'form.scantron_selectfile'};
1.202     albertel 8031:     if (! &valid_file($file)) {
1.492     albertel 8032: 	$r->print('
1.202     albertel 8033: 	<p>
1.492     albertel 8034: 	    '.&mt('The requested file name was invalid.').'
1.202     albertel 8035:         </p>
1.492     albertel 8036: ');
1.202     albertel 8037: 	return;
                   8038:     }
                   8039:     my $orig='/uploaded/'.$cdom.'/'.$cname.'/scantron_orig_'.$file;
                   8040:     my $corrected='/uploaded/'.$cdom.'/'.$cname.'/scantron_corrected_'.$file;
                   8041:     my $skipped='/uploaded/'.$cdom.'/'.$cname.'/scantron_skipped_'.$file;
                   8042:     &Apache::lonnet::allowuploaded('/adm/grades',$orig);
                   8043:     &Apache::lonnet::allowuploaded('/adm/grades',$corrected);
                   8044:     &Apache::lonnet::allowuploaded('/adm/grades',$skipped);
1.492     albertel 8045:     $r->print('
1.202     albertel 8046:     <p>
1.492     albertel 8047: 	'.&mt('[_1]Original[_2] file as uploaded by the scantron office.',
                   8048: 	      '<a href="'.$orig.'">','</a>').'
1.202     albertel 8049:     </p>
                   8050:     <p>
1.492     albertel 8051: 	'.&mt('[_1]Corrections[_2], a file of corrected records that were used in grading.',
                   8052: 	      '<a href="'.$corrected.'">','</a>').'
1.202     albertel 8053:     </p>
                   8054:     <p>
1.492     albertel 8055: 	'.&mt('[_1]Skipped[_2], a file of records that were skipped.',
                   8056: 	      '<a href="'.$skipped.'">','</a>').'
1.202     albertel 8057:     </p>
1.492     albertel 8058: ');
1.202     albertel 8059:     return '';
                   8060: }
1.157     albertel 8061: 
1.523     raeburn  8062: sub checkscantron_results {
1.608     www      8063:     my ($r,$symb) = @_;
1.523     raeburn  8064:     if (!$symb) {return '';}
                   8065:     my $cid = $env{'request.course.id'};
1.542     raeburn  8066:     my %lettdig = &letter_to_digits();
1.523     raeburn  8067:     my $numletts = scalar(keys(%lettdig));
                   8068:     my $cnum = $env{'course.'.$cid.'.num'};
                   8069:     my $cdom = $env{'course.'.$cid.'.domain'};
                   8070:     my (undef, undef, $sequence) = &Apache::lonnet::decode_symb($env{'form.selectpage'});
                   8071:     my %record;
                   8072:     my %scantron_config =
                   8073:         &Apache::grades::get_scantron_config($env{'form.scantron_format'});
                   8074:     my ($scanlines,$scan_data)=&Apache::grades::scantron_getfile();
                   8075:     my $classlist=&Apache::loncoursedata::get_classlist();
                   8076:     my %idmap=&Apache::grades::username_to_idmap($classlist);
                   8077:     my $navmap=Apache::lonnavmaps::navmap->new();
1.582     raeburn  8078:     unless (ref($navmap)) {
                   8079:         $r->print(&navmap_errormsg());
                   8080:         return '';
                   8081:     }
1.523     raeburn  8082:     my $map=$navmap->getResourceByUrl($sequence);
1.557     raeburn  8083:     my @resources=$navmap->retrieveResources($map,\&scantron_filter,1,0);
                   8084:     my (%grader_partids_by_symb,%grader_randomlists_by_symb);
                   8085:     &graders_resources_pass(\@resources,\%grader_partids_by_symb,                             \%grader_randomlists_by_symb);
                   8086: 
1.554     raeburn  8087:     my ($uname,$udom);
1.523     raeburn  8088:     my (%scandata,%lastname,%bylast);
                   8089:     $r->print('
                   8090: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="checkscantron">'."\n");
                   8091: 
                   8092:     my @delayqueue;
                   8093:     my %completedstudents;
                   8094: 
                   8095:     my $count=&Apache::grades::get_todo_count($scanlines,$scan_data);
1.581     www      8096:     my %prog_state=&Apache::lonhtmlcommon::Create_PrgWin($r,'Bubblesheet/Submissions Comparison Status',
                   8097:                                     'Progress of Bubblesheet Data/Submission Records Comparison',$count,
1.523     raeburn  8098:                                     'inline',undef,'checkscantron');
1.546     raeburn  8099:     my ($username,$domain,$started);
1.582     raeburn  8100:     my $nav_error;
                   8101:     &scantron_get_maxbubble(\$nav_error); # Need the bubble lines array to parse.
                   8102:     if ($nav_error) {
                   8103:         $r->print(&navmap_errormsg());
                   8104:         return '';
                   8105:     }
1.523     raeburn  8106: 
                   8107:     &Apache::lonhtmlcommon::Update_PrgWin($r,\%prog_state,
                   8108:                                           'Processing first student');
                   8109:     my $start=&Time::HiRes::time();
                   8110:     my $i=-1;
                   8111: 
                   8112:     while ($i<$scanlines->{'count'}) {
                   8113:         ($username,$domain,$uname)=('','','');
                   8114:         $i++;
                   8115:         my $line=&Apache::grades::scantron_get_line($scanlines,$scan_data,$i);
                   8116:         if ($line=~/^[\s\cz]*$/) { next; }
                   8117:         if ($started) {
                   8118:             &Apache::lonhtmlcommon::Increment_PrgWin($r,\%prog_state,
                   8119:                                                      'last student');
                   8120:         }
                   8121:         $started=1;
                   8122:         my $scan_record=
                   8123:             &Apache::grades::scantron_parse_scanline($line,$i,\%scantron_config,
                   8124:                                                      $scan_data);
                   8125:         unless ($uname=&Apache::grades::scantron_find_student($scan_record,$scan_data,
                   8126:                                                               \%idmap,$i)) {
                   8127:             &Apache::grades::scantron_add_delay(\@delayqueue,$line,
                   8128:                                 'Unable to find a student that matches',1);
                   8129:             next;
                   8130:         }
                   8131:         if (exists $completedstudents{$uname}) {
                   8132:             &Apache::grades::scantron_add_delay(\@delayqueue,$line,
                   8133:                                 'Student '.$uname.' has multiple sheets',2);
                   8134:             next;
                   8135:         }
                   8136:         my $pid = $scan_record->{'scantron.ID'};
                   8137:         $lastname{$pid} = $scan_record->{'scantron.LastName'};
                   8138:         push(@{$bylast{$lastname{$pid}}},$pid);
                   8139:         my $lastpos = $env{'form.scantron_maxbubble'}*$scantron_config{'Qlength'};
                   8140:         $scandata{$pid} = substr($line,$scantron_config{'Qstart'}-1,$lastpos);
                   8141:         chomp($scandata{$pid});
                   8142:         $scandata{$pid} =~ s/\r$//;
                   8143:         ($username,$domain)=split(/:/,$uname);
                   8144:         my $counter = -1;
                   8145:         foreach my $resource (@resources) {
1.557     raeburn  8146:             my $parts;
1.554     raeburn  8147:             my $ressymb = $resource->symb();
1.557     raeburn  8148:             if ((exists($grader_randomlists_by_symb{$ressymb})) ||
                   8149:                 (ref($grader_partids_by_symb{$ressymb}) ne 'ARRAY')) {
                   8150:                 (my $analysis,$parts) =
                   8151:                     &scantron_partids_tograde($resource,$env{'request.course.id'},$username,$domain);
                   8152:             } else {
                   8153:                 $parts = $grader_partids_by_symb{$ressymb};
                   8154:             }
1.542     raeburn  8155:             ($counter,my $recording) =
                   8156:                 &verify_scantron_grading($resource,$domain,$username,$cid,$counter,
1.554     raeburn  8157:                                          $scandata{$pid},$parts,
1.542     raeburn  8158:                                          \%scantron_config,\%lettdig,$numletts);
                   8159:             $record{$pid} .= $recording;
1.523     raeburn  8160:         }
                   8161:     }
                   8162:     &Apache::lonhtmlcommon::Close_PrgWin($r,\%prog_state);
                   8163:     $r->print('<br />');
                   8164:     my ($okstudents,$badstudents,$numstudents,$passed,$failed);
                   8165:     $passed = 0;
                   8166:     $failed = 0;
                   8167:     $numstudents = 0;
                   8168:     foreach my $last (sort(keys(%bylast))) {
                   8169:         if (ref($bylast{$last}) eq 'ARRAY') {
                   8170:             foreach my $pid (sort(@{$bylast{$last}})) {
                   8171:                 my $showscandata = $scandata{$pid};
                   8172:                 my $showrecord = $record{$pid};
                   8173:                 $showscandata =~ s/\s/&nbsp;/g;
                   8174:                 $showrecord =~ s/\s/&nbsp;/g;
                   8175:                 if ($scandata{$pid} eq $record{$pid}) {
                   8176:                     my $css_class = ($passed % 2)?'LC_odd_row':'LC_even_row';
                   8177:                     $okstudents .= '<tr class="'.$css_class.'">'.
1.581     www      8178: '<td>'.&mt('Bubblesheet').'</td><td>'.$showscandata.'</td><td rowspan="2">'.$last.'</td><td rowspan="2">'.$pid.'</td>'."\n".
1.523     raeburn  8179: '</tr>'."\n".
                   8180: '<tr class="'.$css_class.'">'."\n".
                   8181: '<td>Submissions</td><td>'.$showrecord.'</td></tr>'."\n";
                   8182:                     $passed ++;
                   8183:                 } else {
                   8184:                     my $css_class = ($failed % 2)?'LC_odd_row':'LC_even_row';
1.581     www      8185:                     $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  8186: '</tr>'."\n".
                   8187: '<tr class="'.$css_class.'">'."\n".
                   8188: '<td>Submissions</td><td><span class="LC_nobreak">'.$record{$pid}.'</span></td>'."\n".
                   8189: '</tr>'."\n";
                   8190:                     $failed ++;
                   8191:                 }
                   8192:                 $numstudents ++;
                   8193:             }
                   8194:         }
                   8195:     }
1.572     www      8196:     $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  8197:     $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>');
                   8198:     if ($passed) {
1.572     www      8199:         $r->print(&mt('Students with exact correspondence between bubblesheet data and submissions are as follows:').'<br /><br />');
1.523     raeburn  8200:         $r->print(&Apache::loncommon::start_data_table()."\n".
                   8201:                  &Apache::loncommon::start_data_table_header_row()."\n".
                   8202:                  '<th>'.&mt('Source').'</th><th>'.&mt('Bubble records').'</th><th>'.&mt('Name').'</th><th>'.&mt('ID').'</th>'.
                   8203:                  &Apache::loncommon::end_data_table_header_row()."\n".
                   8204:                  $okstudents."\n".
                   8205:                  &Apache::loncommon::end_data_table().'<br />');
                   8206:     }
                   8207:     if ($failed) {
1.572     www      8208:         $r->print(&mt('Students with differences between bubblesheet data and submissions are as follows:').'<br /><br />');
1.523     raeburn  8209:         $r->print(&Apache::loncommon::start_data_table()."\n".
                   8210:                  &Apache::loncommon::start_data_table_header_row()."\n".
                   8211:                  '<th>'.&mt('Source').'</th><th>'.&mt('Bubble records').'</th><th>'.&mt('Name').'</th><th>'.&mt('ID').'</th>'.
                   8212:                  &Apache::loncommon::end_data_table_header_row()."\n".
                   8213:                  $badstudents."\n".
                   8214:                  &Apache::loncommon::end_data_table()).'<br />'.
1.572     www      8215:                  &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  8216:     }
1.614     www      8217:     $r->print('</form><br />');
1.523     raeburn  8218:     return;
                   8219: }
                   8220: 
1.542     raeburn  8221: sub verify_scantron_grading {
1.554     raeburn  8222:     my ($resource,$domain,$username,$cid,$counter,$scandata,$partids,
1.542     raeburn  8223:         $scantron_config,$lettdig,$numletts) = @_;
                   8224:     my ($record,%expected,%startpos);
                   8225:     return ($counter,$record) if (!ref($resource));
                   8226:     return ($counter,$record) if (!$resource->is_problem());
                   8227:     my $symb = $resource->symb();
1.554     raeburn  8228:     return ($counter,$record) if (ref($partids) ne 'ARRAY');
                   8229:     foreach my $part_id (@{$partids}) {
1.542     raeburn  8230:         $counter ++;
                   8231:         $expected{$part_id} = 0;
                   8232:         if ($env{"form.scantron.sub_bubblelines.$counter"}) {
                   8233:             my @sub_lines = split(/,/,$env{"form.scantron.sub_bubblelines.$counter"});
                   8234:             foreach my $item (@sub_lines) {
                   8235:                 $expected{$part_id} += $item;
                   8236:             }
                   8237:         } else {
                   8238:             $expected{$part_id} = $env{"form.scantron.bubblelines.$counter"};
                   8239:         }
                   8240:         $startpos{$part_id} = $env{"form.scantron.first_bubble_line.$counter"};
                   8241:     }
                   8242:     if ($symb) {
                   8243:         my %recorded;
                   8244:         my (%returnhash) = &Apache::lonnet::restore($symb,$cid,$domain,$username);
                   8245:         if ($returnhash{'version'}) {
                   8246:             my %lasthash=();
                   8247:             my $version;
                   8248:             for ($version=1;$version<=$returnhash{'version'};$version++) {
                   8249:                 foreach my $key (sort(split(/\:/,$returnhash{$version.':keys'}))) {
                   8250:                     $lasthash{$key}=$returnhash{$version.':'.$key};
                   8251:                 }
                   8252:             }
                   8253:             foreach my $key (keys(%lasthash)) {
                   8254:                 if ($key =~ /\.scantron$/) {
                   8255:                     my $value = &unescape($lasthash{$key});
                   8256:                     my ($part_id) = ($key =~ /^resource\.(.+)\.scantron$/);
                   8257:                     if ($value eq '') {
                   8258:                         for (my $i=0; $i<$expected{$part_id}; $i++) {
                   8259:                             for (my $j=0; $j<$scantron_config->{'length'}; $j++) {
                   8260:                                 $recorded{$part_id} .= $scantron_config->{'Qoff'};
                   8261:                             }
                   8262:                         }
                   8263:                     } else {
                   8264:                         my @tocheck;
                   8265:                         my @items = split(//,$value);
                   8266:                         if (($scantron_config->{'Qon'} eq 'letter') ||
                   8267:                             ($scantron_config->{'Qon'} eq 'number')) {
                   8268:                             if (@items < $expected{$part_id}) {
                   8269:                                 my $fragment = substr($scandata,$startpos{$part_id},$expected{$part_id});
                   8270:                                 my @singles = split(//,$fragment);
                   8271:                                 foreach my $pos (@singles) {
                   8272:                                     if ($pos eq ' ') {
                   8273:                                         push(@tocheck,$pos);
                   8274:                                     } else {
                   8275:                                         my $next = shift(@items);
                   8276:                                         push(@tocheck,$next);
                   8277:                                     }
                   8278:                                 }
                   8279:                             } else {
                   8280:                                 @tocheck = @items;
                   8281:                             }
                   8282:                             foreach my $letter (@tocheck) {
                   8283:                                 if ($scantron_config->{'Qon'} eq 'letter') {
                   8284:                                     if ($letter !~ /^[A-J]$/) {
                   8285:                                         $letter = $scantron_config->{'Qoff'};
                   8286:                                     }
                   8287:                                     $recorded{$part_id} .= $letter;
                   8288:                                 } elsif ($scantron_config->{'Qon'} eq 'number') {
                   8289:                                     my $digit;
                   8290:                                     if ($letter !~ /^[A-J]$/) {
                   8291:                                         $digit = $scantron_config->{'Qoff'};
                   8292:                                     } else {
                   8293:                                         $digit = $lettdig->{$letter};
                   8294:                                     }
                   8295:                                     $recorded{$part_id} .= $digit;
                   8296:                                 }
                   8297:                             }
                   8298:                         } else {
                   8299:                             @tocheck = @items;
                   8300:                             for (my $i=0; $i<$expected{$part_id}; $i++) {
                   8301:                                 my $curr_sub = shift(@tocheck);
                   8302:                                 my $digit;
                   8303:                                 if ($curr_sub =~ /^[A-J]$/) {
                   8304:                                     $digit = $lettdig->{$curr_sub}-1;
                   8305:                                 }
                   8306:                                 if ($curr_sub eq 'J') {
                   8307:                                     $digit += scalar($numletts);
                   8308:                                 }
                   8309:                                 for (my $j=0; $j<$scantron_config->{'Qlength'}; $j++) {
                   8310:                                     if ($j == $digit) {
                   8311:                                         $recorded{$part_id} .= $scantron_config->{'Qon'};
                   8312:                                     } else {
                   8313:                                         $recorded{$part_id} .= $scantron_config->{'Qoff'};
                   8314:                                     }
                   8315:                                 }
                   8316:                             }
                   8317:                         }
                   8318:                     }
                   8319:                 }
                   8320:             }
                   8321:         }
1.554     raeburn  8322:         foreach my $part_id (@{$partids}) {
1.542     raeburn  8323:             if ($recorded{$part_id} eq '') {
                   8324:                 for (my $i=0; $i<$expected{$part_id}; $i++) {
                   8325:                     for (my $j=0; $j<$scantron_config->{'Qlength'}; $j++) {
                   8326:                         $recorded{$part_id} .= $scantron_config->{'Qoff'};
                   8327:                     }
                   8328:                 }
                   8329:             }
                   8330:             $record .= $recorded{$part_id};
                   8331:         }
                   8332:     }
                   8333:     return ($counter,$record);
                   8334: }
                   8335: 
                   8336: sub letter_to_digits { 
                   8337:     my %lettdig = (
                   8338:                     A => 1,
                   8339:                     B => 2,
                   8340:                     C => 3,
                   8341:                     D => 4,
                   8342:                     E => 5,
                   8343:                     F => 6,
                   8344:                     G => 7,
                   8345:                     H => 8,
                   8346:                     I => 9,
                   8347:                     J => 0,
                   8348:                   );
                   8349:     return %lettdig;
                   8350: }
                   8351: 
1.423     albertel 8352: 
1.75      albertel 8353: #-------- end of section for handling grading scantron forms -------
                   8354: #
                   8355: #-------------------------------------------------------------------
                   8356: 
1.72      ng       8357: #-------------------------- Menu interface -------------------------
                   8358: #
1.614     www      8359: #--- Href with symb and command ---
                   8360: 
                   8361: sub href_symb_cmd {
                   8362:     my ($symb,$cmd)=@_;
                   8363:     return '/adm/grades?symb='.&HTML::Entities::encode(&Apache::lonenc::check_encrypt($symb),'<>&"').'&command='.$cmd;
1.72      ng       8364: }
                   8365: 
1.443     banghart 8366: sub grading_menu {
1.608     www      8367:     my ($request,$symb) = @_;
1.443     banghart 8368:     if (!$symb) {return '';}
                   8369: 
                   8370:     my %fields = ('symb'=>&Apache::lonenc::check_encrypt($symb),
1.618     www      8371:                   'command'=>'individual');
1.538     schulted 8372:     
1.598     www      8373:     my $url1a = &Apache::lonhtmlcommon::build_url('grades/',\%fields);
                   8374: 
                   8375:     $fields{'command'}='ungraded';
                   8376:     my $url1b=&Apache::lonhtmlcommon::build_url('grades/',\%fields);
                   8377: 
                   8378:     $fields{'command'}='table';
                   8379:     my $url1c=&Apache::lonhtmlcommon::build_url('grades/',\%fields);
                   8380: 
                   8381:     $fields{'command'}='all_for_one';
                   8382:     my $url1d=&Apache::lonhtmlcommon::build_url('grades/',\%fields);
                   8383: 
1.621     www      8384:     $fields{'command'}='downloadfilesselect';
                   8385:     my $url1e=&Apache::lonhtmlcommon::build_url('grades/',\%fields);
                   8386: 
1.443     banghart 8387:     $fields{'command'} = 'csvform';
1.538     schulted 8388:     my $url2 = &Apache::lonhtmlcommon::build_url('grades/',\%fields);
                   8389:     
1.443     banghart 8390:     $fields{'command'} = 'processclicker';
1.538     schulted 8391:     my $url3 = &Apache::lonhtmlcommon::build_url('grades/',\%fields);
                   8392:     
1.443     banghart 8393:     $fields{'command'} = 'scantron_selectphase';
1.538     schulted 8394:     my $url4 = &Apache::lonhtmlcommon::build_url('grades/',\%fields);
1.602     www      8395: 
                   8396:     $fields{'command'} = 'initialverifyreceipt';
                   8397:     my $url5 = &Apache::lonhtmlcommon::build_url('grades/',\%fields);
1.538     schulted 8398:     
1.598     www      8399:     my @menu = ({	categorytitle=>'Hand Grading',
1.538     schulted 8400:             items =>[
1.598     www      8401:                         {	linktext => 'Select individual students to grade',
                   8402:                     		url => $url1a,
1.538     schulted 8403:                     		permission => 'F',
                   8404:                     		icon => 'edit-find-replace.png',
1.598     www      8405:                     		linktitle => 'Grade current resource for a selection of students.'
                   8406:                         }, 
                   8407:                         {       linktext => 'Grade ungraded submissions.',
                   8408:                                 url => $url1b,
                   8409:                                 permission => 'F',
                   8410:                                 icon => 'edit-find-replace.png',
                   8411:                                 linktitle => 'Grade all submissions that have not been graded yet.'
1.538     schulted 8412:                         },
1.598     www      8413: 
                   8414:                         {       linktext => 'Grading table',
                   8415:                                 url => $url1c,
                   8416:                                 permission => 'F',
                   8417:                                 icon => 'edit-find-replace.png',
                   8418:                                 linktitle => 'Grade current resource for all students.'
                   8419:                         },
1.615     www      8420:                         {       linktext => 'Grade page/folder for one student',
1.598     www      8421:                                 url => $url1d,
                   8422:                                 permission => 'F',
                   8423:                                 icon => 'edit-find-replace.png',
                   8424:                                 linktitle => 'Grade all resources in current page/sequence/folder for one student.'
1.621     www      8425:                         },
                   8426:                         {       linktext => 'Download submissions',
                   8427:                                 url => $url1e,
                   8428:                                 permission => 'F',
                   8429:                                 icon => 'edit-find-replace.png',
                   8430:                                 linktitle => 'Download all students submissions.'
1.598     www      8431:                         }]},
                   8432:                          { categorytitle=>'Automated Grading',
                   8433:                items =>[
                   8434: 
1.538     schulted 8435:                 	    {	linktext => 'Upload Scores',
                   8436:                     		url => $url2,
                   8437:                     		permission => 'F',
                   8438:                     		icon => 'uploadscores.png',
                   8439:                     		linktitle => 'Specify a file containing the class scores for current resource.'
                   8440:                 	    },
                   8441:                 	    {	linktext => 'Process Clicker',
                   8442:                     		url => $url3,
                   8443:                     		permission => 'F',
                   8444:                     		icon => 'addClickerInfoFile.png',
                   8445:                     		linktitle => 'Specify a file containing the clicker information for this resource.'
                   8446:                 	    },
1.587     raeburn  8447:                 	    {	linktext => 'Grade/Manage/Review Bubblesheets',
1.538     schulted 8448:                     		url => $url4,
                   8449:                     		permission => 'F',
                   8450:                     		icon => 'stat.png',
                   8451:                     		linktitle => 'Grade scantron exams, upload/download scantron data files, and review previously graded scantron exams.'
1.602     www      8452:                 	    },
1.616     www      8453:                             {   linktext => 'Verify Receipt Number',
1.602     www      8454:                                 url => $url5,
                   8455:                                 permission => 'F',
                   8456:                                 icon => 'edit-find-replace.png',
                   8457:                                 linktitle => 'Verify a system-generated receipt number for correct problem solution.'
                   8458:                             }
                   8459: 
1.538     schulted 8460:                     ]
                   8461:             });
                   8462: 
1.443     banghart 8463:     # Create the menu
                   8464:     my $Str;
1.445     banghart 8465:     $Str .= '<form method="post" action="" name="gradingMenu">';
                   8466:     $Str .= '<input type="hidden" name="command" value="" />'.
1.618     www      8467:     	'<input type="hidden" name="symb"        value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n";
1.445     banghart 8468: 
1.602     www      8469:     $Str .= &Apache::lonhtmlcommon::generate_menu(@menu);
1.443     banghart 8470:     return $Str;    
                   8471: }
                   8472: 
1.598     www      8473: 
                   8474: sub ungraded {
                   8475:     my ($request)=@_;
                   8476:     &submit_options($request);
                   8477: }
                   8478: 
1.599     www      8479: sub submit_options_sequence {
1.608     www      8480:     my ($request,$symb) = @_;
1.599     www      8481:     if (!$symb) {return '';}
1.600     www      8482:     &commonJSfunctions($request);
                   8483:     my $result;
1.599     www      8484: 
1.600     www      8485:     $result.='<form action="/adm/grades" method="post" name="gradingMenu">'."\n".
1.618     www      8486:         '<input type="hidden" name="symb"        value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n";
1.632   ! www      8487:     $result.=&selectfield(0).
1.601     www      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: 
1.632   ! www      8506:     $result.=&selectfield(0).
1.601     www      8507:             '<input type="hidden" name="command" value="viewgrades" />
1.599     www      8508:             <div>
                   8509:               <input type="submit" value="'.&mt('Next').' &rarr;" />
                   8510:             </div>
                   8511:         </div>
                   8512:   </form>';
                   8513:     return $result;
                   8514: }
1.443     banghart 8515: 
1.621     www      8516: sub submit_options_download {
                   8517:     my ($request,$symb) = @_;
                   8518:     if (!$symb) {return '';}
                   8519: 
                   8520:     &commonJSfunctions($request);
                   8521: 
                   8522:     my $result='<form action="/adm/grades" method="post" name="gradingMenu">'."\n".
                   8523:         '<input type="hidden" name="symb"        value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n";
                   8524:     $result.='
                   8525: <h2>
                   8526:   '.&mt('Select Students for Which to Download Submissions').'
                   8527: </h2>'.&selectfield(1).'
                   8528:                 <input type="hidden" name="command" value="downloadfileslink" /> 
                   8529:               <input type="submit" value="'.&mt('Next').' &rarr;" />
                   8530:             </div>
                   8531:           </div>
1.600     www      8532: 
                   8533: 
1.621     www      8534:   </form>';
                   8535:     return $result;
                   8536: }
                   8537: 
1.443     banghart 8538: #--- Displays the submissions first page -------
                   8539: sub submit_options {
1.608     www      8540:     my ($request,$symb) = @_;
1.72      ng       8541:     if (!$symb) {return '';}
                   8542: 
1.118     ng       8543:     &commonJSfunctions($request);
1.473     albertel 8544:     my $result;
1.533     bisitz   8545: 
1.72      ng       8546:     $result.='<form action="/adm/grades" method="post" name="gradingMenu">'."\n".
1.618     www      8547: 	'<input type="hidden" name="symb"        value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n";
1.632   ! www      8548:     $result.=&selectfield(1).'
1.601     www      8549:                 <input type="hidden" name="command" value="submission" /> 
                   8550: 	      <input type="submit" value="'.&mt('Next').' &rarr;" />
                   8551:             </div>
                   8552:           </div>
                   8553: 
                   8554: 
                   8555:   </form>';
                   8556:     return $result;
                   8557: }
1.533     bisitz   8558: 
1.601     www      8559: sub selectfield {
                   8560:    my ($full)=@_;
                   8561:    my $result='<div class="LC_columnSection">
1.537     harmsja  8562:   
1.533     bisitz   8563:     <fieldset>
                   8564:       <legend>
                   8565:        '.&mt('Sections').'
                   8566:       </legend>
1.601     www      8567:       '.&Apache::lonstatistics::SectionSelect('section','multiple',5).'
1.533     bisitz   8568:     </fieldset>
1.537     harmsja  8569:   
1.533     bisitz   8570:     <fieldset>
                   8571:       <legend>
                   8572:         '.&mt('Groups').'
                   8573:       </legend>
                   8574:       '.&Apache::lonstatistics::GroupSelect('group','multiple',5).'
                   8575:     </fieldset>
1.537     harmsja  8576:   
1.533     bisitz   8577:     <fieldset>
                   8578:       <legend>
                   8579:         '.&mt('Access Status').'
                   8580:       </legend>
1.601     www      8581:       '.&Apache::lonhtmlcommon::StatusOptions(undef,undef,5,undef,'mult').'
                   8582:     </fieldset>';
                   8583:     if ($full) {
                   8584:        $result.='
1.533     bisitz   8585:     <fieldset>
                   8586:       <legend>
                   8587:         '.&mt('Submission Status').'
1.601     www      8588:       </legend>'.
                   8589:        &Apache::loncommon::select_form('all','submitonly',
                   8590:           (&Apache::lonlocal::texthash(
                   8591:              'yes'       => 'with submissions',
                   8592:              'queued'    => 'in grading queue',
                   8593:              'graded'    => 'with ungraded submissions',
                   8594:              'incorrect' => 'with incorrect submissions',
                   8595:              'all'       => 'with any status'),
                   8596:              'select_form_order' => ['yes','queued','graded','incorrect','all'])).
                   8597:    '</fieldset>';
                   8598:     }
                   8599:     $result.='</div><br />';
1.44      ng       8600:     return $result;
1.2       albertel 8601: }
                   8602: 
1.285     albertel 8603: sub reset_perm {
                   8604:     undef(%perm);
                   8605: }
                   8606: 
                   8607: sub init_perm {
                   8608:     &reset_perm();
1.300     albertel 8609:     foreach my $test_perm ('vgr','mgr','opa') {
                   8610: 
                   8611: 	my $scope = $env{'request.course.id'};
                   8612: 	if (!($perm{$test_perm}=&Apache::lonnet::allowed($test_perm,$scope))) {
                   8613: 
                   8614: 	    $scope .= '/'.$env{'request.course.sec'};
                   8615: 	    if ( $perm{$test_perm}=
                   8616: 		 &Apache::lonnet::allowed($test_perm,$scope)) {
                   8617: 		$perm{$test_perm.'_section'}=$env{'request.course.sec'};
                   8618: 	    } else {
                   8619: 		delete($perm{$test_perm});
                   8620: 	    }
1.285     albertel 8621: 	}
                   8622:     }
                   8623: }
                   8624: 
1.400     www      8625: sub gather_clicker_ids {
1.408     albertel 8626:     my %clicker_ids;
1.400     www      8627: 
                   8628:     my $classlist = &Apache::loncoursedata::get_classlist();
                   8629: 
                   8630:     # Set up a couple variables.
1.407     albertel 8631:     my $username_idx = &Apache::loncoursedata::CL_SNAME();
                   8632:     my $domain_idx   = &Apache::loncoursedata::CL_SDOM();
1.438     www      8633:     my $status_idx   = &Apache::loncoursedata::CL_STATUS();
1.400     www      8634: 
1.407     albertel 8635:     foreach my $student (keys(%$classlist)) {
1.438     www      8636:         if ($classlist->{$student}->[$status_idx] ne 'Active') { next; }
1.407     albertel 8637:         my $username = $classlist->{$student}->[$username_idx];
                   8638:         my $domain   = $classlist->{$student}->[$domain_idx];
1.400     www      8639:         my $clickers =
1.408     albertel 8640: 	    (&Apache::lonnet::userenvironment($domain,$username,'clickers'))[1];
1.400     www      8641:         foreach my $id (split(/\,/,$clickers)) {
1.414     www      8642:             $id=~s/^[\#0]+//;
1.421     www      8643:             $id=~s/[\-\:]//g;
1.407     albertel 8644:             if (exists($clicker_ids{$id})) {
1.408     albertel 8645: 		$clicker_ids{$id}.=','.$username.':'.$domain;
1.400     www      8646:             } else {
1.408     albertel 8647: 		$clicker_ids{$id}=$username.':'.$domain;
1.400     www      8648:             }
                   8649:         }
                   8650:     }
1.407     albertel 8651:     return %clicker_ids;
1.400     www      8652: }
                   8653: 
1.402     www      8654: sub gather_adv_clicker_ids {
1.408     albertel 8655:     my %clicker_ids;
1.402     www      8656:     my $cnum=$env{'course.'.$env{'request.course.id'}.'.num'};
                   8657:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
                   8658:     my %coursepersonnel=&Apache::lonnet::get_course_adv_roles($cdom.'/'.$cnum);
1.409     albertel 8659:     foreach my $element (sort(keys(%coursepersonnel))) {
1.402     www      8660:         foreach my $person (split(/\,/,$coursepersonnel{$element})) {
                   8661:             my ($puname,$pudom)=split(/\:/,$person);
                   8662:             my $clickers =
1.408     albertel 8663: 		(&Apache::lonnet::userenvironment($pudom,$puname,'clickers'))[1];
1.405     www      8664:             foreach my $id (split(/\,/,$clickers)) {
1.414     www      8665: 		$id=~s/^[\#0]+//;
1.421     www      8666:                 $id=~s/[\-\:]//g;
1.408     albertel 8667: 		if (exists($clicker_ids{$id})) {
                   8668: 		    $clicker_ids{$id}.=','.$puname.':'.$pudom;
                   8669: 		} else {
                   8670: 		    $clicker_ids{$id}=$puname.':'.$pudom;
                   8671: 		}
1.405     www      8672:             }
1.402     www      8673:         }
                   8674:     }
1.407     albertel 8675:     return %clicker_ids;
1.402     www      8676: }
                   8677: 
1.413     www      8678: sub clicker_grading_parameters {
                   8679:     return ('gradingmechanism' => 'scalar',
                   8680:             'upfiletype' => 'scalar',
                   8681:             'specificid' => 'scalar',
                   8682:             'pcorrect' => 'scalar',
                   8683:             'pincorrect' => 'scalar');
                   8684: }
                   8685: 
1.400     www      8686: sub process_clicker {
1.608     www      8687:     my ($r,$symb)=@_;
1.400     www      8688:     if (!$symb) {return '';}
                   8689:     my $result=&checkforfile_js();
1.632   ! www      8690:     $result.=&Apache::loncommon::start_data_table().
        !          8691:              &Apache::loncommon::start_data_table_header_row().
        !          8692:              '<th>'.&mt('Specify a file containing clicker information and set grading options.').'</th>'.
        !          8693:              &Apache::loncommon::end_data_table_header_row().
        !          8694:              &Apache::loncommon::start_data_table_row()."<td>\n";
1.413     www      8695: # Attempt to restore parameters from last session, set defaults if not present
                   8696:     my %Saveable_Parameters=&clicker_grading_parameters();
                   8697:     &Apache::loncommon::restore_course_settings('grades_clicker',
                   8698:                                                  \%Saveable_Parameters);
                   8699:     if (!$env{'form.pcorrect'}) { $env{'form.pcorrect'}=100; }
                   8700:     if (!$env{'form.pincorrect'}) { $env{'form.pincorrect'}=100; }
                   8701:     if (!$env{'form.gradingmechanism'}) { $env{'form.gradingmechanism'}='attendance'; }
                   8702:     if (!$env{'form.upfiletype'}) { $env{'form.upfiletype'}='iclicker'; }
                   8703: 
                   8704:     my %checked;
1.521     www      8705:     foreach my $gradingmechanism ('attendance','personnel','specific','given') {
1.413     www      8706:        if ($env{'form.gradingmechanism'} eq $gradingmechanism) {
1.569     bisitz   8707:           $checked{$gradingmechanism}=' checked="checked"';
1.413     www      8708:        }
                   8709:     }
                   8710: 
1.632   ! www      8711:     my $upload=&mt("Evaluate File");
1.400     www      8712:     my $type=&mt("Type");
1.402     www      8713:     my $attendance=&mt("Award points just for participation");
                   8714:     my $personnel=&mt("Correctness determined from response by course personnel");
1.414     www      8715:     my $specific=&mt("Correctness determined from response with clicker ID(s)"); 
1.521     www      8716:     my $given=&mt("Correctness determined from given list of answers").' '.
                   8717:               '<font size="-2"><tt>('.&mt("Provide comma-separated list. Use '*' for any answer correct, '-' for skip").')</tt></font>';
1.402     www      8718:     my $pcorrect=&mt("Percentage points for correct solution");
                   8719:     my $pincorrect=&mt("Percentage points for incorrect solution");
1.413     www      8720:     my $selectform=&Apache::loncommon::select_form($env{'form.upfiletype'},'upfiletype',
1.419     www      8721: 						   ('iclicker' => 'i>clicker',
                   8722:                                                     'interwrite' => 'interwrite PRS'));
1.418     albertel 8723:     $symb = &Apache::lonenc::check_encrypt($symb);
1.597     wenzelju 8724:     $result.= &Apache::lonhtmlcommon::scripttag(<<ENDUPFORM);
1.402     www      8725: function sanitycheck() {
                   8726: // Accept only integer percentages
                   8727:    document.forms.gradesupload.pcorrect.value=Math.round(document.forms.gradesupload.pcorrect.value);
                   8728:    document.forms.gradesupload.pincorrect.value=Math.round(document.forms.gradesupload.pincorrect.value);
                   8729: // Find out grading choice
                   8730:    for (i=0; i<document.forms.gradesupload.gradingmechanism.length; i++) {
                   8731:       if (document.forms.gradesupload.gradingmechanism[i].checked) {
                   8732:          gradingchoice=document.forms.gradesupload.gradingmechanism[i].value;
                   8733:       }
                   8734:    }
                   8735: // By default, new choice equals user selection
                   8736:    newgradingchoice=gradingchoice;
                   8737: // Not good to give more points for false answers than correct ones
                   8738:    if (Math.round(document.forms.gradesupload.pcorrect.value)<Math.round(document.forms.gradesupload.pincorrect.value)) {
                   8739:       document.forms.gradesupload.pcorrect.value=document.forms.gradesupload.pincorrect.value;
                   8740:    }
                   8741: // If new choice is attendance only, and old choice was correctness-based, restore defaults
                   8742:    if ((gradingchoice=='attendance') && (document.forms.gradesupload.waschecked.value!='attendance')) {
                   8743:       document.forms.gradesupload.pcorrect.value=100;
                   8744:       document.forms.gradesupload.pincorrect.value=100;
                   8745:    }
                   8746: // If the values are different, cannot be attendance only
                   8747:    if ((Math.round(document.forms.gradesupload.pcorrect.value)!=Math.round(document.forms.gradesupload.pincorrect.value)) &&
                   8748:        (gradingchoice=='attendance')) {
                   8749:        newgradingchoice='personnel';
                   8750:    }
                   8751: // Change grading choice to new one
                   8752:    for (i=0; i<document.forms.gradesupload.gradingmechanism.length; i++) {
                   8753:       if (document.forms.gradesupload.gradingmechanism[i].value==newgradingchoice) {
                   8754:          document.forms.gradesupload.gradingmechanism[i].checked=true;
                   8755:       } else {
                   8756:          document.forms.gradesupload.gradingmechanism[i].checked=false;
                   8757:       }
                   8758:    }
                   8759: // Remember the old state
                   8760:    document.forms.gradesupload.waschecked.value=newgradingchoice;
                   8761: }
1.597     wenzelju 8762: ENDUPFORM
                   8763:     $result.= <<ENDUPFORM;
1.400     www      8764: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="gradesupload">
                   8765: <input type="hidden" name="symb" value="$symb" />
                   8766: <input type="hidden" name="command" value="processclickerfile" />
                   8767: <input type="file" name="upfile" size="50" />
                   8768: <br /><label>$type: $selectform</label>
1.632   ! www      8769: ENDUPFORM
        !          8770:     $result.='</td>'.&Apache::loncommon::end_data_table_row().
        !          8771:                      &Apache::loncommon::start_data_table_row().'<td>'.(<<ENDGRADINGFORM);
        !          8772:       <label><input type="radio" name="gradingmechanism" value="attendance"$checked{'attendance'} onclick="sanitycheck()" />$attendance </label>
1.589     bisitz   8773: <br /><label><input type="radio" name="gradingmechanism" value="personnel"$checked{'personnel'} onclick="sanitycheck()" />$personnel</label>
                   8774: <br /><label><input type="radio" name="gradingmechanism" value="specific"$checked{'specific'} onclick="sanitycheck()" />$specific </label>
1.414     www      8775: <input type="text" name="specificid" value="$env{'form.specificid'}" size="20" />
1.589     bisitz   8776: <br /><label><input type="radio" name="gradingmechanism" value="given"$checked{'given'} onclick="sanitycheck()" />$given </label>
1.521     www      8777: <br />&nbsp;&nbsp;&nbsp;
                   8778: <input type="text" name="givenanswer" size="50" />
1.413     www      8779: <input type="hidden" name="waschecked" value="$env{'form.gradingmechanism'}" />
1.632   ! www      8780: ENDGRADINGFORM
        !          8781:          $result.='</td>'.&Apache::loncommon::end_data_table_row().
        !          8782:                      &Apache::loncommon::start_data_table_row().'<td>'.(<<ENDPERCFORM);
        !          8783:       <label>$pcorrect: <input type="text" name="pcorrect" size="4" value="$env{'form.pcorrect'}" onchange="sanitycheck()" /></label>
1.589     bisitz   8784: <br /><label>$pincorrect: <input type="text" name="pincorrect" size="4" value="$env{'form.pincorrect'}" onchange="sanitycheck()" /></label>
                   8785: <br /><input type="button" onclick="javascript:checkUpload(this.form);" value="$upload" />
1.597     wenzelju 8786: </form>'
1.632   ! www      8787: ENDPERCFORM
        !          8788:     $result.='</td>'.
        !          8789:              &Apache::loncommon::end_data_table_row().
        !          8790:              &Apache::loncommon::end_data_table();
1.400     www      8791:     return $result;
                   8792: }
                   8793: 
                   8794: sub process_clicker_file {
1.608     www      8795:     my ($r,$symb)=@_;
1.400     www      8796:     if (!$symb) {return '';}
1.413     www      8797: 
                   8798:     my %Saveable_Parameters=&clicker_grading_parameters();
                   8799:     &Apache::loncommon::store_course_settings('grades_clicker',
                   8800:                                               \%Saveable_Parameters);
1.598     www      8801:     my $result='';
1.404     www      8802:     if (($env{'form.gradingmechanism'} eq 'specific') && ($env{'form.specificid'}!~/\w/)) {
1.408     albertel 8803: 	$result.='<span class="LC_error">'.&mt('You need to specify a clicker ID for the correct answer').'</span>';
1.614     www      8804: 	return $result;
1.404     www      8805:     }
1.522     www      8806:     if (($env{'form.gradingmechanism'} eq 'given') && ($env{'form.givenanswer'}!~/\S/)) {
1.521     www      8807:         $result.='<span class="LC_error">'.&mt('You need to specify the correct answer').'</span>';
1.614     www      8808:         return $result;
1.521     www      8809:     }
1.522     www      8810:     my $foundgiven=0;
1.521     www      8811:     if ($env{'form.gradingmechanism'} eq 'given') {
                   8812:         $env{'form.givenanswer'}=~s/^\s*//gs;
                   8813:         $env{'form.givenanswer'}=~s/\s*$//gs;
                   8814:         $env{'form.givenanswer'}=~s/[^a-zA-Z0-9\.\*\-]+/\,/g;
                   8815:         $env{'form.givenanswer'}=uc($env{'form.givenanswer'});
1.522     www      8816:         my @answers=split(/\,/,$env{'form.givenanswer'});
                   8817:         $foundgiven=$#answers+1;
1.521     www      8818:     }
1.407     albertel 8819:     my %clicker_ids=&gather_clicker_ids();
1.408     albertel 8820:     my %correct_ids;
1.404     www      8821:     if ($env{'form.gradingmechanism'} eq 'personnel') {
1.408     albertel 8822: 	%correct_ids=&gather_adv_clicker_ids();
1.404     www      8823:     }
                   8824:     if ($env{'form.gradingmechanism'} eq 'specific') {
1.414     www      8825: 	foreach my $correct_id (split(/[\s\,]/,$env{'form.specificid'})) {;
                   8826: 	   $correct_id=~tr/a-z/A-Z/;
                   8827: 	   $correct_id=~s/\s//gs;
                   8828: 	   $correct_id=~s/^[\#0]+//;
1.421     www      8829:            $correct_id=~s/[\-\:]//g;
1.414     www      8830:            if ($correct_id) {
                   8831: 	      $correct_ids{$correct_id}='specified';
                   8832:            }
                   8833:         }
1.400     www      8834:     }
1.404     www      8835:     if ($env{'form.gradingmechanism'} eq 'attendance') {
1.408     albertel 8836: 	$result.=&mt('Score based on attendance only');
1.521     www      8837:     } elsif ($env{'form.gradingmechanism'} eq 'given') {
1.522     www      8838:         $result.=&mt('Score based on [_1] ([_2] answers)','<tt>'.$env{'form.givenanswer'}.'</tt>',$foundgiven);
1.404     www      8839:     } else {
1.408     albertel 8840: 	my $number=0;
1.411     www      8841: 	$result.='<p><b>'.&mt('Correctness determined by the following IDs').'</b>';
1.408     albertel 8842: 	foreach my $id (sort(keys(%correct_ids))) {
1.411     www      8843: 	    $result.='<br /><tt>'.$id.'</tt> - ';
1.408     albertel 8844: 	    if ($correct_ids{$id} eq 'specified') {
                   8845: 		$result.=&mt('specified');
                   8846: 	    } else {
                   8847: 		my ($uname,$udom)=split(/\:/,$correct_ids{$id});
                   8848: 		$result.=&Apache::loncommon::plainname($uname,$udom);
                   8849: 	    }
                   8850: 	    $number++;
                   8851: 	}
1.411     www      8852:         $result.="</p>\n";
1.408     albertel 8853: 	if ($number==0) {
                   8854: 	    $result.='<span class="LC_error">'.&mt('No IDs found to determine correct answer').'</span>';
1.614     www      8855: 	    return $result;
1.408     albertel 8856: 	}
1.404     www      8857:     }
1.405     www      8858:     if (length($env{'form.upfile'}) < 2) {
1.407     albertel 8859:         $result.=&mt('[_1] Error: [_2] The file you attempted to upload, [_3] contained no information. Please check that you entered the correct filename.',
                   8860: 		     '<span class="LC_error">',
                   8861: 		     '</span>',
                   8862: 		     '<span class="LC_filename">'.&HTML::Entities::encode($env{'form.upfile.filename'},'<>&"').'</span>');
1.614     www      8863:         return $result;
1.405     www      8864:     }
1.410     www      8865: 
                   8866: # Were able to get all the info needed, now analyze the file
                   8867: 
1.411     www      8868:     $result.=&Apache::loncommon::studentbrowser_javascript();
1.418     albertel 8869:     $symb = &Apache::lonenc::check_encrypt($symb);
1.632   ! www      8870:     $result.=&Apache::loncommon::start_data_table().
        !          8871:              &Apache::loncommon::start_data_table_header_row().
        !          8872:              '<th>'.&mt('Evaluate clicker file').'</th>'.
        !          8873:              &Apache::loncommon::end_data_table_header_row().
        !          8874:              &Apache::loncommon::start_data_table_row().(<<ENDHEADER);
        !          8875: <td>
1.410     www      8876: <form method="post" action="/adm/grades" name="clickeranalysis">
                   8877: <input type="hidden" name="symb" value="$symb" />
                   8878: <input type="hidden" name="command" value="assignclickergrades" />
1.411     www      8879: <input type="hidden" name="gradingmechanism" value="$env{'form.gradingmechanism'}" />
                   8880: <input type="hidden" name="pcorrect" value="$env{'form.pcorrect'}" />
                   8881: <input type="hidden" name="pincorrect" value="$env{'form.pincorrect'}" />
1.410     www      8882: ENDHEADER
1.522     www      8883:     if ($env{'form.gradingmechanism'} eq 'given') {
                   8884:        $result.='<input type="hidden" name="correct:given" value="'.$env{'form.givenanswer'}.'" />';
                   8885:     } 
1.408     albertel 8886:     my %responses;
                   8887:     my @questiontitles;
1.405     www      8888:     my $errormsg='';
                   8889:     my $number=0;
                   8890:     if ($env{'form.upfiletype'} eq 'iclicker') {
1.408     albertel 8891: 	($errormsg,$number)=&iclicker_eval(\@questiontitles,\%responses);
1.406     www      8892:     }
1.419     www      8893:     if ($env{'form.upfiletype'} eq 'interwrite') {
                   8894:         ($errormsg,$number)=&interwrite_eval(\@questiontitles,\%responses);
                   8895:     }
1.411     www      8896:     $result.='<br />'.&mt('Found [_1] question(s)',$number).'<br />'.
                   8897:              '<input type="hidden" name="number" value="'.$number.'" />'.
                   8898:              &mt('Awarding [_1] percent for correct and [_2] percent for incorrect responses',
                   8899:                  $env{'form.pcorrect'},$env{'form.pincorrect'}).
                   8900:              '<br />';
1.522     www      8901:     if (($env{'form.gradingmechanism'} eq 'given') && ($number!=$foundgiven)) {
                   8902:        $result.='<span class="LC_error">'.&mt('Number of given answers does not agree with number of questions in file.').'</span>';
1.614     www      8903:        return $result;
1.522     www      8904:     } 
1.414     www      8905: # Remember Question Titles
                   8906: # FIXME: Possibly need delimiter other than ":"
                   8907:     for (my $i=0;$i<$number;$i++) {
                   8908:         $result.='<input type="hidden" name="question:'.$i.'" value="'.
                   8909:                  &HTML::Entities::encode($questiontitles[$i],'"&<>').'" />';
                   8910:     }
1.411     www      8911:     my $correct_count=0;
                   8912:     my $student_count=0;
                   8913:     my $unknown_count=0;
1.414     www      8914: # Match answers with usernames
                   8915: # FIXME: Possibly need delimiter other than ":"
1.409     albertel 8916:     foreach my $id (keys(%responses)) {
1.410     www      8917:        if ($correct_ids{$id}) {
1.414     www      8918:           $result.="\n".'<input type="hidden" name="correct:'.$correct_count.':'.$correct_ids{$id}.'" value="'.$responses{$id}.'" />';
1.411     www      8919:           $correct_count++;
1.410     www      8920:        } elsif ($clicker_ids{$id}) {
1.437     www      8921:           if ($clicker_ids{$id}=~/\,/) {
                   8922: # More than one user with the same clicker!
1.632   ! www      8923:              $result.="</td>".&Apache::loncommon::end_data_table_row().
        !          8924:                            &Apache::loncommon::start_data_table_row()."<td>".
        !          8925:                        &mt('Clicker registered more than once').": <tt>".$id."</tt><br />";
1.437     www      8926:              $result.="\n".'<input type="hidden" name="unknown:'.$id.'" value="'.$responses{$id}.'" />'.
                   8927:                            "<select name='multi".$id."'>";
                   8928:              foreach my $reguser (sort(split(/\,/,$clicker_ids{$id}))) {
                   8929:                  $result.="<option value='".$reguser."'>".&Apache::loncommon::plainname(split(/\:/,$reguser)).' ('.$reguser.')</option>';
                   8930:              }
                   8931:              $result.='</select>';
                   8932:              $unknown_count++;
                   8933:           } else {
                   8934: # Good: found one and only one user with the right clicker
                   8935:              $result.="\n".'<input type="hidden" name="student:'.$clicker_ids{$id}.'" value="'.$responses{$id}.'" />';
                   8936:              $student_count++;
                   8937:           }
1.410     www      8938:        } else {
1.632   ! www      8939:           $result.="</td>".&Apache::loncommon::end_data_table_row().
        !          8940:                            &Apache::loncommon::start_data_table_row()."<td>".
        !          8941:                     &mt('Unregistered Clicker')." <tt>".$id."</tt><br />";
1.411     www      8942:           $result.="\n".'<input type="hidden" name="unknown:'.$id.'" value="'.$responses{$id}.'" />'.
                   8943:                    "\n".&mt("Username").": <input type='text' name='uname".$id."' />&nbsp;".
                   8944:                    "\n".&mt("Domain").": ".
                   8945:                    &Apache::loncommon::select_dom_form($env{'course.'.$env{'request.course.id'}.'.domain'},'udom'.$id).'&nbsp;'.
                   8946:                    &Apache::loncommon::selectstudent_link('clickeranalysis','uname'.$id,'udom'.$id);
                   8947:           $unknown_count++;
1.410     www      8948:        }
1.405     www      8949:     }
1.412     www      8950:     $result.='<hr />'.
                   8951:              &mt('Found [_1] registered and [_2] unregistered clickers.',$student_count,$unknown_count);
1.521     www      8952:     if (($env{'form.gradingmechanism'} ne 'attendance') && ($env{'form.gradingmechanism'} ne 'given')) {
1.412     www      8953:        if ($correct_count==0) {
                   8954:           $errormsg.="Found no correct answers answers for grading!";
                   8955:        } elsif ($correct_count>1) {
1.414     www      8956:           $result.='<br /><span class="LC_warning">'.&mt("Found [_1] entries for grading!",$correct_count).'</span>';
1.412     www      8957:        }
                   8958:     }
1.428     www      8959:     if ($number<1) {
                   8960:        $errormsg.="Found no questions.";
                   8961:     }
1.412     www      8962:     if ($errormsg) {
                   8963:        $result.='<br /><span class="LC_error">'.&mt($errormsg).'</span>';
                   8964:     } else {
                   8965:        $result.='<br /><input type="submit" name="finalize" value="'.&mt('Finalize Grading').'" />';
                   8966:     }
1.632   ! www      8967:     $result.='</form></td>'.
        !          8968:              &Apache::loncommon::end_data_table_row().
        !          8969:              &Apache::loncommon::end_data_table();
1.614     www      8970:     return $result;
1.400     www      8971: }
                   8972: 
1.405     www      8973: sub iclicker_eval {
1.406     www      8974:     my ($questiontitles,$responses)=@_;
1.405     www      8975:     my $number=0;
                   8976:     my $errormsg='';
                   8977:     foreach my $line (split(/[\n\r]/,$env{'form.upfile'})) {
1.410     www      8978:         my %components=&Apache::loncommon::record_sep($line);
                   8979:         my @entries=map {$components{$_}} (sort(keys(%components)));
1.408     albertel 8980: 	if ($entries[0] eq 'Question') {
                   8981: 	    for (my $i=3;$i<$#entries;$i+=6) {
                   8982: 		$$questiontitles[$number]=$entries[$i];
                   8983: 		$number++;
                   8984: 	    }
                   8985: 	}
                   8986: 	if ($entries[0]=~/^\#/) {
                   8987: 	    my $id=$entries[0];
                   8988: 	    my @idresponses;
                   8989: 	    $id=~s/^[\#0]+//;
                   8990: 	    for (my $i=0;$i<$number;$i++) {
                   8991: 		my $idx=3+$i*6;
                   8992: 		push(@idresponses,$entries[$idx]);
                   8993: 	    }
                   8994: 	    $$responses{$id}=join(',',@idresponses);
                   8995: 	}
1.405     www      8996:     }
                   8997:     return ($errormsg,$number);
                   8998: }
                   8999: 
1.419     www      9000: sub interwrite_eval {
                   9001:     my ($questiontitles,$responses)=@_;
                   9002:     my $number=0;
                   9003:     my $errormsg='';
1.420     www      9004:     my $skipline=1;
                   9005:     my $questionnumber=0;
                   9006:     my %idresponses=();
1.419     www      9007:     foreach my $line (split(/[\n\r]/,$env{'form.upfile'})) {
                   9008:         my %components=&Apache::loncommon::record_sep($line);
                   9009:         my @entries=map {$components{$_}} (sort(keys(%components)));
1.420     www      9010:         if ($entries[1] eq 'Time') { $skipline=0; next; }
                   9011:         if ($entries[1] eq 'Response') { $skipline=1; }
                   9012:         next if $skipline;
                   9013:         if ($entries[0]!=$questionnumber) {
                   9014:            $questionnumber=$entries[0];
                   9015:            $$questiontitles[$number]=&mt('Question [_1]',$questionnumber);
                   9016:            $number++;
1.419     www      9017:         }
1.420     www      9018:         my $id=$entries[4];
                   9019:         $id=~s/^[\#0]+//;
1.421     www      9020:         $id=~s/^v\d*\://i;
                   9021:         $id=~s/[\-\:]//g;
1.420     www      9022:         $idresponses{$id}[$number]=$entries[6];
                   9023:     }
1.524     raeburn  9024:     foreach my $id (keys(%idresponses)) {
1.420     www      9025:        $$responses{$id}=join(',',@{$idresponses{$id}});
                   9026:        $$responses{$id}=~s/^\s*\,//;
1.419     www      9027:     }
                   9028:     return ($errormsg,$number);
                   9029: }
                   9030: 
1.414     www      9031: sub assign_clicker_grades {
1.608     www      9032:     my ($r,$symb)=@_;
1.414     www      9033:     if (!$symb) {return '';}
1.416     www      9034: # See which part we are saving to
1.582     raeburn  9035:     my $res_error;
                   9036:     my ($partlist,$handgrade,$responseType) = &response_type($symb,\$res_error);
                   9037:     if ($res_error) {
                   9038:         return &navmap_errormsg();
                   9039:     }
1.416     www      9040: # FIXME: This should probably look for the first handgradeable part
                   9041:     my $part=$$partlist[0];
                   9042: # Start screen output
1.632   ! www      9043:     my $result=&Apache::loncommon::start_data_table().
        !          9044:              &Apache::loncommon::start_data_table_header_row().
        !          9045:              '<th>'.&mt('Assigning grades based on clicker file').'</th>'.
        !          9046:              &Apache::loncommon::end_data_table_header_row().
        !          9047:              &Apache::loncommon::start_data_table_row().'<td>';
1.414     www      9048: # Get correct result
                   9049: # FIXME: Possibly need delimiter other than ":"
                   9050:     my @correct=();
1.415     www      9051:     my $gradingmechanism=$env{'form.gradingmechanism'};
                   9052:     my $number=$env{'form.number'};
                   9053:     if ($gradingmechanism ne 'attendance') {
1.414     www      9054:        foreach my $key (keys(%env)) {
                   9055:           if ($key=~/^form\.correct\:/) {
                   9056:              my @input=split(/\,/,$env{$key});
                   9057:              for (my $i=0;$i<=$#input;$i++) {
                   9058:                  if (($correct[$i]) && ($input[$i]) &&
                   9059:                      ($correct[$i] ne $input[$i])) {
                   9060:                     $result.='<br /><span class="LC_warning">'.
                   9061:                              &mt('More than one correct result given for question "[_1]": [_2] versus [_3].',
                   9062:                                  $env{'form.question:'.$i},$correct[$i],$input[$i]).'</span>';
                   9063:                  } elsif ($input[$i]) {
                   9064:                     $correct[$i]=$input[$i];
                   9065:                  }
                   9066:              }
                   9067:           }
                   9068:        }
1.415     www      9069:        for (my $i=0;$i<$number;$i++) {
1.414     www      9070:           if (!$correct[$i]) {
                   9071:              $result.='<br /><span class="LC_error">'.
                   9072:                       &mt('No correct result given for question "[_1]"!',
                   9073:                           $env{'form.question:'.$i}).'</span>';
                   9074:           }
                   9075:        }
                   9076:        $result.='<br />'.&mt("Correct answer: [_1]",join(', ',map { ($_?$_:'-') } @correct));
                   9077:     }
                   9078: # Start grading
1.415     www      9079:     my $pcorrect=$env{'form.pcorrect'};
                   9080:     my $pincorrect=$env{'form.pincorrect'};
1.416     www      9081:     my $storecount=0;
1.632   ! www      9082:     my %users=();
1.415     www      9083:     foreach my $key (keys(%env)) {
1.420     www      9084:        my $user='';
1.415     www      9085:        if ($key=~/^form\.student\:(.*)$/) {
1.420     www      9086:           $user=$1;
                   9087:        }
                   9088:        if ($key=~/^form\.unknown\:(.*)$/) {
                   9089:           my $id=$1;
                   9090:           if (($env{'form.uname'.$id}) && ($env{'form.udom'.$id})) {
                   9091:              $user=$env{'form.uname'.$id}.':'.$env{'form.udom'.$id};
1.437     www      9092:           } elsif ($env{'form.multi'.$id}) {
                   9093:              $user=$env{'form.multi'.$id};
1.420     www      9094:           }
                   9095:        }
1.632   ! www      9096:        if ($user) {
        !          9097:           if ($users{$user}) {
        !          9098:              $result.='<br /><span class="LC_warning">'.
        !          9099:                       &mt("More than one entry found for <tt>[_1]</tt>!",$user).
        !          9100:                       '</span><br />';
        !          9101:           }
        !          9102:           $users{$user}=1; 
1.415     www      9103:           my @answer=split(/\,/,$env{$key});
                   9104:           my $sum=0;
1.522     www      9105:           my $realnumber=$number;
1.415     www      9106:           for (my $i=0;$i<$number;$i++) {
1.576     www      9107:              if  ($correct[$i] eq '-') {
                   9108:                 $realnumber--;
                   9109:              } elsif ($answer[$i]) {
1.415     www      9110:                 if ($gradingmechanism eq 'attendance') {
                   9111:                    $sum+=$pcorrect;
1.576     www      9112:                 } elsif ($correct[$i] eq '*') {
1.522     www      9113:                    $sum+=$pcorrect;
1.415     www      9114:                 } else {
                   9115:                    if ($answer[$i] eq $correct[$i]) {
                   9116:                       $sum+=$pcorrect;
                   9117:                    } else {
                   9118:                       $sum+=$pincorrect;
                   9119:                    }
                   9120:                 }
                   9121:              }
                   9122:           }
1.522     www      9123:           my $ave=$sum/(100*$realnumber);
1.416     www      9124: # Store
                   9125:           my ($username,$domain)=split(/\:/,$user);
                   9126:           my %grades=();
                   9127:           $grades{"resource.$part.solved"}='correct_by_override';
                   9128:           $grades{"resource.$part.awarded"}=$ave;
                   9129:           $grades{"resource.regrader"}="$env{'user.name'}:$env{'user.domain'}";
                   9130:           my $returncode=&Apache::lonnet::cstore(\%grades,$symb,
                   9131:                                                  $env{'request.course.id'},
                   9132:                                                  $domain,$username);
                   9133:           if ($returncode ne 'ok') {
                   9134:              $result.="<br /><span class=\"LC_error\">Failed to save student $username:$domain. Message when trying to save was ($returncode)</span>";
                   9135:           } else {
                   9136:              $storecount++;
                   9137:           }
1.415     www      9138:        }
                   9139:     }
                   9140: # We are done
1.549     hauer    9141:     $result.='<br />'.&mt('Successfully stored grades for [quant,_1,student].',$storecount).
1.632   ! www      9142:              '</td>'.
        !          9143:              &Apache::loncommon::end_data_table_row().
        !          9144:              &Apache::loncommon::end_data_table();
1.614     www      9145:     return $result;
1.414     www      9146: }
                   9147: 
1.582     raeburn  9148: sub navmap_errormsg {
                   9149:     return '<div class="LC_error">'.
                   9150:            &mt('An error occurred retrieving information about resources in the course.').'<br />'.
1.595     raeburn  9151:            &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  9152:            '</div>';
                   9153: }
1.607     droeschl 9154: 
1.609     www      9155: sub startpage {
1.613     www      9156:     my ($r,$symb,$crumbs,$onlyfolderflag,$nodisplayflag) = @_;
1.614     www      9157:     unshift(@$crumbs,{href=>&href_symb_cmd($symb,'gradingmenu'),text=>"Grading"});
1.607     droeschl 9158:     $r->print(&Apache::loncommon::start_page('Grading',undef,
1.610     www      9159:                                           {'bread_crumbs' => $crumbs}));
1.632   ! www      9160:     $r->print('<h3>'.$$crumbs[-1]{'text'}.'</h3>');
1.613     www      9161:     unless ($nodisplayflag) {
                   9162:        $r->print(&Apache::lonhtmlcommon::resource_info_box($symb,$onlyfolderflag));
                   9163:     }
1.607     droeschl 9164: }
1.582     raeburn  9165: 
1.622     www      9166: sub select_problem {
                   9167:     my ($r)=@_;
1.632   ! www      9168:     $r->print('<h3>'.&mt('Select the problem or one of the problems you want to grade').'</h3><form action="/adm/grades">');
1.622     www      9169:     $r->print(&Apache::lonstathelpers::problem_selector('.',undef,1));
                   9170:     $r->print('<input type="hidden" name="command" value="gradingmenu" />');
                   9171:     $r->print('<input type="submit" value="'.&mt('Next').' &rarr;" /></form>');
                   9172: }
                   9173: 
1.1       albertel 9174: sub handler {
1.41      ng       9175:     my $request=$_[0];
1.434     albertel 9176:     &reset_caches();
1.257     albertel 9177:     if ($env{'browser.mathml'}) {
1.141     www      9178: 	&Apache::loncommon::content_type($request,'text/xml');
1.41      ng       9179:     } else {
1.141     www      9180: 	&Apache::loncommon::content_type($request,'text/html');
1.41      ng       9181:     }
                   9182:     $request->send_http_header;
1.44      ng       9183:     return '' if $request->header_only;
1.41      ng       9184:     &Apache::loncommon::get_unprocessed_cgi($ENV{'QUERY_STRING'});
1.608     www      9185: 
                   9186: # see what command we need to execute
                   9187: 
1.160     albertel 9188:     my @commands=&Apache::loncommon::get_env_multiple('form.command');
                   9189:     my $command=$commands[0];
1.447     foxr     9190: 
1.160     albertel 9191:     if ($#commands > 0) {
                   9192: 	&Apache::lonnet::logthis("grades got multiple commands ".join(':',@commands));
                   9193:     }
1.608     www      9194: 
                   9195: # see what the symb is
                   9196: 
                   9197:     my $symb=$env{'form.symb'};
                   9198:     unless ($symb) {
                   9199:        (my $url=$env{'form.url'}) =~ s-^https*://($ENV{'SERVER_NAME'}|$ENV{'HTTP_HOST'})--;
                   9200:        $symb=&Apache::lonnet::symbread($url);
                   9201:     }
                   9202:     &Apache::lonenc::check_decrypt(\$symb);                             
                   9203: 
1.513     foxr     9204:     $ssi_error = 0;
1.622     www      9205:     if ($symb eq '' || $command eq '') {
1.601     www      9206: #
                   9207: # Not called from a resource
                   9208: #    
1.622     www      9209:         &startpage($request,undef,[],1,1);
                   9210:         &select_problem($request);
1.41      ng       9211:     } else {
1.285     albertel 9212: 	&init_perm();
1.104     albertel 9213: 	if ($command eq 'submission' && $perm{'vgr'}) {
1.608     www      9214:             &startpage($request,$symb,[{href=>"", text=>"Student Submissions"}]);
1.611     www      9215: 	    ($env{'form.student'} eq '' ? &listStudents($request,$symb) : &submission($request,0,0,$symb));
1.103     albertel 9216: 	} elsif ($command eq 'pickStudentPage' && $perm{'vgr'}) {
1.615     www      9217:             &startpage($request,$symb,[{href=>&href_symb_cmd($symb,'all_for_one'),text=>'Grade page/folder for one student'},
                   9218:                                        {href=>'',text=>'Select student'}],1,1);
1.608     www      9219: 	    &pickStudentPage($request,$symb);
1.103     albertel 9220: 	} elsif ($command eq 'displayPage' && $perm{'vgr'}) {
1.615     www      9221:             &startpage($request,$symb,
                   9222:                                       [{href=>&href_symb_cmd($symb,'all_for_one'),text=>'Grade page/folder for one student'},
                   9223:                                        {href=>'',text=>'Select student'},
                   9224:                                        {href=>'',text=>'Grade student'}],1,1);
1.608     www      9225: 	    &displayPage($request,$symb);
1.104     albertel 9226: 	} elsif ($command eq 'gradeByPage' && $perm{'mgr'}) {
1.616     www      9227:             &startpage($request,$symb,[{href=>&href_symb_cmd($symb,'all_for_one'),text=>'Grade page/folder for one student'},
                   9228:                                        {href=>'',text=>'Select student'},
                   9229:                                        {href=>'',text=>'Grade student'},
                   9230:                                        {href=>'',text=>'Store grades'}],1,1);
1.608     www      9231: 	    &updateGradeByPage($request,$symb);
1.104     albertel 9232: 	} elsif ($command eq 'processGroup' && $perm{'vgr'}) {
1.619     www      9233:             &startpage($request,$symb,[{href=>'',text=>'...'},
                   9234:                                        {href=>'',text=>'Modify grades'}]);
1.608     www      9235: 	    &processGroup($request,$symb);
1.104     albertel 9236: 	} elsif ($command eq 'gradingmenu' && $perm{'vgr'}) {
1.608     www      9237:             &startpage($request,$symb);
                   9238: 	    $request->print(&grading_menu($request,$symb));
1.598     www      9239: 	} elsif ($command eq 'individual' && $perm{'vgr'}) {
1.617     www      9240:             &startpage($request,$symb,[{href=>'',text=>'Select individual students to grade'}]);
1.608     www      9241: 	    $request->print(&submit_options($request,$symb));
1.598     www      9242:         } elsif ($command eq 'ungraded' && $perm{'vgr'}) {
1.617     www      9243:             &startpage($request,$symb,[{href=>'',text=>'Grade ungraded submissions'}]);
                   9244:             $request->print(&listStudents($request,$symb,'graded'));
1.598     www      9245:         } elsif ($command eq 'table' && $perm{'vgr'}) {
1.614     www      9246:             &startpage($request,$symb,[{href=>"", text=>"Grading table"}]);
1.611     www      9247:             $request->print(&submit_options_table($request,$symb));
1.598     www      9248:         } elsif ($command eq 'all_for_one' && $perm{'vgr'}) {
1.615     www      9249:             &startpage($request,$symb,[{href=>'',text=>'Grade page/folder for one student'}],1,1);
1.608     www      9250:             $request->print(&submit_options_sequence($request,$symb));
1.104     albertel 9251: 	} elsif ($command eq 'viewgrades' && $perm{'vgr'}) {
1.614     www      9252:             &startpage($request,$symb,[{href=>&href_symb_cmd($symb,"table"), text=>"Grading table"},{href=>'', text=>"Modify grades"}]);
1.608     www      9253: 	    $request->print(&viewgrades($request,$symb));
1.104     albertel 9254: 	} elsif ($command eq 'handgrade' && $perm{'mgr'}) {
1.620     www      9255:             &startpage($request,$symb,[{href=>'',text=>'...'},
                   9256:                                        {href=>'',text=>'Store grades'}]);
1.608     www      9257: 	    $request->print(&processHandGrade($request,$symb));
1.106     albertel 9258: 	} elsif ($command eq 'editgrades' && $perm{'mgr'}) {
1.614     www      9259:             &startpage($request,$symb,[{href=>&href_symb_cmd($symb,"table"), text=>"Grading table"},
                   9260:                                        {href=>&href_symb_cmd($symb,'viewgrades').'&group=all&section=all&Status=Active',
                   9261:                                                                              text=>"Modify grades"},
                   9262:                                        {href=>'', text=>"Store grades"}]);
1.608     www      9263: 	    $request->print(&editgrades($request,$symb));
1.602     www      9264:         } elsif ($command eq 'initialverifyreceipt' && $perm{'vgr'}) {
1.616     www      9265:             &startpage($request,$symb,[{href=>'',text=>'Verify Receipt Number'}]);
1.611     www      9266:             $request->print(&initialverifyreceipt($request,$symb));
1.106     albertel 9267: 	} elsif ($command eq 'verify' && $perm{'vgr'}) {
1.616     www      9268:             &startpage($request,$symb,[{href=>&href_symb_cmd($symb,"initialverifyreceipt"),text=>'Verify Receipt Number'},
                   9269:                                        {href=>'',text=>'Verification Result'}]);
1.608     www      9270: 	    $request->print(&verifyreceipt($request,$symb));
1.400     www      9271:         } elsif ($command eq 'processclicker' && $perm{'mgr'}) {
1.615     www      9272:             &startpage($request,$symb,[{href=>'', text=>'Process clicker'}]);
1.608     www      9273:             $request->print(&process_clicker($request,$symb));
1.400     www      9274:         } elsif ($command eq 'processclickerfile' && $perm{'mgr'}) {
1.615     www      9275:             &startpage($request,$symb,[{href=>&href_symb_cmd($symb,'processclicker'), text=>'Process clicker'},
                   9276:                                        {href=>'', text=>'Process clicker file'}]);
1.608     www      9277:             $request->print(&process_clicker_file($request,$symb));
1.414     www      9278:         } elsif ($command eq 'assignclickergrades' && $perm{'mgr'}) {
1.615     www      9279:             &startpage($request,$symb,[{href=>&href_symb_cmd($symb,'processclicker'), text=>'Process clicker'},
                   9280:                                        {href=>'', text=>'Process clicker file'},
                   9281:                                        {href=>'', text=>'Store grades'}]);
1.608     www      9282:             $request->print(&assign_clicker_grades($request,$symb));
1.106     albertel 9283: 	} elsif ($command eq 'csvform' && $perm{'mgr'}) {
1.627     www      9284:             &startpage($request,$symb,[{href=>'', text=>'Upload Scores'}],1,1);
1.608     www      9285: 	    $request->print(&upcsvScores_form($request,$symb));
1.106     albertel 9286: 	} elsif ($command eq 'csvupload' && $perm{'mgr'}) {
1.627     www      9287:             &startpage($request,$symb,[{href=>'', text=>'Upload Scores'}],1,1);
1.608     www      9288: 	    $request->print(&csvupload($request,$symb));
1.106     albertel 9289: 	} elsif ($command eq 'csvuploadmap' && $perm{'mgr'} ) {
1.627     www      9290:             &startpage($request,$symb,[{href=>'', text=>'Upload Scores'}],1,1);
1.608     www      9291: 	    $request->print(&csvuploadmap($request,$symb));
1.246     albertel 9292: 	} elsif ($command eq 'csvuploadoptions' && $perm{'mgr'}) {
1.257     albertel 9293: 	    if ($env{'form.associate'} ne 'Reverse Association') {
1.627     www      9294:                 &startpage($request,$symb,[{href=>'', text=>'Upload Scores'}],1,1);
1.608     www      9295: 		$request->print(&csvuploadoptions($request,$symb));
1.41      ng       9296: 	    } else {
1.257     albertel 9297: 		if ( $env{'form.upfile_associate'} ne 'reverse' ) {
                   9298: 		    $env{'form.upfile_associate'} = 'reverse';
1.41      ng       9299: 		} else {
1.257     albertel 9300: 		    $env{'form.upfile_associate'} = 'forward';
1.41      ng       9301: 		}
1.627     www      9302:                 &startpage($request,$symb,[{href=>'', text=>'Upload Scores'}],1,1);
1.608     www      9303: 		$request->print(&csvuploadmap($request,$symb));
1.41      ng       9304: 	    }
1.246     albertel 9305: 	} elsif ($command eq 'csvuploadassign' && $perm{'mgr'} ) {
1.627     www      9306:             &startpage($request,$symb,[{href=>'', text=>'Upload Scores'}],1,1);
1.608     www      9307: 	    $request->print(&csvuploadassign($request,$symb));
1.106     albertel 9308: 	} elsif ($command eq 'scantron_selectphase' && $perm{'mgr'}) {
1.616     www      9309:             &startpage($request,$symb,[{href=>'', text=>'Grade/Manage/Review Bubblesheets'}],1,1);
1.612     www      9310: 	    $request->print(&scantron_selectphase($request,undef,$symb));
1.203     albertel 9311:  	} elsif ($command eq 'scantron_warning' && $perm{'mgr'}) {
1.616     www      9312:             &startpage($request,$symb,[{href=>'', text=>'Grade/Manage/Review Bubblesheets'}],1,1);
1.608     www      9313:  	    $request->print(&scantron_do_warning($request,$symb));
1.142     albertel 9314: 	} elsif ($command eq 'scantron_validate' && $perm{'mgr'}) {
1.616     www      9315:             &startpage($request,$symb,[{href=>'', text=>'Grade/Manage/Review Bubblesheets'}],1,1);
1.608     www      9316: 	    $request->print(&scantron_validate_file($request,$symb));
1.106     albertel 9317: 	} elsif ($command eq 'scantron_process' && $perm{'mgr'}) {
1.616     www      9318:             &startpage($request,$symb,[{href=>'', text=>'Grade/Manage/Review Bubblesheets'}],1,1);
1.608     www      9319: 	    $request->print(&scantron_process_students($request,$symb));
1.157     albertel 9320:  	} elsif ($command eq 'scantronupload' && 
1.257     albertel 9321:  		 (&Apache::lonnet::allowed('usc',$env{'request.role.domain'})||
                   9322: 		  &Apache::lonnet::allowed('usc',$env{'request.course.id'}))) {
1.616     www      9323:             &startpage($request,$symb,[{href=>'', text=>'Grade/Manage/Review Bubblesheets'}],1,1);
1.608     www      9324:  	    $request->print(&scantron_upload_scantron_data($request,$symb)); 
1.157     albertel 9325:  	} elsif ($command eq 'scantronupload_save' &&
1.257     albertel 9326:  		 (&Apache::lonnet::allowed('usc',$env{'request.role.domain'})||
                   9327: 		  &Apache::lonnet::allowed('usc',$env{'request.course.id'}))) {
1.616     www      9328:             &startpage($request,$symb,[{href=>'', text=>'Grade/Manage/Review Bubblesheets'}],1,1);
1.608     www      9329:  	    $request->print(&scantron_upload_scantron_data_save($request,$symb));
1.202     albertel 9330:  	} elsif ($command eq 'scantron_download' &&
1.257     albertel 9331: 		 &Apache::lonnet::allowed('usc',$env{'request.course.id'})) {
1.616     www      9332:             &startpage($request,$symb,[{href=>'', text=>'Grade/Manage/Review Bubblesheets'}],1,1);
1.608     www      9333:  	    $request->print(&scantron_download_scantron_data($request,$symb));
1.523     raeburn  9334:         } elsif ($command eq 'checksubmissions' && $perm{'vgr'}) {
1.616     www      9335:             &startpage($request,$symb,[{href=>'', text=>'Grade/Manage/Review Bubblesheets'}],1,1);
1.621     www      9336:             $request->print(&checkscantron_results($request,$symb));
                   9337:         } elsif ($command eq 'downloadfilesselect' && $perm{'vgr'}) {
                   9338:             &startpage($request,$symb,[{href=>'', text=>'Select which submissions to download'}]);
                   9339:             $request->print(&submit_options_download($request,$symb));
                   9340:          } elsif ($command eq 'downloadfileslink' && $perm{'vgr'}) {
                   9341:             &startpage($request,$symb,
                   9342:    [{href=>&href_symb_cmd($symb,'downloadfilesselect'), text=>'Select which submissions to download'},
                   9343:     {href=>'', text=>'Download submissions'}]);
                   9344:             &submit_download_link($request,$symb);
1.106     albertel 9345: 	} elsif ($command) {
1.620     www      9346:             &startpage($request,$symb,[{href=>'', text=>'Access denied'}]);
1.562     bisitz   9347: 	    $request->print('<p class="LC_error">'.&mt('Access Denied ([_1])',$command).'</p>');
1.26      albertel 9348: 	}
1.2       albertel 9349:     }
1.513     foxr     9350:     if ($ssi_error) {
                   9351: 	&ssi_print_error($request);
                   9352:     }
1.353     albertel 9353:     $request->print(&Apache::loncommon::end_page());
1.434     albertel 9354:     &reset_caches();
1.44      ng       9355:     return '';
                   9356: }
                   9357: 
1.1       albertel 9358: 1;
                   9359: 
1.13      albertel 9360: __END__;
1.531     jms      9361: 
                   9362: 
                   9363: =head1 NAME
                   9364: 
                   9365: Apache::grades
                   9366: 
                   9367: =head1 SYNOPSIS
                   9368: 
                   9369: Handles the viewing of grades.
                   9370: 
                   9371: This is part of the LearningOnline Network with CAPA project
                   9372: described at http://www.lon-capa.org.
                   9373: 
                   9374: =head1 OVERVIEW
                   9375: 
                   9376: Do an ssi with retries:
                   9377: While I'd love to factor out this with the vesrion in lonprintout,
                   9378: 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
                   9379: I'm not quite ready to invent (e.g. an ssi_with_retry object).
                   9380: 
                   9381: At least the logic that drives this has been pulled out into loncommon.
                   9382: 
                   9383: 
                   9384: 
                   9385: ssi_with_retries - Does the server side include of a resource.
                   9386:                      if the ssi call returns an error we'll retry it up to
                   9387:                      the number of times requested by the caller.
                   9388:                      If we still have a proble, no text is appended to the
                   9389:                      output and we set some global variables.
                   9390:                      to indicate to the caller an SSI error occurred.  
                   9391:                      All of this is supposed to deal with the issues described
                   9392:                      in LonCAPA BZ 5631 see:
                   9393:                      http://bugs.lon-capa.org/show_bug.cgi?id=5631
                   9394:                      by informing the user that this happened.
                   9395: 
                   9396: Parameters:
                   9397:   resource   - The resource to include.  This is passed directly, without
                   9398:                interpretation to lonnet::ssi.
                   9399:   form       - The form hash parameters that guide the interpretation of the resource
                   9400:                
                   9401:   retries    - Number of retries allowed before giving up completely.
                   9402: Returns:
                   9403:   On success, returns the rendered resource identified by the resource parameter.
                   9404: Side Effects:
                   9405:   The following global variables can be set:
                   9406:    ssi_error                - If an unrecoverable error occurred this becomes true.
                   9407:                               It is up to the caller to initialize this to false
                   9408:                               if desired.
                   9409:    ssi_error_resource  - If an unrecoverable error occurred, this is the value
                   9410:                               of the resource that could not be rendered by the ssi
                   9411:                               call.
                   9412:    ssi_error_message   - The error string fetched from the ssi response
                   9413:                               in the event of an error.
                   9414: 
                   9415: 
                   9416: =head1 HANDLER SUBROUTINE
                   9417: 
                   9418: ssi_with_retries()
                   9419: 
                   9420: =head1 SUBROUTINES
                   9421: 
                   9422: =over
                   9423: 
                   9424: =item scantron_get_correction() : 
                   9425: 
                   9426:    Builds the interface screen to interact with the operator to fix a
                   9427:    specific error condition in a specific scanline
                   9428: 
                   9429:  Arguments:
                   9430:     $r           - Apache request object
                   9431:     $i           - number of the current scanline
                   9432:     $scan_record - hash ref as returned from &scantron_parse_scanline()
                   9433:     $scan_config - hash ref as returned from &get_scantron_config()
                   9434:     $line        - full contents of the current scanline
                   9435:     $error       - error condition, valid values are
                   9436:                    'incorrectCODE', 'duplicateCODE',
                   9437:                    'doublebubble', 'missingbubble',
                   9438:                    'duplicateID', 'incorrectID'
                   9439:     $arg         - extra information needed
                   9440:        For errors:
                   9441:          - duplicateID   - paper number that this studentID was seen before on
                   9442:          - duplicateCODE - array ref of the paper numbers this CODE was
                   9443:                            seen on before
                   9444:          - incorrectCODE - current incorrect CODE 
                   9445:          - doublebubble  - array ref of the bubble lines that have double
                   9446:                            bubble errors
                   9447:          - missingbubble - array ref of the bubble lines that have missing
                   9448:                            bubble errors
                   9449: 
                   9450: =item  scantron_get_maxbubble() : 
                   9451: 
1.582     raeburn  9452:    Arguments:
                   9453:        $nav_error  - Reference to scalar which is a flag to indicate a
                   9454:                       failure to retrieve a navmap object.
                   9455:        if $nav_error is set to 1 by scantron_get_maxbubble(), the 
                   9456:        calling routine should trap the error condition and display the warning
                   9457:        found in &navmap_errormsg().
                   9458: 
1.531     jms      9459:    Returns the maximum number of bubble lines that are expected to
                   9460:    occur. Does this by walking the selected sequence rendering the
                   9461:    resource and then checking &Apache::lonxml::get_problem_counter()
                   9462:    for what the current value of the problem counter is.
                   9463: 
                   9464:    Caches the results to $env{'form.scantron_maxbubble'},
                   9465:    $env{'form.scantron.bubble_lines.n'}, 
                   9466:    $env{'form.scantron.first_bubble_line.n'} and
                   9467:    $env{"form.scantron.sub_bubblelines.n"}
                   9468:    which are the total number of bubble, lines, the number of bubble
                   9469:    lines for response n and number of the first bubble line for response n,
                   9470:    and a comma separated list of numbers of bubble lines for sub-questions
                   9471:    (for optionresponse, matchresponse, and rankresponse items), for response n.  
                   9472: 
                   9473: 
                   9474: =item  scantron_validate_missingbubbles() : 
                   9475: 
                   9476:    Validates all scanlines in the selected file to not have any
                   9477:     answers that don't have bubbles that have not been verified
                   9478:     to be bubble free.
                   9479: 
                   9480: =item  scantron_process_students() : 
                   9481: 
                   9482:    Routine that does the actual grading of the bubble sheet information.
                   9483: 
                   9484:    The parsed scanline hash is added to %env 
                   9485: 
                   9486:    Then foreach unskipped scanline it does an &Apache::lonnet::ssi()
                   9487:    foreach resource , with the form data of
                   9488: 
                   9489: 	'submitted'     =>'scantron' 
                   9490: 	'grade_target'  =>'grade',
                   9491: 	'grade_username'=> username of student
                   9492: 	'grade_domain'  => domain of student
                   9493: 	'grade_courseid'=> of course
                   9494: 	'grade_symb'    => symb of resource to grade
                   9495: 
                   9496:     This triggers a grading pass. The problem grading code takes care
                   9497:     of converting the bubbled letter information (now in %env) into a
                   9498:     valid submission.
                   9499: 
                   9500: =item  scantron_upload_scantron_data() :
                   9501: 
                   9502:     Creates the screen for adding a new bubble sheet data file to a course.
                   9503: 
                   9504: =item  scantron_upload_scantron_data_save() : 
                   9505: 
                   9506:    Adds a provided bubble information data file to the course if user
                   9507:    has the correct privileges to do so. 
                   9508: 
                   9509: =item  valid_file() :
                   9510: 
                   9511:    Validates that the requested bubble data file exists in the course.
                   9512: 
                   9513: =item  scantron_download_scantron_data() : 
                   9514: 
                   9515:    Shows a list of the three internal files (original, corrected,
                   9516:    skipped) for a specific bubble sheet data file that exists in the
                   9517:    course.
                   9518: 
                   9519: =item  scantron_validate_ID() : 
                   9520: 
                   9521:    Validates all scanlines in the selected file to not have any
1.556     weissno  9522:    invalid or underspecified student/employee IDs
1.531     jms      9523: 
1.582     raeburn  9524: =item navmap_errormsg() :
                   9525: 
                   9526:    Returns HTML mark-up inside a <div></div> with a link to re-initialize the course.
                   9527:    Should be called whenever the request to instantiate a navmap object fails.  
                   9528: 
1.531     jms      9529: =back
                   9530: 
                   9531: =cut

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