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

1.17      albertel    1: # The LearningOnline Network with CAPA
1.13      albertel    2: # The LON-CAPA Grading handler
1.17      albertel    3: #
1.735   ! raeburn     4: # $Id: grades.pm,v 1.734 2015/03/17 12:22:20 raeburn 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.646     raeburn    43: use Apache::Constants qw(:common :http);
1.167     sakharuk   44: use Apache::lonlocal;
1.386     raeburn    45: use Apache::lonenc;
1.622     www        46: use Apache::lonstathelpers;
1.639     www        47: use Apache::lonquickgrades;
1.657     raeburn    48: use Apache::bridgetask();
1.170     albertel   49: use String::Similarity;
1.359     www        50: use LONCAPA;
                     51: 
1.315     bowersj2   52: use POSIX qw(floor);
1.87      www        53: 
1.435     foxr       54: 
1.513     foxr       55: 
1.435     foxr       56: my %perm=();
1.674     raeburn    57: my %old_essays=();
1.447     foxr       58: 
1.513     foxr       59: #  These variables are used to recover from ssi errors
                     60: 
                     61: my $ssi_retries = 5;
                     62: my $ssi_error;
                     63: my $ssi_error_resource;
                     64: my $ssi_error_message;
                     65: 
                     66: 
                     67: sub ssi_with_retries {
                     68:     my ($resource, $retries, %form) = @_;
                     69:     my ($content, $response) = &Apache::loncommon::ssi_with_retries($resource, $retries, %form);
                     70:     if ($response->is_error) {
                     71: 	$ssi_error          = 1;
                     72: 	$ssi_error_resource = $resource;
                     73: 	$ssi_error_message  = $response->code . " " . $response->message;
                     74:     }
                     75: 
                     76:     return $content;
                     77: 
                     78: }
                     79: #
                     80: #  Prodcuces an ssi retry failure error message to the user:
                     81: #
                     82: 
                     83: sub ssi_print_error {
                     84:     my ($r) = @_;
1.516     raeburn    85:     my $helpurl = &Apache::loncommon::top_nav_help('Helpdesk');
                     86:     $r->print('
                     87: <br />
                     88: <h2>'.&mt('An unrecoverable network error occurred:').'</h2>
                     89: <p>
                     90: '.&mt('Unable to retrieve a resource from a server:').'<br />
                     91: '.&mt('Resource:').' '.$ssi_error_resource.'<br />
                     92: '.&mt('Error:').' '.$ssi_error_message.'
                     93: </p>
                     94: <p>'.
                     95: &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 />'.
                     96: &mt('If the error persists, please contact the [_1] for assistance.',$helpurl).
                     97: '</p>');
                     98:     return;
1.513     foxr       99: }
                    100: 
1.44      ng        101: #
1.146     albertel  102: # --- Retrieve the parts from the metadata file.---
1.598     www       103: # Returns an array of everything that the resources stores away
                    104: #
                    105: 
1.44      ng        106: sub getpartlist {
1.582     raeburn   107:     my ($symb,$errorref) = @_;
1.439     albertel  108: 
                    109:     my $navmap   = Apache::lonnavmaps::navmap->new();
1.582     raeburn   110:     unless (ref($navmap)) {
                    111:         if (ref($errorref)) { 
                    112:             $$errorref = 'navmap';
                    113:             return;
                    114:         }
                    115:     }
1.439     albertel  116:     my $res      = $navmap->getBySymb($symb);
                    117:     my $partlist = $res->parts();
                    118:     my $url      = $res->src();
                    119:     my @metakeys = split(/,/,&Apache::lonnet::metadata($url,'keys'));
                    120: 
1.146     albertel  121:     my @stores;
1.439     albertel  122:     foreach my $part (@{ $partlist }) {
1.146     albertel  123: 	foreach my $key (@metakeys) {
                    124: 	    if ($key =~ m/^stores_\Q$part\E_/) { push(@stores,$key); }
                    125: 	}
                    126:     }
                    127:     return @stores;
1.2       albertel  128: }
                    129: 
1.129     ng        130: #--- Format fullname, username:domain if different for display
                    131: #--- Use anywhere where the student names are listed
                    132: sub nameUserString {
                    133:     my ($type,$fullname,$uname,$udom) = @_;
                    134:     if ($type eq 'header') {
1.485     albertel  135: 	return '<b>&nbsp;'.&mt('Fullname').'&nbsp;</b><span class="LC_internal_info">('.&mt('Username').')</span>';
1.129     ng        136:     } else {
1.398     albertel  137: 	return '&nbsp;'.$fullname.'<span class="LC_internal_info">&nbsp;('.$uname.
                    138: 	    ($env{'user.domain'} eq $udom ? '' : ' ('.$udom.')').')</span>';
1.129     ng        139:     }
                    140: }
                    141: 
1.44      ng        142: #--- Get the partlist and the response type for a given problem. ---
                    143: #--- Indicate if a response type is coded handgraded or not. ---
1.623     www       144: #--- Sets response_error pointer to "1" if navmaps object broken ---
1.39      ng        145: sub response_type {
1.582     raeburn   146:     my ($symb,$response_error) = @_;
1.377     albertel  147: 
                    148:     my $navmap = Apache::lonnavmaps::navmap->new();
1.582     raeburn   149:     unless (ref($navmap)) {
                    150:         if (ref($response_error)) {
                    151:             $$response_error = 1;
                    152:         }
                    153:         return;
                    154:     }
1.377     albertel  155:     my $res = $navmap->getBySymb($symb);
1.593     raeburn   156:     unless (ref($res)) {
                    157:         $$response_error = 1;
                    158:         return;
                    159:     }
1.377     albertel  160:     my $partlist = $res->parts();
1.392     albertel  161:     my %vPart = 
                    162: 	map { $_ => 1 } (&Apache::loncommon::get_env_multiple('form.vPart'));
1.377     albertel  163:     my (%response_types,%handgrade);
                    164:     foreach my $part (@{ $partlist }) {
1.392     albertel  165: 	next if (%vPart && !exists($vPart{$part}));
                    166: 
1.377     albertel  167: 	my @types = $res->responseType($part);
                    168: 	my @ids = $res->responseIds($part);
                    169: 	for (my $i=0; $i < scalar(@ids); $i++) {
                    170: 	    $response_types{$part}{$ids[$i]} = $types[$i];
                    171: 	    $handgrade{$part.'_'.$ids[$i]} = 
                    172: 		&Apache::lonnet::EXT('resource.'.$part.'_'.$ids[$i].
                    173: 				     '.handgrade',$symb);
1.41      ng        174: 	}
                    175:     }
1.377     albertel  176:     return ($partlist,\%handgrade,\%response_types);
1.39      ng        177: }
                    178: 
1.375     albertel  179: sub flatten_responseType {
                    180:     my ($responseType) = @_;
                    181:     my @part_response_id =
                    182: 	map { 
                    183: 	    my $part = $_;
                    184: 	    map {
                    185: 		[$part,$_]
                    186: 		} sort(keys(%{ $responseType->{$part} }));
                    187: 	} sort(keys(%$responseType));
                    188:     return @part_response_id;
                    189: }
                    190: 
1.207     albertel  191: sub get_display_part {
1.324     albertel  192:     my ($partID,$symb)=@_;
1.207     albertel  193:     my $display=&Apache::lonnet::EXT('resource.'.$partID.'.display',$symb);
                    194:     if (defined($display) and $display ne '') {
1.577     bisitz    195:         $display.= ' (<span class="LC_internal_info">'
                    196:                   .&mt('Part ID: [_1]',$partID).'</span>)';
1.207     albertel  197:     } else {
                    198: 	$display=$partID;
                    199:     }
                    200:     return $display;
                    201: }
1.269     raeburn   202: 
1.434     albertel  203: sub reset_caches {
                    204:     &reset_analyze_cache();
                    205:     &reset_perm();
1.674     raeburn   206:     &reset_old_essays();
1.434     albertel  207: }
                    208: 
                    209: {
                    210:     my %analyze_cache;
1.557     raeburn   211:     my %analyze_cache_formkeys;
1.148     albertel  212: 
1.434     albertel  213:     sub reset_analyze_cache {
                    214: 	undef(%analyze_cache);
1.557     raeburn   215:         undef(%analyze_cache_formkeys);
1.434     albertel  216:     }
                    217: 
                    218:     sub get_analyze {
1.649     raeburn   219: 	my ($symb,$uname,$udom,$no_increment,$add_to_hash,$type,$trial,$rndseed,$bubbles_per_row)=@_;
1.434     albertel  220: 	my $key = "$symb\0$uname\0$udom";
1.640     raeburn   221:         if ($type eq 'randomizetry') {
                    222:             if ($trial ne '') {
                    223:                 $key .= "\0".$trial;
                    224:             }
                    225:         }
1.557     raeburn   226: 	if (exists($analyze_cache{$key})) {
                    227:             my $getupdate = 0;
                    228:             if (ref($add_to_hash) eq 'HASH') {
                    229:                 foreach my $item (keys(%{$add_to_hash})) {
                    230:                     if (ref($analyze_cache_formkeys{$key}) eq 'HASH') {
                    231:                         if (!exists($analyze_cache_formkeys{$key}{$item})) {
                    232:                             $getupdate = 1;
                    233:                             last;
                    234:                         }
                    235:                     } else {
                    236:                         $getupdate = 1;
                    237:                     }
                    238:                 }
                    239:             }
                    240:             if (!$getupdate) {
                    241:                 return $analyze_cache{$key};
                    242:             }
                    243:         }
1.434     albertel  244: 
                    245: 	my (undef,undef,$url)=&Apache::lonnet::decode_symb($symb);
                    246: 	$url=&Apache::lonnet::clutter($url);
1.557     raeburn   247:         my %form = ('grade_target'      => 'analyze',
                    248:                     'grade_domain'      => $udom,
                    249:                     'grade_symb'        => $symb,
                    250:                     'grade_courseid'    =>  $env{'request.course.id'},
                    251:                     'grade_username'    => $uname,
                    252:                     'grade_noincrement' => $no_increment);
1.649     raeburn   253:         if ($bubbles_per_row ne '') {
                    254:             $form{'bubbles_per_row'} = $bubbles_per_row;
                    255:         }
1.640     raeburn   256:         if ($type eq 'randomizetry') {
                    257:             $form{'grade_questiontype'} = $type;
                    258:             if ($rndseed ne '') {
                    259:                 $form{'grade_rndseed'} = $rndseed;
                    260:             }
                    261:         }
1.557     raeburn   262:         if (ref($add_to_hash)) {
                    263:             %form = (%form,%{$add_to_hash});
1.640     raeburn   264:         }
1.557     raeburn   265: 	my $subresult=&ssi_with_retries($url, $ssi_retries,%form);
1.434     albertel  266: 	(undef,$subresult)=split(/_HASH_REF__/,$subresult,2);
                    267: 	my %analyze=&Apache::lonnet::str2hash($subresult);
1.557     raeburn   268:         if (ref($add_to_hash) eq 'HASH') {
                    269:             $analyze_cache_formkeys{$key} = $add_to_hash;
                    270:         } else {
                    271:             $analyze_cache_formkeys{$key} = {};
                    272:         }
1.434     albertel  273: 	return $analyze_cache{$key} = \%analyze;
                    274:     }
                    275: 
                    276:     sub get_order {
1.640     raeburn   277: 	my ($partid,$respid,$symb,$uname,$udom,$no_increment,$type,$trial,$rndseed)=@_;
                    278: 	my $analyze = &get_analyze($symb,$uname,$udom,$no_increment,undef,$type,$trial,$rndseed);
1.434     albertel  279: 	return $analyze->{"$partid.$respid.shown"};
                    280:     }
                    281: 
                    282:     sub get_radiobutton_correct_foil {
1.640     raeburn   283: 	my ($partid,$respid,$symb,$uname,$udom,$type,$trial,$rndseed)=@_;
                    284: 	my $analyze = &get_analyze($symb,$uname,$udom,undef,undef,$type,$trial,$rndseed);
                    285:         my $foils = &get_order($partid,$respid,$symb,$uname,$udom,undef,$type,$trial,$rndseed);
1.555     raeburn   286:         if (ref($foils) eq 'ARRAY') {
                    287: 	    foreach my $foil (@{$foils}) {
                    288: 	        if ($analyze->{"$partid.$respid.foil.value.$foil"} eq 'true') {
                    289: 		    return $foil;
                    290: 	        }
1.434     albertel  291: 	    }
                    292: 	}
                    293:     }
1.554     raeburn   294: 
                    295:     sub scantron_partids_tograde {
1.649     raeburn   296:         my ($resource,$cid,$uname,$udom,$check_for_randomlist,$bubbles_per_row) = @_;
1.554     raeburn   297:         my (%analysis,@parts);
                    298:         if (ref($resource)) {
                    299:             my $symb = $resource->symb();
1.557     raeburn   300:             my $add_to_form;
                    301:             if ($check_for_randomlist) {
                    302:                 $add_to_form = { 'check_parts_withrandomlist' => 1,};
                    303:             }
1.649     raeburn   304:             my $analyze = 
                    305:                 &get_analyze($symb,$uname,$udom,undef,$add_to_form,
                    306:                              undef,undef,undef,$bubbles_per_row);
1.554     raeburn   307:             if (ref($analyze) eq 'HASH') {
                    308:                 %analysis = %{$analyze};
                    309:             }
                    310:             if (ref($analysis{'parts'}) eq 'ARRAY') {
                    311:                 foreach my $part (@{$analysis{'parts'}}) {
                    312:                     my ($id,$respid) = split(/\./,$part);
                    313:                     if (!&Apache::loncommon::check_if_partid_hidden($id,$symb,$udom,$uname)) {
                    314:                         push(@parts,$part);
                    315:                     }
                    316:                 }
                    317:             }
                    318:         }
                    319:         return (\%analysis,\@parts);
                    320:     }
                    321: 
1.148     albertel  322: }
1.434     albertel  323: 
1.118     ng        324: #--- Clean response type for display
1.335     albertel  325: #--- Currently filters option/rank/radiobutton/match/essay/Task
                    326: #        response types only.
1.118     ng        327: sub cleanRecord {
1.336     albertel  328:     my ($answer,$response,$symb,$partid,$respid,$record,$order,$version,
1.640     raeburn   329: 	$uname,$udom,$type,$trial,$rndseed) = @_;
1.398     albertel  330:     my $grayFont = '<span class="LC_internal_info">';
1.148     albertel  331:     if ($response =~ /^(option|rank)$/) {
                    332: 	my %answer=&Apache::lonnet::str2hash($answer);
1.720     kruse     333:         my @answer = %answer;
                    334:         %answer = map {&HTML::Entities::encode($_, '"<>&')}  @answer;
1.148     albertel  335: 	my %grading=&Apache::lonnet::str2hash($record->{$version."resource.$partid.$respid.submissiongrading"});
                    336: 	my ($toprow,$bottomrow);
                    337: 	foreach my $foil (@$order) {
                    338: 	    if ($grading{$foil} == 1) {
                    339: 		$toprow.='<td><b>'.$answer{$foil}.'&nbsp;</b></td>';
                    340: 	    } else {
                    341: 		$toprow.='<td><i>'.$answer{$foil}.'&nbsp;</i></td>';
                    342: 	    }
1.398     albertel  343: 	    $bottomrow.='<td>'.$grayFont.$foil.'</span>&nbsp;</td>';
1.148     albertel  344: 	}
                    345: 	return '<blockquote><table border="1">'.
1.466     albertel  346: 	    '<tr valign="top"><td>'.&mt('Answer').'</td>'.$toprow.'</tr>'.
                    347: 	    '<tr valign="top"><td>'.$grayFont.&mt('Option ID').'</span></td>'.
1.660     raeburn   348: 	    $bottomrow.'</tr></table></blockquote>';
1.148     albertel  349:     } elsif ($response eq 'match') {
                    350: 	my %answer=&Apache::lonnet::str2hash($answer);
1.720     kruse     351:         my @answer = %answer;
                    352:         %answer = map {&HTML::Entities::encode($_, '"<>&')}  @answer;
1.148     albertel  353: 	my %grading=&Apache::lonnet::str2hash($record->{$version."resource.$partid.$respid.submissiongrading"});
                    354: 	my @items=&Apache::lonnet::str2array($record->{$version."resource.$partid.$respid.submissionitems"});
                    355: 	my ($toprow,$middlerow,$bottomrow);
                    356: 	foreach my $foil (@$order) {
                    357: 	    my $item=shift(@items);
                    358: 	    if ($grading{$foil} == 1) {
                    359: 		$toprow.='<td><b>'.$item.'&nbsp;</b></td>';
1.398     albertel  360: 		$middlerow.='<td><b>'.$grayFont.$answer{$foil}.'&nbsp;</span></b></td>';
1.148     albertel  361: 	    } else {
                    362: 		$toprow.='<td><i>'.$item.'&nbsp;</i></td>';
1.398     albertel  363: 		$middlerow.='<td><i>'.$grayFont.$answer{$foil}.'&nbsp;</span></i></td>';
1.148     albertel  364: 	    }
1.398     albertel  365: 	    $bottomrow.='<td>'.$grayFont.$foil.'</span>&nbsp;</td>';
1.118     ng        366: 	}
1.126     ng        367: 	return '<blockquote><table border="1">'.
1.466     albertel  368: 	    '<tr valign="top"><td>'.&mt('Answer').'</td>'.$toprow.'</tr>'.
                    369: 	    '<tr valign="top"><td>'.$grayFont.&mt('Item ID').'</span></td>'.
1.148     albertel  370: 	    $middlerow.'</tr>'.
1.466     albertel  371: 	    '<tr valign="top"><td>'.$grayFont.&mt('Option ID').'</span></td>'.
1.660     raeburn   372: 	    $bottomrow.'</tr></table></blockquote>';
1.148     albertel  373:     } elsif ($response eq 'radiobutton') {
                    374: 	my %answer=&Apache::lonnet::str2hash($answer);
1.720     kruse     375:         my @answer = %answer;
                    376:         %answer = map {&HTML::Entities::encode($_, '"<>&')}  @answer;
1.148     albertel  377: 	my ($toprow,$bottomrow);
1.434     albertel  378: 	my $correct = 
1.640     raeburn   379: 	    &get_radiobutton_correct_foil($partid,$respid,$symb,$uname,$udom,$type,$trial,$rndseed);
1.434     albertel  380: 	foreach my $foil (@$order) {
1.148     albertel  381: 	    if (exists($answer{$foil})) {
1.434     albertel  382: 		if ($foil eq $correct) {
1.466     albertel  383: 		    $toprow.='<td><b>'.&mt('true').'</b></td>';
1.148     albertel  384: 		} else {
1.466     albertel  385: 		    $toprow.='<td><i>'.&mt('true').'</i></td>';
1.148     albertel  386: 		}
                    387: 	    } else {
1.466     albertel  388: 		$toprow.='<td>'.&mt('false').'</td>';
1.148     albertel  389: 	    }
1.398     albertel  390: 	    $bottomrow.='<td>'.$grayFont.$foil.'</span>&nbsp;</td>';
1.148     albertel  391: 	}
                    392: 	return '<blockquote><table border="1">'.
1.466     albertel  393: 	    '<tr valign="top"><td>'.&mt('Answer').'</td>'.$toprow.'</tr>'.
                    394: 	    '<tr valign="top"><td>'.$grayFont.&mt('Option ID').'</span></td>'.
1.660     raeburn   395: 	    $bottomrow.'</tr></table></blockquote>';
1.148     albertel  396:     } elsif ($response eq 'essay') {
1.257     albertel  397: 	if (! exists ($env{'form.'.$symb})) {
1.122     ng        398: 	    my (%keyhash) = &Apache::lonnet::dump('nohist_handgrade',
1.257     albertel  399: 						  $env{'course.'.$env{'request.course.id'}.'.domain'},
                    400: 						  $env{'course.'.$env{'request.course.id'}.'.num'});
1.122     ng        401: 
1.257     albertel  402: 	    my $loginuser = $env{'user.name'}.':'.$env{'user.domain'};
                    403: 	    $env{'form.keywords'} = $keyhash{$symb.'_keywords'} ne '' ? $keyhash{$symb.'_keywords'} : '';
                    404: 	    $env{'form.kwclr'}    = $keyhash{$loginuser.'_kwclr'} ne '' ? $keyhash{$loginuser.'_kwclr'} : 'red';
                    405: 	    $env{'form.kwsize'}   = $keyhash{$loginuser.'_kwsize'} ne '' ? $keyhash{$loginuser.'_kwsize'} : '0';
                    406: 	    $env{'form.kwstyle'}  = $keyhash{$loginuser.'_kwstyle'} ne '' ? $keyhash{$loginuser.'_kwstyle'} : '';
                    407: 	    $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        408: 	}
1.730     kruse     409: 	return '<br /><br /><blockquote><tt>'.&keywords_highlight($answer).'</tt></blockquote>';
1.720     kruse     410: 
1.268     albertel  411:     } elsif ( $response eq 'organic') {
1.721     bisitz    412:         my $result=&mt('Smile representation: [_1]',
                    413:                            '"<tt>'.&HTML::Entities::encode($answer, '"<>&').'</tt>"');
1.268     albertel  414: 	my $jme=$record->{$version."resource.$partid.$respid.molecule"};
                    415: 	$result.=&Apache::chemresponse::jme_img($jme,$answer,400);
                    416: 	return $result;
1.335     albertel  417:     } elsif ( $response eq 'Task') {
                    418: 	if ( $answer eq 'SUBMITTED') {
                    419: 	    my $files = $record->{$version."resource.$respid.$partid.bridgetask.portfiles"};
1.336     albertel  420: 	    my $result = &Apache::bridgetask::file_list($files,$uname,$udom);
1.335     albertel  421: 	    return $result;
                    422: 	} elsif ( grep(/^\Q$version\E.*?\.instance$/, keys(%{$record})) ) {
                    423: 	    my @matches = grep(/^\Q$version\E.*?\.instance$/,
                    424: 			       keys(%{$record}));
                    425: 	    return join('<br />',($version,@matches));
                    426: 			       
                    427: 			       
                    428: 	} else {
                    429: 	    my $result =
                    430: 		'<p>'
                    431: 		.&mt('Overall result: [_1]',
                    432: 		     $record->{$version."resource.$respid.$partid.status"})
                    433: 		.'</p>';
                    434: 	    
                    435: 	    $result .= '<ul>';
                    436: 	    my @grade = grep(/^\Q${version}resource.$respid.$partid.\E[^.]*[.]status$/,
                    437: 			     keys(%{$record}));
                    438: 	    foreach my $grade (sort(@grade)) {
                    439: 		my ($dim) = ($grade =~/[.]([^.]+)[.]status$/);
                    440: 		$result.= '<li>'.&mt("Dimension: [_1], status [_2] ",
                    441: 				     $dim, $record->{$grade}).
                    442: 			  '</li>';
                    443: 	    }
                    444: 	    $result.='</ul>';
                    445: 	    return $result;
                    446: 	}
1.716     bisitz    447:     } elsif ( $response =~ m/(?:numerical|formula|custom)/) {
                    448:         # Respect multiple input fields, see Bug #5409
1.440     albertel  449: 	$answer = 
                    450: 	    &Apache::loncommon::format_previous_attempt_value('submission',
                    451: 							      $answer);
1.720     kruse     452: 	return $answer;
1.122     ng        453:     }
1.720     kruse     454:     return &HTML::Entities::encode($answer, '"<>&');
1.118     ng        455: }
                    456: 
                    457: #-- A couple of common js functions
                    458: sub commonJSfunctions {
                    459:     my $request = shift;
1.597     wenzelju  460:     $request->print(&Apache::lonhtmlcommon::scripttag(<<COMMONJSFUNCTIONS));
1.118     ng        461:     function radioSelection(radioButton) {
                    462: 	var selection=null;
                    463: 	if (radioButton.length > 1) {
                    464: 	    for (var i=0; i<radioButton.length; i++) {
                    465: 		if (radioButton[i].checked) {
                    466: 		    return radioButton[i].value;
                    467: 		}
                    468: 	    }
                    469: 	} else {
                    470: 	    if (radioButton.checked) return radioButton.value;
                    471: 	}
                    472: 	return selection;
                    473:     }
                    474: 
                    475:     function pullDownSelection(selectOne) {
                    476: 	var selection="";
                    477: 	if (selectOne.length > 1) {
                    478: 	    for (var i=0; i<selectOne.length; i++) {
                    479: 		if (selectOne[i].selected) {
                    480: 		    return selectOne[i].value;
                    481: 		}
                    482: 	    }
                    483: 	} else {
1.138     albertel  484:             // only one value it must be the selected one
                    485: 	    return selectOne.value;
1.118     ng        486: 	}
                    487:     }
                    488: COMMONJSFUNCTIONS
                    489: }
                    490: 
1.44      ng        491: #--- Dumps the class list with usernames,list of sections,
                    492: #--- section, ids and fullnames for each user.
                    493: sub getclasslist {
1.449     banghart  494:     my ($getsec,$filterlist,$getgroup) = @_;
1.291     albertel  495:     my @getsec;
1.450     banghart  496:     my @getgroup;
1.442     banghart  497:     my $stu_status = join(':',&Apache::loncommon::get_env_multiple('form.Status'));
1.291     albertel  498:     if (!ref($getsec)) {
                    499: 	if ($getsec ne '' && $getsec ne 'all') {
                    500: 	    @getsec=($getsec);
                    501: 	}
                    502:     } else {
                    503: 	@getsec=@{$getsec};
                    504:     }
                    505:     if (grep(/^all$/,@getsec)) { undef(@getsec); }
1.450     banghart  506:     if (!ref($getgroup)) {
                    507: 	if ($getgroup ne '' && $getgroup ne 'all') {
                    508: 	    @getgroup=($getgroup);
                    509: 	}
                    510:     } else {
                    511: 	@getgroup=@{$getgroup};
                    512:     }
                    513:     if (grep(/^all$/,@getgroup)) { undef(@getgroup); }
1.291     albertel  514: 
1.449     banghart  515:     my ($classlist,$keylist)=&Apache::loncoursedata::get_classlist();
1.49      albertel  516:     # Bail out if we were unable to get the classlist
1.56      matthew   517:     return if (! defined($classlist));
1.449     banghart  518:     &Apache::loncoursedata::get_group_memberships($classlist,$keylist);
1.56      matthew   519:     #
                    520:     my %sections;
                    521:     my %fullnames;
1.205     matthew   522:     foreach my $student (keys(%$classlist)) {
                    523:         my $end      = 
                    524:             $classlist->{$student}->[&Apache::loncoursedata::CL_END()];
                    525:         my $start    = 
                    526:             $classlist->{$student}->[&Apache::loncoursedata::CL_START()];
                    527:         my $id       = 
                    528:             $classlist->{$student}->[&Apache::loncoursedata::CL_ID()];
                    529:         my $section  = 
                    530:             $classlist->{$student}->[&Apache::loncoursedata::CL_SECTION()];
                    531:         my $fullname = 
                    532:             $classlist->{$student}->[&Apache::loncoursedata::CL_FULLNAME()];
                    533:         my $status   = 
                    534:             $classlist->{$student}->[&Apache::loncoursedata::CL_STATUS()];
1.449     banghart  535:         my $group   = 
                    536:             $classlist->{$student}->[&Apache::loncoursedata::CL_GROUP()];
1.76      ng        537: 	# filter students according to status selected
1.442     banghart  538: 	if ($filterlist && (!($stu_status =~ /Any/))) {
                    539: 	    if (!($stu_status =~ $status)) {
1.450     banghart  540: 		delete($classlist->{$student});
1.76      ng        541: 		next;
                    542: 	    }
                    543: 	}
1.450     banghart  544: 	# filter students according to groups selected
1.453     banghart  545: 	my @stu_groups = split(/,/,$group);
1.450     banghart  546: 	if (@getgroup) {
                    547: 	    my $exclude = 1;
1.454     banghart  548: 	    foreach my $grp (@getgroup) {
                    549: 	        foreach my $stu_group (@stu_groups) {
1.453     banghart  550: 	            if ($stu_group eq $grp) {
                    551: 	                $exclude = 0;
                    552:     	            } 
1.450     banghart  553: 	        }
1.453     banghart  554:     	        if (($grp eq 'none') && !$group) {
                    555:         	        $exclude = 0;
                    556:         	}
1.450     banghart  557: 	    }
                    558: 	    if ($exclude) {
                    559: 	        delete($classlist->{$student});
                    560: 	    }
                    561: 	}
1.205     matthew   562: 	$section = ($section ne '' ? $section : 'none');
1.106     albertel  563: 	if (&canview($section)) {
1.291     albertel  564: 	    if (!@getsec || grep(/^\Q$section\E$/,@getsec)) {
1.103     albertel  565: 		$sections{$section}++;
1.450     banghart  566: 		if ($classlist->{$student}) {
                    567: 		    $fullnames{$student}=$fullname;
                    568: 		}
1.103     albertel  569: 	    } else {
1.205     matthew   570: 		delete($classlist->{$student});
1.103     albertel  571: 	    }
                    572: 	} else {
1.205     matthew   573: 	    delete($classlist->{$student});
1.103     albertel  574: 	}
1.44      ng        575:     }
                    576:     my %seen = ();
1.56      matthew   577:     my @sections = sort(keys(%sections));
                    578:     return ($classlist,\@sections,\%fullnames);
1.44      ng        579: }
                    580: 
1.103     albertel  581: sub canmodify {
                    582:     my ($sec)=@_;
                    583:     if ($perm{'mgr'}) {
                    584: 	if (!defined($perm{'mgr_section'})) {
                    585: 	    # can modify whole class
                    586: 	    return 1;
                    587: 	} else {
                    588: 	    if ($sec eq $perm{'mgr_section'}) {
                    589: 		#can modify the requested section
                    590: 		return 1;
                    591: 	    } else {
                    592: 		# can't modify the request section
                    593: 		return 0;
                    594: 	    }
                    595: 	}
                    596:     }
                    597:     #can't modify
                    598:     return 0;
                    599: }
                    600: 
                    601: sub canview {
                    602:     my ($sec)=@_;
                    603:     if ($perm{'vgr'}) {
                    604: 	if (!defined($perm{'vgr_section'})) {
                    605: 	    # can modify whole class
                    606: 	    return 1;
                    607: 	} else {
                    608: 	    if ($sec eq $perm{'vgr_section'}) {
                    609: 		#can modify the requested section
                    610: 		return 1;
                    611: 	    } else {
                    612: 		# can't modify the request section
                    613: 		return 0;
                    614: 	    }
                    615: 	}
                    616:     }
                    617:     #can't modify
                    618:     return 0;
                    619: }
                    620: 
1.44      ng        621: #--- Retrieve the grade status of a student for all the parts
                    622: sub student_gradeStatus {
1.324     albertel  623:     my ($symb,$udom,$uname,$partlist) = @_;
1.257     albertel  624:     my %record     = &Apache::lonnet::restore($symb,$env{'request.course.id'},$udom,$uname);
1.44      ng        625:     my %partstatus = ();
                    626:     foreach (@$partlist) {
1.128     ng        627: 	my ($status,undef)   = split(/_/,$record{"resource.$_.solved"},2);
1.44      ng        628: 	$status              = 'nothing' if ($status eq '');
                    629: 	$partstatus{$_}      = $status;
                    630: 	my $subkey           = "resource.$_.submitted_by";
                    631: 	$partstatus{$subkey} = $record{$subkey} if ($record{$subkey} ne '');
                    632:     }
                    633:     return %partstatus;
                    634: }
                    635: 
1.45      ng        636: # hidden form and javascript that calls the form
                    637: # Use by verifyscript and viewgrades
                    638: # Shows a student's view of problem and submission
                    639: sub jscriptNform {
1.324     albertel  640:     my ($symb) = @_;
1.442     banghart  641:     my $stu_status = join(':',&Apache::loncommon::get_env_multiple('form.Status'));
1.597     wenzelju  642:     my $jscript= &Apache::lonhtmlcommon::scripttag(
1.45      ng        643: 	'    function viewOneStudent(user,domain) {'."\n".
                    644: 	'	document.onestudent.student.value = user;'."\n".
                    645: 	'	document.onestudent.userdom.value = domain;'."\n".
                    646: 	'	document.onestudent.submit();'."\n".
                    647: 	'    }'."\n".
1.597     wenzelju  648: 	"\n");
1.45      ng        649:     $jscript.= '<form action="/adm/grades" method="post" name="onestudent">'."\n".
1.418     albertel  650: 	'<input type="hidden" name="symb"    value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
1.442     banghart  651: 	'<input type="hidden" name="Status"  value="'.$stu_status.'" />'."\n".
1.45      ng        652: 	'<input type="hidden" name="command" value="submission" />'."\n".
                    653: 	'<input type="hidden" name="student" value="" />'."\n".
                    654: 	'<input type="hidden" name="userdom" value="" />'."\n".
                    655: 	'</form>'."\n";
                    656:     return $jscript;
                    657: }
1.39      ng        658: 
1.447     foxr      659: 
                    660: 
1.315     bowersj2  661: # Given the score (as a number [0-1] and the weight) what is the final
                    662: # point value? This function will round to the nearest tenth, third,
                    663: # or quarter if one of those is within the tolerance of .00001.
1.316     albertel  664: sub compute_points {
1.315     bowersj2  665:     my ($score, $weight) = @_;
                    666:     
                    667:     my $tolerance = .00001;
                    668:     my $points = $score * $weight;
                    669: 
                    670:     # Check for nearness to 1/x.
                    671:     my $check_for_nearness = sub {
                    672:         my ($factor) = @_;
                    673:         my $num = ($points * $factor) + $tolerance;
                    674:         my $floored_num = floor($num);
1.316     albertel  675:         if ($num - $floored_num < 2 * $tolerance * $factor) {
1.315     bowersj2  676:             return $floored_num / $factor;
                    677:         }
                    678:         return $points;
                    679:     };
                    680: 
                    681:     $points = $check_for_nearness->(10);
                    682:     $points = $check_for_nearness->(3);
                    683:     $points = $check_for_nearness->(4);
                    684:     
                    685:     return $points;
                    686: }
                    687: 
1.44      ng        688: #------------------ End of general use routines --------------------
1.87      www       689: 
                    690: #
                    691: # Find most similar essay
                    692: #
                    693: 
                    694: sub most_similar {
1.674     raeburn   695:     my ($uname,$udom,$symb,$uessay)=@_;
                    696: 
                    697:     unless ($symb) { return ''; }
                    698: 
                    699:     unless (ref($old_essays{$symb}) eq 'HASH') { return ''; }
1.87      www       700: 
                    701: # ignore spaces and punctuation
                    702: 
                    703:     $uessay=~s/\W+/ /gs;
                    704: 
1.282     www       705: # ignore empty submissions (occuring when only files are sent)
                    706: 
1.598     www       707:     unless ($uessay=~/\w+/s) { return ''; }
1.282     www       708: 
1.87      www       709: # these will be returned. Do not care if not at least 50 percent similar
1.88      www       710:     my $limit=0.6;
1.87      www       711:     my $sname='';
                    712:     my $sdom='';
                    713:     my $scrsid='';
                    714:     my $sessay='';
                    715: # go through all essays ...
1.674     raeburn   716:     foreach my $tkey (keys(%{$old_essays{$symb}})) {
1.426     albertel  717: 	my ($tname,$tdom,$tcrsid)=map {&unescape($_)} (split(/\./,$tkey));
1.87      www       718: # ... except the same student
1.426     albertel  719:         next if (($tname eq $uname) && ($tdom eq $udom));
1.674     raeburn   720: 	my $tessay=$old_essays{$symb}{$tkey};
1.426     albertel  721: 	$tessay=~s/\W+/ /gs;
1.87      www       722: # String similarity gives up if not even limit
1.426     albertel  723: 	my $tsimilar=&String::Similarity::similarity($uessay,$tessay,$limit);
1.87      www       724: # Found one
1.426     albertel  725: 	if ($tsimilar>$limit) {
                    726: 	    $limit=$tsimilar;
                    727: 	    $sname=$tname;
                    728: 	    $sdom=$tdom;
                    729: 	    $scrsid=$tcrsid;
1.674     raeburn   730: 	    $sessay=$old_essays{$symb}{$tkey};
1.426     albertel  731: 	}
1.87      www       732:     }
1.88      www       733:     if ($limit>0.6) {
1.87      www       734:        return ($sname,$sdom,$scrsid,$sessay,$limit);
                    735:     } else {
                    736:        return ('','','','',0);
                    737:     }
                    738: }
                    739: 
1.44      ng        740: #-------------------------------------------------------------------
                    741: 
                    742: #------------------------------------ Receipt Verification Routines
1.45      ng        743: #
1.602     www       744: 
                    745: sub initialverifyreceipt {
1.608     www       746:    my ($request,$symb) = @_;
1.602     www       747:    &commonJSfunctions($request);
1.694     bisitz    748:    return '<form name="gradingMenu" action=""><input type="submit" value="'.&mt('Verify Receipt Number.').'" />'.
1.602     www       749:         &Apache::lonnet::recprefix($env{'request.course.id'}).
                    750:         '-<input type="text" name="receipt" size="4" />'.
1.603     www       751:         '<input type="hidden" name="symb" value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
                    752:         '<input type="hidden" name="command" value="verify" />'.
                    753:         "</form>\n";
1.602     www       754: }
                    755: 
1.44      ng        756: #--- Check whether a receipt number is valid.---
                    757: sub verifyreceipt {
1.608     www       758:     my ($request,$symb)  = @_;
1.44      ng        759: 
1.257     albertel  760:     my $courseid = $env{'request.course.id'};
1.184     www       761:     my $receipt  = &Apache::lonnet::recprefix($courseid).'-'.
1.257     albertel  762: 	$env{'form.receipt'};
1.44      ng        763:     $receipt     =~ s/[^\-\d]//g;
                    764: 
1.487     albertel  765:     my $title.=
                    766: 	'<h3><span class="LC_info">'.
1.605     www       767: 	&mt('Verifying Receipt Number [_1]',$receipt).
                    768: 	'</span></h3>'."\n";
1.44      ng        769: 
                    770:     my ($string,$contents,$matches) = ('','',0);
1.56      matthew   771:     my (undef,undef,$fullname) = &getclasslist('all','0');
1.177     albertel  772:     
                    773:     my $receiptparts=0;
1.390     albertel  774:     if ($env{"course.$courseid.receiptalg"} eq 'receipt2' ||
                    775: 	$env{"course.$courseid.receiptalg"} eq 'receipt3') { $receiptparts=1; }
1.177     albertel  776:     my $parts=['0'];
1.582     raeburn   777:     if ($receiptparts) {
                    778:         my $res_error; 
                    779:         ($parts)=&response_type($symb,\$res_error);
                    780:         if ($res_error) {
                    781:             return &navmap_errormsg();
                    782:         } 
                    783:     }
1.486     albertel  784:     
                    785:     my $header = 
                    786: 	&Apache::loncommon::start_data_table().
                    787: 	&Apache::loncommon::start_data_table_header_row().
1.487     albertel  788: 	'<th>&nbsp;'.&mt('Fullname').'&nbsp;</th>'."\n".
                    789: 	'<th>&nbsp;'.&mt('Username').'&nbsp;</th>'."\n".
                    790: 	'<th>&nbsp;'.&mt('Domain').'&nbsp;</th>';
1.486     albertel  791:     if ($receiptparts) {
1.487     albertel  792: 	$header.='<th>&nbsp;'.&mt('Problem Part').'&nbsp;</th>';
1.486     albertel  793:     }
                    794:     $header.=
                    795: 	&Apache::loncommon::end_data_table_header_row();
                    796: 
1.294     albertel  797:     foreach (sort 
                    798: 	     {
                    799: 		 if (lc($$fullname{$a}) ne lc($$fullname{$b})) {
                    800: 		     return (lc($$fullname{$a}) cmp lc($$fullname{$b}));
                    801: 		 }
                    802: 		 return $a cmp $b;
                    803: 	     } (keys(%$fullname))) {
1.44      ng        804: 	my ($uname,$udom)=split(/\:/);
1.177     albertel  805: 	foreach my $part (@$parts) {
                    806: 	    if ($receipt eq &Apache::lonnet::ireceipt($uname,$udom,$courseid,$symb,$part)) {
1.486     albertel  807: 		$contents.=
                    808: 		    &Apache::loncommon::start_data_table_row().
                    809: 		    '<td>&nbsp;'."\n".
1.177     albertel  810: 		    '<a href="javascript:viewOneStudent(\''.$uname.'\',\''.$udom.
1.417     albertel  811: 		    '\');" target="_self">'.$$fullname{$_}.'</a>&nbsp;</td>'."\n".
1.177     albertel  812: 		    '<td>&nbsp;'.$uname.'&nbsp;</td>'.
                    813: 		    '<td>&nbsp;'.$udom.'&nbsp;</td>';
                    814: 		if ($receiptparts) {
                    815: 		    $contents.='<td>&nbsp;'.$part.'&nbsp;</td>';
                    816: 		}
1.486     albertel  817: 		$contents.= 
                    818: 		    &Apache::loncommon::end_data_table_row()."\n";
1.177     albertel  819: 		
                    820: 		$matches++;
                    821: 	    }
1.44      ng        822: 	}
                    823:     }
                    824:     if ($matches == 0) {
1.584     bisitz    825:         $string = $title
                    826:                  .'<p class="LC_warning">'
                    827:                  .&mt('No match found for the above receipt number.')
                    828:                  .'</p>';
1.44      ng        829:     } else {
1.324     albertel  830: 	$string = &jscriptNform($symb).$title.
1.487     albertel  831: 	    '<p>'.
1.584     bisitz    832: 	    &mt('The above receipt number matches the following [quant,_1,student].',$matches).
1.487     albertel  833: 	    '</p>'.
1.486     albertel  834: 	    $header.
                    835: 	    $contents.
                    836: 	    &Apache::loncommon::end_data_table()."\n";
1.44      ng        837:     }
1.614     www       838:     return $string;
1.44      ng        839: }
                    840: 
                    841: #--- This is called by a number of programs.
                    842: #--- Called from the Grading Menu - View/Grade an individual student
                    843: #--- Also called directly when one clicks on the subm button 
                    844: #    on the problem page.
1.30      ng        845: sub listStudents {
1.617     www       846:     my ($request,$symb,$submitonly) = @_;
1.49      albertel  847: 
1.257     albertel  848:     my $cdom      = $env{"course.$env{'request.course.id'}.domain"};
                    849:     my $cnum      = $env{"course.$env{'request.course.id'}.num"};
                    850:     my $getsec    = $env{'form.section'} eq '' ? 'all' : $env{'form.section'};
1.449     banghart  851:     my $getgroup  = $env{'form.group'} eq '' ? 'all' : $env{'form.group'};
1.617     www       852:     unless ($submitonly) {
                    853:        $submitonly= $env{'form.submitonly'} eq '' ? 'all' : $env{'form.submitonly'};
                    854:     }
1.49      albertel  855: 
1.632     www       856:     my $result='';
1.623     www       857:     my $res_error;
                    858:     my ($partlist,$handgrade,$responseType) = &response_type($symb,\$res_error);
1.49      albertel  859: 
1.559     raeburn   860:     my %lt = &Apache::lonlocal::texthash (
                    861: 		'multiple' => 'Please select a student or group of students before clicking on the Next button.',
                    862: 		'single'   => 'Please select the student before clicking on the Next button.',
                    863: 	     );
1.597     wenzelju  864:     $request->print(&Apache::lonhtmlcommon::scripttag(<<LISTJAVASCRIPT));
1.110     ng        865:     function checkSelect(checkBox) {
                    866: 	var ctr=0;
                    867: 	var sense="";
                    868: 	if (checkBox.length > 1) {
                    869: 	    for (var i=0; i<checkBox.length; i++) {
                    870: 		if (checkBox[i].checked) {
                    871: 		    ctr++;
                    872: 		}
                    873: 	    }
1.485     albertel  874: 	    sense = '$lt{'multiple'}';
1.110     ng        875: 	} else {
                    876: 	    if (checkBox.checked) {
                    877: 		ctr = 1;
                    878: 	    }
1.485     albertel  879: 	    sense = '$lt{'single'}';
1.110     ng        880: 	}
                    881: 	if (ctr == 0) {
1.485     albertel  882: 	    alert(sense);
1.110     ng        883: 	    return false;
                    884: 	}
                    885: 	document.gradesub.submit();
                    886:     }
                    887: 
                    888:     function reLoadList(formname) {
1.112     ng        889: 	if (formname.saveStatusOld.value == pullDownSelection(formname.Status)) {return;}
1.110     ng        890: 	formname.command.value = 'submission';
                    891: 	formname.submit();
                    892:     }
1.45      ng        893: LISTJAVASCRIPT
                    894: 
1.118     ng        895:     &commonJSfunctions($request);
1.41      ng        896:     $request->print($result);
1.39      ng        897: 
1.154     albertel  898:     my $gradeTable='<form action="/adm/grades" method="post" name="gradesub">'.
1.598     www       899: 	"\n";
1.485     albertel  900: 	
1.561     bisitz    901:     $gradeTable .= &Apache::lonhtmlcommon::start_pick_box();
                    902:     $gradeTable .= &Apache::lonhtmlcommon::row_title(&mt('View Problem Text'))
                    903:                   .'<label><input type="radio" name="vProb" value="no" checked="checked" /> '.&mt('no').' </label>'."\n"
                    904:                   .'<label><input type="radio" name="vProb" value="yes" /> '.&mt('one student').' </label>'."\n"
                    905:                   .'<label><input type="radio" name="vProb" value="all" /> '.&mt('all students').' </label><br />'."\n"
                    906:                   .&Apache::lonhtmlcommon::row_closure();
                    907:     $gradeTable .= &Apache::lonhtmlcommon::row_title(&mt('View Answer'))
                    908:                   .'<label><input type="radio" name="vAns" value="no"  /> '.&mt('no').' </label>'."\n"
                    909:                   .'<label><input type="radio" name="vAns" value="yes" /> '.&mt('one student').' </label>'."\n"
                    910:                   .'<label><input type="radio" name="vAns" value="all" checked="checked" /> '.&mt('all students').' </label><br />'."\n"
                    911:                   .&Apache::lonhtmlcommon::row_closure();
1.485     albertel  912: 
                    913:     my $submission_options;
1.442     banghart  914:     my $stu_status = join(':',&Apache::loncommon::get_env_multiple('form.Status'));
                    915:     my $saveStatus = $stu_status eq '' ? 'Active' : $stu_status;
1.257     albertel  916:     $env{'form.Status'} = $saveStatus;
1.485     albertel  917:     $submission_options.=
1.592     bisitz    918:         '<span class="LC_nobreak">'.
1.624     www       919:         '<label><input type="radio" name="lastSub" value="lastonly" /> '.
1.699     kruse     920:         &mt('last submission').' </label></span>'."\n".
1.592     bisitz    921:         '<span class="LC_nobreak">'.
                    922:         '<label><input type="radio" name="lastSub" value="last" /> '.
1.699     kruse     923:         &mt('last submission with details').' </label></span>'."\n".
1.592     bisitz    924:         '<span class="LC_nobreak">'.
1.628     www       925:         '<label><input type="radio" name="lastSub" value="datesub" checked="checked" /> '.
1.699     kruse     926:         &mt('all submissions').'</label></span>'."\n".
1.592     bisitz    927:         '<span class="LC_nobreak">'.
                    928:         '<label><input type="radio" name="lastSub" value="all" /> '.
1.699     kruse     929:         &mt('all submissions with details').'</label></span>';
                    930:     $gradeTable .= &Apache::lonhtmlcommon::row_title(&mt('View Submissions'))
1.561     bisitz    931:                   .$submission_options
                    932:                   .&Apache::lonhtmlcommon::row_closure();
                    933: 
                    934:     $gradeTable .= &Apache::lonhtmlcommon::row_title(&mt('Grading Increments'))
                    935:                   .'<select name="increment">'
                    936:                   .'<option value="1">'.&mt('Whole Points').'</option>'
                    937:                   .'<option value=".5">'.&mt('Half Points').'</option>'
                    938:                   .'<option value=".25">'.&mt('Quarter Points').'</option>'
                    939:                   .'<option value=".1">'.&mt('Tenths of a Point').'</option>'
                    940:                   .'</select>'
                    941:                   .&Apache::lonhtmlcommon::row_closure();
1.485     albertel  942: 
                    943:     $gradeTable .= 
1.432     banghart  944:         &build_section_inputs().
1.45      ng        945: 	'<input type="hidden" name="submitonly"  value="'.$submitonly.'" />'."\n".
1.418     albertel  946: 	'<input type="hidden" name="symb" value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
1.110     ng        947: 	'<input type="hidden" name="saveStatusOld" value="'.$saveStatus.'" />'."\n";
                    948: 
1.618     www       949:     if (exists($env{'form.Status'})) {
1.561     bisitz    950: 	$gradeTable .= '<input type="hidden" name="Status" value="'.$stu_status.'" />'."\n";
1.124     ng        951:     } else {
1.561     bisitz    952:         $gradeTable .= &Apache::lonhtmlcommon::row_title(&mt('Student Status'))
                    953:                       .&Apache::lonhtmlcommon::StatusOptions(
                    954:                            $saveStatus,undef,1,'javascript:reLoadList(this.form);')
                    955:                       .&Apache::lonhtmlcommon::row_closure();
1.124     ng        956:     }
1.112     ng        957: 
1.561     bisitz    958:     $gradeTable .= &Apache::lonhtmlcommon::row_title(&mt('Check For Plagiarism'))
                    959:                   .'<input type="checkbox" name="checkPlag" checked="checked" />'
                    960:                   .&Apache::lonhtmlcommon::row_closure(1)
                    961:                   .&Apache::lonhtmlcommon::end_pick_box();
                    962: 
                    963:     $gradeTable .= '<p>'
1.618     www       964:                   .&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    965:                   .'<input type="hidden" name="command" value="processGroup" />'
                    966:                   .'</p>';
1.249     albertel  967: 
                    968: # checkall buttons
                    969:     $gradeTable.=&check_script('gradesub', 'stuinfo');
1.110     ng        970:     $gradeTable.='<input type="button" '."\n".
1.589     bisitz    971:         'onclick="javascript:checkSelect(this.form.stuinfo);" '."\n".
                    972:         'value="'.&mt('Next').' &rarr;" /> <br />'."\n";
1.249     albertel  973:     $gradeTable.=&check_buttons();
1.450     banghart  974:     my ($classlist, undef, $fullname) = &getclasslist($getsec,'1',$getgroup);
1.474     albertel  975:     $gradeTable.= &Apache::loncommon::start_data_table().
                    976: 	&Apache::loncommon::start_data_table_header_row();
1.110     ng        977:     my $loop = 0;
                    978:     while ($loop < 2) {
1.485     albertel  979: 	$gradeTable.='<th>'.&mt('No.').'</th><th>'.&mt('Select').'</th>'.
                    980: 	    '<th>'.&nameUserString('header').'&nbsp;'.&mt('Section/Group').'</th>';
1.618     www       981: 	if (($submitonly ne 'queued') && ($submitonly ne 'all')) {
1.485     albertel  982: 	    foreach my $part (sort(@$partlist)) {
                    983: 		my $display_part=
                    984: 		    &get_display_part((split(/_/,$part))[0],$symb);
                    985: 		$gradeTable.=
                    986: 		    '<th>'.&mt('Part: [_1] Status',$display_part).'</th>';
1.110     ng        987: 	    }
1.301     albertel  988: 	} elsif ($submitonly eq 'queued') {
1.474     albertel  989: 	    $gradeTable.='<th>'.&mt('Queue Status').'&nbsp;</th>';
1.110     ng        990: 	}
                    991: 	$loop++;
1.126     ng        992: #	$gradeTable.='<td></td>' if ($loop%2 ==1);
1.41      ng        993:     }
1.474     albertel  994:     $gradeTable.=&Apache::loncommon::end_data_table_header_row()."\n";
1.41      ng        995: 
1.45      ng        996:     my $ctr = 0;
1.294     albertel  997:     foreach my $student (sort 
                    998: 			 {
                    999: 			     if (lc($$fullname{$a}) ne lc($$fullname{$b})) {
                   1000: 				 return (lc($$fullname{$a}) cmp lc($$fullname{$b}));
                   1001: 			     }
                   1002: 			     return $a cmp $b;
                   1003: 			 }
                   1004: 			 (keys(%$fullname))) {
1.41      ng       1005: 	my ($uname,$udom) = split(/:/,$student);
1.301     albertel 1006: 
1.110     ng       1007: 	my %status = ();
1.301     albertel 1008: 
                   1009: 	if ($submitonly eq 'queued') {
                   1010: 	    my %queue_status = 
                   1011: 		&Apache::bridgetask::get_student_status($symb,$cdom,$cnum,
                   1012: 							$udom,$uname);
                   1013: 	    next if (!defined($queue_status{'gradingqueue'}));
                   1014: 	    $status{'gradingqueue'} = $queue_status{'gradingqueue'};
                   1015: 	}
                   1016: 
1.618     www      1017: 	if (($submitonly ne 'queued') && ($submitonly ne 'all')) {
1.324     albertel 1018: 	    (%status) =&student_gradeStatus($symb,$udom,$uname,$partlist);
1.145     albertel 1019: 	    my $submitted = 0;
1.164     albertel 1020: 	    my $graded = 0;
1.248     albertel 1021: 	    my $incorrect = 0;
1.110     ng       1022: 	    foreach (keys(%status)) {
1.145     albertel 1023: 		$submitted = 1 if ($status{$_} ne 'nothing');
1.248     albertel 1024: 		$graded = 1 if ($status{$_} =~ /^ungraded/);
                   1025: 		$incorrect = 1 if ($status{$_} =~ /^incorrect/);
                   1026: 		
1.110     ng       1027: 		my ($foo,$partid,$foo1) = split(/\./,$_);
                   1028: 		if ($status{'resource.'.$partid.'.submitted_by'} ne '') {
1.145     albertel 1029: 		    $submitted = 0;
1.150     albertel 1030: 		    my ($part)=split(/\./,$partid);
1.110     ng       1031: 		    $gradeTable.='<input type="hidden" name="'.
1.150     albertel 1032: 			$student.':'.$part.':submitted_by" value="'.
1.110     ng       1033: 			$status{'resource.'.$partid.'.submitted_by'}.'" />';
                   1034: 		}
1.41      ng       1035: 	    }
1.248     albertel 1036: 	    
1.156     albertel 1037: 	    next if (!$submitted && ($submitonly eq 'yes' ||
                   1038: 				     $submitonly eq 'incorrect' ||
                   1039: 				     $submitonly eq 'graded'));
1.248     albertel 1040: 	    next if (!$graded && ($submitonly eq 'graded'));
                   1041: 	    next if (!$incorrect && $submitonly eq 'incorrect');
1.41      ng       1042: 	}
1.34      ng       1043: 
1.45      ng       1044: 	$ctr++;
1.249     albertel 1045: 	my $section = $classlist->{$student}->[&Apache::loncoursedata::CL_SECTION()];
1.452     banghart 1046:         my $group = $classlist->{$student}->[&Apache::loncoursedata::CL_GROUP()];
1.104     albertel 1047: 	if ( $perm{'vgr'} eq 'F' ) {
1.474     albertel 1048: 	    if ($ctr%2 ==1) {
                   1049: 		$gradeTable.= &Apache::loncommon::start_data_table_row();
                   1050: 	    }
1.126     ng       1051: 	    $gradeTable.='<td align="right">'.$ctr.'&nbsp;</td>'.
1.563     bisitz   1052:                '<td align="center"><label><input type="checkbox" name="stuinfo" value="'.
1.249     albertel 1053:                $student.':'.$$fullname{$student}.':::SECTION'.$section.
                   1054: 	       ')&nbsp;" />&nbsp;&nbsp;</label></td>'."\n".'<td>'.
                   1055: 	       &nameUserString(undef,$$fullname{$student},$uname,$udom).
1.474     albertel 1056: 	       '&nbsp;'.$section.($group ne '' ?'/'.$group:'').'</td>'."\n";
1.110     ng       1057: 
1.618     www      1058: 	    if ($submitonly ne 'all') {
1.524     raeburn  1059: 		foreach (sort(keys(%status))) {
1.485     albertel 1060: 		    next if ($_ =~ /^resource.*?submitted_by$/);
                   1061: 		    $gradeTable.='<td align="center">&nbsp;'.&mt($status{$_}).'&nbsp;</td>'."\n";
1.110     ng       1062: 		}
1.41      ng       1063: 	    }
1.126     ng       1064: #	    $gradeTable.='<td></td>' if ($ctr%2 ==1);
1.474     albertel 1065: 	    if ($ctr%2 ==0) {
                   1066: 		$gradeTable.=&Apache::loncommon::end_data_table_row()."\n";
                   1067: 	    }
1.41      ng       1068: 	}
                   1069:     }
1.110     ng       1070:     if ($ctr%2 ==1) {
1.126     ng       1071: 	$gradeTable.='<td>&nbsp;</td><td>&nbsp;</td><td>&nbsp;</td>';
1.618     www      1072: 	    if (($submitonly ne 'queued') && ($submitonly ne 'all')) {
1.110     ng       1073: 		foreach (@$partlist) {
                   1074: 		    $gradeTable.='<td>&nbsp;</td>';
                   1075: 		}
1.301     albertel 1076: 	    } elsif ($submitonly eq 'queued') {
                   1077: 		$gradeTable.='<td>&nbsp;</td>';
1.110     ng       1078: 	    }
1.474     albertel 1079: 	$gradeTable.=&Apache::loncommon::end_data_table_row();
1.110     ng       1080:     }
                   1081: 
1.474     albertel 1082:     $gradeTable.=&Apache::loncommon::end_data_table()."\n".
1.589     bisitz   1083:         '<input type="button" '.
                   1084:         'onclick="javascript:checkSelect(this.form.stuinfo);" '.
                   1085:         'value="'.&mt('Next').' &rarr;" /></form>'."\n";
1.45      ng       1086:     if ($ctr == 0) {
1.96      albertel 1087: 	my $num_students=(scalar(keys(%$fullname)));
                   1088: 	if ($num_students eq 0) {
1.485     albertel 1089: 	    $gradeTable='<br />&nbsp;<span class="LC_warning">'.&mt('There are no students currently enrolled.').'</span>';
1.96      albertel 1090: 	} else {
1.171     albertel 1091: 	    my $submissions='submissions';
                   1092: 	    if ($submitonly eq 'incorrect') { $submissions = 'incorrect submissions'; }
                   1093: 	    if ($submitonly eq 'graded'   ) { $submissions = 'ungraded submissions'; }
1.301     albertel 1094: 	    if ($submitonly eq 'queued'   ) { $submissions = 'queued submissions'; }
1.398     albertel 1095: 	    $gradeTable='<br />&nbsp;<span class="LC_warning">'.
1.709     bisitz   1096: 		&mt('No '.$submissions.' found for this resource for any students. ([quant,_1,student] checked for '.$submissions.')',
1.485     albertel 1097: 		    $num_students).
                   1098: 		'</span><br />';
1.96      albertel 1099: 	}
1.46      ng       1100:     } elsif ($ctr == 1) {
1.474     albertel 1101: 	$gradeTable =~ s/type="checkbox"/type="checkbox" checked="checked"/;
1.45      ng       1102:     }
                   1103:     $request->print($gradeTable);
1.44      ng       1104:     return '';
1.10      ng       1105: }
                   1106: 
1.44      ng       1107: #---- Called from the listStudents routine
1.249     albertel 1108: 
                   1109: sub check_script {
                   1110:     my ($form, $type)=@_;
1.597     wenzelju 1111:     my $chkallscript= &Apache::lonhtmlcommon::scripttag('
1.249     albertel 1112:     function checkall() {
                   1113:         for (i=0; i<document.forms.'.$form.'.elements.length; i++) {
                   1114:             ele = document.forms.'.$form.'.elements[i];
                   1115:             if (ele.name == "'.$type.'") {
                   1116:             document.forms.'.$form.'.elements[i].checked=true;
                   1117:                                        }
                   1118:         }
                   1119:     }
                   1120: 
                   1121:     function checksec() {
                   1122:         for (i=0; i<document.forms.'.$form.'.elements.length; i++) {
                   1123:             ele = document.forms.'.$form.'.elements[i];
                   1124:            string = document.forms.'.$form.'.chksec.value;
                   1125:            if
                   1126:           (ele.value.indexOf(":::SECTION"+string)>0) {
                   1127:               document.forms.'.$form.'.elements[i].checked=true;
                   1128:             }
                   1129:         }
                   1130:     }
                   1131: 
                   1132: 
                   1133:     function uncheckall() {
                   1134:         for (i=0; i<document.forms.'.$form.'.elements.length; i++) {
                   1135:             ele = document.forms.'.$form.'.elements[i];
                   1136:             if (ele.name == "'.$type.'") {
                   1137:             document.forms.'.$form.'.elements[i].checked=false;
                   1138:                                        }
                   1139:         }
                   1140:     }
                   1141: 
1.597     wenzelju 1142: '."\n");
1.249     albertel 1143:     return $chkallscript;
                   1144: }
                   1145: 
                   1146: sub check_buttons {
1.485     albertel 1147:     my $buttons.='<input type="button" onclick="checkall()" value="'.&mt('Check All').'" />';
                   1148:     $buttons.='<input type="button" onclick="uncheckall()" value="'.&mt('Uncheck All').'" />&nbsp;';
                   1149:     $buttons.='<input type="button" onclick="checksec()" value="'.&mt('Check Section/Group').'" />';
1.249     albertel 1150:     $buttons.='<input type="text" size="5" name="chksec" />&nbsp;';
                   1151:     return $buttons;
                   1152: }
                   1153: 
1.44      ng       1154: #     Displays the submissions for one student or a group of students
1.34      ng       1155: sub processGroup {
1.619     www      1156:     my ($request,$symb)  = @_;
1.41      ng       1157:     my $ctr        = 0;
1.155     albertel 1158:     my @stuchecked = &Apache::loncommon::get_env_multiple('form.stuinfo');
1.41      ng       1159:     my $total      = scalar(@stuchecked)-1;
1.45      ng       1160: 
1.396     banghart 1161:     foreach my $student (@stuchecked) {
                   1162: 	my ($uname,$udom,$fullname) = split(/:/,$student);
1.257     albertel 1163: 	$env{'form.student'}        = $uname;
                   1164: 	$env{'form.userdom'}        = $udom;
                   1165: 	$env{'form.fullname'}       = $fullname;
1.619     www      1166: 	&submission($request,$ctr,$total,$symb);
1.41      ng       1167: 	$ctr++;
                   1168:     }
                   1169:     return '';
1.35      ng       1170: }
1.34      ng       1171: 
1.44      ng       1172: #------------------------------------------------------------------------------------
                   1173: #
                   1174: #-------------------------- Next few routines handles grading by student, essentially
                   1175: #                           handles essay response type problem/part
                   1176: #
                   1177: #--- Javascript to handle the submission page functionality ---
                   1178: sub sub_page_js {
                   1179:     my $request = shift;
1.539     riegler  1180: 	    my $alertmsg = &mt('A number equal or greater than 0 is expected. Entered value = ');
1.597     wenzelju 1181:     $request->print(&Apache::lonhtmlcommon::scripttag(<<SUBJAVASCRIPT));
1.71      ng       1182:     function updateRadio(formname,id,weight) {
1.125     ng       1183: 	var gradeBox = formname["GD_BOX"+id];
                   1184: 	var radioButton = formname["RADVAL"+id];
                   1185: 	var oldpts = formname["oldpts"+id].value;
1.72      ng       1186: 	var pts = checkSolved(formname,id) == 'update' ? gradeBox.value : oldpts;
1.71      ng       1187: 	gradeBox.value = pts;
                   1188: 	var resetbox = false;
                   1189: 	if (isNaN(pts) || pts < 0) {
1.539     riegler  1190: 	    alert("$alertmsg"+pts);
1.71      ng       1191: 	    for (var i=0; i<radioButton.length; i++) {
                   1192: 		if (radioButton[i].checked) {
                   1193: 		    gradeBox.value = i;
                   1194: 		    resetbox = true;
                   1195: 		}
                   1196: 	    }
                   1197: 	    if (!resetbox) {
                   1198: 		formtextbox.value = "";
                   1199: 	    }
                   1200: 	    return;
1.44      ng       1201: 	}
1.71      ng       1202: 
                   1203: 	if (pts > weight) {
                   1204: 	    var resp = confirm("You entered a value ("+pts+
                   1205: 			       ") greater than the weight for the part. Accept?");
                   1206: 	    if (resp == false) {
1.125     ng       1207: 		gradeBox.value = oldpts;
1.71      ng       1208: 		return;
                   1209: 	    }
1.44      ng       1210: 	}
1.13      albertel 1211: 
1.71      ng       1212: 	for (var i=0; i<radioButton.length; i++) {
                   1213: 	    radioButton[i].checked=false;
                   1214: 	    if (pts == i && pts != "") {
                   1215: 		radioButton[i].checked=true;
                   1216: 	    }
                   1217: 	}
                   1218: 	updateSelect(formname,id);
1.125     ng       1219: 	formname["stores"+id].value = "0";
1.41      ng       1220:     }
1.5       albertel 1221: 
1.72      ng       1222:     function writeBox(formname,id,pts) {
1.125     ng       1223: 	var gradeBox = formname["GD_BOX"+id];
1.71      ng       1224: 	if (checkSolved(formname,id) == 'update') {
                   1225: 	    gradeBox.value = pts;
                   1226: 	} else {
1.125     ng       1227: 	    var oldpts = formname["oldpts"+id].value;
1.72      ng       1228: 	    gradeBox.value = oldpts;
1.125     ng       1229: 	    var radioButton = formname["RADVAL"+id];
1.71      ng       1230: 	    for (var i=0; i<radioButton.length; i++) {
                   1231: 		radioButton[i].checked=false;
1.72      ng       1232: 		if (i == oldpts) {
1.71      ng       1233: 		    radioButton[i].checked=true;
                   1234: 		}
                   1235: 	    }
1.41      ng       1236: 	}
1.125     ng       1237: 	formname["stores"+id].value = "0";
1.71      ng       1238: 	updateSelect(formname,id);
                   1239: 	return;
1.41      ng       1240:     }
1.44      ng       1241: 
1.71      ng       1242:     function clearRadBox(formname,id) {
                   1243: 	if (checkSolved(formname,id) == 'noupdate') {
                   1244: 	    updateSelect(formname,id);
                   1245: 	    return;
                   1246: 	}
1.125     ng       1247: 	gradeSelect = formname["GD_SEL"+id];
1.71      ng       1248: 	for (var i=0; i<gradeSelect.length; i++) {
                   1249: 	    if (gradeSelect[i].selected) {
                   1250: 		var selectx=i;
                   1251: 	    }
                   1252: 	}
1.125     ng       1253: 	var stores = formname["stores"+id];
1.71      ng       1254: 	if (selectx == stores.value) { return };
1.125     ng       1255: 	var gradeBox = formname["GD_BOX"+id];
1.71      ng       1256: 	gradeBox.value = "";
1.125     ng       1257: 	var radioButton = formname["RADVAL"+id];
1.71      ng       1258: 	for (var i=0; i<radioButton.length; i++) {
                   1259: 	    radioButton[i].checked=false;
                   1260: 	}
                   1261: 	stores.value = selectx;
                   1262:     }
1.5       albertel 1263: 
1.71      ng       1264:     function checkSolved(formname,id) {
1.125     ng       1265: 	if (formname["solved"+id].value == "correct_by_student" && formname.overRideScore.value == 'no') {
1.118     ng       1266: 	    var reply = confirm("This problem has been graded correct by the computer. Do you want to change the score?");
                   1267: 	    if (!reply) {return "noupdate";}
1.120     ng       1268: 	    formname.overRideScore.value = 'yes';
1.41      ng       1269: 	}
1.71      ng       1270: 	return "update";
1.13      albertel 1271:     }
1.71      ng       1272: 
                   1273:     function updateSelect(formname,id) {
1.125     ng       1274: 	formname["GD_SEL"+id][0].selected = true;
1.71      ng       1275: 	return;
1.41      ng       1276:     }
1.33      ng       1277: 
1.121     ng       1278: //=========== Check that a point is assigned for all the parts  ============
1.71      ng       1279:     function checksubmit(formname,val,total,parttot) {
1.121     ng       1280: 	formname.gradeOpt.value = val;
1.71      ng       1281: 	if (val == "Save & Next") {
                   1282: 	    for (i=0;i<=total;i++) {
                   1283: 		for (j=0;j<parttot;j++) {
1.125     ng       1284: 		    var partid = formname["partid"+i+"_"+j].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;
1.71      ng       1287: 			if (points == "") {
1.125     ng       1288: 			    var name = formname["name"+i].value;
1.129     ng       1289: 			    var studentID = (name != '' ? name : formname["unamedom"+i].value);
                   1290: 			    var resp = confirm("You did not assign a score for "+studentID+
                   1291: 					       ", part "+partid+". Continue?");
1.71      ng       1292: 			    if (resp == false) {
1.125     ng       1293: 				formname["GD_BOX"+i+"_"+partid].focus();
1.71      ng       1294: 				return false;
                   1295: 			    }
                   1296: 			}
                   1297: 		    }
                   1298: 		}
                   1299: 	    }
                   1300: 	}
1.120     ng       1301: 	formname.submit();
                   1302:     }
                   1303: 
1.71      ng       1304: //======= Check that a score is assigned for all the problems (page/sequence grading only) =========
                   1305:     function checkSubmitPage(formname,total) {
                   1306: 	noscore = new Array(100);
                   1307: 	var ptr = 0;
                   1308: 	for (i=1;i<total;i++) {
1.125     ng       1309: 	    var partid = formname["q_"+i].value;
1.127     ng       1310: 	    if (formname["GD_SEL"+i+"_"+partid][0].selected) {
1.125     ng       1311: 		var points = formname["GD_BOX"+i+"_"+partid].value;
                   1312: 		var status = formname["solved"+i+"_"+partid].value;
1.71      ng       1313: 		if (points == "" && status != "correct_by_student") {
                   1314: 		    noscore[ptr] = i;
                   1315: 		    ptr++;
                   1316: 		}
                   1317: 	    }
                   1318: 	}
                   1319: 	if (ptr != 0) {
                   1320: 	    var sense = ptr == 1 ? ": " : "s: ";
                   1321: 	    var prolist = "";
                   1322: 	    if (ptr == 1) {
                   1323: 		prolist = noscore[0];
                   1324: 	    } else {
                   1325: 		var i = 0;
                   1326: 		while (i < ptr-1) {
                   1327: 		    prolist += noscore[i]+", ";
                   1328: 		    i++;
                   1329: 		}
                   1330: 		prolist += "and "+noscore[i];
                   1331: 	    }
                   1332: 	    var resp = confirm("You did not assign any score for the following problem"+sense+prolist+". Continue?");
                   1333: 	    if (resp == false) {
                   1334: 		return false;
                   1335: 	    }
                   1336: 	}
1.45      ng       1337: 
1.71      ng       1338: 	formname.submit();
                   1339:     }
                   1340: SUBJAVASCRIPT
                   1341: }
1.45      ng       1342: 
1.71      ng       1343: #--- javascript for essay type problem --
                   1344: sub sub_page_kw_js {
                   1345:     my $request = shift;
1.80      ng       1346:     my $iconpath = $request->dir_config('lonIconsURL');
1.118     ng       1347:     &commonJSfunctions($request);
1.350     albertel 1348: 
1.629     www      1349:     my $inner_js_msg_central= (<<INNERJS);
                   1350: <script type="text/javascript">
1.350     albertel 1351:     function checkInput() {
                   1352:       opener.document.SCORE.msgsub.value = opener.checkEntities(document.msgcenter.msgsub.value);
                   1353:       var nmsg   = opener.document.SCORE.savemsgN.value;
                   1354:       var usrctr = document.msgcenter.usrctr.value;
                   1355:       var newval = opener.document.SCORE["newmsg"+usrctr];
                   1356:       newval.value = opener.checkEntities(document.msgcenter.newmsg.value);
                   1357: 
                   1358:       var msgchk = "";
                   1359:       if (document.msgcenter.subchk.checked) {
                   1360:          msgchk = "msgsub,";
                   1361:       }
                   1362:       var includemsg = 0;
                   1363:       for (var i=1; i<=nmsg; i++) {
                   1364:           var opnmsg = opener.document.SCORE["savemsg"+i];
                   1365:           var frmmsg = document.msgcenter["msg"+i];
                   1366:           opnmsg.value = opener.checkEntities(frmmsg.value);
                   1367:           var showflg = opener.document.SCORE["shownOnce"+i];
                   1368:           showflg.value = "1";
                   1369:           var chkbox = document.msgcenter["msgn"+i];
                   1370:           if (chkbox.checked) {
                   1371:              msgchk += "savemsg"+i+",";
                   1372:              includemsg = 1;
                   1373:           }
                   1374:       }
                   1375:       if (document.msgcenter.newmsgchk.checked) {
                   1376:          msgchk += "newmsg"+usrctr;
                   1377:          includemsg = 1;
                   1378:       }
                   1379:       imgformname = opener.document.SCORE["mailicon"+usrctr];
                   1380:       imgformname.src = "$iconpath/"+((includemsg) ? "mailto.gif" : "mailbkgrd.gif");
                   1381:       var includemsg = opener.document.SCORE["includemsg"+usrctr];
                   1382:       includemsg.value = msgchk;
                   1383: 
                   1384:       self.close()
                   1385: 
                   1386:     }
1.629     www      1387: </script>
1.350     albertel 1388: INNERJS
                   1389: 
1.629     www      1390:     my $inner_js_highlight_central= (<<INNERJS);
                   1391: <script type="text/javascript">
1.351     albertel 1392:     function updateChoice(flag) {
                   1393:       opener.document.SCORE.kwclr.value = opener.radioSelection(document.hlCenter.kwdclr);
                   1394:       opener.document.SCORE.kwsize.value = opener.radioSelection(document.hlCenter.kwdsize);
                   1395:       opener.document.SCORE.kwstyle.value = opener.radioSelection(document.hlCenter.kwdstyle);
                   1396:       opener.document.SCORE.refresh.value = "on";
                   1397:       if (opener.document.SCORE.keywords.value!=""){
                   1398:          opener.document.SCORE.submit();
                   1399:       }
                   1400:       self.close()
                   1401:     }
1.629     www      1402: </script>
1.351     albertel 1403: INNERJS
                   1404: 
                   1405:     my $start_page_msg_central = 
                   1406:         &Apache::loncommon::start_page('Message Central',$inner_js_msg_central,
                   1407: 				       {'js_ready'  => 1,
                   1408: 					'only_body' => 1,
                   1409: 					'bgcolor'   =>'#FFFFFF',});
                   1410:     my $end_page_msg_central = 
                   1411: 	&Apache::loncommon::end_page({'js_ready' => 1});
                   1412: 
                   1413: 
                   1414:     my $start_page_highlight_central = 
                   1415:         &Apache::loncommon::start_page('Highlight Central',
                   1416: 				       $inner_js_highlight_central,
1.350     albertel 1417: 				       {'js_ready'  => 1,
                   1418: 					'only_body' => 1,
                   1419: 					'bgcolor'   =>'#FFFFFF',});
1.351     albertel 1420:     my $end_page_highlight_central = 
1.350     albertel 1421: 	&Apache::loncommon::end_page({'js_ready' => 1});
                   1422: 
1.219     www      1423:     my $docopen=&Apache::lonhtmlcommon::javascript_docopen();
1.236     albertel 1424:     $docopen=~s/^document\.//;
1.652     raeburn  1425:     my %lt = &Apache::lonlocal::texthash(
                   1426:                 keyw => 'Keywords list, separated by a space. Add/delete to list if desired.',
                   1427:                 plse => 'Please select a word or group of words from document and then click this link.',
                   1428:                 adds => 'Add selection to keyword list? Edit if desired.',
                   1429:                 comp => 'Compose Message for: ',
                   1430:                 incl => 'Include',
1.656     raeburn  1431:                 type => 'Type',
1.652     raeburn  1432:                 subj => 'Subject',
                   1433:                 mesa => 'Message',
                   1434:                 new  => 'New',
                   1435:                 save => 'Save',
                   1436:                 canc => 'Cancel',
                   1437:                 kehi => 'Keyword Highlight Options',
                   1438:                 txtc => 'Text Color',
                   1439:                 font => 'Font Size',
1.656     raeburn  1440:                 fnst => 'Font Style',
1.718     bisitz   1441:                 col1 => 'red',
                   1442:                 col2 => 'green',
                   1443:                 col3 => 'blue',
                   1444:                 siz1 => 'normal',
                   1445:                 siz2 => '+1',
                   1446:                 siz3 => '+2',
                   1447:                 sty1 => 'normal',
                   1448:                 sty2 => 'italic',
                   1449:                 sty3 => 'bold',
1.652     raeburn  1450:              );
1.597     wenzelju 1451:     $request->print(&Apache::lonhtmlcommon::scripttag(<<SUBJAVASCRIPT));
1.45      ng       1452: 
1.44      ng       1453: //===================== Show list of keywords ====================
1.122     ng       1454:   function keywords(formname) {
1.652     raeburn  1455:     var nret = prompt("$lt{'keyw'}",formname.keywords.value);
1.44      ng       1456:     if (nret==null) return;
1.122     ng       1457:     formname.keywords.value = nret;
1.44      ng       1458: 
1.122     ng       1459:     if (formname.keywords.value != "") {
1.128     ng       1460: 	formname.refresh.value = "on";
1.122     ng       1461: 	formname.submit();
1.44      ng       1462:     }
                   1463:     return;
                   1464:   }
                   1465: 
                   1466: //===================== Script to view submitted by ==================
                   1467:   function viewSubmitter(submitter) {
                   1468:     document.SCORE.refresh.value = "on";
                   1469:     document.SCORE.NCT.value = "1";
                   1470:     document.SCORE.unamedom0.value = submitter;
                   1471:     document.SCORE.submit();
                   1472:     return;
                   1473:   }
                   1474: 
                   1475: //===================== Script to add keyword(s) ==================
                   1476:   function getSel() {
                   1477:     if (document.getSelection) txt = document.getSelection();
                   1478:     else if (document.selection) txt = document.selection.createRange().text;
                   1479:     else return;
                   1480:     var cleantxt = txt.replace(new RegExp('([\\f\\n\\r\\t\\v ])+', 'g')," ");
                   1481:     if (cleantxt=="") {
1.652     raeburn  1482: 	alert("$lt{'plse'}");
1.44      ng       1483: 	return;
                   1484:     }
1.652     raeburn  1485:     var nret = prompt("$lt{'adds'}",cleantxt);
1.44      ng       1486:     if (nret==null) return;
1.127     ng       1487:     document.SCORE.keywords.value = document.SCORE.keywords.value+" "+nret;
1.44      ng       1488:     if (document.SCORE.keywords.value != "") {
1.127     ng       1489: 	document.SCORE.refresh.value = "on";
1.44      ng       1490: 	document.SCORE.submit();
                   1491:     }
                   1492:     return;
                   1493:   }
                   1494: 
                   1495: //====================== Script for composing message ==============
1.80      ng       1496:    // preload images
                   1497:    img1 = new Image();
                   1498:    img1.src = "$iconpath/mailbkgrd.gif";
                   1499:    img2 = new Image();
                   1500:    img2.src = "$iconpath/mailto.gif";
                   1501: 
1.44      ng       1502:   function msgCenter(msgform,usrctr,fullname) {
                   1503:     var Nmsg  = msgform.savemsgN.value;
                   1504:     savedMsgHeader(Nmsg,usrctr,fullname);
                   1505:     var subject = msgform.msgsub.value;
1.127     ng       1506:     var msgchk = document.SCORE["includemsg"+usrctr].value;
1.44      ng       1507:     re = /msgsub/;
                   1508:     var shwsel = "";
                   1509:     if (re.test(msgchk)) { shwsel = "checked" }
1.123     ng       1510:     subject = (document.SCORE.shownSub.value == 0 ? checkEntities(subject) : subject);
                   1511:     displaySubject(checkEntities(subject),shwsel);
1.44      ng       1512:     for (var i=1; i<=Nmsg; i++) {
1.123     ng       1513: 	var testmsg = "savemsg"+i+",";
                   1514: 	re = new RegExp(testmsg,"g");
1.44      ng       1515: 	shwsel = "";
                   1516: 	if (re.test(msgchk)) { shwsel = "checked" }
1.125     ng       1517: 	var message = document.SCORE["savemsg"+i].value;
1.126     ng       1518: 	message = (document.SCORE["shownOnce"+i].value == 0 ? checkEntities(message) : message);
1.123     ng       1519: 	displaySavedMsg(i,message,shwsel); //I do not get it. w/o checkEntities on saved messages,
                   1520: 	                                   //any &lt; is already converted to <, etc. However, only once!!
1.44      ng       1521:     }
1.125     ng       1522:     newmsg = document.SCORE["newmsg"+usrctr].value;
1.44      ng       1523:     shwsel = "";
                   1524:     re = /newmsg/;
                   1525:     if (re.test(msgchk)) { shwsel = "checked" }
                   1526:     newMsg(newmsg,shwsel);
                   1527:     msgTail(); 
                   1528:     return;
                   1529:   }
                   1530: 
1.123     ng       1531:   function checkEntities(strx) {
                   1532:     if (strx.length == 0) return strx;
                   1533:     var orgStr = ["&", "<", ">", '"']; 
                   1534:     var newStr = ["&amp;", "&lt;", "&gt;", "&quot;"];
                   1535:     var counter = 0;
                   1536:     while (counter < 4) {
                   1537: 	strx = strReplace(strx,orgStr[counter],newStr[counter]);
                   1538: 	counter++;
                   1539:     }
                   1540:     return strx;
                   1541:   }
                   1542: 
                   1543:   function strReplace(strx, orgStr, newStr) {
                   1544:     return strx.split(orgStr).join(newStr);
                   1545:   }
                   1546: 
1.44      ng       1547:   function savedMsgHeader(Nmsg,usrctr,fullname) {
1.76      ng       1548:     var height = 70*Nmsg+250;
1.44      ng       1549:     if (height > 600) {
                   1550: 	height = 600;
                   1551:     }
1.118     ng       1552:     var xpos = (screen.width-600)/2;
                   1553:     xpos = (xpos < 0) ? '0' : xpos;
                   1554:     var ypos = (screen.height-height)/2-30;
                   1555:     ypos = (ypos < 0) ? '0' : ypos;
                   1556: 
1.668     www      1557:     pWin = window.open('', 'MessageCenter', 'resizable=yes,toolbar=no,location=no,scrollbars=yes,screenx='+xpos+',screeny='+ypos+',width=700,height='+height);
1.76      ng       1558:     pWin.focus();
                   1559:     pDoc = pWin.document;
1.219     www      1560:     pDoc.$docopen;
1.351     albertel 1561:     pDoc.write('$start_page_msg_central');
1.76      ng       1562: 
                   1563:     pDoc.write("<form action=\\"inactive\\" name=\\"msgcenter\\">");
                   1564:     pDoc.write("<input value=\\""+usrctr+"\\" name=\\"usrctr\\" type=\\"hidden\\">");
1.676     golterma 1565:     pDoc.write("<h1>&nbsp;$lt{'comp'}\"+fullname+\"<\\/h1>");
1.76      ng       1566: 
1.676     golterma 1567:     pDoc.write('<table style="border:1px solid black;"><tr>');
                   1568:     pDoc.write("<td><b>$lt{'incl'}<\\/b><\\/td><td><b>$lt{'type'}<\\/b><\\/td><td><b>$lt{'mesa'}<\\/td><\\/tr>");
1.44      ng       1569: }
                   1570:     function displaySubject(msg,shwsel) {
1.76      ng       1571:     pDoc = pWin.document;
1.676     golterma 1572:     pDoc.write("<tr>");
                   1573:     pDoc.write("<td align=\\"center\\"><input name=\\"subchk\\" type=\\"checkbox\\"" +shwsel+"><\\/td>");
1.652     raeburn  1574:     pDoc.write("<td>$lt{'subj'}<\\/td>");
1.676     golterma 1575:     pDoc.write("<td><input name=\\"msgsub\\" type=\\"text\\" value=\\""+msg+"\\"size=\\"40\\" maxlength=\\"80\\"><\\/td><\\/tr>");
1.44      ng       1576: }
                   1577: 
1.72      ng       1578:   function displaySavedMsg(ctr,msg,shwsel) {
1.76      ng       1579:     pDoc = pWin.document;
1.676     golterma 1580:     pDoc.write("<tr>");
                   1581:     pDoc.write("<td align=\\"center\\"><input name=\\"msgn"+ctr+"\\" type=\\"checkbox\\"" +shwsel+"><\\/td>");
1.465     albertel 1582:     pDoc.write("<td align=\\"center\\">"+ctr+"<\\/td>");
                   1583:     pDoc.write("<td><textarea name=\\"msg"+ctr+"\\" cols=\\"60\\" rows=\\"3\\">"+msg+"<\\/textarea><\\/td><\\/tr>");
1.44      ng       1584: }
                   1585: 
                   1586:   function newMsg(newmsg,shwsel) {
1.76      ng       1587:     pDoc = pWin.document;
1.676     golterma 1588:     pDoc.write("<tr>");
                   1589:     pDoc.write("<td align=\\"center\\"><input name=\\"newmsgchk\\" type=\\"checkbox\\"" +shwsel+"><\\/td>");
1.652     raeburn  1590:     pDoc.write("<td align=\\"center\\">$lt{'new'}<\\/td>");
1.465     albertel 1591:     pDoc.write("<td><textarea name=\\"newmsg\\" cols=\\"60\\" rows=\\"3\\" onchange=\\"javascript:this.form.newmsgchk.checked=true\\" >"+newmsg+"<\\/textarea><\\/td><\\/tr>");
1.44      ng       1592: }
                   1593: 
                   1594:   function msgTail() {
1.76      ng       1595:     pDoc = pWin.document;
1.676     golterma 1596:     //pDoc.write("<\\/table>");
1.465     albertel 1597:     pDoc.write("<\\/td><\\/tr><\\/table>&nbsp;");
1.652     raeburn  1598:     pDoc.write("<input type=\\"button\\" value=\\"$lt{'save'}\\" onclick=\\"javascript:checkInput()\\">&nbsp;&nbsp;");
                   1599:     pDoc.write("<input type=\\"button\\" value=\\"$lt{'canc'}\\" onclick=\\"self.close()\\"><br /><br />");
1.465     albertel 1600:     pDoc.write("<\\/form>");
1.351     albertel 1601:     pDoc.write('$end_page_msg_central');
1.128     ng       1602:     pDoc.close();
1.44      ng       1603: }
                   1604: 
                   1605: //====================== Script for keyword highlight options ==============
                   1606:   function kwhighlight() {
                   1607:     var kwclr    = document.SCORE.kwclr.value;
                   1608:     var kwsize   = document.SCORE.kwsize.value;
                   1609:     var kwstyle  = document.SCORE.kwstyle.value;
                   1610:     var redsel = "";
                   1611:     var grnsel = "";
                   1612:     var blusel = "";
1.718     bisitz   1613:     var txtcol1 = "$lt{'col1'}";
                   1614:     var txtcol2 = "$lt{'col2'}";
                   1615:     var txtcol3 = "$lt{'col3'}";
                   1616:     var txtsiz1 = "$lt{'siz1'}";
                   1617:     var txtsiz2 = "$lt{'siz2'}";
                   1618:     var txtsiz3 = "$lt{'siz3'}";
                   1619:     var txtsty1 = "$lt{'sty1'}";
                   1620:     var txtsty2 = "$lt{'sty2'}";
                   1621:     var txtsty3 = "$lt{'sty3'}";
                   1622:     if (kwclr=="red")   {var redsel="checked='checked'"};
                   1623:     if (kwclr=="green") {var grnsel="checked='checked'"};
                   1624:     if (kwclr=="blue")  {var blusel="checked='checked'"};
1.44      ng       1625:     var sznsel = "";
                   1626:     var sz1sel = "";
                   1627:     var sz2sel = "";
1.718     bisitz   1628:     if (kwsize=="0")  {var sznsel="checked='checked'"};
                   1629:     if (kwsize=="+1") {var sz1sel="checked='checked'"};
                   1630:     if (kwsize=="+2") {var sz2sel="checked='checked'"};
1.44      ng       1631:     var synsel = "";
                   1632:     var syisel = "";
                   1633:     var sybsel = "";
1.718     bisitz   1634:     if (kwstyle=="")    {var synsel="checked='checked'"};
                   1635:     if (kwstyle=="<i>") {var syisel="checked='checked'"};
                   1636:     if (kwstyle=="<b>") {var sybsel="checked='checked'"};
1.44      ng       1637:     highlightCentral();
1.718     bisitz   1638:     highlightbody('red',txtcol1,redsel,'0',txtsiz1,sznsel,'',txtsty1,synsel);
                   1639:     highlightbody('green',txtcol2,grnsel,'+1',txtsiz2,sz1sel,'<i>',txtsty2,syisel);
                   1640:     highlightbody('blue',txtcol3,blusel,'+2',txtsiz3,sz2sel,'<b>',txtsty3,sybsel);
1.44      ng       1641:     highlightend();
                   1642:     return;
                   1643:   }
                   1644: 
                   1645:   function highlightCentral() {
1.76      ng       1646: //    if (window.hwdWin) window.hwdWin.close();
1.118     ng       1647:     var xpos = (screen.width-400)/2;
                   1648:     xpos = (xpos < 0) ? '0' : xpos;
                   1649:     var ypos = (screen.height-330)/2-30;
                   1650:     ypos = (ypos < 0) ? '0' : ypos;
                   1651: 
1.206     albertel 1652:     hwdWin = window.open('', 'KeywordHighlightCentral', 'resizeable=yes,toolbar=no,location=no,scrollbars=no,width=400,height=300,screenx='+xpos+',screeny='+ypos);
1.76      ng       1653:     hwdWin.focus();
                   1654:     var hDoc = hwdWin.document;
1.219     www      1655:     hDoc.$docopen;
1.351     albertel 1656:     hDoc.write('$start_page_highlight_central');
1.76      ng       1657:     hDoc.write("<form action=\\"inactive\\" name=\\"hlCenter\\">");
1.718     bisitz   1658:     hDoc.write("<h1>$lt{'kehi'}<\\/h1>");
1.76      ng       1659: 
1.718     bisitz   1660:     hDoc.write('<table border="0" width="100%"><tr style="background-color:#A1D676">');
                   1661:     hDoc.write("<th>$lt{'txtc'}<\\/th><th>$lt{'font'}<\\/th><th>$lt{'fnst'}<\\/th><\\/tr>");
1.44      ng       1662:   }
                   1663: 
                   1664:   function highlightbody(clrval,clrtxt,clrsel,szval,sztxt,szsel,syval,sytxt,sysel) { 
1.76      ng       1665:     var hDoc = hwdWin.document;
1.718     bisitz   1666:     hDoc.write("<tr>");
1.76      ng       1667:     hDoc.write("<td align=\\"left\\">");
1.718     bisitz   1668:     hDoc.write("<input name=\\"kwdclr\\" type=\\"radio\\" value=\\""+clrval+"\\" "+clrsel+" \\/>&nbsp;"+clrtxt+"<\\/td>");
1.76      ng       1669:     hDoc.write("<td align=\\"left\\">");
1.718     bisitz   1670:     hDoc.write("<input name=\\"kwdsize\\" type=\\"radio\\" value=\\""+szval+"\\" "+szsel+" \\/>&nbsp;"+sztxt+"<\\/td>");
1.76      ng       1671:     hDoc.write("<td align=\\"left\\">");
1.718     bisitz   1672:     hDoc.write("<input name=\\"kwdstyle\\" type=\\"radio\\" value=\\""+syval+"\\" "+sysel+" \\/>&nbsp;"+sytxt+"<\\/td>");
1.465     albertel 1673:     hDoc.write("<\\/tr>");
1.44      ng       1674:   }
                   1675: 
                   1676:   function highlightend() { 
1.76      ng       1677:     var hDoc = hwdWin.document;
1.718     bisitz   1678:     hDoc.write("<\\/table><br \\/>");
                   1679:     hDoc.write("<input type=\\"button\\" value=\\"$lt{'save'}\\" onclick=\\"javascript:updateChoice(1)\\" \\/>&nbsp;&nbsp;");
                   1680:     hDoc.write("<input type=\\"button\\" value=\\"$lt{'canc'}\\" onclick=\\"self.close()\\" \\/><br /><br />");
1.465     albertel 1681:     hDoc.write("<\\/form>");
1.351     albertel 1682:     hDoc.write('$end_page_highlight_central');
1.128     ng       1683:     hDoc.close();
1.44      ng       1684:   }
                   1685: 
                   1686: SUBJAVASCRIPT
                   1687: }
                   1688: 
1.349     albertel 1689: sub get_increment {
1.348     bowersj2 1690:     my $increment = $env{'form.increment'};
                   1691:     if ($increment != 1 && $increment != .5 && $increment != .25 &&
                   1692:         $increment != .1) {
                   1693:         $increment = 1;
                   1694:     }
                   1695:     return $increment;
                   1696: }
                   1697: 
1.585     bisitz   1698: sub gradeBox_start {
                   1699:     return (
                   1700:         &Apache::loncommon::start_data_table()
                   1701:        .&Apache::loncommon::start_data_table_header_row()
                   1702:        .'<th>'.&mt('Part').'</th>'
                   1703:        .'<th>'.&mt('Points').'</th>'
                   1704:        .'<th>&nbsp;</th>'
                   1705:        .'<th>'.&mt('Assign Grade').'</th>'
                   1706:        .'<th>'.&mt('Weight').'</th>'
                   1707:        .'<th>'.&mt('Grade Status').'</th>'
                   1708:        .&Apache::loncommon::end_data_table_header_row()
                   1709:     );
                   1710: }
                   1711: 
                   1712: sub gradeBox_end {
                   1713:     return (
                   1714:         &Apache::loncommon::end_data_table()
                   1715:     );
                   1716: }
1.71      ng       1717: #--- displays the grading box, used in essay type problem and grading by page/sequence
                   1718: sub gradeBox {
1.322     albertel 1719:     my ($request,$symb,$uname,$udom,$counter,$partid,$record) = @_;
1.381     albertel 1720:     my $checkIcon = '<img alt="'.&mt('Check Mark').
1.485     albertel 1721: 	'" src="'.&Apache::loncommon::lonhttpdurl($request->dir_config('lonIconsURL').'/check.gif').'" height="16" border="0" />';
1.71      ng       1722:     my $wgt    = &Apache::lonnet::EXT('resource.'.$partid.'.weight',$symb,$udom,$uname);
1.466     albertel 1723:     my $wgtmsg = ($wgt > 0) ? &mt('(problem weight)') 
                   1724:                            : '<span class="LC_info">'.&mt('problem weight assigned by computer').'</span>';
1.71      ng       1725:     $wgt       = ($wgt > 0 ? $wgt : '1');
                   1726:     my $score  = ($$record{'resource.'.$partid.'.awarded'} eq '' ?
1.320     albertel 1727: 		  '' : &compute_points($$record{'resource.'.$partid.'.awarded'},$wgt));
1.695     bisitz   1728:     my $data_WGT='<input type="hidden" name="WGT'.$counter.'_'.$partid.'" value="'.$wgt.'" />'."\n";
1.466     albertel 1729:     my $display_part= &get_display_part($partid,$symb);
1.270     albertel 1730:     my %last_resets = &get_last_resets($symb,$env{'request.course.id'},
                   1731: 				       [$partid]);
                   1732:     my $aggtries = $$record{'resource.'.$partid.'.tries'};
1.269     raeburn  1733:     if ($last_resets{$partid}) {
                   1734:         $aggtries = &get_num_tries($record,$last_resets{$partid},$partid);
                   1735:     }
1.695     bisitz   1736:     my $result=&Apache::loncommon::start_data_table_row();
1.71      ng       1737:     my $ctr = 0;
1.348     bowersj2 1738:     my $thisweight = 0;
1.349     albertel 1739:     my $increment = &get_increment();
1.485     albertel 1740: 
                   1741:     my $radio.='<table border="0"><tr>'."\n";  # display radio buttons in a nice table 10 across
1.348     bowersj2 1742:     while ($thisweight<=$wgt) {
1.532     bisitz   1743: 	$radio.= '<td><span class="LC_nobreak"><label><input type="radio" name="RADVAL'.$counter.'_'.$partid.'" '.
1.589     bisitz   1744:         'onclick="javascript:writeBox(this.form,\''.$counter.'_'.$partid.'\','.
1.348     bowersj2 1745: 	    $thisweight.')" value="'.$thisweight.'" '.
1.401     albertel 1746: 	    ($score eq $thisweight ? 'checked="checked"':'').' /> '.$thisweight."</label></span></td>\n";
1.485     albertel 1747: 	$radio.=(($ctr+1)%10 == 0 ? '</tr><tr>' : '');
1.348     bowersj2 1748:         $thisweight += $increment;
1.71      ng       1749: 	$ctr++;
                   1750:     }
1.485     albertel 1751:     $radio.='</tr></table>';
                   1752: 
                   1753:     my $line.='<input type="text" name="GD_BOX'.$counter.'_'.$partid.'"'.
1.71      ng       1754: 	($score ne ''? ' value = "'.$score.'"':'').' size="4" '.
1.589     bisitz   1755: 	'onchange="javascript:updateRadio(this.form,\''.$counter.'_'.$partid.'\','.
1.71      ng       1756: 	$wgt.')" /></td>'."\n";
1.485     albertel 1757:     $line.='<td>/'.$wgt.' '.$wgtmsg.
1.71      ng       1758: 	($$record{'resource.'.$partid.'.solved'} eq 'correct_by_student' ? '&nbsp;'.$checkIcon : '').
1.585     bisitz   1759: 	' </td>'."\n";
                   1760:     $line.='<td><select name="GD_SEL'.$counter.'_'.$partid.'" '.
1.589     bisitz   1761: 	'onchange="javascript:clearRadBox(this.form,\''.$counter.'_'.$partid.'\')" >'."\n";
1.71      ng       1762:     if ($$record{'resource.'.$partid.'.solved'} eq 'excused') {
1.485     albertel 1763: 	$line.='<option></option>'.
                   1764: 	    '<option value="excused" selected="selected">'.&mt('excused').'</option>';
1.71      ng       1765:     } else {
1.485     albertel 1766: 	$line.='<option selected="selected"></option>'.
                   1767: 	    '<option value="excused" >'.&mt('excused').'</option>';
1.71      ng       1768:     }
1.485     albertel 1769:     $line.='<option value="reset status">'.&mt('reset status').'</option></select>'."\n";
                   1770: 
                   1771: 
                   1772:     $result .= 
1.695     bisitz   1773: 	    '<td>'.$data_WGT.$display_part.'</td><td>'.$radio.'</td><td>'.&mt('or').'</td><td>'.$line.'</td>';
1.585     bisitz   1774:     $result.=&Apache::loncommon::end_data_table_row();
1.695     bisitz   1775:     $result.=&Apache::loncommon::start_data_table_row().'<td colspan="6">';
1.71      ng       1776:     $result.='<input type="hidden" name="stores'.$counter.'_'.$partid.'" value="" />'."\n".
                   1777: 	'<input type="hidden" name="oldpts'.$counter.'_'.$partid.'" value="'.$score.'" />'."\n".
                   1778: 	'<input type="hidden" name="solved'.$counter.'_'.$partid.'" value="'.
1.269     raeburn  1779: 	$$record{'resource.'.$partid.'.solved'}.'" />'."\n".
                   1780:         '<input type="hidden" name="totaltries'.$counter.'_'.$partid.'" value="'.
                   1781:         $$record{'resource.'.$partid.'.tries'}.'" />'."\n".
                   1782:         '<input type="hidden" name="aggtries'.$counter.'_'.$partid.'" value="'.
                   1783:         $aggtries.'" />'."\n";
1.582     raeburn  1784:     my $res_error;
                   1785:     $result.=&handback_box($symb,$uname,$udom,$counter,$partid,$record,\$res_error);
1.695     bisitz   1786:     $result.='</td>'.&Apache::loncommon::end_data_table_row();
1.582     raeburn  1787:     if ($res_error) {
                   1788:         return &navmap_errormsg();
                   1789:     }
1.318     banghart 1790:     return $result;
                   1791: }
1.322     albertel 1792: 
                   1793: sub handback_box {
1.623     www      1794:     my ($symb,$uname,$udom,$counter,$partid,$record,$res_error_pointer) = @_;
                   1795:     my ($partlist,$handgrade,$responseType) = &response_type($symb,$res_error_pointer);
1.323     banghart 1796:     my (@respids);
1.652     raeburn  1797:     my @part_response_id = &flatten_responseType($responseType);
1.375     albertel 1798:     foreach my $part_response_id (@part_response_id) {
                   1799:     	my ($part,$resp) = @{ $part_response_id };
1.323     banghart 1800:         if ($part eq $partid) {
1.375     albertel 1801:             push(@respids,$resp);
1.323     banghart 1802:         }
                   1803:     }
1.318     banghart 1804:     my $result;
1.323     banghart 1805:     foreach my $respid (@respids) {
1.322     albertel 1806: 	my $prefix = $counter.'_'.$partid.'_'.$respid.'_';
                   1807: 	my $files=&get_submitted_files($udom,$uname,$partid,$respid,$record);
                   1808: 	next if (!@$files);
1.654     raeburn  1809: 	my $file_counter = 0;
1.313     banghart 1810: 	foreach my $file (@$files) {
1.368     banghart 1811: 	    if ($file =~ /\/portfolio\//) {
1.654     raeburn  1812:                 $file_counter++;
1.368     banghart 1813:     	        my ($file_path, $file_disp) = ($file =~ m|(.+/)(.+)$|);
1.729     raeburn  1814:     	        my ($name,$version,$ext) = &Apache::lonnet::file_name_version_ext($file_disp);
1.368     banghart 1815:     	        $file_disp = "$name.$ext";
                   1816:     	        $file = $file_path.$file_disp;
                   1817:     	        $result.=&mt('Return commented version of [_1] to student.',
                   1818:     			 '<span class="LC_filename">'.$file_disp.'</span>');
                   1819:     	        $result.='<input type="file"   name="'.$prefix.'returndoc'.$file_counter.'" />'."\n";
1.654     raeburn  1820:     	        $result.='<input type="hidden" name="'.$prefix.'origdoc'.$file_counter.'" value="'.$file.'" /><br />'."\n";
1.368     banghart 1821: 	    }
1.322     albertel 1822: 	}
1.654     raeburn  1823:         if ($file_counter) {
                   1824:             $result .= '<input type="hidden" name="'.$prefix.'countreturndoc" value="'.$file_counter.'" />'."\n".
                   1825:                        '<span class="LC_info">'.
                   1826:                        '('.&mt('File(s) will be uploaded when you click on Save &amp; Next below.',$file_counter).')</span><br /><br />';
                   1827:         }
1.313     banghart 1828:     }
1.318     banghart 1829:     return $result;    
1.71      ng       1830: }
1.44      ng       1831: 
1.58      albertel 1832: sub show_problem {
1.382     albertel 1833:     my ($request,$symb,$uname,$udom,$removeform,$viewon,$mode,$form) = @_;
1.144     albertel 1834:     my $rendered;
1.382     albertel 1835:     my %form = ((ref($form) eq 'HASH')? %{$form} : ());
1.329     albertel 1836:     &Apache::lonxml::remember_problem_counter();
1.144     albertel 1837:     if ($mode eq 'both' or $mode eq 'text') {
                   1838: 	$rendered=&Apache::loncommon::get_student_view($symb,$uname,$udom,
1.382     albertel 1839: 						       $env{'request.course.id'},
                   1840: 						       undef,\%form);
1.144     albertel 1841:     }
1.58      albertel 1842:     if ($removeform) {
                   1843: 	$rendered=~s|<form(.*?)>||g;
                   1844: 	$rendered=~s|</form>||g;
1.374     albertel 1845: 	$rendered=~s|(<input[^>]*name\s*=\s*"?)(\w+)("?)|$1would_have_been_$2$3|g;
1.58      albertel 1846:     }
1.144     albertel 1847:     my $companswer;
                   1848:     if ($mode eq 'both' or $mode eq 'answer') {
1.329     albertel 1849: 	&Apache::lonxml::restore_problem_counter();
1.382     albertel 1850: 	$companswer=
                   1851: 	    &Apache::loncommon::get_student_answers($symb,$uname,$udom,
                   1852: 						    $env{'request.course.id'},
                   1853: 						    %form);
1.144     albertel 1854:     }
1.58      albertel 1855:     if ($removeform) {
                   1856: 	$companswer=~s|<form(.*?)>||g;
                   1857: 	$companswer=~s|</form>||g;
1.144     albertel 1858: 	$companswer=~s|name="submit"|name="would_have_been_submit"|g;
1.58      albertel 1859:     }
1.671     raeburn  1860:     my $renderheading = &mt('View of the problem');
                   1861:     my $answerheading = &mt('Correct answer');
                   1862:     if (($uname ne $env{'user.name'}) || ($udom ne $env{'user.domain'})) {
                   1863:         my $stu_fullname = $env{'form.fullname'};
                   1864:         if ($stu_fullname eq '') {
                   1865:             $stu_fullname = &Apache::loncommon::plainname($uname,$udom,'lastname');
                   1866:         }
                   1867:         my $forwhom = &nameUserString(undef,$stu_fullname,$uname,$udom);
                   1868:         if ($forwhom ne '') {
                   1869:             $renderheading = &mt('View of the problem for[_1]',$forwhom);
                   1870:             $answerheading = &mt('Correct answer for[_1]',$forwhom);
                   1871:         }
                   1872:     }
1.468     albertel 1873:     $rendered=
1.588     bisitz   1874:         '<div class="LC_Box">'
1.671     raeburn  1875:        .'<h3 class="LC_hcell">'.$renderheading.'</h3>'
1.588     bisitz   1876:        .$rendered
                   1877:        .'</div>';
1.468     albertel 1878:     $companswer=
1.588     bisitz   1879:         '<div class="LC_Box">'
1.671     raeburn  1880:        .'<h3 class="LC_hcell">'.$answerheading.'</h3>'
1.588     bisitz   1881:        .$companswer
                   1882:        .'</div>';
1.468     albertel 1883:     my $result;
1.144     albertel 1884:     if ($mode eq 'both') {
1.588     bisitz   1885:         $result=$rendered.$companswer;
1.144     albertel 1886:     } elsif ($mode eq 'text') {
1.588     bisitz   1887:         $result=$rendered;
1.144     albertel 1888:     } elsif ($mode eq 'answer') {
1.588     bisitz   1889:         $result=$companswer;
1.144     albertel 1890:     }
1.71      ng       1891:     return $result;
1.58      albertel 1892: }
1.397     albertel 1893: 
1.396     banghart 1894: sub files_exist {
                   1895:     my ($r, $symb) = @_;
                   1896:     my @students = &Apache::loncommon::get_env_multiple('form.stuinfo');
1.397     albertel 1897: 
1.396     banghart 1898:     foreach my $student (@students) {
                   1899:         my ($uname,$udom,$fullname) = split(/:/,$student);
1.397     albertel 1900:         my %record = &Apache::lonnet::restore($symb,$env{'request.course.id'},
                   1901: 					      $udom,$uname);
1.396     banghart 1902:         my ($string,$timestamp)= &get_last_submission(\%record);
1.397     albertel 1903:         foreach my $submission (@$string) {
                   1904:             my ($partid,$respid) =
                   1905: 		($submission =~ /^resource\.([^\.]*)\.([^\.]*)\.submission/);
                   1906:             my $files=&get_submitted_files($udom,$uname,$partid,$respid,
                   1907: 					   \%record);
                   1908:             return 1 if (@$files);
1.396     banghart 1909:         }
                   1910:     }
1.397     albertel 1911:     return 0;
1.396     banghart 1912: }
1.397     albertel 1913: 
1.394     banghart 1914: sub download_all_link {
                   1915:     my ($r,$symb) = @_;
1.621     www      1916:     unless (&files_exist($r, $symb)) {
                   1917:        $r->print(&mt('There are currently no submitted documents.'));
                   1918:        return;
                   1919:     }
                   1920: 
1.395     albertel 1921:     my $all_students = 
                   1922: 	join("\n", &Apache::loncommon::get_env_multiple('form.stuinfo'));
                   1923: 
                   1924:     my $parts =
                   1925: 	join("\n",&Apache::loncommon::get_env_multiple('form.vPart'));
                   1926: 
1.394     banghart 1927:     my $identifier = &Apache::loncommon::get_cgi_id();
1.514     raeburn  1928:     &Apache::lonnet::appenv({'cgi.'.$identifier.'.students' => $all_students,
                   1929:                              'cgi.'.$identifier.'.symb' => $symb,
                   1930:                              'cgi.'.$identifier.'.parts' => $parts,});
1.395     albertel 1931:     $r->print('<a href="/cgi-bin/multidownload.pl?'.$identifier.'">'.
                   1932: 	      &mt('Download All Submitted Documents').'</a>');
1.621     www      1933:     return;
                   1934: }
                   1935: 
                   1936: sub submit_download_link {
                   1937:     my ($request,$symb) = @_;
                   1938:     if (!$symb) { return ''; }
                   1939: #FIXME: Figure out which type of problem this is and provide appropriate download
                   1940:     &download_all_link($request,$symb);
1.394     banghart 1941: }
1.395     albertel 1942: 
1.432     banghart 1943: sub build_section_inputs {
                   1944:     my $section_inputs;
                   1945:     if ($env{'form.section'} eq '') {
                   1946:         $section_inputs .= '<input type="hidden" name="section" value="all" />'."\n";
                   1947:     } else {
                   1948:         my @sections = &Apache::loncommon::get_env_multiple('form.section');
1.434     albertel 1949:         foreach my $section (@sections) {
1.432     banghart 1950:             $section_inputs .= '<input type="hidden" name="section" value="'.$section.'" />'."\n";
                   1951:         }
                   1952:     }
                   1953:     return $section_inputs;
                   1954: }
                   1955: 
1.44      ng       1956: # --------------------------- show submissions of a student, option to grade 
                   1957: sub submission {
1.608     www      1958:     my ($request,$counter,$total,$symb) = @_;
1.257     albertel 1959:     my ($uname,$udom)     = ($env{'form.student'},$env{'form.userdom'});
                   1960:     $udom = ($udom eq '' ? $env{'user.domain'} : $udom); #has form.userdom changed for a student?
                   1961:     my $usec = &Apache::lonnet::getsection($udom,$uname,$env{'request.course.id'});
                   1962:     $env{'form.fullname'} = &Apache::loncommon::plainname($uname,$udom,'lastname') if $env{'form.fullname'} eq '';
1.608     www      1963: 
1.605     www      1964:     my $probtitle=&Apache::lonnet::gettitle($symb); 
1.324     albertel 1965:     if ($symb eq '') { $request->print("Unable to handle ambiguous references:."); return ''; }
1.104     albertel 1966: 
                   1967:     if (!&canview($usec)) {
1.712     bisitz   1968:         $request->print(
                   1969:             '<span class="LC_warning">'.
1.713     bisitz   1970:             &mt('Unable to view requested student.').
1.712     bisitz   1971:             ' '.&mt('([_1] in section [_2] in course id [_3])',
                   1972:                         $uname.':'.$udom,$usec,$env{'request.course.id'}).
                   1973:             '</span>');
1.104     albertel 1974: 	return;
                   1975:     }
                   1976: 
1.257     albertel 1977:     if (!$env{'form.lastSub'}) { $env{'form.lastSub'} = 'datesub'; }
                   1978:     if (!$env{'form.vProb'}) { $env{'form.vProb'} = 'yes'; }
                   1979:     if (!$env{'form.vAns'}) { $env{'form.vAns'} = 'yes'; }
                   1980:     my $last = ($env{'form.lastSub'} eq 'last' ? 'last' : '');
1.381     albertel 1981:     my $checkIcon = '<img alt="'.&mt('Check Mark').
                   1982: 	'" src="'.$request->dir_config('lonIconsURL').
1.122     ng       1983: 	'/check.gif" height="16" border="0" />';
1.41      ng       1984: 
                   1985:     # header info
                   1986:     if ($counter == 0) {
                   1987: 	&sub_page_js($request);
1.621     www      1988: 	&sub_page_kw_js($request);
1.118     ng       1989: 
1.44      ng       1990: 	# option to display problem, only once else it cause problems 
                   1991:         # with the form later since the problem has a form.
1.257     albertel 1992: 	if ($env{'form.vProb'} eq 'yes' or $env{'form.vAns'} eq 'yes') {
1.144     albertel 1993: 	    my $mode;
1.257     albertel 1994: 	    if ($env{'form.vProb'} eq 'yes' && $env{'form.vAns'} eq 'yes') {
1.144     albertel 1995: 		$mode='both';
1.257     albertel 1996: 	    } elsif ($env{'form.vProb'} eq 'yes') {
1.144     albertel 1997: 		$mode='text';
1.257     albertel 1998: 	    } elsif ($env{'form.vAns'} eq 'yes') {
1.144     albertel 1999: 		$mode='answer';
                   2000: 	    }
1.329     albertel 2001: 	    &Apache::lonxml::clear_problem_counter();
1.144     albertel 2002: 	    $request->print(&show_problem($request,$symb,$uname,$udom,0,1,$mode));
1.41      ng       2003: 	}
1.441     www      2004: 
1.704     raeburn  2005: 	# kwclr is the only variable that is guaranteed not to be blank 
1.44      ng       2006:         # if this subroutine has been called once.
1.41      ng       2007: 	my %keyhash = ();
1.624     www      2008: #	if ($env{'form.kwclr'} eq '' && $env{'form.handgrade'} eq 'yes') {
                   2009:         if (1) {
1.41      ng       2010: 	    %keyhash = &Apache::lonnet::dump('nohist_handgrade',
1.257     albertel 2011: 					     $env{'course.'.$env{'request.course.id'}.'.domain'},
                   2012: 					     $env{'course.'.$env{'request.course.id'}.'.num'});
1.41      ng       2013: 
1.257     albertel 2014: 	    my $loginuser = $env{'user.name'}.':'.$env{'user.domain'};
                   2015: 	    $env{'form.keywords'} = $keyhash{$symb.'_keywords'} ne '' ? $keyhash{$symb.'_keywords'} : '';
                   2016: 	    $env{'form.kwclr'}    = $keyhash{$loginuser.'_kwclr'} ne '' ? $keyhash{$loginuser.'_kwclr'} : 'red';
                   2017: 	    $env{'form.kwsize'}   = $keyhash{$loginuser.'_kwsize'} ne '' ? $keyhash{$loginuser.'_kwsize'} : '0';
                   2018: 	    $env{'form.kwstyle'}  = $keyhash{$loginuser.'_kwstyle'} ne '' ? $keyhash{$loginuser.'_kwstyle'} : '';
                   2019: 	    $env{'form.msgsub'}   = $keyhash{$symb.'_subject'} ne '' ? 
1.605     www      2020: 		$keyhash{$symb.'_subject'} : $probtitle;
1.257     albertel 2021: 	    $env{'form.savemsgN'} = $keyhash{$symb.'_savemsgN'} ne '' ? $keyhash{$symb.'_savemsgN'} : '0';
1.41      ng       2022: 	}
1.257     albertel 2023: 	my $overRideScore = $env{'form.overRideScore'} eq '' ? 'no' : $env{'form.overRideScore'};
1.442     banghart 2024: 	my $stu_status = join(':',&Apache::loncommon::get_env_multiple('form.Status'));
1.303     banghart 2025: 	$request->print('<form action="/adm/grades" method="post" name="SCORE" enctype="multipart/form-data">'."\n".
1.41      ng       2026: 			'<input type="hidden" name="command"    value="handgrade" />'."\n".
1.442     banghart 2027: 			'<input type="hidden" name="Status"     value="'.$stu_status.'" />'."\n".
1.120     ng       2028: 			'<input type="hidden" name="overRideScore" value="'.$overRideScore.'" />'."\n".
1.41      ng       2029: 			'<input type="hidden" name="refresh"    value="off" />'."\n".
1.120     ng       2030: 			'<input type="hidden" name="studentNo"  value="" />'."\n".
                   2031: 			'<input type="hidden" name="gradeOpt"   value="" />'."\n".
1.418     albertel 2032: 			'<input type="hidden" name="symb"       value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
1.257     albertel 2033: 			'<input type="hidden" name="vProb"      value="'.$env{'form.vProb'}.'" />'."\n".
                   2034: 			'<input type="hidden" name="vAns"       value="'.$env{'form.vAns'}.'" />'."\n".
                   2035: 			'<input type="hidden" name="lastSub"    value="'.$env{'form.lastSub'}.'" />'."\n".
1.432     banghart 2036: 			&build_section_inputs().
1.326     albertel 2037: 			'<input type="hidden" name="submitonly" value="'.$env{'form.submitonly'}.'" />'."\n".
1.41      ng       2038: 			'<input type="hidden" name="NCT"'.
1.257     albertel 2039: 			' value="'.($env{'form.NTSTU'} ne '' ? $env{'form.NTSTU'} : $total+1).'" />'."\n");
1.624     www      2040: #	if ($env{'form.handgrade'} eq 'yes') {
                   2041:         if (1) {
1.257     albertel 2042: 	    $request->print('<input type="hidden" name="keywords" value="'.$env{'form.keywords'}.'" />'."\n".
                   2043: 			    '<input type="hidden" name="kwclr"    value="'.$env{'form.kwclr'}.'" />'."\n".
                   2044: 			    '<input type="hidden" name="kwsize"   value="'.$env{'form.kwsize'}.'" />'."\n".
                   2045: 			    '<input type="hidden" name="kwstyle"  value="'.$env{'form.kwstyle'}.'" />'."\n".
                   2046: 			    '<input type="hidden" name="msgsub"   value="'.$env{'form.msgsub'}.'" />'."\n".
1.123     ng       2047: 			    '<input type="hidden" name="shownSub" value="0" />'."\n".
1.257     albertel 2048: 			    '<input type="hidden" name="savemsgN" value="'.$env{'form.savemsgN'}.'" />'."\n");
1.154     albertel 2049: 	    foreach my $partid (&Apache::loncommon::get_env_multiple('form.vPart')) {
                   2050: 		$request->print('<input type="hidden" name="vPart" value="'.$partid.'" />'."\n");
                   2051: 	    }
1.123     ng       2052: 	}
1.41      ng       2053: 	
                   2054: 	my ($cts,$prnmsg) = (1,'');
1.257     albertel 2055: 	while ($cts <= $env{'form.savemsgN'}) {
1.41      ng       2056: 	    $prnmsg.='<input type="hidden" name="savemsg'.$cts.'" value="'.
1.123     ng       2057: 		(!exists($keyhash{$symb.'_savemsg'.$cts}) ? 
1.257     albertel 2058: 		 &Apache::lonfeedback::clear_out_html($env{'form.savemsg'.$cts}) :
1.80      ng       2059: 		 &Apache::lonfeedback::clear_out_html($keyhash{$symb.'_savemsg'.$cts})).
1.123     ng       2060: 		'" />'."\n".
                   2061: 		'<input type="hidden" name="shownOnce'.$cts.'" value="0" />'."\n";
1.41      ng       2062: 	    $cts++;
                   2063: 	}
                   2064: 	$request->print($prnmsg);
1.32      ng       2065: 
1.624     www      2066: #	if ($env{'form.handgrade'} eq 'yes') {
                   2067:         if (1) {
1.652     raeburn  2068: 
                   2069:             my %lt = &Apache::lonlocal::texthash(
1.719     bisitz   2070:                           keyh => 'Keyword Highlighting for Essays',
1.652     raeburn  2071:                           keyw => 'Keyword Options',
1.655     raeburn  2072:                           list => 'List',
1.652     raeburn  2073:                           past => 'Paste Selection to List',
1.661     www      2074:                           high => 'Highlight Attribute',
1.652     raeburn  2075:                      );    
1.88      www      2076: #
                   2077: # Print out the keyword options line
                   2078: #
1.718     bisitz   2079: 	    $request->print(
                   2080:                 '<div class="LC_columnSection">'
                   2081:                .'<fieldset><legend>'.$lt{'keyh'}.'</legend>'
                   2082:                .&Apache::lonhtmlcommon::funclist_from_array(
                   2083:                     ['<a href="javascript:keywords(document.SCORE);" target="_self">'.$lt{'list'}.'</a>',
                   2084:                      '<a href="#" onmousedown="javascript:getSel(); return false"
                   2085:  class="page">'.$lt{'past'}.'</a>',
                   2086:                      '<a href="javascript:kwhighlight();" target="_self">'.$lt{'high'}.'</a>'],
                   2087:                     {legend => $lt{'keyw'}})
                   2088:                .'</fieldset></div>'
                   2089:             );
                   2090: 
1.88      www      2091: #
                   2092: # Load the other essays for similarity check
                   2093: #
1.324     albertel 2094:             my (undef,undef,$essayurl) = &Apache::lonnet::decode_symb($symb);
1.384     albertel 2095: 	    my ($adom,$aname,$apath)=($essayurl=~/^($LONCAPA::domain_re)\/($LONCAPA::username_re)\/(.*)$/);
1.359     www      2096: 	    $apath=&escape($apath);
1.88      www      2097: 	    $apath=~s/\W/\_/gs;
1.674     raeburn  2098:             &init_old_essays($symb,$apath,$adom,$aname);
1.41      ng       2099:         }
                   2100:     }
1.44      ng       2101: 
1.441     www      2102: # This is where output for one specific student would start
1.592     bisitz   2103:     my $add_class = ($counter%2) ? ' LC_grade_show_user_odd_row' : '';
                   2104:     $request->print(
                   2105:         "\n\n"
                   2106:        .'<div class="LC_grade_show_user'.$add_class.'">'
                   2107:        .'<h2>'.&nameUserString(undef,$env{'form.fullname'},$uname,$udom).'</h2>'
                   2108:        ."\n"
                   2109:     );
1.441     www      2110: 
1.592     bisitz   2111:     # Show additional functions if allowed
                   2112:     if ($perm{'vgr'}) {
                   2113:         $request->print(
                   2114:             &Apache::loncommon::track_student_link(
1.708     bisitz   2115:                 'View recent activity',
1.592     bisitz   2116:                 $uname,$udom,'check')
                   2117:            .' '
                   2118:         );
                   2119:     }
                   2120:     if ($perm{'opa'}) {
                   2121:         $request->print(
                   2122:             &Apache::loncommon::pprmlink(
                   2123:                 &mt('Set/Change parameters'),
                   2124:                 $uname,$udom,$symb,'check'));
                   2125:     }
                   2126: 
                   2127:     # Show Problem
1.257     albertel 2128:     if ($env{'form.vProb'} eq 'all' or $env{'form.vAns'} eq 'all') {
1.144     albertel 2129: 	my $mode;
1.257     albertel 2130: 	if ($env{'form.vProb'} eq 'all' && $env{'form.vAns'} eq 'all') {
1.144     albertel 2131: 	    $mode='both';
1.257     albertel 2132: 	} elsif ($env{'form.vProb'} eq 'all' ) {
1.144     albertel 2133: 	    $mode='text';
1.257     albertel 2134: 	} elsif ($env{'form.vAns'} eq 'all') {
1.144     albertel 2135: 	    $mode='answer';
                   2136: 	}
1.329     albertel 2137: 	&Apache::lonxml::clear_problem_counter();
1.475     albertel 2138: 	$request->print(&show_problem($request,$symb,$uname,$udom,1,1,$mode,{'request.prefix' => 'ctr'.$counter}));
1.58      albertel 2139:     }
1.144     albertel 2140: 
1.257     albertel 2141:     my %record = &Apache::lonnet::restore($symb,$env{'request.course.id'},$udom,$uname);
1.582     raeburn  2142:     my $res_error;
                   2143:     my ($partlist,$handgrade,$responseType) = &response_type($symb,\$res_error);
                   2144:     if ($res_error) {
                   2145:         $request->print(&navmap_errormsg());
                   2146:         return;
                   2147:     }
1.41      ng       2148: 
1.44      ng       2149:     # Display student info
1.41      ng       2150:     $request->print(($counter == 0 ? '' : '<br />'));
1.590     bisitz   2151: 
                   2152:     my $result='<div class="LC_Box">'
                   2153:               .'<h3 class="LC_hcell">'.&mt('Submissions').'</h3>';
1.45      ng       2154:     $result.='<input type="hidden" name="name'.$counter.
1.588     bisitz   2155:              '" value="'.$env{'form.fullname'}.'" />'."\n";
1.624     www      2156: #    if ($env{'form.handgrade'} eq 'no') {
                   2157:     if (1) {
1.588     bisitz   2158:         $result.='<p class="LC_info">'
                   2159:                 .&mt('Part(s) graded correct by the computer is marked with a [_1] symbol.',$checkIcon)
                   2160:                 ."</p>\n";
1.469     albertel 2161:     }
                   2162: 
1.118     ng       2163:     # If any part of the problem is an essay-response (handgraded), then check for collaborators
1.464     albertel 2164:     my $fullname;
                   2165:     my $col_fullnames = [];
1.624     www      2166: #    if ($env{'form.handgrade'} eq 'yes') {
                   2167:     if (1) {
1.464     albertel 2168: 	(my $sub_result,$fullname,$col_fullnames)=
                   2169: 	    &check_collaborators($symb,$uname,$udom,\%record,$handgrade,
                   2170: 				 $counter);
                   2171: 	$result.=$sub_result;
1.41      ng       2172:     }
1.44      ng       2173:     $request->print($result."\n");
1.702     kruse    2174:     
1.44      ng       2175:     # print student answer/submission
1.588     bisitz   2176:     # Options are (1) Handgraded submission only
1.44      ng       2177:     #             (2) Last submission, includes submission that is not handgraded 
                   2178:     #                  (for multi-response type part)
                   2179:     #             (3) Last submission plus the parts info
                   2180:     #             (4) The whole record for this student
1.702     kruse    2181:     
                   2182:     my ($string,$timestamp)= &get_last_submission(\%record);
1.468     albertel 2183: 	
1.702     kruse    2184:     my $lastsubonly;
1.468     albertel 2185: 
1.702     kruse    2186:     if ($$timestamp eq '') {
                   2187:         $lastsubonly.='<div class="LC_grade_submissions_body">'.$$string[0].'</div>'; 
                   2188:     } else {
                   2189:         $lastsubonly =
                   2190:             '<div class="LC_grade_submissions_body">'
                   2191:            .'<b>'.&mt('Date Submitted:').'</b> '.$$timestamp."\n";
                   2192: 
                   2193: 	my %seenparts;
                   2194: 	my @part_response_id = &flatten_responseType($responseType);
                   2195: 	foreach my $part (@part_response_id) {
                   2196: 	    next if ($env{'form.lastSub'} eq 'hdgrade' 
1.393     albertel 2197: 			 && $$handgrade{$$part[0].'_'.$$part[1]} ne 'yes');
                   2198: 
1.702     kruse    2199: 	    my ($partid,$respid) = @{ $part };
                   2200: 	    my $display_part=&get_display_part($partid,$symb);
                   2201: 	    if ($env{"form.$uname:$udom:$partid:submitted_by"}) {
                   2202: 		if (exists($seenparts{$partid})) { next; }
                   2203: 		$seenparts{$partid}=1;
                   2204:                 $request->print(
                   2205:                     '<b>'.&mt('Part: [_1]',$display_part).'</b>'.
                   2206:                     ' <b>'.&mt('Collaborative submission by: [_1]',
                   2207:                                '<a href="javascript:viewSubmitter(\''.
                   2208:                                $env{"form.$uname:$udom:$partid:submitted_by"}.
                   2209:                                '\');" target="_self">'.
                   2210:                                $$fullname{$env{"form.$uname:$udom:$partid:submitted_by"}}.'</a>').
                   2211:                     '<br />');
                   2212: 		next;
                   2213: 		}
                   2214: 	    my $responsetype = $responseType->{$partid}->{$respid};
                   2215: 	    if (!exists($record{"resource.$partid.$respid.submission"})) {
                   2216:                 $lastsubonly.="\n".'<div class="LC_grade_submission_part">'.
                   2217:                     '<b>'.&mt('Part: [_1]',$display_part).'</b>'.
                   2218:                     ' <span class="LC_internal_info">'.
                   2219:                     '('.&mt('Response ID: [_1]',$respid).')'.
                   2220:                     '</span>&nbsp; &nbsp;'.
                   2221: 	       	    '<span class="LC_warning">'.&mt('Nothing submitted - no attempts.').'</span><br /><br /></div>';
                   2222: 		next;
                   2223: 	    }
                   2224: 	    foreach my $submission (@$string) {
                   2225: 		my ($partid,$respid) = ($submission =~ /^resource\.([^\.]*)\.([^\.]*)\.submission/);
                   2226: 		if (join('_',@{$part}) ne ($partid.'_'.$respid)) { next; }
1.724     raeburn  2227: 		my ($ressub,$hide,$draft,$subval) = split(/:/,$submission,4);
1.702     kruse    2228: 		# Similarity check
                   2229:                 my $similar='';
                   2230:                 my ($type,$trial,$rndseed);
                   2231:                 if ($hide eq 'rand') {
                   2232:                     $type = 'randomizetry';
                   2233:                     $trial = $record{"resource.$partid.tries"};
1.733     raeburn  2234:                     $rndseed = $record{"resource.$partid.rndseed"};
1.702     kruse    2235:                 }
                   2236: 	        if ($env{'form.checkPlag'}) {
                   2237:     		    my ($oname,$odom,$ocrsid,$oessay,$osim)=
                   2238: 		        &most_similar($uname,$udom,$symb,$subval);
                   2239: 		    if ($osim) {
                   2240: 			$osim=int($osim*100.0);
                   2241: 			my %old_course_desc = 
                   2242: 			    &Apache::lonnet::coursedescription($ocrsid,
                   2243: 							{'one_time' => 1});
                   2244: 
                   2245:                         if ($hide eq 'anon') {
                   2246:                             $similar='<hr /><span class="LC_warning">'.&mt("Essay was found to be similar to another essay submitted for this assignment.").'<br />'.
                   2247:                                      &mt('As the current submission is for an anonymous survey, no other details are available.').'</span><hr />';
                   2248:                         } else {
                   2249: 			    $similar="<hr /><h3><span class=\"LC_warning\">".
                   2250: 				&mt('Essay is [_1]% similar to an essay by [_2] in course [_3] (course id [_4]:[_5])',
                   2251: 				    $osim,
                   2252: 				    &Apache::loncommon::plainname($oname,$odom).' ('.$oname.':'.$odom.')',
1.596     raeburn  2253: 				        $old_course_desc{'description'},
                   2254: 				        $old_course_desc{'num'},
                   2255: 				        $old_course_desc{'domain'}).
                   2256: 				    '</span></h3><blockquote><i>'.
                   2257: 				    &keywords_highlight($oessay).
                   2258: 				    '</i></blockquote><hr />';
1.702     kruse    2259:                         }
                   2260: 	            }
                   2261: 		}
                   2262: 		my $order=&get_order($partid,$respid,$symb,$uname,$udom,
                   2263:                                      undef,$type,$trial,$rndseed);
                   2264:                 if ($env{'form.lastSub'} eq 'lastonly' || $env{'form.lastSub'} eq 'datesub' || $env{'form.lastSub'} =~ /^(last|all)$/ || ($env{'form.lastSub'} eq 'hdgrade' && 
1.377     albertel 2265: 			 $$handgrade{$$part[0].'_'.$$part[1]} eq 'yes')) {
1.702     kruse    2266: 		    my $display_part=&get_display_part($partid,$symb);
                   2267:                     $lastsubonly.='<div class="LC_grade_submission_part">'.
                   2268:                         '<b>'.&mt('Part: [_1]',$display_part).'</b>'.
                   2269:                         ' <span class="LC_internal_info">'.
                   2270:                         '('.&mt('Response ID: [_1]',$respid).')'.
                   2271:                         '</span>&nbsp; &nbsp;';
                   2272: 		    my $files=&get_submitted_files($udom,$uname,$partid,$respid,\%record);
                   2273:                         
                   2274: 		    if (@$files) {
                   2275:                         if ($hide eq 'anon') {
                   2276:                             $lastsubonly.='<br />'.&mt('[quant,_1,file] uploaded to this anonymous survey',scalar(@{$files}));
                   2277:                         } else {
                   2278:                             $lastsubonly.='<br /><br />'.'<b>'.&mt('Submitted Files:').'</b>'
                   2279:                                         .'<br /><span class="LC_warning">';
                   2280:                             if(@$files == 1) {
                   2281:                                 $lastsubonly .= &mt('Like all files provided by users, this file may contain viruses!');
1.596     raeburn  2282:                             } else {
1.702     kruse    2283:                                 $lastsubonly .= &mt('Like all files provided by users, these files may contain viruses!');
                   2284:                             }
                   2285:                             $lastsubonly .= '</span>';                         
                   2286:                             foreach my $file (@$files) {
                   2287:                                 &Apache::lonnet::allowuploaded('/adm/grades',$file);
                   2288:                                 $lastsubonly.='<br /><a href="'.$file.'?rawmode=1" target="lonGRDs"><img src="'.&Apache::loncommon::icon($file).'" border="0" alt="" /> '.$file.'</a>';
1.596     raeburn  2289:                             }
                   2290:                         }
1.702     kruse    2291: 			$lastsubonly.='<br />';
                   2292:                     }
                   2293:                     if ($hide eq 'anon') {
                   2294:                         $lastsubonly.='<br /><b>'.&mt('Anonymous Survey').'</b>'; 
                   2295:                     } else {
1.724     raeburn  2296:              	        $lastsubonly.='<br /><b>'.&mt('Submitted Answer:').' </b>';
                   2297:                         if ($draft) {
                   2298:                             $lastsubonly.= ' <span class="LC_warning">'.&mt('Draft Copy').'</span>';
                   2299:                         }
                   2300:                         $subval =
1.702     kruse    2301: 			    &cleanRecord($subval,$responsetype,$symb,$partid,
                   2302: 					 $respid,\%record,$order,undef,$uname,$udom,$type,$trial,$rndseed);
1.724     raeburn  2303:                         if ($responsetype eq 'essay') {
                   2304:                             $subval =~ s{\n}{<br />}g;
                   2305:                         }
                   2306:                         $lastsubonly.=$subval."\n";
1.702     kruse    2307:                     }
                   2308: 	            if ($similar) {$lastsubonly.="<br /><br />$similar\n";}
                   2309: 		    $lastsubonly.='</div>';
1.41      ng       2310: 		}
1.702     kruse    2311:             }
1.151     albertel 2312: 	}
1.702     kruse    2313: 	$lastsubonly.='</div>'."\n"; # End: LC_grade_submissions_body
                   2314:     }
                   2315:     $request->print($lastsubonly);
                   2316:     if ($env{'form.lastSub'} eq 'datesub') {
1.623     www      2317:         my ($parts,$handgrade,$responseType) = &response_type($symb,\$res_error);
1.148     albertel 2318: 	$request->print(&displaySubByDates($symb,\%record,$parts,$responseType,$checkIcon,$uname,$udom));
1.720     kruse    2319:   
1.702     kruse    2320:     } 
                   2321:     if ($env{'form.lastSub'} =~ /^(last|all)$/) {
1.726     raeburn  2322:         my $identifier = (&canmodify($usec)? $counter : '');
1.702     kruse    2323:         $request->print(&Apache::loncommon::get_previous_attempt($symb,$uname,$udom,
1.257     albertel 2324: 								 $env{'request.course.id'},
1.44      ng       2325: 								 $last,'.submission',
1.726     raeburn  2326: 								 'Apache::grades::keywords_highlight',
                   2327:                                                                  $usec,$identifier));
1.41      ng       2328:     }
1.121     ng       2329:     $request->print('<input type="hidden" name="unamedom'.$counter.'" value="'.$uname.':'
                   2330: 	.$udom.'" />'."\n");
1.44      ng       2331:     # return if view submission with no grading option
1.618     www      2332:     if (!&canmodify($usec)) {
1.633     www      2333: 	$request->print('<p><span class="LC_warning">'.&mt('No grading privileges').'</span></p></div>');
1.41      ng       2334: 	return;
1.180     albertel 2335:     } else {
1.468     albertel 2336: 	$request->print('</div>'."\n");
1.41      ng       2337:     }
1.33      ng       2338: 
1.121     ng       2339:     # essay grading message center
1.624     www      2340: #    if ($env{'form.handgrade'} eq 'yes') {
                   2341:     if (1) {
1.468     albertel 2342: 	my $result='<div class="LC_grade_message_center">';
                   2343:     
                   2344: 	$result.='<div class="LC_grade_message_center_header">'.
                   2345: 	    &mt('Send Message').'</div><div class="LC_grade_message_center_body">';
1.257     albertel 2346: 	my ($lastname,$givenn) = split(/,/,$env{'form.fullname'});
1.118     ng       2347: 	my $msgfor = $givenn.' '.$lastname;
1.464     albertel 2348: 	if (scalar(@$col_fullnames) > 0) {
                   2349: 	    my $lastone = pop(@$col_fullnames);
                   2350: 	    $msgfor .= ', '.(join ', ',@$col_fullnames).' and '.$lastone.'.';
1.118     ng       2351: 	}
                   2352: 	$msgfor =~ s/\'/\\'/g; #' stupid emacs - no! javascript
1.468     albertel 2353: 	$result.='<input type="hidden" name="includemsg'.$counter.'" value="" />'."\n".
1.121     ng       2354: 	    '<input type="hidden" name="newmsg'.$counter.'" value="" />'."\n";
                   2355: 	$result.='&nbsp;<a href="javascript:msgCenter(document.SCORE,'.$counter.
1.417     albertel 2356: 	    ',\''.$msgfor.'\');" target="_self">'.
1.695     bisitz   2357: 	    &mt('Compose message to student'.(scalar(@$col_fullnames) >= 1 ? 's' : '')).'</a><label> ('.
1.350     albertel 2358: 	    &mt('incl. grades').' <input type="checkbox" name="withgrades'.$counter.'" /></label>)'.
1.695     bisitz   2359: 	    ' <img src="'.$request->dir_config('lonIconsURL').
                   2360: 	    '/mailbkgrd.gif" width="14" height="10" alt="" name="mailicon'.$counter.'" />'."\n".
1.298     www      2361: 	    '<br />&nbsp;('.
1.468     albertel 2362: 	    &mt('Message will be sent when you click on Save &amp; Next below.').")\n";
                   2363: 	$result.='</div></div>';
1.121     ng       2364: 	$request->print($result);
1.118     ng       2365:     }
1.41      ng       2366: 
                   2367:     my %seen = ();
                   2368:     my @partlist;
1.129     ng       2369:     my @gradePartRespid;
1.375     albertel 2370:     my @part_response_id = &flatten_responseType($responseType);
1.585     bisitz   2371:     $request->print(
1.588     bisitz   2372:         '<div class="LC_Box">'
                   2373:        .'<h3 class="LC_hcell">'.&mt('Assign Grades').'</h3>'
1.585     bisitz   2374:     );
1.592     bisitz   2375:     $request->print(&gradeBox_start());
1.375     albertel 2376:     foreach my $part_response_id (@part_response_id) {
                   2377:     	my ($partid,$respid) = @{ $part_response_id };
                   2378: 	my $part_resp = join('_',@{ $part_response_id });
1.322     albertel 2379: 	next if ($seen{$partid} > 0);
1.41      ng       2380: 	$seen{$partid}++;
1.393     albertel 2381: 	next if ($$handgrade{$part_resp} ne 'yes' 
                   2382: 		 && $env{'form.lastSub'} eq 'hdgrade');
1.524     raeburn  2383: 	push(@partlist,$partid);
                   2384: 	push(@gradePartRespid,$partid.'.'.$respid);
1.322     albertel 2385: 	$request->print(&gradeBox($request,$symb,$uname,$udom,$counter,$partid,\%record));
1.41      ng       2386:     }
1.585     bisitz   2387:     $request->print(&gradeBox_end()); # </div>
                   2388:     $request->print('</div>');
1.468     albertel 2389: 
                   2390:     $request->print('<div class="LC_grade_info_links">');
                   2391:     $request->print('</div>');
                   2392: 
1.45      ng       2393:     $result='<input type="hidden" name="partlist'.$counter.
                   2394: 	'" value="'.(join ":",@partlist).'" />'."\n";
1.129     ng       2395:     $result.='<input type="hidden" name="gradePartRespid'.
                   2396: 	'" value="'.(join ":",@gradePartRespid).'" />'."\n" if ($counter == 0);
1.45      ng       2397:     my $ctr = 0;
                   2398:     while ($ctr < scalar(@partlist)) {
                   2399: 	$result.='<input type="hidden" name="partid'.$counter.'_'.$ctr.'" value="'.
                   2400: 	    $partlist[$ctr].'" />'."\n";
                   2401: 	$ctr++;
                   2402:     }
1.468     albertel 2403:     $request->print($result.''."\n");
1.41      ng       2404: 
1.441     www      2405: # Done with printing info for one student
                   2406: 
1.468     albertel 2407:     $request->print('</div>');#LC_grade_show_user
1.441     www      2408: 
                   2409: 
1.41      ng       2410:     # print end of form
                   2411:     if ($counter == $total) {
1.592     bisitz   2412:         my $endform='<br /><hr /><table border="0"><tr><td>'."\n";
1.485     albertel 2413: 	$endform.='<input type="button" value="'.&mt('Save &amp; Next').'" '.
1.589     bisitz   2414: 	    'onclick="javascript:checksubmit(this.form,\'Save & Next\','.
1.417     albertel 2415: 	    $total.','.scalar(@partlist).');" target="_self" /> &nbsp;'."\n";
1.119     ng       2416: 	my $ntstu ='<select name="NTSTU">'.
                   2417: 	    '<option>1</option><option>2</option>'.
                   2418: 	    '<option>3</option><option>5</option>'.
                   2419: 	    '<option>7</option><option>10</option></select>'."\n";
1.257     albertel 2420: 	my $nsel = ($env{'form.NTSTU'} ne '' ? $env{'form.NTSTU'} : '1');
1.401     albertel 2421: 	$ntstu =~ s/<option>$nsel</<option selected="selected">$nsel</;
1.578     raeburn  2422:         $endform.=&mt('[_1]student(s)',$ntstu);
1.485     albertel 2423: 	$endform.='&nbsp;&nbsp;<input type="button" value="'.&mt('Previous').'" '.
1.589     bisitz   2424: 	    'onclick="javascript:checksubmit(this.form,\'Previous\');" target="_self" /> &nbsp;'."\n".
1.485     albertel 2425: 	    '<input type="button" value="'.&mt('Next').'" '.
1.589     bisitz   2426: 	    'onclick="javascript:checksubmit(this.form,\'Next\');" target="_self" /> &nbsp;';
1.592     bisitz   2427:         $endform.='<span class="LC_warning">'.
                   2428:                   &mt('(Next and Previous (student) do not save the scores.)').
                   2429:                   '</span>'."\n" ;
1.349     albertel 2430:         $endform.="<input type='hidden' value='".&get_increment().
1.348     bowersj2 2431:             "' name='increment' />";
1.485     albertel 2432: 	$endform.='</td></tr></table></form>';
1.41      ng       2433: 	$request->print($endform);
                   2434:     }
                   2435:     return '';
1.38      ng       2436: }
                   2437: 
1.464     albertel 2438: sub check_collaborators {
                   2439:     my ($symb,$uname,$udom,$record,$handgrade,$counter) = @_;
                   2440:     my ($result,@col_fullnames);
                   2441:     my ($classlist,undef,$fullname) = &getclasslist('all','0');
                   2442:     foreach my $part (keys(%$handgrade)) {
                   2443: 	my $ncol = &Apache::lonnet::EXT('resource.'.$part.
                   2444: 					'.maxcollaborators',
                   2445: 					$symb,$udom,$uname);
                   2446: 	next if ($ncol <= 0);
                   2447: 	$part =~ s/\_/\./g;
                   2448: 	next if ($record->{'resource.'.$part.'.collaborators'} eq '');
                   2449: 	my (@good_collaborators, @bad_collaborators);
                   2450: 	foreach my $possible_collaborator
1.630     www      2451: 	    (split(/[,;\s]+/,$record->{'resource.'.$part.'.collaborators'})) { 
1.464     albertel 2452: 	    $possible_collaborator =~ s/[\$\^\(\)]//g;
                   2453: 	    next if ($possible_collaborator eq '');
1.631     www      2454: 	    my ($co_name,$co_dom) = split(/:/,$possible_collaborator);
1.464     albertel 2455: 	    $co_dom = $udom if (! defined($co_dom) || $co_dom =~ /^domain$/i);
                   2456: 	    next if ($co_name eq $uname && $co_dom eq $udom);
                   2457: 	    # Doing this grep allows 'fuzzy' specification
                   2458: 	    my @matches = grep(/^\Q$co_name\E:\Q$co_dom\E$/i, 
                   2459: 			       keys(%$classlist));
                   2460: 	    if (! scalar(@matches)) {
                   2461: 		push(@bad_collaborators, $possible_collaborator);
                   2462: 	    } else {
                   2463: 		push(@good_collaborators, @matches);
                   2464: 	    }
                   2465: 	}
                   2466: 	if (scalar(@good_collaborators) != 0) {
1.630     www      2467: 	    $result.='<br />'.&mt('Collaborators:').'<ol>';
1.464     albertel 2468: 	    foreach my $name (@good_collaborators) {
                   2469: 		my ($lastname,$givenn) = split(/,/,$$fullname{$name});
                   2470: 		push(@col_fullnames, $givenn.' '.$lastname);
1.630     www      2471: 		$result.='<li>'.$fullname->{$name}.'</li>';
1.464     albertel 2472: 	    }
1.630     www      2473: 	    $result.='</ol><br />'."\n";
1.466     albertel 2474: 	    my ($part)=split(/\./,$part);
1.464     albertel 2475: 	    $result.='<input type="hidden" name="collaborator'.$counter.
                   2476: 		'" value="'.$part.':'.(join ':',@good_collaborators).'" />'.
                   2477: 		"\n";
                   2478: 	}
                   2479: 	if (scalar(@bad_collaborators) > 0) {
1.466     albertel 2480: 	    $result.='<div class="LC_warning">';
1.464     albertel 2481: 	    $result.=&mt('This student has submitted [quant,_1,invalid collaborator]: [_2]',scalar(@bad_collaborators),join(', ',@bad_collaborators));
                   2482: 	    $result .= '</div>';
                   2483: 	}         
                   2484: 	if (scalar(@bad_collaborators > $ncol)) {
1.466     albertel 2485: 	    $result .= '<div class="LC_warning">';
1.464     albertel 2486: 	    $result .= &mt('This student has submitted too many '.
                   2487: 		'collaborators.  Maximum is [_1].',$ncol);
                   2488: 	    $result .= '</div>';
                   2489: 	}
                   2490:     }
                   2491:     return ($result,$fullname,\@col_fullnames);
                   2492: }
                   2493: 
1.44      ng       2494: #--- Retrieve the last submission for all the parts
1.38      ng       2495: sub get_last_submission {
1.119     ng       2496:     my ($returnhash)=@_;
1.596     raeburn  2497:     my (@string,$timestamp,%lasthidden);
1.119     ng       2498:     if ($$returnhash{'version'}) {
1.46      ng       2499: 	my %lasthash=();
                   2500: 	my ($version);
1.119     ng       2501: 	for ($version=1;$version<=$$returnhash{'version'};$version++) {
1.397     albertel 2502: 	    foreach my $key (sort(split(/\:/,
                   2503: 					$$returnhash{$version.':keys'}))) {
                   2504: 		$lasthash{$key}=$$returnhash{$version.':'.$key};
                   2505: 		$timestamp = 
1.545     raeburn  2506: 		    &Apache::lonlocal::locallocaltime($$returnhash{$version.':timestamp'});
1.46      ng       2507: 	    }
                   2508: 	}
1.640     raeburn  2509:         my (%typeparts,%randombytry);
1.596     raeburn  2510:         my $showsurv = 
                   2511:             &Apache::lonnet::allowed('vas',$env{'request.course.id'});
                   2512:         foreach my $key (sort(keys(%lasthash))) {
                   2513:             if ($key =~ /\.type$/) {
                   2514:                 if (($lasthash{$key} eq 'anonsurvey') || 
1.640     raeburn  2515:                     ($lasthash{$key} eq 'anonsurveycred') ||
                   2516:                     ($lasthash{$key} eq 'randomizetry')) {
1.596     raeburn  2517:                     my ($ign,@parts) = split(/\./,$key);
                   2518:                     pop(@parts);
1.641     raeburn  2519:                     my $id = join('.',@parts);
1.640     raeburn  2520:                     if ($lasthash{$key} eq 'randomizetry') {
                   2521:                         $randombytry{$ign.'.'.$id} = $lasthash{$key};
                   2522:                     } else {
                   2523:                         unless ($showsurv) {
                   2524:                             $typeparts{$ign.'.'.$id} = $lasthash{$key};
                   2525:                         }
1.596     raeburn  2526:                     }
                   2527:                     delete($lasthash{$key});
                   2528:                 }
                   2529:             }
                   2530:         }
                   2531:         my @hidden = keys(%typeparts);
1.640     raeburn  2532:         my @randomize = keys(%randombytry);
1.397     albertel 2533: 	foreach my $key (keys(%lasthash)) {
                   2534: 	    next if ($key !~ /\.submission$/);
1.596     raeburn  2535:             my $hide;
                   2536:             if (@hidden) {
                   2537:                 foreach my $id (@hidden) {
                   2538:                     if ($key =~ /^\Q$id\E/) {
1.640     raeburn  2539:                         $hide = 'anon';
1.596     raeburn  2540:                         last;
                   2541:                     }
                   2542:                 }
                   2543:             }
1.640     raeburn  2544:             unless ($hide) {
                   2545:                 if (@randomize) {
1.732     raeburn  2546:                     foreach my $id (@randomize) {
1.640     raeburn  2547:                         if ($key =~ /^\Q$id\E/) {
                   2548:                             $hide = 'rand';
                   2549:                             last;
                   2550:                         }
                   2551:                     }
                   2552:                 }
                   2553:             }
1.397     albertel 2554: 	    my ($partid,$foo) = split(/submission$/,$key);
1.724     raeburn  2555: 	    my $draft  = $lasthash{$partid.'awarddetail'} eq 'DRAFT' ? 1 : 0;
                   2556:             push(@string, join(':', $key, $hide, $draft, (
1.716     bisitz   2557:                 ref($lasthash{$key}) eq 'ARRAY' ?
                   2558:                     join(',', @{$lasthash{$key}}) : $lasthash{$key}) ));
1.41      ng       2559: 	}
                   2560:     }
1.397     albertel 2561:     if (!@string) {
                   2562: 	$string[0] =
1.539     riegler  2563: 	    '<span class="LC_warning">'.&mt('Nothing submitted - no attempts.').'</span>';
1.397     albertel 2564:     }
                   2565:     return (\@string,\$timestamp);
1.38      ng       2566: }
1.35      ng       2567: 
1.44      ng       2568: #--- High light keywords, with style choosen by user.
1.38      ng       2569: sub keywords_highlight {
1.44      ng       2570:     my $string    = shift;
1.257     albertel 2571:     my $size      = $env{'form.kwsize'} eq '0' ? '' : 'size='.$env{'form.kwsize'};
                   2572:     my $styleon   = $env{'form.kwstyle'} eq ''  ? '' : $env{'form.kwstyle'};
1.41      ng       2573:     (my $styleoff = $styleon) =~ s/\</\<\//;
1.257     albertel 2574:     my @keylist   = split(/[,\s+]/,$env{'form.keywords'});
1.398     albertel 2575:     foreach my $keyword (@keylist) {
                   2576: 	$string =~ s/\b\Q$keyword\E(\b|\.)/<font color\=$env{'form.kwclr'} $size\>$styleon$keyword$styleoff<\/font>/gi;
1.41      ng       2577:     }
                   2578:     return $string;
1.38      ng       2579: }
1.36      ng       2580: 
1.671     raeburn  2581: # For Tasks provide a mechanism to display previous version for one specific student
                   2582: 
                   2583: sub show_previous_task_version {
                   2584:     my ($request,$symb) = @_;
                   2585:     if ($symb eq '') {
1.717     bisitz   2586:         $request->print(
                   2587:             '<span class="LC_error">'.
                   2588:             &mt('Unable to handle ambiguous references.').
                   2589:             '</span>');
1.671     raeburn  2590:         return '';
                   2591:     }
                   2592:     my ($uname,$udom) = ($env{'form.student'},$env{'form.userdom'});
                   2593:     my $usec = &Apache::lonnet::getsection($udom,$uname,$env{'request.course.id'});
                   2594:     if (!&canview($usec)) {
1.712     bisitz   2595:         $request->print(
                   2596:             '<span class="LC_warning">'.
1.713     bisitz   2597:             &mt('Unable to view previous version for requested student.').
1.712     bisitz   2598:             ' '.&mt('([_1] in section [_2] in course id [_3])',
                   2599:                     $uname.':'.$udom,$usec,$env{'request.course.id'}).
                   2600:             '</span>');
1.671     raeburn  2601:         return;
                   2602:     }
                   2603:     my $mode = 'both';
                   2604:     my $isTask = ($symb =~/\.task$/);
                   2605:     if ($isTask) {
                   2606:         if ($env{'form.previousversion'} =~ /^\d+$/) {
                   2607:             if ($env{'form.fullname'} eq '') {
                   2608:                 $env{'form.fullname'} =
                   2609:                     &Apache::loncommon::plainname($uname,$udom,'lastname');
                   2610:             }
                   2611:             my $probtitle=&Apache::lonnet::gettitle($symb);
                   2612:             $request->print("\n\n".
                   2613:                             '<div class="LC_grade_show_user">'.
                   2614:                             '<h2>'.&nameUserString(undef,$env{'form.fullname'},$uname,$udom).
                   2615:                             '</h2>'."\n");
                   2616:             &Apache::lonxml::clear_problem_counter();
                   2617:             $request->print(&show_problem($request,$symb,$uname,$udom,1,1,$mode,
                   2618:                             {'previousversion' => $env{'form.previousversion'} }));
                   2619:             $request->print("\n</div>");
                   2620:         }
                   2621:     }
                   2622:     return;
                   2623: }
                   2624: 
                   2625: sub choose_task_version_form {
                   2626:     my ($symb,$uname,$udom,$nomenu) = @_;
                   2627:     my $isTask = ($symb =~/\.task$/);
                   2628:     my ($current,$version,$result,$js,$displayed,$rowtitle);
                   2629:     if ($isTask) {
                   2630:         my %record = &Apache::lonnet::restore($symb,$env{'request.course.id'},
                   2631:                                               $udom,$uname);
                   2632:         if (($record{'resource.0.version'} eq '') ||
                   2633:             ($record{'resource.0.version'} < 2)) {
                   2634:             return ($record{'resource.0.version'},
                   2635:                     $record{'resource.0.version'},$result,$js);
                   2636:         } else {
                   2637:             $current = $record{'resource.0.version'};
                   2638:         }
                   2639:         if ($env{'form.previousversion'}) {
                   2640:             $displayed = $env{'form.previousversion'};
                   2641:             $rowtitle = &mt('Choose another version:')
                   2642:         } else {
                   2643:             $displayed = $current;
                   2644:             $rowtitle = &mt('Show earlier version:');
                   2645:         }
                   2646:         $result = '<div class="LC_left_float">';
                   2647:         my $list;
                   2648:         my $numversions = 0;
                   2649:         for (my $i=1; $i<=$record{'resource.0.version'}; $i++) {
                   2650:             if ($i == $current) {
                   2651:                 if (!$env{'form.previousversion'} || $nomenu) {
                   2652:                     next;
                   2653:                 } else {
                   2654:                     $list .= '<option value="'.$i.'">'.&mt('Current').'</option>'."\n";
                   2655:                     $numversions ++;
                   2656:                 }
                   2657:             } elsif (defined($record{'resource.'.$i.'.0.status'})) {
                   2658:                 unless ($i == $env{'form.previousversion'}) {
                   2659:                     $numversions ++;
                   2660:                 }
                   2661:                 $list .= '<option value="'.$i.'">'.$i.'</option>'."\n";
                   2662:             }
                   2663:         }
                   2664:         if ($numversions) {
                   2665:             $symb = &HTML::Entities::encode($symb,'<>"&');
                   2666:             $result .=
                   2667:                 '<form name="getprev" method="post" action=""'.
                   2668:                 ' onsubmit="return previousVersion('."'$uname','$udom','$symb','$displayed'".');">'.
                   2669:                 &Apache::loncommon::start_data_table().
                   2670:                 &Apache::loncommon::start_data_table_row().
                   2671:                 '<th align="left">'.$rowtitle.'</th>'.
                   2672:                 '<td><select name="version">'.
                   2673:                 '<option>'.&mt('Select').'</option>'.
                   2674:                 $list.
                   2675:                 '</select></td>'.
                   2676:                 &Apache::loncommon::end_data_table_row();
                   2677:             unless ($nomenu) {
                   2678:                 $result .= &Apache::loncommon::start_data_table_row().
                   2679:                 '<th align="left">'.&mt('Open in new window').'</th>'.
                   2680:                 '<td><span class="LC_nobreak">'.
                   2681:                 '<label><input type="radio" name="prevwin" value="1" />'.
                   2682:                 &mt('Yes').'</label>'.
                   2683:                 '<label><input type="radio" name="prevwin" value="0" checked="checked" />'.&mt('No').'</label>'.
                   2684:                 '</span></td>'.
                   2685:                 &Apache::loncommon::end_data_table_row();
                   2686:             }
                   2687:             $result .=
                   2688:                 &Apache::loncommon::start_data_table_row().
                   2689:                 '<th align="left">&nbsp;</th>'.
                   2690:                 '<td>'.
                   2691:                 '<input type="submit" name="prevsub" value="'.&mt('Display').'" />'.
                   2692:                 '</td>'.
                   2693:                 &Apache::loncommon::end_data_table_row().
                   2694:                 &Apache::loncommon::end_data_table().
                   2695:                 '</form>';
                   2696:             $js = &previous_display_javascript($nomenu,$current);
                   2697:         } elsif ($displayed && $nomenu) {
                   2698:             $result .= '<a href="javascript:window.close()">'.&mt('Close window').'</a>';
                   2699:         } else {
                   2700:             $result .= &mt('No previous versions to show for this student');
                   2701:         }
                   2702:         $result .= '</div>';
                   2703:     }
                   2704:     return ($current,$displayed,$result,$js);
                   2705: }
                   2706: 
                   2707: sub previous_display_javascript {
                   2708:     my ($nomenu,$current) = @_;
                   2709:     my $js = <<"JSONE";
                   2710: <script type="text/javascript">
                   2711: // <![CDATA[
                   2712: function previousVersion(uname,udom,symb) {
                   2713:     var current = '$current';
                   2714:     var version = document.getprev.version.options[document.getprev.version.selectedIndex].value;
                   2715:     var prevstr = new RegExp("^\\\\d+\$");
                   2716:     if (!prevstr.test(version)) {
                   2717:         return false;
                   2718:     }
                   2719:     var url = '';
                   2720:     if (version == current) {
                   2721:         url = '/adm/grades?student='+uname+'&userdom='+udom+'&symb='+symb+'&command=submission';
                   2722:     } else {
                   2723:         url = '/adm/grades?student='+uname+'&userdom='+udom+'&symb='+symb+'&command=versionsub&previousversion='+version;
                   2724:     }
                   2725: JSONE
                   2726:     if ($nomenu) {
                   2727:         $js .= <<"JSTWO";
                   2728:     document.location.href = url;
                   2729: JSTWO
                   2730:     } else {
                   2731:         $js .= <<"JSTHREE";
                   2732:     var newwin = 0;
                   2733:     for (var i=0; i<document.getprev.prevwin.length; i++) {
                   2734:         if (document.getprev.prevwin[i].checked == true) {
                   2735:             newwin = document.getprev.prevwin[i].value;
                   2736:         }
                   2737:     }
                   2738:     if (newwin == 1) {
                   2739:         var options = 'height=600,width=800,resizable=yes,scrollbars=yes,location=no,menubar=no,toolbar=no';
                   2740:         url = url+'&inhibitmenu=yes';
                   2741:         if (typeof(previousWin) == 'undefined' || previousWin.closed) {
                   2742:             previousWin = window.open(url,'',options,1);
                   2743:         } else {
                   2744:             previousWin.location.href = url;
                   2745:         }
                   2746:         previousWin.focus();
                   2747:         return false;
                   2748:     } else {
                   2749:         document.location.href = url;
                   2750:         return false;
                   2751:     }
                   2752: JSTHREE
                   2753:     }
                   2754:     $js .= <<"ENDJS";
                   2755:     return false;
                   2756: }
                   2757: // ]]>
                   2758: </script>
                   2759: ENDJS
                   2760: 
                   2761: }
                   2762: 
1.44      ng       2763: #--- Called from submission routine
1.38      ng       2764: sub processHandGrade {
1.608     www      2765:     my ($request,$symb) = @_;
1.324     albertel 2766:     my (undef,undef,$url) = &Apache::lonnet::decode_symb($symb);
1.257     albertel 2767:     my $button = $env{'form.gradeOpt'};
                   2768:     my $ngrade = $env{'form.NCT'};
                   2769:     my $ntstu  = $env{'form.NTSTU'};
1.301     albertel 2770:     my $cdom   = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   2771:     my $cnum   = $env{'course.'.$env{'request.course.id'}.'.num'};
                   2772: 
1.44      ng       2773:     if ($button eq 'Save & Next') {
                   2774: 	my $ctr = 0;
                   2775: 	while ($ctr < $ngrade) {
1.257     albertel 2776: 	    my ($uname,$udom) = split(/:/,$env{'form.unamedom'.$ctr});
1.726     raeburn  2777: 	    my ($errorflag,$pts,$wgt,$numhidden) = 
                   2778:                 &saveHandGrade($request,$symb,$uname,$udom,$ctr);
1.71      ng       2779: 	    if ($errorflag eq 'no_score') {
                   2780: 		$ctr++;
                   2781: 		next;
                   2782: 	    }
1.104     albertel 2783: 	    if ($errorflag eq 'not_allowed') {
1.721     bisitz   2784: 		$request->print(
                   2785:                     '<span class="LC_error">'
                   2786:                    .&mt('Not allowed to modify grades for [_1]',"$uname:$udom")
                   2787:                    .'</span>');
1.104     albertel 2788: 		$ctr++;
                   2789: 		next;
                   2790: 	    }
1.726     raeburn  2791:             if ($numhidden) {
                   2792:                 $request->print(
                   2793:                     '<span class="LC_info">'
                   2794:                    .&mt('For [_1]: [quant,_2,transaction] hidden',"$uname:$udom",$numhidden)
                   2795:                    .'</span><br />');
                   2796:             }
1.257     albertel 2797: 	    my $includemsg = $env{'form.includemsg'.$ctr};
1.44      ng       2798: 	    my ($subject,$message,$msgstatus) = ('','','');
1.418     albertel 2799: 	    my $restitle = &Apache::lonnet::gettitle($symb);
                   2800:             my ($feedurl,$showsymb) =
                   2801: 		&get_feedurl_and_symb($symb,$uname,$udom);
                   2802: 	    my $messagetail;
1.62      albertel 2803: 	    if ($includemsg =~ /savemsg|newmsg\Q$ctr\E/) {
1.298     www      2804: 		$subject = $env{'form.msgsub'} if ($includemsg =~ /msgsub/);
1.295     www      2805: 		unless ($subject=~/\w/) { $subject=&mt('Grading Feedback'); }
1.386     raeburn  2806: 		$subject.=' ['.$restitle.']';
1.44      ng       2807: 		my (@msgnum) = split(/,/,$includemsg);
                   2808: 		foreach (@msgnum) {
1.257     albertel 2809: 		    $message.=$env{'form.'.$_} if ($_ =~ /savemsg|newmsg/ && $_ ne '');
1.44      ng       2810: 		}
1.80      ng       2811: 		$message =&Apache::lonfeedback::clear_out_html($message);
1.298     www      2812: 		if ($env{'form.withgrades'.$ctr}) {
                   2813: 		    $message.="\n\nPoint".($pts > 1 ? 's':'').' awarded = '.$pts.' out of '.$wgt;
1.386     raeburn  2814: 		    $messagetail = " for <a href=\"".
1.605     www      2815: 		                   $feedurl."?symb=$showsymb\">$restitle</a>";
1.386     raeburn  2816: 		}
                   2817: 		$msgstatus = 
                   2818:                     &Apache::lonmsg::user_normal_msg($uname,$udom,$subject,
                   2819: 						     $message.$messagetail,
1.418     albertel 2820:                                                      undef,$feedurl,undef,
1.386     raeburn  2821:                                                      undef,undef,$showsymb,
                   2822:                                                      $restitle);
1.574     bisitz   2823: 		$request->print('<br />'.&mt('Sending message to [_1]',$uname.':'.$udom).': '.
1.652     raeburn  2824: 				$msgstatus.'<br />');
1.44      ng       2825: 	    }
1.257     albertel 2826: 	    if ($env{'form.collaborator'.$ctr}) {
1.155     albertel 2827: 		my @collabstrs=&Apache::loncommon::get_env_multiple("form.collaborator$ctr");
1.150     albertel 2828: 		foreach my $collabstr (@collabstrs) {
                   2829: 		    my ($part,@collaborators) = split(/:/,$collabstr);
1.310     banghart 2830: 		    foreach my $collaborator (@collaborators) {
1.150     albertel 2831: 			my ($errorflag,$pts,$wgt) = 
1.324     albertel 2832: 			    &saveHandGrade($request,$symb,$collaborator,$udom,$ctr,
1.257     albertel 2833: 					   $env{'form.unamedom'.$ctr},$part);
1.150     albertel 2834: 			if ($errorflag eq 'not_allowed') {
1.362     albertel 2835: 			    $request->print("<span class=\"LC_error\">".&mt('Not allowed to modify grades for [_1]',"$collaborator:$udom")."</span>");
1.150     albertel 2836: 			    next;
1.418     albertel 2837: 			} elsif ($message ne '') {
                   2838: 			    my ($baseurl,$showsymb) = 
                   2839: 				&get_feedurl_and_symb($symb,$collaborator,
                   2840: 						      $udom);
                   2841: 			    if ($env{'form.withgrades'.$ctr}) {
                   2842: 				$messagetail = " for <a href=\"".
1.605     www      2843:                                     $baseurl."?symb=$showsymb\">$restitle</a>";
1.150     albertel 2844: 			    }
1.418     albertel 2845: 			    $msgstatus = 
                   2846: 				&Apache::lonmsg::user_normal_msg($collaborator,$udom,$subject,$message.$messagetail,undef,$baseurl,undef,undef,undef,$showsymb,$restitle);
1.104     albertel 2847: 			}
1.44      ng       2848: 		    }
                   2849: 		}
                   2850: 	    }
                   2851: 	    $ctr++;
                   2852: 	}
                   2853:     }
                   2854: 
1.624     www      2855: #    if ($env{'form.handgrade'} eq 'yes') {
                   2856:     if (1) {
1.119     ng       2857: 	# Keywords sorted in alphabatical order
1.257     albertel 2858: 	my $loginuser = $env{'user.name'}.':'.$env{'user.domain'};
1.119     ng       2859: 	my %keyhash = ();
1.257     albertel 2860: 	$env{'form.keywords'}           =~ s/,\s{0,}|\s+/ /g;
                   2861: 	$env{'form.keywords'}           =~ s/^\s+|\s+$//;
                   2862: 	my (@keywords) = sort(split(/\s+/,$env{'form.keywords'}));
                   2863: 	$env{'form.keywords'} = join(' ',@keywords);
                   2864: 	$keyhash{$symb.'_keywords'}     = $env{'form.keywords'};
                   2865: 	$keyhash{$symb.'_subject'}      = $env{'form.msgsub'};
                   2866: 	$keyhash{$loginuser.'_kwclr'}   = $env{'form.kwclr'};
                   2867: 	$keyhash{$loginuser.'_kwsize'}  = $env{'form.kwsize'};
                   2868: 	$keyhash{$loginuser.'_kwstyle'} = $env{'form.kwstyle'};
1.119     ng       2869: 
                   2870: 	# message center - Order of message gets changed. Blank line is eliminated.
1.257     albertel 2871: 	# New messages are saved in env for the next student.
1.119     ng       2872: 	# All messages are saved in nohist_handgrade.db
                   2873: 	my ($ctr,$idx) = (1,1);
1.257     albertel 2874: 	while ($ctr <= $env{'form.savemsgN'}) {
                   2875: 	    if ($env{'form.savemsg'.$ctr} ne '') {
                   2876: 		$keyhash{$symb.'_savemsg'.$idx} = $env{'form.savemsg'.$ctr};
1.119     ng       2877: 		$idx++;
                   2878: 	    }
                   2879: 	    $ctr++;
1.41      ng       2880: 	}
1.119     ng       2881: 	$ctr = 0;
                   2882: 	while ($ctr < $ngrade) {
1.257     albertel 2883: 	    if ($env{'form.newmsg'.$ctr} ne '') {
                   2884: 		$keyhash{$symb.'_savemsg'.$idx} = $env{'form.newmsg'.$ctr};
                   2885: 		$env{'form.savemsg'.$idx} = $env{'form.newmsg'.$ctr};
1.119     ng       2886: 		$idx++;
                   2887: 	    }
                   2888: 	    $ctr++;
1.41      ng       2889: 	}
1.257     albertel 2890: 	$env{'form.savemsgN'} = --$idx;
                   2891: 	$keyhash{$symb.'_savemsgN'} = $env{'form.savemsgN'};
1.119     ng       2892: 	my $putresult = &Apache::lonnet::put
1.301     albertel 2893: 	    ('nohist_handgrade',\%keyhash,$cdom,$cnum);
1.41      ng       2894:     }
1.44      ng       2895:     # Called by Save & Refresh from Highlight Attribute Window
1.257     albertel 2896:     my (undef,undef,$fullname) = &getclasslist($env{'form.section'},'1');
                   2897:     if ($env{'form.refresh'} eq 'on') {
1.86      ng       2898: 	my ($ctr,$total) = (0,0);
                   2899: 	while ($ctr < $ngrade) {
1.257     albertel 2900: 	    $total++ if  $env{'form.unamedom'.$ctr} ne '';
1.86      ng       2901: 	    $ctr++;
                   2902: 	}
1.257     albertel 2903: 	$env{'form.NTSTU'}=$ngrade;
1.86      ng       2904: 	$ctr = 0;
                   2905: 	while ($ctr < $total) {
1.257     albertel 2906: 	    my $processUser = $env{'form.unamedom'.$ctr};
                   2907: 	    ($env{'form.student'},$env{'form.userdom'}) = split(/:/,$processUser);
                   2908: 	    $env{'form.fullname'} = $$fullname{$processUser};
1.625     www      2909: 	    &submission($request,$ctr,$total-1,$symb);
1.41      ng       2910: 	    $ctr++;
                   2911: 	}
                   2912: 	return '';
                   2913:     }
1.36      ng       2914: 
1.44      ng       2915:     # Get the next/previous one or group of students
1.257     albertel 2916:     my $firststu = $env{'form.unamedom0'};
                   2917:     my $laststu = $env{'form.unamedom'.($ngrade-1)};
1.119     ng       2918:     my $ctr = 2;
1.41      ng       2919:     while ($laststu eq '') {
1.257     albertel 2920: 	$laststu  = $env{'form.unamedom'.($ngrade-$ctr)};
1.41      ng       2921: 	$ctr++;
                   2922: 	$laststu = $firststu if ($ctr > $ngrade);
                   2923:     }
1.44      ng       2924: 
1.41      ng       2925:     my (@parsedlist,@nextlist);
                   2926:     my ($nextflg) = 0;
1.524     raeburn  2927:     foreach my $item (sort 
1.294     albertel 2928: 	     {
                   2929: 		 if (lc($$fullname{$a}) ne lc($$fullname{$b})) {
                   2930: 		     return (lc($$fullname{$a}) cmp lc($$fullname{$b}));
                   2931: 		 }
                   2932: 		 return $a cmp $b;
                   2933: 	     } (keys(%$fullname))) {
1.605     www      2934: # FIXME: this is fishy, looks like the button label
1.41      ng       2935: 	if ($nextflg == 1 && $button =~ /Next$/) {
1.524     raeburn  2936: 	    push(@parsedlist,$item);
1.41      ng       2937: 	}
1.524     raeburn  2938: 	$nextflg = 1 if ($item eq $laststu);
1.41      ng       2939: 	if ($button eq 'Previous') {
1.524     raeburn  2940: 	    last if ($item eq $firststu);
                   2941: 	    push(@parsedlist,$item);
1.41      ng       2942: 	}
                   2943:     }
                   2944:     $ctr = 0;
1.605     www      2945: # FIXME: this is fishy, looks like the button label
1.41      ng       2946:     @parsedlist = reverse @parsedlist if ($button eq 'Previous');
1.582     raeburn  2947:     my $res_error;
                   2948:     my ($partlist) = &response_type($symb,\$res_error);
                   2949:     if ($res_error) {
                   2950:         $request->print(&navmap_errormsg());
                   2951:         return;
                   2952:     }
1.41      ng       2953:     foreach my $student (@parsedlist) {
1.257     albertel 2954: 	my $submitonly=$env{'form.submitonly'};
1.41      ng       2955: 	my ($uname,$udom) = split(/:/,$student);
1.301     albertel 2956: 	
                   2957: 	if ($submitonly eq 'queued') {
                   2958: 	    my %queue_status = 
                   2959: 		&Apache::bridgetask::get_student_status($symb,$cdom,$cnum,
                   2960: 							$udom,$uname);
                   2961: 	    next if (!defined($queue_status{'gradingqueue'}));
                   2962: 	}
                   2963: 
1.156     albertel 2964: 	if ($submitonly =~ /^(yes|graded|incorrect)$/) {
1.257     albertel 2965: #	    my %record = &Apache::lonnet::restore($symb,$env{'request.course.id'},$udom,$uname);
1.324     albertel 2966: 	    my %status=&student_gradeStatus($symb,$udom,$uname,$partlist);
1.145     albertel 2967: 	    my $submitted = 0;
1.248     albertel 2968: 	    my $ungraded = 0;
                   2969: 	    my $incorrect = 0;
1.524     raeburn  2970: 	    foreach my $item (keys(%status)) {
                   2971: 		$submitted = 1 if ($status{$item} ne 'nothing');
                   2972: 		$ungraded = 1 if ($status{$item} =~ /^ungraded/);
                   2973: 		$incorrect = 1 if ($status{$item} =~ /^incorrect/);
                   2974: 		my ($foo,$partid,$foo1) = split(/\./,$item);
1.145     albertel 2975: 		if ($status{'resource.'.$partid.'.submitted_by'} ne '') {
                   2976: 		    $submitted = 0;
                   2977: 		}
1.41      ng       2978: 	    }
1.156     albertel 2979: 	    next if (!$submitted && ($submitonly eq 'yes' ||
                   2980: 				     $submitonly eq 'incorrect' ||
                   2981: 				     $submitonly eq 'graded'));
1.248     albertel 2982: 	    next if (!$ungraded && ($submitonly eq 'graded'));
                   2983: 	    next if (!$incorrect && $submitonly eq 'incorrect');
1.41      ng       2984: 	}
1.524     raeburn  2985: 	push(@nextlist,$student) if ($ctr < $ntstu);
1.129     ng       2986: 	last if ($ctr == $ntstu);
1.41      ng       2987: 	$ctr++;
                   2988:     }
1.36      ng       2989: 
1.41      ng       2990:     $ctr = 0;
                   2991:     my $total = scalar(@nextlist)-1;
1.39      ng       2992: 
1.524     raeburn  2993:     foreach (sort(@nextlist)) {
1.41      ng       2994: 	my ($uname,$udom,$submitter) = split(/:/);
1.257     albertel 2995: 	$env{'form.student'}  = $uname;
                   2996: 	$env{'form.userdom'}  = $udom;
                   2997: 	$env{'form.fullname'} = $$fullname{$_};
1.625     www      2998: 	&submission($request,$ctr,$total,$symb);
1.41      ng       2999: 	$ctr++;
                   3000:     }
                   3001:     if ($total < 0) {
1.653     raeburn  3002: 	my $the_end.='<p>'.&mt('[_1]Message:[_2] No more students for this section or class.','<b>','</b>').'</p>'."\n";
1.41      ng       3003: 	$request->print($the_end);
                   3004:     }
                   3005:     return '';
1.38      ng       3006: }
1.36      ng       3007: 
1.44      ng       3008: #---- Save the score and award for each student, if changed
1.38      ng       3009: sub saveHandGrade {
1.324     albertel 3010:     my ($request,$symb,$stuname,$domain,$newflg,$submitter,$part) = @_;
1.342     banghart 3011:     my @version_parts;
1.104     albertel 3012:     my $usec = &Apache::lonnet::getsection($domain,$stuname,
1.257     albertel 3013: 					   $env{'request.course.id'});
1.104     albertel 3014:     if (!&canmodify($usec)) { return('not_allowed'); }
1.337     banghart 3015:     my %record = &Apache::lonnet::restore($symb,$env{'request.course.id'},$domain,$stuname);
1.251     banghart 3016:     my @parts_graded;
1.77      ng       3017:     my %newrecord  = ();
1.726     raeburn  3018:     my ($pts,$wgt,$totchg) = ('','',0);
1.269     raeburn  3019:     my %aggregate = ();
                   3020:     my $aggregateflag = 0;
1.726     raeburn  3021:     if ($env{'form.HIDE'.$newflg}) {
1.727     raeburn  3022:         my ($version,$parts) = split(/:/,$env{'form.HIDE'.$newflg},2);
1.728     raeburn  3023:         my $numchgs = &makehidden($version,$parts,\%record,$symb,$domain,$stuname,1);
1.726     raeburn  3024:         $totchg += $numchgs;
                   3025:     }
1.301     albertel 3026:     my @parts = split(/:/,$env{'form.partlist'.$newflg});
                   3027:     foreach my $new_part (@parts) {
1.337     banghart 3028: 	#collaborator ($submi may vary for different parts
1.259     banghart 3029: 	if ($submitter && $new_part ne $part) { next; }
                   3030: 	my $dropMenu = $env{'form.GD_SEL'.$newflg.'_'.$new_part};
1.125     ng       3031: 	if ($dropMenu eq 'excused') {
1.259     banghart 3032: 	    if ($record{'resource.'.$new_part.'.solved'} ne 'excused') {
                   3033: 		$newrecord{'resource.'.$new_part.'.solved'} = 'excused';
                   3034: 		if (exists($record{'resource.'.$new_part.'.awarded'})) {
                   3035: 		    $newrecord{'resource.'.$new_part.'.awarded'} = '';
1.58      albertel 3036: 		}
1.364     banghart 3037: 	        $newrecord{'resource.'.$new_part.'.regrader'}="$env{'user.name'}:$env{'user.domain'}";
1.58      albertel 3038: 	    }
1.125     ng       3039: 	} elsif ($dropMenu eq 'reset status'
1.259     banghart 3040: 		 && exists($record{'resource.'.$new_part.'.solved'})) { #don't bother if no old records -> no attempts
1.524     raeburn  3041: 	    foreach my $key (keys(%record)) {
1.259     banghart 3042: 		if ($key=~/^resource\.\Q$new_part\E\./) { $newrecord{$key} = ''; }
1.197     albertel 3043: 	    }
1.259     banghart 3044: 	    $newrecord{'resource.'.$new_part.'.regrader'}=
1.257     albertel 3045: 		"$env{'user.name'}:$env{'user.domain'}";
1.270     albertel 3046:             my $totaltries = $record{'resource.'.$part.'.tries'};
                   3047: 
                   3048:             my %last_resets = &get_last_resets($symb,$env{'request.course.id'},
                   3049: 					       [$new_part]);
                   3050:             my $aggtries =$totaltries;
1.269     raeburn  3051:             if ($last_resets{$new_part}) {
1.270     albertel 3052:                 $aggtries = &get_num_tries(\%record,$last_resets{$new_part},
                   3053: 					   $new_part);
1.269     raeburn  3054:             }
1.270     albertel 3055: 
                   3056:             my $solvedstatus = $record{'resource.'.$new_part.'.solved'};
1.269     raeburn  3057:             if ($aggtries > 0) {
1.327     albertel 3058:                 &decrement_aggs($symb,$new_part,\%aggregate,$aggtries,$totaltries,$solvedstatus);
1.269     raeburn  3059:                 $aggregateflag = 1;
                   3060:             }
1.125     ng       3061: 	} elsif ($dropMenu eq '') {
1.259     banghart 3062: 	    $pts = ($env{'form.GD_BOX'.$newflg.'_'.$new_part} ne '' ? 
                   3063: 		    $env{'form.GD_BOX'.$newflg.'_'.$new_part} : 
                   3064: 		    $env{'form.RADVAL'.$newflg.'_'.$new_part});
                   3065: 	    if ($pts eq '' && $env{'form.GD_SEL'.$newflg.'_'.$new_part} eq '') {
1.153     albertel 3066: 		next;
                   3067: 	    }
1.259     banghart 3068: 	    $wgt = $env{'form.WGT'.$newflg.'_'.$new_part} eq '' ? 1 : 
                   3069: 		$env{'form.WGT'.$newflg.'_'.$new_part};
1.41      ng       3070: 	    my $partial= $pts/$wgt;
1.259     banghart 3071: 	    if ($partial eq $record{'resource.'.$new_part.'.awarded'}) {
1.153     albertel 3072: 		#do not update score for part if not changed.
1.346     banghart 3073:                 &handback_files($request,$symb,$stuname,$domain,$newflg,$new_part,\%newrecord);
1.153     albertel 3074: 		next;
1.251     banghart 3075: 	    } else {
1.524     raeburn  3076: 	        push(@parts_graded,$new_part);
1.153     albertel 3077: 	    }
1.259     banghart 3078: 	    if ($record{'resource.'.$new_part.'.awarded'} ne $partial) {
                   3079: 		$newrecord{'resource.'.$new_part.'.awarded'}  = $partial;
1.153     albertel 3080: 	    }
1.259     banghart 3081: 	    my $reckey = 'resource.'.$new_part.'.solved';
1.41      ng       3082: 	    if ($partial == 0) {
1.153     albertel 3083: 		if ($record{$reckey} ne 'incorrect_by_override') {
                   3084: 		    $newrecord{$reckey} = 'incorrect_by_override';
                   3085: 		}
1.41      ng       3086: 	    } else {
1.153     albertel 3087: 		if ($record{$reckey} ne 'correct_by_override') {
                   3088: 		    $newrecord{$reckey} = 'correct_by_override';
                   3089: 		}
                   3090: 	    }	    
                   3091: 	    if ($submitter && 
1.259     banghart 3092: 		($record{'resource.'.$new_part.'.submitted_by'} ne $submitter)) {
                   3093: 		$newrecord{'resource.'.$new_part.'.submitted_by'} = $submitter;
1.41      ng       3094: 	    }
1.259     banghart 3095: 	    $newrecord{'resource.'.$new_part.'.regrader'}=
1.257     albertel 3096: 		"$env{'user.name'}:$env{'user.domain'}";
1.41      ng       3097: 	}
1.259     banghart 3098: 	# unless problem has been graded, set flag to version the submitted files
1.305     banghart 3099: 	unless ($record{'resource.'.$new_part.'.solved'} =~ /^correct_/  || 
                   3100: 	        $record{'resource.'.$new_part.'.solved'} eq 'incorrect_by_override' ||
                   3101: 	        $dropMenu eq 'reset status')
                   3102: 	   {
1.524     raeburn  3103: 	    push(@version_parts,$new_part);
1.259     banghart 3104: 	}
1.41      ng       3105:     }
1.301     albertel 3106:     my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   3107:     my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   3108: 
1.344     albertel 3109:     if (%newrecord) {
                   3110:         if (@version_parts) {
1.364     banghart 3111:             my @changed_keys = &version_portfiles(\%record, \@parts_graded, 
                   3112:                                 $env{'request.course.id'}, $symb, $domain, $stuname, \@version_parts);
1.344     albertel 3113: 	    @newrecord{@changed_keys} = @record{@changed_keys};
1.367     albertel 3114: 	    foreach my $new_part (@version_parts) {
                   3115: 		&handback_files($request,$symb,$stuname,$domain,$newflg,
                   3116: 				$new_part,\%newrecord);
                   3117: 	    }
1.259     banghart 3118:         }
1.44      ng       3119: 	&Apache::lonnet::cstore(\%newrecord,$symb,
1.257     albertel 3120: 				$env{'request.course.id'},$domain,$stuname);
1.380     albertel 3121: 	&check_and_remove_from_queue(\@parts,\%record,\%newrecord,$symb,
                   3122: 				     $cdom,$cnum,$domain,$stuname);
1.41      ng       3123:     }
1.269     raeburn  3124:     if ($aggregateflag) {
                   3125:         &Apache::lonnet::cinc('nohist_resourcetracker',\%aggregate,
1.301     albertel 3126: 			      $cdom,$cnum);
1.269     raeburn  3127:     }
1.726     raeburn  3128:     return ('',$pts,$wgt,$totchg);
                   3129: }
                   3130: 
                   3131: sub makehidden {
1.728     raeburn  3132:     my ($version,$parts,$record,$symb,$domain,$stuname,$tolog) = @_;
1.726     raeburn  3133:     return unless (ref($record) eq 'HASH');
                   3134:     my %modified;
                   3135:     my $numchanged = 0;
                   3136:     if (exists($record->{$version.':keys'})) {
                   3137:         my $partsregexp = $parts;
                   3138:         $partsregexp =~ s/,/|/g;
                   3139:         foreach my $key (split(/\:/,$record->{$version.':keys'})) {
                   3140:             if ($key =~ /^resource\.(?:$partsregexp)\.([^\.]+)$/) {
                   3141:                  my $item = $1;
                   3142:                  unless (($item eq 'solved') || ($item =~ /^award(|msg|ed)$/)) {
                   3143:                      $modified{$key} = $record->{$version.':'.$key};
                   3144:                  }
                   3145:             } elsif ($key =~ m{^(resource\.(?:$partsregexp)\.[^\.]+\.)(.+)$}) {
                   3146:                 $modified{$1.'hidden'.$2} = $record->{$version.':'.$key};
                   3147:             } elsif ($key =~ /^(ip|timestamp|host)$/) {
                   3148:                 $modified{$key} = $record->{$version.':'.$key};
                   3149:             }
                   3150:         }
                   3151:         if (keys(%modified)) {
                   3152:             if (&Apache::lonnet::putstore($env{'request.course.id'},$symb,$version,\%modified,
1.728     raeburn  3153:                                           $domain,$stuname,$tolog) eq 'ok') {
1.726     raeburn  3154:                 $numchanged ++;
                   3155:             }
                   3156:         }
                   3157:     }
                   3158:     return $numchanged;
1.36      ng       3159: }
1.322     albertel 3160: 
1.380     albertel 3161: sub check_and_remove_from_queue {
                   3162:     my ($parts,$record,$newrecord,$symb,$cdom,$cnum,$domain,$stuname) = @_;
                   3163:     my @ungraded_parts;
                   3164:     foreach my $part (@{$parts}) {
                   3165: 	if (    $record->{   'resource.'.$part.'.awarded'} eq ''
                   3166: 	     && $record->{   'resource.'.$part.'.solved' } ne 'excused'
                   3167: 	     && $newrecord->{'resource.'.$part.'.awarded'} eq ''
                   3168: 	     && $newrecord->{'resource.'.$part.'.solved' } ne 'excused'
                   3169: 		) {
                   3170: 	    push(@ungraded_parts, $part);
                   3171: 	}
                   3172:     }
                   3173:     if ( !@ungraded_parts ) {
                   3174: 	&Apache::bridgetask::remove_from_queue('gradingqueue',$symb,$cdom,
                   3175: 					       $cnum,$domain,$stuname);
                   3176:     }
                   3177: }
                   3178: 
1.337     banghart 3179: sub handback_files {
                   3180:     my ($request,$symb,$stuname,$domain,$newflg,$new_part,$newrecord) = @_;
1.517     raeburn  3181:     my $portfolio_root = '/userfiles/portfolio';
1.582     raeburn  3182:     my $res_error;
                   3183:     my ($partlist,$handgrade,$responseType) = &response_type($symb,\$res_error);
                   3184:     if ($res_error) {
                   3185:         $request->print('<br />'.&navmap_errormsg().'<br />');
                   3186:         return;
                   3187:     }
1.654     raeburn  3188:     my @handedback;
                   3189:     my $file_msg;
1.375     albertel 3190:     my @part_response_id = &flatten_responseType($responseType);
                   3191:     foreach my $part_response_id (@part_response_id) {
                   3192:     	my ($part_id,$resp_id) = @{ $part_response_id };
                   3193: 	my $part_resp = join('_',@{ $part_response_id });
1.654     raeburn  3194:         if (($env{'form.'.$newflg.'_'.$part_resp.'_countreturndoc'} =~ /^\d+$/) & ($new_part eq $part_id)) {
                   3195:             for (my $counter=1; $counter<=$env{'form.'.$newflg.'_'.$part_resp.'_countreturndoc'}; $counter++) {
                   3196:                 # if multiple files are uploaded names will be 'returndoc2','returndoc3' 
                   3197:                 if ($env{'form.'.$newflg.'_'.$part_resp.'_returndoc'.$counter}) {
                   3198:                     my $fname=$env{'form.'.$newflg.'_'.$part_resp.'_returndoc'.$counter.'.filename'};
1.338     banghart 3199:                     my ($directory,$answer_file) = 
1.654     raeburn  3200:                         ($env{'form.'.$newflg.'_'.$part_resp.'_origdoc'.$counter} =~ /^(.*?)([^\/]*)$/);
1.338     banghart 3201:                     my ($answer_name,$answer_ver,$answer_ext) =
1.729     raeburn  3202: 		        &Apache::lonnet::file_name_version_ext($answer_file);
1.355     banghart 3203: 		    my ($portfolio_path) = ($directory =~ /^.+$stuname\/portfolio(.*)/);
1.517     raeburn  3204:                     my $getpropath = 1;
1.662     raeburn  3205:                     my ($dir_list,$listerror) = 
                   3206:                         &Apache::lonnet::dirlist($portfolio_root.$portfolio_path,
                   3207:                                                  $domain,$stuname,$getpropath);
1.729     raeburn  3208: 		    my $version = &Apache::lonnet::get_next_version($answer_name,$answer_ext,$dir_list);
1.686     bisitz   3209:                     # fix filename
1.355     banghart 3210:                     my ($save_file_name) = (($directory.$answer_name.".$version.".$answer_ext) =~ /^.+\/${stuname}\/(.*)/);
                   3211:                     my $result=&Apache::lonnet::finishuserfileupload($stuname,$domain,
1.654     raeburn  3212:             	                                $newflg.'_'.$part_resp.'_returndoc'.$counter,
1.355     banghart 3213:             	                                $save_file_name);
1.337     banghart 3214:                     if ($result !~ m|^/uploaded/|) {
1.536     raeburn  3215:                         $request->print('<br /><span class="LC_error">'.
                   3216:                             &mt('An error occurred ([_1]) while trying to upload [_2].',
1.654     raeburn  3217:                                 $result,$newflg.'_'.$part_resp.'_returndoc'.$counter).
1.536     raeburn  3218:                                         '</span>');
1.356     banghart 3219:                     } else {
1.360     banghart 3220:                         # mark the file as read only
1.654     raeburn  3221:                         push(@handedback,$save_file_name);
1.367     albertel 3222: 			if (exists($$newrecord{"resource.$new_part.$resp_id.handback"})) {
                   3223: 			    $$newrecord{"resource.$new_part.$resp_id.handback"}.=',';
                   3224: 			}
                   3225:                         $$newrecord{"resource.$new_part.$resp_id.handback"} .= $save_file_name;
1.654     raeburn  3226: 			$file_msg.= '<span class="LC_filename"><a href="/uploaded/'."$domain/$stuname/".$save_file_name.'">'.$save_file_name."</a></span> <br />";
1.337     banghart 3227:                     }
1.686     bisitz   3228:                     $request->print('<br />'.&mt('[_1] will be the uploaded filename [_2]','<span class="LC_info">'.$fname.'</span>','<span class="LC_filename">'.$env{'form.'.$newflg.'_'.$part_resp.'_origdoc'.$counter}.'</span>'));
1.337     banghart 3229:                 }
                   3230:             }
                   3231:         }
1.654     raeburn  3232:     }
                   3233:     if (@handedback > 0) {
                   3234:         $request->print('<br />');
                   3235:         my @what = ($symb,$env{'request.course.id'},'handback');
                   3236:         &Apache::lonnet::mark_as_readonly($domain,$stuname,\@handedback,\@what);
                   3237:         my $user_lh = &Apache::loncommon::user_lang($stuname,$domain,$env{'request.course.id'});    
                   3238:         my ($subject,$message);
                   3239:         if (scalar(@handedback) == 1) {
                   3240:             $subject = &mt_user($user_lh,'File Handed Back by Instructor');
                   3241:             $message = &mt_user($user_lh,'A file has been returned that was originally submitted in response to: ');
                   3242:         } else {
                   3243:             $subject = &mt_user($user_lh,'Files Handed Back by Instructor');
                   3244:             $message = &mt_user($user_lh,'Files have been returned that were originally submitted in response to: ');
                   3245:         }
                   3246:         $message .= "<p><strong>".&Apache::lonnet::gettitle($symb)." </strong></p>";
                   3247:         $message .= &mt_user($user_lh,'The returned file(s) are named: [_1]',"<br />$file_msg <br />").
                   3248:                     &mt_user($user_lh,'The file(s) can be found in your [_1]portfolio[_2].','<a href="/adm/portfolio">','</a>');
                   3249:         my ($feedurl,$showsymb) =
                   3250:             &get_feedurl_and_symb($symb,$domain,$stuname);
                   3251:         my $restitle = &Apache::lonnet::gettitle($symb);
                   3252:         $subject .= ' '.&mt_user($user_lh,'(File Returned)').' ['.$restitle.']';
                   3253:         my $msgstatus =
                   3254:              &Apache::lonmsg::user_normal_msg($stuname,$domain,$subject,
                   3255:                  $message,undef,$feedurl,undef,undef,undef,$showsymb,
                   3256:                  $restitle);
                   3257:         if ($msgstatus) {
                   3258:             $request->print(&mt('Notification message status: [_1]','<span class="LC_info">'.$msgstatus.'</span>').'<br />');
                   3259:         }
                   3260:     }
1.338     banghart 3261:     return;
1.337     banghart 3262: }
                   3263: 
1.418     albertel 3264: sub get_feedurl_and_symb {
                   3265:     my ($symb,$uname,$udom) = @_;
                   3266:     my (undef,undef,$url) = &Apache::lonnet::decode_symb($symb);
                   3267:     $url = &Apache::lonnet::clutter($url);
                   3268:     my $encrypturl=&Apache::lonnet::EXT('resource.0.encrypturl',
                   3269: 					$symb,$udom,$uname);
                   3270:     if ($encrypturl =~ /^yes$/i) {
                   3271: 	&Apache::lonenc::encrypted(\$url,1);
                   3272: 	&Apache::lonenc::encrypted(\$symb,1);
                   3273:     }
                   3274:     return ($url,$symb);
                   3275: }
                   3276: 
1.313     banghart 3277: sub get_submitted_files {
                   3278:     my ($udom,$uname,$partid,$respid,$record) = @_;
                   3279:     my @files;
                   3280:     if ($$record{"resource.$partid.$respid.portfiles"}) {
                   3281:         my $file_url = '/uploaded/'.$udom.'/'.$uname.'/portfolio';
                   3282:         foreach my $file (split(',',$$record{"resource.$partid.$respid.portfiles"})) {
                   3283:     	    push(@files,$file_url.$file);
                   3284:         }
                   3285:     }
                   3286:     if ($$record{"resource.$partid.$respid.uploadedurl"}) {
                   3287:         push(@files,$$record{"resource.$partid.$respid.uploadedurl"});
                   3288:     }
                   3289:     return (\@files);
                   3290: }
1.322     albertel 3291: 
1.269     raeburn  3292: # ----------- Provides number of tries since last reset.
                   3293: sub get_num_tries {
                   3294:     my ($record,$last_reset,$part) = @_;
                   3295:     my $timestamp = '';
                   3296:     my $num_tries = 0;
                   3297:     if ($$record{'version'}) {
                   3298:         for (my $version=$$record{'version'};$version>=1;$version--) {
                   3299:             if (exists($$record{$version.':resource.'.$part.'.solved'})) {
                   3300:                 $timestamp = $$record{$version.':timestamp'};
                   3301:                 if ($timestamp > $last_reset) {
                   3302:                     $num_tries ++;
                   3303:                 } else {
                   3304:                     last;
                   3305:                 }
                   3306:             }
                   3307:         }
                   3308:     }
                   3309:     return $num_tries;
                   3310: }
                   3311: 
                   3312: # ----------- Determine decrements required in aggregate totals 
                   3313: sub decrement_aggs {
                   3314:     my ($symb,$part,$aggregate,$aggtries,$totaltries,$solvedstatus) = @_;
                   3315:     my %decrement = (
                   3316:                         attempts => 0,
                   3317:                         users => 0,
                   3318:                         correct => 0
                   3319:                     );
                   3320:     $decrement{'attempts'} = $aggtries;
                   3321:     if ($solvedstatus =~ /^correct/) {
                   3322:         $decrement{'correct'} = 1;
                   3323:     }
                   3324:     if ($aggtries == $totaltries) {
                   3325:         $decrement{'users'} = 1;
                   3326:     }
1.524     raeburn  3327:     foreach my $type (keys(%decrement)) {
1.269     raeburn  3328:         $$aggregate{$symb."\0".$part."\0".$type} = -$decrement{$type};
                   3329:     }
                   3330:     return;
                   3331: }
                   3332: 
                   3333: # ----------- Determine timestamps for last reset of aggregate totals for parts  
                   3334: sub get_last_resets {
1.270     albertel 3335:     my ($symb,$courseid,$partids) =@_;
                   3336:     my %last_resets;
1.269     raeburn  3337:     my $cdom = $env{'course.'.$courseid.'.domain'};
                   3338:     my $cname = $env{'course.'.$courseid.'.num'};
1.271     albertel 3339:     my @keys;
                   3340:     foreach my $part (@{$partids}) {
                   3341: 	push(@keys,"$symb\0$part\0resettime");
                   3342:     }
                   3343:     my %results=&Apache::lonnet::get('nohist_resourcetracker',\@keys,
                   3344: 				     $cdom,$cname);
                   3345:     foreach my $part (@{$partids}) {
                   3346: 	$last_resets{$part}=$results{"$symb\0$part\0resettime"};
1.269     raeburn  3347:     }
1.270     albertel 3348:     return %last_resets;
1.269     raeburn  3349: }
                   3350: 
1.251     banghart 3351: # ----------- Handles creating versions for portfolio files as answers
                   3352: sub version_portfiles {
1.343     banghart 3353:     my ($record, $parts_graded, $courseid, $symb, $domain, $stu_name, $v_flag) = @_;
1.263     banghart 3354:     my $version_parts = join('|',@$v_flag);
1.343     banghart 3355:     my @returned_keys;
1.255     banghart 3356:     my $parts = join('|', @$parts_graded);
1.277     albertel 3357:     foreach my $key (keys(%$record)) {
1.259     banghart 3358:         my $new_portfiles;
1.263     banghart 3359:         if ($key =~ /^resource\.($version_parts)\./ && $key =~ /\.portfiles$/ ) {
1.342     banghart 3360:             my @versioned_portfiles;
1.367     albertel 3361:             my @portfiles = split(/\s*,\s*/,$$record{$key});
1.729     raeburn  3362:             if (@portfiles) {
                   3363:                 &Apache::lonnet::portfiles_versioning($symb,$domain,$stu_name,\@portfiles,
                   3364:                                                       \@versioned_portfiles);
1.252     banghart 3365:             }
1.343     banghart 3366:             $$record{$key} = join(',',@versioned_portfiles);
                   3367:             push(@returned_keys,$key);
1.251     banghart 3368:         }
                   3369:     } 
1.343     banghart 3370:     return (@returned_keys);   
1.305     banghart 3371: }
                   3372: 
1.44      ng       3373: #--------------------------------------------------------------------------------------
                   3374: #
                   3375: #-------------------------- Next few routines handles grading by section or whole class
                   3376: #
                   3377: #--- Javascript to handle grading by section or whole class
1.42      ng       3378: sub viewgrades_js {
                   3379:     my ($request) = shift;
                   3380: 
1.539     riegler  3381:     my $alertmsg = &mt('A number equal or greater than 0 is expected. Entered value = ');
1.597     wenzelju 3382:     $request->print(&Apache::lonhtmlcommon::scripttag(<<VIEWJAVASCRIPT));
1.45      ng       3383:    function writePoint(partid,weight,point) {
1.125     ng       3384: 	var radioButton = document.classgrade["RADVAL_"+partid];
                   3385: 	var textbox = document.classgrade["TEXTVAL_"+partid];
1.42      ng       3386: 	if (point == "textval") {
1.125     ng       3387: 	    point = document.classgrade["TEXTVAL_"+partid].value;
1.109     matthew  3388: 	    if (isNaN(point) || parseFloat(point) < 0) {
1.539     riegler  3389: 		alert("$alertmsg"+parseFloat(point));
1.42      ng       3390: 		var resetbox = false;
                   3391: 		for (var i=0; i<radioButton.length; i++) {
                   3392: 		    if (radioButton[i].checked) {
                   3393: 			textbox.value = i;
                   3394: 			resetbox = true;
                   3395: 		    }
                   3396: 		}
                   3397: 		if (!resetbox) {
                   3398: 		    textbox.value = "";
                   3399: 		}
                   3400: 		return;
                   3401: 	    }
1.109     matthew  3402: 	    if (parseFloat(point) > parseFloat(weight)) {
                   3403: 		var resp = confirm("You entered a value ("+parseFloat(point)+
1.44      ng       3404: 				   ") greater than the weight for the part. Accept?");
                   3405: 		if (resp == false) {
                   3406: 		    textbox.value = "";
                   3407: 		    return;
                   3408: 		}
                   3409: 	    }
1.42      ng       3410: 	    for (var i=0; i<radioButton.length; i++) {
                   3411: 		radioButton[i].checked=false;
1.109     matthew  3412: 		if (parseFloat(point) == i) {
1.42      ng       3413: 		    radioButton[i].checked=true;
                   3414: 		}
                   3415: 	    }
1.41      ng       3416: 
1.42      ng       3417: 	} else {
1.125     ng       3418: 	    textbox.value = parseFloat(point);
1.42      ng       3419: 	}
1.41      ng       3420: 	for (i=0;i<document.classgrade.total.value;i++) {
1.125     ng       3421: 	    var user = document.classgrade["ctr"+i].value;
1.289     albertel 3422: 	    user = user.replace(new RegExp(':', 'g'),"_");
1.125     ng       3423: 	    var scorename = document.classgrade["GD_"+user+"_"+partid+"_awarded"];
                   3424: 	    var saveval   = document.classgrade["GD_"+user+"_"+partid+"_solved_s"].value;
                   3425: 	    var selname   = document.classgrade["GD_"+user+"_"+partid+"_solved"];
1.42      ng       3426: 	    if (saveval != "correct") {
                   3427: 		scorename.value = point;
1.43      ng       3428: 		if (selname[0].selected != true) {
                   3429: 		    selname[0].selected = true;
                   3430: 		}
1.42      ng       3431: 	    }
                   3432: 	}
1.125     ng       3433: 	document.classgrade["SELVAL_"+partid][0].selected = true;
1.42      ng       3434:     }
                   3435: 
                   3436:     function writeRadText(partid,weight) {
1.125     ng       3437: 	var selval   = document.classgrade["SELVAL_"+partid];
                   3438: 	var radioButton = document.classgrade["RADVAL_"+partid];
1.265     www      3439:         var override = document.classgrade["FORCE_"+partid].checked;
1.125     ng       3440: 	var textbox = document.classgrade["TEXTVAL_"+partid];
                   3441: 	if (selval[1].selected || selval[2].selected) {
1.42      ng       3442: 	    for (var i=0; i<radioButton.length; i++) {
                   3443: 		radioButton[i].checked=false;
                   3444: 
                   3445: 	    }
                   3446: 	    textbox.value = "";
                   3447: 
                   3448: 	    for (i=0;i<document.classgrade.total.value;i++) {
1.125     ng       3449: 		var user = document.classgrade["ctr"+i].value;
1.289     albertel 3450: 		user = user.replace(new RegExp(':', 'g'),"_");
1.125     ng       3451: 		var scorename = document.classgrade["GD_"+user+"_"+partid+"_awarded"];
                   3452: 		var saveval   = document.classgrade["GD_"+user+"_"+partid+"_solved_s"].value;
                   3453: 		var selname   = document.classgrade["GD_"+user+"_"+partid+"_solved"];
1.265     www      3454: 		if ((saveval != "correct") || override) {
1.42      ng       3455: 		    scorename.value = "";
1.125     ng       3456: 		    if (selval[1].selected) {
                   3457: 			selname[1].selected = true;
                   3458: 		    } else {
                   3459: 			selname[2].selected = true;
                   3460: 			if (Number(document.classgrade["GD_"+user+"_"+partid+"_tries"].value)) 
                   3461: 			{document.classgrade["GD_"+user+"_"+partid+"_tries"].value = '0';}
                   3462: 		    }
1.42      ng       3463: 		}
                   3464: 	    }
1.43      ng       3465: 	} else {
                   3466: 	    for (i=0;i<document.classgrade.total.value;i++) {
1.125     ng       3467: 		var user = document.classgrade["ctr"+i].value;
1.289     albertel 3468: 		user = user.replace(new RegExp(':', 'g'),"_");
1.125     ng       3469: 		var scorename = document.classgrade["GD_"+user+"_"+partid+"_awarded"];
                   3470: 		var saveval   = document.classgrade["GD_"+user+"_"+partid+"_solved_s"].value;
                   3471: 		var selname   = document.classgrade["GD_"+user+"_"+partid+"_solved"];
1.265     www      3472: 		if ((saveval != "correct") || override) {
1.125     ng       3473: 		    scorename.value = document.classgrade["GD_"+user+"_"+partid+"_awarded_s"].value;
1.43      ng       3474: 		    selname[0].selected = true;
                   3475: 		}
                   3476: 	    }
                   3477: 	}	    
1.42      ng       3478:     }
                   3479: 
                   3480:     function changeSelect(partid,user) {
1.125     ng       3481: 	var selval = document.classgrade["GD_"+user+'_'+partid+"_solved"];
                   3482: 	var textbox = document.classgrade["GD_"+user+'_'+partid+"_awarded"];
1.44      ng       3483: 	var point  = textbox.value;
1.125     ng       3484: 	var weight = document.classgrade["weight_"+partid].value;
1.44      ng       3485: 
1.109     matthew  3486: 	if (isNaN(point) || parseFloat(point) < 0) {
1.539     riegler  3487: 	    alert("$alertmsg"+parseFloat(point));
1.44      ng       3488: 	    textbox.value = "";
                   3489: 	    return;
                   3490: 	}
1.109     matthew  3491: 	if (parseFloat(point) > parseFloat(weight)) {
                   3492: 	    var resp = confirm("You entered a value ("+parseFloat(point)+
1.44      ng       3493: 			       ") greater than the weight of the part. Accept?");
                   3494: 	    if (resp == false) {
                   3495: 		textbox.value = "";
                   3496: 		return;
                   3497: 	    }
                   3498: 	}
1.42      ng       3499: 	selval[0].selected = true;
                   3500:     }
                   3501: 
                   3502:     function changeOneScore(partid,user) {
1.125     ng       3503: 	var selval = document.classgrade["GD_"+user+'_'+partid+"_solved"];
                   3504: 	if (selval[1].selected || selval[2].selected) {
                   3505: 	    document.classgrade["GD_"+user+'_'+partid+"_awarded"].value = "";
                   3506: 	    if (selval[2].selected) {
                   3507: 		document.classgrade["GD_"+user+'_'+partid+"_tries"].value = "0";
                   3508: 	    }
1.269     raeburn  3509:         }
1.42      ng       3510:     }
                   3511: 
                   3512:     function resetEntry(numpart) {
                   3513: 	for (ctpart=0;ctpart<numpart;ctpart++) {
1.125     ng       3514: 	    var partid = document.classgrade["partid_"+ctpart].value;
                   3515: 	    var radioButton = document.classgrade["RADVAL_"+partid];
                   3516: 	    var textbox = document.classgrade["TEXTVAL_"+partid];
                   3517: 	    var selval  = document.classgrade["SELVAL_"+partid];
1.42      ng       3518: 	    for (var i=0; i<radioButton.length; i++) {
                   3519: 		radioButton[i].checked=false;
                   3520: 
                   3521: 	    }
                   3522: 	    textbox.value = "";
                   3523: 	    selval[0].selected = true;
                   3524: 
                   3525: 	    for (i=0;i<document.classgrade.total.value;i++) {
1.125     ng       3526: 		var user = document.classgrade["ctr"+i].value;
1.289     albertel 3527: 		user = user.replace(new RegExp(':', 'g'),"_");
1.125     ng       3528: 		var resetscore = document.classgrade["GD_"+user+"_"+partid+"_awarded"];
                   3529: 		resetscore.value = document.classgrade["GD_"+user+"_"+partid+"_awarded_s"].value;
                   3530: 		var resettries = document.classgrade["GD_"+user+"_"+partid+"_tries"];
                   3531: 		resettries.value = document.classgrade["GD_"+user+"_"+partid+"_tries_s"].value;
                   3532: 		var saveselval   = document.classgrade["GD_"+user+"_"+partid+"_solved_s"].value;
                   3533: 		var selname   = document.classgrade["GD_"+user+"_"+partid+"_solved"];
1.42      ng       3534: 		if (saveselval == "excused") {
1.43      ng       3535: 		    if (selname[1].selected == false) { selname[1].selected = true;}
1.42      ng       3536: 		} else {
1.43      ng       3537: 		    if (selname[0].selected == false) {selname[0].selected = true};
1.42      ng       3538: 		}
                   3539: 	    }
1.41      ng       3540: 	}
1.42      ng       3541:     }
                   3542: 
1.41      ng       3543: VIEWJAVASCRIPT
1.42      ng       3544: }
                   3545: 
1.44      ng       3546: #--- show scores for a section or whole class w/ option to change/update a score
1.42      ng       3547: sub viewgrades {
1.608     www      3548:     my ($request,$symb) = @_;
1.42      ng       3549:     &viewgrades_js($request);
1.41      ng       3550: 
1.168     albertel 3551:     #need to make sure we have the correct data for later EXT calls, 
                   3552:     #thus invalidate the cache
                   3553:     &Apache::lonnet::devalidatecourseresdata(
1.257     albertel 3554:                  $env{'course.'.$env{'request.course.id'}.'.num'},
                   3555:                  $env{'course.'.$env{'request.course.id'}.'.domain'});
1.168     albertel 3556:     &Apache::lonnet::clear_EXT_cache_status();
                   3557: 
1.398     albertel 3558:     my $result='<h3><span class="LC_info">'.&mt('Manual Grading').'</span></h3>';
1.41      ng       3559: 
                   3560:     #view individual student submission form - called using Javascript viewOneStudent
1.324     albertel 3561:     $result.=&jscriptNform($symb);
1.41      ng       3562: 
1.44      ng       3563:     #beginning of class grading form
1.442     banghart 3564:     my $stu_status = join(':',&Apache::loncommon::get_env_multiple('form.Status'));
1.41      ng       3565:     $result.= '<form action="/adm/grades" method="post" name="classgrade">'."\n".
1.418     albertel 3566: 	'<input type="hidden" name="symb"    value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
1.38      ng       3567: 	'<input type="hidden" name="command" value="editgrades" />'."\n".
1.432     banghart 3568: 	&build_section_inputs().
1.442     banghart 3569: 	'<input type="hidden" name="Status" value="'.$env{'stu_status'}.'" />'."\n".
1.72      ng       3570: 
1.560     raeburn  3571:     my ($common_header,$specific_header);
1.257     albertel 3572:     if ($env{'form.section'} eq 'all') {
1.560     raeburn  3573: 	$common_header = &mt('Assign Common Grade to Class');
                   3574:         $specific_header = &mt('Assign Grade to Specific Students in Class');
1.257     albertel 3575:     } elsif ($env{'form.section'} eq 'none') {
1.560     raeburn  3576:         $common_header = &mt('Assign Common Grade to Students in no Section');
                   3577: 	$specific_header = &mt('Assign Grade to Specific Students in no Section');
1.52      albertel 3578:     } else {
1.560     raeburn  3579:         my $section_display = join (", ",&Apache::loncommon::get_env_multiple('form.section'));
                   3580:         $common_header = &mt('Assign Common Grade to Students in Section(s) [_1]',$section_display);
                   3581: 	$specific_header = &mt('Assign Grade to Specific Students in Section(s) [_1]',$section_display);
1.52      albertel 3582:     }
1.560     raeburn  3583:     $result.= '<h3>'.$common_header.'</h3>'.&Apache::loncommon::start_data_table();
1.44      ng       3584:     #radio buttons/text box for assigning points for a section or class.
                   3585:     #handles different parts of a problem
1.582     raeburn  3586:     my $res_error;
                   3587:     my ($partlist,$handgrade,$responseType) = &response_type($symb,\$res_error);
                   3588:     if ($res_error) {
                   3589:         return &navmap_errormsg();
                   3590:     }
1.42      ng       3591:     my %weight = ();
                   3592:     my $ctsparts = 0;
1.45      ng       3593:     my %seen = ();
1.375     albertel 3594:     my @part_response_id = &flatten_responseType($responseType);
                   3595:     foreach my $part_response_id (@part_response_id) {
                   3596:     	my ($partid,$respid) = @{ $part_response_id };
                   3597: 	my $part_resp = join('_',@{ $part_response_id });
1.45      ng       3598: 	next if $seen{$partid};
                   3599: 	$seen{$partid}++;
1.375     albertel 3600: 	my $handgrade=$$handgrade{$part_resp};
1.42      ng       3601: 	my $wgt = &Apache::lonnet::EXT('resource.'.$partid.'.weight',$symb);
                   3602: 	$weight{$partid} = $wgt eq '' ? '1' : $wgt;
                   3603: 
1.324     albertel 3604: 	my $display_part=&get_display_part($partid,$symb);
1.485     albertel 3605: 	my $radio.='<table border="0"><tr>';  
1.41      ng       3606: 	my $ctr = 0;
1.42      ng       3607: 	while ($ctr<=$weight{$partid}) { # display radio buttons in a nice table 10 across
1.485     albertel 3608: 	    $radio.= '<td><label><input type="radio" name="RADVAL_'.$partid.'" '.
1.54      albertel 3609: 		'onclick="javascript:writePoint(\''.$partid.'\','.$weight{$partid}.
1.288     albertel 3610: 		','.$ctr.')" />'.$ctr."</label></td>\n";
1.41      ng       3611: 	    $result.=(($ctr+1)%10 == 0 ? '</tr><tr>' : '');
                   3612: 	    $ctr++;
                   3613: 	}
1.485     albertel 3614: 	$radio.='</tr></table>';
                   3615: 	my $line = '<input type="text" name="TEXTVAL_'.
1.589     bisitz   3616: 	    $partid.'" size="4" '.'onchange="javascript:writePoint(\''.
1.54      albertel 3617: 		$partid.'\','.$weight{$partid}.',\'textval\')" /> /'.
1.539     riegler  3618: 	    $weight{$partid}.' '.&mt('(problem weight)').'</td>'."\n";
1.701     bisitz   3619:         $line.= '<td><b>'.&mt('Grade Status').':</b>'.
                   3620:             '<select name="SELVAL_'.$partid.'" '.
                   3621:             'onchange="javascript:writeRadText(\''.$partid.'\','.
                   3622:                 $weight{$partid}.')"> '.
1.401     albertel 3623: 	    '<option selected="selected"> </option>'.
1.485     albertel 3624: 	    '<option value="excused">'.&mt('excused').'</option>'.
                   3625: 	    '<option value="reset status">'.&mt('reset status').'</option>'.
                   3626: 	    '</select></td>'.
                   3627:             '<td><label><input type="checkbox" name="FORCE_'.$partid.'" />'.&mt('Override "Correct"').'</label>';
                   3628: 	$line.='<input type="hidden" name="partid_'.
                   3629: 	    $ctsparts.'" value="'.$partid.'" />'."\n";
                   3630: 	$line.='<input type="hidden" name="weight_'.
                   3631: 	    $partid.'" value="'.$weight{$partid}.'" />'."\n";
                   3632: 
                   3633: 	$result.=
                   3634: 	    &Apache::loncommon::start_data_table_row()."\n".
1.577     bisitz   3635: 	    '<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 3636: 	    &Apache::loncommon::end_data_table_row()."\n";
1.42      ng       3637: 	$ctsparts++;
1.41      ng       3638:     }
1.474     albertel 3639:     $result.=&Apache::loncommon::end_data_table()."\n".
1.52      albertel 3640: 	'<input type="hidden" name="totalparts" value="'.$ctsparts.'" />';
1.485     albertel 3641:     $result.='<input type="button" value="'.&mt('Revert to Default').'" '.
1.589     bisitz   3642: 	'onclick="javascript:resetEntry('.$ctsparts.');" />';
1.41      ng       3643: 
1.44      ng       3644:     #table listing all the students in a section/class
                   3645:     #header of table
1.560     raeburn  3646:     $result.= '<h3>'.$specific_header.'</h3>'.
                   3647:               &Apache::loncommon::start_data_table().
                   3648: 	      &Apache::loncommon::start_data_table_header_row().
                   3649: 	      '<th>'.&mt('No.').'</th>'.
                   3650: 	      '<th>'.&nameUserString('header')."</th>\n";
1.582     raeburn  3651:     my $partserror;
                   3652:     my (@parts) = sort(&getpartlist($symb,\$partserror));
                   3653:     if ($partserror) {
                   3654:         return &navmap_errormsg();
                   3655:     }
1.324     albertel 3656:     my (undef,undef,$url)=&Apache::lonnet::decode_symb($symb);
1.269     raeburn  3657:     my @partids = ();
1.41      ng       3658:     foreach my $part (@parts) {
                   3659: 	my $display=&Apache::lonnet::metadata($url,$part.'.display');
1.539     riegler  3660:         my $narrowtext = &mt('Tries');
                   3661: 	$display =~ s|^Number of Attempts|$narrowtext <br />|; # makes the column narrower
1.41      ng       3662: 	if  (!$display) { $display = &Apache::lonnet::metadata($url,$part.'.name'); }
1.207     albertel 3663: 	my ($partid) = &split_part_type($part);
1.524     raeburn  3664:         push(@partids,$partid);
1.628     www      3665: #
                   3666: # FIXME: Looks like $display looks at English text
                   3667: #
1.324     albertel 3668: 	my $display_part=&get_display_part($partid,$symb);
1.41      ng       3669: 	if ($display =~ /^Partial Credit Factor/) {
1.485     albertel 3670: 	    $result.='<th>'.
1.697     bisitz   3671: 		&mt('Score Part: [_1][_2](weight = [_3])',
                   3672: 		    $display_part,'<br />',$weight{$partid}).'</th>'."\n";
1.41      ng       3673: 	    next;
1.485     albertel 3674: 	    
1.207     albertel 3675: 	} else {
1.485     albertel 3676: 	    if ($display =~ /Problem Status/) {
                   3677: 		my $grade_status_mt = &mt('Grade Status');
                   3678: 		$display =~ s{Problem Status}{$grade_status_mt<br />};
                   3679: 	    }
                   3680: 	    my $part_mt = &mt('Part:');
                   3681: 	    $display =~s{\[Part: \Q$partid\E\]}{$part_mt $display_part};
1.41      ng       3682: 	}
1.485     albertel 3683: 
1.474     albertel 3684: 	$result.='<th>'.$display.'</th>'."\n";
1.41      ng       3685:     }
1.474     albertel 3686:     $result.=&Apache::loncommon::end_data_table_header_row();
1.44      ng       3687: 
1.270     albertel 3688:     my %last_resets = 
                   3689: 	&get_last_resets($symb,$env{'request.course.id'},\@partids);
1.269     raeburn  3690: 
1.41      ng       3691:     #get info for each student
1.44      ng       3692:     #list all the students - with points and grade status
1.257     albertel 3693:     my (undef,undef,$fullname) = &getclasslist($env{'form.section'},'1');
1.41      ng       3694:     my $ctr = 0;
1.294     albertel 3695:     foreach (sort 
                   3696: 	     {
                   3697: 		 if (lc($$fullname{$a}) ne lc($$fullname{$b})) {
                   3698: 		     return (lc($$fullname{$a}) cmp lc($$fullname{$b}));
                   3699: 		 }
                   3700: 		 return $a cmp $b;
                   3701: 	     } (keys(%$fullname))) {
1.126     ng       3702: 	$ctr++;
1.324     albertel 3703: 	$result.=&viewstudentgrade($symb,$env{'request.course.id'},
1.269     raeburn  3704: 				   $_,$$fullname{$_},\@parts,\%weight,$ctr,\%last_resets);
1.41      ng       3705:     }
1.474     albertel 3706:     $result.=&Apache::loncommon::end_data_table();
1.41      ng       3707:     $result.='<input type="hidden" name="total" value="'.$ctr.'" />'."\n";
1.485     albertel 3708:     $result.='<input type="button" value="'.&mt('Save').'" '.
1.589     bisitz   3709: 	'onclick="javascript:submit();" target="_self" /></form>'."\n";
1.96      albertel 3710:     if (scalar(%$fullname) eq 0) {
                   3711: 	my $colspan=3+scalar(@parts);
1.433     banghart 3712: 	my $section_display = join (", ",&Apache::loncommon::get_env_multiple('form.section'));
1.442     banghart 3713:         my $stu_status = join(' or ',&Apache::loncommon::get_env_multiple('form.Status'));
1.433     banghart 3714: 	$result='<span class="LC_warning">'.
1.485     albertel 3715: 	    &mt('There are no students in section(s) [_1] with enrollment status [_2] to modify or grade.',
1.442     banghart 3716: 	        $section_display, $stu_status).
1.433     banghart 3717: 	    '</span>';
1.96      albertel 3718:     }
1.41      ng       3719:     return $result;
                   3720: }
                   3721: 
1.44      ng       3722: #--- call by previous routine to display each student
1.41      ng       3723: sub viewstudentgrade {
1.324     albertel 3724:     my ($symb,$courseid,$student,$fullname,$parts,$weight,$ctr,$last_resets) = @_;
1.44      ng       3725:     my ($uname,$udom) = split(/:/,$student);
                   3726:     my %record=&Apache::lonnet::restore($symb,$courseid,$udom,$uname);
1.269     raeburn  3727:     my %aggregates = (); 
1.474     albertel 3728:     my $result=&Apache::loncommon::start_data_table_row().'<td align="right">'.
1.233     albertel 3729: 	'<input type="hidden" name="ctr'.($ctr-1).'" value="'.$student.'" />'.
                   3730: 	"\n".$ctr.'&nbsp;</td><td>&nbsp;'.
1.44      ng       3731: 	'<a href="javascript:viewOneStudent(\''.$uname.'\',\''.$udom.
1.417     albertel 3732: 	'\');" target="_self">'.$fullname.'</a> '.
1.398     albertel 3733: 	'<span class="LC_internal_info">('.$uname.($env{'user.domain'} eq $udom ? '' : ':'.$udom).')</span></td>'."\n";
1.281     albertel 3734:     $student=~s/:/_/; # colon doen't work in javascript for names
1.63      albertel 3735:     foreach my $apart (@$parts) {
                   3736: 	my ($part,$type) = &split_part_type($apart);
1.41      ng       3737: 	my $score=$record{"resource.$part.$type"};
1.276     albertel 3738:         $result.='<td align="center">';
1.269     raeburn  3739:         my ($aggtries,$totaltries);
                   3740:         unless (exists($aggregates{$part})) {
1.270     albertel 3741: 	    $totaltries = $record{'resource.'.$part.'.tries'};
                   3742: 
                   3743: 	    $aggtries = $totaltries;
1.269     raeburn  3744:             if ($$last_resets{$part}) {  
1.270     albertel 3745:                 $aggtries = &get_num_tries(\%record,$$last_resets{$part},
                   3746: 					   $part);
                   3747:             }
1.269     raeburn  3748:             $result.='<input type="hidden" name="'.
                   3749:                 'GD_'.$student.'_'.$part.'_aggtries" value="'.$aggtries.'" />'."\n";
                   3750:             $result.='<input type="hidden" name="'.
                   3751:                 'GD_'.$student.'_'.$part.'_totaltries" value="'.$totaltries.'" />'."\n";
                   3752:             $aggregates{$part} = 1;
                   3753:         }
1.41      ng       3754: 	if ($type eq 'awarded') {
1.320     albertel 3755: 	    my $pts = $score eq '' ? '' : &compute_points($score,$$weight{$part});
1.42      ng       3756: 	    $result.='<input type="hidden" name="'.
1.89      albertel 3757: 		'GD_'.$student.'_'.$part.'_awarded_s" value="'.$pts.'" />'."\n";
1.233     albertel 3758: 	    $result.='<input type="text" name="'.
1.89      albertel 3759: 		'GD_'.$student.'_'.$part.'_awarded" '.
1.589     bisitz   3760:                 'onchange="javascript:changeSelect(\''.$part.'\',\''.$student.
1.44      ng       3761: 		'\')" value="'.$pts.'" size="4" /></td>'."\n";
1.41      ng       3762: 	} elsif ($type eq 'solved') {
                   3763: 	    my ($status,$foo)=split(/_/,$score,2);
                   3764: 	    $status = 'nothing' if ($status eq '');
1.89      albertel 3765: 	    $result.='<input type="hidden" name="'.'GD_'.$student.'_'.
1.54      albertel 3766: 		$part.'_solved_s" value="'.$status.'" />'."\n";
1.233     albertel 3767: 	    $result.='&nbsp;<select name="'.
1.89      albertel 3768: 		'GD_'.$student.'_'.$part.'_solved" '.
1.589     bisitz   3769:                 'onchange="javascript:changeOneScore(\''.$part.'\',\''.$student.'\')" >'."\n";
1.485     albertel 3770: 	    $result.= (($status eq 'excused') ? '<option> </option><option selected="selected" value="excused">'.&mt('excused').'</option>' 
                   3771: 		: '<option selected="selected"> </option><option value="excused">'.&mt('excused').'</option>')."\n";
                   3772: 	    $result.='<option value="reset status">'.&mt('reset status').'</option>';
1.126     ng       3773: 	    $result.="</select>&nbsp;</td>\n";
1.122     ng       3774: 	} else {
                   3775: 	    $result.='<input type="hidden" name="'.
                   3776: 		'GD_'.$student.'_'.$part.'_'.$type.'_s" value="'.$score.'" />'.
                   3777: 		    "\n";
1.233     albertel 3778: 	    $result.='<input type="text" name="'.
1.122     ng       3779: 		'GD_'.$student.'_'.$part.'_'.$type.'" '.
                   3780: 		'value="'.$score.'" size="4" /></td>'."\n";
1.41      ng       3781: 	}
                   3782:     }
1.474     albertel 3783:     $result.=&Apache::loncommon::end_data_table_row();
1.41      ng       3784:     return $result;
1.38      ng       3785: }
                   3786: 
1.44      ng       3787: #--- change scores for all the students in a section/class
                   3788: #    record does not get update if unchanged
1.38      ng       3789: sub editgrades {
1.608     www      3790:     my ($request,$symb) = @_;
1.41      ng       3791: 
1.433     banghart 3792:     my $section_display = join (", ",&Apache::loncommon::get_env_multiple('form.section'));
1.477     albertel 3793:     my $title='<h2>'.&mt('Current Grade Status').'</h2>';
1.433     banghart 3794:     $title.='<h4>'.&mt('<b>Section: </b>[_1]',$section_display).'</h4>'."\n";
1.126     ng       3795: 
1.477     albertel 3796:     my $result= &Apache::loncommon::start_data_table().
                   3797: 	&Apache::loncommon::start_data_table_header_row().
                   3798: 	'<th rowspan="2" valign="middle">'.&mt('No.').'</th>'.
                   3799: 	'<th rowspan="2" valign="middle">'.&nameUserString('header')."</th>\n";
1.43      ng       3800:     my %scoreptr = (
                   3801: 		    'correct'  =>'correct_by_override',
                   3802: 		    'incorrect'=>'incorrect_by_override',
                   3803: 		    'excused'  =>'excused',
                   3804: 		    'ungraded' =>'ungraded_attempted',
1.596     raeburn  3805:                     'credited' =>'credit_attempted',
1.43      ng       3806: 		    'nothing'  => '',
                   3807: 		    );
1.257     albertel 3808:     my ($classlist,undef,$fullname) = &getclasslist($env{'form.section'},'0');
1.34      ng       3809: 
1.44      ng       3810:     my (@partid);
                   3811:     my %weight = ();
1.54      albertel 3812:     my %columns = ();
1.44      ng       3813:     my ($i,$ctr,$count,$rec_update) = (0,0,0,0);
1.54      albertel 3814: 
1.582     raeburn  3815:     my $partserror;
                   3816:     my (@parts) = sort(&getpartlist($symb,\$partserror));
                   3817:     if ($partserror) {
                   3818:         return &navmap_errormsg();
                   3819:     }
1.54      albertel 3820:     my $header;
1.257     albertel 3821:     while ($ctr < $env{'form.totalparts'}) {
                   3822: 	my $partid = $env{'form.partid_'.$ctr};
1.524     raeburn  3823: 	push(@partid,$partid);
1.257     albertel 3824: 	$weight{$partid} = $env{'form.weight_'.$partid};
1.44      ng       3825: 	$ctr++;
1.54      albertel 3826:     }
1.324     albertel 3827:     my (undef,undef,$url) = &Apache::lonnet::decode_symb($symb);
1.54      albertel 3828:     foreach my $partid (@partid) {
1.478     albertel 3829: 	$header .= '<th align="center">'.&mt('Old Score').'</th>'.
                   3830: 	    '<th align="center">'.&mt('New Score').'</th>';
1.54      albertel 3831: 	$columns{$partid}=2;
                   3832: 	foreach my $stores (@parts) {
                   3833: 	    my ($part,$type) = &split_part_type($stores);
                   3834: 	    if ($part !~ m/^\Q$partid\E/) { next;}
                   3835: 	    if ($type eq 'awarded' || $type eq 'solved') { next; }
                   3836: 	    my $display=&Apache::lonnet::metadata($url,$stores.'.display');
1.551     raeburn  3837: 	    $display =~ s/\[Part: \Q$part\E\]//;
1.539     riegler  3838:             my $narrowtext = &mt('Tries');
                   3839: 	    $display =~ s/Number of Attempts/$narrowtext/;
                   3840: 	    $header .= '<th align="center">'.&mt('Old').' '.$display.'</th>'.
                   3841: 		'<th align="center">'.&mt('New').' '.$display.'</th>';
1.54      albertel 3842: 	    $columns{$partid}+=2;
                   3843: 	}
                   3844:     }
                   3845:     foreach my $partid (@partid) {
1.324     albertel 3846: 	my $display_part=&get_display_part($partid,$symb);
1.478     albertel 3847: 	$result .= '<th colspan="'.$columns{$partid}.'" align="center">'.
                   3848: 	    &mt('Part: [_1] (Weight = [_2])',$display_part,$weight{$partid}).
                   3849: 	    '</th>';
1.54      albertel 3850: 
1.44      ng       3851:     }
1.477     albertel 3852:     $result .= &Apache::loncommon::end_data_table_header_row().
                   3853: 	&Apache::loncommon::start_data_table_header_row().
                   3854: 	$header.
                   3855: 	&Apache::loncommon::end_data_table_header_row();
                   3856:     my @noupdate;
1.126     ng       3857:     my ($updateCtr,$noupdateCtr) = (1,1);
1.257     albertel 3858:     for ($i=0; $i<$env{'form.total'}; $i++) {
1.93      albertel 3859: 	my $line;
1.257     albertel 3860: 	my $user = $env{'form.ctr'.$i};
1.281     albertel 3861: 	my ($uname,$udom)=split(/:/,$user);
1.44      ng       3862: 	my %newrecord;
                   3863: 	my $updateflag = 0;
1.281     albertel 3864: 	$line .= '<td>'.&nameUserString(undef,$$fullname{$user},$uname,$udom).'</td>';
1.108     albertel 3865: 	my $usec=$classlist->{"$uname:$udom"}[5];
1.105     albertel 3866: 	if (!&canmodify($usec)) {
1.126     ng       3867: 	    my $numcols=scalar(@partid)*4+2;
1.477     albertel 3868: 	    push(@noupdate,
1.478     albertel 3869: 		 $line."<td colspan=\"$numcols\"><span class=\"LC_warning\">".
                   3870: 		 &mt('Not allowed to modify student')."</span></td></tr>");
1.105     albertel 3871: 	    next;
                   3872: 	}
1.269     raeburn  3873:         my %aggregate = ();
                   3874:         my $aggregateflag = 0;
1.281     albertel 3875: 	$user=~s/:/_/; # colon doen't work in javascript for names
1.44      ng       3876: 	foreach (@partid) {
1.257     albertel 3877: 	    my $old_aw    = $env{'form.GD_'.$user.'_'.$_.'_awarded_s'};
1.54      albertel 3878: 	    my $old_part_pcr = $old_aw/($weight{$_} ne '0' ? $weight{$_}:1);
                   3879: 	    my $old_part  = $old_aw eq '' ? '' : $old_part_pcr;
1.257     albertel 3880: 	    my $old_score = $scoreptr{$env{'form.GD_'.$user.'_'.$_.'_solved_s'}};
                   3881: 	    my $awarded   = $env{'form.GD_'.$user.'_'.$_.'_awarded'};
1.54      albertel 3882: 	    my $pcr       = $awarded/($weight{$_} ne '0' ? $weight{$_} : 1);
                   3883: 	    my $partial   = $awarded eq '' ? '' : $pcr;
1.44      ng       3884: 	    my $score;
                   3885: 	    if ($partial eq '') {
1.257     albertel 3886: 		$score = $scoreptr{$env{'form.GD_'.$user.'_'.$_.'_solved_s'}};
1.44      ng       3887: 	    } elsif ($partial > 0) {
                   3888: 		$score = 'correct_by_override';
                   3889: 	    } elsif ($partial == 0) {
                   3890: 		$score = 'incorrect_by_override';
                   3891: 	    }
1.257     albertel 3892: 	    my $dropMenu = $env{'form.GD_'.$user.'_'.$_.'_solved'};
1.125     ng       3893: 	    $score = 'excused' if (($dropMenu eq 'excused') && ($score ne 'excused'));
                   3894: 
1.292     albertel 3895: 	    $newrecord{'resource.'.$_.'.regrader'}=
                   3896: 		"$env{'user.name'}:$env{'user.domain'}";
1.125     ng       3897: 	    if ($dropMenu eq 'reset status' &&
                   3898: 		$old_score ne '') { # ignore if no previous attempts => nothing to reset
1.299     albertel 3899: 		$newrecord{'resource.'.$_.'.tries'} = '';
1.125     ng       3900: 		$newrecord{'resource.'.$_.'.solved'} = '';
                   3901: 		$newrecord{'resource.'.$_.'.award'} = '';
1.299     albertel 3902: 		$newrecord{'resource.'.$_.'.awarded'} = '';
1.125     ng       3903: 		$updateflag = 1;
1.269     raeburn  3904:                 if ($env{'form.GD_'.$user.'_'.$_.'_aggtries'} > 0) {
                   3905:                     my $aggtries = $env{'form.GD_'.$user.'_'.$_.'_aggtries'};
                   3906:                     my $totaltries = $env{'form.GD_'.$user.'_'.$_.'_totaltries'};
                   3907:                     my $solvedstatus = $env{'form.GD_'.$user.'_'.$_.'_solved_s'};
                   3908:                     &decrement_aggs($symb,$_,\%aggregate,$aggtries,$totaltries,$solvedstatus);
                   3909:                     $aggregateflag = 1;
                   3910:                 }
1.139     albertel 3911: 	    } elsif (!($old_part eq $partial && $old_score eq $score)) {
                   3912: 		$updateflag = 1;
                   3913: 		$newrecord{'resource.'.$_.'.awarded'}  = $partial if $partial ne '';
                   3914: 		$newrecord{'resource.'.$_.'.solved'}   = $score;
                   3915: 		$rec_update++;
1.125     ng       3916: 	    }
                   3917: 
1.93      albertel 3918: 	    $line .= '<td align="center">'.$old_aw.'&nbsp;</td>'.
1.44      ng       3919: 		'<td align="center">'.$awarded.
                   3920: 		($score eq 'excused' ? $score : '').'&nbsp;</td>';
1.5       albertel 3921: 
1.54      albertel 3922: 
                   3923: 	    my $partid=$_;
                   3924: 	    foreach my $stores (@parts) {
                   3925: 		my ($part,$type) = &split_part_type($stores);
                   3926: 		if ($part !~ m/^\Q$partid\E/) { next;}
                   3927: 		if ($type eq 'awarded' || $type eq 'solved') { next; }
1.257     albertel 3928: 		my $old_aw    = $env{'form.GD_'.$user.'_'.$part.'_'.$type.'_s'};
                   3929: 		my $awarded   = $env{'form.GD_'.$user.'_'.$part.'_'.$type};
1.54      albertel 3930: 		if ($awarded ne '' && $awarded ne $old_aw) {
                   3931: 		    $newrecord{'resource.'.$part.'.'.$type}= $awarded;
1.257     albertel 3932: 		    $newrecord{'resource.'.$part.'.regrader'}="$env{'user.name'}:$env{'user.domain'}";
1.54      albertel 3933: 		    $updateflag=1;
                   3934: 		}
1.93      albertel 3935: 		$line .= '<td align="center">'.$old_aw.'&nbsp;</td>'.
1.54      albertel 3936: 		    '<td align="center">'.$awarded.'&nbsp;</td>';
                   3937: 	    }
1.44      ng       3938: 	}
1.477     albertel 3939: 	$line.="\n";
1.301     albertel 3940: 
                   3941: 	my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   3942: 	my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   3943: 
1.44      ng       3944: 	if ($updateflag) {
                   3945: 	    $count++;
1.257     albertel 3946: 	    &Apache::lonnet::cstore(\%newrecord,$symb,$env{'request.course.id'},
1.89      albertel 3947: 				    $udom,$uname);
1.301     albertel 3948: 
                   3949: 	    if (&Apache::bridgetask::in_queue('gradingqueue',$symb,$cdom,
                   3950: 					      $cnum,$udom,$uname)) {
                   3951: 		# need to figure out if should be in queue.
                   3952: 		my %record =  
                   3953: 		    &Apache::lonnet::restore($symb,$env{'request.course.id'},
                   3954: 					     $udom,$uname);
                   3955: 		my $all_graded = 1;
                   3956: 		my $none_graded = 1;
                   3957: 		foreach my $part (@parts) {
                   3958: 		    if ( $record{'resource.'.$part.'.awarded'} eq '' ) {
                   3959: 			$all_graded = 0;
                   3960: 		    } else {
                   3961: 			$none_graded = 0;
                   3962: 		    }
                   3963: 		}
                   3964: 
                   3965: 		if ($all_graded || $none_graded) {
                   3966: 		    &Apache::bridgetask::remove_from_queue('gradingqueue',
                   3967: 							   $symb,$cdom,$cnum,
                   3968: 							   $udom,$uname);
                   3969: 		}
                   3970: 	    }
                   3971: 
1.477     albertel 3972: 	    $result.=&Apache::loncommon::start_data_table_row().
                   3973: 		'<td align="right">&nbsp;'.$updateCtr.'&nbsp;</td>'.$line.
                   3974: 		&Apache::loncommon::end_data_table_row();
1.126     ng       3975: 	    $updateCtr++;
1.93      albertel 3976: 	} else {
1.477     albertel 3977: 	    push(@noupdate,
                   3978: 		 '<td align="right">&nbsp;'.$noupdateCtr.'&nbsp;</td>'.$line);
1.126     ng       3979: 	    $noupdateCtr++;
1.44      ng       3980: 	}
1.269     raeburn  3981:         if ($aggregateflag) {
                   3982:             &Apache::lonnet::cinc('nohist_resourcetracker',\%aggregate,
1.301     albertel 3983: 				  $cdom,$cnum);
1.269     raeburn  3984:         }
1.93      albertel 3985:     }
1.477     albertel 3986:     if (@noupdate) {
1.126     ng       3987: #	my $numcols=(scalar(@partid)*(scalar(@parts)-1)*2)+3;
                   3988: 	my $numcols=scalar(@partid)*4+2;
1.477     albertel 3989: 	$result .= &Apache::loncommon::start_data_table_row('LC_empty_row').
1.478     albertel 3990: 	    '<td align="center" colspan="'.$numcols.'">'.
                   3991: 	    &mt('No Changes Occurred For the Students Below').
                   3992: 	    '</td>'.
1.477     albertel 3993: 	    &Apache::loncommon::end_data_table_row();
                   3994: 	foreach my $line (@noupdate) {
                   3995: 	    $result.=
                   3996: 		&Apache::loncommon::start_data_table_row().
                   3997: 		$line.
                   3998: 		&Apache::loncommon::end_data_table_row();
                   3999: 	}
1.44      ng       4000:     }
1.614     www      4001:     $result .= &Apache::loncommon::end_data_table();
1.478     albertel 4002:     my $msg = '<p><b>'.
                   4003: 	&mt('Number of records updated = [_1] for [quant,_2,student].',
                   4004: 	    $rec_update,$count).'</b><br />'.
                   4005: 	'<b>'.&mt('Total number of students = [_1]',$env{'form.total'}).
                   4006: 	'</b></p>';
1.44      ng       4007:     return $title.$msg.$result;
1.5       albertel 4008: }
1.54      albertel 4009: 
                   4010: sub split_part_type {
                   4011:     my ($partstr) = @_;
                   4012:     my ($temp,@allparts)=split(/_/,$partstr);
                   4013:     my $type=pop(@allparts);
1.439     albertel 4014:     my $part=join('_',@allparts);
1.54      albertel 4015:     return ($part,$type);
                   4016: }
                   4017: 
1.44      ng       4018: #------------- end of section for handling grading by section/class ---------
                   4019: #
                   4020: #----------------------------------------------------------------------------
                   4021: 
1.5       albertel 4022: 
1.44      ng       4023: #----------------------------------------------------------------------------
                   4024: #
                   4025: #-------------------------- Next few routines handles grading by csv upload
                   4026: #
                   4027: #--- Javascript to handle csv upload
1.27      albertel 4028: sub csvupload_javascript_reverse_associate {
1.573     bisitz   4029:     my $error1=&mt('You need to specify the username or the student/employee ID');
1.246     albertel 4030:     my $error2=&mt('You need to specify at least one grading field');
1.27      albertel 4031:   return(<<ENDPICK);
                   4032:   function verify(vf) {
                   4033:     var foundsomething=0;
                   4034:     var founduname=0;
1.243     albertel 4035:     var foundID=0;
1.27      albertel 4036:     for (i=0;i<=vf.nfields.value;i++) {
                   4037:       tw=eval('vf.f'+i+'.selectedIndex');
1.243     albertel 4038:       if (i==0 && tw!=0) { foundID=1; }
                   4039:       if (i==1 && tw!=0) { founduname=1; }
                   4040:       if (i!=0 && i!=1 && i!=2 && tw!=0) { foundsomething=1; }
1.27      albertel 4041:     }
1.246     albertel 4042:     if (founduname==0 && foundID==0) {
                   4043: 	alert('$error1');
                   4044: 	return;
1.27      albertel 4045:     }
                   4046:     if (foundsomething==0) {
1.246     albertel 4047: 	alert('$error2');
                   4048: 	return;
1.27      albertel 4049:     }
                   4050:     vf.submit();
                   4051:   }
                   4052:   function flip(vf,tf) {
                   4053:     var nw=eval('vf.f'+tf+'.selectedIndex');
                   4054:     var i;
                   4055:     for (i=0;i<=vf.nfields.value;i++) {
                   4056:       //can not pick the same destination field for both name and domain
                   4057:       if (((i ==0)||(i ==1)) && 
                   4058:           ((tf==0)||(tf==1)) && 
                   4059:           (i!=tf) &&
                   4060:           (eval('vf.f'+i+'.selectedIndex')==nw)) {
                   4061:         eval('vf.f'+i+'.selectedIndex=0;')
                   4062:       }
                   4063:     }
                   4064:   }
                   4065: ENDPICK
                   4066: }
                   4067: 
                   4068: sub csvupload_javascript_forward_associate {
1.573     bisitz   4069:     my $error1=&mt('You need to specify the username or the student/employee ID');
1.246     albertel 4070:     my $error2=&mt('You need to specify at least one grading field');
1.27      albertel 4071:   return(<<ENDPICK);
                   4072:   function verify(vf) {
                   4073:     var foundsomething=0;
                   4074:     var founduname=0;
1.243     albertel 4075:     var foundID=0;
1.27      albertel 4076:     for (i=0;i<=vf.nfields.value;i++) {
                   4077:       tw=eval('vf.f'+i+'.selectedIndex');
1.243     albertel 4078:       if (tw==1) { foundID=1; }
                   4079:       if (tw==2) { founduname=1; }
                   4080:       if (tw>3) { foundsomething=1; }
1.27      albertel 4081:     }
1.246     albertel 4082:     if (founduname==0 && foundID==0) {
                   4083: 	alert('$error1');
                   4084: 	return;
1.27      albertel 4085:     }
                   4086:     if (foundsomething==0) {
1.246     albertel 4087: 	alert('$error2');
                   4088: 	return;
1.27      albertel 4089:     }
                   4090:     vf.submit();
                   4091:   }
                   4092:   function flip(vf,tf) {
                   4093:     var nw=eval('vf.f'+tf+'.selectedIndex');
                   4094:     var i;
                   4095:     //can not pick the same destination field twice
                   4096:     for (i=0;i<=vf.nfields.value;i++) {
                   4097:       if ((i!=tf) && (eval('vf.f'+i+'.selectedIndex')==nw)) {
                   4098:         eval('vf.f'+i+'.selectedIndex=0;')
                   4099:       }
                   4100:     }
                   4101:   }
                   4102: ENDPICK
                   4103: }
                   4104: 
1.26      albertel 4105: sub csvuploadmap_header {
1.324     albertel 4106:     my ($request,$symb,$datatoken,$distotal)= @_;
1.41      ng       4107:     my $javascript;
1.257     albertel 4108:     if ($env{'form.upfile_associate'} eq 'reverse') {
1.41      ng       4109: 	$javascript=&csvupload_javascript_reverse_associate();
                   4110:     } else {
                   4111: 	$javascript=&csvupload_javascript_forward_associate();
                   4112:     }
1.45      ng       4113: 
1.418     albertel 4114:     $symb = &Apache::lonenc::check_encrypt($symb);
1.632     www      4115:     $request->print('<form method="post" enctype="multipart/form-data" action="/adm/grades" name="gradesupload">'.
                   4116:                     &mt('Total number of records found in file: [_1]',$distotal).'<hr />'.
                   4117:                     &mt('Associate entries from the uploaded file with as many fields as you can.'));
                   4118:     my $reverse=&mt("Reverse Association");
1.41      ng       4119:     $request->print(<<ENDPICK);
1.632     www      4120: <br />
                   4121: <input type="button" value="$reverse" onclick="javascript:this.form.associate.value='Reverse Association';submit(this.form);" />
1.26      albertel 4122: <input type="hidden" name="associate"  value="" />
                   4123: <input type="hidden" name="phase"      value="three" />
                   4124: <input type="hidden" name="datatoken"  value="$datatoken" />
1.257     albertel 4125: <input type="hidden" name="fileupload" value="$env{'form.fileupload'}" />
                   4126: <input type="hidden" name="upfiletype" value="$env{'form.upfiletype'}" />
1.26      albertel 4127: <input type="hidden" name="upfile_associate" 
1.257     albertel 4128:                                        value="$env{'form.upfile_associate'}" />
1.26      albertel 4129: <input type="hidden" name="symb"       value="$symb" />
1.246     albertel 4130: <input type="hidden" name="command"    value="csvuploadoptions" />
1.26      albertel 4131: <hr />
                   4132: ENDPICK
1.597     wenzelju 4133:     $request->print(&Apache::lonhtmlcommon::scripttag($javascript));
1.118     ng       4134:     return '';
1.26      albertel 4135: 
                   4136: }
                   4137: 
                   4138: sub csvupload_fields {
1.582     raeburn  4139:     my ($symb,$errorref) = @_;
                   4140:     my (@parts) = &getpartlist($symb,$errorref);
                   4141:     if (ref($errorref)) {
                   4142:         if ($$errorref) {
                   4143:             return;
                   4144:         }
                   4145:     }
                   4146: 
1.556     weissno  4147:     my @fields=(['ID','Student/Employee ID'],
1.243     albertel 4148: 		['username','Student Username'],
                   4149: 		['domain','Student Domain']);
1.324     albertel 4150:     my (undef,undef,$url) = &Apache::lonnet::decode_symb($symb);
1.41      ng       4151:     foreach my $part (sort(@parts)) {
                   4152: 	my @datum;
                   4153: 	my $display=&Apache::lonnet::metadata($url,$part.'.display');
                   4154: 	my $name=$part;
                   4155: 	if  (!$display) { $display = $name; }
                   4156: 	@datum=($name,$display);
1.244     albertel 4157: 	if ($name=~/^stores_(.*)_awarded/) {
                   4158: 	    push(@fields,['stores_'.$1.'_points',"Points [Part: $1]"]);
                   4159: 	}
1.41      ng       4160: 	push(@fields,\@datum);
                   4161:     }
                   4162:     return (@fields);
1.26      albertel 4163: }
                   4164: 
                   4165: sub csvuploadmap_footer {
1.41      ng       4166:     my ($request,$i,$keyfields) =@_;
1.703     bisitz   4167:     my $buttontext = &mt('Assign Grades');
1.41      ng       4168:     $request->print(<<ENDPICK);
1.26      albertel 4169: </table>
                   4170: <input type="hidden" name="nfields" value="$i" />
                   4171: <input type="hidden" name="keyfields" value="$keyfields" />
1.703     bisitz   4172: <input type="button" onclick="javascript:verify(this.form)" value="$buttontext" /><br />
1.26      albertel 4173: </form>
                   4174: ENDPICK
                   4175: }
                   4176: 
1.283     albertel 4177: sub checkforfile_js {
1.638     www      4178:     my $alertmsg = &mt('Please use the browse button to select a file from your local directory.');
1.597     wenzelju 4179:     my $result = &Apache::lonhtmlcommon::scripttag(<<CSVFORMJS);
1.86      ng       4180:     function checkUpload(formname) {
                   4181: 	if (formname.upfile.value == "") {
1.539     riegler  4182: 	    alert("$alertmsg");
1.86      ng       4183: 	    return false;
                   4184: 	}
                   4185: 	formname.submit();
                   4186:     }
                   4187: CSVFORMJS
1.283     albertel 4188:     return $result;
                   4189: }
                   4190: 
                   4191: sub upcsvScores_form {
1.608     www      4192:     my ($request,$symb) = @_;
1.283     albertel 4193:     if (!$symb) {return '';}
                   4194:     my $result=&checkforfile_js();
1.632     www      4195:     $result.=&Apache::loncommon::start_data_table().
                   4196:              &Apache::loncommon::start_data_table_header_row().
                   4197:              '<th>'.&mt('Specify a file containing the class scores for current resource.').'</th>'.
                   4198:              &Apache::loncommon::end_data_table_header_row().
                   4199:              &Apache::loncommon::start_data_table_row().'<td>';
1.370     www      4200:     my $upload=&mt("Upload Scores");
1.86      ng       4201:     my $upfile_select=&Apache::loncommon::upfile_select_html();
1.245     albertel 4202:     my $ignore=&mt('Ignore First Line');
1.418     albertel 4203:     $symb = &Apache::lonenc::check_encrypt($symb);
1.86      ng       4204:     $result.=<<ENDUPFORM;
1.106     albertel 4205: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="gradesupload">
1.86      ng       4206: <input type="hidden" name="symb" value="$symb" />
                   4207: <input type="hidden" name="command" value="csvuploadmap" />
                   4208: $upfile_select
1.589     bisitz   4209: <br /><input type="button" onclick="javascript:checkUpload(this.form);" value="$upload" />
1.86      ng       4210: </form>
                   4211: ENDUPFORM
1.370     www      4212:     $result.=&Apache::loncommon::help_open_topic("Course_Convert_To_CSV",
1.632     www      4213:                            &mt("How do I create a CSV file from a spreadsheet")).
                   4214:              '</td>'.
                   4215:             &Apache::loncommon::end_data_table_row().
                   4216:             &Apache::loncommon::end_data_table();
1.86      ng       4217:     return $result;
                   4218: }
                   4219: 
                   4220: 
1.26      albertel 4221: sub csvuploadmap {
1.608     www      4222:     my ($request,$symb)= @_;
1.41      ng       4223:     if (!$symb) {return '';}
1.72      ng       4224: 
1.41      ng       4225:     my $datatoken;
1.257     albertel 4226:     if (!$env{'form.datatoken'}) {
1.41      ng       4227: 	$datatoken=&Apache::loncommon::upfile_store($request);
1.26      albertel 4228:     } else {
1.257     albertel 4229: 	$datatoken=$env{'form.datatoken'};
1.41      ng       4230: 	&Apache::loncommon::load_tmp_file($request);
1.26      albertel 4231:     }
1.41      ng       4232:     my @records=&Apache::loncommon::upfile_record_sep();
1.324     albertel 4233:     &csvuploadmap_header($request,$symb,$datatoken,$#records+1);
1.41      ng       4234:     my ($i,$keyfields);
                   4235:     if (@records) {
1.582     raeburn  4236:         my $fieldserror;
                   4237: 	my @fields=&csvupload_fields($symb,\$fieldserror);
                   4238:         if ($fieldserror) {
                   4239:             $request->print(&navmap_errormsg());
                   4240:             return;
                   4241:         }
1.257     albertel 4242: 	if ($env{'form.upfile_associate'} eq 'reverse') {	
1.41      ng       4243: 	    &Apache::loncommon::csv_print_samples($request,\@records);
                   4244: 	    $i=&Apache::loncommon::csv_print_select_table($request,\@records,
                   4245: 							  \@fields);
                   4246: 	    foreach (@fields) { $keyfields.=$_->[0].','; }
                   4247: 	    chop($keyfields);
                   4248: 	} else {
                   4249: 	    unshift(@fields,['none','']);
                   4250: 	    $i=&Apache::loncommon::csv_samples_select_table($request,\@records,
                   4251: 							    \@fields);
1.311     banghart 4252:             foreach my $rec (@records) {
                   4253:                 my %temp = &Apache::loncommon::record_sep($rec);
                   4254:                 if (%temp) {
                   4255:                     $keyfields=join(',',sort(keys(%temp)));
                   4256:                     last;
                   4257:                 }
                   4258:             }
1.41      ng       4259: 	}
                   4260:     }
                   4261:     &csvuploadmap_footer($request,$i,$keyfields);
1.72      ng       4262: 
1.41      ng       4263:     return '';
1.27      albertel 4264: }
                   4265: 
1.246     albertel 4266: sub csvuploadoptions {
1.608     www      4267:     my ($request,$symb)= @_;
1.632     www      4268:     my $overwrite=&mt('Overwrite any existing score');
1.246     albertel 4269:     $request->print(<<ENDPICK);
                   4270: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="gradesupload">
                   4271: <input type="hidden" name="command"    value="csvuploadassign" />
                   4272: <p>
                   4273: <label>
                   4274:    <input type="checkbox" name="overwite_scores" checked="checked" />
1.632     www      4275:    $overwrite
1.246     albertel 4276: </label>
                   4277: </p>
                   4278: ENDPICK
                   4279:     my %fields=&get_fields();
                   4280:     if (!defined($fields{'domain'})) {
1.257     albertel 4281: 	my $domform = &Apache::loncommon::select_dom_form($env{'request.role.domain'},'default_domain');
1.632     www      4282: 	$request->print("\n<p>".&mt('Users are in domain: [_1]',$domform)."</p>\n");
1.246     albertel 4283:     }
1.257     albertel 4284:     foreach my $key (sort(keys(%env))) {
1.246     albertel 4285: 	if ($key !~ /^form\.(.*)$/) { next; }
                   4286: 	my $cleankey=$1;
                   4287: 	if ($cleankey eq 'command') { next; }
                   4288: 	$request->print('<input type="hidden" name="'.$cleankey.
1.257     albertel 4289: 			'"  value="'.$env{$key}.'" />'."\n");
1.246     albertel 4290:     }
                   4291:     # FIXME do a check for any duplicated user ids...
                   4292:     # FIXME do a check for any invalid user ids?...
1.703     bisitz   4293:     $request->print('<input type="submit" value="'.&mt('Assign Grades').'" /><br />
1.290     albertel 4294: <hr /></form>'."\n");
1.246     albertel 4295:     return '';
                   4296: }
                   4297: 
                   4298: sub get_fields {
                   4299:     my %fields;
1.257     albertel 4300:     my @keyfields = split(/\,/,$env{'form.keyfields'});
                   4301:     for (my $i=0; $i<=$env{'form.nfields'}; $i++) {
                   4302: 	if ($env{'form.upfile_associate'} eq 'reverse') {
                   4303: 	    if ($env{'form.f'.$i} ne 'none') {
                   4304: 		$fields{$keyfields[$i]}=$env{'form.f'.$i};
1.41      ng       4305: 	    }
                   4306: 	} else {
1.257     albertel 4307: 	    if ($env{'form.f'.$i} ne 'none') {
                   4308: 		$fields{$env{'form.f'.$i}}=$keyfields[$i];
1.41      ng       4309: 	    }
                   4310: 	}
1.27      albertel 4311:     }
1.246     albertel 4312:     return %fields;
                   4313: }
                   4314: 
                   4315: sub csvuploadassign {
1.608     www      4316:     my ($request,$symb)= @_;
1.246     albertel 4317:     if (!$symb) {return '';}
1.345     bowersj2 4318:     my $error_msg = '';
1.246     albertel 4319:     &Apache::loncommon::load_tmp_file($request);
                   4320:     my @gradedata = &Apache::loncommon::upfile_record_sep();
                   4321:     my %fields=&get_fields();
1.257     albertel 4322:     my $courseid=$env{'request.course.id'};
1.97      albertel 4323:     my ($classlist) = &getclasslist('all',0);
1.106     albertel 4324:     my @notallowed;
1.41      ng       4325:     my @skipped;
1.657     raeburn  4326:     my @warnings;
1.41      ng       4327:     my $countdone=0;
                   4328:     foreach my $grade (@gradedata) {
                   4329: 	my %entries=&Apache::loncommon::record_sep($grade);
1.246     albertel 4330: 	my $domain;
                   4331: 	if ($entries{$fields{'domain'}}) {
                   4332: 	    $domain=$entries{$fields{'domain'}};
                   4333: 	} else {
1.257     albertel 4334: 	    $domain=$env{'form.default_domain'};
1.246     albertel 4335: 	}
1.243     albertel 4336: 	$domain=~s/\s//g;
1.41      ng       4337: 	my $username=$entries{$fields{'username'}};
1.160     albertel 4338: 	$username=~s/\s//g;
1.243     albertel 4339: 	if (!$username) {
                   4340: 	    my $id=$entries{$fields{'ID'}};
1.247     albertel 4341: 	    $id=~s/\s//g;
1.243     albertel 4342: 	    my %ids=&Apache::lonnet::idget($domain,$id);
                   4343: 	    $username=$ids{$id};
                   4344: 	}
1.41      ng       4345: 	if (!exists($$classlist{"$username:$domain"})) {
1.247     albertel 4346: 	    my $id=$entries{$fields{'ID'}};
                   4347: 	    $id=~s/\s//g;
                   4348: 	    if ($id) {
                   4349: 		push(@skipped,"$id:$domain");
                   4350: 	    } else {
                   4351: 		push(@skipped,"$username:$domain");
                   4352: 	    }
1.41      ng       4353: 	    next;
                   4354: 	}
1.108     albertel 4355: 	my $usec=$classlist->{"$username:$domain"}[5];
1.106     albertel 4356: 	if (!&canmodify($usec)) {
                   4357: 	    push(@notallowed,"$username:$domain");
                   4358: 	    next;
                   4359: 	}
1.244     albertel 4360: 	my %points;
1.41      ng       4361: 	my %grades;
                   4362: 	foreach my $dest (keys(%fields)) {
1.244     albertel 4363: 	    if ($dest eq 'ID' || $dest eq 'username' ||
                   4364: 		$dest eq 'domain') { next; }
                   4365: 	    if ($entries{$fields{$dest}} =~ /^\s*$/) { next; }
                   4366: 	    if ($dest=~/stores_(.*)_points/) {
                   4367: 		my $part=$1;
                   4368: 		my $wgt =&Apache::lonnet::EXT('resource.'.$part.'.weight',
                   4369: 					      $symb,$domain,$username);
1.345     bowersj2 4370:                 if ($wgt) {
                   4371:                     $entries{$fields{$dest}}=~s/\s//g;
                   4372:                     my $pcr=$entries{$fields{$dest}} / $wgt;
1.463     albertel 4373:                     my $award=($pcr == 0) ? 'incorrect_by_override'
                   4374:                                           : 'correct_by_override';
1.638     www      4375:                     if ($pcr>1) {
1.657     raeburn  4376:                        push(@warnings,&mt("[_1]: point value larger than weight","$username:$domain"));
1.638     www      4377:                     }
1.345     bowersj2 4378:                     $grades{"resource.$part.awarded"}=$pcr;
                   4379:                     $grades{"resource.$part.solved"}=$award;
                   4380:                     $points{$part}=1;
                   4381:                 } else {
                   4382:                     $error_msg = "<br />" .
                   4383:                         &mt("Some point values were assigned"
                   4384:                             ." for problems with a weight "
                   4385:                             ."of zero. These values were "
                   4386:                             ."ignored.");
                   4387:                 }
1.244     albertel 4388: 	    } else {
                   4389: 		if ($dest=~/stores_(.*)_awarded/) { if ($points{$1}) {next;} }
                   4390: 		if ($dest=~/stores_(.*)_solved/)  { if ($points{$1}) {next;} }
                   4391: 		my $store_key=$dest;
                   4392: 		$store_key=~s/^stores/resource/;
                   4393: 		$store_key=~s/_/\./g;
                   4394: 		$grades{$store_key}=$entries{$fields{$dest}};
                   4395: 	    }
1.41      ng       4396: 	}
1.508     www      4397: 	if (! %grades) { 
                   4398:            push(@skipped,&mt("[_1]: no data to save","$username:$domain")); 
                   4399:         } else {
                   4400: 	   $grades{"resource.regrader"}="$env{'user.name'}:$env{'user.domain'}";
                   4401: 	   my $result=&Apache::lonnet::cstore(\%grades,$symb,
1.302     albertel 4402: 					   $env{'request.course.id'},
                   4403: 					   $domain,$username);
1.508     www      4404: 	   if ($result eq 'ok') {
1.627     www      4405: # Successfully stored
1.508     www      4406: 	      $request->print('.');
1.627     www      4407: # Remove from grading queue
                   4408:               &Apache::bridgetask::remove_from_queue('gradingqueue',$symb,
                   4409:                                              $env{'course.'.$env{'request.course.id'}.'.domain'},
                   4410:                                              $env{'course.'.$env{'request.course.id'}.'.num'},
                   4411:                                              $domain,$username);
                   4412:               $countdone++;
                   4413:            } else {
1.508     www      4414: 	      $request->print("<p><span class=\"LC_error\">".
                   4415:                               &mt("Failed to save data for student [_1]. Message when trying to save was: [_2]",
                   4416:                                   "$username:$domain",$result)."</span></p>");
                   4417: 	   }
                   4418: 	   $request->rflush();
                   4419:         }
1.41      ng       4420:     }
1.570     www      4421:     $request->print('<br />'.&Apache::lonhtmlcommon::confirm_success(&mt("Saved scores for [quant,_1,student]",$countdone),$countdone==0));
1.657     raeburn  4422:     if (@warnings) {
                   4423:         $request->print('<br />'.&Apache::lonhtmlcommon::confirm_success(&mt('Warnings generated for the following saved scores:'),1).'<br />');
                   4424:         $request->print(join(', ',@warnings));
                   4425:     }
1.41      ng       4426:     if (@skipped) {
1.571     www      4427: 	$request->print('<br />'.&Apache::lonhtmlcommon::confirm_success(&mt('No scores stored for the following username(s):'),1).'<br />');
                   4428:         $request->print(join(', ',@skipped));
1.106     albertel 4429:     }
                   4430:     if (@notallowed) {
1.571     www      4431: 	$request->print('<br />'.&Apache::lonhtmlcommon::confirm_success(&mt('Modification of scores not allowed for the following username(s):'),1).'<br />');
                   4432: 	$request->print(join(', ',@notallowed));
1.41      ng       4433:     }
1.106     albertel 4434:     $request->print("<br />\n");
1.345     bowersj2 4435:     return $error_msg;
1.26      albertel 4436: }
1.44      ng       4437: #------------- end of section for handling csv file upload ---------
                   4438: #
                   4439: #-------------------------------------------------------------------
                   4440: #
1.122     ng       4441: #-------------- Next few routines handle grading by page/sequence
1.72      ng       4442: #
                   4443: #--- Select a page/sequence and a student to grade
1.68      ng       4444: sub pickStudentPage {
1.608     www      4445:     my ($request,$symb) = @_;
1.68      ng       4446: 
1.539     riegler  4447:     my $alertmsg = &mt('Please select the student you wish to grade.');
1.597     wenzelju 4448:     $request->print(&Apache::lonhtmlcommon::scripttag(<<LISTJAVASCRIPT));
1.68      ng       4449: 
                   4450: function checkPickOne(formname) {
1.76      ng       4451:     if (radioSelection(formname.student) == null) {
1.539     riegler  4452: 	alert("$alertmsg");
1.68      ng       4453: 	return;
                   4454:     }
1.125     ng       4455:     ptr = pullDownSelection(formname.selectpage);
                   4456:     formname.page.value = formname["page"+ptr].value;
                   4457:     formname.title.value = formname["title"+ptr].value;
1.68      ng       4458:     formname.submit();
                   4459: }
                   4460: 
                   4461: LISTJAVASCRIPT
1.118     ng       4462:     &commonJSfunctions($request);
1.608     www      4463: 
1.257     albertel 4464:     my $cdom      = $env{"course.$env{'request.course.id'}.domain"};
                   4465:     my $cnum      = $env{"course.$env{'request.course.id'}.num"};
                   4466:     my $getsec    = $env{'form.section'} eq '' ? 'all' : $env{'form.section'};
1.68      ng       4467: 
1.398     albertel 4468:     my $result='<h3><span class="LC_info">&nbsp;'.
1.485     albertel 4469: 	&mt('Manual Grading by Page or Sequence').'</span></h3>';
1.68      ng       4470: 
1.80      ng       4471:     $result.='<form action="/adm/grades" method="post" name="displayPage">'."\n";
1.582     raeburn  4472:     my $map_error;
                   4473:     my ($titles,$symbx) = &getSymbMap($map_error);
                   4474:     if ($map_error) {
                   4475:         $request->print(&navmap_errormsg());
                   4476:         return; 
                   4477:     }
1.137     albertel 4478:     my ($curpage) =&Apache::lonnet::decode_symb($symb); 
                   4479: #    my ($curpage,$mapId) =&Apache::lonnet::decode_symb($symb); 
                   4480: #    my $type=($curpage =~ /\.(page|sequence)/);
1.700     bisitz   4481: 
                   4482:     # Collection of hidden fields
1.70      ng       4483:     my $ctr=0;
1.68      ng       4484:     foreach (@$titles) {
1.700     bisitz   4485:         my ($minder,$showtitle) = ($_ =~ /(\d+)\.(.*)/);
                   4486:         $result.='<input type="hidden" name="page'.$ctr.'" value="'.$$symbx{$_}.'" />'."\n";
                   4487:         $result.='<input type="hidden" name="title'.$ctr.'" value="'.$showtitle.'" />'."\n";
                   4488:         $ctr++;
1.68      ng       4489:     }
1.700     bisitz   4490:     $result.='<input type="hidden" name="page" />'."\n".
                   4491:         '<input type="hidden" name="title" />'."\n";
                   4492: 
                   4493:     $result.=&build_section_inputs();
                   4494:     my $stu_status = join(':',&Apache::loncommon::get_env_multiple('form.Status'));
                   4495:     $result.='<input type="hidden" name="Status"  value="'.$stu_status.'" />'."\n".
                   4496: 	'<input type="hidden" name="command" value="displayPage" />'."\n".
                   4497: 	'<input type="hidden" name="symb"    value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n";
1.485     albertel 4498: 
1.700     bisitz   4499:     # Show grading options
                   4500:     $result.=&Apache::lonhtmlcommon::start_pick_box();
                   4501:     my $select = '<select name="selectpage">'."\n";
1.70      ng       4502:     $ctr=0;
                   4503:     foreach (@$titles) {
                   4504: 	my ($minder,$showtitle) = ($_ =~ /(\d+)\.(.*)/);
1.700     bisitz   4505: 	$select.='<option value="'.$ctr.'"'.
                   4506: 	    ($$symbx{$_} =~ /$curpage$/ ? ' selected="selected"' : '').
                   4507: 	    '>'.$showtitle.'</option>'."\n";
1.70      ng       4508: 	$ctr++;
                   4509:     }
1.700     bisitz   4510:     $select.= '</select>';
1.68      ng       4511: 
1.700     bisitz   4512:     $result.=
                   4513:         &Apache::lonhtmlcommon::row_title(&mt('Problems from'))
                   4514:        .$select
                   4515:        .&Apache::lonhtmlcommon::row_closure();
                   4516: 
                   4517:     $result.=
                   4518:         &Apache::lonhtmlcommon::row_title(&mt('View Problem Text'))
                   4519:        .'<label><input type="radio" name="vProb" value="no"'
                   4520:            .' checked="checked" /> '.&mt('no').' </label>'."\n"
                   4521:        .'<label><input type="radio" name="vProb" value="yes" />'
                   4522:            .&mt('yes').'</label>'."\n"
                   4523:        .&Apache::lonhtmlcommon::row_closure();
                   4524: 
                   4525:     $result.=
                   4526:         &Apache::lonhtmlcommon::row_title(&mt('View Submissions'))
                   4527:        .'<label><input type="radio" name="lastSub" value="none" /> '
                   4528:            .&mt('none').' </label>'."\n"
                   4529:        .'<label><input type="radio" name="lastSub" value="datesub"'
                   4530:            .' checked="checked" /> '.&mt('all submissions').'</label>'."\n"
                   4531:        .'<label><input type="radio" name="lastSub" value="all" /> '
                   4532:            .&mt('all submissions with details').' </label>'
                   4533:        .&Apache::lonhtmlcommon::row_closure();
1.432     banghart 4534:     
1.700     bisitz   4535:     $result.=
                   4536:         &Apache::lonhtmlcommon::row_title(&mt('Use CODE'))
                   4537:        .'<input type="text" name="CODE" value="" />'
                   4538:        .&Apache::lonhtmlcommon::row_closure(1)
                   4539:        .&Apache::lonhtmlcommon::end_pick_box();
1.382     albertel 4540: 
1.700     bisitz   4541:     # Show list of students to select for grading
                   4542:     $result.='<br /><input type="button" '.
1.589     bisitz   4543:              'onclick="javascript:checkPickOne(this.form);" value="'.&mt('Next').' &rarr;" /><br />'."\n";
1.72      ng       4544: 
1.68      ng       4545:     $request->print($result);
                   4546: 
1.485     albertel 4547:     my $studentTable.='&nbsp;<b>'.&mt('Select a student you wish to grade and then click on the Next button.').'</b><br />'.
1.484     albertel 4548: 	&Apache::loncommon::start_data_table().
                   4549: 	&Apache::loncommon::start_data_table_header_row().
1.485     albertel 4550: 	'<th align="right">&nbsp;'.&mt('No.').'</th>'.
1.484     albertel 4551: 	'<th>'.&nameUserString('header').'</th>'.
1.485     albertel 4552: 	'<th align="right">&nbsp;'.&mt('No.').'</th>'.
1.484     albertel 4553: 	'<th>'.&nameUserString('header').'</th>'.
                   4554: 	&Apache::loncommon::end_data_table_header_row();
1.68      ng       4555:  
1.76      ng       4556:     my (undef,undef,$fullname) = &getclasslist($getsec,'1');
1.68      ng       4557:     my $ptr = 1;
1.294     albertel 4558:     foreach my $student (sort 
                   4559: 			 {
                   4560: 			     if (lc($$fullname{$a}) ne lc($$fullname{$b})) {
                   4561: 				 return (lc($$fullname{$a}) cmp lc($$fullname{$b}));
                   4562: 			     }
                   4563: 			     return $a cmp $b;
                   4564: 			 } (keys(%$fullname))) {
1.68      ng       4565: 	my ($uname,$udom) = split(/:/,$student);
1.484     albertel 4566: 	$studentTable.=($ptr%2==1 ? &Apache::loncommon::start_data_table_row()
                   4567:                                   : '</td>');
1.126     ng       4568: 	$studentTable.='<td align="right">'.$ptr.'&nbsp;</td>';
1.288     albertel 4569: 	$studentTable.='<td>&nbsp;<label><input type="radio" name="student" value="'.$student.'" /> '
                   4570: 	    .&nameUserString(undef,$$fullname{$student},$uname,$udom)."</label>\n";
1.484     albertel 4571: 	$studentTable.=
                   4572: 	    ($ptr%2 == 0 ? '</td>'.&Apache::loncommon::end_data_table_row() 
                   4573:                          : '');
1.68      ng       4574: 	$ptr++;
                   4575:     }
1.484     albertel 4576:     if ($ptr%2 == 0) {
                   4577: 	$studentTable.='</td><td>&nbsp;</td><td>&nbsp;</td>'.
                   4578: 	    &Apache::loncommon::end_data_table_row();
                   4579:     }
                   4580:     $studentTable.=&Apache::loncommon::end_data_table()."\n";
1.126     ng       4581:     $studentTable.='<input type="button" '.
1.589     bisitz   4582:                    'onclick="javascript:checkPickOne(this.form);" value="'.&mt('Next').' &rarr;" /></form>'."\n";
1.68      ng       4583: 
                   4584:     $request->print($studentTable);
                   4585: 
                   4586:     return '';
                   4587: }
                   4588: 
                   4589: sub getSymbMap {
1.582     raeburn  4590:     my ($map_error) = @_;
1.132     bowersj2 4591:     my $navmap = Apache::lonnavmaps::navmap->new();
1.582     raeburn  4592:     unless (ref($navmap)) {
                   4593:         if (ref($map_error)) {
                   4594:             $$map_error = 'navmap';
                   4595:         }
                   4596:         return;
                   4597:     }
1.68      ng       4598:     my %symbx = ();
                   4599:     my @titles = ();
1.117     bowersj2 4600:     my $minder = 0;
                   4601: 
                   4602:     # Gather every sequence that has problems.
1.240     albertel 4603:     my @sequences = $navmap->retrieveResources(undef, sub { shift->is_map(); },
                   4604: 					       1,0,1);
1.117     bowersj2 4605:     for my $sequence ($navmap->getById('0.0'), @sequences) {
1.241     albertel 4606: 	if ($navmap->hasResource($sequence, sub { shift->is_problem(); }, 0) ) {
1.381     albertel 4607: 	    my $title = $minder.'.'.
                   4608: 		&HTML::Entities::encode($sequence->compTitle(),'"\'&');
                   4609: 	    push(@titles, $title); # minder in case two titles are identical
                   4610: 	    $symbx{$title} = &HTML::Entities::encode($sequence->symb(),'"\'&');
1.117     bowersj2 4611: 	    $minder++;
1.241     albertel 4612: 	}
1.68      ng       4613:     }
                   4614:     return \@titles,\%symbx;
                   4615: }
                   4616: 
1.72      ng       4617: #
                   4618: #--- Displays a page/sequence w/wo problems, w/wo submissions
1.68      ng       4619: sub displayPage {
1.608     www      4620:     my ($request,$symb) = @_;
1.257     albertel 4621:     my $cdom      = $env{"course.$env{'request.course.id'}.domain"};
                   4622:     my $cnum      = $env{"course.$env{'request.course.id'}.num"};
                   4623:     my $getsec    = $env{'form.section'} eq '' ? 'all' : $env{'form.section'};
                   4624:     my $pageTitle = $env{'form.page'};
1.103     albertel 4625:     my ($classlist,undef,$fullname) = &getclasslist($getsec,'1');
1.257     albertel 4626:     my ($uname,$udom) = split(/:/,$env{'form.student'});
                   4627:     my $usec=$classlist->{$env{'form.student'}}[5];
1.168     albertel 4628: 
                   4629:     #need to make sure we have the correct data for later EXT calls, 
                   4630:     #thus invalidate the cache
                   4631:     &Apache::lonnet::devalidatecourseresdata(
1.257     albertel 4632:                  $env{'course.'.$env{'request.course.id'}.'.num'},
                   4633:                  $env{'course.'.$env{'request.course.id'}.'.domain'});
1.168     albertel 4634:     &Apache::lonnet::clear_EXT_cache_status();
                   4635: 
1.103     albertel 4636:     if (!&canview($usec)) {
1.712     bisitz   4637:         $request->print(
                   4638:             '<span class="LC_warning">'.
                   4639:             &mt('Unable to view requested student. ([_1])',
                   4640:                     $env{'form.student'}).
                   4641:             '</span>');
                   4642:         return;
1.103     albertel 4643:     }
1.398     albertel 4644:     my $result='<h3><span class="LC_info">&nbsp;'.$env{'form.title'}.'</span></h3>';
1.485     albertel 4645:     $result.='<h3>&nbsp;'.&mt('Student: [_1]',&nameUserString(undef,$$fullname{$env{'form.student'}},$uname,$udom)).
1.129     ng       4646: 	'</h3>'."\n";
1.500     albertel 4647:     $env{'form.CODE'} = uc($env{'form.CODE'});
1.501     foxr     4648:     if (&Apache::lonnet::validCODE(uc($env{'form.CODE'}))) {
1.485     albertel 4649: 	$result.='<h3>&nbsp;'.&mt('CODE: [_1]',$env{'form.CODE'}).'</h3>'."\n";
1.382     albertel 4650:     } else {
                   4651: 	delete($env{'form.CODE'});
                   4652:     }
1.71      ng       4653:     &sub_page_js($request);
                   4654:     $request->print($result);
                   4655: 
1.132     bowersj2 4656:     my $navmap = Apache::lonnavmaps::navmap->new();
1.582     raeburn  4657:     unless (ref($navmap)) {
                   4658:         $request->print(&navmap_errormsg());
                   4659:         return;
                   4660:     }
1.257     albertel 4661:     my ($mapUrl, $id, $resUrl)=&Apache::lonnet::decode_symb($env{'form.page'});
1.68      ng       4662:     my $map = $navmap->getResourceByUrl($resUrl); # add to navmaps
1.288     albertel 4663:     if (!$map) {
1.485     albertel 4664: 	$request->print('<span class="LC_warning">'.&mt('Unable to view requested sequence. ([_1])',$resUrl).'</span>');
1.288     albertel 4665: 	return; 
                   4666:     }
1.68      ng       4667:     my $iterator = $navmap->getIterator($map->map_start(),
                   4668: 					$map->map_finish());
                   4669: 
1.71      ng       4670:     my $studentTable='<form action="/adm/grades" method="post" name="gradePage">'."\n".
1.72      ng       4671: 	'<input type="hidden" name="command" value="gradeByPage" />'."\n".
1.257     albertel 4672: 	'<input type="hidden" name="fullname" value="'.$$fullname{$env{'form.student'}}.'" />'."\n".
                   4673: 	'<input type="hidden" name="student" value="'.$env{'form.student'}.'" />'."\n".
1.72      ng       4674: 	'<input type="hidden" name="page"    value="'.$pageTitle.'" />'."\n".
1.257     albertel 4675: 	'<input type="hidden" name="title"   value="'.$env{'form.title'}.'" />'."\n".
1.418     albertel 4676: 	'<input type="hidden" name="symb"    value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
1.613     www      4677: 	'<input type="hidden" name="overRideScore" value="no" />'."\n";
1.71      ng       4678: 
1.382     albertel 4679:     if (defined($env{'form.CODE'})) {
                   4680: 	$studentTable.=
                   4681: 	    '<input type="hidden" name="CODE" value="'.$env{'form.CODE'}.'" />'."\n";
                   4682:     }
1.381     albertel 4683:     my $checkIcon = '<img alt="'.&mt('Check Mark').
1.485     albertel 4684: 	'" src="'.&Apache::loncommon::lonhttpdurl($request->dir_config('lonIconsURL').'/check.gif').'" height="16" border="0" />';
1.71      ng       4685: 
1.594     bisitz   4686:     $studentTable.='&nbsp;<span class="LC_info">'.
                   4687:         &mt('Problems graded correct by the computer are marked with a [_1] symbol.',$checkIcon).
                   4688:         '</span>'."\n".
1.484     albertel 4689: 	&Apache::loncommon::start_data_table().
                   4690: 	&Apache::loncommon::start_data_table_header_row().
1.700     bisitz   4691: 	'<th>'.&mt('Prob.').'</th>'.
1.485     albertel 4692: 	'<th>&nbsp;'.($env{'form.vProb'} eq 'no' ? &mt('Title') : &mt('Problem Text')).'/'.&mt('Grade').'</th>'.
1.484     albertel 4693: 	&Apache::loncommon::end_data_table_header_row();
1.71      ng       4694: 
1.329     albertel 4695:     &Apache::lonxml::clear_problem_counter();
1.196     albertel 4696:     my ($depth,$question,$prob) = (1,1,1);
1.68      ng       4697:     $iterator->next(); # skip the first BEGIN_MAP
                   4698:     my $curRes = $iterator->next(); # for "current resource"
1.101     albertel 4699:     while ($depth > 0) {
1.68      ng       4700:         if($curRes == $iterator->BEGIN_MAP) { $depth++; }
1.100     bowersj2 4701:         if($curRes == $iterator->END_MAP) { $depth--; }
1.68      ng       4702: 
1.385     albertel 4703:         if (ref($curRes) && $curRes->is_problem()) {
1.91      albertel 4704: 	    my $parts = $curRes->parts();
1.68      ng       4705:             my $title = $curRes->compTitle();
1.71      ng       4706: 	    my $symbx = $curRes->symb();
1.484     albertel 4707: 	    $studentTable.=
                   4708: 		&Apache::loncommon::start_data_table_row().
                   4709: 		'<td align="center" valign="top" >'.$prob.
1.485     albertel 4710: 		(scalar(@{$parts}) == 1 ? '' 
1.681     raeburn  4711: 		                        : '<br />('.&mt('[_1]parts',
                   4712: 							scalar(@{$parts}).'&nbsp;').')'
1.485     albertel 4713: 		 ).
                   4714: 		 '</td>';
1.71      ng       4715: 	    $studentTable.='<td valign="top">';
1.382     albertel 4716: 	    my %form = ('CODE' => $env{'form.CODE'},);
1.257     albertel 4717: 	    if ($env{'form.vProb'} eq 'yes' ) {
1.144     albertel 4718: 		$studentTable.=&show_problem($request,$symbx,$uname,$udom,1,
1.383     albertel 4719: 					     undef,'both',\%form);
1.71      ng       4720: 	    } else {
1.382     albertel 4721: 		my $companswer = &Apache::loncommon::get_student_answers($symbx,$uname,$udom,$env{'request.course.id'},%form);
1.80      ng       4722: 		$companswer =~ s|<form(.*?)>||g;
                   4723: 		$companswer =~ s|</form>||g;
1.71      ng       4724: #		while ($companswer =~ /(<a href\=\"javascript:newWindow.*?Script Vars<\/a>)/s) { #<a href="javascript:newWindow</a>
1.116     ng       4725: #		    $companswer =~ s/$1/ /ms;
1.326     albertel 4726: #		    $request->print('match='.$1."<br />\n");
1.71      ng       4727: #		}
1.116     ng       4728: #		$companswer =~ s|<table border=\"1\">|<table border=\"0\">|g;
1.539     riegler  4729: 		$studentTable.='&nbsp;<b>'.$title.'</b>&nbsp;<br />&nbsp;<b>'.&mt('Correct answer').':</b><br />'.$companswer;
1.71      ng       4730: 	    }
                   4731: 
1.257     albertel 4732: 	    my %record = &Apache::lonnet::restore($symbx,$env{'request.course.id'},$udom,$uname);
1.125     ng       4733: 
1.257     albertel 4734: 	    if ($env{'form.lastSub'} eq 'datesub') {
1.71      ng       4735: 		if ($record{'version'} eq '') {
1.485     albertel 4736: 		    $studentTable.='<br />&nbsp;<span class="LC_warning">'.&mt('No recorded submission for this problem.').'</span><br />';
1.71      ng       4737: 		} else {
1.116     ng       4738: 		    my %responseType = ();
                   4739: 		    foreach my $partid (@{$parts}) {
1.147     albertel 4740: 			my @responseIds =$curRes->responseIds($partid);
                   4741: 			my @responseType =$curRes->responseType($partid);
                   4742: 			my %responseIds;
                   4743: 			for (my $i=0;$i<=$#responseIds;$i++) {
                   4744: 			    $responseIds{$responseIds[$i]}=$responseType[$i];
                   4745: 			}
                   4746: 			$responseType{$partid} = \%responseIds;
1.116     ng       4747: 		    }
1.148     albertel 4748: 		    $studentTable.= &displaySubByDates($symbx,\%record,$parts,\%responseType,$checkIcon,$uname,$udom);
1.147     albertel 4749: 
1.71      ng       4750: 		}
1.257     albertel 4751: 	    } elsif ($env{'form.lastSub'} eq 'all') {
                   4752: 		my $last = ($env{'form.lastSub'} eq 'last' ? 'last' : '');
1.726     raeburn  4753:                 my $identifier = (&canmodify($usec)? $prob : ''); 
1.71      ng       4754: 		$studentTable.=&Apache::loncommon::get_previous_attempt($symbx,$uname,$udom,
1.257     albertel 4755: 									$env{'request.course.id'},
1.726     raeburn  4756: 									'','.submission',undef,
                   4757:                                                                         $usec,$identifier);
1.71      ng       4758:  
                   4759: 	    }
1.103     albertel 4760: 	    if (&canmodify($usec)) {
1.585     bisitz   4761:             $studentTable.=&gradeBox_start();
1.103     albertel 4762: 		foreach my $partid (@{$parts}) {
                   4763: 		    $studentTable.=&gradeBox($request,$symbx,$uname,$udom,$question,$partid,\%record);
                   4764: 		    $studentTable.='<input type="hidden" name="q_'.$question.'" value="'.$partid.'" />'."\n";
                   4765: 		    $question++;
                   4766: 		}
1.585     bisitz   4767:             $studentTable.=&gradeBox_end();
1.196     albertel 4768: 		$prob++;
1.71      ng       4769: 	    }
                   4770: 	    $studentTable.='</td></tr>';
1.68      ng       4771: 
1.103     albertel 4772: 	}
1.68      ng       4773:         $curRes = $iterator->next();
                   4774:     }
                   4775: 
1.589     bisitz   4776:     $studentTable.=
                   4777:         '</table>'."\n".
                   4778:         '<input type="button" value="'.&mt('Save').'" '.
                   4779:         'onclick="javascript:checkSubmitPage(this.form,'.$question.');" />'.
                   4780:         '</form>'."\n";
1.71      ng       4781:     $request->print($studentTable);
                   4782: 
                   4783:     return '';
1.119     ng       4784: }
                   4785: 
                   4786: sub displaySubByDates {
1.148     albertel 4787:     my ($symb,$record,$parts,$responseType,$checkIcon,$uname,$udom) = @_;
1.224     albertel 4788:     my $isCODE=0;
1.335     albertel 4789:     my $isTask = ($symb =~/\.task$/);
1.224     albertel 4790:     if (exists($record->{'resource.CODE'})) { $isCODE=1; }
1.467     albertel 4791:     my $studentTable=&Apache::loncommon::start_data_table().
                   4792: 	&Apache::loncommon::start_data_table_header_row().
                   4793: 	'<th>'.&mt('Date/Time').'</th>'.
                   4794: 	($isCODE?'<th>'.&mt('CODE').'</th>':'').
1.671     raeburn  4795:         ($isTask?'<th>'.&mt('Version').'</th>':'').
1.467     albertel 4796: 	'<th>'.&mt('Submission').'</th>'.
                   4797: 	'<th>'.&mt('Status').'</th>'.
                   4798: 	&Apache::loncommon::end_data_table_header_row();
1.119     ng       4799:     my ($version);
                   4800:     my %mark;
1.148     albertel 4801:     my %orders;
1.119     ng       4802:     $mark{'correct_by_student'} = $checkIcon;
1.147     albertel 4803:     if (!exists($$record{'1:timestamp'})) {
1.539     riegler  4804: 	return '<br />&nbsp;<span class="LC_warning">'.&mt('Nothing submitted - no attempts.').'</span><br />';
1.147     albertel 4805:     }
1.335     albertel 4806: 
                   4807:     my $interaction;
1.525     raeburn  4808:     my $no_increment = 1;
1.735   ! raeburn  4809:     my (%lastrndseed,%lasttype);
1.119     ng       4810:     for ($version=1;$version<=$$record{'version'};$version++) {
1.467     albertel 4811: 	my $timestamp = 
                   4812: 	    &Apache::lonlocal::locallocaltime($$record{$version.':timestamp'});
1.335     albertel 4813: 	if (exists($$record{$version.':resource.0.version'})) {
                   4814: 	    $interaction = $$record{$version.':resource.0.version'};
                   4815: 	}
1.671     raeburn  4816:         if ($isTask && $env{'form.previousversion'}) {
                   4817:             next unless ($interaction == $env{'form.previousversion'});
                   4818:         }
1.335     albertel 4819: 	my $where = ($isTask ? "$version:resource.$interaction"
                   4820: 		             : "$version:resource");
1.467     albertel 4821: 	$studentTable.=&Apache::loncommon::start_data_table_row().
                   4822: 	    '<td>'.$timestamp.'</td>';
1.224     albertel 4823: 	if ($isCODE) {
                   4824: 	    $studentTable.='<td>'.$record->{$version.':resource.CODE'}.'</td>';
                   4825: 	}
1.671     raeburn  4826:         if ($isTask) {
                   4827:             $studentTable.='<td>'.$interaction.'</td>';
                   4828:         }
1.119     ng       4829: 	my @versionKeys = split(/\:/,$$record{$version.':keys'});
                   4830: 	my @displaySub = ();
                   4831: 	foreach my $partid (@{$parts}) {
1.640     raeburn  4832:             my ($hidden,$type);
                   4833:             $type = $$record{$version.':resource.'.$partid.'.type'};
                   4834:             if (($type eq 'anonsurvey') || ($type eq 'anonsurveycred')) {
1.596     raeburn  4835:                 $hidden = 1;
                   4836:             }
1.335     albertel 4837: 	    my @matchKey = ($isTask ? sort(grep /^resource\.\d+\.\Q$partid\E\.award$/,@versionKeys)
                   4838: 			            : sort(grep /^resource\.\Q$partid\E\..*?\.submission$/,@versionKeys));
                   4839: 	    
1.122     ng       4840: #	    next if ($$record{"$version:resource.$partid.solved"} eq '');
1.324     albertel 4841: 	    my $display_part=&get_display_part($partid,$symb);
1.147     albertel 4842: 	    foreach my $matchKey (@matchKey) {
1.198     albertel 4843: 		if (exists($$record{$version.':'.$matchKey}) &&
                   4844: 		    $$record{$version.':'.$matchKey} ne '') {
1.596     raeburn  4845:                     
1.335     albertel 4846: 		    my ($responseId)= ($isTask ? ($matchKey=~ /^resource\.(.*?)\.\Q$partid\E\.award$/)
                   4847: 				               : ($matchKey=~ /^resource\.\Q$partid\E\.(.*?)\.submission$/));
1.670     raeburn  4848:                     $displaySub[0].='<span class="LC_nobreak">';
1.577     bisitz   4849:                     $displaySub[0].='<b>'.&mt('Part: [_1]',$display_part).'</b>'
                   4850:                                    .' <span class="LC_internal_info">'
1.625     www      4851:                                    .'('.&mt('Response ID: [_1]',$responseId).')'
1.577     bisitz   4852:                                    .'</span>'
                   4853:                                    .' <b>';
1.596     raeburn  4854:                     if ($hidden) {
                   4855:                         $displaySub[0].= &mt('Anonymous Survey').'</b>';
                   4856:                     } else {
1.640     raeburn  4857:                         my ($trial,$rndseed,$newvariation);
                   4858:                         if ($type eq 'randomizetry') {
                   4859:                             $trial = $$record{"$where.$partid.tries"};
1.733     raeburn  4860:                             $rndseed = $$record{"$where.$partid.rndseed"};
1.640     raeburn  4861:                         }
1.596     raeburn  4862: 		        if ($$record{"$where.$partid.tries"} eq '') {
                   4863: 			    $displaySub[0].=&mt('Trial not counted');
                   4864: 		        } else {
                   4865: 			    $displaySub[0].=&mt('Trial: [_1]',
1.467     albertel 4866: 					    $$record{"$where.$partid.tries"});
1.734     raeburn  4867:                             if (($rndseed ne '') && ($lastrndseed{$partid} ne '')) {
1.735   ! raeburn  4868:                                 if (($rndseed ne $lastrndseed{$partid}) &&
        !          4869:                                     (($type eq 'randomizetry') || ($lasttype{$partid} eq 'randomizetry'))) {
1.640     raeburn  4870:                                     $newvariation = '&nbsp;('.&mt('New variation this try').')';
                   4871:                                 }
                   4872:                             }
                   4873:                             $lastrndseed{$partid} = $rndseed;
1.735   ! raeburn  4874:                             $lasttype{$partid} = $type;
1.596     raeburn  4875: 		        }
                   4876: 		        my $responseType=($isTask ? 'Task'
1.335     albertel 4877:                                               : $responseType->{$partid}->{$responseId});
1.596     raeburn  4878: 		        if (!exists($orders{$partid})) { $orders{$partid}={}; }
1.640     raeburn  4879: 		        if ((!exists($orders{$partid}->{$responseId})) || ($trial)) {
1.596     raeburn  4880: 			    $orders{$partid}->{$responseId}=
                   4881: 			        &get_order($partid,$responseId,$symb,$uname,$udom,
1.640     raeburn  4882:                                            $no_increment,$type,$trial,$rndseed);
1.596     raeburn  4883: 		        }
1.640     raeburn  4884: 		        $displaySub[0].='</b>'.$newvariation.'</span>'; # /nobreak
1.596     raeburn  4885: 		        $displaySub[0].='&nbsp; '.
1.640     raeburn  4886: 			    &cleanRecord($$record{$version.':'.$matchKey},$responseType,$symb,$partid,$responseId,$record,$orders{$partid}->{$responseId},"$version:",$uname,$udom,$type,$trial,$rndseed).'<br />';
1.596     raeburn  4887:                     }
1.147     albertel 4888: 		}
                   4889: 	    }
1.335     albertel 4890: 	    if (exists($$record{"$where.$partid.checkedin"})) {
1.485     albertel 4891: 		$displaySub[1].=&mt('Checked in by [_1] into slot [_2]',
                   4892: 				    $$record{"$where.$partid.checkedin"},
                   4893: 				    $$record{"$where.$partid.checkedin.slot"}).
                   4894: 					'<br />';
1.335     albertel 4895: 	    }
                   4896: 	    if (exists $$record{"$where.$partid.award"}) {
1.485     albertel 4897: 		$displaySub[1].='<b>'.&mt('Part:').'</b>&nbsp;'.$display_part.' &nbsp;'.
1.335     albertel 4898: 		    lc($$record{"$where.$partid.award"}).' '.
                   4899: 		    $mark{$$record{"$where.$partid.solved"}}.
1.147     albertel 4900: 		    '<br />';
                   4901: 	    }
1.335     albertel 4902: 	    if (exists $$record{"$where.$partid.regrader"}) {
                   4903: 		$displaySub[2].=$$record{"$where.$partid.regrader"}.
                   4904: 		    ' (<b>'.&mt('Part').':</b> '.$display_part.')';
                   4905: 	    } elsif ($$record{"$version:resource.$partid.regrader"} =~ /\S/) {
                   4906: 		$displaySub[2].=
                   4907: 		    $$record{"$version:resource.$partid.regrader"}.
1.207     albertel 4908: 		    ' (<b>'.&mt('Part').':</b> '.$display_part.')';
1.147     albertel 4909: 	    }
                   4910: 	}
                   4911: 	# needed because old essay regrader has not parts info
                   4912: 	if (exists $$record{"$version:resource.regrader"}) {
                   4913: 	    $displaySub[2].=$$record{"$version:resource.regrader"};
                   4914: 	}
                   4915: 	$studentTable.='<td>'.$displaySub[0].'&nbsp;</td><td>'.$displaySub[1];
                   4916: 	if ($displaySub[2]) {
1.467     albertel 4917: 	    $studentTable.=&mt('Manually graded by [_1]',$displaySub[2]);
1.147     albertel 4918: 	}
1.467     albertel 4919: 	$studentTable.='&nbsp;</td>'.
                   4920: 	    &Apache::loncommon::end_data_table_row();
1.119     ng       4921:     }
1.467     albertel 4922:     $studentTable.=&Apache::loncommon::end_data_table();
1.119     ng       4923:     return $studentTable;
1.71      ng       4924: }
                   4925: 
                   4926: sub updateGradeByPage {
1.608     www      4927:     my ($request,$symb) = @_;
1.71      ng       4928: 
1.257     albertel 4929:     my $cdom      = $env{"course.$env{'request.course.id'}.domain"};
                   4930:     my $cnum      = $env{"course.$env{'request.course.id'}.num"};
                   4931:     my $getsec    = $env{'form.section'} eq '' ? 'all' : $env{'form.section'};
                   4932:     my $pageTitle = $env{'form.page'};
1.103     albertel 4933:     my ($classlist,undef,$fullname) = &getclasslist($getsec,'1');
1.257     albertel 4934:     my ($uname,$udom) = split(/:/,$env{'form.student'});
                   4935:     my $usec=$classlist->{$env{'form.student'}}[5];
1.103     albertel 4936:     if (!&canmodify($usec)) {
1.526     raeburn  4937: 	$request->print('<span class="LC_warning">'.&mt('Unable to modify requested student ([_1])',$env{'form.student'}).'</span>');
1.103     albertel 4938: 	return;
                   4939:     }
1.398     albertel 4940:     my $result='<h3><span class="LC_info">&nbsp;'.$env{'form.title'}.'</span></h3>';
1.526     raeburn  4941:     $result.='<h3>&nbsp;'.&mt('Student: ').&nameUserString(undef,$env{'form.fullname'},$uname,$udom).
1.129     ng       4942: 	'</h3>'."\n";
1.70      ng       4943: 
1.68      ng       4944:     $request->print($result);
                   4945: 
1.582     raeburn  4946: 
1.132     bowersj2 4947:     my $navmap = Apache::lonnavmaps::navmap->new();
1.582     raeburn  4948:     unless (ref($navmap)) {
                   4949:         $request->print(&navmap_errormsg());
                   4950:         return;
                   4951:     }
1.257     albertel 4952:     my ($mapUrl, $id, $resUrl) = &Apache::lonnet::decode_symb( $env{'form.page'});
1.71      ng       4953:     my $map = $navmap->getResourceByUrl($resUrl); # add to navmaps
1.288     albertel 4954:     if (!$map) {
1.527     raeburn  4955: 	$request->print('<span class="LC_warning">'.&mt('Unable to grade requested sequence ([_1]).',$resUrl).'</span>');
1.288     albertel 4956: 	return; 
                   4957:     }
1.71      ng       4958:     my $iterator = $navmap->getIterator($map->map_start(),
                   4959: 					$map->map_finish());
1.70      ng       4960: 
1.484     albertel 4961:     my $studentTable=
                   4962: 	&Apache::loncommon::start_data_table().
                   4963: 	&Apache::loncommon::start_data_table_header_row().
1.485     albertel 4964: 	'<th align="center">&nbsp;'.&mt('Prob.').'&nbsp;</th>'.
                   4965: 	'<th>&nbsp;'.&mt('Title').'&nbsp;</th>'.
                   4966: 	'<th>&nbsp;'.&mt('Previous Score').'&nbsp;</th>'.
                   4967: 	'<th>&nbsp;'.&mt('New Score').'&nbsp;</th>'.
1.484     albertel 4968: 	&Apache::loncommon::end_data_table_header_row();
1.71      ng       4969: 
                   4970:     $iterator->next(); # skip the first BEGIN_MAP
                   4971:     my $curRes = $iterator->next(); # for "current resource"
1.726     raeburn  4972:     my ($depth,$question,$prob,$changeflag,$hideflag)= (1,1,1,0,0);
1.101     albertel 4973:     while ($depth > 0) {
1.71      ng       4974:         if($curRes == $iterator->BEGIN_MAP) { $depth++; }
1.100     bowersj2 4975:         if($curRes == $iterator->END_MAP) { $depth--; }
1.71      ng       4976: 
1.385     albertel 4977:         if (ref($curRes) && $curRes->is_problem()) {
1.91      albertel 4978: 	    my $parts = $curRes->parts();
1.71      ng       4979:             my $title = $curRes->compTitle();
                   4980: 	    my $symbx = $curRes->symb();
1.484     albertel 4981: 	    $studentTable.=
                   4982: 		&Apache::loncommon::start_data_table_row().
                   4983: 		'<td align="center" valign="top" >'.$prob.
1.485     albertel 4984: 		(scalar(@{$parts}) == 1 ? '' 
1.640     raeburn  4985:                                         : '<br />('.&mt('[quant,_1,part]',scalar(@{$parts}))
1.526     raeburn  4986: 		.')').'</td>';
1.71      ng       4987: 	    $studentTable.='<td valign="top">&nbsp;<b>'.$title.'</b>&nbsp;</td>';
                   4988: 
                   4989: 	    my %newrecord=();
                   4990: 	    my @displayPts=();
1.269     raeburn  4991:             my %aggregate = ();
                   4992:             my $aggregateflag = 0;
1.726     raeburn  4993:             if ($env{'form.HIDE'.$prob}) {
                   4994:                 my %record = &Apache::lonnet::restore($symbx,$env{'request.course.id'},$udom,$uname);
1.727     raeburn  4995:                 my ($version,$parts) = split(/:/,$env{'form.HIDE'.$prob},2);
1.728     raeburn  4996:                 my $numchgs = &makehidden($version,$parts,\%record,$symbx,$udom,$uname,1);
1.726     raeburn  4997:                 $hideflag += $numchgs;
                   4998:             }
1.71      ng       4999: 	    foreach my $partid (@{$parts}) {
1.257     albertel 5000: 		my $newpts = $env{'form.GD_BOX'.$question.'_'.$partid};
                   5001: 		my $oldpts = $env{'form.oldpts'.$question.'_'.$partid};
1.71      ng       5002: 
1.257     albertel 5003: 		my $wgt = $env{'form.WGT'.$question.'_'.$partid} != 0 ? 
                   5004: 		    $env{'form.WGT'.$question.'_'.$partid} : 1;
1.71      ng       5005: 		my $partial = $newpts/$wgt;
                   5006: 		my $score;
                   5007: 		if ($partial > 0) {
                   5008: 		    $score = 'correct_by_override';
1.125     ng       5009: 		} elsif ($newpts ne '') { #empty is taken as 0
1.71      ng       5010: 		    $score = 'incorrect_by_override';
                   5011: 		}
1.257     albertel 5012: 		my $dropMenu = $env{'form.GD_SEL'.$question.'_'.$partid};
1.125     ng       5013: 		if ($dropMenu eq 'excused') {
1.71      ng       5014: 		    $partial = '';
                   5015: 		    $score = 'excused';
1.125     ng       5016: 		} elsif ($dropMenu eq 'reset status'
1.257     albertel 5017: 			 && $env{'form.solved'.$question.'_'.$partid} ne '') { #update only if previous record exists
1.125     ng       5018: 		    $newrecord{'resource.'.$partid.'.tries'} = 0;
                   5019: 		    $newrecord{'resource.'.$partid.'.solved'} = '';
                   5020: 		    $newrecord{'resource.'.$partid.'.award'} = '';
                   5021: 		    $newrecord{'resource.'.$partid.'.awarded'} = 0;
1.257     albertel 5022: 		    $newrecord{'resource.'.$partid.'.regrader'} = "$env{'user.name'}:$env{'user.domain'}";
1.125     ng       5023: 		    $changeflag++;
                   5024: 		    $newpts = '';
1.269     raeburn  5025:                     
                   5026:                     my $aggtries =  $env{'form.aggtries'.$question.'_'.$partid};
                   5027:                     my $totaltries = $env{'form.totaltries'.$question.'_'.$partid};
                   5028:                     my $solvedstatus = $env{'form.solved'.$question.'_'.$partid};
                   5029:                     if ($aggtries > 0) {
                   5030:                         &decrement_aggs($symbx,$partid,\%aggregate,$aggtries,$totaltries,$solvedstatus);
                   5031:                         $aggregateflag = 1;
                   5032:                     }
1.71      ng       5033: 		}
1.324     albertel 5034: 		my $display_part=&get_display_part($partid,$curRes->symb());
1.257     albertel 5035: 		my $oldstatus = $env{'form.solved'.$question.'_'.$partid};
1.526     raeburn  5036: 		$displayPts[0].='&nbsp;<b>'.&mt('Part').':</b> '.$display_part.' = '.
1.71      ng       5037: 		    (($oldstatus eq 'excused') ? 'excused' : $oldpts).
1.326     albertel 5038: 		    '&nbsp;<br />';
1.526     raeburn  5039: 		$displayPts[1].='&nbsp;<b>'.&mt('Part').':</b> '.$display_part.' = '.
1.125     ng       5040: 		     (($score eq 'excused') ? 'excused' : $newpts).
1.326     albertel 5041: 		    '&nbsp;<br />';
1.71      ng       5042: 		$question++;
1.380     albertel 5043: 		next if ($dropMenu eq 'reset status' || ($newpts eq $oldpts && $score ne 'excused'));
1.125     ng       5044: 
1.71      ng       5045: 		$newrecord{'resource.'.$partid.'.awarded'}  = $partial if $partial ne '';
1.125     ng       5046: 		$newrecord{'resource.'.$partid.'.solved'}   = $score if $score ne '';
1.257     albertel 5047: 		$newrecord{'resource.'.$partid.'.regrader'} = "$env{'user.name'}:$env{'user.domain'}"
1.125     ng       5048: 		    if (scalar(keys(%newrecord)) > 0);
1.71      ng       5049: 
                   5050: 		$changeflag++;
                   5051: 	    }
                   5052: 	    if (scalar(keys(%newrecord)) > 0) {
1.382     albertel 5053: 		my %record = 
                   5054: 		    &Apache::lonnet::restore($symbx,$env{'request.course.id'},
                   5055: 					     $udom,$uname);
                   5056: 
                   5057: 		if (&Apache::lonnet::validCODE($env{'form.CODE'})) {
                   5058: 		    $newrecord{'resource.CODE'} = $env{'form.CODE'};
                   5059: 		} elsif (&Apache::lonnet::validCODE($record{'resource.CODE'})) {
                   5060: 		    $newrecord{'resource.CODE'} = '';
                   5061: 		}
1.257     albertel 5062: 		&Apache::lonnet::cstore(\%newrecord,$symbx,$env{'request.course.id'},
1.71      ng       5063: 					$udom,$uname);
1.382     albertel 5064: 		%record = &Apache::lonnet::restore($symbx,
                   5065: 						   $env{'request.course.id'},
                   5066: 						   $udom,$uname);
1.380     albertel 5067: 		&check_and_remove_from_queue($parts,\%record,undef,$symbx,
                   5068: 					     $cdom,$cnum,$udom,$uname);
1.71      ng       5069: 	    }
1.380     albertel 5070: 	    
1.269     raeburn  5071:             if ($aggregateflag) {
                   5072:                 &Apache::lonnet::cinc('nohist_resourcetracker',\%aggregate,
                   5073:                       $env{'course.'.$env{'request.course.id'}.'.domain'},
                   5074:                       $env{'course.'.$env{'request.course.id'}.'.num'});
                   5075:             }
1.125     ng       5076: 
1.71      ng       5077: 	    $studentTable.='<td valign="top">'.$displayPts[0].'</td>'.
                   5078: 		'<td valign="top">'.$displayPts[1].'</td>'.
1.484     albertel 5079: 		&Apache::loncommon::end_data_table_row();
1.68      ng       5080: 
1.196     albertel 5081: 	    $prob++;
1.68      ng       5082: 	}
1.71      ng       5083:         $curRes = $iterator->next();
1.68      ng       5084:     }
1.98      albertel 5085: 
1.484     albertel 5086:     $studentTable.=&Apache::loncommon::end_data_table();
1.526     raeburn  5087:     my $grademsg=($changeflag == 0 ? &mt('No score was changed or updated.') :
                   5088: 		  &mt('The scores were changed for [quant,_1,problem].',
1.726     raeburn  5089: 		  $changeflag).'<br />');
                   5090:     my $hidemsg=($hideflag == 0 ? '' :
                   5091:                  &mt('Submissions were marked "hidden" for [quant,_1,transaction].',
                   5092:                      $hideflag).'<br />');
                   5093:     $request->print($hidemsg.$grademsg.$studentTable);
1.68      ng       5094: 
1.70      ng       5095:     return '';
                   5096: }
                   5097: 
1.72      ng       5098: #-------- end of section for handling grading by page/sequence ---------
                   5099: #
                   5100: #-------------------------------------------------------------------
                   5101: 
1.581     www      5102: #-------------------- Bubblesheet (Scantron) Grading -------------------
1.75      albertel 5103: #
                   5104: #------ start of section for handling grading by page/sequence ---------
                   5105: 
1.423     albertel 5106: =pod
                   5107: 
                   5108: =head1 Bubble sheet grading routines
                   5109: 
1.424     albertel 5110:   For this documentation:
                   5111: 
                   5112:    'scanline' refers to the full line of characters
                   5113:    from the file that we are parsing that represents one entire sheet
                   5114: 
                   5115:    'bubble line' refers to the data
1.659     raeburn  5116:    representing the line of bubbles that are on the physical bubblesheet
1.424     albertel 5117: 
                   5118: 
1.659     raeburn  5119: The overall process is that a scanned in bubblesheet data is uploaded
1.424     albertel 5120: into a course. When a user wants to grade, they select a
1.659     raeburn  5121: sequence/folder of resources, a file of bubblesheet info, and pick
1.424     albertel 5122: one of the predefined configurations for what each scanline looks
                   5123: like.
                   5124: 
                   5125: Next each scanline is checked for any errors of either 'missing
1.435     foxr     5126: bubbles' (it's an error because it may have been mis-scanned
1.424     albertel 5127: because too light bubbling), 'double bubble' (each bubble line should
1.703     bisitz   5128: have no more than one letter picked), invalid or duplicated CODE,
1.556     weissno  5129: invalid student/employee ID
1.424     albertel 5130: 
                   5131: If the CODE option is used that determines the randomization of the
1.556     weissno  5132: homework problems, either way the student/employee ID is looked up into a
1.424     albertel 5133: username:domain.
                   5134: 
                   5135: During the validation phase the instructor can choose to skip scanlines. 
                   5136: 
1.659     raeburn  5137: After the validation phase, there are now 3 bubblesheet files
1.424     albertel 5138: 
                   5139:   scantron_original_filename (unmodified original file)
                   5140:   scantron_corrected_filename (file where the corrected information has replaced the original information)
                   5141:   scantron_skipped_filename (contains the exact text of scanlines that where skipped)
                   5142: 
                   5143: Also there is a separate hash nohist_scantrondata that contains extra
1.659     raeburn  5144: correction information that isn't representable in the bubblesheet
1.424     albertel 5145: file (see &scantron_getfile() for more information)
                   5146: 
                   5147: After all scanlines are either valid, marked as valid or skipped, then
                   5148: foreach line foreach problem in the picked sequence, an ssi request is
                   5149: made that simulates a user submitting their selected letter(s) against
                   5150: the homework problem.
1.423     albertel 5151: 
                   5152: =over 4
                   5153: 
                   5154: 
                   5155: 
                   5156: =item defaultFormData
                   5157: 
                   5158:   Returns html hidden inputs used to hold context/default values.
                   5159: 
                   5160:  Arguments:
                   5161:   $symb - $symb of the current resource 
                   5162: 
                   5163: =cut
1.422     foxr     5164: 
1.81      albertel 5165: sub defaultFormData {
1.324     albertel 5166:     my ($symb)=@_;
1.613     www      5167:     return '<input type="hidden" name="symb"    value="'.&Apache::lonenc::check_encrypt($symb).'" />';
1.81      albertel 5168: }
                   5169: 
1.447     foxr     5170: 
1.423     albertel 5171: =pod 
                   5172: 
                   5173: =item getSequenceDropDown
                   5174: 
                   5175:    Return html dropdown of possible sequences to grade
                   5176:  
                   5177:  Arguments:
1.582     raeburn  5178:    $symb - $symb of the current resource
                   5179:    $map_error - ref to scalar which will container error if
                   5180:                 $navmap object is unavailable in &getSymbMap().
1.423     albertel 5181: 
                   5182: =cut
1.422     foxr     5183: 
1.75      albertel 5184: sub getSequenceDropDown {
1.582     raeburn  5185:     my ($symb,$map_error)=@_;
1.75      albertel 5186:     my $result='<select name="selectpage">'."\n";
1.582     raeburn  5187:     my ($titles,$symbx) = &getSymbMap($map_error);
                   5188:     if (ref($map_error)) {
                   5189:         return if ($$map_error);
                   5190:     }
1.137     albertel 5191:     my ($curpage)=&Apache::lonnet::decode_symb($symb); 
1.75      albertel 5192:     my $ctr=0;
                   5193:     foreach (@$titles) {
                   5194: 	my ($minder,$showtitle) = ($_ =~ /(\d+)\.(.*)/);
                   5195: 	$result.='<option value="'.$$symbx{$_}.'" '.
1.401     albertel 5196: 	    ($$symbx{$_} =~ /$curpage$/ ? 'selected="selected"' : '').
1.75      albertel 5197: 	    '>'.$showtitle.'</option>'."\n";
                   5198: 	$ctr++;
                   5199:     }
                   5200:     $result.= '</select>';
                   5201:     return $result;
                   5202: }
                   5203: 
1.495     albertel 5204: my %bubble_lines_per_response;     # no. bubble lines for each response.
1.554     raeburn  5205:                                    # key is zero-based index - 0, 1, 2 ...
1.495     albertel 5206: 
                   5207: my %first_bubble_line;             # First bubble line no. for each bubble.
                   5208: 
1.509     raeburn  5209: my %subdivided_bubble_lines;       # no. bubble lines for optionresponse, 
                   5210:                                    # matchresponse or rankresponse, where 
                   5211:                                    # an individual response can have multiple 
                   5212:                                    # lines
1.503     raeburn  5213: 
                   5214: my %responsetype_per_response;     # responsetype for each response
                   5215: 
1.691     raeburn  5216: my %masterseq_id_responsenum;      # src_id (e.g., 12.3_0.11 etc.) for each
                   5217:                                    # numbered response. Needed when randomorder
                   5218:                                    # or randompick are in use. Key is ID, value 
                   5219:                                    # is response number.
                   5220: 
1.495     albertel 5221: # Save and restore the bubble lines array to the form env.
                   5222: 
                   5223: 
                   5224: sub save_bubble_lines {
                   5225:     foreach my $line (keys(%bubble_lines_per_response)) {
                   5226: 	$env{"form.scantron.bubblelines.$line"}  = $bubble_lines_per_response{$line};
                   5227: 	$env{"form.scantron.first_bubble_line.$line"} =
                   5228: 	    $first_bubble_line{$line};
1.503     raeburn  5229:         $env{"form.scantron.sub_bubblelines.$line"} = 
                   5230:             $subdivided_bubble_lines{$line};
                   5231:         $env{"form.scantron.responsetype.$line"} =
                   5232:             $responsetype_per_response{$line};
1.495     albertel 5233:     }
1.691     raeburn  5234:     foreach my $resid (keys(%masterseq_id_responsenum)) {
                   5235:         my $line = $masterseq_id_responsenum{$resid};
                   5236:         $env{"form.scantron.residpart.$line"} = $resid;
                   5237:     }
1.495     albertel 5238: }
                   5239: 
                   5240: 
                   5241: sub restore_bubble_lines {
                   5242:     my $line = 0;
                   5243:     %bubble_lines_per_response = ();
1.691     raeburn  5244:     %masterseq_id_responsenum = ();
1.495     albertel 5245:     while ($env{"form.scantron.bubblelines.$line"}) {
                   5246: 	my $value = $env{"form.scantron.bubblelines.$line"};
                   5247: 	$bubble_lines_per_response{$line} = $value;
                   5248: 	$first_bubble_line{$line}  =
                   5249: 	    $env{"form.scantron.first_bubble_line.$line"};
1.503     raeburn  5250:         $subdivided_bubble_lines{$line} =
                   5251:             $env{"form.scantron.sub_bubblelines.$line"};
                   5252:         $responsetype_per_response{$line} =
                   5253:             $env{"form.scantron.responsetype.$line"};
1.691     raeburn  5254:         my $id = $env{"form.scantron.residpart.$line"};
                   5255:         $masterseq_id_responsenum{$id} = $line;
1.495     albertel 5256: 	$line++;
                   5257:     }
                   5258: }
                   5259: 
1.423     albertel 5260: =pod 
                   5261: 
                   5262: =item scantron_filenames
                   5263: 
                   5264:    Returns a list of the scantron files in the current course 
                   5265: 
                   5266: =cut
1.422     foxr     5267: 
1.202     albertel 5268: sub scantron_filenames {
1.257     albertel 5269:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
                   5270:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
1.517     raeburn  5271:     my $getpropath = 1;
1.662     raeburn  5272:     my ($dirlist,$listerror) = &Apache::lonnet::dirlist('userfiles',$cdom,
                   5273:                                                         $cname,$getpropath);
1.202     albertel 5274:     my @possiblenames;
1.662     raeburn  5275:     if (ref($dirlist) eq 'ARRAY') {
                   5276:         foreach my $filename (sort(@{$dirlist})) {
                   5277: 	    ($filename)=split(/&/,$filename);
                   5278: 	    if ($filename!~/^scantron_orig_/) { next ; }
                   5279: 	    $filename=~s/^scantron_orig_//;
                   5280: 	    push(@possiblenames,$filename);
                   5281:         }
1.202     albertel 5282:     }
                   5283:     return @possiblenames;
                   5284: }
                   5285: 
1.423     albertel 5286: =pod 
                   5287: 
                   5288: =item scantron_uploads
                   5289: 
                   5290:    Returns  html drop-down list of scantron files in current course.
                   5291: 
                   5292:  Arguments:
                   5293:    $file2grade - filename to set as selected in the dropdown
                   5294: 
                   5295: =cut
1.422     foxr     5296: 
1.202     albertel 5297: sub scantron_uploads {
1.209     ng       5298:     my ($file2grade) = @_;
1.202     albertel 5299:     my $result=	'<select name="scantron_selectfile">';
                   5300:     $result.="<option></option>";
                   5301:     foreach my $filename (sort(&scantron_filenames())) {
1.401     albertel 5302: 	$result.="<option".($filename eq $file2grade ? ' selected="selected"':'').">$filename</option>\n";
1.81      albertel 5303:     }
                   5304:     $result.="</select>";
                   5305:     return $result;
                   5306: }
                   5307: 
1.423     albertel 5308: =pod 
                   5309: 
                   5310: =item scantron_scantab
                   5311: 
                   5312:   Returns html drop down of the scantron formats in the scantronformat.tab
                   5313:   file.
                   5314: 
                   5315: =cut
1.422     foxr     5316: 
1.82      albertel 5317: sub scantron_scantab {
                   5318:     my $result='<select name="scantron_format">'."\n";
1.191     albertel 5319:     $result.='<option></option>'."\n";
1.518     raeburn  5320:     my @lines = &get_scantronformat_file();
                   5321:     if (@lines > 0) {
                   5322:         foreach my $line (@lines) {
                   5323:             next if (($line =~ /^\#/) || ($line eq ''));
                   5324: 	    my ($name,$descrip)=split(/:/,$line);
                   5325: 	    $result.='<option value="'.$name.'">'.$descrip.'</option>'."\n";
                   5326:         }
1.82      albertel 5327:     }
                   5328:     $result.='</select>'."\n";
1.518     raeburn  5329:     return $result;
                   5330: }
                   5331: 
                   5332: =pod
                   5333: 
                   5334: =item get_scantronformat_file
                   5335: 
                   5336:   Returns an array containing lines from the scantron format file for
                   5337:   the domain of the course.
                   5338: 
                   5339:   If a url for a custom.tab file is listed in domain's configuration.db, 
                   5340:   lines are from this file.
                   5341: 
                   5342:   Otherwise, if a default.tab has been published in RES space by the 
                   5343:   domainconfig user, lines are from this file.
                   5344: 
                   5345:   Otherwise, fall back to getting lines from the legacy file on the
1.519     raeburn  5346:   local server:  /home/httpd/lonTabs/default_scantronformat.tab    
1.82      albertel 5347: 
1.518     raeburn  5348: =cut
                   5349: 
                   5350: sub get_scantronformat_file {
                   5351:     my $cdom= $env{'course.'.$env{'request.course.id'}.'.domain'};
                   5352:     my %domconfig = &Apache::lonnet::get_dom('configuration',['scantron'],$cdom);
                   5353:     my $gottab = 0;
                   5354:     my @lines;
                   5355:     if (ref($domconfig{'scantron'}) eq 'HASH') {
                   5356:         if ($domconfig{'scantron'}{'scantronformat'} ne '') {
                   5357:             my $formatfile = &Apache::lonnet::getfile($Apache::lonnet::perlvar{'lonDocRoot'}.$domconfig{'scantron'}{'scantronformat'});
                   5358:             if ($formatfile ne '-1') {
                   5359:                 @lines = split("\n",$formatfile,-1);
                   5360:                 $gottab = 1;
                   5361:             }
                   5362:         }
                   5363:     }
                   5364:     if (!$gottab) {
                   5365:         my $confname = $cdom.'-domainconfig';
                   5366:         my $default = $Apache::lonnet::perlvar{'lonDocRoot'}.'/res/'.$cdom.'/'.$confname.'/default.tab';
                   5367:         my $formatfile =  &Apache::lonnet::getfile($default);
                   5368:         if ($formatfile ne '-1') {
                   5369:             @lines = split("\n",$formatfile,-1);
                   5370:             $gottab = 1;
                   5371:         }
                   5372:     }
                   5373:     if (!$gottab) {
1.519     raeburn  5374:         my @domains = &Apache::lonnet::current_machine_domains();
                   5375:         if (grep(/^\Q$cdom\E$/,@domains)) {
                   5376:             my $fh=Apache::File->new($Apache::lonnet::perlvar{'lonTabDir'}.'/scantronformat.tab');
                   5377:             @lines = <$fh>;
                   5378:             close($fh);
                   5379:         } else {
                   5380:             my $fh=Apache::File->new($Apache::lonnet::perlvar{'lonTabDir'}.'/default_scantronformat.tab');
                   5381:             @lines = <$fh>;
                   5382:             close($fh);
                   5383:         }
1.518     raeburn  5384:     }
                   5385:     return @lines;
1.82      albertel 5386: }
                   5387: 
1.423     albertel 5388: =pod 
                   5389: 
                   5390: =item scantron_CODElist
                   5391: 
                   5392:   Returns html drop down of the saved CODE lists from current course,
                   5393:   generated from earlier printings.
                   5394: 
                   5395: =cut
1.422     foxr     5396: 
1.186     albertel 5397: sub scantron_CODElist {
1.257     albertel 5398:     my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   5399:     my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
1.186     albertel 5400:     my @names=&Apache::lonnet::getkeys('CODEs',$cdom,$cnum);
                   5401:     my $namechoice='<option></option>';
1.225     albertel 5402:     foreach my $name (sort {uc($a) cmp uc($b)} @names) {
1.191     albertel 5403: 	if ($name =~ /^error: 2 /) { next; }
1.278     albertel 5404: 	if ($name =~ /^type\0/) { next; }
1.186     albertel 5405: 	$namechoice.='<option value="'.$name.'">'.$name.'</option>';
                   5406:     }
                   5407:     $namechoice='<select name="scantron_CODElist">'.$namechoice.'</select>';
                   5408:     return $namechoice;
                   5409: }
                   5410: 
1.423     albertel 5411: =pod 
                   5412: 
                   5413: =item scantron_CODEunique
                   5414: 
                   5415:   Returns the html for "Each CODE to be used once" radio.
                   5416: 
                   5417: =cut
1.422     foxr     5418: 
1.186     albertel 5419: sub scantron_CODEunique {
1.532     bisitz   5420:     my $result='<span class="LC_nobreak">
1.272     albertel 5421:                  <label><input type="radio" name="scantron_CODEunique"
1.423     albertel 5422:                         value="yes" checked="checked" />'.&mt('Yes').' </label>
1.381     albertel 5423:                 </span>
1.532     bisitz   5424:                 <span class="LC_nobreak">
1.272     albertel 5425:                  <label><input type="radio" name="scantron_CODEunique"
1.423     albertel 5426:                         value="no" />'.&mt('No').' </label>
1.381     albertel 5427:                 </span>';
1.186     albertel 5428:     return $result;
                   5429: }
1.423     albertel 5430: 
                   5431: =pod 
                   5432: 
                   5433: =item scantron_selectphase
                   5434: 
1.659     raeburn  5435:   Generates the initial screen to start the bubblesheet process.
1.423     albertel 5436:   Allows for - starting a grading run.
1.424     albertel 5437:              - downloading existing scan data (original, corrected
1.423     albertel 5438:                                                 or skipped info)
                   5439: 
                   5440:              - uploading new scan data
                   5441: 
                   5442:  Arguments:
                   5443:   $r          - The Apache request object
                   5444:   $file2grade - name of the file that contain the scanned data to score
                   5445: 
                   5446: =cut
1.186     albertel 5447: 
1.75      albertel 5448: sub scantron_selectphase {
1.608     www      5449:     my ($r,$file2grade,$symb) = @_;
1.75      albertel 5450:     if (!$symb) {return '';}
1.582     raeburn  5451:     my $map_error;
                   5452:     my $sequence_selector=&getSequenceDropDown($symb,\$map_error);
                   5453:     if ($map_error) {
                   5454:         $r->print('<br />'.&navmap_errormsg().'<br />');
                   5455:         return;
                   5456:     }
1.324     albertel 5457:     my $default_form_data=&defaultFormData($symb);
1.209     ng       5458:     my $file_selector=&scantron_uploads($file2grade);
1.82      albertel 5459:     my $format_selector=&scantron_scantab();
1.186     albertel 5460:     my $CODE_selector=&scantron_CODElist();
                   5461:     my $CODE_unique=&scantron_CODEunique();
1.75      albertel 5462:     my $result;
1.422     foxr     5463: 
1.513     foxr     5464:     $ssi_error = 0;
                   5465: 
1.606     wenzelju 5466:     if (&Apache::lonnet::allowed('usc',$env{'request.role.domain'}) ||
                   5467:         &Apache::lonnet::allowed('usc',$env{'request.course.id'})) {
                   5468: 
                   5469: 	# Chunk of form to prompt for a scantron file upload.
                   5470: 
                   5471:         $r->print('
                   5472:     <br />
                   5473:     '.&Apache::loncommon::start_data_table('LC_scantron_action').'
                   5474:        '.&Apache::loncommon::start_data_table_header_row().'
                   5475:             <th>
                   5476:               &nbsp;'.&mt('Specify a bubblesheet data file to upload.').'
                   5477:             </th>
                   5478:        '.&Apache::loncommon::end_data_table_header_row().'
                   5479:        '.&Apache::loncommon::start_data_table_row().'
                   5480:             <td>
                   5481: ');
1.608     www      5482:     my $default_form_data=&defaultFormData($symb);
1.606     wenzelju 5483:     my $cdom= $env{'course.'.$env{'request.course.id'}.'.domain'};
                   5484:     my $cnum= $env{'course.'.$env{'request.course.id'}.'.num'};
                   5485:     $r->print(&Apache::lonhtmlcommon::scripttag('
                   5486:     function checkUpload(formname) {
                   5487: 	if (formname.upfile.value == "") {
                   5488: 	    alert("'.&mt('Please use the browse button to select a file from your local directory.').'");
                   5489: 	    return false;
                   5490: 	}
                   5491: 	formname.submit();
                   5492:     }'));
                   5493:     $r->print('
                   5494:               <form enctype="multipart/form-data" action="/adm/grades" name="rules" method="post">
                   5495:                 '.$default_form_data.'
                   5496:                 <input name="courseid" type="hidden" value="'.$cnum.'" />
                   5497:                 <input name="domainid" type="hidden" value="'.$cdom.'" />
                   5498:                 <input name="command" value="scantronupload_save" type="hidden" />
                   5499:                 '.&mt('File to upload: [_1]','<input type="file" name="upfile" size="50" />').'
                   5500:                 <br />
                   5501:                 <input type="button" onclick="javascript:checkUpload(this.form);" value="'.&mt('Upload Bubblesheet Data').'" />
                   5502:               </form>
                   5503: ');
                   5504: 
                   5505:         $r->print('
                   5506:             </td>
                   5507:        '.&Apache::loncommon::end_data_table_row().'
                   5508:        '.&Apache::loncommon::end_data_table().'
                   5509: ');
                   5510:     }
                   5511: 
1.422     foxr     5512:     # Chunk of form to prompt for a file to grade and how:
                   5513: 
1.489     albertel 5514:     $result.= '
                   5515:     <br />
                   5516:     <form method="post" enctype="multipart/form-data" action="/adm/grades" name="scantron_process">
                   5517:     <input type="hidden" name="command" value="scantron_warning" />
                   5518:     '.$default_form_data.'
                   5519:     '.&Apache::loncommon::start_data_table('LC_scantron_action').'
                   5520:        '.&Apache::loncommon::start_data_table_header_row().'
                   5521:             <th colspan="2">
1.492     albertel 5522:               &nbsp;'.&mt('Specify file and which Folder/Sequence to grade').'
1.489     albertel 5523:             </th>
                   5524:        '.&Apache::loncommon::end_data_table_header_row().'
                   5525:        '.&Apache::loncommon::start_data_table_row().'
1.492     albertel 5526:             <td> '.&mt('Sequence to grade:').' </td><td> '.$sequence_selector.' </td>
1.489     albertel 5527:        '.&Apache::loncommon::end_data_table_row().'
                   5528:        '.&Apache::loncommon::start_data_table_row().'
1.572     www      5529:             <td> '.&mt('Filename of bubblesheet data file:').' </td><td> '.$file_selector.' </td>
1.489     albertel 5530:        '.&Apache::loncommon::end_data_table_row().'
                   5531:        '.&Apache::loncommon::start_data_table_row().'
1.572     www      5532:             <td> '.&mt('Format of bubblesheet data file:').' </td><td> '.$format_selector.' </td>
1.489     albertel 5533:        '.&Apache::loncommon::end_data_table_row().'
                   5534:        '.&Apache::loncommon::start_data_table_row().'
1.492     albertel 5535:             <td> '.&mt('Saved CODEs to validate against:').' </td><td> '.$CODE_selector.' </td>
1.489     albertel 5536:        '.&Apache::loncommon::end_data_table_row().'
                   5537:        '.&Apache::loncommon::start_data_table_row().'
1.492     albertel 5538:             <td> '.&mt('Each CODE is only to be used once:').'</td><td> '.$CODE_unique.' </td>
1.489     albertel 5539:        '.&Apache::loncommon::end_data_table_row().'
                   5540:        '.&Apache::loncommon::start_data_table_row().'
1.492     albertel 5541: 	    <td> '.&mt('Options:').' </td>
1.187     albertel 5542:             <td>
1.492     albertel 5543: 	       <label><input type="checkbox" name="scantron_options_redo" value="redo_skipped"/> '.&mt('Do only previously skipped records').'</label> <br />
                   5544:                <label><input type="checkbox" name="scantron_options_ignore" value="ignore_corrections"/> '.&mt('Remove all existing corrections').'</label> <br />
                   5545:                <label><input type="checkbox" name="scantron_options_hidden" value="ignore_hidden"/> '.&mt('Skip hidden resources when grading').'</label>
1.187     albertel 5546: 	    </td>
1.489     albertel 5547:        '.&Apache::loncommon::end_data_table_row().'
                   5548:        '.&Apache::loncommon::start_data_table_row().'
1.174     albertel 5549:             <td colspan="2">
1.572     www      5550:               <input type="submit" value="'.&mt('Grading: Validate Bubblesheet Records').'" />
1.162     albertel 5551:             </td>
1.489     albertel 5552:        '.&Apache::loncommon::end_data_table_row().'
                   5553:     '.&Apache::loncommon::end_data_table().'
                   5554:     </form>
                   5555: ';
1.162     albertel 5556:    
                   5557:     $r->print($result);
                   5558: 
1.422     foxr     5559: 
                   5560: 
                   5561:     # Chunk of the form that prompts to view a scoring office file,
                   5562:     # corrected file, skipped records in a file.
                   5563: 
1.489     albertel 5564:     $r->print('
                   5565:    <br />
                   5566:    <form action="/adm/grades" name="scantron_download">
                   5567:      '.$default_form_data.'
                   5568:      <input type="hidden" name="command" value="scantron_download" />
                   5569:      '.&Apache::loncommon::start_data_table('LC_scantron_action').'
                   5570:        '.&Apache::loncommon::start_data_table_header_row().'
                   5571:               <th>
1.492     albertel 5572:                 &nbsp;'.&mt('Download a scoring office file').'
1.489     albertel 5573:               </th>
                   5574:        '.&Apache::loncommon::end_data_table_header_row().'
                   5575:        '.&Apache::loncommon::start_data_table_row().'
1.492     albertel 5576:               <td> '.&mt('Filename of scoring office file: [_1]',$file_selector).' 
1.489     albertel 5577:                 <br />
1.492     albertel 5578:                 <input type="submit" value="'.&mt('Download: Show List of Associated Files').'" />
1.489     albertel 5579:        '.&Apache::loncommon::end_data_table_row().'
                   5580:      '.&Apache::loncommon::end_data_table().'
                   5581:    </form>
                   5582:    <br />
                   5583: ');
1.162     albertel 5584: 
1.457     banghart 5585:     &Apache::lonpickcode::code_list($r,2);
1.523     raeburn  5586: 
1.694     bisitz   5587:     $r->print('<br /><form method="post" name="checkscantron" action="">'.
1.523     raeburn  5588:              $default_form_data."\n".
                   5589:              &Apache::loncommon::start_data_table('LC_scantron_action')."\n".
                   5590:              &Apache::loncommon::start_data_table_header_row()."\n".
                   5591:              '<th colspan="2">
1.572     www      5592:               &nbsp;'.&mt('Review bubblesheet data and submissions for a previously graded folder/sequence')."\n".
1.523     raeburn  5593:              '</th>'."\n".
                   5594:               &Apache::loncommon::end_data_table_header_row()."\n".
                   5595:               &Apache::loncommon::start_data_table_row()."\n".
                   5596:               '<td> '.&mt('Graded folder/sequence:').' </td>'."\n".
                   5597:               '<td> '.$sequence_selector.' </td>'.
                   5598:               &Apache::loncommon::end_data_table_row()."\n".
                   5599:               &Apache::loncommon::start_data_table_row()."\n".
                   5600:               '<td> '.&mt('Filename of scoring office file:').' </td>'."\n".
                   5601:               '<td> '.$file_selector.' </td>'."\n".
                   5602:               &Apache::loncommon::end_data_table_row()."\n".
                   5603:               &Apache::loncommon::start_data_table_row()."\n".
                   5604:               '<td> '.&mt('Format of data file:').' </td>'."\n".
                   5605:               '<td> '.$format_selector.' </td>'."\n".
                   5606:               &Apache::loncommon::end_data_table_row()."\n".
                   5607:               &Apache::loncommon::start_data_table_row()."\n".
1.557     raeburn  5608:               '<td> '.&mt('Options').' </td>'."\n".
                   5609:               '<td> <label><input type="checkbox" name="scantron_options_hidden" value="ignore_hidden"/> '.&mt('Skip hidden resources').'</label></td>'.
                   5610:               &Apache::loncommon::end_data_table_row()."\n".
                   5611:               &Apache::loncommon::start_data_table_row()."\n".
1.523     raeburn  5612:               '<td colspan="2">'."\n".
                   5613:               '<input type="hidden" name="command" value="checksubmissions" />'."\n".
1.575     www      5614:               '<input type="submit" value="'.&mt('Review Bubblesheet Data and Submission Records').'" />'."\n".
1.523     raeburn  5615:               '</td>'."\n".
                   5616:               &Apache::loncommon::end_data_table_row()."\n".
                   5617:               &Apache::loncommon::end_data_table()."\n".
                   5618:               '</form><br />');
                   5619:     return;
1.75      albertel 5620: }
                   5621: 
1.423     albertel 5622: =pod
                   5623: 
                   5624: =item get_scantron_config
                   5625: 
1.711     bisitz   5626:    Parse and return the bubblesheet configuration line selected as a
1.423     albertel 5627:    hash of configuration file fields.
                   5628: 
                   5629:  Arguments:
                   5630:     which - the name of the configuration to parse from the file.
                   5631: 
                   5632: 
                   5633:  Returns:
                   5634:             If the named configuration is not in the file, an empty
                   5635:             hash is returned.
                   5636:     a hash with the fields
                   5637:       name         - internal name for the this configuration setup
                   5638:       description  - text to display to operator that describes this config
                   5639:       CODElocation - if 0 or the string 'none'
                   5640:                           - no CODE exists for this config
                   5641:                      if -1 || the string 'letter'
                   5642:                           - a CODE exists for this config and is
                   5643:                             a string of letters
                   5644:                      Unsupported value (but planned for future support)
                   5645:                           if a positive integer
                   5646:                                - The CODE exists as the first n items from
                   5647:                                  the question section of the form
                   5648:                           if the string 'number'
                   5649:                                - The CODE exists for this config and is
                   5650:                                  a string of numbers
                   5651:       CODEstart   - (only matter if a CODE exists) column in the line where
                   5652:                      the CODE starts
                   5653:       CODElength  - length of the CODE
1.573     bisitz   5654:       IDstart     - column where the student/employee ID starts
1.556     weissno  5655:       IDlength    - length of the student/employee ID info
1.423     albertel 5656:       Qstart      - column where the information from the bubbled
                   5657:                     'questions' start
                   5658:       Qlength     - number of columns comprising a single bubble line from
                   5659:                     the sheet. (usually either 1 or 10)
1.424     albertel 5660:       Qon         - either a single character representing the character used
1.423     albertel 5661:                     to signal a bubble was chosen in the positional setup, or
                   5662:                     the string 'letter' if the letter of the chosen bubble is
                   5663:                     in the final, or 'number' if a number representing the
                   5664:                     chosen bubble is in the file (1->A 0->J)
1.424     albertel 5665:       Qoff        - the character used to represent that a bubble was
                   5666:                     left blank
1.423     albertel 5667:       PaperID     - if the scanning process generates a unique number for each
                   5668:                     sheet scanned the column that this ID number starts in
                   5669:       PaperIDlength - number of columns that comprise the unique ID number
                   5670:                       for the sheet of paper
1.424     albertel 5671:       FirstName   - column that the first name starts in
1.423     albertel 5672:       FirstNameLength - number of columns that the first name spans
                   5673:  
                   5674:       LastName    - column that the last name starts in
                   5675:       LastNameLength - number of columns that the last name spans
1.649     raeburn  5676:       BubblesPerRow - number of bubbles available in each row used to 
                   5677:                       bubble an answer. (If not specified, 10 assumed).
1.671     raeburn  5678: 
1.423     albertel 5679: =cut
1.422     foxr     5680: 
1.82      albertel 5681: sub get_scantron_config {
                   5682:     my ($which) = @_;
1.518     raeburn  5683:     my @lines = &get_scantronformat_file();
1.82      albertel 5684:     my %config;
1.157     albertel 5685:     #FIXME probably should move to XML it has already gotten a bit much now
1.518     raeburn  5686:     foreach my $line (@lines) {
1.82      albertel 5687: 	my ($name,$descrip)=split(/:/,$line);
                   5688: 	if ($name ne $which ) { next; }
                   5689: 	chomp($line);
                   5690: 	my @config=split(/:/,$line);
                   5691: 	$config{'name'}=$config[0];
                   5692: 	$config{'description'}=$config[1];
                   5693: 	$config{'CODElocation'}=$config[2];
                   5694: 	$config{'CODEstart'}=$config[3];
                   5695: 	$config{'CODElength'}=$config[4];
                   5696: 	$config{'IDstart'}=$config[5];
                   5697: 	$config{'IDlength'}=$config[6];
                   5698: 	$config{'Qstart'}=$config[7];
1.497     foxr     5699:  	$config{'Qlength'}=$config[8];
1.82      albertel 5700: 	$config{'Qoff'}=$config[9];
                   5701: 	$config{'Qon'}=$config[10];
1.157     albertel 5702: 	$config{'PaperID'}=$config[11];
                   5703: 	$config{'PaperIDlength'}=$config[12];
                   5704: 	$config{'FirstName'}=$config[13];
                   5705: 	$config{'FirstNamelength'}=$config[14];
                   5706: 	$config{'LastName'}=$config[15];
                   5707: 	$config{'LastNamelength'}=$config[16];
1.649     raeburn  5708:         $config{'BubblesPerRow'}=$config[17];
1.82      albertel 5709: 	last;
                   5710:     }
                   5711:     return %config;
                   5712: }
                   5713: 
1.423     albertel 5714: =pod 
                   5715: 
                   5716: =item username_to_idmap
                   5717: 
1.556     weissno  5718:     creates a hash keyed by student/employee ID with values of the corresponding
1.731     raeburn  5719:     student username:domain. If a single ID occurs for more than one student,
                   5720:     the status of the student is checked, and if Active, the value in the hash
                   5721:     will be set to the Active student.
1.423     albertel 5722: 
                   5723:   Arguments:
                   5724: 
                   5725:     $classlist - reference to the class list hash. This is a hash
                   5726:                  keyed by student name:domain  whose elements are references
1.424     albertel 5727:                  to arrays containing various chunks of information
1.423     albertel 5728:                  about the student. (See loncoursedata for more info).
                   5729: 
                   5730:   Returns
                   5731:     %idmap - the constructed hash
                   5732: 
                   5733: =cut
                   5734: 
1.82      albertel 5735: sub username_to_idmap {
                   5736:     my ($classlist)= @_;
                   5737:     my %idmap;
                   5738:     foreach my $student (keys(%$classlist)) {
1.731     raeburn  5739:         my $id = $classlist->{$student}->[&Apache::loncoursedata::CL_ID];
                   5740:         unless ($id eq '') {
                   5741:             if (!exists($idmap{$id})) {
                   5742:                 $idmap{$id} = $student;
                   5743:             } else {
                   5744:                 my $status = $classlist->{$student}->[&Apache::loncoursedata::CL_STATUS];
                   5745:                 if ($status eq 'Active') {
                   5746:                     $idmap{$id} = $student;
                   5747:                 }
                   5748:             }
                   5749:         }
1.82      albertel 5750:     }
                   5751:     return %idmap;
                   5752: }
1.423     albertel 5753: 
                   5754: =pod
                   5755: 
1.424     albertel 5756: =item scantron_fixup_scanline
1.423     albertel 5757: 
                   5758:    Process a requested correction to a scanline.
                   5759: 
                   5760:   Arguments:
                   5761:     $scantron_config   - hash from &get_scantron_config()
                   5762:     $scan_data         - hash of correction information 
                   5763:                           (see &scantron_getfile())
                   5764:     $line              - existing scanline
                   5765:     $whichline         - line number of the passed in scanline
                   5766:     $field             - type of change to process 
                   5767:                          (either 
1.573     bisitz   5768:                           'ID'     -> correct the student/employee ID
1.423     albertel 5769:                           'CODE'   -> correct the CODE
                   5770:                           'answer' -> fixup the submitted answers)
                   5771:     
                   5772:    $args               - hash of additional info,
                   5773:                           - 'ID' 
                   5774:                                'newid' -> studentID to use in replacement
1.424     albertel 5775:                                           of existing one
1.423     albertel 5776:                           - 'CODE' 
                   5777:                                'CODE_ignore_dup' - set to true if duplicates
                   5778:                                                    should be ignored.
                   5779: 	                       'CODE' - is new code or 'use_unfound'
1.424     albertel 5780:                                         if the existing unfound code should
1.423     albertel 5781:                                         be used as is
                   5782:                           - 'answer'
                   5783:                                'response' - new answer or 'none' if blank
                   5784:                                'question' - the bubble line to change
1.503     raeburn  5785:                                'questionnum' - the question identifier,
                   5786:                                                may include subquestion. 
1.423     albertel 5787: 
                   5788:   Returns:
                   5789:     $line - the modified scanline
                   5790: 
                   5791:   Side effects: 
                   5792:     $scan_data - may be updated
                   5793: 
                   5794: =cut
                   5795: 
1.82      albertel 5796: 
1.157     albertel 5797: sub scantron_fixup_scanline {
                   5798:     my ($scantron_config,$scan_data,$line,$whichline,$field,$args)=@_;
                   5799:     if ($field eq 'ID') {
                   5800: 	if (length($args->{'newid'}) > $$scantron_config{'IDlength'}) {
1.186     albertel 5801: 	    return ($line,1,'New value too large');
1.157     albertel 5802: 	}
                   5803: 	if (length($args->{'newid'}) < $$scantron_config{'IDlength'}) {
                   5804: 	    $args->{'newid'}=sprintf('%-'.$$scantron_config{'IDlength'}.'s',
                   5805: 				     $args->{'newid'});
                   5806: 	}
                   5807: 	substr($line,$$scantron_config{'IDstart'}-1,
                   5808: 	       $$scantron_config{'IDlength'})=$args->{'newid'};
                   5809: 	if ($args->{'newid'}=~/^\s*$/) {
                   5810: 	    &scan_data($scan_data,"$whichline.user",
                   5811: 		       $args->{'username'}.':'.$args->{'domain'});
                   5812: 	}
1.186     albertel 5813:     } elsif ($field eq 'CODE') {
1.192     albertel 5814: 	if ($args->{'CODE_ignore_dup'}) {
                   5815: 	    &scan_data($scan_data,"$whichline.CODE_ignore_dup",'1');
                   5816: 	}
                   5817: 	&scan_data($scan_data,"$whichline.useCODE",'1');
                   5818: 	if ($args->{'CODE'} ne 'use_unfound') {
1.191     albertel 5819: 	    if (length($args->{'CODE'}) > $$scantron_config{'CODElength'}) {
                   5820: 		return ($line,1,'New CODE value too large');
                   5821: 	    }
                   5822: 	    if (length($args->{'CODE'}) < $$scantron_config{'CODElength'}) {
                   5823: 		$args->{'CODE'}=sprintf('%-'.$$scantron_config{'CODElength'}.'s',$args->{'CODE'});
                   5824: 	    }
                   5825: 	    substr($line,$$scantron_config{'CODEstart'}-1,
                   5826: 		   $$scantron_config{'CODElength'})=$args->{'CODE'};
1.186     albertel 5827: 	}
1.157     albertel 5828:     } elsif ($field eq 'answer') {
1.497     foxr     5829: 	my $length=$scantron_config->{'Qlength'};
1.157     albertel 5830: 	my $off=$scantron_config->{'Qoff'};
                   5831: 	my $on=$scantron_config->{'Qon'};
1.497     foxr     5832: 	my $answer=${off}x$length;
                   5833: 	if ($args->{'response'} eq 'none') {
                   5834: 	    &scan_data($scan_data,
1.503     raeburn  5835: 		       "$whichline.no_bubble.".$args->{'questionnum'},'1');
1.497     foxr     5836: 	} else {
                   5837: 	    if ($on eq 'letter') {
                   5838: 		my @alphabet=('A'..'Z');
                   5839: 		$answer=$alphabet[$args->{'response'}];
                   5840: 	    } elsif ($on eq 'number') {
                   5841: 		$answer=$args->{'response'}+1;
                   5842: 		if ($answer == 10) { $answer = '0'; }
1.274     albertel 5843: 	    } else {
1.497     foxr     5844: 		substr($answer,$args->{'response'},1)=$on;
1.274     albertel 5845: 	    }
1.497     foxr     5846: 	    &scan_data($scan_data,
1.503     raeburn  5847: 		       "$whichline.no_bubble.".$args->{'questionnum'},undef,'1');
1.157     albertel 5848: 	}
1.497     foxr     5849: 	my $where=$length*($args->{'question'}-1)+$scantron_config->{'Qstart'};
                   5850: 	substr($line,$where-1,$length)=$answer;
1.157     albertel 5851:     }
                   5852:     return $line;
                   5853: }
1.423     albertel 5854: 
                   5855: =pod
                   5856: 
                   5857: =item scan_data
                   5858: 
                   5859:     Edit or look up  an item in the scan_data hash.
                   5860: 
                   5861:   Arguments:
                   5862:     $scan_data  - The hash (see scantron_getfile)
                   5863:     $key        - shorthand of the key to edit (actual key is
1.424     albertel 5864:                   scantronfilename_key).
1.423     albertel 5865:     $data        - New value of the hash entry.
                   5866:     $delete      - If true, the entry is removed from the hash.
                   5867: 
                   5868:   Returns:
                   5869:     The new value of the hash table field (undefined if deleted).
                   5870: 
                   5871: =cut
                   5872: 
                   5873: 
1.157     albertel 5874: sub scan_data {
                   5875:     my ($scan_data,$key,$value,$delete)=@_;
1.257     albertel 5876:     my $filename=$env{'form.scantron_selectfile'};
1.157     albertel 5877:     if (defined($value)) {
                   5878: 	$scan_data->{$filename.'_'.$key} = $value;
                   5879:     }
                   5880:     if ($delete) { delete($scan_data->{$filename.'_'.$key}); }
                   5881:     return $scan_data->{$filename.'_'.$key};
                   5882: }
1.423     albertel 5883: 
1.495     albertel 5884: # ----- These first few routines are general use routines.----
                   5885: 
                   5886: # Return the number of occurences of a pattern in a string.
                   5887: 
                   5888: sub occurence_count {
                   5889:     my ($string, $pattern) = @_;
                   5890: 
                   5891:     my @matches = ($string =~ /$pattern/g);
                   5892: 
                   5893:     return scalar(@matches);
                   5894: }
                   5895: 
                   5896: 
                   5897: # Take a string known to have digits and convert all the
                   5898: # digits into letters in the range J,A..I.
                   5899: 
                   5900: sub digits_to_letters {
                   5901:     my ($input) = @_;
                   5902: 
                   5903:     my @alphabet = ('J', 'A'..'I');
                   5904: 
                   5905:     my @input    = split(//, $input);
                   5906:     my $output ='';
                   5907:     for (my $i = 0; $i < scalar(@input); $i++) {
                   5908: 	if ($input[$i] =~ /\d/) {
                   5909: 	    $output .= $alphabet[$input[$i]];
                   5910: 	} else {
                   5911: 	    $output .= $input[$i];
                   5912: 	}
                   5913:     }
                   5914:     return $output;
                   5915: }
                   5916: 
1.423     albertel 5917: =pod 
                   5918: 
                   5919: =item scantron_parse_scanline
                   5920: 
1.711     bisitz   5921:   Decodes a scanline from the selected bubblesheet file
1.423     albertel 5922: 
                   5923:  Arguments:
1.711     bisitz   5924:     line             - The text of the bubblesheet file line to process
1.423     albertel 5925:     whichline        - Line number
1.711     bisitz   5926:     scantron_config  - Hash describing the format of the bubblesheet lines.
1.423     albertel 5927:     scan_data        - Hash of extra information about the scanline
                   5928:                        (see scantron_getfile for more information)
                   5929:     just_header      - True if should not process question answers but only
                   5930:                        the stuff to the left of the answers.
1.691     raeburn  5931:     randomorder      - True if randomorder in use
                   5932:     randompick       - True if randompick in use
                   5933:     sequence         - Exam folder URL
                   5934:     master_seq       - Ref to array containing symbs in exam folder
                   5935:     symb_to_resource - Ref to hash of symbs for resources in exam folder
                   5936:                        (corresponding values are resource objects)
                   5937:     partids_by_symb  - Ref to hash of symb -> array ref of partIDs
                   5938:     orderedforcode   - Ref to hash of arrays. keys are CODEs and values
                   5939:                        are refs to an array of resource objects, ordered
                   5940:                        according to order used for CODE, when randomorder
                   5941:                        and or randompick are in use.
                   5942:     respnumlookup    - Ref to hash mapping question numbers in bubble lines
                   5943:                        for current line to question number used for same question
                   5944:                         in "Master Sequence" (as seen by Course Coordinator).
                   5945:     startline        - Ref to hash where key is question number (0 is first)
                   5946:                        and value is number of first bubble line for current 
                   5947:                        student or code-based randompick and/or randomorder.
                   5948:     totalref         - Ref of scalar used to score total number of bubble
                   5949:                        lines needed for responses in a scan line (used when
                   5950:                        randompick in use. 
                   5951:     
1.423     albertel 5952:  Returns:
                   5953:    Hash containing the result of parsing the scanline
                   5954: 
                   5955:    Keys are all proceeded by the string 'scantron.'
                   5956: 
                   5957:        CODE    - the CODE in use for this scanline
                   5958:        useCODE - 1 if the CODE is invalid but it usage has been forced
                   5959:                  by the operator
                   5960:        CODE_ignore_dup - 1 if the CODE is a duplicated use when unique
                   5961:                             CODEs were selected, but the usage has been
                   5962:                             forced by the operator
1.556     weissno  5963:        ID  - student/employee ID
1.423     albertel 5964:        PaperID - if used, the ID number printed on the sheet when the 
                   5965:                  paper was scanned
                   5966:        FirstName - first name from the sheet
                   5967:        LastName  - last name from the sheet
                   5968: 
                   5969:      if just_header was not true these key may also exist
                   5970: 
1.447     foxr     5971:        missingerror - a list of bubble ranges that are considered to be answers
                   5972:                       to a single question that don't have any bubbles filled in.
                   5973:                       Of the form questionnumber:firstbubblenumber:count.
                   5974:        doubleerror  - a list of bubble ranges that are considered to be answers
                   5975:                       to a single question that have more than one bubble filled in.
                   5976:                       Of the form questionnumber::firstbubblenumber:count
                   5977:    
                   5978:                 In the above, count is the number of bubble responses in the
                   5979:                 input line needed to represent the possible answers to the question.
                   5980:                 e.g. a radioresponse with 15 choices in an answer sheet with 10 choices
                   5981:                 per line would have count = 2.
                   5982: 
1.423     albertel 5983:        maxquest     - the number of the last bubble line that was parsed
                   5984: 
                   5985:        (<number> starts at 1)
                   5986:        <number>.answer - zero or more letters representing the selected
                   5987:                          letters from the scanline for the bubble line 
                   5988:                          <number>.
                   5989:                          if blank there was either no bubble or there where
                   5990:                          multiple bubbles, (consult the keys missingerror and
                   5991:                          doubleerror if this is an error condition)
                   5992: 
                   5993: =cut
                   5994: 
1.82      albertel 5995: sub scantron_parse_scanline {
1.691     raeburn  5996:     my ($line,$whichline,$scantron_config,$scan_data,$just_header,$idmap,
                   5997:         $randomorder,$randompick,$sequence,$master_seq,$symb_to_resource,
                   5998:         $partids_by_symb,$orderedforcode,$respnumlookup,$startline,$totalref)=@_;
1.470     foxr     5999: 
1.82      albertel 6000:     my %record;
1.691     raeburn  6001:     my $data=substr($line,0,$$scantron_config{'Qstart'}-1); # stuff before answers
1.278     albertel 6002:     if (!($$scantron_config{'CODElocation'} eq 0 ||
                   6003: 	  $$scantron_config{'CODElocation'} eq 'none')) {
                   6004: 	if ($$scantron_config{'CODElocation'} < 0 ||
                   6005: 	    $$scantron_config{'CODElocation'} eq 'letter' ||
                   6006: 	    $$scantron_config{'CODElocation'} eq 'number') {
1.191     albertel 6007: 	    $record{'scantron.CODE'}=substr($data,
                   6008: 					    $$scantron_config{'CODEstart'}-1,
1.83      albertel 6009: 					    $$scantron_config{'CODElength'});
1.191     albertel 6010: 	    if (&scan_data($scan_data,"$whichline.useCODE")) {
                   6011: 		$record{'scantron.useCODE'}=1;
                   6012: 	    }
1.192     albertel 6013: 	    if (&scan_data($scan_data,"$whichline.CODE_ignore_dup")) {
                   6014: 		$record{'scantron.CODE_ignore_dup'}=1;
                   6015: 	    }
1.82      albertel 6016: 	} else {
                   6017: 	    #FIXME interpret first N questions
                   6018: 	}
                   6019:     }
1.83      albertel 6020:     $record{'scantron.ID'}=substr($data,$$scantron_config{'IDstart'}-1,
                   6021: 				  $$scantron_config{'IDlength'});
1.157     albertel 6022:     $record{'scantron.PaperID'}=
                   6023: 	substr($data,$$scantron_config{'PaperID'}-1,
                   6024: 	       $$scantron_config{'PaperIDlength'});
                   6025:     $record{'scantron.FirstName'}=
                   6026: 	substr($data,$$scantron_config{'FirstName'}-1,
                   6027: 	       $$scantron_config{'FirstNamelength'});
                   6028:     $record{'scantron.LastName'}=
                   6029: 	substr($data,$$scantron_config{'LastName'}-1,
                   6030: 	       $$scantron_config{'LastNamelength'});
1.423     albertel 6031:     if ($just_header) { return \%record; }
1.194     albertel 6032: 
1.82      albertel 6033:     my @alphabet=('A'..'Z');
                   6034:     my $questnum=0;
1.447     foxr     6035:     my $ansnum  =1;		# Multiple 'answer lines'/question.
                   6036: 
1.691     raeburn  6037:     my $lastpos = $env{'form.scantron_maxbubble'}*$$scantron_config{'Qlength'};
                   6038:     if ($randompick || $randomorder) {
                   6039:         my $total = &get_respnum_lookups($sequence,$scan_data,$idmap,$line,\%record,
                   6040:                                          $master_seq,$symb_to_resource,
                   6041:                                          $partids_by_symb,$orderedforcode,
                   6042:                                          $respnumlookup,$startline);
                   6043:         if ($total) {
                   6044:             $lastpos = $total*$$scantron_config{'Qlength'}; 
                   6045:         }
                   6046:         if (ref($totalref)) {
                   6047:             $$totalref = $total;
                   6048:         }
                   6049:     }
                   6050:     my $questions=substr($line,$$scantron_config{'Qstart'}-1,$lastpos);  # Answers
1.470     foxr     6051:     chomp($questions);		# Get rid of any trailing \n.
                   6052:     $questions =~ s/\r$//;      # Get rid of trailing \r too (MAC or Win uploads).
                   6053:     while (length($questions)) {
1.691     raeburn  6054:         my $answers_needed;
                   6055:         if (($randompick || $randomorder) && (ref($respnumlookup) eq 'HASH')) {
                   6056:             $answers_needed = $bubble_lines_per_response{$respnumlookup->{$questnum}};
                   6057:         } else {
                   6058: 	    $answers_needed = $bubble_lines_per_response{$questnum};
                   6059:         }
1.503     raeburn  6060:         my $answer_length  = ($$scantron_config{'Qlength'} * $answers_needed)
                   6061:                              || 1;
                   6062:         $questnum++;
                   6063:         my $quest_id = $questnum;
                   6064:         my $currentquest = substr($questions,0,$answer_length);
                   6065:         $questions       = substr($questions,$answer_length);
                   6066:         if (length($currentquest) < $answer_length) { next; }
                   6067: 
1.691     raeburn  6068:         my $subdivided;
                   6069:         if (($randompick || $randomorder) && (ref($respnumlookup) eq 'HASH')) {
                   6070:             $subdivided = $subdivided_bubble_lines{$respnumlookup->{$questnum-1}};
                   6071:         } else {
                   6072:             $subdivided = $subdivided_bubble_lines{$questnum-1};
                   6073:         }
                   6074:         if ($subdivided =~ /,/) {
1.503     raeburn  6075:             my $subquestnum = 1;
                   6076:             my $subquestions = $currentquest;
1.691     raeburn  6077:             my @subanswers_needed = split(/,/,$subdivided);
1.503     raeburn  6078:             foreach my $subans (@subanswers_needed) {
                   6079:                 my $subans_length =
                   6080:                     ($$scantron_config{'Qlength'} * $subans)  || 1;
                   6081:                 my $currsubquest = substr($subquestions,0,$subans_length);
                   6082:                 $subquestions   = substr($subquestions,$subans_length);
                   6083:                 $quest_id = "$questnum.$subquestnum";
                   6084:                 if (($$scantron_config{'Qon'} eq 'letter') ||
                   6085:                     ($$scantron_config{'Qon'} eq 'number')) {
                   6086:                     $ansnum = &scantron_validator_lettnum($ansnum, 
                   6087:                         $questnum,$quest_id,$subans,$currsubquest,$whichline,
1.691     raeburn  6088:                         \@alphabet,\%record,$scantron_config,$scan_data,
                   6089:                         $randomorder,$randompick,$respnumlookup);
1.503     raeburn  6090:                 } else {
                   6091:                     $ansnum = &scantron_validator_positional($ansnum,
1.691     raeburn  6092:                         $questnum,$quest_id,$subans,$currsubquest,$whichline,
                   6093:                         \@alphabet,\%record,$scantron_config,$scan_data,
                   6094:                         $randomorder,$randompick,$respnumlookup);
1.503     raeburn  6095:                 }
                   6096:                 $subquestnum ++;
                   6097:             }
                   6098:         } else {
                   6099:             if (($$scantron_config{'Qon'} eq 'letter') ||
                   6100:                 ($$scantron_config{'Qon'} eq 'number')) {
                   6101:                 $ansnum = &scantron_validator_lettnum($ansnum,$questnum,
                   6102:                     $quest_id,$answers_needed,$currentquest,$whichline,
1.691     raeburn  6103:                     \@alphabet,\%record,$scantron_config,$scan_data,
                   6104:                     $randomorder,$randompick,$respnumlookup);
1.503     raeburn  6105:             } else {
                   6106:                 $ansnum = &scantron_validator_positional($ansnum,$questnum,
                   6107:                     $quest_id,$answers_needed,$currentquest,$whichline,
1.691     raeburn  6108:                     \@alphabet,\%record,$scantron_config,$scan_data,
                   6109:                     $randomorder,$randompick,$respnumlookup);
1.503     raeburn  6110:             }
                   6111:         }
                   6112:     }
                   6113:     $record{'scantron.maxquest'}=$questnum;
                   6114:     return \%record;
                   6115: }
1.447     foxr     6116: 
1.691     raeburn  6117: sub get_master_seq {
                   6118:     my ($resources,$master_seq,$symb_to_resource) = @_;
                   6119:     return unless ((ref($resources) eq 'ARRAY') && (ref($master_seq) eq 'ARRAY') && 
                   6120:                    (ref($symb_to_resource) eq 'HASH'));
                   6121:     my $resource_error;
                   6122:     foreach my $resource (@{$resources}) {
                   6123:         my $ressymb;
                   6124:         if (ref($resource)) {
                   6125:             $ressymb = $resource->symb();
                   6126:             push(@{$master_seq},$ressymb);
                   6127:             $symb_to_resource->{$ressymb} = $resource;
                   6128:         } else {
                   6129:             $resource_error = 1;
                   6130:             last;
                   6131:         }
                   6132:     }
                   6133:     return $resource_error;
                   6134: }
                   6135: 
                   6136: sub get_respnum_lookups {
                   6137:     my ($sequence,$scan_data,$idmap,$line,$record,$master_seq,$symb_to_resource,
                   6138:         $partids_by_symb,$orderedforcode,$respnumlookup,$startline) = @_;
                   6139:     return unless ((ref($record) eq 'HASH') && (ref($master_seq) eq 'ARRAY') &&
                   6140:                    (ref($symb_to_resource) eq 'HASH') && (ref($partids_by_symb) eq 'HASH') &&
                   6141:                    (ref($orderedforcode) eq 'HASH') && (ref($respnumlookup) eq 'HASH') &&
                   6142:                    (ref($startline) eq 'HASH'));
                   6143:     my ($user,$scancode);
                   6144:     if ((exists($record->{'scantron.CODE'})) &&
                   6145:         (&Apache::lonnet::validCODE($record->{'scantron.CODE'}))) {
                   6146:         $scancode = $record->{'scantron.CODE'};
                   6147:     } else {
                   6148:         $user = &scantron_find_student($record,$scan_data,$idmap,$line);
                   6149:     }
                   6150:     my @mapresources =
                   6151:         &users_order($user,$scancode,$sequence,$master_seq,$symb_to_resource,
                   6152:                      $orderedforcode);
                   6153:     my $total = 0;
                   6154:     my $count = 0;
                   6155:     foreach my $resource (@mapresources) {
                   6156:         my $id = $resource->id();
                   6157:         my $symb = $resource->symb();
                   6158:         if (ref($partids_by_symb->{$symb}) eq 'ARRAY') {
                   6159:             foreach my $partid (@{$partids_by_symb->{$symb}}) {
                   6160:                 my $respnum = $masterseq_id_responsenum{$id.'_'.$partid};
                   6161:                 if ($respnum ne '') {
                   6162:                     $respnumlookup->{$count} = $respnum;
                   6163:                     $startline->{$count} = $total;
                   6164:                     $total += $bubble_lines_per_response{$respnum};
                   6165:                     $count ++;
                   6166:                 }
                   6167:             }
                   6168:         }
                   6169:     }
                   6170:     return $total;
                   6171: }
                   6172: 
1.503     raeburn  6173: sub scantron_validator_lettnum {
                   6174:     my ($ansnum,$questnum,$quest_id,$answers_needed,$currquest,$whichline,
1.691     raeburn  6175:         $alphabet,$record,$scantron_config,$scan_data,$randomorder,
                   6176:         $randompick,$respnumlookup) = @_;
1.503     raeburn  6177: 
                   6178:     # Qon 'letter' implies for each slot in currquest we have:
                   6179:     #    ? or * for doubles, a letter in A-Z for a bubble, and
                   6180:     #    about anything else (esp. a value of Qoff) for missing
                   6181:     #    bubbles.
                   6182:     #
                   6183:     # Qon 'number' implies each slot gives a digit that indexes the
                   6184:     #    bubbles filled, or Qoff, or a non-number for unbubbled lines,
                   6185:     #    and * or ? for double bubbles on a single line.
                   6186:     #
1.447     foxr     6187: 
1.503     raeburn  6188:     my $matchon;
                   6189:     if ($$scantron_config{'Qon'} eq 'letter') {
                   6190:         $matchon = '[A-Z]';
                   6191:     } elsif ($$scantron_config{'Qon'} eq 'number') {
                   6192:         $matchon = '\d';
                   6193:     }
                   6194:     my $occurrences = 0;
1.691     raeburn  6195:     my $responsenum = $questnum-1;
                   6196:     if (($randompick || $randomorder) && (ref($respnumlookup) eq 'HASH')) {
                   6197:        $responsenum = $respnumlookup->{$questnum-1} 
                   6198:     }
                   6199:     if (($responsetype_per_response{$responsenum} eq 'essayresponse') ||
                   6200:         ($responsetype_per_response{$responsenum} eq 'formularesponse') ||
                   6201:         ($responsetype_per_response{$responsenum} eq 'stringresponse') ||
                   6202:         ($responsetype_per_response{$responsenum} eq 'imageresponse') ||
                   6203:         ($responsetype_per_response{$responsenum} eq 'reactionresponse') ||
                   6204:         ($responsetype_per_response{$responsenum} eq 'organicresponse')) {
1.503     raeburn  6205:         my @singlelines = split('',$currquest);
                   6206:         foreach my $entry (@singlelines) {
                   6207:             $occurrences = &occurence_count($entry,$matchon);
                   6208:             if ($occurrences > 1) {
                   6209:                 last;
                   6210:             }
1.691     raeburn  6211:         }
1.503     raeburn  6212:     } else {
                   6213:         $occurrences = &occurence_count($currquest,$matchon); 
                   6214:     }
                   6215:     if (($currquest =~ /\?/ || $currquest =~ /\*/) || ($occurrences > 1)) {
                   6216:         push(@{$record->{'scantron.doubleerror'}},$quest_id);
                   6217:         for (my $ans=0; $ans<$answers_needed; $ans++) {
                   6218:             my $bubble = substr($currquest,$ans,1);
                   6219:             if ($bubble =~ /$matchon/ ) {
                   6220:                 if ($$scantron_config{'Qon'} eq 'number') {
                   6221:                     if ($bubble == 0) {
                   6222:                         $bubble = 10; 
                   6223:                     }
                   6224:                     $record->{"scantron.$ansnum.answer"} = 
                   6225:                         $alphabet->[$bubble-1];
                   6226:                 } else {
                   6227:                     $record->{"scantron.$ansnum.answer"} = $bubble;
                   6228:                 }
                   6229:             } else {
                   6230:                 $record->{"scantron.$ansnum.answer"}='';
                   6231:             }
                   6232:             $ansnum++;
                   6233:         }
                   6234:     } elsif (!defined($currquest)
                   6235:             || (&occurence_count($currquest, $$scantron_config{'Qoff'}) == length($currquest))
                   6236:             || (&occurence_count($currquest,$matchon) == 0)) {
                   6237:         for (my $ans=0; $ans<$answers_needed; $ans++ ) {
                   6238:             $record->{"scantron.$ansnum.answer"}='';
                   6239:             $ansnum++;
                   6240:         }
                   6241:         if (!&scan_data($scan_data,"$whichline.no_bubble.$quest_id")) {
                   6242:             push(@{$record->{'scantron.missingerror'}},$quest_id);
                   6243:         }
                   6244:     } else {
                   6245:         if ($$scantron_config{'Qon'} eq 'number') {
                   6246:             $currquest = &digits_to_letters($currquest);            
                   6247:         }
                   6248:         for (my $ans=0; $ans<$answers_needed; $ans++) {
                   6249:             my $bubble = substr($currquest,$ans,1);
                   6250:             $record->{"scantron.$ansnum.answer"} = $bubble;
                   6251:             $ansnum++;
                   6252:         }
                   6253:     }
                   6254:     return $ansnum;
                   6255: }
1.447     foxr     6256: 
1.503     raeburn  6257: sub scantron_validator_positional {
                   6258:     my ($ansnum,$questnum,$quest_id,$answers_needed,$currquest,
1.691     raeburn  6259:         $whichline,$alphabet,$record,$scantron_config,$scan_data,
                   6260:         $randomorder,$randompick,$respnumlookup) = @_;
1.447     foxr     6261: 
1.503     raeburn  6262:     # Otherwise there's a positional notation;
                   6263:     # each bubble line requires Qlength items, and there are filled in
                   6264:     # bubbles for each case where there 'Qon' characters.
                   6265:     #
1.447     foxr     6266: 
1.503     raeburn  6267:     my @array=split($$scantron_config{'Qon'},$currquest,-1);
1.447     foxr     6268: 
1.503     raeburn  6269:     # If the split only gives us one element.. the full length of the
                   6270:     # answer string, no bubbles are filled in:
1.447     foxr     6271: 
1.507     raeburn  6272:     if ($answers_needed eq '') {
                   6273:         return;
                   6274:     }
                   6275: 
1.503     raeburn  6276:     if (length($array[0]) eq $$scantron_config{'Qlength'}*$answers_needed) {
                   6277:         for (my $ans=0; $ans<$answers_needed; $ans++ ) {
                   6278:             $record->{"scantron.$ansnum.answer"}='';
                   6279:             $ansnum++;
                   6280:         }
                   6281:         if (!&scan_data($scan_data,"$whichline.no_bubble.$quest_id")) {
                   6282:             push(@{$record->{"scantron.missingerror"}},$quest_id);
                   6283:         }
                   6284:     } elsif (scalar(@array) == 2) {
                   6285:         my $location = length($array[0]);
                   6286:         my $line_num = int($location / $$scantron_config{'Qlength'});
                   6287:         my $bubble   = $alphabet->[$location % $$scantron_config{'Qlength'}];
                   6288:         for (my $ans=0; $ans<$answers_needed; $ans++) {
                   6289:             if ($ans eq $line_num) {
                   6290:                 $record->{"scantron.$ansnum.answer"} = $bubble;
                   6291:             } else {
                   6292:                 $record->{"scantron.$ansnum.answer"} = ' ';
                   6293:             }
                   6294:             $ansnum++;
                   6295:          }
                   6296:     } else {
                   6297:         #  If there's more than one instance of a bubble character
                   6298:         #  That's a double bubble; with positional notation we can
                   6299:         #  record all the bubbles filled in as well as the
                   6300:         #  fact this response consists of multiple bubbles.
                   6301:         #
1.691     raeburn  6302:         my $responsenum = $questnum-1;
                   6303:         if (($randompick || $randomorder) && (ref($respnumlookup) eq 'HASH')) {
                   6304:             $responsenum = $respnumlookup->{$questnum-1}
                   6305:         }
                   6306:         if (($responsetype_per_response{$responsenum} eq 'essayresponse') ||
                   6307:             ($responsetype_per_response{$responsenum} eq 'formularesponse') ||
                   6308:             ($responsetype_per_response{$responsenum} eq 'stringresponse') ||
                   6309:             ($responsetype_per_response{$responsenum} eq 'imageresponse') ||
                   6310:             ($responsetype_per_response{$responsenum} eq 'reactionresponse') ||
                   6311:             ($responsetype_per_response{$responsenum} eq 'organicresponse')) {
1.503     raeburn  6312:             my $doubleerror = 0;
                   6313:             while (($currquest >= $$scantron_config{'Qlength'}) && 
                   6314:                    (!$doubleerror)) {
                   6315:                my $currline = substr($currquest,0,$$scantron_config{'Qlength'});
                   6316:                $currquest = substr($currquest,$$scantron_config{'Qlength'});
                   6317:                my @currarray = split($$scantron_config{'Qon'},$currline,-1);
                   6318:                if (length(@currarray) > 2) {
                   6319:                    $doubleerror = 1;
                   6320:                } 
                   6321:             }
                   6322:             if ($doubleerror) {
                   6323:                 push(@{$record->{'scantron.doubleerror'}},$quest_id);
                   6324:             }
                   6325:         } else {
                   6326:             push(@{$record->{'scantron.doubleerror'}},$quest_id);
                   6327:         }
                   6328:         my $item = $ansnum;
                   6329:         for (my $ans=0; $ans<$answers_needed; $ans++) {
                   6330:             $record->{"scantron.$item.answer"} = '';
                   6331:             $item ++;
                   6332:         }
1.447     foxr     6333: 
1.503     raeburn  6334:         my @ans=@array;
                   6335:         my $i=0;
                   6336:         my $increment = 0;
                   6337:         while ($#ans) {
                   6338:             $i+=length($ans[0]) + $increment;
                   6339:             my $line   = int($i/$$scantron_config{'Qlength'} + $ansnum);
                   6340:             my $bubble = $i%$$scantron_config{'Qlength'};
                   6341:             $record->{"scantron.$line.answer"}.=$alphabet->[$bubble];
                   6342:             shift(@ans);
                   6343:             $increment = 1;
                   6344:         }
                   6345:         $ansnum += $answers_needed;
1.82      albertel 6346:     }
1.503     raeburn  6347:     return $ansnum;
1.82      albertel 6348: }
                   6349: 
1.423     albertel 6350: =pod
                   6351: 
                   6352: =item scantron_add_delay
                   6353: 
                   6354:    Adds an error message that occurred during the grading phase to a
                   6355:    queue of messages to be shown after grading pass is complete
                   6356: 
                   6357:  Arguments:
1.424     albertel 6358:    $delayqueue  - arrary ref of hash ref of error messages
1.423     albertel 6359:    $scanline    - the scanline that caused the error
                   6360:    $errormesage - the error message
                   6361:    $errorcode   - a numeric code for the error
                   6362: 
                   6363:  Side Effects:
1.424     albertel 6364:    updates the $delayqueue to have a new hash ref of the error
1.423     albertel 6365: 
                   6366: =cut
                   6367: 
1.82      albertel 6368: sub scantron_add_delay {
1.140     albertel 6369:     my ($delayqueue,$scanline,$errormessage,$errorcode)=@_;
                   6370:     push(@$delayqueue,
                   6371: 	 {'line' => $scanline, 'emsg' => $errormessage,
                   6372: 	  'ecode' => $errorcode }
                   6373: 	 );
1.82      albertel 6374: }
                   6375: 
1.423     albertel 6376: =pod
                   6377: 
                   6378: =item scantron_find_student
                   6379: 
1.424     albertel 6380:    Finds the username for the current scanline
                   6381: 
                   6382:   Arguments:
                   6383:    $scantron_record - hash result from scantron_parse_scanline
                   6384:    $scan_data       - hash of correction information 
                   6385:                       (see &scantron_getfile() form more information)
                   6386:    $idmap           - hash from &username_to_idmap()
                   6387:    $line            - number of current scanline
                   6388:  
                   6389:   Returns:
                   6390:    Either 'username:domain' or undef if unknown
                   6391: 
1.423     albertel 6392: =cut
                   6393: 
1.82      albertel 6394: sub scantron_find_student {
1.157     albertel 6395:     my ($scantron_record,$scan_data,$idmap,$line)=@_;
1.83      albertel 6396:     my $scanID=$$scantron_record{'scantron.ID'};
1.157     albertel 6397:     if ($scanID =~ /^\s*$/) {
                   6398:  	return &scan_data($scan_data,"$line.user");
                   6399:     }
1.83      albertel 6400:     foreach my $id (keys(%$idmap)) {
1.157     albertel 6401:  	if (lc($id) eq lc($scanID)) {
                   6402:  	    return $$idmap{$id};
                   6403:  	}
1.83      albertel 6404:     }
                   6405:     return undef;
                   6406: }
                   6407: 
1.423     albertel 6408: =pod
                   6409: 
                   6410: =item scantron_filter
                   6411: 
1.424     albertel 6412:    Filter sub for lonnavmaps, filters out hidden resources if ignore
                   6413:    hidden resources was selected
                   6414: 
1.423     albertel 6415: =cut
                   6416: 
1.83      albertel 6417: sub scantron_filter {
                   6418:     my ($curres)=@_;
1.331     albertel 6419: 
                   6420:     if (ref($curres) && $curres->is_problem()) {
                   6421: 	# if the user has asked to not have either hidden
                   6422: 	# or 'randomout' controlled resources to be graded
                   6423: 	# don't include them
                   6424: 	if ($env{'form.scantron_options_hidden'} eq 'ignore_hidden'
                   6425: 	    && $curres->randomout) {
                   6426: 	    return 0;
                   6427: 	}
1.83      albertel 6428: 	return 1;
                   6429:     }
                   6430:     return 0;
1.82      albertel 6431: }
                   6432: 
1.423     albertel 6433: =pod
                   6434: 
                   6435: =item scantron_process_corrections
                   6436: 
1.424     albertel 6437:    Gets correction information out of submitted form data and corrects
                   6438:    the scanline
                   6439: 
1.423     albertel 6440: =cut
                   6441: 
1.157     albertel 6442: sub scantron_process_corrections {
                   6443:     my ($r) = @_;
1.257     albertel 6444:     my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
1.157     albertel 6445:     my ($scanlines,$scan_data)=&scantron_getfile();
                   6446:     my $classlist=&Apache::loncoursedata::get_classlist();
1.257     albertel 6447:     my $which=$env{'form.scantron_line'};
1.200     albertel 6448:     my $line=&scantron_get_line($scanlines,$scan_data,$which);
1.157     albertel 6449:     my ($skip,$err,$errmsg);
1.257     albertel 6450:     if ($env{'form.scantron_skip_record'}) {
1.157     albertel 6451: 	$skip=1;
1.257     albertel 6452:     } elsif ($env{'form.scantron_corrections'} =~ /^(duplicate|incorrect)ID$/) {
                   6453: 	my $newstudent=$env{'form.scantron_username'}.':'.
                   6454: 	    $env{'form.scantron_domain'};
1.157     albertel 6455: 	my $newid=$classlist->{$newstudent}->[&Apache::loncoursedata::CL_ID];
                   6456: 	($line,$err,$errmsg)=
                   6457: 	    &scantron_fixup_scanline(\%scantron_config,$scan_data,$line,$which,
                   6458: 				     'ID',{'newid'=>$newid,
1.257     albertel 6459: 				    'username'=>$env{'form.scantron_username'},
                   6460: 				    'domain'=>$env{'form.scantron_domain'}});
                   6461:     } elsif ($env{'form.scantron_corrections'} =~ /^(duplicate|incorrect)CODE$/) {
                   6462: 	my $resolution=$env{'form.scantron_CODE_resolution'};
1.190     albertel 6463: 	my $newCODE;
1.192     albertel 6464: 	my %args;
1.190     albertel 6465: 	if      ($resolution eq 'use_unfound') {
1.191     albertel 6466: 	    $newCODE='use_unfound';
1.190     albertel 6467: 	} elsif ($resolution eq 'use_found') {
1.257     albertel 6468: 	    $newCODE=$env{'form.scantron_CODE_selectedvalue'};
1.190     albertel 6469: 	} elsif ($resolution eq 'use_typed') {
1.257     albertel 6470: 	    $newCODE=$env{'form.scantron_CODE_newvalue'};
1.194     albertel 6471: 	} elsif ($resolution =~ /^use_closest_(\d+)/) {
1.257     albertel 6472: 	    $newCODE=$env{"form.scantron_CODE_closest_$1"};
1.190     albertel 6473: 	}
1.257     albertel 6474: 	if ($env{'form.scantron_corrections'} eq 'duplicateCODE') {
1.192     albertel 6475: 	    $args{'CODE_ignore_dup'}=1;
                   6476: 	}
                   6477: 	$args{'CODE'}=$newCODE;
1.186     albertel 6478: 	($line,$err,$errmsg)=
                   6479: 	    &scantron_fixup_scanline(\%scantron_config,$scan_data,$line,$which,
1.192     albertel 6480: 				     'CODE',\%args);
1.257     albertel 6481:     } elsif ($env{'form.scantron_corrections'} =~ /^(missing|double)bubble$/) {
                   6482: 	foreach my $question (split(',',$env{'form.scantron_questions'})) {
1.157     albertel 6483: 	    ($line,$err,$errmsg)=
                   6484: 		&scantron_fixup_scanline(\%scantron_config,$scan_data,$line,
                   6485: 					 $which,'answer',
                   6486: 					 { 'question'=>$question,
1.503     raeburn  6487: 		      		   'response'=>$env{"form.scantron_correct_Q_$question"},
                   6488:                                    'questionnum'=>$env{"form.scantron_questionnum_Q_$question"}});
1.157     albertel 6489: 	    if ($err) { last; }
                   6490: 	}
                   6491:     }
                   6492:     if ($err) {
1.703     bisitz   6493:         $r->print(
                   6494:             '<p class="LC_error">'
                   6495:            .&mt('Unable to accept last correction, an error occurred: [_1]',
                   6496:                 $errmsg)
1.704     raeburn  6497:            .'</p>');
1.157     albertel 6498:     } else {
1.200     albertel 6499: 	&scantron_put_line($scanlines,$scan_data,$which,$line,$skip);
1.157     albertel 6500: 	&scantron_putfile($scanlines,$scan_data);
                   6501:     }
                   6502: }
                   6503: 
1.423     albertel 6504: =pod
                   6505: 
                   6506: =item reset_skipping_status
                   6507: 
1.424     albertel 6508:    Forgets the current set of remember skipped scanlines (and thus
                   6509:    reverts back to considering all lines in the
                   6510:    scantron_skipped_<filename> file)
                   6511: 
1.423     albertel 6512: =cut
                   6513: 
1.200     albertel 6514: sub reset_skipping_status {
                   6515:     my ($scanlines,$scan_data)=&scantron_getfile();
                   6516:     &scan_data($scan_data,'remember_skipping',undef,1);
                   6517:     &scantron_putfile(undef,$scan_data);
                   6518: }
                   6519: 
1.423     albertel 6520: =pod
                   6521: 
                   6522: =item start_skipping
                   6523: 
1.424     albertel 6524:    Marks a scanline to be skipped. 
                   6525: 
1.423     albertel 6526: =cut
                   6527: 
1.376     albertel 6528: sub start_skipping {
1.200     albertel 6529:     my ($scan_data,$i)=@_;
                   6530:     my %remembered=split(':',&scan_data($scan_data,'remember_skipping'));
1.376     albertel 6531:     if ($env{'form.scantron_options_redo'} =~ /^redo_/) {
                   6532: 	$remembered{$i}=2;
                   6533:     } else {
                   6534: 	$remembered{$i}=1;
                   6535:     }
1.200     albertel 6536:     &scan_data($scan_data,'remember_skipping',join(':',%remembered));
                   6537: }
                   6538: 
1.423     albertel 6539: =pod
                   6540: 
                   6541: =item should_be_skipped
                   6542: 
1.424     albertel 6543:    Checks whether a scanline should be skipped.
                   6544: 
1.423     albertel 6545: =cut
                   6546: 
1.200     albertel 6547: sub should_be_skipped {
1.376     albertel 6548:     my ($scanlines,$scan_data,$i)=@_;
1.257     albertel 6549:     if ($env{'form.scantron_options_redo'} !~ /^redo_/) {
1.200     albertel 6550: 	# not redoing old skips
1.376     albertel 6551: 	if ($scanlines->{'skipped'}[$i]) { return 1; }
1.200     albertel 6552: 	return 0;
                   6553:     }
                   6554:     my %remembered=split(':',&scan_data($scan_data,'remember_skipping'));
1.376     albertel 6555: 
                   6556:     if (exists($remembered{$i}) && $remembered{$i} != 2 ) {
                   6557: 	return 0;
                   6558:     }
1.200     albertel 6559:     return 1;
                   6560: }
                   6561: 
1.423     albertel 6562: =pod
                   6563: 
                   6564: =item remember_current_skipped
                   6565: 
1.424     albertel 6566:    Discovers what scanlines are in the scantron_skipped_<filename>
                   6567:    file and remembers them into scan_data for later use.
                   6568: 
1.423     albertel 6569: =cut
                   6570: 
1.200     albertel 6571: sub remember_current_skipped {
                   6572:     my ($scanlines,$scan_data)=&scantron_getfile();
                   6573:     my %to_remember;
                   6574:     for (my $i=0;$i<=$scanlines->{'count'};$i++) {
                   6575: 	if ($scanlines->{'skipped'}[$i]) {
                   6576: 	    $to_remember{$i}=1;
                   6577: 	}
                   6578:     }
1.376     albertel 6579: 
1.200     albertel 6580:     &scan_data($scan_data,'remember_skipping',join(':',%to_remember));
                   6581:     &scantron_putfile(undef,$scan_data);
                   6582: }
                   6583: 
1.423     albertel 6584: =pod
                   6585: 
                   6586: =item check_for_error
                   6587: 
1.424     albertel 6588:     Checks if there was an error when attempting to remove a specific
1.659     raeburn  6589:     scantron_.. bubblesheet data file. Prints out an error if
1.424     albertel 6590:     something went wrong.
                   6591: 
1.423     albertel 6592: =cut
                   6593: 
1.200     albertel 6594: sub check_for_error {
                   6595:     my ($r,$result)=@_;
                   6596:     if ($result ne 'ok' && $result ne 'not_found' ) {
1.492     albertel 6597: 	$r->print(&mt("An error occurred ([_1]) when trying to remove the existing corrections.",$result));
1.200     albertel 6598:     }
                   6599: }
1.157     albertel 6600: 
1.423     albertel 6601: =pod
                   6602: 
                   6603: =item scantron_warning_screen
                   6604: 
1.424     albertel 6605:    Interstitial screen to make sure the operator has selected the
                   6606:    correct options before we start the validation phase.
                   6607: 
1.423     albertel 6608: =cut
                   6609: 
1.203     albertel 6610: sub scantron_warning_screen {
1.650     raeburn  6611:     my ($button_text,$symb)=@_;
1.257     albertel 6612:     my $title=&Apache::lonnet::gettitle($env{'form.selectpage'});
1.284     albertel 6613:     my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
1.373     albertel 6614:     my $CODElist;
1.284     albertel 6615:     if ($scantron_config{'CODElocation'} &&
                   6616: 	$scantron_config{'CODEstart'} &&
                   6617: 	$scantron_config{'CODElength'}) {
                   6618: 	$CODElist=$env{'form.scantron_CODElist'};
1.721     bisitz   6619: 	if ($env{'form.scantron_CODElist'} eq '') { $CODElist='<span class="LC_warning">'.&mt('None').'</span>'; }
1.284     albertel 6620: 	$CODElist=
1.492     albertel 6621: 	    '<tr><td><b>'.&mt('List of CODES to validate against:').'</b></td><td><tt>'.
1.373     albertel 6622: 	    $env{'form.scantron_CODElist'}.'</tt></td></tr>';
1.284     albertel 6623:     }
1.663     raeburn  6624:     my $lastbubblepoints;
                   6625:     if ($env{'form.scantron_lastbubblepoints'} ne '') {
                   6626:         $lastbubblepoints =
                   6627:             '<tr><td><b>'.&mt('Hand-graded items: points from last bubble in row').'</b></td><td><tt>'.
                   6628:             $env{'form.scantron_lastbubblepoints'}.'</tt></td></tr>';
                   6629:     }
1.492     albertel 6630:     return ('
1.203     albertel 6631: <p>
1.492     albertel 6632: <span class="LC_warning">
1.705     raeburn  6633: '.&mt("Please double check the information below before clicking on '[_1]'",&mt($button_text)).'</span>
1.203     albertel 6634: </p>
                   6635: <table>
1.492     albertel 6636: <tr><td><b>'.&mt('Sequence to be Graded:').'</b></td><td>'.$title.'</td></tr>
                   6637: <tr><td><b>'.&mt('Data File that will be used:').'</b></td><td><tt>'.$env{'form.scantron_selectfile'}.'</tt></td></tr>
1.663     raeburn  6638: '.$CODElist.$lastbubblepoints.'
1.203     albertel 6639: </table>
1.680     raeburn  6640: <p> '.&mt("If this information is correct, please click on '[_1]'.",&mt($button_text)).'<br />
1.650     raeburn  6641: '.&mt('If something is incorrect, please return to [_1]Grade/Manage/Review Bubblesheets[_2] to start over.','<a href="/adm/grades?symb='.$symb.'&command=scantron_selectphase" class="LC_info">','</a>').'</p>
1.203     albertel 6642: 
                   6643: <br />
1.492     albertel 6644: ');
1.203     albertel 6645: }
                   6646: 
1.423     albertel 6647: =pod
                   6648: 
                   6649: =item scantron_do_warning
                   6650: 
1.424     albertel 6651:    Check if the operator has picked something for all required
                   6652:    fields. Error out if something is missing.
                   6653: 
1.423     albertel 6654: =cut
                   6655: 
1.203     albertel 6656: sub scantron_do_warning {
1.608     www      6657:     my ($r,$symb)=@_;
1.203     albertel 6658:     if (!$symb) {return '';}
1.324     albertel 6659:     my $default_form_data=&defaultFormData($symb);
1.203     albertel 6660:     $r->print(&scantron_form_start().$default_form_data);
1.257     albertel 6661:     if ( $env{'form.selectpage'} eq '' ||
                   6662: 	 $env{'form.scantron_selectfile'} eq '' ||
                   6663: 	 $env{'form.scantron_format'} eq '' ) {
1.642     raeburn  6664: 	$r->print("<p>".&mt('You have forgotten to specify some information. Please go Back and try again.')."</p>");
1.257     albertel 6665: 	if ( $env{'form.selectpage'} eq '') {
1.492     albertel 6666: 	    $r->print('<p><span class="LC_error">'.&mt('You have not selected a Sequence to grade').'</span></p>');
1.237     albertel 6667: 	} 
1.257     albertel 6668: 	if ( $env{'form.scantron_selectfile'} eq '') {
1.642     raeburn  6669: 	    $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 6670: 	} 
1.257     albertel 6671: 	if ( $env{'form.scantron_format'} eq '') {
1.642     raeburn  6672: 	    $r->print('<p><span class="LC_error">'.&mt("You have not selected the format of the student's response data.").'</span></p>');
1.237     albertel 6673: 	} 
                   6674:     } else {
1.650     raeburn  6675: 	my $warning=&scantron_warning_screen('Grading: Validate Records',$symb);
1.663     raeburn  6676:         my $bubbledbyhand=&hand_bubble_option();
1.492     albertel 6677: 	$r->print('
1.663     raeburn  6678: '.$warning.$bubbledbyhand.'
1.492     albertel 6679: <input type="submit" name="submit" value="'.&mt('Grading: Validate Records').'" />
1.203     albertel 6680: <input type="hidden" name="command" value="scantron_validate" />
1.492     albertel 6681: ');
1.237     albertel 6682:     }
1.614     www      6683:     $r->print("</form><br />");
1.203     albertel 6684:     return '';
                   6685: }
                   6686: 
1.423     albertel 6687: =pod
                   6688: 
                   6689: =item scantron_form_start
                   6690: 
1.424     albertel 6691:     html hidden input for remembering all selected grading options
                   6692: 
1.423     albertel 6693: =cut
                   6694: 
1.203     albertel 6695: sub scantron_form_start {
                   6696:     my ($max_bubble)=@_;
                   6697:     my $result= <<SCANTRONFORM;
                   6698: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="scantronupload">
1.257     albertel 6699:   <input type="hidden" name="selectpage" value="$env{'form.selectpage'}" />
                   6700:   <input type="hidden" name="scantron_format" value="$env{'form.scantron_format'}" />
                   6701:   <input type="hidden" name="scantron_selectfile" value="$env{'form.scantron_selectfile'}" />
1.218     albertel 6702:   <input type="hidden" name="scantron_maxbubble" value="$max_bubble" />
1.257     albertel 6703:   <input type="hidden" name="scantron_CODElist" value="$env{'form.scantron_CODElist'}" />
                   6704:   <input type="hidden" name="scantron_CODEunique" value="$env{'form.scantron_CODEunique'}" />
                   6705:   <input type="hidden" name="scantron_options_redo" value="$env{'form.scantron_options_redo'}" />
                   6706:   <input type="hidden" name="scantron_options_ignore" value="$env{'form.scantron_options_ignore'}" />
1.331     albertel 6707:   <input type="hidden" name="scantron_options_hidden" value="$env{'form.scantron_options_hidden'}" />
1.203     albertel 6708: SCANTRONFORM
1.447     foxr     6709: 
                   6710:   my $line = 0;
                   6711:     while (defined($env{"form.scantron.bubblelines.$line"})) {
                   6712:        my $chunk =
                   6713: 	   '<input type="hidden" name="scantron.bubblelines.'.$line.'" value="'.$env{"form.scantron.bubblelines.$line"}.'" />'."\n";
1.448     foxr     6714:        $chunk .=
                   6715: 	   '<input type="hidden" name="scantron.first_bubble_line.'.$line.'" value="'.$env{"form.scantron.first_bubble_line.$line"}.'" />'."\n";
1.503     raeburn  6716:        $chunk .= 
                   6717:            '<input type="hidden" name="scantron.sub_bubblelines.'.$line.'" value="'.$env{"form.scantron.sub_bubblelines.$line"}.'" />'."\n";
1.504     raeburn  6718:        $chunk .=
                   6719:            '<input type="hidden" name="scantron.responsetype.'.$line.'" value="'.$env{"form.scantron.responsetype.$line"}.'" />'."\n";
1.691     raeburn  6720:        $chunk .=
                   6721:            '<input type="hidden" name="scantron.residpart.'.$line.'" value="'.$env{"form.scantron.residpart.$line"}.'" />'."\n";
1.447     foxr     6722:        $result .= $chunk;
                   6723:        $line++;
1.691     raeburn  6724:     }
1.203     albertel 6725:     return $result;
                   6726: }
                   6727: 
1.423     albertel 6728: =pod
                   6729: 
                   6730: =item scantron_validate_file
                   6731: 
1.659     raeburn  6732:     Dispatch routine for doing validation of a bubblesheet data file.
1.424     albertel 6733: 
                   6734:     Also processes any necessary information resets that need to
                   6735:     occur before validation begins (ignore previous corrections,
                   6736:     restarting the skipped records processing)
                   6737: 
1.423     albertel 6738: =cut
                   6739: 
1.157     albertel 6740: sub scantron_validate_file {
1.608     www      6741:     my ($r,$symb) = @_;
1.157     albertel 6742:     if (!$symb) {return '';}
1.324     albertel 6743:     my $default_form_data=&defaultFormData($symb);
1.200     albertel 6744:     
1.703     bisitz   6745:     # do the detection of only doing skipped records first before we delete
1.424     albertel 6746:     # them when doing the corrections reset
1.257     albertel 6747:     if ($env{'form.scantron_options_redo'} ne 'redo_skipped_ready') {
1.200     albertel 6748: 	&reset_skipping_status();
                   6749:     }
1.257     albertel 6750:     if ($env{'form.scantron_options_redo'} eq 'redo_skipped') {
1.200     albertel 6751: 	&remember_current_skipped();
1.257     albertel 6752: 	$env{'form.scantron_options_redo'}='redo_skipped_ready';
1.200     albertel 6753:     }
                   6754: 
1.257     albertel 6755:     if ($env{'form.scantron_options_ignore'} eq 'ignore_corrections') {
1.200     albertel 6756: 	&check_for_error($r,&scantron_remove_file('corrected'));
                   6757: 	&check_for_error($r,&scantron_remove_file('skipped'));
                   6758: 	&check_for_error($r,&scantron_remove_scan_data());
1.257     albertel 6759: 	$env{'form.scantron_options_ignore'}='done';
1.192     albertel 6760:     }
1.200     albertel 6761: 
1.257     albertel 6762:     if ($env{'form.scantron_corrections'}) {
1.157     albertel 6763: 	&scantron_process_corrections($r);
                   6764:     }
1.503     raeburn  6765:     $r->print('<p>'.&mt('Gathering necessary information.').'</p>');$r->rflush();
1.157     albertel 6766:     #get the student pick code ready
                   6767:     $r->print(&Apache::loncommon::studentbrowser_javascript());
1.582     raeburn  6768:     my $nav_error;
1.649     raeburn  6769:     my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
                   6770:     my $max_bubble=&scantron_get_maxbubble(\$nav_error,\%scantron_config);
1.582     raeburn  6771:     if ($nav_error) {
                   6772:         $r->print(&navmap_errormsg());
                   6773:         return '';
                   6774:     }
1.203     albertel 6775:     my $result=&scantron_form_start($max_bubble).$default_form_data;
1.663     raeburn  6776:     if ($env{'form.scantron_lastbubblepoints'} ne '') {
                   6777:         $result .= '<input type="hidden" name="scantron_lastbubblepoints" value="'.$env{'form.scantron_lastbubblepoints'}.'" />';
                   6778:     }
1.157     albertel 6779:     $r->print($result);
                   6780:     
1.334     albertel 6781:     my @validate_phases=( 'sequence',
                   6782: 			  'ID',
1.157     albertel 6783: 			  'CODE',
                   6784: 			  'doublebubble',
                   6785: 			  'missingbubbles');
1.257     albertel 6786:     if (!$env{'form.validatepass'}) {
                   6787: 	$env{'form.validatepass'} = 0;
1.157     albertel 6788:     }
1.257     albertel 6789:     my $currentphase=$env{'form.validatepass'};
1.157     albertel 6790: 
1.448     foxr     6791: 
1.157     albertel 6792:     my $stop=0;
                   6793:     while (!$stop && $currentphase < scalar(@validate_phases)) {
1.503     raeburn  6794: 	$r->print(&mt('Validating '.$validate_phases[$currentphase]).'<br />');
1.157     albertel 6795: 	$r->rflush();
1.691     raeburn  6796:      
1.157     albertel 6797: 	my $which="scantron_validate_".$validate_phases[$currentphase];
                   6798: 	{
                   6799: 	    no strict 'refs';
                   6800: 	    ($stop,$currentphase)=&$which($r,$currentphase);
                   6801: 	}
                   6802:     }
                   6803:     if (!$stop) {
1.650     raeburn  6804: 	my $warning=&scantron_warning_screen('Start Grading',$symb);
1.542     raeburn  6805: 	$r->print(&mt('Validation process complete.').'<br />'.
                   6806:                   $warning.
                   6807:                   &mt('Perform verification for each student after storage of submissions?').
                   6808:                   '&nbsp;<span class="LC_nobreak"><label>'.
                   6809:                   '<input type="radio" name="verifyrecord" value="1" />'.&mt('Yes').'</label>'.
                   6810:                   ('&nbsp;'x3).'<label>'.
                   6811:                   '<input type="radio" name="verifyrecord" value="0" checked="checked" />'.&mt('No').
                   6812:                   '</label></span><br />'.
                   6813:                   &mt('Grading will take longer if you use verification.').'<br />'.
1.650     raeburn  6814:                   &mt('Otherwise, Grade/Manage/Review Bubblesheets [_1] Review bubblesheet data can be used once grading is complete.','&raquo;').'<br /><br />'.
1.542     raeburn  6815:                   '<input type="submit" name="submit" value="'.&mt('Start Grading').'" />'.
                   6816:                   '<input type="hidden" name="command" value="scantron_process" />'."\n");
1.157     albertel 6817:     } else {
                   6818: 	$r->print('<input type="hidden" name="command" value="scantron_validate" />');
                   6819: 	$r->print("<input type='hidden' name='validatepass' value='".$currentphase."' />");
                   6820:     }
                   6821:     if ($stop) {
1.334     albertel 6822: 	if ($validate_phases[$currentphase] eq 'sequence') {
1.539     riegler  6823: 	    $r->print('<input type="submit" name="submit" value="'.&mt('Ignore').' &rarr; " />');
1.492     albertel 6824: 	    $r->print(' '.&mt('this error').' <br />');
1.334     albertel 6825: 
1.650     raeburn  6826: 	    $r->print('<p>'.&mt('Or return to [_1]Grade/Manage/Review Bubblesheets[_2] to start over.','<a href="/adm/grades?symb='.$symb.'&command=scantron_selectphase" class="LC_info">','</a>').'</p>');
1.334     albertel 6827: 	} else {
1.503     raeburn  6828:             if ($validate_phases[$currentphase] eq 'doublebubble' || $validate_phases[$currentphase] eq 'missingbubbles') {
1.539     riegler  6829: 	        $r->print('<input type="button" name="submitbutton" value="'.&mt('Continue').' &rarr;" onclick="javascript:verify_bubble_radio(this.form)" />');
1.503     raeburn  6830:             } else {
1.539     riegler  6831:                 $r->print('<input type="submit" name="submit" value="'.&mt('Continue').' &rarr;" />');
1.503     raeburn  6832:             }
1.492     albertel 6833: 	    $r->print(' '.&mt('using corrected info').' <br />');
                   6834: 	    $r->print("<input type='submit' value='".&mt("Skip")."' name='scantron_skip_record' />");
                   6835: 	    $r->print(" ".&mt("this scanline saving it for later."));
1.334     albertel 6836: 	}
1.157     albertel 6837:     }
1.614     www      6838:     $r->print(" </form><br />");
1.157     albertel 6839:     return '';
                   6840: }
                   6841: 
1.423     albertel 6842: 
                   6843: =pod
                   6844: 
                   6845: =item scantron_remove_file
                   6846: 
1.659     raeburn  6847:    Removes the requested bubblesheet data file, makes sure that
1.424     albertel 6848:    scantron_original_<filename> is never removed
                   6849: 
                   6850: 
1.423     albertel 6851: =cut
                   6852: 
1.200     albertel 6853: sub scantron_remove_file {
1.192     albertel 6854:     my ($which)=@_;
1.257     albertel 6855:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   6856:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1.192     albertel 6857:     my $file='scantron_';
1.200     albertel 6858:     if ($which eq 'corrected' || $which eq 'skipped') {
                   6859: 	$file.=$which.'_';
1.192     albertel 6860:     } else {
                   6861: 	return 'refused';
                   6862:     }
1.257     albertel 6863:     $file.=$env{'form.scantron_selectfile'};
1.200     albertel 6864:     return &Apache::lonnet::removeuserfile($cname,$cdom,$file);
                   6865: }
                   6866: 
1.423     albertel 6867: 
                   6868: =pod
                   6869: 
                   6870: =item scantron_remove_scan_data
                   6871: 
1.659     raeburn  6872:    Removes all scan_data correction for the requested bubblesheet
1.424     albertel 6873:    data file.  (In the case that both the are doing skipped records we need
                   6874:    to remember the old skipped lines for the time being so that element
                   6875:    persists for a while.)
                   6876: 
1.423     albertel 6877: =cut
                   6878: 
1.200     albertel 6879: sub scantron_remove_scan_data {
1.257     albertel 6880:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   6881:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1.192     albertel 6882:     my @keys=&Apache::lonnet::getkeys('nohist_scantrondata',$cdom,$cname);
                   6883:     my @todelete;
1.257     albertel 6884:     my $filename=$env{'form.scantron_selectfile'};
1.192     albertel 6885:     foreach my $key (@keys) {
                   6886: 	if ($key=~/^\Q$filename\E_/) {
1.257     albertel 6887: 	    if ($env{'form.scantron_options_redo'} eq 'redo_skipped_ready' &&
1.200     albertel 6888: 		$key=~/remember_skipping/) {
                   6889: 		next;
                   6890: 	    }
1.192     albertel 6891: 	    push(@todelete,$key);
                   6892: 	}
                   6893:     }
1.200     albertel 6894:     my $result;
1.192     albertel 6895:     if (@todelete) {
1.491     albertel 6896: 	$result = &Apache::lonnet::del('nohist_scantrondata',
                   6897: 				       \@todelete,$cdom,$cname);
                   6898:     } else {
                   6899: 	$result = 'ok';
1.192     albertel 6900:     }
                   6901:     return $result;
                   6902: }
                   6903: 
1.423     albertel 6904: 
                   6905: =pod
                   6906: 
                   6907: =item scantron_getfile
                   6908: 
1.659     raeburn  6909:     Fetches the requested bubblesheet data file (all 3 versions), and
1.424     albertel 6910:     the scan_data hash
                   6911:   
                   6912:   Arguments:
                   6913:     None
                   6914: 
                   6915:   Returns:
                   6916:     2 hash references
                   6917: 
                   6918:      - first one has 
                   6919:          orig      -
                   6920:          corrected -
                   6921:          skipped   -  each of which points to an array ref of the specified
                   6922:                       file broken up into individual lines
                   6923:          count     - number of scanlines
                   6924:  
                   6925:      - second is the scan_data hash possible keys are
1.425     albertel 6926:        ($number refers to scanline numbered $number and thus the key affects
                   6927:         only that scanline
                   6928:         $bubline refers to the specific bubble line element and the aspects
                   6929:         refers to that specific bubble line element)
                   6930: 
                   6931:        $number.user - username:domain to use
                   6932:        $number.CODE_ignore_dup 
                   6933:                     - ignore the duplicate CODE error 
                   6934:        $number.useCODE
                   6935:                     - use the CODE in the scanline as is
                   6936:        $number.no_bubble.$bubline
                   6937:                     - it is valid that there is no bubbled in bubble
                   6938:                       at $number $bubline
                   6939:        remember_skipping
                   6940:                     - a frozen hash containing keys of $number and values
                   6941:                       of either 
                   6942:                         1 - we are on a 'do skipped records pass' and plan
                   6943:                             on processing this line
                   6944:                         2 - we are on a 'do skipped records pass' and this
                   6945:                             scanline has been marked to skip yet again
1.424     albertel 6946: 
1.423     albertel 6947: =cut
                   6948: 
1.157     albertel 6949: sub scantron_getfile {
1.200     albertel 6950:     #FIXME really would prefer a scantron directory
1.257     albertel 6951:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   6952:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1.157     albertel 6953:     my $lines;
                   6954:     $lines=&Apache::lonnet::getfile('/uploaded/'.$cdom.'/'.$cname.'/'.
1.257     albertel 6955: 		       'scantron_orig_'.$env{'form.scantron_selectfile'});
1.157     albertel 6956:     my %scanlines;
                   6957:     $scanlines{'orig'}=[(split("\n",$lines,-1))];
                   6958:     my $temp=$scanlines{'orig'};
                   6959:     $scanlines{'count'}=$#$temp;
                   6960: 
                   6961:     $lines=&Apache::lonnet::getfile('/uploaded/'.$cdom.'/'.$cname.'/'.
1.257     albertel 6962: 		       'scantron_corrected_'.$env{'form.scantron_selectfile'});
1.157     albertel 6963:     if ($lines eq '-1') {
                   6964: 	$scanlines{'corrected'}=[];
                   6965:     } else {
                   6966: 	$scanlines{'corrected'}=[(split("\n",$lines,-1))];
                   6967:     }
                   6968:     $lines=&Apache::lonnet::getfile('/uploaded/'.$cdom.'/'.$cname.'/'.
1.257     albertel 6969: 		       'scantron_skipped_'.$env{'form.scantron_selectfile'});
1.157     albertel 6970:     if ($lines eq '-1') {
                   6971: 	$scanlines{'skipped'}=[];
                   6972:     } else {
                   6973: 	$scanlines{'skipped'}=[(split("\n",$lines,-1))];
                   6974:     }
1.175     albertel 6975:     my @tmp=&Apache::lonnet::dump('nohist_scantrondata',$cdom,$cname);
1.157     albertel 6976:     if ($tmp[0] =~ /^(error:|no_such_host)/) { @tmp=(); }
                   6977:     my %scan_data = @tmp;
                   6978:     return (\%scanlines,\%scan_data);
                   6979: }
                   6980: 
1.423     albertel 6981: =pod
                   6982: 
                   6983: =item lonnet_putfile
                   6984: 
1.424     albertel 6985:    Wrapper routine to call &Apache::lonnet::finishuserfileupload
                   6986: 
                   6987:  Arguments:
                   6988:    $contents - data to store
                   6989:    $filename - filename to store $contents into
                   6990: 
                   6991:  Returns:
                   6992:    result value from &Apache::lonnet::finishuserfileupload
                   6993: 
1.423     albertel 6994: =cut
                   6995: 
1.157     albertel 6996: sub lonnet_putfile {
                   6997:     my ($contents,$filename)=@_;
1.257     albertel 6998:     my $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   6999:     my $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
                   7000:     $env{'form.sillywaytopassafilearound'}=$contents;
1.275     albertel 7001:     &Apache::lonnet::finishuserfileupload($docuname,$docudom,'sillywaytopassafilearound',$filename);
1.157     albertel 7002: 
                   7003: }
                   7004: 
1.423     albertel 7005: =pod
                   7006: 
                   7007: =item scantron_putfile
                   7008: 
1.659     raeburn  7009:     Stores the current version of the bubblesheet data files, and the
1.424     albertel 7010:     scan_data hash. (Does not modify the original version only the
                   7011:     corrected and skipped versions.
                   7012: 
                   7013:  Arguments:
                   7014:     $scanlines - hash ref that looks like the first return value from
                   7015:                  &scantron_getfile()
                   7016:     $scan_data - hash ref that looks like the second return value from
                   7017:                  &scantron_getfile()
                   7018: 
1.423     albertel 7019: =cut
                   7020: 
1.157     albertel 7021: sub scantron_putfile {
                   7022:     my ($scanlines,$scan_data) = @_;
1.200     albertel 7023:     #FIXME really would prefer a scantron directory
1.257     albertel 7024:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   7025:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1.200     albertel 7026:     if ($scanlines) {
                   7027: 	my $prefix='scantron_';
1.157     albertel 7028: # no need to update orig, shouldn't change
                   7029: #   &lonnet_putfile(join("\n",@{$scanlines->{'orig'}}),$prefix.'orig_'.
1.257     albertel 7030: #		    $env{'form.scantron_selectfile'});
1.200     albertel 7031: 	&lonnet_putfile(join("\n",@{$scanlines->{'corrected'}}),
                   7032: 			$prefix.'corrected_'.
1.257     albertel 7033: 			$env{'form.scantron_selectfile'});
1.200     albertel 7034: 	&lonnet_putfile(join("\n",@{$scanlines->{'skipped'}}),
                   7035: 			$prefix.'skipped_'.
1.257     albertel 7036: 			$env{'form.scantron_selectfile'});
1.200     albertel 7037:     }
1.175     albertel 7038:     &Apache::lonnet::put('nohist_scantrondata',$scan_data,$cdom,$cname);
1.157     albertel 7039: }
                   7040: 
1.423     albertel 7041: =pod
                   7042: 
                   7043: =item scantron_get_line
                   7044: 
1.424     albertel 7045:    Returns the correct version of the scanline
                   7046: 
                   7047:  Arguments:
                   7048:     $scanlines - hash ref that looks like the first return value from
                   7049:                  &scantron_getfile()
                   7050:     $scan_data - hash ref that looks like the second return value from
                   7051:                  &scantron_getfile()
                   7052:     $i         - number of the requested line (starts at 0)
                   7053: 
                   7054:  Returns:
                   7055:    A scanline, (either the original or the corrected one if it
                   7056:    exists), or undef if the requested scanline should be
                   7057:    skipped. (Either because it's an skipped scanline, or it's an
                   7058:    unskipped scanline and we are not doing a 'do skipped scanlines'
                   7059:    pass.
                   7060: 
1.423     albertel 7061: =cut
                   7062: 
1.157     albertel 7063: sub scantron_get_line {
1.200     albertel 7064:     my ($scanlines,$scan_data,$i)=@_;
1.376     albertel 7065:     if (&should_be_skipped($scanlines,$scan_data,$i)) { return undef; }
                   7066:     #if ($scanlines->{'skipped'}[$i]) { return undef; }
1.157     albertel 7067:     if ($scanlines->{'corrected'}[$i]) {return $scanlines->{'corrected'}[$i];}
                   7068:     return $scanlines->{'orig'}[$i]; 
                   7069: }
                   7070: 
1.423     albertel 7071: =pod
                   7072: 
                   7073: =item scantron_todo_count
                   7074: 
1.424     albertel 7075:     Counts the number of scanlines that need processing.
                   7076: 
                   7077:  Arguments:
                   7078:     $scanlines - hash ref that looks like the first return value from
                   7079:                  &scantron_getfile()
                   7080:     $scan_data - hash ref that looks like the second return value from
                   7081:                  &scantron_getfile()
                   7082: 
                   7083:  Returns:
                   7084:     $count - number of scanlines to process
                   7085: 
1.423     albertel 7086: =cut
                   7087: 
1.200     albertel 7088: sub get_todo_count {
                   7089:     my ($scanlines,$scan_data)=@_;
                   7090:     my $count=0;
                   7091:     for (my $i=0;$i<=$scanlines->{'count'};$i++) {
                   7092: 	my $line=&scantron_get_line($scanlines,$scan_data,$i);
                   7093: 	if ($line=~/^[\s\cz]*$/) { next; }
                   7094: 	$count++;
                   7095:     }
                   7096:     return $count;
                   7097: }
                   7098: 
1.423     albertel 7099: =pod
                   7100: 
                   7101: =item scantron_put_line
                   7102: 
1.659     raeburn  7103:     Updates the 'corrected' or 'skipped' versions of the bubblesheet
1.424     albertel 7104:     data file.
                   7105: 
                   7106:  Arguments:
                   7107:     $scanlines - hash ref that looks like the first return value from
                   7108:                  &scantron_getfile()
                   7109:     $scan_data - hash ref that looks like the second return value from
                   7110:                  &scantron_getfile()
                   7111:     $i         - line number to update
                   7112:     $newline   - contents of the updated scanline
                   7113:     $skip      - if true make the line for skipping and update the
                   7114:                  'skipped' file
                   7115: 
1.423     albertel 7116: =cut
                   7117: 
1.157     albertel 7118: sub scantron_put_line {
1.200     albertel 7119:     my ($scanlines,$scan_data,$i,$newline,$skip)=@_;
1.157     albertel 7120:     if ($skip) {
                   7121: 	$scanlines->{'skipped'}[$i]=$newline;
1.376     albertel 7122: 	&start_skipping($scan_data,$i);
1.157     albertel 7123: 	return;
                   7124:     }
                   7125:     $scanlines->{'corrected'}[$i]=$newline;
                   7126: }
                   7127: 
1.423     albertel 7128: =pod
                   7129: 
                   7130: =item scantron_clear_skip
                   7131: 
1.424     albertel 7132:    Remove a line from the 'skipped' file
                   7133: 
                   7134:  Arguments:
                   7135:     $scanlines - hash ref that looks like the first return value from
                   7136:                  &scantron_getfile()
                   7137:     $scan_data - hash ref that looks like the second return value from
                   7138:                  &scantron_getfile()
                   7139:     $i         - line number to update
                   7140: 
1.423     albertel 7141: =cut
                   7142: 
1.376     albertel 7143: sub scantron_clear_skip {
                   7144:     my ($scanlines,$scan_data,$i)=@_;
                   7145:     if (exists($scanlines->{'skipped'}[$i])) {
                   7146: 	undef($scanlines->{'skipped'}[$i]);
                   7147: 	return 1;
                   7148:     }
                   7149:     return 0;
                   7150: }
                   7151: 
1.423     albertel 7152: =pod
                   7153: 
                   7154: =item scantron_filter_not_exam
                   7155: 
1.424     albertel 7156:    Filter routine used by &Apache::lonnavmaps::retrieveResources(), to
                   7157:    filter out resources that are not marked as 'exam' mode
                   7158: 
1.423     albertel 7159: =cut
                   7160: 
1.334     albertel 7161: sub scantron_filter_not_exam {
                   7162:     my ($curres)=@_;
                   7163:     
                   7164:     if (ref($curres) && $curres->is_problem() && !$curres->is_exam()) {
                   7165: 	# if the user has asked to not have either hidden
                   7166: 	# or 'randomout' controlled resources to be graded
                   7167: 	# don't include them
                   7168: 	if ($env{'form.scantron_options_hidden'} eq 'ignore_hidden'
                   7169: 	    && $curres->randomout) {
                   7170: 	    return 0;
                   7171: 	}
                   7172: 	return 1;
                   7173:     }
                   7174:     return 0;
                   7175: }
                   7176: 
1.423     albertel 7177: =pod
                   7178: 
                   7179: =item scantron_validate_sequence
                   7180: 
1.424     albertel 7181:     Validates the selected sequence, checking for resource that are
                   7182:     not set to exam mode.
                   7183: 
1.423     albertel 7184: =cut
                   7185: 
1.334     albertel 7186: sub scantron_validate_sequence {
                   7187:     my ($r,$currentphase) = @_;
                   7188: 
                   7189:     my $navmap=Apache::lonnavmaps::navmap->new();
1.582     raeburn  7190:     unless (ref($navmap)) {
                   7191:         $r->print(&navmap_errormsg());
                   7192:         return (1,$currentphase);
                   7193:     }
1.334     albertel 7194:     my (undef,undef,$sequence)=
                   7195: 	&Apache::lonnet::decode_symb($env{'form.selectpage'});
                   7196: 
                   7197:     my $map=$navmap->getResourceByUrl($sequence);
                   7198: 
                   7199:     $r->print('<input type="hidden" name="validate_sequence_exam"
                   7200:                                     value="ignore" />');
                   7201:     if ($env{'form.validate_sequence_exam'} ne 'ignore') {
                   7202: 	my @resources=
                   7203: 	    $navmap->retrieveResources($map,\&scantron_filter_not_exam,1,0);
                   7204: 	if (@resources) {
1.675     bisitz   7205: 	    $r->print(
                   7206:                 '<p class="LC_warning">'
                   7207:                .&mt('Some resources in the sequence currently are not set to'
1.684     bisitz   7208:                    .' bubblesheet exam mode. Grading these resources currently may not'
1.675     bisitz   7209:                    .' work correctly.')
                   7210:                .'</p>'
                   7211:             );
1.334     albertel 7212: 	    return (1,$currentphase);
                   7213: 	}
                   7214:     }
                   7215: 
                   7216:     return (0,$currentphase+1);
                   7217: }
                   7218: 
1.423     albertel 7219: 
                   7220: 
1.157     albertel 7221: sub scantron_validate_ID {
                   7222:     my ($r,$currentphase) = @_;
                   7223:     
                   7224:     #get student info
                   7225:     my $classlist=&Apache::loncoursedata::get_classlist();
                   7226:     my %idmap=&username_to_idmap($classlist);
                   7227: 
                   7228:     #get scantron line setup
1.257     albertel 7229:     my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
1.157     albertel 7230:     my ($scanlines,$scan_data)=&scantron_getfile();
1.582     raeburn  7231: 
                   7232:     my $nav_error;
1.649     raeburn  7233:     &scantron_get_maxbubble(\$nav_error,\%scantron_config); # parse needs the bubble_lines.. array.
1.582     raeburn  7234:     if ($nav_error) {
                   7235:         $r->print(&navmap_errormsg());
                   7236:         return(1,$currentphase);
                   7237:     }
1.157     albertel 7238: 
                   7239:     my %found=('ids'=>{},'usernames'=>{});
                   7240:     for (my $i=0;$i<=$scanlines->{'count'};$i++) {
1.200     albertel 7241: 	my $line=&scantron_get_line($scanlines,$scan_data,$i);
1.157     albertel 7242: 	if ($line=~/^[\s\cz]*$/) { next; }
                   7243: 	my $scan_record=&scantron_parse_scanline($line,$i,\%scantron_config,
                   7244: 						 $scan_data);
                   7245: 	my $id=$$scan_record{'scantron.ID'};
                   7246: 	my $found;
                   7247: 	foreach my $checkid (keys(%idmap)) {
                   7248: 	    if (lc($checkid) eq lc($id)) { $found=$checkid;last; }
                   7249: 	}
                   7250: 	if ($found) {
                   7251: 	    my $username=$idmap{$found};
                   7252: 	    if ($found{'ids'}{$found}) {
                   7253: 		&scantron_get_correction($r,$i,$scan_record,\%scantron_config,
                   7254: 					 $line,'duplicateID',$found);
1.194     albertel 7255: 		return(1,$currentphase);
1.157     albertel 7256: 	    } elsif ($found{'usernames'}{$username}) {
                   7257: 		&scantron_get_correction($r,$i,$scan_record,\%scantron_config,
                   7258: 					 $line,'duplicateID',$username);
1.194     albertel 7259: 		return(1,$currentphase);
1.157     albertel 7260: 	    }
1.186     albertel 7261: 	    #FIXME store away line we previously saw the ID on to use above
1.157     albertel 7262: 	    $found{'ids'}{$found}++;
                   7263: 	    $found{'usernames'}{$username}++;
                   7264: 	} else {
                   7265: 	    if ($id =~ /^\s*$/) {
1.158     albertel 7266: 		my $username=&scan_data($scan_data,"$i.user");
1.157     albertel 7267: 		if (defined($username) && $found{'usernames'}{$username}) {
                   7268: 		    &scantron_get_correction($r,$i,$scan_record,
                   7269: 					     \%scantron_config,
                   7270: 					     $line,'duplicateID',$username);
1.194     albertel 7271: 		    return(1,$currentphase);
1.157     albertel 7272: 		} elsif (!defined($username)) {
                   7273: 		    &scantron_get_correction($r,$i,$scan_record,
                   7274: 					     \%scantron_config,
                   7275: 					     $line,'incorrectID');
1.194     albertel 7276: 		    return(1,$currentphase);
1.157     albertel 7277: 		}
                   7278: 		$found{'usernames'}{$username}++;
                   7279: 	    } else {
                   7280: 		&scantron_get_correction($r,$i,$scan_record,\%scantron_config,
                   7281: 					 $line,'incorrectID');
1.194     albertel 7282: 		return(1,$currentphase);
1.157     albertel 7283: 	    }
                   7284: 	}
                   7285:     }
                   7286: 
                   7287:     return (0,$currentphase+1);
                   7288: }
                   7289: 
1.423     albertel 7290: 
1.157     albertel 7291: sub scantron_get_correction {
1.691     raeburn  7292:     my ($r,$i,$scan_record,$scan_config,$line,$error,$arg,
                   7293:         $randomorder,$randompick,$respnumlookup,$startline)=@_;
1.454     banghart 7294: #FIXME in the case of a duplicated ID the previous line, probably need
1.157     albertel 7295: #to show both the current line and the previous one and allow skipping
                   7296: #the previous one or the current one
                   7297: 
1.333     albertel 7298:     if ( $$scan_record{'scantron.PaperID'} =~ /\S/) {
1.658     bisitz   7299:         $r->print(
                   7300:             '<p class="LC_warning">'
                   7301:            .&mt('An error was detected ([_1]) for PaperID [_2]',
                   7302:                 "<b>$error</b>",
                   7303:                 '<tt>'.$$scan_record{'scantron.PaperID'}.'</tt>')
                   7304:            ."</p> \n");
1.157     albertel 7305:     } else {
1.658     bisitz   7306:         $r->print(
                   7307:             '<p class="LC_warning">'
                   7308:            .&mt('An error was detected ([_1]) in scanline [_2] [_3]',
                   7309:                 "<b>$error</b>", $i, "<pre>$line</pre>")
                   7310:            ."</p> \n");
                   7311:     }
                   7312:     my $message =
                   7313:         '<p>'
                   7314:        .&mt('The ID on the form is [_1]',
                   7315:             "<tt>$$scan_record{'scantron.ID'}</tt>")
                   7316:        .'<br />'
1.665     raeburn  7317:        .&mt('The name on the paper is [_1], [_2]',
1.658     bisitz   7318:             $$scan_record{'scantron.LastName'},
                   7319:             $$scan_record{'scantron.FirstName'})
                   7320:        .'</p>';
1.242     albertel 7321: 
1.157     albertel 7322:     $r->print('<input type="hidden" name="scantron_corrections" value="'.$error.'" />'."\n");
                   7323:     $r->print('<input type="hidden" name="scantron_line" value="'.$i.'" />'."\n");
1.503     raeburn  7324:                            # Array populated for doublebubble or
                   7325:     my @lines_to_correct;  # missingbubble errors to build javascript
                   7326:                            # to validate radio button checking   
                   7327: 
1.157     albertel 7328:     if ($error =~ /ID$/) {
1.186     albertel 7329: 	if ($error eq 'incorrectID') {
1.658     bisitz   7330:             $r->print('<p class="LC_warning">'.&mt("The encoded ID is not in the classlist").
1.492     albertel 7331: 		      "</p>\n");
1.157     albertel 7332: 	} elsif ($error eq 'duplicateID') {
1.658     bisitz   7333:             $r->print('<p class="LC_warning">'.&mt("The encoded ID has also been used by a previous paper [_1]",$arg)."</p>\n");
1.157     albertel 7334: 	}
1.242     albertel 7335: 	$r->print($message);
1.492     albertel 7336: 	$r->print("<p>".&mt("How should I handle this?")." <br /> \n");
1.157     albertel 7337: 	$r->print("\n<ul><li> ");
                   7338: 	#FIXME it would be nice if this sent back the user ID and
                   7339: 	#could do partial userID matches
                   7340: 	$r->print(&Apache::loncommon::selectstudent_link('scantronupload',
                   7341: 				       'scantron_username','scantron_domain'));
                   7342: 	$r->print(": <input type='text' name='scantron_username' value='' />");
1.685     bisitz   7343: 	$r->print("\n:\n".
1.257     albertel 7344: 		 &Apache::loncommon::select_dom_form($env{'request.role.domain'},'scantron_domain'));
1.157     albertel 7345: 
                   7346: 	$r->print('</li>');
1.186     albertel 7347:     } elsif ($error =~ /CODE$/) {
                   7348: 	if ($error eq 'incorrectCODE') {
1.658     bisitz   7349: 	    $r->print('<p class="LC_warning">'.&mt("The encoded CODE is not in the list of possible CODEs.")."</p>\n");
1.186     albertel 7350: 	} elsif ($error eq 'duplicateCODE') {
1.658     bisitz   7351: 	    $r->print('<p class="LC_warning">'.&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 7352: 	}
1.658     bisitz   7353: 	$r->print("<p>".&mt('The CODE on the form is [_1]',
                   7354: 			    "<tt>'$$scan_record{'scantron.CODE'}'</tt>")
                   7355:                  ."</p>\n");
1.242     albertel 7356: 	$r->print($message);
1.658     bisitz   7357: 	$r->print("<p>".&mt("How should I handle this?")."</p>\n");
1.187     albertel 7358: 	$r->print("\n<br /> ");
1.194     albertel 7359: 	my $i=0;
1.273     albertel 7360: 	if ($error eq 'incorrectCODE' 
                   7361: 	    && $$scan_record{'scantron.CODE'}=~/\S/ ) {
1.194     albertel 7362: 	    my ($max,$closest)=&scantron_get_closely_matching_CODEs($arg,$$scan_record{'scantron.CODE'});
1.278     albertel 7363: 	    if ($closest > 0) {
                   7364: 		foreach my $testcode (@{$closest}) {
                   7365: 		    my $checked='';
1.569     bisitz   7366: 		    if (!$i) { $checked=' checked="checked"'; }
1.492     albertel 7367: 		    $r->print("
                   7368:    <label>
1.569     bisitz   7369:        <input type='radio' name='scantron_CODE_resolution' value='use_closest_$i'$checked />
1.492     albertel 7370:        ".&mt("Use the similar CODE [_1] instead.",
                   7371: 	    "<b><tt>".$testcode."</tt></b>")."
                   7372:     </label>
                   7373:     <input type='hidden' name='scantron_CODE_closest_$i' value='$testcode' />");
1.278     albertel 7374: 		    $r->print("\n<br />");
                   7375: 		    $i++;
                   7376: 		}
1.194     albertel 7377: 	    }
                   7378: 	}
1.273     albertel 7379: 	if ($$scan_record{'scantron.CODE'}=~/\S/ ) {
1.569     bisitz   7380: 	    my $checked; if (!$i) { $checked=' checked="checked"'; }
1.492     albertel 7381: 	    $r->print("
                   7382:     <label>
1.569     bisitz   7383:         <input type='radio' name='scantron_CODE_resolution' value='use_unfound'$checked />
1.659     raeburn  7384:        ".&mt("Use the CODE [_1] that was on the paper, ignoring the error.",
1.492     albertel 7385: 	     "<b><tt>".$$scan_record{'scantron.CODE'}."</tt></b>")."
                   7386:     </label>");
1.273     albertel 7387: 	    $r->print("\n<br />");
                   7388: 	}
1.194     albertel 7389: 
1.597     wenzelju 7390: 	$r->print(&Apache::lonhtmlcommon::scripttag(<<ENDSCRIPT));
1.188     albertel 7391: function change_radio(field) {
1.190     albertel 7392:     var slct=document.scantronupload.scantron_CODE_resolution;
1.188     albertel 7393:     var i;
                   7394:     for (i=0;i<slct.length;i++) {
                   7395:         if (slct[i].value==field) { slct[i].checked=true; }
                   7396:     }
                   7397: }
                   7398: ENDSCRIPT
1.187     albertel 7399: 	my $href="/adm/pickcode?".
1.359     www      7400: 	   "form=".&escape("scantronupload").
                   7401: 	   "&scantron_format=".&escape($env{'form.scantron_format'}).
                   7402: 	   "&scantron_CODElist=".&escape($env{'form.scantron_CODElist'}).
                   7403: 	   "&curCODE=".&escape($$scan_record{'scantron.CODE'}).
                   7404: 	   "&scantron_selectfile=".&escape($env{'form.scantron_selectfile'});
1.332     albertel 7405: 	if ($env{'form.scantron_CODElist'} =~ /\S/) { 
1.492     albertel 7406: 	    $r->print("
                   7407:     <label>
                   7408:        <input type='radio' name='scantron_CODE_resolution' value='use_found' />
                   7409:        ".&mt("[_1]Select[_2] a CODE from the list of all CODEs and use it.",
                   7410: 	     "<a target='_blank' href='$href'>","</a>")."
                   7411:     </label> 
1.558     bisitz   7412:     ".&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 7413: 	    $r->print("\n<br />");
                   7414: 	}
1.492     albertel 7415: 	$r->print("
                   7416:     <label>
                   7417:        <input type='radio' name='scantron_CODE_resolution' value='use_typed' />
                   7418:        ".&mt("Use [_1] as the CODE.",
                   7419: 	     "</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 7420: 	$r->print("\n<br /><br />");
1.157     albertel 7421:     } elsif ($error eq 'doublebubble') {
1.658     bisitz   7422: 	$r->print('<p class="LC_warning">'.&mt("There have been multiple bubbles scanned for some question(s)")."</p>\n");
1.497     foxr     7423: 
                   7424: 	# The form field scantron_questions is acutally a list of line numbers.
                   7425: 	# represented by this form so:
                   7426: 
1.691     raeburn  7427: 	my $line_list = &questions_to_line_list($arg,$randomorder,$randompick,
                   7428:                                                 $respnumlookup,$startline);
1.497     foxr     7429: 
1.157     albertel 7430: 	$r->print('<input type="hidden" name="scantron_questions" value="'.
1.497     foxr     7431: 		  $line_list.'" />');
1.242     albertel 7432: 	$r->print($message);
1.492     albertel 7433: 	$r->print("<p>".&mt("Please indicate which bubble should be used for grading")."</p>");
1.157     albertel 7434: 	foreach my $question (@{$arg}) {
1.503     raeburn  7435: 	    my @linenums = &prompt_for_corrections($r,$question,$scan_config,
1.691     raeburn  7436:                                                    $scan_record, $error,
                   7437:                                                    $randomorder,$randompick,
                   7438:                                                    $respnumlookup,$startline);
1.524     raeburn  7439:             push(@lines_to_correct,@linenums);
1.157     albertel 7440: 	}
1.503     raeburn  7441:         $r->print(&verify_bubbles_checked(@lines_to_correct));
1.157     albertel 7442:     } elsif ($error eq 'missingbubble') {
1.658     bisitz   7443: 	$r->print('<p class="LC_warning">'.&mt("There have been [_1]no[_2] bubbles scanned for some question(s)",'<b>','</b>')."</p>\n");
1.242     albertel 7444: 	$r->print($message);
1.492     albertel 7445: 	$r->print("<p>".&mt("Please indicate which bubble should be used for grading.")."</p>");
1.503     raeburn  7446: 	$r->print(&mt("Some questions have no scanned bubbles.")."\n");
1.497     foxr     7447: 
1.503     raeburn  7448: 	# The form field scantron_questions is actually a list of line numbers not
1.497     foxr     7449: 	# a list of question numbers. Therefore:
                   7450: 	#
1.691     raeburn  7451: 
                   7452: 	my $line_list = &questions_to_line_list($arg,$randomorder,$randompick,
                   7453:                                                 $respnumlookup,$startline);
1.497     foxr     7454: 
1.157     albertel 7455: 	$r->print('<input type="hidden" name="scantron_questions" value="'.
1.497     foxr     7456: 		  $line_list.'" />');
1.157     albertel 7457: 	foreach my $question (@{$arg}) {
1.503     raeburn  7458: 	    my @linenums = &prompt_for_corrections($r,$question,$scan_config,
1.691     raeburn  7459:                                                    $scan_record, $error,
                   7460:                                                    $randomorder,$randompick,
                   7461:                                                    $respnumlookup,$startline);
1.524     raeburn  7462:             push(@lines_to_correct,@linenums);
1.157     albertel 7463: 	}
1.503     raeburn  7464:         $r->print(&verify_bubbles_checked(@lines_to_correct));
1.157     albertel 7465:     } else {
                   7466: 	$r->print("\n<ul>");
                   7467:     }
                   7468:     $r->print("\n</li></ul>");
1.497     foxr     7469: }
                   7470: 
1.503     raeburn  7471: sub verify_bubbles_checked {
                   7472:     my (@ansnums) = @_;
                   7473:     my $ansnumstr = join('","',@ansnums);
                   7474:     my $warning = &mt("A bubble or 'No bubble' selection has not been made for one or more lines.");
1.597     wenzelju 7475:     my $output = &Apache::lonhtmlcommon::scripttag((<<ENDSCRIPT));
1.503     raeburn  7476: function verify_bubble_radio(form) {
                   7477:     var ansnumArray = new Array ("$ansnumstr");
                   7478:     var need_bubble_count = 0;
                   7479:     for (var i=0; i<ansnumArray.length; i++) {
                   7480:         if (form.elements["scantron_correct_Q_"+ansnumArray[i]].length > 1) {
                   7481:             var bubble_picked = 0; 
                   7482:             for (var j=0; j<form.elements["scantron_correct_Q_"+ansnumArray[i]].length; j++) {
                   7483:                 if (form.elements["scantron_correct_Q_"+ansnumArray[i]][j].checked == true) {
                   7484:                     bubble_picked = 1;
                   7485:                 }
                   7486:             }
                   7487:             if (bubble_picked == 0) {
                   7488:                 need_bubble_count ++;
                   7489:             }
                   7490:         }
                   7491:     }
                   7492:     if (need_bubble_count) {
                   7493:         alert("$warning");
                   7494:         return;
                   7495:     }
                   7496:     form.submit(); 
                   7497: }
                   7498: ENDSCRIPT
                   7499:     return $output;
                   7500: }
                   7501: 
1.497     foxr     7502: =pod
                   7503: 
                   7504: =item  questions_to_line_list
1.157     albertel 7505: 
1.497     foxr     7506: Converts a list of questions into a string of comma separated
                   7507: line numbers in the answer sheet used by the questions.  This is
                   7508: used to fill in the scantron_questions form field.
                   7509: 
                   7510:   Arguments:
                   7511:      questions    - Reference to an array of questions.
1.691     raeburn  7512:      randomorder  - True if randomorder in use.
                   7513:      randompick   - True if randompick in use.
                   7514:      respnumlookup - Reference to HASH mapping question numbers in bubble lines
                   7515:                      for current line to question number used for same question
                   7516:                      in "Master Seqence" (as seen by Course Coordinator).
                   7517:      startline    - Reference to hash where key is question number (0 is first)
                   7518:                     and key is number of first bubble line for current student
                   7519:                     or code-based randompick and/or randomorder.
1.693     raeburn  7520: 
1.497     foxr     7521: =cut
                   7522: 
                   7523: 
                   7524: sub questions_to_line_list {
1.691     raeburn  7525:     my ($questions,$randomorder,$randompick,$respnumlookup,$startline) = @_;
1.497     foxr     7526:     my @lines;
                   7527: 
1.503     raeburn  7528:     foreach my $item (@{$questions}) {
                   7529:         my $question = $item;
                   7530:         my ($first,$count,$last);
                   7531:         if ($item =~ /^(\d+)\.(\d+)$/) {
                   7532:             $question = $1;
                   7533:             my $subquestion = $2;
1.691     raeburn  7534:             my $responsenum = $question-1;
                   7535:             if (($randomorder || $randompick) && (ref($respnumlookup) eq 'HASH')) {
                   7536:                 $responsenum = $respnumlookup->{$question-1};
                   7537:                 if (ref($startline) eq 'HASH') {
                   7538:                     $first = $startline->{$question-1} + 1;
                   7539:                 }
                   7540:             } else {
                   7541:                 $first = $first_bubble_line{$responsenum} + 1;
                   7542:             }
                   7543:             my @subans = split(/,/,$subdivided_bubble_lines{$responsenum});
1.503     raeburn  7544:             my $subcount = 1;
                   7545:             while ($subcount<$subquestion) {
                   7546:                 $first += $subans[$subcount-1];
                   7547:                 $subcount ++;
                   7548:             }
                   7549:             $count = $subans[$subquestion-1];
                   7550:         } else {
1.691     raeburn  7551:             my $responsenum = $question-1;
                   7552:             if (($randomorder || $randompick) && (ref($respnumlookup) eq 'HASH')) {
                   7553:                 $responsenum = $respnumlookup->{$question-1};
                   7554:                 if (ref($startline) eq 'HASH') {
                   7555:                     $first = $startline->{$question-1} + 1;
                   7556:                 }
                   7557:             } else {
                   7558:                 $first = $first_bubble_line{$responsenum} + 1;
                   7559:             }
                   7560: 	    $count   = $bubble_lines_per_response{$responsenum};
1.503     raeburn  7561:         }
1.506     raeburn  7562:         $last = $first+$count-1;
1.503     raeburn  7563:         push(@lines, ($first..$last));
1.497     foxr     7564:     }
                   7565:     return join(',', @lines);
                   7566: }
                   7567: 
                   7568: =pod 
                   7569: 
                   7570: =item prompt_for_corrections
                   7571: 
                   7572: Prompts for a potentially multiline correction to the
                   7573: user's bubbling (factors out common code from scantron_get_correction
                   7574: for multi and missing bubble cases).
                   7575: 
                   7576:  Arguments:
                   7577:    $r           - Apache request object.
                   7578:    $question    - The question number to prompt for.
                   7579:    $scan_config - The scantron file configuration hash.
                   7580:    $scan_record - Reference to the hash that has the the parsed scanlines.
1.503     raeburn  7581:    $error       - Type of error
1.691     raeburn  7582:    $randomorder - True if randomorder in use.
                   7583:    $randompick  - True if randompick in use.
                   7584:    $respnumlookup - Reference to HASH mapping question numbers in bubble lines
                   7585:                     for current line to question number used for same question
                   7586:                     in "Master Seqence" (as seen by Course Coordinator).
                   7587:    $startline   - Reference to hash where key is question number (0 is first)
                   7588:                   and value is number of first bubble line for current student
                   7589:                   or code-based randompick and/or randomorder.
                   7590: 
1.497     foxr     7591: 
                   7592:  Implicit inputs:
                   7593:    %bubble_lines_per_response   - Starting line numbers for each question.
                   7594:                                   Numbered from 0 (but question numbers are from
                   7595:                                   1.
                   7596:    %first_bubble_line           - Starting bubble line for each question.
1.509     raeburn  7597:    %subdivided_bubble_lines     - optionresponse, matchresponse and rankresponse 
                   7598:                                   type problems render as separate sub-questions, 
1.503     raeburn  7599:                                   in exam mode. This hash contains a 
                   7600:                                   comma-separated list of the lines per 
                   7601:                                   sub-question.
1.510     raeburn  7602:    %responsetype_per_response   - essayresponse, formularesponse,
                   7603:                                   stringresponse, imageresponse, reactionresponse,
                   7604:                                   and organicresponse type problem parts can have
1.503     raeburn  7605:                                   multiple lines per response if the weight
                   7606:                                   assigned exceeds 10.  In this case, only
                   7607:                                   one bubble per line is permitted, but more 
                   7608:                                   than one line might contain bubbles, e.g.
                   7609:                                   bubbling of: line 1 - J, line 2 - J, 
                   7610:                                   line 3 - B would assign 22 points.  
1.497     foxr     7611: 
                   7612: =cut
                   7613: 
                   7614: sub prompt_for_corrections {
1.691     raeburn  7615:     my ($r, $question, $scan_config, $scan_record, $error, $randomorder,
                   7616:         $randompick, $respnumlookup, $startline) = @_;
1.503     raeburn  7617:     my ($current_line,$lines);
                   7618:     my @linenums;
                   7619:     my $questionnum = $question;
1.691     raeburn  7620:     my ($first,$responsenum);
1.503     raeburn  7621:     if ($question =~ /^(\d+)\.(\d+)$/) {
                   7622:         $question = $1;
                   7623:         my $subquestion = $2;
1.691     raeburn  7624:         if (($randomorder || $randompick) && (ref($respnumlookup) eq 'HASH')) {
                   7625:             $responsenum = $respnumlookup->{$question-1};
                   7626:             if (ref($startline) eq 'HASH') {
                   7627:                 $first = $startline->{$question-1};
                   7628:             }
                   7629:         } else {
                   7630:             $responsenum = $question-1;
1.714     raeburn  7631:             $first = $first_bubble_line{$responsenum};
1.691     raeburn  7632:         }
                   7633:         $current_line = $first + 1 ;
                   7634:         my @subans = split(/,/,$subdivided_bubble_lines{$responsenum});
1.503     raeburn  7635:         my $subcount = 1;
                   7636:         while ($subcount<$subquestion) {
                   7637:             $current_line += $subans[$subcount-1];
                   7638:             $subcount ++;
                   7639:         }
                   7640:         $lines = $subans[$subquestion-1];
                   7641:     } else {
1.691     raeburn  7642:         if (($randomorder || $randompick) && (ref($respnumlookup) eq 'HASH')) {
                   7643:             $responsenum = $respnumlookup->{$question-1};
                   7644:             if (ref($startline) eq 'HASH') { 
                   7645:                 $first = $startline->{$question-1};
                   7646:             }
                   7647:         } else {
                   7648:             $responsenum = $question-1;
                   7649:             $first = $first_bubble_line{$responsenum};
                   7650:         }
                   7651:         $current_line = $first + 1;
                   7652:         $lines        = $bubble_lines_per_response{$responsenum};
1.503     raeburn  7653:     }
1.497     foxr     7654:     if ($lines > 1) {
1.503     raeburn  7655:         $r->print(&mt('The group of bubble lines below responds to a single question.').'<br />');
1.691     raeburn  7656:         if (($responsetype_per_response{$responsenum} eq 'essayresponse') ||
                   7657:             ($responsetype_per_response{$responsenum} eq 'formularesponse') ||
                   7658:             ($responsetype_per_response{$responsenum} eq 'stringresponse') ||
                   7659:             ($responsetype_per_response{$responsenum} eq 'imageresponse') ||
                   7660:             ($responsetype_per_response{$responsenum} eq 'reactionresponse') ||
                   7661:             ($responsetype_per_response{$responsenum} eq 'organicresponse')) {
1.684     bisitz   7662:             $r->print(
                   7663:                 &mt("Although this particular question type requires handgrading, the instructions for this question in the bubblesheet exam directed students to leave [quant,_1,line] blank on their bubblesheets.",$lines)
                   7664:                .'<br /><br />'
                   7665:                .&mt('A non-zero score can be assigned to the student during bubblesheet grading by selecting a bubble in at least one line.')
                   7666:                .'<br />'
                   7667:                .&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.')
                   7668:                .'<br />'
                   7669:                .&mt("To assign a score of zero for this question, mark all lines as 'No bubble'.")
                   7670:                .'<br /><br />'
                   7671:             );
1.503     raeburn  7672:         } else {
                   7673:             $r->print(&mt("Select at most one bubble in a single line and select 'No Bubble' in all the other lines. ")."<br />");
                   7674:         }
1.497     foxr     7675:     }
                   7676:     for (my $i =0; $i < $lines; $i++) {
1.503     raeburn  7677:         my $selected = $$scan_record{"scantron.$current_line.answer"};
1.691     raeburn  7678: 	&scantron_bubble_selector($r,$scan_config,$current_line,
1.503     raeburn  7679: 	        		  $questionnum,$error,split('', $selected));
1.524     raeburn  7680:         push(@linenums,$current_line);
1.497     foxr     7681: 	$current_line++;
                   7682:     }
                   7683:     if ($lines > 1) {
                   7684: 	$r->print("<hr /><br />");
                   7685:     }
1.503     raeburn  7686:     return @linenums;
1.157     albertel 7687: }
1.423     albertel 7688: 
                   7689: =pod
                   7690: 
                   7691: =item scantron_bubble_selector
                   7692:   
                   7693:    Generates the html radiobuttons to correct a single bubble line
1.424     albertel 7694:    possibly showing the existing the selected bubbles if known
1.423     albertel 7695: 
                   7696:  Arguments:
                   7697:     $r           - Apache request object
                   7698:     $scan_config - hash from &get_scantron_config()
1.497     foxr     7699:     $line        - Number of the line being displayed.
1.503     raeburn  7700:     $questionnum - Question number (may include subquestion)
                   7701:     $error       - Type of error.
1.497     foxr     7702:     @selected    - Array of bubbles picked on this line.
1.423     albertel 7703: 
                   7704: =cut
                   7705: 
1.157     albertel 7706: sub scantron_bubble_selector {
1.503     raeburn  7707:     my ($r,$scan_config,$line,$questionnum,$error,@selected)=@_;
1.157     albertel 7708:     my $max=$$scan_config{'Qlength'};
1.274     albertel 7709: 
                   7710:     my $scmode=$$scan_config{'Qon'};
1.649     raeburn  7711:     if ($scmode eq 'number' || $scmode eq 'letter') { 
                   7712:         if (($$scan_config{'BubblesPerRow'} =~ /^\d+$/) &&
                   7713:             ($$scan_config{'BubblesPerRow'} > 0)) {
                   7714:             $max=$$scan_config{'BubblesPerRow'};
                   7715:             if (($scmode eq 'number') && ($max > 10)) {
                   7716:                 $max = 10;
                   7717:             } elsif (($scmode eq 'letter') && $max > 26) {
                   7718:                 $max = 26;
                   7719:             }
                   7720:         } else {
                   7721:             $max = 10;
                   7722:         }
                   7723:     }
1.274     albertel 7724: 
1.157     albertel 7725:     my @alphabet=('A'..'Z');
1.503     raeburn  7726:     $r->print(&Apache::loncommon::start_data_table().
                   7727:               &Apache::loncommon::start_data_table_row());
                   7728:     $r->print('<td rowspan="2" class="LC_leftcol_header">'.$line.'</td>');
1.497     foxr     7729:     for (my $i=0;$i<$max+1;$i++) {
                   7730: 	$r->print("\n".'<td align="center">');
                   7731: 	if ($selected[0] eq $alphabet[$i]) { $r->print('X'); shift(@selected) }
                   7732: 	else { $r->print('&nbsp;'); }
                   7733: 	$r->print('</td>');
                   7734:     }
1.503     raeburn  7735:     $r->print(&Apache::loncommon::end_data_table_row().
                   7736:               &Apache::loncommon::start_data_table_row());
1.497     foxr     7737:     for (my $i=0;$i<$max;$i++) {
                   7738: 	$r->print("\n".
                   7739: 		  '<td><label><input type="radio" name="scantron_correct_Q_'.
                   7740: 		  $line.'" value="'.$i.'" />'.$alphabet[$i]."</label></td>");
                   7741:     }
1.503     raeburn  7742:     my $nobub_checked = ' ';
                   7743:     if ($error eq 'missingbubble') {
                   7744:         $nobub_checked = ' checked = "checked" ';
                   7745:     }
                   7746:     $r->print("\n".'<td><label><input type="radio" name="scantron_correct_Q_'.
                   7747: 	      $line.'" value="none"'.$nobub_checked.'/>'.&mt('No bubble').
                   7748:               '</label>'."\n".'<input type="hidden" name="scantron_questionnum_Q_'.
                   7749:               $line.'" value="'.$questionnum.'" /></td>');
                   7750:     $r->print(&Apache::loncommon::end_data_table_row().
                   7751:               &Apache::loncommon::end_data_table());
1.157     albertel 7752: }
                   7753: 
1.423     albertel 7754: =pod
                   7755: 
                   7756: =item num_matches
                   7757: 
1.424     albertel 7758:    Counts the number of characters that are the same between the two arguments.
                   7759: 
                   7760:  Arguments:
                   7761:    $orig - CODE from the scanline
                   7762:    $code - CODE to match against
                   7763: 
                   7764:  Returns:
                   7765:    $count - integer count of the number of same characters between the
                   7766:             two arguments
                   7767: 
1.423     albertel 7768: =cut
                   7769: 
1.194     albertel 7770: sub num_matches {
                   7771:     my ($orig,$code) = @_;
                   7772:     my @code=split(//,$code);
                   7773:     my @orig=split(//,$orig);
                   7774:     my $same=0;
                   7775:     for (my $i=0;$i<scalar(@code);$i++) {
                   7776: 	if ($code[$i] eq $orig[$i]) { $same++; }
                   7777:     }
                   7778:     return $same;
                   7779: }
                   7780: 
1.423     albertel 7781: =pod
                   7782: 
                   7783: =item scantron_get_closely_matching_CODEs
                   7784: 
1.424     albertel 7785:    Cycles through all CODEs and finds the set that has the greatest
                   7786:    number of same characters as the provided CODE
                   7787: 
                   7788:  Arguments:
                   7789:    $allcodes - hash ref returned by &get_codes()
                   7790:    $CODE     - CODE from the current scanline
                   7791: 
                   7792:  Returns:
                   7793:    2 element list
                   7794:     - first elements is number of how closely matching the best fit is 
                   7795:       (5 means best set has 5 matching characters)
                   7796:     - second element is an arrary ref containing the set of valid CODEs
                   7797:       that best fit the passed in CODE
                   7798: 
1.423     albertel 7799: =cut
                   7800: 
1.194     albertel 7801: sub scantron_get_closely_matching_CODEs {
                   7802:     my ($allcodes,$CODE)=@_;
                   7803:     my @CODEs;
                   7804:     foreach my $testcode (sort(keys(%{$allcodes}))) {
                   7805: 	push(@{$CODEs[&num_matches($CODE,$testcode)]},$testcode);
                   7806:     }
                   7807: 
                   7808:     return ($#CODEs,$CODEs[-1]);
                   7809: }
                   7810: 
1.423     albertel 7811: =pod
                   7812: 
                   7813: =item get_codes
                   7814: 
1.424     albertel 7815:    Builds a hash which has keys of all of the valid CODEs from the selected
                   7816:    set of remembered CODEs.
                   7817: 
                   7818:  Arguments:
                   7819:   $old_name - name of the set of remembered CODEs
                   7820:   $cdom     - domain of the course
                   7821:   $cnum     - internal course name
                   7822: 
                   7823:  Returns:
                   7824:   %allcodes - keys are the valid CODEs, values are all 1
                   7825: 
1.423     albertel 7826: =cut
                   7827: 
1.194     albertel 7828: sub get_codes {
1.280     foxr     7829:     my ($old_name, $cdom, $cnum) = @_;
                   7830:     if (!$old_name) {
                   7831: 	$old_name=$env{'form.scantron_CODElist'};
                   7832:     }
                   7833:     if (!$cdom) {
                   7834: 	$cdom =$env{'course.'.$env{'request.course.id'}.'.domain'};
                   7835:     }
                   7836:     if (!$cnum) {
                   7837: 	$cnum =$env{'course.'.$env{'request.course.id'}.'.num'};
                   7838:     }
1.278     albertel 7839:     my %result=&Apache::lonnet::get('CODEs',[$old_name,"type\0$old_name"],
                   7840: 				    $cdom,$cnum);
                   7841:     my %allcodes;
                   7842:     if ($result{"type\0$old_name"} eq 'number') {
                   7843: 	%allcodes=map {($_,1)} split(',',$result{$old_name});
                   7844:     } else {
                   7845: 	%allcodes=map {(&Apache::lonprintout::num_to_letters($_),1)} split(',',$result{$old_name});
                   7846:     }
1.194     albertel 7847:     return %allcodes;
                   7848: }
                   7849: 
1.423     albertel 7850: =pod
                   7851: 
                   7852: =item scantron_validate_CODE
                   7853: 
1.424     albertel 7854:    Validates all scanlines in the selected file to not have any
                   7855:    invalid or underspecified CODEs and that none of the codes are
                   7856:    duplicated if this was requested.
                   7857: 
1.423     albertel 7858: =cut
                   7859: 
1.157     albertel 7860: sub scantron_validate_CODE {
                   7861:     my ($r,$currentphase) = @_;
1.257     albertel 7862:     my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
1.186     albertel 7863:     if ($scantron_config{'CODElocation'} &&
                   7864: 	$scantron_config{'CODEstart'} &&
                   7865: 	$scantron_config{'CODElength'}) {
1.257     albertel 7866: 	if (!defined($env{'form.scantron_CODElist'})) {
1.186     albertel 7867: 	    &FIXME_blow_up()
                   7868: 	}
                   7869:     } else {
                   7870: 	return (0,$currentphase+1);
                   7871:     }
                   7872:     
                   7873:     my %usedCODEs;
                   7874: 
1.194     albertel 7875:     my %allcodes=&get_codes();
1.186     albertel 7876: 
1.582     raeburn  7877:     my $nav_error;
1.649     raeburn  7878:     &scantron_get_maxbubble(\$nav_error,\%scantron_config); # parse needs the lines per response array.
1.582     raeburn  7879:     if ($nav_error) {
                   7880:         $r->print(&navmap_errormsg());
                   7881:         return(1,$currentphase);
                   7882:     }
1.447     foxr     7883: 
1.186     albertel 7884:     my ($scanlines,$scan_data)=&scantron_getfile();
                   7885:     for (my $i=0;$i<=$scanlines->{'count'};$i++) {
1.200     albertel 7886: 	my $line=&scantron_get_line($scanlines,$scan_data,$i);
1.186     albertel 7887: 	if ($line=~/^[\s\cz]*$/) { next; }
                   7888: 	my $scan_record=&scantron_parse_scanline($line,$i,\%scantron_config,
                   7889: 						 $scan_data);
                   7890: 	my $CODE=$$scan_record{'scantron.CODE'};
                   7891: 	my $error=0;
1.224     albertel 7892: 	if (!&Apache::lonnet::validCODE($CODE)) {
                   7893: 	    &scantron_get_correction($r,$i,$scan_record,
                   7894: 				     \%scantron_config,
                   7895: 				     $line,'incorrectCODE',\%allcodes);
                   7896: 	    return(1,$currentphase);
                   7897: 	}
1.221     albertel 7898: 	if (%allcodes && !exists($allcodes{$CODE}) 
                   7899: 	    && !$$scan_record{'scantron.useCODE'}) {
1.186     albertel 7900: 	    &scantron_get_correction($r,$i,$scan_record,
                   7901: 				     \%scantron_config,
1.194     albertel 7902: 				     $line,'incorrectCODE',\%allcodes);
                   7903: 	    return(1,$currentphase);
1.186     albertel 7904: 	}
1.214     albertel 7905: 	if (exists($usedCODEs{$CODE}) 
1.257     albertel 7906: 	    && $env{'form.scantron_CODEunique'} eq 'yes'
1.192     albertel 7907: 	    && !$$scan_record{'scantron.CODE_ignore_dup'}) {
1.186     albertel 7908: 	    &scantron_get_correction($r,$i,$scan_record,
                   7909: 				     \%scantron_config,
1.194     albertel 7910: 				     $line,'duplicateCODE',$usedCODEs{$CODE});
                   7911: 	    return(1,$currentphase);
1.186     albertel 7912: 	}
1.524     raeburn  7913: 	push(@{$usedCODEs{$CODE}},$$scan_record{'scantron.PaperID'});
1.186     albertel 7914:     }
1.157     albertel 7915:     return (0,$currentphase+1);
                   7916: }
                   7917: 
1.423     albertel 7918: =pod
                   7919: 
                   7920: =item scantron_validate_doublebubble
                   7921: 
1.424     albertel 7922:    Validates all scanlines in the selected file to not have any
                   7923:    bubble lines with multiple bubbles marked.
                   7924: 
1.423     albertel 7925: =cut
                   7926: 
1.157     albertel 7927: sub scantron_validate_doublebubble {
                   7928:     my ($r,$currentphase) = @_;
                   7929:     #get student info
                   7930:     my $classlist=&Apache::loncoursedata::get_classlist();
                   7931:     my %idmap=&username_to_idmap($classlist);
1.691     raeburn  7932:     my (undef,undef,$sequence)=
                   7933:         &Apache::lonnet::decode_symb($env{'form.selectpage'});
1.157     albertel 7934: 
                   7935:     #get scantron line setup
1.257     albertel 7936:     my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
1.157     albertel 7937:     my ($scanlines,$scan_data)=&scantron_getfile();
1.691     raeburn  7938: 
                   7939:     my $navmap = Apache::lonnavmaps::navmap->new();
                   7940:     unless (ref($navmap)) {
                   7941:         $r->print(&navmap_errormsg());
                   7942:         return(1,$currentphase);
                   7943:     }
                   7944:     my $map=$navmap->getResourceByUrl($sequence);
                   7945:     my @resources=$navmap->retrieveResources($map,\&scantron_filter,1,0);
                   7946:     my ($randomorder,$randompick,@master_seq,%symb_to_resource,%grader_partids_by_symb,
                   7947:         %grader_randomlists_by_symb,%orderedforcode,%respnumlookup,%startline);
                   7948:     my $bubbles_per_row = &bubblesheet_bubbles_per_row(\%scantron_config);
                   7949: 
1.583     raeburn  7950:     my $nav_error;
1.691     raeburn  7951:     if (ref($map)) {
                   7952:         $randomorder = $map->randomorder();
                   7953:         $randompick = $map->randompick();
                   7954:         if ($randomorder || $randompick) {
                   7955:             $nav_error = &get_master_seq(\@resources,\@master_seq,\%symb_to_resource);
                   7956:             if ($nav_error) {
                   7957:                 $r->print(&navmap_errormsg());
                   7958:                 return(1,$currentphase);
                   7959:             }
                   7960:             &graders_resources_pass(\@resources,\%grader_partids_by_symb,
                   7961:                                     \%grader_randomlists_by_symb,$bubbles_per_row);
                   7962:         }
                   7963:     } else {
                   7964:         $r->print(&navmap_errormsg());
                   7965:         return(1,$currentphase);
                   7966:     }
                   7967: 
1.649     raeburn  7968:     &scantron_get_maxbubble(\$nav_error,\%scantron_config); # parse needs the bubble line array.
1.583     raeburn  7969:     if ($nav_error) {
                   7970:         $r->print(&navmap_errormsg());
                   7971:         return(1,$currentphase);
                   7972:     }
1.447     foxr     7973: 
1.157     albertel 7974:     for (my $i=0;$i<=$scanlines->{'count'};$i++) {
1.200     albertel 7975: 	my $line=&scantron_get_line($scanlines,$scan_data,$i);
1.157     albertel 7976: 	if ($line=~/^[\s\cz]*$/) { next; }
                   7977: 	my $scan_record=&scantron_parse_scanline($line,$i,\%scantron_config,
1.691     raeburn  7978: 						 $scan_data,undef,\%idmap,$randomorder,
                   7979:                                                  $randompick,$sequence,\@master_seq,
                   7980:                                                  \%symb_to_resource,\%grader_partids_by_symb,
                   7981:                                                  \%orderedforcode,\%respnumlookup,\%startline);
1.157     albertel 7982: 	if (!defined($$scan_record{'scantron.doubleerror'})) { next; }
                   7983: 	&scantron_get_correction($r,$i,$scan_record,\%scantron_config,$line,
                   7984: 				 'doublebubble',
1.691     raeburn  7985: 				 $$scan_record{'scantron.doubleerror'},
                   7986:                                  $randomorder,$randompick,\%respnumlookup,\%startline);
1.157     albertel 7987:     	return (1,$currentphase);
                   7988:     }
                   7989:     return (0,$currentphase+1);
                   7990: }
                   7991: 
1.423     albertel 7992: 
1.503     raeburn  7993: sub scantron_get_maxbubble {
1.649     raeburn  7994:     my ($nav_error,$scantron_config) = @_;
1.257     albertel 7995:     if (defined($env{'form.scantron_maxbubble'}) &&
                   7996: 	$env{'form.scantron_maxbubble'}) {
1.447     foxr     7997: 	&restore_bubble_lines();
1.257     albertel 7998: 	return $env{'form.scantron_maxbubble'};
1.191     albertel 7999:     }
1.330     albertel 8000: 
1.447     foxr     8001:     my (undef, undef, $sequence) =
1.257     albertel 8002: 	&Apache::lonnet::decode_symb($env{'form.selectpage'});
1.330     albertel 8003: 
1.447     foxr     8004:     my $navmap=Apache::lonnavmaps::navmap->new();
1.582     raeburn  8005:     unless (ref($navmap)) {
                   8006:         if (ref($nav_error)) {
                   8007:             $$nav_error = 1;
                   8008:         }
1.591     raeburn  8009:         return;
1.582     raeburn  8010:     }
1.191     albertel 8011:     my $map=$navmap->getResourceByUrl($sequence);
                   8012:     my @resources=$navmap->retrieveResources($map,\&scantron_filter,1,0);
1.649     raeburn  8013:     my $bubbles_per_row = &bubblesheet_bubbles_per_row($scantron_config);
1.330     albertel 8014: 
                   8015:     &Apache::lonxml::clear_problem_counter();
                   8016: 
1.557     raeburn  8017:     my $uname       = $env{'user.name'};
                   8018:     my $udom        = $env{'user.domain'};
1.435     foxr     8019:     my $cid         = $env{'request.course.id'};
                   8020:     my $total_lines = 0;
                   8021:     %bubble_lines_per_response = ();
1.447     foxr     8022:     %first_bubble_line         = ();
1.503     raeburn  8023:     %subdivided_bubble_lines   = ();
                   8024:     %responsetype_per_response = ();
1.691     raeburn  8025:     %masterseq_id_responsenum  = ();
1.554     raeburn  8026: 
1.447     foxr     8027:     my $response_number = 0;
                   8028:     my $bubble_line     = 0;
1.191     albertel 8029:     foreach my $resource (@resources) {
1.691     raeburn  8030:         my $resid = $resource->id(); 
1.672     raeburn  8031:         my ($analysis,$parts) = &scantron_partids_tograde($resource,$cid,$uname,
                   8032:                                                           $udom,undef,$bubbles_per_row);
1.542     raeburn  8033:         if ((ref($analysis) eq 'HASH') && (ref($parts) eq 'ARRAY')) {
                   8034: 	    foreach my $part_id (@{$parts}) {
                   8035:                 my $lines;
                   8036: 
                   8037: 	        # TODO - make this a persistent hash not an array.
                   8038: 
                   8039:                 # optionresponse, matchresponse and rankresponse type items 
                   8040:                 # render as separate sub-questions in exam mode.
                   8041:                 if (($analysis->{$part_id.'.type'} eq 'optionresponse') ||
                   8042:                     ($analysis->{$part_id.'.type'} eq 'matchresponse') ||
                   8043:                     ($analysis->{$part_id.'.type'} eq 'rankresponse')) {
                   8044:                     my ($numbub,$numshown);
                   8045:                     if ($analysis->{$part_id.'.type'} eq 'optionresponse') {
                   8046:                         if (ref($analysis->{$part_id.'.options'}) eq 'ARRAY') {
                   8047:                             $numbub = scalar(@{$analysis->{$part_id.'.options'}});
                   8048:                         }
                   8049:                     } elsif ($analysis->{$part_id.'.type'} eq 'matchresponse') {
                   8050:                         if (ref($analysis->{$part_id.'.items'}) eq 'ARRAY') {
                   8051:                             $numbub = scalar(@{$analysis->{$part_id.'.items'}});
                   8052:                         }
                   8053:                     } elsif ($analysis->{$part_id.'.type'} eq 'rankresponse') {
                   8054:                         if (ref($analysis->{$part_id.'.foils'}) eq 'ARRAY') {
                   8055:                             $numbub = scalar(@{$analysis->{$part_id.'.foils'}});
                   8056:                         }
                   8057:                     }
                   8058:                     if (ref($analysis->{$part_id.'.shown'}) eq 'ARRAY') {
                   8059:                         $numshown = scalar(@{$analysis->{$part_id.'.shown'}});
                   8060:                     }
1.649     raeburn  8061:                     my $bubbles_per_row =
                   8062:                         &bubblesheet_bubbles_per_row($scantron_config);
                   8063:                     my $inner_bubble_lines = int($numbub/$bubbles_per_row);
                   8064:                     if (($numbub % $bubbles_per_row) != 0) {
1.542     raeburn  8065:                         $inner_bubble_lines++;
                   8066:                     }
                   8067:                     for (my $i=0; $i<$numshown; $i++) {
                   8068:                         $subdivided_bubble_lines{$response_number} .= 
                   8069:                             $inner_bubble_lines.',';
                   8070:                     }
                   8071:                     $subdivided_bubble_lines{$response_number} =~ s/,$//;
                   8072:                     $lines = $numshown * $inner_bubble_lines;
                   8073:                 } else {
                   8074:                     $lines = $analysis->{"$part_id.bubble_lines"};
1.649     raeburn  8075:                 }
1.542     raeburn  8076: 
                   8077:                 $first_bubble_line{$response_number} = $bubble_line;
                   8078: 	        $bubble_lines_per_response{$response_number} = $lines;
                   8079:                 $responsetype_per_response{$response_number} = 
                   8080:                     $analysis->{$part_id.'.type'};
1.691     raeburn  8081:                 $masterseq_id_responsenum{$resid.'_'.$part_id} = $response_number;  
1.542     raeburn  8082: 	        $response_number++;
                   8083: 
                   8084: 	        $bubble_line +=  $lines;
                   8085: 	        $total_lines +=  $lines;
                   8086: 	    }
                   8087:         }
                   8088:     }
1.552     raeburn  8089:     &Apache::lonnet::delenv('scantron.');
1.542     raeburn  8090: 
                   8091:     &save_bubble_lines();
                   8092:     $env{'form.scantron_maxbubble'} =
                   8093: 	$total_lines;
                   8094:     return $env{'form.scantron_maxbubble'};
                   8095: }
1.523     raeburn  8096: 
1.649     raeburn  8097: sub bubblesheet_bubbles_per_row {
                   8098:     my ($scantron_config) = @_;
                   8099:     my $bubbles_per_row;
                   8100:     if (ref($scantron_config) eq 'HASH') {
                   8101:         $bubbles_per_row = $scantron_config->{'BubblesPerRow'};
                   8102:     }
                   8103:     if ((!$bubbles_per_row) || ($bubbles_per_row < 1)) {
                   8104:         $bubbles_per_row = 10;
                   8105:     }
                   8106:     return $bubbles_per_row;
                   8107: }
                   8108: 
1.157     albertel 8109: sub scantron_validate_missingbubbles {
                   8110:     my ($r,$currentphase) = @_;
                   8111:     #get student info
                   8112:     my $classlist=&Apache::loncoursedata::get_classlist();
                   8113:     my %idmap=&username_to_idmap($classlist);
1.691     raeburn  8114:     my (undef,undef,$sequence)=
                   8115:         &Apache::lonnet::decode_symb($env{'form.selectpage'});
1.157     albertel 8116: 
                   8117:     #get scantron line setup
1.257     albertel 8118:     my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
1.157     albertel 8119:     my ($scanlines,$scan_data)=&scantron_getfile();
1.691     raeburn  8120: 
                   8121:     my $navmap = Apache::lonnavmaps::navmap->new();
                   8122:     unless (ref($navmap)) {
                   8123:         $r->print(&navmap_errormsg());
                   8124:         return(1,$currentphase);
                   8125:     }
                   8126: 
                   8127:     my $map=$navmap->getResourceByUrl($sequence);
                   8128:     my @resources=$navmap->retrieveResources($map,\&scantron_filter,1,0);
                   8129:     my ($randomorder,$randompick,@master_seq,%symb_to_resource,%grader_partids_by_symb,
                   8130:         %grader_randomlists_by_symb,%orderedforcode,%respnumlookup,%startline);
                   8131:     my $bubbles_per_row = &bubblesheet_bubbles_per_row(\%scantron_config);
                   8132: 
1.582     raeburn  8133:     my $nav_error;
1.691     raeburn  8134:     if (ref($map)) {
                   8135:         $randomorder = $map->randomorder();
                   8136:         $randompick = $map->randompick();
                   8137:         if ($randomorder || $randompick) {
                   8138:             $nav_error = &get_master_seq(\@resources,\@master_seq,\%symb_to_resource);
                   8139:             if ($nav_error) {
                   8140:                 $r->print(&navmap_errormsg());
                   8141:                 return(1,$currentphase);
                   8142:             }
                   8143:             &graders_resources_pass(\@resources,\%grader_partids_by_symb,
                   8144:                                     \%grader_randomlists_by_symb,$bubbles_per_row);
                   8145:         }
                   8146:     } else {
                   8147:         $r->print(&navmap_errormsg());
                   8148:         return(1,$currentphase);
                   8149:     }
                   8150: 
                   8151: 
1.649     raeburn  8152:     my $max_bubble=&scantron_get_maxbubble(\$nav_error,\%scantron_config);
1.582     raeburn  8153:     if ($nav_error) {
1.691     raeburn  8154:         $r->print(&navmap_errormsg());
1.693     raeburn  8155:         return(1,$currentphase);
1.582     raeburn  8156:     }
1.691     raeburn  8157: 
1.157     albertel 8158:     if (!$max_bubble) { $max_bubble=2**31; }
                   8159:     for (my $i=0;$i<=$scanlines->{'count'};$i++) {
1.200     albertel 8160: 	my $line=&scantron_get_line($scanlines,$scan_data,$i);
1.157     albertel 8161: 	if ($line=~/^[\s\cz]*$/) { next; }
1.691     raeburn  8162: 	my $scan_record =
                   8163:             &scantron_parse_scanline($line,$i,\%scantron_config,$scan_data,undef,\%idmap,
                   8164: 				     $randomorder,$randompick,$sequence,\@master_seq,
                   8165:                                      \%symb_to_resource,\%grader_partids_by_symb,
                   8166:                                      \%orderedforcode,\%respnumlookup,\%startline);
1.157     albertel 8167: 	if (!defined($$scan_record{'scantron.missingerror'})) { next; }
                   8168: 	my @to_correct;
1.470     foxr     8169: 	
                   8170: 	# Probably here's where the error is...
                   8171: 
1.157     albertel 8172: 	foreach my $missing (@{$$scan_record{'scantron.missingerror'}}) {
1.505     raeburn  8173:             my $lastbubble;
                   8174:             if ($missing =~ /^(\d+)\.(\d+)$/) {
                   8175:                my $question = $1;
                   8176:                my $subquestion = $2;
1.691     raeburn  8177:                my ($first,$responsenum);
                   8178:                if ($randomorder || $randompick) {
                   8179:                    $responsenum = $respnumlookup{$question-1};
                   8180:                    $first = $startline{$question-1};
                   8181:                } else {
                   8182:                    $responsenum = $question-1; 
                   8183:                    $first = $first_bubble_line{$responsenum};
                   8184:                }
                   8185:                if (!defined($first)) { next; }
                   8186:                my @subans = split(/,/,$subdivided_bubble_lines{$responsenum});
1.505     raeburn  8187:                my $subcount = 1;
                   8188:                while ($subcount<$subquestion) {
                   8189:                    $first += $subans[$subcount-1];
                   8190:                    $subcount ++;
                   8191:                }
                   8192:                my $count = $subans[$subquestion-1];
                   8193:                $lastbubble = $first + $count;
                   8194:             } else {
1.691     raeburn  8195:                my ($first,$responsenum);
                   8196:                if ($randomorder || $randompick) {
                   8197:                    $responsenum = $respnumlookup{$missing-1};
                   8198:                    $first = $startline{$missing-1};
                   8199:                } else {
                   8200:                    $responsenum = $missing-1;
                   8201:                    $first = $first_bubble_line{$responsenum};
                   8202:                }
                   8203:                if (!defined($first)) { next; }
                   8204:                $lastbubble = $first + $bubble_lines_per_response{$responsenum};
1.505     raeburn  8205:             }
                   8206:             if ($lastbubble > $max_bubble) { next; }
1.157     albertel 8207: 	    push(@to_correct,$missing);
                   8208: 	}
                   8209: 	if (@to_correct) {
                   8210: 	    &scantron_get_correction($r,$i,$scan_record,\%scantron_config,
1.691     raeburn  8211: 				     $line,'missingbubble',\@to_correct,
                   8212:                                      $randomorder,$randompick,\%respnumlookup,
                   8213:                                      \%startline);
1.157     albertel 8214: 	    return (1,$currentphase);
                   8215: 	}
                   8216: 
                   8217:     }
                   8218:     return (0,$currentphase+1);
                   8219: }
                   8220: 
1.663     raeburn  8221: sub hand_bubble_option {
                   8222:     my (undef, undef, $sequence) =
                   8223:         &Apache::lonnet::decode_symb($env{'form.selectpage'});
                   8224:     return if ($sequence eq '');
                   8225:     my $navmap = Apache::lonnavmaps::navmap->new();
                   8226:     unless (ref($navmap)) {
                   8227:         return;
                   8228:     }
                   8229:     my $needs_hand_bubbles;
                   8230:     my $map=$navmap->getResourceByUrl($sequence);
                   8231:     my @resources=$navmap->retrieveResources($map,\&scantron_filter,1,0);
                   8232:     foreach my $res (@resources) {
                   8233:         if (ref($res)) {
                   8234:             if ($res->is_problem()) {
                   8235:                 my $partlist = $res->parts();
                   8236:                 foreach my $part (@{ $partlist }) {
                   8237:                     my @types = $res->responseType($part);
                   8238:                     if (grep(/^(chem|essay|image|formula|math|string|functionplot)$/,@types)) {
                   8239:                         $needs_hand_bubbles = 1;
                   8240:                         last;
                   8241:                     }
                   8242:                 }
                   8243:             }
                   8244:         }
                   8245:     }
                   8246:     if ($needs_hand_bubbles) {
                   8247:         my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
                   8248:         my $bubbles_per_row = &bubblesheet_bubbles_per_row(\%scantron_config);
                   8249:         return &mt('The sequence to be graded contains response types which are handgraded.').'<p>'.
                   8250:                &mt('If you have already graded these by bubbling sheets to indicate points awarded, [_1]what point value is assigned to a filled last bubble in each row?','<br />').
                   8251:                '<label><input type="radio" name="scantron_lastbubblepoints" value="'.$bubbles_per_row.'" checked="checked" />'.&mt('[quant,_1,point]',$bubbles_per_row).'</label>&nbsp;'.&mt('or').'&nbsp;'.
1.722     raeburn  8252:                '<label><input type="radio" name="scantron_lastbubblepoints" value="0" />'.&mt('0 points').'</label></p>';
1.663     raeburn  8253:     }
                   8254:     return;
                   8255: }
1.423     albertel 8256: 
1.82      albertel 8257: sub scantron_process_students {
1.608     www      8258:     my ($r,$symb) = @_;
1.513     foxr     8259: 
1.257     albertel 8260:     my (undef,undef,$sequence)=&Apache::lonnet::decode_symb($env{'form.selectpage'});
1.513     foxr     8261:     if (!$symb) {
                   8262: 	return '';
                   8263:     }
1.324     albertel 8264:     my $default_form_data=&defaultFormData($symb);
1.82      albertel 8265: 
1.257     albertel 8266:     my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
1.691     raeburn  8267:     my $bubbles_per_row = &bubblesheet_bubbles_per_row(\%scantron_config); 
1.157     albertel 8268:     my ($scanlines,$scan_data)=&scantron_getfile();
1.82      albertel 8269:     my $classlist=&Apache::loncoursedata::get_classlist();
                   8270:     my %idmap=&username_to_idmap($classlist);
1.132     bowersj2 8271:     my $navmap=Apache::lonnavmaps::navmap->new();
1.582     raeburn  8272:     unless (ref($navmap)) {
                   8273:         $r->print(&navmap_errormsg());
                   8274:         return '';
1.691     raeburn  8275:     }
1.83      albertel 8276:     my $map=$navmap->getResourceByUrl($sequence);
1.691     raeburn  8277:     my ($randomorder,$randompick,@master_seq,%symb_to_resource,%grader_partids_by_symb,
1.693     raeburn  8278:         %grader_randomlists_by_symb);
1.677     raeburn  8279:     if (ref($map)) {
                   8280:         $randomorder = $map->randomorder();
1.689     raeburn  8281:         $randompick = $map->randompick();
1.691     raeburn  8282:     } else {
                   8283:         $r->print(&navmap_errormsg());
                   8284:         return '';
1.677     raeburn  8285:     }
1.691     raeburn  8286:     my $nav_error;
1.83      albertel 8287:     my @resources=$navmap->retrieveResources($map,\&scantron_filter,1,0);
1.691     raeburn  8288:     if ($randomorder || $randompick) {
                   8289:         $nav_error = &get_master_seq(\@resources,\@master_seq,\%symb_to_resource);
                   8290:         if ($nav_error) {
                   8291:             $r->print(&navmap_errormsg());
                   8292:             return '';
                   8293:         }
                   8294:     }
1.557     raeburn  8295:     &graders_resources_pass(\@resources,\%grader_partids_by_symb,
1.649     raeburn  8296:                             \%grader_randomlists_by_symb,$bubbles_per_row);
1.557     raeburn  8297: 
1.554     raeburn  8298:     my ($uname,$udom);
1.82      albertel 8299:     my $result= <<SCANTRONFORM;
1.81      albertel 8300: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="scantronupload">
                   8301:   <input type="hidden" name="command" value="scantron_configphase" />
                   8302:   $default_form_data
                   8303: SCANTRONFORM
1.82      albertel 8304:     $r->print($result);
                   8305: 
                   8306:     my @delayqueue;
1.542     raeburn  8307:     my (%completedstudents,%scandata);
1.140     albertel 8308:     
1.520     www      8309:     my $lock=&Apache::lonnet::set_lock(&mt('Grading bubblesheet exam'));
1.200     albertel 8310:     my $count=&get_todo_count($scanlines,$scan_data);
1.667     www      8311:     my %prog_state=&Apache::lonhtmlcommon::Create_PrgWin($r,$count);
                   8312:     &Apache::lonhtmlcommon::Update_PrgWin($r,\%prog_state,'Processing first student');
1.542     raeburn  8313:     $r->print('<br />');
1.140     albertel 8314:     my $start=&Time::HiRes::time();
1.158     albertel 8315:     my $i=-1;
1.542     raeburn  8316:     my $started;
1.447     foxr     8317: 
1.649     raeburn  8318:     &scantron_get_maxbubble(\$nav_error,\%scantron_config); # Need the bubble lines array to parse.
1.582     raeburn  8319:     if ($nav_error) {
                   8320:         $r->print(&navmap_errormsg());
                   8321:         return '';
                   8322:     }
                   8323: 
1.513     foxr     8324:     # If an ssi failed in scantron_get_maxbubble, put an error message out to
                   8325:     # the user and return.
                   8326: 
                   8327:     if ($ssi_error) {
                   8328: 	$r->print("</form>");
                   8329: 	&ssi_print_error($r);
1.520     www      8330:         &Apache::lonnet::remove_lock($lock);
1.513     foxr     8331: 	return '';		# Dunno why the other returns return '' rather than just returning.
                   8332:     }
1.447     foxr     8333: 
1.542     raeburn  8334:     my %lettdig = &letter_to_digits();
                   8335:     my $numletts = scalar(keys(%lettdig));
1.691     raeburn  8336:     my %orderedforcode;
1.542     raeburn  8337: 
1.157     albertel 8338:     while ($i<$scanlines->{'count'}) {
                   8339:  	($uname,$udom)=('','');
                   8340:  	$i++;
1.200     albertel 8341:  	my $line=&scantron_get_line($scanlines,$scan_data,$i);
1.157     albertel 8342:  	if ($line=~/^[\s\cz]*$/) { next; }
1.200     albertel 8343: 	if ($started) {
1.667     www      8344: 	    &Apache::lonhtmlcommon::Increment_PrgWin($r,\%prog_state,'last student');
1.200     albertel 8345: 	}
                   8346: 	$started=1;
1.691     raeburn  8347:         my %respnumlookup = ();
                   8348:         my %startline = ();
                   8349:         my $total;
1.157     albertel 8350:  	my $scan_record=&scantron_parse_scanline($line,$i,\%scantron_config,
1.691     raeburn  8351:                                                  $scan_data,undef,\%idmap,$randomorder,
                   8352:                                                  $randompick,$sequence,\@master_seq,
                   8353:                                                  \%symb_to_resource,\%grader_partids_by_symb,
                   8354:                                                  \%orderedforcode,\%respnumlookup,\%startline,
                   8355:                                                  \$total);
1.157     albertel 8356:  	unless ($uname=&scantron_find_student($scan_record,$scan_data,
                   8357:  					      \%idmap,$i)) {
                   8358:   	    &scantron_add_delay(\@delayqueue,$line,
                   8359:  				'Unable to find a student that matches',1);
                   8360:  	    next;
                   8361:   	}
                   8362:  	if (exists $completedstudents{$uname}) {
                   8363:  	    &scantron_add_delay(\@delayqueue,$line,
                   8364:  				'Student '.$uname.' has multiple sheets',2);
                   8365:  	    next;
                   8366:  	}
1.677     raeburn  8367:         my $usec = $classlist->{$uname}->[&Apache::loncoursedata::CL_SECTION];
                   8368:         my $user = $uname.':'.$usec;
1.157     albertel 8369:   	($uname,$udom)=split(/:/,$uname);
1.330     albertel 8370: 
1.677     raeburn  8371:         my $scancode;
                   8372:         if ((exists($scan_record->{'scantron.CODE'})) &&
                   8373:             (&Apache::lonnet::validCODE($scan_record->{'scantron.CODE'}))) {
                   8374:             $scancode = $scan_record->{'scantron.CODE'};
                   8375:         } else {
                   8376:             $scancode = '';
                   8377:         }
                   8378: 
                   8379:         my @mapresources = @resources;
1.689     raeburn  8380:         if ($randomorder || $randompick) {
1.678     raeburn  8381:             @mapresources = 
1.691     raeburn  8382:                 &users_order($user,$scancode,$sequence,\@master_seq,\%symb_to_resource,
                   8383:                              \%orderedforcode);
1.677     raeburn  8384:         }
1.586     raeburn  8385:         my (%partids_by_symb,$res_error);
1.677     raeburn  8386:         foreach my $resource (@mapresources) {
1.586     raeburn  8387:             my $ressymb;
                   8388:             if (ref($resource)) {
                   8389:                 $ressymb = $resource->symb();
                   8390:             } else {
                   8391:                 $res_error = 1;
                   8392:                 last;
                   8393:             }
1.557     raeburn  8394:             if ((exists($grader_randomlists_by_symb{$ressymb})) ||
                   8395:                 (ref($grader_partids_by_symb{$ressymb}) ne 'ARRAY')) {
                   8396:                 my ($analysis,$parts) =
1.672     raeburn  8397:                     &scantron_partids_tograde($resource,$env{'request.course.id'},
                   8398:                                               $uname,$udom,undef,$bubbles_per_row);
1.557     raeburn  8399:                 $partids_by_symb{$ressymb} = $parts;
                   8400:             } else {
                   8401:                 $partids_by_symb{$ressymb} = $grader_partids_by_symb{$ressymb};
                   8402:             }
1.554     raeburn  8403:         }
                   8404: 
1.586     raeburn  8405:         if ($res_error) {
                   8406:             &scantron_add_delay(\@delayqueue,$line,
                   8407:                                 'An error occurred while grading student '.$uname,2);
                   8408:             next;
                   8409:         }
                   8410: 
1.330     albertel 8411: 	&Apache::lonxml::clear_problem_counter();
1.514     raeburn  8412:   	&Apache::lonnet::appenv($scan_record);
1.376     albertel 8413: 
                   8414: 	if (&scantron_clear_skip($scanlines,$scan_data,$i)) {
                   8415: 	    &scantron_putfile($scanlines,$scan_data);
                   8416: 	}
1.161     albertel 8417: 	
1.542     raeburn  8418:         if (&grade_student_bubbles($r,$uname,$udom,$scan_record,$scancode,
1.677     raeburn  8419:                                    \@mapresources,\%partids_by_symb,
1.691     raeburn  8420:                                    $bubbles_per_row,$randomorder,$randompick,
                   8421:                                    \%respnumlookup,\%startline) 
                   8422:             eq 'ssi_error') {
1.542     raeburn  8423:             $ssi_error = 0; # So end of handler error message does not trigger.
                   8424:             $r->print("</form>");
                   8425:             &ssi_print_error($r);
                   8426:             &Apache::lonnet::remove_lock($lock);
                   8427:             return '';      # Why return ''?  Beats me.
                   8428:         }
1.513     foxr     8429: 
1.692     raeburn  8430:         if (($scancode) && ($randomorder || $randompick)) {
                   8431:             my $parmresult =
                   8432:                 &Apache::lonparmset::storeparm_by_symb($symb,
                   8433:                                                        '0_examcode',2,$scancode,
                   8434:                                                        'string_examcode',$uname,
                   8435:                                                        $udom);
                   8436:         }
1.140     albertel 8437: 	$completedstudents{$uname}={'line'=>$line};
1.542     raeburn  8438:         if ($env{'form.verifyrecord'}) {
                   8439:             my $lastpos = $env{'form.scantron_maxbubble'}*$scantron_config{'Qlength'};
1.691     raeburn  8440:             if ($randompick) {
                   8441:                 if ($total) {
                   8442:                     $lastpos = $total*$scantron_config{'Qlength'};
                   8443:                 }
                   8444:             }
                   8445: 
1.542     raeburn  8446:             my $studentdata = substr($line,$scantron_config{'Qstart'}-1,$lastpos);
                   8447:             chomp($studentdata);
                   8448:             $studentdata =~ s/\r$//;
                   8449:             my $studentrecord = '';
                   8450:             my $counter = -1;
1.677     raeburn  8451:             foreach my $resource (@mapresources) {
1.554     raeburn  8452:                 my $ressymb = $resource->symb();
1.542     raeburn  8453:                 ($counter,my $recording) =
                   8454:                     &verify_scantron_grading($resource,$udom,$uname,$env{'request.course.id'},
1.554     raeburn  8455:                                              $counter,$studentdata,$partids_by_symb{$ressymb},
1.691     raeburn  8456:                                              \%scantron_config,\%lettdig,$numletts,$randomorder,
                   8457:                                              $randompick,\%respnumlookup,\%startline);
1.542     raeburn  8458:                 $studentrecord .= $recording;
                   8459:             }
                   8460:             if ($studentrecord ne $studentdata) {
1.554     raeburn  8461:                 &Apache::lonxml::clear_problem_counter();
                   8462:                 if (&grade_student_bubbles($r,$uname,$udom,$scan_record,$scancode,
1.677     raeburn  8463:                                            \@mapresources,\%partids_by_symb,
1.691     raeburn  8464:                                            $bubbles_per_row,$randomorder,$randompick,
                   8465:                                            \%respnumlookup,\%startline) 
                   8466:                     eq 'ssi_error') {
1.554     raeburn  8467:                     $ssi_error = 0; # So end of handler error message does not trigger.
                   8468:                     $r->print("</form>");
                   8469:                     &ssi_print_error($r);
                   8470:                     &Apache::lonnet::remove_lock($lock);
                   8471:                     delete($completedstudents{$uname});
                   8472:                     return '';
                   8473:                 }
1.542     raeburn  8474:                 $counter = -1;
                   8475:                 $studentrecord = '';
1.677     raeburn  8476:                 foreach my $resource (@mapresources) {
1.554     raeburn  8477:                     my $ressymb = $resource->symb();
1.542     raeburn  8478:                     ($counter,my $recording) =
                   8479:                         &verify_scantron_grading($resource,$udom,$uname,$env{'request.course.id'},
1.554     raeburn  8480:                                                  $counter,$studentdata,$partids_by_symb{$ressymb},
1.691     raeburn  8481:                                                  \%scantron_config,\%lettdig,$numletts,
                   8482:                                                  $randomorder,$randompick,\%respnumlookup,
                   8483:                                                  \%startline);
1.542     raeburn  8484:                     $studentrecord .= $recording;
                   8485:                 }
                   8486:                 if ($studentrecord ne $studentdata) {
1.658     bisitz   8487:                     $r->print('<p><span class="LC_warning">');
1.542     raeburn  8488:                     if ($scancode eq '') {
1.658     bisitz   8489:                         $r->print(&mt('Mismatch grading bubblesheet for user: [_1] with ID: [_2].',
1.542     raeburn  8490:                                   $uname.':'.$udom,$scan_record->{'scantron.ID'}));
                   8491:                     } else {
1.658     bisitz   8492:                         $r->print(&mt('Mismatch grading bubblesheet for user: [_1] with ID: [_2] and CODE: [_3].',
1.542     raeburn  8493:                                   $uname.':'.$udom,$scan_record->{'scantron.ID'},$scancode));
                   8494:                     }
                   8495:                     $r->print('</span><br />'.&Apache::loncommon::start_data_table()."\n".
                   8496:                               &Apache::loncommon::start_data_table_header_row()."\n".
                   8497:                               '<th>'.&mt('Source').'</th><th>'.&mt('Bubbled responses').'</th>'.
                   8498:                               &Apache::loncommon::end_data_table_header_row()."\n".
                   8499:                               &Apache::loncommon::start_data_table_row().
1.658     bisitz   8500:                               '<td>'.&mt('Bubblesheet').'</td>'.
1.707     bisitz   8501:                               '<td><span class="LC_nobreak" style="white-space: pre;"><tt>'.$studentdata.'</tt></span></td>'.
1.542     raeburn  8502:                               &Apache::loncommon::end_data_table_row().
                   8503:                               &Apache::loncommon::start_data_table_row().
1.658     bisitz   8504:                               '<td>'.&mt('Stored submissions').'</td>'.
1.707     bisitz   8505:                               '<td><span class="LC_nobreak" style="white-space: pre;"><tt>'.$studentrecord.'</tt></span></td>'."\n".
1.542     raeburn  8506:                               &Apache::loncommon::end_data_table_row().
                   8507:                               &Apache::loncommon::end_data_table().'</p>');
                   8508:                 } else {
                   8509:                     $r->print('<br /><span class="LC_warning">'.
                   8510:                              &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 />'.
                   8511:                              &mt("As a consequence, this user's submission history records two tries.").
                   8512:                                  '</span><br />');
                   8513:                 }
                   8514:             }
                   8515:         }
1.543     raeburn  8516:         if (&Apache::loncommon::connection_aborted($r)) { last; }
1.140     albertel 8517:     } continue {
1.330     albertel 8518: 	&Apache::lonxml::clear_problem_counter();
1.552     raeburn  8519: 	&Apache::lonnet::delenv('scantron.');
1.82      albertel 8520:     }
1.140     albertel 8521:     &Apache::lonhtmlcommon::Close_PrgWin($r,\%prog_state);
1.520     www      8522:     &Apache::lonnet::remove_lock($lock);
1.172     albertel 8523: #    my $lasttime = &Time::HiRes::time()-$start;
                   8524: #    $r->print("<p>took $lasttime</p>");
1.140     albertel 8525: 
1.200     albertel 8526:     $r->print("</form>");
1.157     albertel 8527:     return '';
1.75      albertel 8528: }
1.157     albertel 8529: 
1.557     raeburn  8530: sub graders_resources_pass {
1.649     raeburn  8531:     my ($resources,$grader_partids_by_symb,$grader_randomlists_by_symb,
                   8532:         $bubbles_per_row) = @_;
1.557     raeburn  8533:     if ((ref($resources) eq 'ARRAY') && (ref($grader_partids_by_symb)) && 
                   8534:         (ref($grader_randomlists_by_symb) eq 'HASH')) {
                   8535:         foreach my $resource (@{$resources}) {
                   8536:             my $ressymb = $resource->symb();
                   8537:             my ($analysis,$parts) =
                   8538:                 &scantron_partids_tograde($resource,$env{'request.course.id'},
1.672     raeburn  8539:                                           $env{'user.name'},$env{'user.domain'},
                   8540:                                           1,$bubbles_per_row);
1.557     raeburn  8541:             $grader_partids_by_symb->{$ressymb} = $parts;
                   8542:             if (ref($analysis) eq 'HASH') {
                   8543:                 if (ref($analysis->{'parts_withrandomlist'}) eq 'ARRAY') {
                   8544:                     $grader_randomlists_by_symb->{$ressymb} =
                   8545:                         $analysis->{'parts_withrandomlist'};
                   8546:                 }
                   8547:             }
                   8548:         }
                   8549:     }
                   8550:     return;
                   8551: }
                   8552: 
1.678     raeburn  8553: =pod
                   8554: 
                   8555: =item users_order
                   8556: 
                   8557:   Returns array of resources in current map, ordered based on either CODE,
                   8558:   if this is a CODEd exam, or based on student's identity if this is a 
                   8559:   "NAMEd" exam.
                   8560: 
1.691     raeburn  8561:   Should be used when randomorder and/or randompick applied when the 
                   8562:   corresponding exam was printed, prior to students completing bubblesheets 
                   8563:   for the version of the exam the student received.
1.678     raeburn  8564: 
                   8565: =cut
                   8566: 
                   8567: sub users_order  {
1.691     raeburn  8568:     my ($user,$scancode,$mapurl,$master_seq,$symb_to_resource,$orderedforcode) = @_;
1.678     raeburn  8569:     my @mapresources;
1.691     raeburn  8570:     unless ((ref($master_seq) eq 'ARRAY') && (ref($symb_to_resource) eq 'HASH')) {
1.678     raeburn  8571:         return @mapresources;
1.691     raeburn  8572:     }
                   8573:     if ($scancode) {
                   8574:         if ((ref($orderedforcode) eq 'HASH') && (ref($orderedforcode->{$scancode}) eq 'ARRAY')) {
                   8575:             @mapresources = @{$orderedforcode->{$scancode}};
                   8576:         } else {
                   8577:             $env{'form.CODE'} = $scancode;
                   8578:             my $actual_seq =
                   8579:                 &Apache::lonprintout::master_seq_to_person_seq($mapurl,
                   8580:                                                                $master_seq,
                   8581:                                                                $user,$scancode,1);
                   8582:             if (ref($actual_seq) eq 'ARRAY') {
                   8583:                 @mapresources = map { $symb_to_resource->{$_}; } @{$actual_seq};
                   8584:                 if (ref($orderedforcode) eq 'HASH') {
                   8585:                     if (@mapresources > 0) { 
                   8586:                         $orderedforcode->{$scancode} = \@mapresources;
                   8587:                     }
                   8588:                 }
                   8589:             }
                   8590:             delete($env{'form.CODE'});
1.678     raeburn  8591:         }
                   8592:     } else {
                   8593:         my $actual_seq =
                   8594:             &Apache::lonprintout::master_seq_to_person_seq($mapurl,
                   8595:                                                            $master_seq,
1.688     raeburn  8596:                                                            $user,undef,1);
1.678     raeburn  8597:         if (ref($actual_seq) eq 'ARRAY') {
                   8598:             @mapresources = 
                   8599:                 map { $symb_to_resource->{$_}; } @{$actual_seq};
                   8600:         }
1.691     raeburn  8601:     }
                   8602:     return @mapresources;
1.678     raeburn  8603: }
                   8604: 
1.542     raeburn  8605: sub grade_student_bubbles {
1.691     raeburn  8606:     my ($r,$uname,$udom,$scan_record,$scancode,$resources,$parts,$bubbles_per_row,
                   8607:         $randomorder,$randompick,$respnumlookup,$startline) = @_;
                   8608:     my $uselookup = 0;
                   8609:     if (($randomorder || $randompick) && (ref($respnumlookup) eq 'HASH') &&
                   8610:         (ref($startline) eq 'HASH')) {
                   8611:         $uselookup = 1;
                   8612:     }
                   8613: 
1.554     raeburn  8614:     if (ref($resources) eq 'ARRAY') {
                   8615:         my $count = 0;
                   8616:         foreach my $resource (@{$resources}) {
                   8617:             my $ressymb = $resource->symb();
                   8618:             my %form = ('submitted'      => 'scantron',
                   8619:                         'grade_target'   => 'grade',
                   8620:                         'grade_username' => $uname,
                   8621:                         'grade_domain'   => $udom,
                   8622:                         'grade_courseid' => $env{'request.course.id'},
                   8623:                         'grade_symb'     => $ressymb,
                   8624:                         'CODE'           => $scancode
                   8625:                        );
1.649     raeburn  8626:             if ($bubbles_per_row ne '') {
                   8627:                 $form{'bubbles_per_row'} = $bubbles_per_row;
                   8628:             }
1.663     raeburn  8629:             if ($env{'form.scantron_lastbubblepoints'} ne '') {
                   8630:                 $form{'scantron_lastbubblepoints'} = $env{'form.scantron_lastbubblepoints'};
                   8631:             }
1.554     raeburn  8632:             if (ref($parts) eq 'HASH') {
                   8633:                 if (ref($parts->{$ressymb}) eq 'ARRAY') {
                   8634:                     foreach my $part (@{$parts->{$ressymb}}) {
1.691     raeburn  8635:                         if ($uselookup) {
                   8636:                             $form{'scantron_questnum_start.'.$part} = $startline->{$count} + 1;
                   8637:                         } else {
                   8638:                             $form{'scantron_questnum_start.'.$part} =
                   8639:                                 1+$env{'form.scantron.first_bubble_line.'.$count};
                   8640:                         }
1.554     raeburn  8641:                         $count++;
                   8642:                     }
                   8643:                 }
                   8644:             }
                   8645:             my $result=&ssi_with_retries($resource->src(),$ssi_retries,%form);
                   8646:             return 'ssi_error' if ($ssi_error);
                   8647:             last if (&Apache::loncommon::connection_aborted($r));
                   8648:         }
1.542     raeburn  8649:     }
                   8650:     return;
                   8651: }
                   8652: 
1.157     albertel 8653: sub scantron_upload_scantron_data {
1.608     www      8654:     my ($r,$symb)=@_;
1.565     raeburn  8655:     my $dom = $env{'request.role.domain'};
                   8656:     my $domdesc = &Apache::lonnet::domain($dom,'description');
                   8657:     $r->print(&Apache::loncommon::coursebrowser_javascript($dom));
1.157     albertel 8658:     my $select_link=&Apache::loncommon::selectcourse_link('rules','courseid',
1.181     albertel 8659: 							  'domainid',
1.565     raeburn  8660: 							  'coursename',$dom);
                   8661:     my $syllabuslink = '<a href="javascript:ToSyllabus();">'.&mt('Syllabus').'</a>'.
                   8662:                        ('&nbsp'x2).&mt('(shows course personnel)'); 
1.608     www      8663:     my $default_form_data=&defaultFormData($symb);
1.579     raeburn  8664:     my $nofile_alert = &mt('Please use the browse button to select a file from your local directory.');
                   8665:     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 8666:     $r->print(&Apache::lonhtmlcommon::scripttag('
1.157     albertel 8667:     function checkUpload(formname) {
                   8668: 	if (formname.upfile.value == "") {
1.579     raeburn  8669: 	    alert("'.$nofile_alert.'");
1.157     albertel 8670: 	    return false;
                   8671: 	}
1.565     raeburn  8672:         if (formname.courseid.value == "") {
1.579     raeburn  8673:             alert("'.$nocourseid_alert.'");
1.565     raeburn  8674:             return false;
                   8675:         }
1.157     albertel 8676: 	formname.submit();
                   8677:     }
1.565     raeburn  8678: 
                   8679:     function ToSyllabus() {
                   8680:         var cdom = '."'$dom'".';
                   8681:         var cnum = document.rules.courseid.value;
                   8682:         if (cdom == "" || cdom == null) {
                   8683:             return;
                   8684:         }
                   8685:         if (cnum == "" || cnum == null) {
                   8686:            return;
                   8687:         }
                   8688:         syllwin=window.open("/public/"+cdom+"/"+cnum+"/syllabus","LONCAPASyllabus",
                   8689:                             "height=350,width=350,scrollbars=yes,menubar=no");
                   8690:         return;
                   8691:     }
                   8692: 
1.597     wenzelju 8693: '));
                   8694:     $r->print('
1.648     bisitz   8695: <h3>'.&mt('Send bubblesheet data to a course').'</h3>
1.566     raeburn  8696: 
1.492     albertel 8697: <form enctype="multipart/form-data" action="/adm/grades" name="rules" method="post">
1.565     raeburn  8698: '.$default_form_data.
                   8699:   &Apache::lonhtmlcommon::start_pick_box().
                   8700:   &Apache::lonhtmlcommon::row_title(&mt('Course ID')).
                   8701:   '<input name="courseid" type="text" size="30" />'.$select_link.
                   8702:   &Apache::lonhtmlcommon::row_closure().
                   8703:   &Apache::lonhtmlcommon::row_title(&mt('Course Name')).
                   8704:   '<input name="coursename" type="text" size="30" />'.$syllabuslink.
                   8705:   &Apache::lonhtmlcommon::row_closure().
                   8706:   &Apache::lonhtmlcommon::row_title(&mt('Domain')).
                   8707:   '<input name="domainid" type="hidden" />'.$domdesc.
                   8708:   &Apache::lonhtmlcommon::row_closure().
                   8709:   &Apache::lonhtmlcommon::row_title(&mt('File to upload')).
                   8710:   '<input type="file" name="upfile" size="50" />'.
                   8711:   &Apache::lonhtmlcommon::row_closure(1).
                   8712:   &Apache::lonhtmlcommon::end_pick_box().'<br />
                   8713: 
1.492     albertel 8714: <input name="command" value="scantronupload_save" type="hidden" />
1.589     bisitz   8715: <input type="button" onclick="javascript:checkUpload(this.form);" value="'.&mt('Upload Bubblesheet Data').'" />
1.157     albertel 8716: </form>
1.492     albertel 8717: ');
1.157     albertel 8718:     return '';
                   8719: }
                   8720: 
1.423     albertel 8721: 
1.157     albertel 8722: sub scantron_upload_scantron_data_save {
1.608     www      8723:     my($r,$symb)=@_;
1.182     albertel 8724:     my $doanotherupload=
                   8725: 	'<br /><form action="/adm/grades" method="post">'."\n".
                   8726: 	'<input type="hidden" name="command" value="scantronupload" />'."\n".
1.492     albertel 8727: 	'<input type="submit" name="submit" value="'.&mt('Do Another Upload').'" />'."\n".
1.182     albertel 8728: 	'</form>'."\n";
1.257     albertel 8729:     if (!&Apache::lonnet::allowed('usc',$env{'form.domainid'}) &&
1.162     albertel 8730: 	!&Apache::lonnet::allowed('usc',
1.257     albertel 8731: 			    $env{'form.domainid'}.'_'.$env{'form.courseid'})) {
1.575     www      8732: 	$r->print(&mt("You are not allowed to upload bubblesheet data to the requested course.")."<br />");
1.614     www      8733: 	unless ($symb) {
1.182     albertel 8734: 	    $r->print($doanotherupload);
                   8735: 	}
1.162     albertel 8736: 	return '';
                   8737:     }
1.257     albertel 8738:     my %coursedata=&Apache::lonnet::coursedescription($env{'form.domainid'}.'_'.$env{'form.courseid'});
1.568     raeburn  8739:     my $uploadedfile;
1.710     bisitz   8740:     $r->print('<p>'.&mt('Uploading file to [_1]','"'.$coursedata{'description'}.'"').'</p>');
1.257     albertel 8741:     if (length($env{'form.upfile'}) < 2) {
1.710     bisitz   8742:         $r->print(
                   8743:             &Apache::lonhtmlcommon::confirm_success(
                   8744:                 &mt('The file: [_1] you attempted to upload contained no information. Please check that you entered the correct filename.',
                   8745:                         '<span class="LC_filename">'.&HTML::Entities::encode($env{'form.upfile.filename'},'<>&"').'</span>'),1));
1.183     albertel 8746:     } else {
1.568     raeburn  8747:         my $result = 
                   8748:             &Apache::lonnet::userfileupload('upfile','','scantron','','','',
                   8749:                                             $env{'form.courseid'},$env{'form.domainid'});
1.710     bisitz   8750:         if ($result =~ m{^/uploaded/}) {
                   8751:             $r->print(
                   8752:                 &Apache::lonhtmlcommon::confirm_success(&mt('Upload successful')).'<br />'.
                   8753:                 &mt('Uploaded [_1] bytes of data into location: [_2]',
                   8754:                         (length($env{'form.upfile'})-1),
                   8755:                         '<span class="LC_filename">'.$result.'</span>'));
1.568     raeburn  8756:             ($uploadedfile) = ($result =~ m{/([^/]+)$});
1.567     raeburn  8757:             $r->print(&validate_uploaded_scantron_file($env{'form.domainid'},
1.568     raeburn  8758:                                                        $env{'form.courseid'},$uploadedfile));
1.710     bisitz   8759:         } else {
                   8760:             $r->print(
                   8761:                 &Apache::lonhtmlcommon::confirm_success(&mt('Upload failed'),1).'<br />'.
                   8762:                     &mt('An error ([_1]) occurred when attempting to upload the file: [_2]',
                   8763:                           $result,
1.568     raeburn  8764: 			  '<span class="LC_filename">'.&HTML::Entities::encode($env{'form.upfile.filename'},'<>&"').'</span>'));
1.183     albertel 8765: 	}
                   8766:     }
1.174     albertel 8767:     if ($symb) {
1.612     www      8768: 	$r->print(&scantron_selectphase($r,$uploadedfile,$symb));
1.174     albertel 8769:     } else {
1.182     albertel 8770: 	$r->print($doanotherupload);
1.174     albertel 8771:     }
1.157     albertel 8772:     return '';
                   8773: }
                   8774: 
1.567     raeburn  8775: sub validate_uploaded_scantron_file {
                   8776:     my ($cdom,$cname,$fname) = @_;
                   8777:     my $scanlines=&Apache::lonnet::getfile('/uploaded/'.$cdom.'/'.$cname.'/'.$fname);
                   8778:     my @lines;
                   8779:     if ($scanlines ne '-1') {
                   8780:         @lines=split("\n",$scanlines,-1);
                   8781:     }
                   8782:     my $output;
                   8783:     if (@lines) {
                   8784:         my (%counts,$max_match_format);
1.710     bisitz   8785:         my ($found_match_count,$max_match_count,$max_match_pct) = (0,0,0);
1.567     raeburn  8786:         my $classlist = &Apache::loncoursedata::get_classlist($cdom,$cname);
                   8787:         my %idmap = &username_to_idmap($classlist);
                   8788:         foreach my $key (keys(%idmap)) {
                   8789:             my $lckey = lc($key);
                   8790:             $idmap{$lckey} = $idmap{$key};
                   8791:         }
                   8792:         my %unique_formats;
                   8793:         my @formatlines = &get_scantronformat_file();
                   8794:         foreach my $line (@formatlines) {
                   8795:             chomp($line);
                   8796:             my @config = split(/:/,$line);
                   8797:             my $idstart = $config[5];
                   8798:             my $idlength = $config[6];
                   8799:             if (($idstart ne '') && ($idlength > 0)) {
                   8800:                 if (ref($unique_formats{$idstart.':'.$idlength}) eq 'ARRAY') {
                   8801:                     push(@{$unique_formats{$idstart.':'.$idlength}},$config[0].':'.$config[1]); 
                   8802:                 } else {
                   8803:                     $unique_formats{$idstart.':'.$idlength} = [$config[0].':'.$config[1]];
                   8804:                 }
                   8805:             }
                   8806:         }
                   8807:         foreach my $key (keys(%unique_formats)) {
                   8808:             my ($idstart,$idlength) = split(':',$key);
                   8809:             %{$counts{$key}} = (
                   8810:                                'found'   => 0,
                   8811:                                'total'   => 0,
                   8812:                               );
                   8813:             foreach my $line (@lines) {
                   8814:                 next if ($line =~ /^#/);
                   8815:                 next if ($line =~ /^[\s\cz]*$/);
                   8816:                 my $id = substr($line,$idstart-1,$idlength);
                   8817:                 $id = lc($id);
                   8818:                 if (exists($idmap{$id})) {
                   8819:                     $counts{$key}{'found'} ++;
                   8820:                 }
                   8821:                 $counts{$key}{'total'} ++;
                   8822:             }
                   8823:             if ($counts{$key}{'total'}) {
                   8824:                 my $percent_match = (100*$counts{$key}{'found'})/($counts{$key}{'total'});
                   8825:                 if (($max_match_format eq '') || ($percent_match > $max_match_pct)) {
                   8826:                     $max_match_pct = $percent_match;
                   8827:                     $max_match_format = $key;
1.710     bisitz   8828:                     $found_match_count = $counts{$key}{'found'};
1.567     raeburn  8829:                     $max_match_count = $counts{$key}{'total'};
                   8830:                 }
                   8831:             }
                   8832:         }
                   8833:         if (ref($unique_formats{$max_match_format}) eq 'ARRAY') {
                   8834:             my $format_descs;
                   8835:             my $numwithformat = @{$unique_formats{$max_match_format}};
                   8836:             for (my $i=0; $i<$numwithformat; $i++) {
                   8837:                 my ($name,$desc) = split(':',$unique_formats{$max_match_format}[$i]);
                   8838:                 if ($i<$numwithformat-2) {
                   8839:                     $format_descs .= '"<i>'.$desc.'</i>", ';
                   8840:                 } elsif ($i==$numwithformat-2) {
                   8841:                     $format_descs .= '"<i>'.$desc.'</i>" '.&mt('and').' ';
                   8842:                 } elsif ($i==$numwithformat-1) {
                   8843:                     $format_descs .= '"<i>'.$desc.'</i>"';
                   8844:                 }
                   8845:             }
                   8846:             my $showpct = sprintf("%.0f",$max_match_pct).'%';
1.710     bisitz   8847:             $output .= '<br />';
                   8848:             if ($found_match_count == $max_match_count) {
                   8849:                 # 100% matching entries
                   8850:                 $output .= &Apache::lonhtmlcommon::confirm_success(
                   8851:                      &mt('Comparison of student IDs: [_1] matching ([quant,_2,entry,entries])',
                   8852:                             '<b>'.$showpct.'</b>',$found_match_count)).'<br />'.
                   8853:                 &mt('Comparison of student IDs in the uploaded file with'.
                   8854:                     ' the course roster found matches for [_1] of the [_2] entries'.
                   8855:                     ' in the file (for the format defined for [_3]).',
                   8856:                         '<b>'.$showpct.'</b>','<b>'.$max_match_count.'</b>',$format_descs);
                   8857:             } else {
                   8858:                 # Not all entries matching? -> Show warning and additional info
                   8859:                 $output .=
                   8860:                     &Apache::lonhtmlcommon::confirm_success(
                   8861:                         &mt('Comparison of student IDs: [_1] matching ([_2]/[quant,_3,entry,entries])',
                   8862:                                 '<b>'.$showpct.'</b>',$found_match_count,$max_match_count).'<br />'.
                   8863:                         &mt('Not all entries could be matched!'),1).'<br />'.
                   8864:                     &mt('Comparison of student IDs in the uploaded file with'.
                   8865:                         ' the course roster found matches for [_1] of the [_2] entries'.
                   8866:                         ' in the file (for the format defined for [_3]).',
                   8867:                             '<b>'.$showpct.'</b>','<b>'.$max_match_count.'</b>',$format_descs).
                   8868:                     '<p class="LC_info">'.
                   8869:                     &mt('A low percentage of matches results from one of the following:').
                   8870:                     '</p><ul>'.
                   8871:                     '<li>'.&mt('The file was uploaded to the wrong course.').'</li>'.
                   8872:                     '<li>'.&mt('The data is not in the format expected for the domain: [_1]',
                   8873:                                '<i>'.$cdom.'</i>').'</li>'.
                   8874:                     '<li>'.&mt('Students did not bubble their IDs, or mis-bubbled them').'</li>'.
                   8875:                     '<li>'.&mt('The course roster is not up to date.').'</li>'.
                   8876:                     '</ul>';
                   8877:             }
1.567     raeburn  8878:         }
                   8879:     } else {
1.710     bisitz   8880:         $output = '<p class="LC_warning">'.&mt('Uploaded file contained no data').'</p>';
1.567     raeburn  8881:     }
                   8882:     return $output;
                   8883: }
                   8884: 
1.202     albertel 8885: sub valid_file {
                   8886:     my ($requested_file)=@_;
                   8887:     foreach my $filename (sort(&scantron_filenames())) {
                   8888: 	if ($requested_file eq $filename) { return 1; }
                   8889:     }
                   8890:     return 0;
                   8891: }
                   8892: 
                   8893: sub scantron_download_scantron_data {
1.608     www      8894:     my ($r,$symb)=@_;
                   8895:     my $default_form_data=&defaultFormData($symb);
1.257     albertel 8896:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   8897:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
                   8898:     my $file=$env{'form.scantron_selectfile'};
1.202     albertel 8899:     if (! &valid_file($file)) {
1.492     albertel 8900: 	$r->print('
1.202     albertel 8901: 	<p>
1.686     bisitz   8902: 	    '.&mt('The requested filename was invalid.').'
1.202     albertel 8903:         </p>
1.492     albertel 8904: ');
1.202     albertel 8905: 	return;
                   8906:     }
                   8907:     my $orig='/uploaded/'.$cdom.'/'.$cname.'/scantron_orig_'.$file;
                   8908:     my $corrected='/uploaded/'.$cdom.'/'.$cname.'/scantron_corrected_'.$file;
                   8909:     my $skipped='/uploaded/'.$cdom.'/'.$cname.'/scantron_skipped_'.$file;
                   8910:     &Apache::lonnet::allowuploaded('/adm/grades',$orig);
                   8911:     &Apache::lonnet::allowuploaded('/adm/grades',$corrected);
                   8912:     &Apache::lonnet::allowuploaded('/adm/grades',$skipped);
1.492     albertel 8913:     $r->print('
1.202     albertel 8914:     <p>
1.723     raeburn  8915: 	'.&mt('[_1]Original[_2] file as uploaded by the bubblesheet scanning office.',
1.492     albertel 8916: 	      '<a href="'.$orig.'">','</a>').'
1.202     albertel 8917:     </p>
                   8918:     <p>
1.492     albertel 8919: 	'.&mt('[_1]Corrections[_2], a file of corrected records that were used in grading.',
                   8920: 	      '<a href="'.$corrected.'">','</a>').'
1.202     albertel 8921:     </p>
                   8922:     <p>
1.492     albertel 8923: 	'.&mt('[_1]Skipped[_2], a file of records that were skipped.',
                   8924: 	      '<a href="'.$skipped.'">','</a>').'
1.202     albertel 8925:     </p>
1.492     albertel 8926: ');
1.202     albertel 8927:     return '';
                   8928: }
1.157     albertel 8929: 
1.523     raeburn  8930: sub checkscantron_results {
1.608     www      8931:     my ($r,$symb) = @_;
1.523     raeburn  8932:     if (!$symb) {return '';}
                   8933:     my $cid = $env{'request.course.id'};
1.542     raeburn  8934:     my %lettdig = &letter_to_digits();
1.523     raeburn  8935:     my $numletts = scalar(keys(%lettdig));
                   8936:     my $cnum = $env{'course.'.$cid.'.num'};
                   8937:     my $cdom = $env{'course.'.$cid.'.domain'};
                   8938:     my (undef, undef, $sequence) = &Apache::lonnet::decode_symb($env{'form.selectpage'});
                   8939:     my %record;
                   8940:     my %scantron_config =
                   8941:         &Apache::grades::get_scantron_config($env{'form.scantron_format'});
1.649     raeburn  8942:     my $bubbles_per_row = &bubblesheet_bubbles_per_row(\%scantron_config);
1.523     raeburn  8943:     my ($scanlines,$scan_data)=&Apache::grades::scantron_getfile();
                   8944:     my $classlist=&Apache::loncoursedata::get_classlist();
                   8945:     my %idmap=&Apache::grades::username_to_idmap($classlist);
                   8946:     my $navmap=Apache::lonnavmaps::navmap->new();
1.582     raeburn  8947:     unless (ref($navmap)) {
                   8948:         $r->print(&navmap_errormsg());
                   8949:         return '';
                   8950:     }
1.523     raeburn  8951:     my $map=$navmap->getResourceByUrl($sequence);
1.691     raeburn  8952:     my ($randomorder,$randompick,@master_seq,%symb_to_resource,%grader_partids_by_symb,
                   8953:         %grader_randomlists_by_symb,%orderedforcode);
1.677     raeburn  8954:     if (ref($map)) { 
                   8955:         $randomorder=$map->randomorder();
1.689     raeburn  8956:         $randompick=$map->randompick();
1.677     raeburn  8957:     }
1.557     raeburn  8958:     my @resources=$navmap->retrieveResources($map,\&scantron_filter,1,0);
1.691     raeburn  8959:     my $nav_error = &get_master_seq(\@resources,\@master_seq,\%symb_to_resource);
                   8960:     if ($nav_error) {
                   8961:         $r->print(&navmap_errormsg());
                   8962:         return '';
1.678     raeburn  8963:     }
1.673     raeburn  8964:     &graders_resources_pass(\@resources,\%grader_partids_by_symb,
                   8965:                             \%grader_randomlists_by_symb,$bubbles_per_row);
1.554     raeburn  8966:     my ($uname,$udom);
1.523     raeburn  8967:     my (%scandata,%lastname,%bylast);
                   8968:     $r->print('
                   8969: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="checkscantron">'."\n");
                   8970: 
                   8971:     my @delayqueue;
                   8972:     my %completedstudents;
                   8973: 
1.691     raeburn  8974:     my $count=&get_todo_count($scanlines,$scan_data);
1.667     www      8975:     my %prog_state=&Apache::lonhtmlcommon::Create_PrgWin($r,$count);
1.706     raeburn  8976:     my ($username,$domain,$started);
1.649     raeburn  8977:     &scantron_get_maxbubble(\$nav_error,\%scantron_config); # Need the bubble lines array to parse.
1.582     raeburn  8978:     if ($nav_error) {
                   8979:         $r->print(&navmap_errormsg());
                   8980:         return '';
                   8981:     }
1.523     raeburn  8982: 
1.667     www      8983:     &Apache::lonhtmlcommon::Update_PrgWin($r,\%prog_state,'Processing first student');
1.523     raeburn  8984:     my $start=&Time::HiRes::time();
                   8985:     my $i=-1;
                   8986: 
                   8987:     while ($i<$scanlines->{'count'}) {
                   8988:         ($username,$domain,$uname)=('','','');
                   8989:         $i++;
                   8990:         my $line=&Apache::grades::scantron_get_line($scanlines,$scan_data,$i);
                   8991:         if ($line=~/^[\s\cz]*$/) { next; }
                   8992:         if ($started) {
1.667     www      8993:             &Apache::lonhtmlcommon::Increment_PrgWin($r,\%prog_state,'last student');
1.523     raeburn  8994:         }
                   8995:         $started=1;
                   8996:         my $scan_record=
                   8997:             &Apache::grades::scantron_parse_scanline($line,$i,\%scantron_config,
                   8998:                                                      $scan_data);
1.693     raeburn  8999:         unless ($uname=&scantron_find_student($scan_record,$scan_data,
                   9000:                                               \%idmap,$i)) {
1.523     raeburn  9001:             &Apache::grades::scantron_add_delay(\@delayqueue,$line,
                   9002:                                 'Unable to find a student that matches',1);
                   9003:             next;
                   9004:         }
                   9005:         if (exists $completedstudents{$uname}) {
                   9006:             &Apache::grades::scantron_add_delay(\@delayqueue,$line,
                   9007:                                 'Student '.$uname.' has multiple sheets',2);
                   9008:             next;
                   9009:         }
                   9010:         my $pid = $scan_record->{'scantron.ID'};
                   9011:         $lastname{$pid} = $scan_record->{'scantron.LastName'};
                   9012:         push(@{$bylast{$lastname{$pid}}},$pid);
1.678     raeburn  9013:         my $usec = $classlist->{$uname}->[&Apache::loncoursedata::CL_SECTION];
                   9014:         my $user = $uname.':'.$usec;
1.523     raeburn  9015:         ($username,$domain)=split(/:/,$uname);
1.677     raeburn  9016: 
1.678     raeburn  9017:         my $scancode;
1.677     raeburn  9018:         if ((exists($scan_record->{'scantron.CODE'})) &&
                   9019:             (&Apache::lonnet::validCODE($scan_record->{'scantron.CODE'}))) {
                   9020:             $scancode = $scan_record->{'scantron.CODE'};
                   9021:         } else {
                   9022:             $scancode = '';
                   9023:         }
                   9024: 
                   9025:         my @mapresources = @resources;
1.691     raeburn  9026:         my $lastpos = $env{'form.scantron_maxbubble'}*$scantron_config{'Qlength'};
                   9027:         my %respnumlookup=();
                   9028:         my %startline=();
1.689     raeburn  9029:         if ($randomorder || $randompick) {
1.678     raeburn  9030:             @mapresources =
1.691     raeburn  9031:                 &users_order($user,$scancode,$sequence,\@master_seq,\%symb_to_resource,
                   9032:                              \%orderedforcode);
                   9033:             my $total = &get_respnum_lookups($sequence,$scan_data,\%idmap,$line,
                   9034:                                              $scan_record,\@master_seq,\%symb_to_resource,
                   9035:                                              \%grader_partids_by_symb,\%orderedforcode,
                   9036:                                              \%respnumlookup,\%startline);
                   9037:             if ($randompick && $total) {
                   9038:                 $lastpos = $total*$scantron_config{'Qlength'};
                   9039:             }
1.677     raeburn  9040:         }
1.691     raeburn  9041:         $scandata{$pid} = substr($line,$scantron_config{'Qstart'}-1,$lastpos);
                   9042:         chomp($scandata{$pid});
                   9043:         $scandata{$pid} =~ s/\r$//;
                   9044: 
1.523     raeburn  9045:         my $counter = -1;
1.677     raeburn  9046:         foreach my $resource (@mapresources) {
1.557     raeburn  9047:             my $parts;
1.554     raeburn  9048:             my $ressymb = $resource->symb();
1.557     raeburn  9049:             if ((exists($grader_randomlists_by_symb{$ressymb})) ||
                   9050:                 (ref($grader_partids_by_symb{$ressymb}) ne 'ARRAY')) {
                   9051:                 (my $analysis,$parts) =
1.672     raeburn  9052:                     &scantron_partids_tograde($resource,$env{'request.course.id'},
                   9053:                                               $username,$domain,undef,
                   9054:                                               $bubbles_per_row);
1.557     raeburn  9055:             } else {
                   9056:                 $parts = $grader_partids_by_symb{$ressymb};
                   9057:             }
1.542     raeburn  9058:             ($counter,my $recording) =
                   9059:                 &verify_scantron_grading($resource,$domain,$username,$cid,$counter,
1.554     raeburn  9060:                                          $scandata{$pid},$parts,
1.691     raeburn  9061:                                          \%scantron_config,\%lettdig,$numletts,
                   9062:                                          $randomorder,$randompick,
                   9063:                                          \%respnumlookup,\%startline);
1.542     raeburn  9064:             $record{$pid} .= $recording;
1.523     raeburn  9065:         }
                   9066:     }
                   9067:     &Apache::lonhtmlcommon::Close_PrgWin($r,\%prog_state);
                   9068:     $r->print('<br />');
                   9069:     my ($okstudents,$badstudents,$numstudents,$passed,$failed);
                   9070:     $passed = 0;
                   9071:     $failed = 0;
                   9072:     $numstudents = 0;
                   9073:     foreach my $last (sort(keys(%bylast))) {
                   9074:         if (ref($bylast{$last}) eq 'ARRAY') {
                   9075:             foreach my $pid (sort(@{$bylast{$last}})) {
                   9076:                 my $showscandata = $scandata{$pid};
                   9077:                 my $showrecord = $record{$pid};
                   9078:                 $showscandata =~ s/\s/&nbsp;/g;
                   9079:                 $showrecord =~ s/\s/&nbsp;/g;
                   9080:                 if ($scandata{$pid} eq $record{$pid}) {
                   9081:                     my $css_class = ($passed % 2)?'LC_odd_row':'LC_even_row';
                   9082:                     $okstudents .= '<tr class="'.$css_class.'">'.
1.581     www      9083: '<td>'.&mt('Bubblesheet').'</td><td>'.$showscandata.'</td><td rowspan="2">'.$last.'</td><td rowspan="2">'.$pid.'</td>'."\n".
1.523     raeburn  9084: '</tr>'."\n".
                   9085: '<tr class="'.$css_class.'">'."\n".
1.721     bisitz   9086: '<td>'.&mt('Submissions').'</td><td>'.$showrecord.'</td></tr>'."\n";
1.523     raeburn  9087:                     $passed ++;
                   9088:                 } else {
                   9089:                     my $css_class = ($failed % 2)?'LC_odd_row':'LC_even_row';
1.581     www      9090:                     $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  9091: '</tr>'."\n".
                   9092: '<tr class="'.$css_class.'">'."\n".
1.721     bisitz   9093: '<td>'.&mt('Submissions').'</td><td><span class="LC_nobreak">'.$record{$pid}.'</span></td>'."\n".
1.523     raeburn  9094: '</tr>'."\n";
                   9095:                     $failed ++;
                   9096:                 }
                   9097:                 $numstudents ++;
                   9098:             }
                   9099:         }
                   9100:     }
1.648     bisitz   9101:     $r->print(
                   9102:         '<p>'
                   9103:        .&mt('Comparison of bubblesheet data (including corrections) with corresponding submission records (most recent submission) for [_1][quant,_2,student][_3] ([quant,_4,bubblesheet line] per student).',
                   9104:             '<b>',
                   9105:             $numstudents,
                   9106:             '</b>',
                   9107:             $env{'form.scantron_maxbubble'})
                   9108:        .'</p>'
                   9109:     );
1.682     raeburn  9110:     $r->print('<p>'
1.683     raeburn  9111:              .&mt('Exact matches for [_1][quant,_2,student][_3].','<b>',$passed,'</b>')
1.682     raeburn  9112:              .'<br />'
                   9113:              .&mt('Discrepancies detected for [_1][quant,_2,student][_3].','<b>',$failed,'</b>')
                   9114:              .'</p>'
                   9115:     );
1.523     raeburn  9116:     if ($passed) {
1.572     www      9117:         $r->print(&mt('Students with exact correspondence between bubblesheet data and submissions are as follows:').'<br /><br />');
1.523     raeburn  9118:         $r->print(&Apache::loncommon::start_data_table()."\n".
                   9119:                  &Apache::loncommon::start_data_table_header_row()."\n".
                   9120:                  '<th>'.&mt('Source').'</th><th>'.&mt('Bubble records').'</th><th>'.&mt('Name').'</th><th>'.&mt('ID').'</th>'.
                   9121:                  &Apache::loncommon::end_data_table_header_row()."\n".
                   9122:                  $okstudents."\n".
                   9123:                  &Apache::loncommon::end_data_table().'<br />');
                   9124:     }
                   9125:     if ($failed) {
1.572     www      9126:         $r->print(&mt('Students with differences between bubblesheet data and submissions are as follows:').'<br /><br />');
1.523     raeburn  9127:         $r->print(&Apache::loncommon::start_data_table()."\n".
                   9128:                  &Apache::loncommon::start_data_table_header_row()."\n".
                   9129:                  '<th>'.&mt('Source').'</th><th>'.&mt('Bubble records').'</th><th>'.&mt('Name').'</th><th>'.&mt('ID').'</th>'.
                   9130:                  &Apache::loncommon::end_data_table_header_row()."\n".
                   9131:                  $badstudents."\n".
                   9132:                  &Apache::loncommon::end_data_table()).'<br />'.
1.572     www      9133:                  &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  9134:     }
1.614     www      9135:     $r->print('</form><br />');
1.523     raeburn  9136:     return;
                   9137: }
                   9138: 
1.542     raeburn  9139: sub verify_scantron_grading {
1.554     raeburn  9140:     my ($resource,$domain,$username,$cid,$counter,$scandata,$partids,
1.691     raeburn  9141:         $scantron_config,$lettdig,$numletts,$randomorder,$randompick,
                   9142:         $respnumlookup,$startline) = @_;
1.542     raeburn  9143:     my ($record,%expected,%startpos);
                   9144:     return ($counter,$record) if (!ref($resource));
                   9145:     return ($counter,$record) if (!$resource->is_problem());
                   9146:     my $symb = $resource->symb();
1.554     raeburn  9147:     return ($counter,$record) if (ref($partids) ne 'ARRAY');
                   9148:     foreach my $part_id (@{$partids}) {
1.542     raeburn  9149:         $counter ++;
                   9150:         $expected{$part_id} = 0;
1.691     raeburn  9151:         my $respnum = $counter;
                   9152:         if ($randomorder || $randompick) {
                   9153:             $respnum = $respnumlookup->{$counter};
                   9154:             $startpos{$part_id} = $startline->{$counter} + 1;
                   9155:         } else {
                   9156:             $startpos{$part_id} = $env{"form.scantron.first_bubble_line.$counter"};
                   9157:         }
                   9158:         if ($env{"form.scantron.sub_bubblelines.$respnum"}) {
                   9159:             my @sub_lines = split(/,/,$env{"form.scantron.sub_bubblelines.$respnum"});
1.542     raeburn  9160:             foreach my $item (@sub_lines) {
                   9161:                 $expected{$part_id} += $item;
                   9162:             }
                   9163:         } else {
1.691     raeburn  9164:             $expected{$part_id} = $env{"form.scantron.bubblelines.$respnum"};
1.542     raeburn  9165:         }
                   9166:     }
                   9167:     if ($symb) {
                   9168:         my %recorded;
                   9169:         my (%returnhash) = &Apache::lonnet::restore($symb,$cid,$domain,$username);
                   9170:         if ($returnhash{'version'}) {
                   9171:             my %lasthash=();
                   9172:             my $version;
                   9173:             for ($version=1;$version<=$returnhash{'version'};$version++) {
                   9174:                 foreach my $key (sort(split(/\:/,$returnhash{$version.':keys'}))) {
                   9175:                     $lasthash{$key}=$returnhash{$version.':'.$key};
                   9176:                 }
                   9177:             }
                   9178:             foreach my $key (keys(%lasthash)) {
                   9179:                 if ($key =~ /\.scantron$/) {
                   9180:                     my $value = &unescape($lasthash{$key});
                   9181:                     my ($part_id) = ($key =~ /^resource\.(.+)\.scantron$/);
                   9182:                     if ($value eq '') {
                   9183:                         for (my $i=0; $i<$expected{$part_id}; $i++) {
                   9184:                             for (my $j=0; $j<$scantron_config->{'length'}; $j++) {
                   9185:                                 $recorded{$part_id} .= $scantron_config->{'Qoff'};
                   9186:                             }
                   9187:                         }
                   9188:                     } else {
                   9189:                         my @tocheck;
                   9190:                         my @items = split(//,$value);
                   9191:                         if (($scantron_config->{'Qon'} eq 'letter') ||
                   9192:                             ($scantron_config->{'Qon'} eq 'number')) {
                   9193:                             if (@items < $expected{$part_id}) {
                   9194:                                 my $fragment = substr($scandata,$startpos{$part_id},$expected{$part_id});
                   9195:                                 my @singles = split(//,$fragment);
                   9196:                                 foreach my $pos (@singles) {
                   9197:                                     if ($pos eq ' ') {
                   9198:                                         push(@tocheck,$pos);
                   9199:                                     } else {
                   9200:                                         my $next = shift(@items);
                   9201:                                         push(@tocheck,$next);
                   9202:                                     }
                   9203:                                 }
                   9204:                             } else {
                   9205:                                 @tocheck = @items;
                   9206:                             }
                   9207:                             foreach my $letter (@tocheck) {
                   9208:                                 if ($scantron_config->{'Qon'} eq 'letter') {
                   9209:                                     if ($letter !~ /^[A-J]$/) {
                   9210:                                         $letter = $scantron_config->{'Qoff'};
                   9211:                                     }
                   9212:                                     $recorded{$part_id} .= $letter;
                   9213:                                 } elsif ($scantron_config->{'Qon'} eq 'number') {
                   9214:                                     my $digit;
                   9215:                                     if ($letter !~ /^[A-J]$/) {
                   9216:                                         $digit = $scantron_config->{'Qoff'};
                   9217:                                     } else {
                   9218:                                         $digit = $lettdig->{$letter};
                   9219:                                     }
                   9220:                                     $recorded{$part_id} .= $digit;
                   9221:                                 }
                   9222:                             }
                   9223:                         } else {
                   9224:                             @tocheck = @items;
                   9225:                             for (my $i=0; $i<$expected{$part_id}; $i++) {
                   9226:                                 my $curr_sub = shift(@tocheck);
                   9227:                                 my $digit;
                   9228:                                 if ($curr_sub =~ /^[A-J]$/) {
                   9229:                                     $digit = $lettdig->{$curr_sub}-1;
                   9230:                                 }
                   9231:                                 if ($curr_sub eq 'J') {
                   9232:                                     $digit += scalar($numletts);
                   9233:                                 }
                   9234:                                 for (my $j=0; $j<$scantron_config->{'Qlength'}; $j++) {
                   9235:                                     if ($j == $digit) {
                   9236:                                         $recorded{$part_id} .= $scantron_config->{'Qon'};
                   9237:                                     } else {
                   9238:                                         $recorded{$part_id} .= $scantron_config->{'Qoff'};
                   9239:                                     }
                   9240:                                 }
                   9241:                             }
                   9242:                         }
                   9243:                     }
                   9244:                 }
                   9245:             }
                   9246:         }
1.554     raeburn  9247:         foreach my $part_id (@{$partids}) {
1.542     raeburn  9248:             if ($recorded{$part_id} eq '') {
                   9249:                 for (my $i=0; $i<$expected{$part_id}; $i++) {
                   9250:                     for (my $j=0; $j<$scantron_config->{'Qlength'}; $j++) {
                   9251:                         $recorded{$part_id} .= $scantron_config->{'Qoff'};
                   9252:                     }
                   9253:                 }
                   9254:             }
                   9255:             $record .= $recorded{$part_id};
                   9256:         }
                   9257:     }
                   9258:     return ($counter,$record);
                   9259: }
                   9260: 
1.691     raeburn  9261: sub letter_to_digits {
1.542     raeburn  9262:     my %lettdig = (
                   9263:                     A => 1,
                   9264:                     B => 2,
                   9265:                     C => 3,
                   9266:                     D => 4,
                   9267:                     E => 5,
                   9268:                     F => 6,
                   9269:                     G => 7,
                   9270:                     H => 8,
                   9271:                     I => 9,
                   9272:                     J => 0,
                   9273:                   );
                   9274:     return %lettdig;
                   9275: }
                   9276: 
1.423     albertel 9277: 
1.75      albertel 9278: #-------- end of section for handling grading scantron forms -------
                   9279: #
                   9280: #-------------------------------------------------------------------
                   9281: 
1.72      ng       9282: #-------------------------- Menu interface -------------------------
                   9283: #
1.614     www      9284: #--- Href with symb and command ---
                   9285: 
                   9286: sub href_symb_cmd {
                   9287:     my ($symb,$cmd)=@_;
1.669     raeburn  9288:     return '/adm/grades?symb='.&HTML::Entities::encode(&Apache::lonenc::check_encrypt($symb),'<>&"').'&amp;command='.$cmd;
1.72      ng       9289: }
                   9290: 
1.443     banghart 9291: sub grading_menu {
1.608     www      9292:     my ($request,$symb) = @_;
1.443     banghart 9293:     if (!$symb) {return '';}
                   9294: 
                   9295:     my %fields = ('symb'=>&Apache::lonenc::check_encrypt($symb),
1.618     www      9296:                   'command'=>'individual');
1.538     schulted 9297:     
1.598     www      9298:     my $url1a = &Apache::lonhtmlcommon::build_url('grades/',\%fields);
                   9299: 
                   9300:     $fields{'command'}='ungraded';
                   9301:     my $url1b=&Apache::lonhtmlcommon::build_url('grades/',\%fields);
                   9302: 
                   9303:     $fields{'command'}='table';
                   9304:     my $url1c=&Apache::lonhtmlcommon::build_url('grades/',\%fields);
                   9305: 
                   9306:     $fields{'command'}='all_for_one';
                   9307:     my $url1d=&Apache::lonhtmlcommon::build_url('grades/',\%fields);
                   9308: 
1.621     www      9309:     $fields{'command'}='downloadfilesselect';
                   9310:     my $url1e=&Apache::lonhtmlcommon::build_url('grades/',\%fields);
                   9311: 
1.443     banghart 9312:     $fields{'command'} = 'csvform';
1.538     schulted 9313:     my $url2 = &Apache::lonhtmlcommon::build_url('grades/',\%fields);
                   9314:     
1.443     banghart 9315:     $fields{'command'} = 'processclicker';
1.538     schulted 9316:     my $url3 = &Apache::lonhtmlcommon::build_url('grades/',\%fields);
                   9317:     
1.443     banghart 9318:     $fields{'command'} = 'scantron_selectphase';
1.538     schulted 9319:     my $url4 = &Apache::lonhtmlcommon::build_url('grades/',\%fields);
1.602     www      9320: 
                   9321:     $fields{'command'} = 'initialverifyreceipt';
                   9322:     my $url5 = &Apache::lonhtmlcommon::build_url('grades/',\%fields);
1.538     schulted 9323:     
1.598     www      9324:     my @menu = ({	categorytitle=>'Hand Grading',
1.538     schulted 9325:             items =>[
1.598     www      9326:                         {	linktext => 'Select individual students to grade',
                   9327:                     		url => $url1a,
1.538     schulted 9328:                     		permission => 'F',
1.636     wenzelju 9329:                     		icon => 'grade_students.png',
1.598     www      9330:                     		linktitle => 'Grade current resource for a selection of students.'
                   9331:                         }, 
                   9332:                         {       linktext => 'Grade ungraded submissions.',
                   9333:                                 url => $url1b,
                   9334:                                 permission => 'F',
1.636     wenzelju 9335:                                 icon => 'ungrade_sub.png',
1.598     www      9336:                                 linktitle => 'Grade all submissions that have not been graded yet.'
1.538     schulted 9337:                         },
1.598     www      9338: 
                   9339:                         {       linktext => 'Grading table',
                   9340:                                 url => $url1c,
                   9341:                                 permission => 'F',
1.636     wenzelju 9342:                                 icon => 'grading_table.png',
1.598     www      9343:                                 linktitle => 'Grade current resource for all students.'
                   9344:                         },
1.615     www      9345:                         {       linktext => 'Grade page/folder for one student',
1.598     www      9346:                                 url => $url1d,
                   9347:                                 permission => 'F',
1.636     wenzelju 9348:                                 icon => 'grade_PageFolder.png',
1.598     www      9349:                                 linktitle => 'Grade all resources in current page/sequence/folder for one student.'
1.621     www      9350:                         },
                   9351:                         {       linktext => 'Download submissions',
                   9352:                                 url => $url1e,
                   9353:                                 permission => 'F',
1.636     wenzelju 9354:                                 icon => 'download_sub.png',
1.621     www      9355:                                 linktitle => 'Download all students submissions.'
1.598     www      9356:                         }]},
                   9357:                          { categorytitle=>'Automated Grading',
                   9358:                items =>[
                   9359: 
1.538     schulted 9360:                 	    {	linktext => 'Upload Scores',
                   9361:                     		url => $url2,
                   9362:                     		permission => 'F',
                   9363:                     		icon => 'uploadscores.png',
                   9364:                     		linktitle => 'Specify a file containing the class scores for current resource.'
                   9365:                 	    },
                   9366:                 	    {	linktext => 'Process Clicker',
                   9367:                     		url => $url3,
                   9368:                     		permission => 'F',
                   9369:                     		icon => 'addClickerInfoFile.png',
                   9370:                     		linktitle => 'Specify a file containing the clicker information for this resource.'
                   9371:                 	    },
1.587     raeburn  9372:                 	    {	linktext => 'Grade/Manage/Review Bubblesheets',
1.538     schulted 9373:                     		url => $url4,
                   9374:                     		permission => 'F',
1.636     wenzelju 9375:                     		icon => 'bubblesheet.png',
1.648     bisitz   9376:                     		linktitle => 'Grade bubblesheet exams, upload/download bubblesheet data files, and review previously graded bubblesheet exams.'
1.602     www      9377:                 	    },
1.616     www      9378:                             {   linktext => 'Verify Receipt Number',
1.602     www      9379:                                 url => $url5,
                   9380:                                 permission => 'F',
1.636     wenzelju 9381:                                 icon => 'receipt_number.png',
1.602     www      9382:                                 linktitle => 'Verify a system-generated receipt number for correct problem solution.'
                   9383:                             }
                   9384: 
1.538     schulted 9385:                     ]
                   9386:             });
                   9387: 
1.443     banghart 9388:     # Create the menu
                   9389:     my $Str;
1.445     banghart 9390:     $Str .= '<form method="post" action="" name="gradingMenu">';
                   9391:     $Str .= '<input type="hidden" name="command" value="" />'.
1.618     www      9392:     	'<input type="hidden" name="symb"        value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n";
1.445     banghart 9393: 
1.602     www      9394:     $Str .= &Apache::lonhtmlcommon::generate_menu(@menu);
1.443     banghart 9395:     return $Str;    
                   9396: }
                   9397: 
1.598     www      9398: 
                   9399: sub ungraded {
                   9400:     my ($request)=@_;
                   9401:     &submit_options($request);
                   9402: }
                   9403: 
1.599     www      9404: sub submit_options_sequence {
1.608     www      9405:     my ($request,$symb) = @_;
1.599     www      9406:     if (!$symb) {return '';}
1.600     www      9407:     &commonJSfunctions($request);
                   9408:     my $result;
1.599     www      9409: 
1.600     www      9410:     $result.='<form action="/adm/grades" method="post" name="gradingMenu">'."\n".
1.618     www      9411:         '<input type="hidden" name="symb"        value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n";
1.632     www      9412:     $result.=&selectfield(0).
1.601     www      9413:             '<input type="hidden" name="command" value="pickStudentPage" />
1.600     www      9414:             <div>
                   9415:               <input type="submit" value="'.&mt('Next').' &rarr;" />
                   9416:             </div>
                   9417:         </div>
                   9418:   </form>';
                   9419:     return $result;
                   9420: }
                   9421: 
                   9422: sub submit_options_table {
1.608     www      9423:     my ($request,$symb) = @_;
1.600     www      9424:     if (!$symb) {return '';}
1.599     www      9425:     &commonJSfunctions($request);
                   9426:     my $result;
                   9427: 
                   9428:     $result.='<form action="/adm/grades" method="post" name="gradingMenu">'."\n".
1.618     www      9429:         '<input type="hidden" name="symb"        value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n";
1.599     www      9430: 
1.632     www      9431:     $result.=&selectfield(0).
1.601     www      9432:             '<input type="hidden" name="command" value="viewgrades" />
1.599     www      9433:             <div>
                   9434:               <input type="submit" value="'.&mt('Next').' &rarr;" />
                   9435:             </div>
                   9436:         </div>
                   9437:   </form>';
                   9438:     return $result;
                   9439: }
1.443     banghart 9440: 
1.621     www      9441: sub submit_options_download {
                   9442:     my ($request,$symb) = @_;
                   9443:     if (!$symb) {return '';}
                   9444: 
                   9445:     &commonJSfunctions($request);
                   9446: 
                   9447:     my $result='<form action="/adm/grades" method="post" name="gradingMenu">'."\n".
                   9448:         '<input type="hidden" name="symb"        value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n";
                   9449:     $result.='
                   9450: <h2>
                   9451:   '.&mt('Select Students for Which to Download Submissions').'
                   9452: </h2>'.&selectfield(1).'
                   9453:                 <input type="hidden" name="command" value="downloadfileslink" /> 
                   9454:               <input type="submit" value="'.&mt('Next').' &rarr;" />
                   9455:             </div>
                   9456:           </div>
1.600     www      9457: 
                   9458: 
1.621     www      9459:   </form>';
                   9460:     return $result;
                   9461: }
                   9462: 
1.443     banghart 9463: #--- Displays the submissions first page -------
                   9464: sub submit_options {
1.608     www      9465:     my ($request,$symb) = @_;
1.72      ng       9466:     if (!$symb) {return '';}
                   9467: 
1.118     ng       9468:     &commonJSfunctions($request);
1.473     albertel 9469:     my $result;
1.533     bisitz   9470: 
1.72      ng       9471:     $result.='<form action="/adm/grades" method="post" name="gradingMenu">'."\n".
1.618     www      9472: 	'<input type="hidden" name="symb"        value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n";
1.632     www      9473:     $result.=&selectfield(1).'
1.601     www      9474:                 <input type="hidden" name="command" value="submission" /> 
                   9475: 	      <input type="submit" value="'.&mt('Next').' &rarr;" />
                   9476:             </div>
                   9477:           </div>
                   9478: 
                   9479: 
                   9480:   </form>';
                   9481:     return $result;
                   9482: }
1.533     bisitz   9483: 
1.601     www      9484: sub selectfield {
                   9485:    my ($full)=@_;
1.635     raeburn  9486:    my %options = 
                   9487:           (&Apache::lonlocal::texthash(
                   9488:              'yes'       => 'with submissions',
                   9489:              'queued'    => 'in grading queue',
                   9490:              'graded'    => 'with ungraded submissions',
                   9491:              'incorrect' => 'with incorrect submissions',
                   9492:              'all'       => 'with any status'),
                   9493:              'select_form_order' => ['yes','queued','graded','incorrect','all']);
1.601     www      9494:    my $result='<div class="LC_columnSection">
1.537     harmsja  9495:   
1.533     bisitz   9496:     <fieldset>
                   9497:       <legend>
                   9498:        '.&mt('Sections').'
                   9499:       </legend>
1.601     www      9500:       '.&Apache::lonstatistics::SectionSelect('section','multiple',5).'
1.533     bisitz   9501:     </fieldset>
1.537     harmsja  9502:   
1.533     bisitz   9503:     <fieldset>
                   9504:       <legend>
                   9505:         '.&mt('Groups').'
                   9506:       </legend>
                   9507:       '.&Apache::lonstatistics::GroupSelect('group','multiple',5).'
                   9508:     </fieldset>
1.537     harmsja  9509:   
1.533     bisitz   9510:     <fieldset>
                   9511:       <legend>
                   9512:         '.&mt('Access Status').'
                   9513:       </legend>
1.601     www      9514:       '.&Apache::lonhtmlcommon::StatusOptions(undef,undef,5,undef,'mult').'
                   9515:     </fieldset>';
                   9516:     if ($full) {
                   9517:        $result.='
1.533     bisitz   9518:     <fieldset>
                   9519:       <legend>
                   9520:         '.&mt('Submission Status').'
1.601     www      9521:       </legend>'.
1.635     raeburn  9522:        &Apache::loncommon::select_form('all','submitonly',\%options).
1.601     www      9523:    '</fieldset>';
                   9524:     }
                   9525:     $result.='</div><br />';
1.44      ng       9526:     return $result;
1.2       albertel 9527: }
                   9528: 
1.285     albertel 9529: sub reset_perm {
                   9530:     undef(%perm);
                   9531: }
                   9532: 
                   9533: sub init_perm {
                   9534:     &reset_perm();
1.300     albertel 9535:     foreach my $test_perm ('vgr','mgr','opa') {
                   9536: 
                   9537: 	my $scope = $env{'request.course.id'};
                   9538: 	if (!($perm{$test_perm}=&Apache::lonnet::allowed($test_perm,$scope))) {
                   9539: 
                   9540: 	    $scope .= '/'.$env{'request.course.sec'};
                   9541: 	    if ( $perm{$test_perm}=
                   9542: 		 &Apache::lonnet::allowed($test_perm,$scope)) {
                   9543: 		$perm{$test_perm.'_section'}=$env{'request.course.sec'};
                   9544: 	    } else {
                   9545: 		delete($perm{$test_perm});
                   9546: 	    }
1.285     albertel 9547: 	}
                   9548:     }
                   9549: }
                   9550: 
1.674     raeburn  9551: sub init_old_essays {
                   9552:     my ($symb,$apath,$adom,$aname) = @_;
                   9553:     if ($symb ne '') {
                   9554:         my %essays = &Apache::lonnet::dump('nohist_essay_'.$apath,$adom,$aname);
                   9555:         if (keys(%essays) > 0) {
                   9556:             $old_essays{$symb} = \%essays;
                   9557:         }
                   9558:     }
                   9559:     return;
                   9560: }
                   9561: 
                   9562: sub reset_old_essays {
                   9563:     undef(%old_essays);
                   9564: }
                   9565: 
1.400     www      9566: sub gather_clicker_ids {
1.408     albertel 9567:     my %clicker_ids;
1.400     www      9568: 
                   9569:     my $classlist = &Apache::loncoursedata::get_classlist();
                   9570: 
                   9571:     # Set up a couple variables.
1.407     albertel 9572:     my $username_idx = &Apache::loncoursedata::CL_SNAME();
                   9573:     my $domain_idx   = &Apache::loncoursedata::CL_SDOM();
1.438     www      9574:     my $status_idx   = &Apache::loncoursedata::CL_STATUS();
1.400     www      9575: 
1.407     albertel 9576:     foreach my $student (keys(%$classlist)) {
1.438     www      9577:         if ($classlist->{$student}->[$status_idx] ne 'Active') { next; }
1.407     albertel 9578:         my $username = $classlist->{$student}->[$username_idx];
                   9579:         my $domain   = $classlist->{$student}->[$domain_idx];
1.400     www      9580:         my $clickers =
1.408     albertel 9581: 	    (&Apache::lonnet::userenvironment($domain,$username,'clickers'))[1];
1.400     www      9582:         foreach my $id (split(/\,/,$clickers)) {
1.414     www      9583:             $id=~s/^[\#0]+//;
1.421     www      9584:             $id=~s/[\-\:]//g;
1.407     albertel 9585:             if (exists($clicker_ids{$id})) {
1.408     albertel 9586: 		$clicker_ids{$id}.=','.$username.':'.$domain;
1.400     www      9587:             } else {
1.408     albertel 9588: 		$clicker_ids{$id}=$username.':'.$domain;
1.400     www      9589:             }
                   9590:         }
                   9591:     }
1.407     albertel 9592:     return %clicker_ids;
1.400     www      9593: }
                   9594: 
1.402     www      9595: sub gather_adv_clicker_ids {
1.408     albertel 9596:     my %clicker_ids;
1.402     www      9597:     my $cnum=$env{'course.'.$env{'request.course.id'}.'.num'};
                   9598:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
                   9599:     my %coursepersonnel=&Apache::lonnet::get_course_adv_roles($cdom.'/'.$cnum);
1.409     albertel 9600:     foreach my $element (sort(keys(%coursepersonnel))) {
1.402     www      9601:         foreach my $person (split(/\,/,$coursepersonnel{$element})) {
                   9602:             my ($puname,$pudom)=split(/\:/,$person);
                   9603:             my $clickers =
1.408     albertel 9604: 		(&Apache::lonnet::userenvironment($pudom,$puname,'clickers'))[1];
1.405     www      9605:             foreach my $id (split(/\,/,$clickers)) {
1.414     www      9606: 		$id=~s/^[\#0]+//;
1.421     www      9607:                 $id=~s/[\-\:]//g;
1.408     albertel 9608: 		if (exists($clicker_ids{$id})) {
                   9609: 		    $clicker_ids{$id}.=','.$puname.':'.$pudom;
                   9610: 		} else {
                   9611: 		    $clicker_ids{$id}=$puname.':'.$pudom;
                   9612: 		}
1.405     www      9613:             }
1.402     www      9614:         }
                   9615:     }
1.407     albertel 9616:     return %clicker_ids;
1.402     www      9617: }
                   9618: 
1.413     www      9619: sub clicker_grading_parameters {
                   9620:     return ('gradingmechanism' => 'scalar',
                   9621:             'upfiletype' => 'scalar',
                   9622:             'specificid' => 'scalar',
                   9623:             'pcorrect' => 'scalar',
                   9624:             'pincorrect' => 'scalar');
                   9625: }
                   9626: 
1.400     www      9627: sub process_clicker {
1.608     www      9628:     my ($r,$symb)=@_;
1.400     www      9629:     if (!$symb) {return '';}
                   9630:     my $result=&checkforfile_js();
1.632     www      9631:     $result.=&Apache::loncommon::start_data_table().
                   9632:              &Apache::loncommon::start_data_table_header_row().
                   9633:              '<th>'.&mt('Specify a file containing clicker information and set grading options.').'</th>'.
                   9634:              &Apache::loncommon::end_data_table_header_row().
                   9635:              &Apache::loncommon::start_data_table_row()."<td>\n";
1.413     www      9636: # Attempt to restore parameters from last session, set defaults if not present
                   9637:     my %Saveable_Parameters=&clicker_grading_parameters();
                   9638:     &Apache::loncommon::restore_course_settings('grades_clicker',
                   9639:                                                  \%Saveable_Parameters);
                   9640:     if (!$env{'form.pcorrect'}) { $env{'form.pcorrect'}=100; }
                   9641:     if (!$env{'form.pincorrect'}) { $env{'form.pincorrect'}=100; }
                   9642:     if (!$env{'form.gradingmechanism'}) { $env{'form.gradingmechanism'}='attendance'; }
                   9643:     if (!$env{'form.upfiletype'}) { $env{'form.upfiletype'}='iclicker'; }
                   9644: 
                   9645:     my %checked;
1.521     www      9646:     foreach my $gradingmechanism ('attendance','personnel','specific','given') {
1.413     www      9647:        if ($env{'form.gradingmechanism'} eq $gradingmechanism) {
1.569     bisitz   9648:           $checked{$gradingmechanism}=' checked="checked"';
1.413     www      9649:        }
                   9650:     }
                   9651: 
1.632     www      9652:     my $upload=&mt("Evaluate File");
1.400     www      9653:     my $type=&mt("Type");
1.402     www      9654:     my $attendance=&mt("Award points just for participation");
                   9655:     my $personnel=&mt("Correctness determined from response by course personnel");
1.414     www      9656:     my $specific=&mt("Correctness determined from response with clicker ID(s)"); 
1.521     www      9657:     my $given=&mt("Correctness determined from given list of answers").' '.
                   9658:               '<font size="-2"><tt>('.&mt("Provide comma-separated list. Use '*' for any answer correct, '-' for skip").')</tt></font>';
1.402     www      9659:     my $pcorrect=&mt("Percentage points for correct solution");
                   9660:     my $pincorrect=&mt("Percentage points for incorrect solution");
1.413     www      9661:     my $selectform=&Apache::loncommon::select_form($env{'form.upfiletype'},'upfiletype',
1.635     raeburn  9662: 						   {'iclicker' => 'i>clicker',
1.666     www      9663:                                                     'interwrite' => 'interwrite PRS',
                   9664:                                                     'turning' => 'Turning Technologies'});
1.418     albertel 9665:     $symb = &Apache::lonenc::check_encrypt($symb);
1.597     wenzelju 9666:     $result.= &Apache::lonhtmlcommon::scripttag(<<ENDUPFORM);
1.402     www      9667: function sanitycheck() {
                   9668: // Accept only integer percentages
                   9669:    document.forms.gradesupload.pcorrect.value=Math.round(document.forms.gradesupload.pcorrect.value);
                   9670:    document.forms.gradesupload.pincorrect.value=Math.round(document.forms.gradesupload.pincorrect.value);
                   9671: // Find out grading choice
                   9672:    for (i=0; i<document.forms.gradesupload.gradingmechanism.length; i++) {
                   9673:       if (document.forms.gradesupload.gradingmechanism[i].checked) {
                   9674:          gradingchoice=document.forms.gradesupload.gradingmechanism[i].value;
                   9675:       }
                   9676:    }
                   9677: // By default, new choice equals user selection
                   9678:    newgradingchoice=gradingchoice;
                   9679: // Not good to give more points for false answers than correct ones
                   9680:    if (Math.round(document.forms.gradesupload.pcorrect.value)<Math.round(document.forms.gradesupload.pincorrect.value)) {
                   9681:       document.forms.gradesupload.pcorrect.value=document.forms.gradesupload.pincorrect.value;
                   9682:    }
                   9683: // If new choice is attendance only, and old choice was correctness-based, restore defaults
                   9684:    if ((gradingchoice=='attendance') && (document.forms.gradesupload.waschecked.value!='attendance')) {
                   9685:       document.forms.gradesupload.pcorrect.value=100;
                   9686:       document.forms.gradesupload.pincorrect.value=100;
                   9687:    }
                   9688: // If the values are different, cannot be attendance only
                   9689:    if ((Math.round(document.forms.gradesupload.pcorrect.value)!=Math.round(document.forms.gradesupload.pincorrect.value)) &&
                   9690:        (gradingchoice=='attendance')) {
                   9691:        newgradingchoice='personnel';
                   9692:    }
                   9693: // Change grading choice to new one
                   9694:    for (i=0; i<document.forms.gradesupload.gradingmechanism.length; i++) {
                   9695:       if (document.forms.gradesupload.gradingmechanism[i].value==newgradingchoice) {
                   9696:          document.forms.gradesupload.gradingmechanism[i].checked=true;
                   9697:       } else {
                   9698:          document.forms.gradesupload.gradingmechanism[i].checked=false;
                   9699:       }
                   9700:    }
                   9701: // Remember the old state
                   9702:    document.forms.gradesupload.waschecked.value=newgradingchoice;
                   9703: }
1.597     wenzelju 9704: ENDUPFORM
                   9705:     $result.= <<ENDUPFORM;
1.400     www      9706: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="gradesupload">
                   9707: <input type="hidden" name="symb" value="$symb" />
                   9708: <input type="hidden" name="command" value="processclickerfile" />
                   9709: <input type="file" name="upfile" size="50" />
                   9710: <br /><label>$type: $selectform</label>
1.632     www      9711: ENDUPFORM
                   9712:     $result.='</td>'.&Apache::loncommon::end_data_table_row().
                   9713:                      &Apache::loncommon::start_data_table_row().'<td>'.(<<ENDGRADINGFORM);
                   9714:       <label><input type="radio" name="gradingmechanism" value="attendance"$checked{'attendance'} onclick="sanitycheck()" />$attendance </label>
1.589     bisitz   9715: <br /><label><input type="radio" name="gradingmechanism" value="personnel"$checked{'personnel'} onclick="sanitycheck()" />$personnel</label>
                   9716: <br /><label><input type="radio" name="gradingmechanism" value="specific"$checked{'specific'} onclick="sanitycheck()" />$specific </label>
1.414     www      9717: <input type="text" name="specificid" value="$env{'form.specificid'}" size="20" />
1.589     bisitz   9718: <br /><label><input type="radio" name="gradingmechanism" value="given"$checked{'given'} onclick="sanitycheck()" />$given </label>
1.521     www      9719: <br />&nbsp;&nbsp;&nbsp;
                   9720: <input type="text" name="givenanswer" size="50" />
1.413     www      9721: <input type="hidden" name="waschecked" value="$env{'form.gradingmechanism'}" />
1.632     www      9722: ENDGRADINGFORM
                   9723:          $result.='</td>'.&Apache::loncommon::end_data_table_row().
                   9724:                      &Apache::loncommon::start_data_table_row().'<td>'.(<<ENDPERCFORM);
                   9725:       <label>$pcorrect: <input type="text" name="pcorrect" size="4" value="$env{'form.pcorrect'}" onchange="sanitycheck()" /></label>
1.589     bisitz   9726: <br /><label>$pincorrect: <input type="text" name="pincorrect" size="4" value="$env{'form.pincorrect'}" onchange="sanitycheck()" /></label>
                   9727: <br /><input type="button" onclick="javascript:checkUpload(this.form);" value="$upload" />
1.597     wenzelju 9728: </form>'
1.632     www      9729: ENDPERCFORM
                   9730:     $result.='</td>'.
                   9731:              &Apache::loncommon::end_data_table_row().
                   9732:              &Apache::loncommon::end_data_table();
1.400     www      9733:     return $result;
                   9734: }
                   9735: 
                   9736: sub process_clicker_file {
1.608     www      9737:     my ($r,$symb)=@_;
1.400     www      9738:     if (!$symb) {return '';}
1.413     www      9739: 
                   9740:     my %Saveable_Parameters=&clicker_grading_parameters();
                   9741:     &Apache::loncommon::store_course_settings('grades_clicker',
                   9742:                                               \%Saveable_Parameters);
1.598     www      9743:     my $result='';
1.404     www      9744:     if (($env{'form.gradingmechanism'} eq 'specific') && ($env{'form.specificid'}!~/\w/)) {
1.408     albertel 9745: 	$result.='<span class="LC_error">'.&mt('You need to specify a clicker ID for the correct answer').'</span>';
1.614     www      9746: 	return $result;
1.404     www      9747:     }
1.522     www      9748:     if (($env{'form.gradingmechanism'} eq 'given') && ($env{'form.givenanswer'}!~/\S/)) {
1.521     www      9749:         $result.='<span class="LC_error">'.&mt('You need to specify the correct answer').'</span>';
1.614     www      9750:         return $result;
1.521     www      9751:     }
1.522     www      9752:     my $foundgiven=0;
1.521     www      9753:     if ($env{'form.gradingmechanism'} eq 'given') {
                   9754:         $env{'form.givenanswer'}=~s/^\s*//gs;
                   9755:         $env{'form.givenanswer'}=~s/\s*$//gs;
1.644     www      9756:         $env{'form.givenanswer'}=~s/[^a-zA-Z0-9\.\*\-\+]+/\,/g;
1.521     www      9757:         $env{'form.givenanswer'}=uc($env{'form.givenanswer'});
1.522     www      9758:         my @answers=split(/\,/,$env{'form.givenanswer'});
                   9759:         $foundgiven=$#answers+1;
1.521     www      9760:     }
1.407     albertel 9761:     my %clicker_ids=&gather_clicker_ids();
1.408     albertel 9762:     my %correct_ids;
1.404     www      9763:     if ($env{'form.gradingmechanism'} eq 'personnel') {
1.408     albertel 9764: 	%correct_ids=&gather_adv_clicker_ids();
1.404     www      9765:     }
                   9766:     if ($env{'form.gradingmechanism'} eq 'specific') {
1.414     www      9767: 	foreach my $correct_id (split(/[\s\,]/,$env{'form.specificid'})) {;
                   9768: 	   $correct_id=~tr/a-z/A-Z/;
                   9769: 	   $correct_id=~s/\s//gs;
                   9770: 	   $correct_id=~s/^[\#0]+//;
1.421     www      9771:            $correct_id=~s/[\-\:]//g;
1.414     www      9772:            if ($correct_id) {
                   9773: 	      $correct_ids{$correct_id}='specified';
                   9774:            }
                   9775:         }
1.400     www      9776:     }
1.404     www      9777:     if ($env{'form.gradingmechanism'} eq 'attendance') {
1.408     albertel 9778: 	$result.=&mt('Score based on attendance only');
1.521     www      9779:     } elsif ($env{'form.gradingmechanism'} eq 'given') {
1.522     www      9780:         $result.=&mt('Score based on [_1] ([_2] answers)','<tt>'.$env{'form.givenanswer'}.'</tt>',$foundgiven);
1.404     www      9781:     } else {
1.408     albertel 9782: 	my $number=0;
1.411     www      9783: 	$result.='<p><b>'.&mt('Correctness determined by the following IDs').'</b>';
1.408     albertel 9784: 	foreach my $id (sort(keys(%correct_ids))) {
1.411     www      9785: 	    $result.='<br /><tt>'.$id.'</tt> - ';
1.408     albertel 9786: 	    if ($correct_ids{$id} eq 'specified') {
                   9787: 		$result.=&mt('specified');
                   9788: 	    } else {
                   9789: 		my ($uname,$udom)=split(/\:/,$correct_ids{$id});
                   9790: 		$result.=&Apache::loncommon::plainname($uname,$udom);
                   9791: 	    }
                   9792: 	    $number++;
                   9793: 	}
1.411     www      9794:         $result.="</p>\n";
1.710     bisitz   9795:         if ($number==0) {
                   9796:             $result .=
                   9797:                  &Apache::lonhtmlcommon::confirm_success(
                   9798:                      &mt('No IDs found to determine correct answer'),1);
                   9799:             return $result;
                   9800:         }
1.404     www      9801:     }
1.405     www      9802:     if (length($env{'form.upfile'}) < 2) {
1.710     bisitz   9803:         $result .=
                   9804:             &Apache::lonhtmlcommon::confirm_success(
                   9805:                 &mt('The file: [_1] you attempted to upload contained no information. Please check that you entered the correct filename.',
                   9806:                         '<span class="LC_filename">'.&HTML::Entities::encode($env{'form.upfile.filename'},'<>&"').'</span>'),1);
1.614     www      9807:         return $result;
1.405     www      9808:     }
1.410     www      9809: 
                   9810: # Were able to get all the info needed, now analyze the file
                   9811: 
1.411     www      9812:     $result.=&Apache::loncommon::studentbrowser_javascript();
1.418     albertel 9813:     $symb = &Apache::lonenc::check_encrypt($symb);
1.632     www      9814:     $result.=&Apache::loncommon::start_data_table().
                   9815:              &Apache::loncommon::start_data_table_header_row().
                   9816:              '<th>'.&mt('Evaluate clicker file').'</th>'.
                   9817:              &Apache::loncommon::end_data_table_header_row().
                   9818:              &Apache::loncommon::start_data_table_row().(<<ENDHEADER);
                   9819: <td>
1.410     www      9820: <form method="post" action="/adm/grades" name="clickeranalysis">
                   9821: <input type="hidden" name="symb" value="$symb" />
                   9822: <input type="hidden" name="command" value="assignclickergrades" />
1.411     www      9823: <input type="hidden" name="gradingmechanism" value="$env{'form.gradingmechanism'}" />
                   9824: <input type="hidden" name="pcorrect" value="$env{'form.pcorrect'}" />
                   9825: <input type="hidden" name="pincorrect" value="$env{'form.pincorrect'}" />
1.410     www      9826: ENDHEADER
1.522     www      9827:     if ($env{'form.gradingmechanism'} eq 'given') {
                   9828:        $result.='<input type="hidden" name="correct:given" value="'.$env{'form.givenanswer'}.'" />';
                   9829:     } 
1.408     albertel 9830:     my %responses;
                   9831:     my @questiontitles;
1.405     www      9832:     my $errormsg='';
                   9833:     my $number=0;
                   9834:     if ($env{'form.upfiletype'} eq 'iclicker') {
1.408     albertel 9835: 	($errormsg,$number)=&iclicker_eval(\@questiontitles,\%responses);
1.406     www      9836:     }
1.419     www      9837:     if ($env{'form.upfiletype'} eq 'interwrite') {
                   9838:         ($errormsg,$number)=&interwrite_eval(\@questiontitles,\%responses);
                   9839:     }
1.666     www      9840:     if ($env{'form.upfiletype'} eq 'turning') {
                   9841:         ($errormsg,$number)=&turning_eval(\@questiontitles,\%responses);
                   9842:     }
1.411     www      9843:     $result.='<br />'.&mt('Found [_1] question(s)',$number).'<br />'.
                   9844:              '<input type="hidden" name="number" value="'.$number.'" />'.
                   9845:              &mt('Awarding [_1] percent for correct and [_2] percent for incorrect responses',
                   9846:                  $env{'form.pcorrect'},$env{'form.pincorrect'}).
                   9847:              '<br />';
1.522     www      9848:     if (($env{'form.gradingmechanism'} eq 'given') && ($number!=$foundgiven)) {
                   9849:        $result.='<span class="LC_error">'.&mt('Number of given answers does not agree with number of questions in file.').'</span>';
1.614     www      9850:        return $result;
1.522     www      9851:     } 
1.414     www      9852: # Remember Question Titles
                   9853: # FIXME: Possibly need delimiter other than ":"
                   9854:     for (my $i=0;$i<$number;$i++) {
                   9855:         $result.='<input type="hidden" name="question:'.$i.'" value="'.
                   9856:                  &HTML::Entities::encode($questiontitles[$i],'"&<>').'" />';
                   9857:     }
1.411     www      9858:     my $correct_count=0;
                   9859:     my $student_count=0;
                   9860:     my $unknown_count=0;
1.414     www      9861: # Match answers with usernames
                   9862: # FIXME: Possibly need delimiter other than ":"
1.409     albertel 9863:     foreach my $id (keys(%responses)) {
1.410     www      9864:        if ($correct_ids{$id}) {
1.414     www      9865:           $result.="\n".'<input type="hidden" name="correct:'.$correct_count.':'.$correct_ids{$id}.'" value="'.$responses{$id}.'" />';
1.411     www      9866:           $correct_count++;
1.410     www      9867:        } elsif ($clicker_ids{$id}) {
1.437     www      9868:           if ($clicker_ids{$id}=~/\,/) {
                   9869: # More than one user with the same clicker!
1.632     www      9870:              $result.="</td>".&Apache::loncommon::end_data_table_row().
                   9871:                            &Apache::loncommon::start_data_table_row()."<td>".
                   9872:                        &mt('Clicker registered more than once').": <tt>".$id."</tt><br />";
1.437     www      9873:              $result.="\n".'<input type="hidden" name="unknown:'.$id.'" value="'.$responses{$id}.'" />'.
                   9874:                            "<select name='multi".$id."'>";
                   9875:              foreach my $reguser (sort(split(/\,/,$clicker_ids{$id}))) {
                   9876:                  $result.="<option value='".$reguser."'>".&Apache::loncommon::plainname(split(/\:/,$reguser)).' ('.$reguser.')</option>';
                   9877:              }
                   9878:              $result.='</select>';
                   9879:              $unknown_count++;
                   9880:           } else {
                   9881: # Good: found one and only one user with the right clicker
                   9882:              $result.="\n".'<input type="hidden" name="student:'.$clicker_ids{$id}.'" value="'.$responses{$id}.'" />';
                   9883:              $student_count++;
                   9884:           }
1.410     www      9885:        } else {
1.632     www      9886:           $result.="</td>".&Apache::loncommon::end_data_table_row().
                   9887:                            &Apache::loncommon::start_data_table_row()."<td>".
                   9888:                     &mt('Unregistered Clicker')." <tt>".$id."</tt><br />";
1.411     www      9889:           $result.="\n".'<input type="hidden" name="unknown:'.$id.'" value="'.$responses{$id}.'" />'.
                   9890:                    "\n".&mt("Username").": <input type='text' name='uname".$id."' />&nbsp;".
                   9891:                    "\n".&mt("Domain").": ".
                   9892:                    &Apache::loncommon::select_dom_form($env{'course.'.$env{'request.course.id'}.'.domain'},'udom'.$id).'&nbsp;'.
1.643     www      9893:                    &Apache::loncommon::selectstudent_link('clickeranalysis','uname'.$id,'udom'.$id,0,$id);
1.411     www      9894:           $unknown_count++;
1.410     www      9895:        }
1.405     www      9896:     }
1.412     www      9897:     $result.='<hr />'.
                   9898:              &mt('Found [_1] registered and [_2] unregistered clickers.',$student_count,$unknown_count);
1.521     www      9899:     if (($env{'form.gradingmechanism'} ne 'attendance') && ($env{'form.gradingmechanism'} ne 'given')) {
1.412     www      9900:        if ($correct_count==0) {
1.696     bisitz   9901:           $errormsg.="Found no correct answers for grading!";
1.412     www      9902:        } elsif ($correct_count>1) {
1.414     www      9903:           $result.='<br /><span class="LC_warning">'.&mt("Found [_1] entries for grading!",$correct_count).'</span>';
1.412     www      9904:        }
                   9905:     }
1.428     www      9906:     if ($number<1) {
                   9907:        $errormsg.="Found no questions.";
                   9908:     }
1.412     www      9909:     if ($errormsg) {
                   9910:        $result.='<br /><span class="LC_error">'.&mt($errormsg).'</span>';
                   9911:     } else {
                   9912:        $result.='<br /><input type="submit" name="finalize" value="'.&mt('Finalize Grading').'" />';
                   9913:     }
1.632     www      9914:     $result.='</form></td>'.
                   9915:              &Apache::loncommon::end_data_table_row().
                   9916:              &Apache::loncommon::end_data_table();
1.614     www      9917:     return $result;
1.400     www      9918: }
                   9919: 
1.405     www      9920: sub iclicker_eval {
1.406     www      9921:     my ($questiontitles,$responses)=@_;
1.405     www      9922:     my $number=0;
                   9923:     my $errormsg='';
                   9924:     foreach my $line (split(/[\n\r]/,$env{'form.upfile'})) {
1.410     www      9925:         my %components=&Apache::loncommon::record_sep($line);
                   9926:         my @entries=map {$components{$_}} (sort(keys(%components)));
1.408     albertel 9927: 	if ($entries[0] eq 'Question') {
                   9928: 	    for (my $i=3;$i<$#entries;$i+=6) {
                   9929: 		$$questiontitles[$number]=$entries[$i];
                   9930: 		$number++;
                   9931: 	    }
                   9932: 	}
                   9933: 	if ($entries[0]=~/^\#/) {
                   9934: 	    my $id=$entries[0];
                   9935: 	    my @idresponses;
                   9936: 	    $id=~s/^[\#0]+//;
                   9937: 	    for (my $i=0;$i<$number;$i++) {
                   9938: 		my $idx=3+$i*6;
1.644     www      9939:                 $entries[$idx]=~s/[^a-zA-Z0-9\.\*\-\+]+//g;
1.408     albertel 9940: 		push(@idresponses,$entries[$idx]);
                   9941: 	    }
                   9942: 	    $$responses{$id}=join(',',@idresponses);
                   9943: 	}
1.405     www      9944:     }
                   9945:     return ($errormsg,$number);
                   9946: }
                   9947: 
1.419     www      9948: sub interwrite_eval {
                   9949:     my ($questiontitles,$responses)=@_;
                   9950:     my $number=0;
                   9951:     my $errormsg='';
1.420     www      9952:     my $skipline=1;
                   9953:     my $questionnumber=0;
                   9954:     my %idresponses=();
1.419     www      9955:     foreach my $line (split(/[\n\r]/,$env{'form.upfile'})) {
                   9956:         my %components=&Apache::loncommon::record_sep($line);
                   9957:         my @entries=map {$components{$_}} (sort(keys(%components)));
1.420     www      9958:         if ($entries[1] eq 'Time') { $skipline=0; next; }
                   9959:         if ($entries[1] eq 'Response') { $skipline=1; }
                   9960:         next if $skipline;
                   9961:         if ($entries[0]!=$questionnumber) {
                   9962:            $questionnumber=$entries[0];
                   9963:            $$questiontitles[$number]=&mt('Question [_1]',$questionnumber);
                   9964:            $number++;
1.419     www      9965:         }
1.420     www      9966:         my $id=$entries[4];
                   9967:         $id=~s/^[\#0]+//;
1.421     www      9968:         $id=~s/^v\d*\://i;
                   9969:         $id=~s/[\-\:]//g;
1.420     www      9970:         $idresponses{$id}[$number]=$entries[6];
                   9971:     }
1.524     raeburn  9972:     foreach my $id (keys(%idresponses)) {
1.420     www      9973:        $$responses{$id}=join(',',@{$idresponses{$id}});
                   9974:        $$responses{$id}=~s/^\s*\,//;
1.419     www      9975:     }
                   9976:     return ($errormsg,$number);
                   9977: }
                   9978: 
1.666     www      9979: sub turning_eval {
                   9980:     my ($questiontitles,$responses)=@_;
                   9981:     my $number=0;
                   9982:     my $errormsg='';
                   9983:     foreach my $line (split(/[\n\r]/,$env{'form.upfile'})) {
                   9984:         my %components=&Apache::loncommon::record_sep($line);
                   9985:         my @entries=map {$components{$_}} (sort(keys(%components)));
                   9986:         if ($#entries>$number) { $number=$#entries; }
                   9987:         my $id=$entries[0];
                   9988:         my @idresponses;
                   9989:         $id=~s/^[\#0]+//;
                   9990:         unless ($id) { next; }
                   9991:         for (my $idx=1;$idx<=$#entries;$idx++) {
                   9992:             $entries[$idx]=~s/\,/\;/g;
                   9993:             $entries[$idx]=~s/[^a-zA-Z0-9\.\*\-\+\;]+//g;
                   9994:             push(@idresponses,$entries[$idx]);
                   9995:         }
                   9996:         $$responses{$id}=join(',',@idresponses);
                   9997:     }
                   9998:     for (my $i=1; $i<=$number; $i++) {
                   9999:         $$questiontitles[$i]=&mt('Question [_1]',$i);
                   10000:     }
                   10001:     return ($errormsg,$number);
                   10002: }
                   10003: 
                   10004: 
1.414     www      10005: sub assign_clicker_grades {
1.608     www      10006:     my ($r,$symb)=@_;
1.414     www      10007:     if (!$symb) {return '';}
1.416     www      10008: # See which part we are saving to
1.582     raeburn  10009:     my $res_error;
                   10010:     my ($partlist,$handgrade,$responseType) = &response_type($symb,\$res_error);
                   10011:     if ($res_error) {
                   10012:         return &navmap_errormsg();
                   10013:     }
1.416     www      10014: # FIXME: This should probably look for the first handgradeable part
                   10015:     my $part=$$partlist[0];
                   10016: # Start screen output
1.632     www      10017:     my $result=&Apache::loncommon::start_data_table().
                   10018:              &Apache::loncommon::start_data_table_header_row().
                   10019:              '<th>'.&mt('Assigning grades based on clicker file').'</th>'.
                   10020:              &Apache::loncommon::end_data_table_header_row().
                   10021:              &Apache::loncommon::start_data_table_row().'<td>';
1.414     www      10022: # Get correct result
                   10023: # FIXME: Possibly need delimiter other than ":"
                   10024:     my @correct=();
1.415     www      10025:     my $gradingmechanism=$env{'form.gradingmechanism'};
                   10026:     my $number=$env{'form.number'};
                   10027:     if ($gradingmechanism ne 'attendance') {
1.414     www      10028:        foreach my $key (keys(%env)) {
                   10029:           if ($key=~/^form\.correct\:/) {
                   10030:              my @input=split(/\,/,$env{$key});
                   10031:              for (my $i=0;$i<=$#input;$i++) {
                   10032:                  if (($correct[$i]) && ($input[$i]) &&
                   10033:                      ($correct[$i] ne $input[$i])) {
                   10034:                     $result.='<br /><span class="LC_warning">'.
                   10035:                              &mt('More than one correct result given for question "[_1]": [_2] versus [_3].',
                   10036:                                  $env{'form.question:'.$i},$correct[$i],$input[$i]).'</span>';
1.644     www      10037:                  } elsif (($input[$i]) || ($input[$i] eq '0')) {
1.414     www      10038:                     $correct[$i]=$input[$i];
                   10039:                  }
                   10040:              }
                   10041:           }
                   10042:        }
1.415     www      10043:        for (my $i=0;$i<$number;$i++) {
1.644     www      10044:           if ((!$correct[$i]) && ($correct[$i] ne '0')) {
1.414     www      10045:              $result.='<br /><span class="LC_error">'.
                   10046:                       &mt('No correct result given for question "[_1]"!',
                   10047:                           $env{'form.question:'.$i}).'</span>';
                   10048:           }
                   10049:        }
1.644     www      10050:        $result.='<br />'.&mt("Correct answer: [_1]",join(', ',map { ((($_) || ($_ eq '0'))?$_:'-') } @correct));
1.414     www      10051:     }
                   10052: # Start grading
1.415     www      10053:     my $pcorrect=$env{'form.pcorrect'};
                   10054:     my $pincorrect=$env{'form.pincorrect'};
1.416     www      10055:     my $storecount=0;
1.632     www      10056:     my %users=();
1.415     www      10057:     foreach my $key (keys(%env)) {
1.420     www      10058:        my $user='';
1.415     www      10059:        if ($key=~/^form\.student\:(.*)$/) {
1.420     www      10060:           $user=$1;
                   10061:        }
                   10062:        if ($key=~/^form\.unknown\:(.*)$/) {
                   10063:           my $id=$1;
                   10064:           if (($env{'form.uname'.$id}) && ($env{'form.udom'.$id})) {
                   10065:              $user=$env{'form.uname'.$id}.':'.$env{'form.udom'.$id};
1.437     www      10066:           } elsif ($env{'form.multi'.$id}) {
                   10067:              $user=$env{'form.multi'.$id};
1.420     www      10068:           }
                   10069:        }
1.632     www      10070:        if ($user) {
                   10071:           if ($users{$user}) {
                   10072:              $result.='<br /><span class="LC_warning">'.
1.696     bisitz   10073:                       &mt('More than one entry found for [_1]!','<tt>'.$user.'</tt>').
1.632     www      10074:                       '</span><br />';
                   10075:           }
                   10076:           $users{$user}=1; 
1.415     www      10077:           my @answer=split(/\,/,$env{$key});
                   10078:           my $sum=0;
1.522     www      10079:           my $realnumber=$number;
1.415     www      10080:           for (my $i=0;$i<$number;$i++) {
1.576     www      10081:              if  ($correct[$i] eq '-') {
                   10082:                 $realnumber--;
1.644     www      10083:              } elsif (($answer[$i]) || ($answer[$i]=~/^[0\.]+$/))  {
1.415     www      10084:                 if ($gradingmechanism eq 'attendance') {
                   10085:                    $sum+=$pcorrect;
1.576     www      10086:                 } elsif ($correct[$i] eq '*') {
1.522     www      10087:                    $sum+=$pcorrect;
1.415     www      10088:                 } else {
1.644     www      10089: # We actually grade if correct or not
                   10090:                    my $increment=$pincorrect;
                   10091: # Special case: numerical answer "0"
                   10092:                    if ($correct[$i] eq '0') {
                   10093:                       if ($answer[$i]=~/^[0\.]+$/) {
                   10094:                          $increment=$pcorrect;
                   10095:                       }
                   10096: # General numerical answer, both evaluate to something non-zero
                   10097:                    } elsif ((1.0*$correct[$i]!=0) && (1.0*$answer[$i]!=0)) {
                   10098:                       if (1.0*$correct[$i]==1.0*$answer[$i]) {
                   10099:                          $increment=$pcorrect;
                   10100:                       }
                   10101: # Must be just alphanumeric
                   10102:                    } elsif ($answer[$i] eq $correct[$i]) {
                   10103:                       $increment=$pcorrect;
1.415     www      10104:                    }
1.644     www      10105:                    $sum+=$increment;
1.415     www      10106:                 }
                   10107:              }
                   10108:           }
1.522     www      10109:           my $ave=$sum/(100*$realnumber);
1.416     www      10110: # Store
                   10111:           my ($username,$domain)=split(/\:/,$user);
                   10112:           my %grades=();
                   10113:           $grades{"resource.$part.solved"}='correct_by_override';
                   10114:           $grades{"resource.$part.awarded"}=$ave;
                   10115:           $grades{"resource.regrader"}="$env{'user.name'}:$env{'user.domain'}";
                   10116:           my $returncode=&Apache::lonnet::cstore(\%grades,$symb,
                   10117:                                                  $env{'request.course.id'},
                   10118:                                                  $domain,$username);
                   10119:           if ($returncode ne 'ok') {
                   10120:              $result.="<br /><span class=\"LC_error\">Failed to save student $username:$domain. Message when trying to save was ($returncode)</span>";
                   10121:           } else {
                   10122:              $storecount++;
                   10123:           }
1.415     www      10124:        }
                   10125:     }
                   10126: # We are done
1.549     hauer    10127:     $result.='<br />'.&mt('Successfully stored grades for [quant,_1,student].',$storecount).
1.632     www      10128:              '</td>'.
                   10129:              &Apache::loncommon::end_data_table_row().
                   10130:              &Apache::loncommon::end_data_table();
1.614     www      10131:     return $result;
1.414     www      10132: }
                   10133: 
1.582     raeburn  10134: sub navmap_errormsg {
                   10135:     return '<div class="LC_error">'.
                   10136:            &mt('An error occurred retrieving information about resources in the course.').'<br />'.
1.595     raeburn  10137:            &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  10138:            '</div>';
                   10139: }
1.607     droeschl 10140: 
1.609     www      10141: sub startpage {
1.671     raeburn  10142:     my ($r,$symb,$crumbs,$onlyfolderflag,$nodisplayflag,$stuvcurrent,$stuvdisp,$nomenu,$js) = @_;
                   10143:     if ($nomenu) {
                   10144:         $r->print(&Apache::loncommon::start_page("Student's Version",$js,{'only_body' => '1'}));
                   10145:     } else {
                   10146:         unshift(@$crumbs,{href=>&href_symb_cmd($symb,'gradingmenu'),text=>"Grading"});
                   10147:         $r->print(&Apache::loncommon::start_page('Grading',$js,
                   10148:                                                  {'bread_crumbs' => $crumbs}));
                   10149:         &Apache::lonquickgrades::startGradeScreen($r,($env{'form.symb'}?'probgrading':'grading'));
                   10150:     }
1.613     www      10151:     unless ($nodisplayflag) {
1.671     raeburn  10152:        $r->print(&Apache::lonhtmlcommon::resource_info_box($symb,$onlyfolderflag,$stuvcurrent,$stuvdisp));
1.613     www      10153:     }
1.607     droeschl 10154: }
1.582     raeburn  10155: 
1.622     www      10156: sub select_problem {
                   10157:     my ($r)=@_;
1.632     www      10158:     $r->print('<h3>'.&mt('Select the problem or one of the problems you want to grade').'</h3><form action="/adm/grades">');
1.622     www      10159:     $r->print(&Apache::lonstathelpers::problem_selector('.',undef,1));
                   10160:     $r->print('<input type="hidden" name="command" value="gradingmenu" />');
                   10161:     $r->print('<input type="submit" value="'.&mt('Next').' &rarr;" /></form>');
                   10162: }
                   10163: 
1.1       albertel 10164: sub handler {
1.41      ng       10165:     my $request=$_[0];
1.434     albertel 10166:     &reset_caches();
1.646     raeburn  10167:     if ($request->header_only) {
                   10168:         &Apache::loncommon::content_type($request,'text/html');
                   10169:         $request->send_http_header;
                   10170:         return OK;
                   10171:     }
                   10172:     &Apache::loncommon::get_unprocessed_cgi($ENV{'QUERY_STRING'});
                   10173: 
1.664     raeburn  10174: # see what command we need to execute
                   10175: 
                   10176:     my @commands=&Apache::loncommon::get_env_multiple('form.command');
                   10177:     my $command=$commands[0];
                   10178: 
1.646     raeburn  10179:     &init_perm();
                   10180:     if (!$env{'request.course.id'}) {
1.664     raeburn  10181:         unless ((&Apache::lonnet::allowed('usc',$env{'request.role.domain'})) &&
                   10182:                 ($command =~ /^scantronupload/)) {
                   10183:             # Not in a course.
                   10184:             $env{'user.error.msg'}="/adm/grades::vgr:0:0:Cannot display grades page outside course context";
                   10185:             return HTTP_NOT_ACCEPTABLE;
                   10186:         }
1.646     raeburn  10187:     } elsif (!%perm) {
                   10188:         $request->internal_redirect('/adm/quickgrades');
1.687     raeburn  10189:         return OK;
1.41      ng       10190:     }
1.646     raeburn  10191:     &Apache::loncommon::content_type($request,'text/html');
1.41      ng       10192:     $request->send_http_header;
1.646     raeburn  10193: 
1.160     albertel 10194:     if ($#commands > 0) {
                   10195: 	&Apache::lonnet::logthis("grades got multiple commands ".join(':',@commands));
                   10196:     }
1.608     www      10197: 
                   10198: # see what the symb is
                   10199: 
                   10200:     my $symb=$env{'form.symb'};
                   10201:     unless ($symb) {
                   10202:        (my $url=$env{'form.url'}) =~ s-^https*://($ENV{'SERVER_NAME'}|$ENV{'HTTP_HOST'})--;
                   10203:        $symb=&Apache::lonnet::symbread($url);
                   10204:     }
1.646     raeburn  10205:     &Apache::lonenc::check_decrypt(\$symb);
1.608     www      10206: 
1.513     foxr     10207:     $ssi_error = 0;
1.637     www      10208:     if (($symb eq '' || $command eq '') && ($env{'request.course.id'})) {
1.601     www      10209: #
1.637     www      10210: # Not called from a resource, but inside a course
1.601     www      10211: #    
1.622     www      10212:         &startpage($request,undef,[],1,1);
                   10213:         &select_problem($request);
1.41      ng       10214:     } else {
1.104     albertel 10215: 	if ($command eq 'submission' && $perm{'vgr'}) {
1.671     raeburn  10216:             my ($stuvcurrent,$stuvdisp,$versionform,$js);
                   10217:             if (($env{'form.student'} ne '') && ($env{'form.userdom'} ne '')) {
                   10218:                 ($stuvcurrent,$stuvdisp,$versionform,$js) =
                   10219:                     &choose_task_version_form($symb,$env{'form.student'},
                   10220:                                               $env{'form.userdom'});
                   10221:             }
                   10222:             &startpage($request,$symb,[{href=>"", text=>"Student Submissions"}],undef,undef,$stuvcurrent,$stuvdisp,undef,$js);
                   10223:             if ($versionform) {
                   10224:                 $request->print($versionform);
                   10225:             }
                   10226:             $request->print('<br clear="all" />');
1.611     www      10227: 	    ($env{'form.student'} eq '' ? &listStudents($request,$symb) : &submission($request,0,0,$symb));
1.671     raeburn  10228:         } elsif ($command eq 'versionsub' && $perm{'vgr'}) {
                   10229:             my ($stuvcurrent,$stuvdisp,$versionform,$js) =
                   10230:                 &choose_task_version_form($symb,$env{'form.student'},
                   10231:                                           $env{'form.userdom'},
                   10232:                                           $env{'form.inhibitmenu'});
                   10233:             &startpage($request,$symb,[{href=>"", text=>"Previous Student Version"}],undef,undef,$stuvcurrent,$stuvdisp,$env{'form.inhibitmenu'},$js);
                   10234:             if ($versionform) {
                   10235:                 $request->print($versionform);
                   10236:             }
                   10237:             $request->print('<br clear="all" />');
                   10238:             $request->print(&show_previous_task_version($request,$symb));
1.103     albertel 10239: 	} elsif ($command eq 'pickStudentPage' && $perm{'vgr'}) {
1.615     www      10240:             &startpage($request,$symb,[{href=>&href_symb_cmd($symb,'all_for_one'),text=>'Grade page/folder for one student'},
                   10241:                                        {href=>'',text=>'Select student'}],1,1);
1.608     www      10242: 	    &pickStudentPage($request,$symb);
1.103     albertel 10243: 	} elsif ($command eq 'displayPage' && $perm{'vgr'}) {
1.615     www      10244:             &startpage($request,$symb,
                   10245:                                       [{href=>&href_symb_cmd($symb,'all_for_one'),text=>'Grade page/folder for one student'},
                   10246:                                        {href=>'',text=>'Select student'},
                   10247:                                        {href=>'',text=>'Grade student'}],1,1);
1.608     www      10248: 	    &displayPage($request,$symb);
1.104     albertel 10249: 	} elsif ($command eq 'gradeByPage' && $perm{'mgr'}) {
1.616     www      10250:             &startpage($request,$symb,[{href=>&href_symb_cmd($symb,'all_for_one'),text=>'Grade page/folder for one student'},
                   10251:                                        {href=>'',text=>'Select student'},
                   10252:                                        {href=>'',text=>'Grade student'},
                   10253:                                        {href=>'',text=>'Store grades'}],1,1);
1.608     www      10254: 	    &updateGradeByPage($request,$symb);
1.104     albertel 10255: 	} elsif ($command eq 'processGroup' && $perm{'vgr'}) {
1.619     www      10256:             &startpage($request,$symb,[{href=>'',text=>'...'},
                   10257:                                        {href=>'',text=>'Modify grades'}]);
1.608     www      10258: 	    &processGroup($request,$symb);
1.104     albertel 10259: 	} elsif ($command eq 'gradingmenu' && $perm{'vgr'}) {
1.608     www      10260:             &startpage($request,$symb);
                   10261: 	    $request->print(&grading_menu($request,$symb));
1.598     www      10262: 	} elsif ($command eq 'individual' && $perm{'vgr'}) {
1.617     www      10263:             &startpage($request,$symb,[{href=>'',text=>'Select individual students to grade'}]);
1.608     www      10264: 	    $request->print(&submit_options($request,$symb));
1.598     www      10265:         } elsif ($command eq 'ungraded' && $perm{'vgr'}) {
1.617     www      10266:             &startpage($request,$symb,[{href=>'',text=>'Grade ungraded submissions'}]);
                   10267:             $request->print(&listStudents($request,$symb,'graded'));
1.598     www      10268:         } elsif ($command eq 'table' && $perm{'vgr'}) {
1.614     www      10269:             &startpage($request,$symb,[{href=>"", text=>"Grading table"}]);
1.611     www      10270:             $request->print(&submit_options_table($request,$symb));
1.598     www      10271:         } elsif ($command eq 'all_for_one' && $perm{'vgr'}) {
1.615     www      10272:             &startpage($request,$symb,[{href=>'',text=>'Grade page/folder for one student'}],1,1);
1.608     www      10273:             $request->print(&submit_options_sequence($request,$symb));
1.104     albertel 10274: 	} elsif ($command eq 'viewgrades' && $perm{'vgr'}) {
1.614     www      10275:             &startpage($request,$symb,[{href=>&href_symb_cmd($symb,"table"), text=>"Grading table"},{href=>'', text=>"Modify grades"}]);
1.608     www      10276: 	    $request->print(&viewgrades($request,$symb));
1.104     albertel 10277: 	} elsif ($command eq 'handgrade' && $perm{'mgr'}) {
1.620     www      10278:             &startpage($request,$symb,[{href=>'',text=>'...'},
                   10279:                                        {href=>'',text=>'Store grades'}]);
1.608     www      10280: 	    $request->print(&processHandGrade($request,$symb));
1.106     albertel 10281: 	} elsif ($command eq 'editgrades' && $perm{'mgr'}) {
1.614     www      10282:             &startpage($request,$symb,[{href=>&href_symb_cmd($symb,"table"), text=>"Grading table"},
                   10283:                                        {href=>&href_symb_cmd($symb,'viewgrades').'&group=all&section=all&Status=Active',
                   10284:                                                                              text=>"Modify grades"},
                   10285:                                        {href=>'', text=>"Store grades"}]);
1.608     www      10286: 	    $request->print(&editgrades($request,$symb));
1.602     www      10287:         } elsif ($command eq 'initialverifyreceipt' && $perm{'vgr'}) {
1.616     www      10288:             &startpage($request,$symb,[{href=>'',text=>'Verify Receipt Number'}]);
1.611     www      10289:             $request->print(&initialverifyreceipt($request,$symb));
1.106     albertel 10290: 	} elsif ($command eq 'verify' && $perm{'vgr'}) {
1.616     www      10291:             &startpage($request,$symb,[{href=>&href_symb_cmd($symb,"initialverifyreceipt"),text=>'Verify Receipt Number'},
                   10292:                                        {href=>'',text=>'Verification Result'}]);
1.608     www      10293: 	    $request->print(&verifyreceipt($request,$symb));
1.400     www      10294:         } elsif ($command eq 'processclicker' && $perm{'mgr'}) {
1.615     www      10295:             &startpage($request,$symb,[{href=>'', text=>'Process clicker'}]);
1.608     www      10296:             $request->print(&process_clicker($request,$symb));
1.400     www      10297:         } elsif ($command eq 'processclickerfile' && $perm{'mgr'}) {
1.615     www      10298:             &startpage($request,$symb,[{href=>&href_symb_cmd($symb,'processclicker'), text=>'Process clicker'},
                   10299:                                        {href=>'', text=>'Process clicker file'}]);
1.608     www      10300:             $request->print(&process_clicker_file($request,$symb));
1.414     www      10301:         } elsif ($command eq 'assignclickergrades' && $perm{'mgr'}) {
1.615     www      10302:             &startpage($request,$symb,[{href=>&href_symb_cmd($symb,'processclicker'), text=>'Process clicker'},
                   10303:                                        {href=>'', text=>'Process clicker file'},
                   10304:                                        {href=>'', text=>'Store grades'}]);
1.608     www      10305:             $request->print(&assign_clicker_grades($request,$symb));
1.106     albertel 10306: 	} elsif ($command eq 'csvform' && $perm{'mgr'}) {
1.627     www      10307:             &startpage($request,$symb,[{href=>'', text=>'Upload Scores'}],1,1);
1.608     www      10308: 	    $request->print(&upcsvScores_form($request,$symb));
1.106     albertel 10309: 	} elsif ($command eq 'csvupload' && $perm{'mgr'}) {
1.627     www      10310:             &startpage($request,$symb,[{href=>'', text=>'Upload Scores'}],1,1);
1.608     www      10311: 	    $request->print(&csvupload($request,$symb));
1.106     albertel 10312: 	} elsif ($command eq 'csvuploadmap' && $perm{'mgr'} ) {
1.627     www      10313:             &startpage($request,$symb,[{href=>'', text=>'Upload Scores'}],1,1);
1.608     www      10314: 	    $request->print(&csvuploadmap($request,$symb));
1.246     albertel 10315: 	} elsif ($command eq 'csvuploadoptions' && $perm{'mgr'}) {
1.257     albertel 10316: 	    if ($env{'form.associate'} ne 'Reverse Association') {
1.627     www      10317:                 &startpage($request,$symb,[{href=>'', text=>'Upload Scores'}],1,1);
1.608     www      10318: 		$request->print(&csvuploadoptions($request,$symb));
1.41      ng       10319: 	    } else {
1.257     albertel 10320: 		if ( $env{'form.upfile_associate'} ne 'reverse' ) {
                   10321: 		    $env{'form.upfile_associate'} = 'reverse';
1.41      ng       10322: 		} else {
1.257     albertel 10323: 		    $env{'form.upfile_associate'} = 'forward';
1.41      ng       10324: 		}
1.627     www      10325:                 &startpage($request,$symb,[{href=>'', text=>'Upload Scores'}],1,1);
1.608     www      10326: 		$request->print(&csvuploadmap($request,$symb));
1.41      ng       10327: 	    }
1.246     albertel 10328: 	} elsif ($command eq 'csvuploadassign' && $perm{'mgr'} ) {
1.627     www      10329:             &startpage($request,$symb,[{href=>'', text=>'Upload Scores'}],1,1);
1.608     www      10330: 	    $request->print(&csvuploadassign($request,$symb));
1.106     albertel 10331: 	} elsif ($command eq 'scantron_selectphase' && $perm{'mgr'}) {
1.616     www      10332:             &startpage($request,$symb,[{href=>'', text=>'Grade/Manage/Review Bubblesheets'}],1,1);
1.612     www      10333: 	    $request->print(&scantron_selectphase($request,undef,$symb));
1.203     albertel 10334:  	} elsif ($command eq 'scantron_warning' && $perm{'mgr'}) {
1.616     www      10335:             &startpage($request,$symb,[{href=>'', text=>'Grade/Manage/Review Bubblesheets'}],1,1);
1.608     www      10336:  	    $request->print(&scantron_do_warning($request,$symb));
1.142     albertel 10337: 	} elsif ($command eq 'scantron_validate' && $perm{'mgr'}) {
1.616     www      10338:             &startpage($request,$symb,[{href=>'', text=>'Grade/Manage/Review Bubblesheets'}],1,1);
1.608     www      10339: 	    $request->print(&scantron_validate_file($request,$symb));
1.106     albertel 10340: 	} elsif ($command eq 'scantron_process' && $perm{'mgr'}) {
1.616     www      10341:             &startpage($request,$symb,[{href=>'', text=>'Grade/Manage/Review Bubblesheets'}],1,1);
1.608     www      10342: 	    $request->print(&scantron_process_students($request,$symb));
1.157     albertel 10343:  	} elsif ($command eq 'scantronupload' && 
1.257     albertel 10344:  		 (&Apache::lonnet::allowed('usc',$env{'request.role.domain'})||
                   10345: 		  &Apache::lonnet::allowed('usc',$env{'request.course.id'}))) {
1.616     www      10346:             &startpage($request,$symb,[{href=>'', text=>'Grade/Manage/Review Bubblesheets'}],1,1);
1.608     www      10347:  	    $request->print(&scantron_upload_scantron_data($request,$symb)); 
1.157     albertel 10348:  	} elsif ($command eq 'scantronupload_save' &&
1.257     albertel 10349:  		 (&Apache::lonnet::allowed('usc',$env{'request.role.domain'})||
                   10350: 		  &Apache::lonnet::allowed('usc',$env{'request.course.id'}))) {
1.616     www      10351:             &startpage($request,$symb,[{href=>'', text=>'Grade/Manage/Review Bubblesheets'}],1,1);
1.608     www      10352:  	    $request->print(&scantron_upload_scantron_data_save($request,$symb));
1.202     albertel 10353:  	} elsif ($command eq 'scantron_download' &&
1.257     albertel 10354: 		 &Apache::lonnet::allowed('usc',$env{'request.course.id'})) {
1.616     www      10355:             &startpage($request,$symb,[{href=>'', text=>'Grade/Manage/Review Bubblesheets'}],1,1);
1.608     www      10356:  	    $request->print(&scantron_download_scantron_data($request,$symb));
1.523     raeburn  10357:         } elsif ($command eq 'checksubmissions' && $perm{'vgr'}) {
1.616     www      10358:             &startpage($request,$symb,[{href=>'', text=>'Grade/Manage/Review Bubblesheets'}],1,1);
1.621     www      10359:             $request->print(&checkscantron_results($request,$symb));
                   10360:         } elsif ($command eq 'downloadfilesselect' && $perm{'vgr'}) {
                   10361:             &startpage($request,$symb,[{href=>'', text=>'Select which submissions to download'}]);
                   10362:             $request->print(&submit_options_download($request,$symb));
                   10363:          } elsif ($command eq 'downloadfileslink' && $perm{'vgr'}) {
                   10364:             &startpage($request,$symb,
                   10365:    [{href=>&href_symb_cmd($symb,'downloadfilesselect'), text=>'Select which submissions to download'},
                   10366:     {href=>'', text=>'Download submissions'}]);
                   10367:             &submit_download_link($request,$symb);
1.106     albertel 10368: 	} elsif ($command) {
1.620     www      10369:             &startpage($request,$symb,[{href=>'', text=>'Access denied'}]);
1.562     bisitz   10370: 	    $request->print('<p class="LC_error">'.&mt('Access Denied ([_1])',$command).'</p>');
1.26      albertel 10371: 	}
1.2       albertel 10372:     }
1.513     foxr     10373:     if ($ssi_error) {
                   10374: 	&ssi_print_error($request);
                   10375:     }
1.671     raeburn  10376:     if ($env{'form.inhibitmenu'}) {
                   10377:         $request->print(&Apache::loncommon::end_page());
                   10378:     } else {
                   10379:         &Apache::lonquickgrades::endGradeScreen($request);
                   10380:     }
1.434     albertel 10381:     &reset_caches();
1.646     raeburn  10382:     return OK;
1.44      ng       10383: }
                   10384: 
1.1       albertel 10385: 1;
                   10386: 
1.13      albertel 10387: __END__;
1.531     jms      10388: 
                   10389: 
                   10390: =head1 NAME
                   10391: 
                   10392: Apache::grades
                   10393: 
                   10394: =head1 SYNOPSIS
                   10395: 
                   10396: Handles the viewing of grades.
                   10397: 
                   10398: This is part of the LearningOnline Network with CAPA project
                   10399: described at http://www.lon-capa.org.
                   10400: 
                   10401: =head1 OVERVIEW
                   10402: 
                   10403: Do an ssi with retries:
1.715     bisitz   10404: While I'd love to factor out this with the version in lonprintout,
1.531     jms      10405: 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
                   10406: I'm not quite ready to invent (e.g. an ssi_with_retry object).
                   10407: 
                   10408: At least the logic that drives this has been pulled out into loncommon.
                   10409: 
                   10410: 
                   10411: 
                   10412: ssi_with_retries - Does the server side include of a resource.
                   10413:                      if the ssi call returns an error we'll retry it up to
                   10414:                      the number of times requested by the caller.
1.715     bisitz   10415:                      If we still have a problem, no text is appended to the
1.531     jms      10416:                      output and we set some global variables.
                   10417:                      to indicate to the caller an SSI error occurred.  
                   10418:                      All of this is supposed to deal with the issues described
1.715     bisitz   10419:                      in LON-CAPA BZ 5631 see:
1.531     jms      10420:                      http://bugs.lon-capa.org/show_bug.cgi?id=5631
                   10421:                      by informing the user that this happened.
                   10422: 
                   10423: Parameters:
                   10424:   resource   - The resource to include.  This is passed directly, without
                   10425:                interpretation to lonnet::ssi.
                   10426:   form       - The form hash parameters that guide the interpretation of the resource
                   10427:                
                   10428:   retries    - Number of retries allowed before giving up completely.
                   10429: Returns:
                   10430:   On success, returns the rendered resource identified by the resource parameter.
                   10431: Side Effects:
                   10432:   The following global variables can be set:
                   10433:    ssi_error                - If an unrecoverable error occurred this becomes true.
                   10434:                               It is up to the caller to initialize this to false
                   10435:                               if desired.
                   10436:    ssi_error_resource  - If an unrecoverable error occurred, this is the value
                   10437:                               of the resource that could not be rendered by the ssi
                   10438:                               call.
                   10439:    ssi_error_message   - The error string fetched from the ssi response
                   10440:                               in the event of an error.
                   10441: 
                   10442: 
                   10443: =head1 HANDLER SUBROUTINE
                   10444: 
                   10445: ssi_with_retries()
                   10446: 
                   10447: =head1 SUBROUTINES
                   10448: 
                   10449: =over
                   10450: 
1.671     raeburn  10451: =head1 Routines to display previous version of a Task for a specific student
                   10452: 
                   10453: Tasks are graded pass/fail. Students who have yet to pass a particular Task
                   10454: can receive another opportunity. Access to tasks is slot-based. If a slot
                   10455: requires a proctor to check-in the student, a new version of the Task will
                   10456: be created when the student is checked in to the new opportunity.
                   10457: 
                   10458: If a particular student has tried two or more versions of a particular task,
                   10459: the submission screen provides a user with vgr privileges (e.g., a Course
                   10460: Coordinator) the ability to display a previous version worked on by the
                   10461: student.  By default, the current version is displayed. If a previous version
                   10462: has been selected for display, submission data are only shown that pertain
                   10463: to that particular version, and the interface to submit grades is not shown.
                   10464: 
                   10465: =over 4
                   10466: 
                   10467: =item show_previous_task_version()
                   10468: 
                   10469: Displays a specified version of a student's Task, as the student sees it.
                   10470: 
                   10471: Inputs: 2
                   10472:         request - request object
                   10473:         symb    - unique symb for current instance of resource
                   10474: 
                   10475: Output: None.
                   10476: 
                   10477: Side Effects: calls &show_problem() to print version of Task, with
                   10478:               version contained in form item: $env{'form.previousversion'}
                   10479: 
                   10480: =item choose_task_version_form()
                   10481: 
                   10482: Displays a web form used to select which version of a student's view of a
                   10483: Task should be displayed.  Either launches a pop-up window, or replaces
                   10484: content in existing pop-up, or replaces page in main window.
                   10485: 
                   10486: Inputs: 4
                   10487:         symb    - unique symb for current instance of resource
                   10488:         uname   - username of student
                   10489:         udom    - domain of student
                   10490:         nomenu  - 1 if display is in a pop-up window, and hence no menu
                   10491:                   breadcrumbs etc., are displayed
                   10492: 
                   10493: Output: 4
                   10494:         current   - student's current version
                   10495:         displayed - student's version being displayed
                   10496:         result    - scalar containing HTML for web form used to switch to
                   10497:                     a different version (or a link to close window, if pop-up).
                   10498:         js        - javascript for processing selection in versions web form
                   10499: 
                   10500: Side Effects: None.
                   10501: 
                   10502: =item previous_display_javascript()
                   10503: 
                   10504: Inputs: 2
                   10505:         nomenu  - 1 if display is in a pop-up window, and hence no menu
                   10506:                   breadcrumbs etc., are displayed.
                   10507:         current - student's current version number.
                   10508: 
                   10509: Output: 1
                   10510:         js      - javascript for processing selection in versions web form.
                   10511: 
                   10512: Side Effects: None.
                   10513: 
                   10514: =back
                   10515: 
                   10516: =head1 Routines to process bubblesheet data.
                   10517: 
                   10518: =over 4
                   10519: 
1.531     jms      10520: =item scantron_get_correction() : 
                   10521: 
                   10522:    Builds the interface screen to interact with the operator to fix a
                   10523:    specific error condition in a specific scanline
                   10524: 
                   10525:  Arguments:
                   10526:     $r           - Apache request object
                   10527:     $i           - number of the current scanline
                   10528:     $scan_record - hash ref as returned from &scantron_parse_scanline()
                   10529:     $scan_config - hash ref as returned from &get_scantron_config()
                   10530:     $line        - full contents of the current scanline
                   10531:     $error       - error condition, valid values are
                   10532:                    'incorrectCODE', 'duplicateCODE',
                   10533:                    'doublebubble', 'missingbubble',
                   10534:                    'duplicateID', 'incorrectID'
                   10535:     $arg         - extra information needed
                   10536:        For errors:
                   10537:          - duplicateID   - paper number that this studentID was seen before on
                   10538:          - duplicateCODE - array ref of the paper numbers this CODE was
                   10539:                            seen on before
                   10540:          - incorrectCODE - current incorrect CODE 
                   10541:          - doublebubble  - array ref of the bubble lines that have double
                   10542:                            bubble errors
                   10543:          - missingbubble - array ref of the bubble lines that have missing
                   10544:                            bubble errors
                   10545: 
1.691     raeburn  10546:    $randomorder - True if exam folder has randomorder set
                   10547:    $randompick  - True if exam folder has randompick set
                   10548:    $respnumlookup - Reference to HASH mapping question numbers in bubble lines
                   10549:                      for current line to question number used for same question
                   10550:                      in "Master Seqence" (as seen by Course Coordinator).
                   10551:    $startline   - Reference to hash where key is question number (0 is first)
                   10552:                   and value is number of first bubble line for current student
                   10553:                   or code-based randompick and/or randomorder.
                   10554: 
                   10555: 
                   10556: 
1.531     jms      10557: =item  scantron_get_maxbubble() : 
                   10558: 
1.582     raeburn  10559:    Arguments:
                   10560:        $nav_error  - Reference to scalar which is a flag to indicate a
                   10561:                       failure to retrieve a navmap object.
                   10562:        if $nav_error is set to 1 by scantron_get_maxbubble(), the 
                   10563:        calling routine should trap the error condition and display the warning
                   10564:        found in &navmap_errormsg().
                   10565: 
1.649     raeburn  10566:        $scantron_config - Reference to bubblesheet format configuration hash.
                   10567: 
1.531     jms      10568:    Returns the maximum number of bubble lines that are expected to
                   10569:    occur. Does this by walking the selected sequence rendering the
                   10570:    resource and then checking &Apache::lonxml::get_problem_counter()
                   10571:    for what the current value of the problem counter is.
                   10572: 
                   10573:    Caches the results to $env{'form.scantron_maxbubble'},
                   10574:    $env{'form.scantron.bubble_lines.n'}, 
                   10575:    $env{'form.scantron.first_bubble_line.n'} and
                   10576:    $env{"form.scantron.sub_bubblelines.n"}
1.691     raeburn  10577:    which are the total number of bubble lines, the number of bubble
1.531     jms      10578:    lines for response n and number of the first bubble line for response n,
                   10579:    and a comma separated list of numbers of bubble lines for sub-questions
                   10580:    (for optionresponse, matchresponse, and rankresponse items), for response n.  
                   10581: 
                   10582: 
                   10583: =item  scantron_validate_missingbubbles() : 
                   10584: 
                   10585:    Validates all scanlines in the selected file to not have any
                   10586:     answers that don't have bubbles that have not been verified
                   10587:     to be bubble free.
                   10588: 
                   10589: =item  scantron_process_students() : 
                   10590: 
1.659     raeburn  10591:    Routine that does the actual grading of the bubblesheet information.
1.531     jms      10592: 
                   10593:    The parsed scanline hash is added to %env 
                   10594: 
                   10595:    Then foreach unskipped scanline it does an &Apache::lonnet::ssi()
                   10596:    foreach resource , with the form data of
                   10597: 
                   10598: 	'submitted'     =>'scantron' 
                   10599: 	'grade_target'  =>'grade',
                   10600: 	'grade_username'=> username of student
                   10601: 	'grade_domain'  => domain of student
                   10602: 	'grade_courseid'=> of course
                   10603: 	'grade_symb'    => symb of resource to grade
                   10604: 
                   10605:     This triggers a grading pass. The problem grading code takes care
                   10606:     of converting the bubbled letter information (now in %env) into a
                   10607:     valid submission.
                   10608: 
                   10609: =item  scantron_upload_scantron_data() :
                   10610: 
1.659     raeburn  10611:     Creates the screen for adding a new bubblesheet data file to a course.
1.531     jms      10612: 
                   10613: =item  scantron_upload_scantron_data_save() : 
                   10614: 
                   10615:    Adds a provided bubble information data file to the course if user
                   10616:    has the correct privileges to do so. 
                   10617: 
                   10618: =item  valid_file() :
                   10619: 
                   10620:    Validates that the requested bubble data file exists in the course.
                   10621: 
                   10622: =item  scantron_download_scantron_data() : 
                   10623: 
                   10624:    Shows a list of the three internal files (original, corrected,
1.659     raeburn  10625:    skipped) for a specific bubblesheet data file that exists in the
1.531     jms      10626:    course.
                   10627: 
                   10628: =item  scantron_validate_ID() : 
                   10629: 
                   10630:    Validates all scanlines in the selected file to not have any
1.556     weissno  10631:    invalid or underspecified student/employee IDs
1.531     jms      10632: 
1.582     raeburn  10633: =item navmap_errormsg() :
                   10634: 
                   10635:    Returns HTML mark-up inside a <div></div> with a link to re-initialize the course.
1.671     raeburn  10636:    Should be called whenever the request to instantiate a navmap object fails.
                   10637: 
                   10638: =back
1.582     raeburn  10639: 
1.531     jms      10640: =back
                   10641: 
                   10642: =cut

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